glory-render 0.9.0

Semantic rendering contracts and reference interpreter for Glory
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
//! A finite semantic UI contract. No HTML tags, engine types or reactive handles.
//! Rendering adapters translate this contract into their own objects and ranges.

mod anchor;
mod viewport_layer;
pub use viewport_layer::ViewportPlacement;
#[cfg(feature = "conformance")]
pub mod conformance;
mod id;
pub use anchor::{
    AnchorAlign, AnchorArrow, AnchorArrowPosition, AnchorPlacement, AnchorPosition, AnchorSide,
};
mod node_map;
pub use node_map::NodeMap;
mod collapse;
mod presence;
pub use presence::{
    MAX_PRESENCE_MILLIS, PresenceConfig, PresenceEffect, PresenceStyle, PresenceTiming,
};
mod document;
pub use collapse::{CollapseConfig, MAX_COLLAPSE_MILLIS};
mod graphic;
mod graphic_transition;
pub use graphic::{
    GraphicFit, GraphicPoint, GraphicProps, GraphicStroke, MAX_GRAPHIC_COMMANDS,
    MAX_GRAPHIC_COORDINATE, PathCommand, StrokeCap,
};
pub use graphic_transition::GraphicTransition;
mod choice;
pub use choice::{ChoiceCommand, ComboboxKind, OptionSemantics};
mod context_menu;
mod tags;
pub use context_menu::{ContextEditPolicy, ContextPoint, ContextSource};
pub use tags::{
    MAX_TAG_INPUT_BYTES, MAX_TAG_PASTE_BYTES, TagHostRejection, TagKey, TagSeparators, TagsCommand,
};
mod select;
pub use select::{
    MAX_SELECT_BYTES, MAX_SELECT_GROUPS, MAX_SELECT_OPTIONS, SelectEntry, SelectGroup,
    SelectOption, SelectProps, SelectSelection,
};
mod range;
pub use range::RangeValue;
mod progress;
pub use progress::ProgressValue;
mod motion;
pub use motion::{GraphicAnimation, MotionPreference};
mod translation;
pub use translation::{
    MAX_TRANSLATION_COORDINATE, TranslationKind, TranslationMotion, TranslationOffset,
    TranslationPhase,
};
pub mod memory;
mod plan;
pub mod profile;
mod props;
mod semantics;
pub use document::DocumentPart;
mod text;

pub use glory_style as style;
pub use id::{NodeId, NodeIds, RuntimeId};
pub use plan::{MAX_PLAN_NODES, Plan, PlanNode, WeakPlan};
pub use props::*;
pub use semantics::{
    Current, Direction, DismissReason, FieldPart, FormAction, FormControl, Layer, LayerFocus,
    LayerPlacement, LinkOpen, MenuItemKind, MenuItemSemantics, Orientation, PopupKind, SemanticId,
    Semantics,
};
pub use text::normalize_text;
mod clipboard;
mod files;
pub use clipboard::{ClipboardOutcome, ClipboardText, MAX_CLIPBOARD_BYTES};
pub use files::{
    FileCapabilities, FileChunk, FileConfig, FileDocumentId, FileEvent, FileFilter,
    FileImageFormat, FileImageInfo, FileInfo, FileOrigin, FileOutcome, FilePreview,
    FilePreviewError, FilePreviewLimits, FileProps, FileRead, FileRejection, FileToken,
    MAX_FILE_BYTES, MAX_FILE_CHUNK_BYTES, MAX_FILE_COUNT, MAX_FILE_FILTER_BYTES, MAX_FILE_FILTERS,
    MAX_FILE_HEADER_BYTES, MAX_FILE_METADATA_BYTES, MAX_FILE_MIME_BYTES, MAX_FILE_NAME_BYTES,
    MAX_FILE_READS, MAX_PREVIEW_DIMENSION, MAX_PREVIEW_ENCODED_BYTES, MAX_PREVIEW_PIXELS,
    inspect_file_preview,
};
mod keyboard;
pub use keyboard::{KeyboardCommand, KeyboardInput};
mod navigation_panel;
pub use navigation_panel::{NavigationPanel, NavigationPanelCommand};
mod grid;
pub use grid::GridCommand;
mod tree;
pub use tree::{TreeCheckState, TreeCommand, TreeItem, TreeNavigation};
mod scroll;
pub use scroll::{ScrollAxes, ScrollCommand, ScrollMetrics, ScrollMovement};
mod sheet;
pub use sheet::{MAX_SHEET_SNAPS, SheetCommand, SheetConfig};
mod slider;
pub use slider::SliderValue;
mod spinbutton;
pub use spinbutton::SpinValue;
mod input_assist;
pub use input_assist::{
    InputAssist, InputAutofill, InputMode, MAX_INPUT_PLACEHOLDER_BYTES, validate_input_placeholder,
};
mod text_selection;
pub use text_selection::{SelectionDirection, TextSelection};
mod focus_scope;
pub use focus_scope::{FocusScopeConfig, MAX_FOCUS_SCOPE_NODES, MAX_FOCUS_SCOPES};
mod input_edit;
pub use input_edit::{
    InputEdit, InputEditCapture, InputEditIntent, InputEditRejection, MAX_INPUT_EDIT_BYTES,
};
mod splitter;
pub use splitter::RangeCommand;
mod typeahead;
pub use typeahead::{MAX_TYPEAHEAD_MILLIS, validate_typeahead};
mod drag;
pub use drag::{DragCapture, DragPhase};
mod menu;
pub use menu::{MenuCommand, PointerPhase};
mod plot_pointer;
pub use plot_pointer::{
    MAX_PLOT_POINTER_COORDINATE, PlotPointer, PlotPointerDevice, PlotPointerPhase,
};

/// Optional windowed-view metadata. Engines can show a flow preview before
/// geometry is available without changing logical ownership or identity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VirtualPart {
    Root,
    Surface,
    Row,
}

/// A patch distinguishes absence, replacement and reset to the default value.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Change<T> {
    #[default]
    Keep,
    Set(T),
    Clear,
}

impl<T: Default> Change<T> {
    pub fn apply(self, target: &mut T) {
        self.apply_or(target, T::default());
    }
}

impl<T> Change<T> {
    pub fn apply_or(self, target: &mut T, default: T) {
        match self {
            Self::Keep => {}
            Self::Set(value) => *target = value,
            Self::Clear => *target = default,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Mutation {
    Create {
        id: NodeId,
        node: Box<Descriptor>,
    },
    /// One validated, detached construction unit. Internal placement belongs
    /// to this mutation; attach/move its root with a subsequent Place.
    CreatePlan {
        plan: Plan,
        ids: Vec<NodeId>,
    },
    Patch {
        id: NodeId,
        patch: Patch,
    },
    /// `None` parent places a root. Existing nodes move, preserving identity.
    Place {
        id: NodeId,
        parent: Option<NodeId>,
        before: Option<NodeId>,
    },
    /// Disconnect a range, preserving nodes and identities until Resume/Dispose.
    Suspend {
        id: NodeId,
    },
    Resume {
        id: NodeId,
        parent: Option<NodeId>,
        before: Option<NodeId>,
    },
    /// Permanently release this subtree, including suspended descendants.
    Dispose {
        id: NodeId,
    },
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Capabilities {
    /// Explicit text clipboard writes with terminal host observations.
    pub clipboard_write: bool,
    /// Current consumer identity and independently available file operations.
    pub files: Option<FileCapabilities>,
    pub measure: bool,
    pub scroll: bool,
    pub focus: bool,
    pub input: bool,
    /// Emits a terminal observation for each finite collapse configuration.
    pub collapse_completion: bool,
    /// Host supplies revisioned presence completion; static renderers settle in the component.
    pub presence_completion: bool,
    /// Transform presence effects in addition to fade/none.
    pub presence_transforms: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QueryToken(pub u64);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Query {
    RichSelection(NodeId),
    FileRead(FileRead),
    FilePreview(FileToken),
    Bounds(NodeId),
    Scroll(NodeId),
    ScrollMetrics(NodeId),
    Selection(NodeId),
    /// Whether this node's actual control owns document focus at the request
    /// barrier. This is neither FocusWithin nor OS/window activation.
    Focus(NodeId),
}

impl Query {
    pub fn node(self) -> NodeId {
        match self {
            Self::FileRead(read) => read.file.node,
            Self::FilePreview(file) => file.node,
            Self::RichSelection(id)
            | Self::Bounds(id)
            | Self::Scroll(id)
            | Self::ScrollMetrics(id)
            | Self::Selection(id)
            | Self::Focus(id) => id,
        }
    }

    /// Semantic target checks precede host-specific availability checks. A
    /// boxless Group has no physical bounds/scroll/selection of its own.
    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
        let node = node.into();
        if matches!(node.props, Props::Group) {
            return Err(Error::Unsupported("group has no physical query target"));
        }
        if matches!(self, Self::RichSelection(_)) && !matches!(node.props, Props::RichEditor(_)) {
            return Err(Error::Unsupported("rich selection requires a RichEditor"));
        }
        if let Self::FileRead(read) = self {
            read.validate()?;
        }
        if let Self::FileRead(FileRead { file, .. }) | Self::FilePreview(file) = self {
            file.validate()?;
            let Props::File(props) = node.props else {
                return Err(Error::Unsupported("file queries require a File control"));
            };
            if file.revision != props.revision {
                return Err(Error::InputRevision {
                    current: props.revision,
                    incoming: file.revision,
                });
            }
            // Disabling selection does not revoke an already selected file.
            // Reads/previews retain their token and configuration checks;
            // picker/removal actions still enforce the enabled state.
            if matches!(self, Self::FilePreview(_)) && props.configuration.preview.is_none() {
                return Err(Error::Unsupported("file previews are not enabled"));
            }
        }

        if matches!(self, Self::Selection(_)) && !matches!(node.props, Props::Input(_)) {
            return Err(Error::Unsupported("selection requires a text input"));
        }
        Ok(())
    }

    /// Check adapter output before it reaches application callbacks. Coordinates
    /// use logical pixels; selection offsets use UTF-16 code units on all hosts.
    pub fn validate_response(self, value: &QueryValue) -> Result<(), Error> {
        match (self, value) {
            (Self::FileRead(read), QueryValue::FileBytes(chunk)) => chunk.validate_read(read)?,
            (Self::FilePreview(file), QueryValue::FilePreview(preview)) => {
                if let Some(preview) = preview {
                    preview.validate()?;
                    if preview.file != file {
                        return Err(Error::InvalidResponse("file preview token mismatch"));
                    }
                }
            }
            (Self::RichSelection(_), QueryValue::RichSelection(snapshot)) => snapshot.validate()?,
            (Self::Bounds(_), QueryValue::Bounds(rect)) => {
                if ![rect.x, rect.y, rect.width, rect.height]
                    .into_iter()
                    .all(f64::is_finite)
                    || rect.width < 0.0
                    || rect.height < 0.0
                {
                    return Err(Error::InvalidResponse("invalid bounds"));
                }
            }
            (Self::Scroll(_), QueryValue::Scroll { x, y }) => {
                // Native RTL and elastic scrolling can expose negative offsets.
                if !x.is_finite() || !y.is_finite() {
                    return Err(Error::InvalidResponse("invalid scroll offsets"));
                }
            }
            (Self::ScrollMetrics(_), QueryValue::ScrollMetrics(metrics)) => metrics.validate()?,
            (Self::Selection(_), QueryValue::Selection { start, end }) => {
                if start > end {
                    return Err(Error::InvalidResponse("reversed selection"));
                }
            }
            (Self::Focus(_), QueryValue::Focus(_)) => {}
            _ => return Err(Error::InvalidResponse("query result kind mismatch")),
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Action {
    PickFiles {
        node: NodeId,
        revision: u64,
        request: u64,
    },
    ClearFiles {
        node: NodeId,
        revision: u64,
    },
    RemoveFile(FileToken),
    CopyText {
        node: NodeId,
        revision: u64,
        request: u64,
    },
    /// Bring a current nonmodal Dialog layer forward without moving its DOM,
    /// editor identity or actual focus. The host's current modal still applies.
    RaiseLayer(NodeId),
    /// Reveal one current physical box using nearest alignment and instant
    /// scrolling, without focus or a logical collection controller.
    ScrollIntoView(NodeId),
    /// Select a range in the current rich document at its accepted revision.
    SelectRich {
        node: NodeId,
        revision: u64,
        selection: RichSelection,
    },
    /// Select an exact UTF-16 range in the current Input value. Stale revisions
    /// and offsets inside surrogate pairs are rejected. A host may refuse
    /// positions inside a shaped cluster; it must never silently clamp them.
    SelectText {
        node: NodeId,
        revision: u64,
        selection: TextSelection,
    },
    /// Reveal a mounted option inside its nearest owning listbox, preserving
    /// actual combobox focus and the outer document scroll position.
    RevealOption {
        node: NodeId,
    },
    /// Leave this named nonmodal Menu's tree in native Tab order, relative to
    /// its return-focus trigger. Does not imply the controlled menu accepted a close.
    ExitMenu {
        node: NodeId,
        backwards: bool,
    },
    /// Request focus without scrolling. Ok means the host processed the intent;
    /// it may decline because of current layout/platform state. Query::Focus
    /// reads the actual result; FocusChanged reports actual transitions only.
    Focus(NodeId),
    ScrollTo {
        node: NodeId,
        x: f64,
        y: f64,
    },
}
impl Action {
    pub fn node(self) -> NodeId {
        match self {
            Self::PickFiles { node, .. }
            | Self::ClearFiles { node, .. }
            | Self::CopyText { node, .. } => node,
            Self::RemoveFile(file) => file.node,
            Self::Focus(node)
            | Self::RaiseLayer(node)
            | Self::ScrollIntoView(node)
            | Self::ScrollTo { node, .. }
            | Self::ExitMenu { node, .. }
            | Self::RevealOption { node } => node,
            Self::SelectText { node, .. } | Self::SelectRich { node, .. } => node,
        }
    }
    /// Validate after checking identity, before capability checks or queuing.
    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
        let node = node.into();
        if let Self::SelectRich {
            revision,
            selection,
            ..
        } = self
        {
            let Props::RichEditor(editor) = node.props else {
                return Err(Error::Unsupported(
                    "rich selection action requires a RichEditor",
                ));
            };
            if revision != editor.revision {
                return Err(Error::InputRevision {
                    current: editor.revision,
                    incoming: revision,
                });
            }
            editor.document.validate_selection(selection)?;
            if !editor.enabled {
                return Err(Error::Unsupported("rich editor is disabled"));
            }
        }
        if let Self::PickFiles { revision, .. }
        | Self::ClearFiles { revision, .. }
        | Self::RemoveFile(FileToken { revision, .. }) = self
        {
            let Props::File(props) = node.props else {
                return Err(Error::Unsupported("file action requires a File control"));
            };
            if revision != props.revision {
                return Err(Error::InputRevision {
                    current: props.revision,
                    incoming: revision,
                });
            }
            if !matches!(self, Self::ClearFiles { .. }) && !props.enabled {
                return Err(Error::Unsupported("file control is disabled"));
            }
            if matches!(self, Self::PickFiles { request: 0, .. }) {
                return Err(Error::InvalidProps("file picker request must be positive"));
            }
            if let Self::RemoveFile(file) = self {
                file.validate()?;
            }
        }

        if let Self::CopyText {
            revision, request, ..
        } = self
        {
            let source = node
                .semantics
                .as_ref()
                .and_then(|s| s.clipboard.as_ref())
                .ok_or(Error::Unsupported("button has no clipboard source"))?;
            source.validate()?;
            if !matches!(node.props, Props::Button(_))
                || !node.props.enabled()
                || node.semantics.as_ref().is_some_and(|s| s.disabled)
            {
                return Err(Error::Unsupported("clipboard requires an enabled Button"));
            }
            if revision != source.revision || request == 0 {
                return Err(Error::InvalidProps(
                    "clipboard request requires the exact source revision and a positive identity",
                ));
            }
        }
        if matches!(self, Self::RaiseLayer(_))
            && (node.role != Some(Role::Dialog)
                || node.hidden()
                || !node
                    .semantics
                    .as_ref()
                    .and_then(|s| s.layer.as_ref())
                    .is_some_and(|layer| !layer.modal))
        {
            return Err(Error::Unsupported(
                "raise requires an open nonmodal dialog layer",
            ));
        }
        if let Self::SelectText {
            revision,
            selection,
            ..
        } = self
        {
            let Props::Input(input) = node.props else {
                return Err(Error::Unsupported("text selection requires an Input"));
            };
            if revision != input.revision {
                return Err(Error::InputRevision {
                    current: input.revision,
                    incoming: revision,
                });
            }
            selection.byte_range(&input.value)?;
        }
        if matches!(self, Self::Focus(_))
            && node.semantics.as_ref().is_some_and(|s| s.menubar_item)
            && node.focus != FocusMode::TabStop
        {
            return Err(Error::Unsupported(
                "menubar focus intent no longer names the current root",
            ));
        }
        if matches!(self, Self::RevealOption { .. })
            && !node.semantics.as_ref().is_some_and(|s| s.option.is_some())
        {
            return Err(Error::Unsupported(
                "option reveal requires an intrinsic listbox option",
            ));
        }
        if matches!(self, Self::Focus(_))
            && (node.role == Some(Role::Listbox)
                || node.semantics.as_ref().is_some_and(|s| s.option.is_some()))
        {
            return Err(Error::Unsupported(
                "listbox options preserve combobox focus",
            ));
        }
        if matches!(self, Self::ExitMenu { .. })
            && (node.role != Some(Role::Menu)
                || !node
                    .semantics
                    .as_ref()
                    .and_then(|s| s.layer.as_ref())
                    .is_some_and(|layer| {
                        !layer.modal
                            && (layer.return_focus.is_some()
                                || matches!(layer.placement, LayerPlacement::ContextPoint(_))
                                    && layer.anchor.is_some())
                    }))
        {
            return Err(Error::Unsupported(
                "menu exit requires a named nonmodal menu with a return target",
            ));
        }
        if let Self::ScrollTo { x, y, .. } = self
            && (!x.is_finite() || !y.is_finite() || x < 0.0 || y < 0.0)
        {
            return Err(Error::InvalidProps("invalid scroll position"));
        }
        if matches!(self, Self::Focus(_))
            && node.role == Some(Role::Separator)
            && !node
                .semantics
                .as_ref()
                .is_some_and(|s| s.splitter.is_some())
        {
            return Err(Error::Unsupported("focus on passive separator"));
        }
        if matches!(self, Self::Focus(_)) && node.role == Some(Role::Tooltip) {
            return Err(Error::Unsupported("focus on passive tooltip"));
        }
        if matches!(self, Self::Focus(_)) && node.role == Some(Role::ProgressBar) {
            return Err(Error::Unsupported("focus on passive progress"));
        }
        if matches!(node.props, Props::Group) {
            return Err(Error::Unsupported("group has no physical action target"));
        }
        if matches!(self, Self::Focus(_)) && !node.props.enabled() {
            return Err(Error::Unsupported("focus on disabled control"));
        }
        if matches!(self, Self::Focus(_))
            && matches!(&node.props, Props::Image(image) if image.alternative.is_none())
        {
            return Err(Error::Unsupported("focus on decorative image"));
        }
        if matches!(self, Self::Focus(_))
            && matches!(node.props, Props::Graphic(graphic) if graphic.alternative.is_none())
        {
            return Err(Error::Unsupported("focus on decorative graphic"));
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

/// Logical collection navigation, independent of a host's key codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Navigation {
    Previous,
    Next,
    First,
    Last,
    PagePrevious,
    PageNext,
    /// Reveal the originating mounted row without moving keyboard focus.
    /// A virtual-list root or an origin outside its rows has no destination.
    Reveal,
}

#[derive(Clone, Debug, PartialEq)]
pub enum QueryValue {
    RichSelection(Box<RichSnapshot>),
    FileBytes(Box<FileChunk>),
    FilePreview(Option<Box<FilePreview>>),
    ScrollMetrics(ScrollMetrics),
    Focus(bool),
    Bounds(Rect),
    Scroll {
        x: f64,
        y: f64,
    },
    /// UTF-16 code-unit offsets, matching Web text controls. Native adapters must
    /// convert their engine's byte/scalar/grapheme offsets at this boundary.
    Selection {
        start: usize,
        end: usize,
    },
}

#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    RichCommand {
        command: RichCommand,
        revision: u64,
    },
    /// Current physical content exceeded the finite rich document grammar or
    /// budgets. The host restores its accepted value before publishing this.
    RichRejected {
        revision: u64,
    },
    RichEdit(Box<RichSnapshot>),
    RichSelection(Box<RichSnapshot>),
    Files(Box<FileEvent>),
    TreeNavigate {
        from: NodeId,
        command: TreeCommand,
    },
    Clipboard {
        revision: u64,
        request: u64,
        outcome: ClipboardOutcome,
    },
    GridNavigate {
        from: NodeId,
        command: GridCommand,
    },
    InputEdit(InputEdit),
    /// Terminal presentation observation; valid while the closing subtree is
    /// logically hidden/inert, without admitting business input there.
    CollapseComplete {
        revision: u64,
    },
    PresenceComplete {
        revision: u64,
    },
    ContextMenu {
        from: NodeId,
        point: ContextPoint,
        source: ContextSource,
    },
    Sheet {
        from: NodeId,
        revision: u64,
        command: SheetCommand,
    },
    NavigationPanel {
        from: NodeId,
        command: NavigationPanelCommand,
    },
    Spin {
        from: NodeId,
        command: RangeCommand,
    },
    Range {
        from: NodeId,
        command: RangeCommand,
    },
    ScrollKeyboard {
        from: NodeId,
        command: ScrollCommand,
    },
    /// Terminal observation for one program-selected image request.
    ImageStatus {
        revision: u64,
        status: ImageStatus,
    },
    Menu {
        from: NodeId,
        command: MenuCommand,
    },
    /// A queued observation in an explicitly observed View's local border box.
    PlotPointer {
        from: NodeId,
        pointer: PlotPointer,
    },
    Pointer {
        from: NodeId,
        related: Option<NodeId>,
        phase: PointerPhase,
    },
    /// Logical boundary observation derived from a physical pointer origin.
    PointerWithin {
        from: NodeId,
        related: Option<NodeId>,
        phase: PointerPhase,
    },
    /// Native form default behavior is cancelled before this queued request.
    /// None represents a programmatic request or implicit keyboard submission.
    Submit {
        submitter: Option<NodeId>,
    },
    Reset,
    Activate,
    /// An activation of an explicitly declared target in a display instance.
    DisplayClick(u16),
    /// A request only: the application may keep controlled state open.
    Dismiss(DismissReason),
    /// Host preference, independent of an application's explicit appearance.
    ColorSchemeChanged {
        dark: bool,
    },
    /// Physical origin remains explicit while App routes to the nearest observer.
    Keyboard {
        from: NodeId,
        command: KeyboardCommand,
    },
    /// Only the explicit palette chord; other application commands stay native.
    Palette {
        from: NodeId,
    },
    /// Start/Move/Cancel target the source. Drop targets a live accepting node.
    Swipe {
        from: NodeId,
        phase: DragPhase,
        x: f64,
        y: f64,
        revision: u64,
    },
    Drag {
        from: NodeId,
        phase: DragPhase,
        x: f64,
        y: f64,
    },
    ValueChanged {
        value: String,
        composing: bool,
        revision: u64,
    },
    Commit {
        value: String,
        revision: u64,
    },
    CheckedChanged(bool),
    Tags {
        from: NodeId,
        revision: u64,
        command: TagsCommand,
    },
    Choice {
        from: NodeId,
        command: ChoiceCommand,
    },
    SelectChanged {
        keys: Vec<SemanticId>,
        revision: u64,
    },
    /// Direct focus origin. Hosts report this even if only an ancestor has a
    /// FocusWithin interest; App derives the logical ancestor observations.
    FocusChanged(bool),
    /// Focus transition originating at `node`, delivered to observing logical
    /// ancestors (including boxless Groups). FocusChanged itself stays direct.
    FocusWithin {
        node: NodeId,
        focused: bool,
    },
    /// Origin stays explicit when routed to the nearest logical observer.
    Navigate {
        from: NodeId,
        command: Navigation,
    },
    Typeahead {
        from: NodeId,
        text: String,
        at_millis: u64,
    },
    Composition {
        active: bool,
    },
    Scroll {
        x: f64,
        y: f64,
        viewport: Rect,
        /// Last accepted assignment, separate from current x/y (which may
        /// already include native movement). None before any host assignment.
        ack: Option<ScrollAck>,
    },
    /// Border-box size and client viewport are distinct (borders/scrollbars).
    /// Size uses local x/y=0; adapters preserve fractional layout dimensions.
    Resize {
        size: Rect,
        viewport: Rect,
    },
    /// Restore an existing visible row and its pixel inset at host handover.
    Anchor {
        row: NodeId,
        within: f64,
        viewport: Rect,
    },
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollRequest {
    pub x: f64,
    pub y: f64,
}
/// Last accepted programmatic assignment, retained on later observations so
/// native movement before the first acknowledgement is still distinguishable.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollAck {
    pub requested: ScrollRequest,
    pub x: f64,
    pub y: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EventKind {
    DisplayClick,
    RichCommand,
    RichRejected,
    RichEdit,
    RichSelection,
    Files,
    TreeNavigate,
    Clipboard,
    GridNavigate,
    InputEdit,
    CollapseComplete,
    PresenceComplete,
    ContextMenu,
    Tags,
    Sheet,
    NavigationPanel,
    Spin,
    Range,
    ScrollKeyboard,
    ImageStatus,
    Menu,
    PlotPointer,
    Pointer,
    PointerWithin,
    Submit,
    Reset,
    Activate,
    Dismiss,
    ColorSchemeChanged,
    Keyboard,
    Palette,
    Swipe,
    Drag,
    ValueChanged,
    Commit,
    CheckedChanged,
    SelectChanged,
    Choice,
    FocusChanged,
    FocusWithin,
    Navigate,
    Typeahead,
    Composition,
    Scroll,
    Resize,
    Anchor,
}
/// Finite event targets of one opaque display instance, not element identities.
#[derive(Clone, Debug)]
pub struct DisplayEvents(pub Vec<u16>);

impl EventKind {
    /// Logical bubbling/ancestor observations can target Groups; direct physical
    /// observations cannot. Recording a valid interest does not promise the host
    /// can produce it (SSR records handlers for later browser adoption).
    pub fn validate_target<'a>(self, node: impl Into<DescriptorView<'a>>) -> Result<(), Error> {
        let node = node.into();
        if self == Self::PlotPointer && !matches!(node.props, Props::View) {
            return Err(Error::Unsupported(
                "plot pointer requires a physical View viewport",
            ));
        }
        if self == Self::DisplayClick
            && (!matches!(node.props, Props::Group)
                || node.options.get::<DisplayEvents>().is_none())
        {
            return Err(Error::InvalidEvent(
                "display activation requires a declared instance",
            ));
        }
        if matches!(
            self,
            Self::RichEdit | Self::RichSelection | Self::RichRejected | Self::RichCommand
        ) && !matches!(node.props, Props::RichEditor(_))
        {
            return Err(Error::InvalidProps(
                "rich observations require a RichEditor",
            ));
        }
        if self == Self::Swipe
            && (!matches!(node.props, Props::View)
                || node
                    .semantics
                    .as_ref()
                    .is_none_or(|s| s.swipe_capture.is_none()))
        {
            return Err(Error::InvalidProps(
                "swipe observations require a declared View capture",
            ));
        }
        if self == Self::Files && !matches!(node.props, Props::File(_)) {
            return Err(Error::InvalidProps(
                "file observations require a File control",
            ));
        }

        if self == Self::TreeNavigate
            && (node.role != Some(Role::Tree)
                || !matches!(node.props, Props::View)
                || node
                    .semantics
                    .as_ref()
                    .is_none_or(|s| s.tree_navigation.is_none()))
        {
            return Err(Error::InvalidProps(
                "tree navigation requires an opted-in Tree View",
            ));
        }
        if self == Self::Clipboard
            && (!matches!(node.props, Props::Button(_))
                || node
                    .semantics
                    .as_ref()
                    .is_none_or(|s| s.clipboard.is_none()))
        {
            return Err(Error::Unsupported(
                "clipboard observation requires a declared Button source",
            ));
        }
        if self == Self::GridNavigate
            && (node.role != Some(Role::Grid)
                || !matches!(node.props, Props::View)
                || !node
                    .semantics
                    .as_ref()
                    .is_some_and(|s| s.grid_navigation.is_some()))
        {
            return Err(Error::InvalidProps(
                "grid navigation requires an opted-in Grid View",
            ));
        }
        if self == Self::InputEdit
            && !matches!(node.props,Props::Input(p) if !p.multiline&&node.semantics.as_ref().is_some_and(|s|s.input_edit.is_some()))
        {
            return Err(Error::Unsupported(
                "InputEdit requires an opted-in single-line Input",
            ));
        }
        if self == Self::PresenceComplete
            && (!matches!(node.props, Props::View)
                || !node
                    .semantics
                    .as_ref()
                    .is_some_and(|s| s.presence.is_some()))
        {
            return Err(Error::InvalidProps(
                "presence completion requires a presence View",
            ));
        }
        if self == Self::CollapseComplete
            && (!matches!(node.props, Props::View)
                || !node
                    .semantics
                    .as_ref()
                    .is_some_and(|s| s.collapse.is_some()))
        {
            return Err(Error::InvalidProps(
                "collapse completion requires a collapse View",
            ));
        }
        if self == Self::ContextMenu
            && (!matches!(node.props, Props::View)
                || !node
                    .semantics
                    .as_ref()
                    .is_some_and(|s| s.context_menu.is_some()))
        {
            return Err(Error::InvalidProps(
                "context requests require an opted-in region view",
            ));
        }
        if self == Self::Tags
            && !matches!(node.props,Props::Input(input) if !input.multiline && node.semantics.as_ref().is_some_and(|s|s.tags_input.is_some()))
        {
            return Err(Error::InvalidProps(
                "tags commands require an opted-in single-line input",
            ));
        }
        if self == Self::Sheet && !matches!(node.props, Props::View) {
            return Err(Error::InvalidProps("sheet commands require a view"));
        }
        if self == Self::NavigationPanel
            && !matches!(node.props, Props::Button(_) | Props::Link(_) | Props::View)
        {
            return Err(Error::InvalidProps(
                "navigation panel commands require a physical navigation control or content view",
            ));
        }
        if self == Self::Spin
            && !matches!(node.props, Props::Input(p) if !p.multiline && node.semantics.as_ref().is_some_and(|s| s.spinbutton.is_some()))
        {
            return Err(Error::InvalidProps(
                "spin commands require an opted-in single-line input",
            ));
        }
        if self == Self::Range
            && (!matches!(node.props, Props::View)
                || !matches!(node.role, Some(Role::Separator | Role::Slider)))
        {
            return Err(Error::InvalidProps(
                "range commands require a slider or splitter separator",
            ));
        }
        if self == Self::Choice
            && !node
                .semantics
                .as_ref()
                .is_some_and(|s| s.combobox.is_some())
        {
            return Err(Error::InvalidProps("choice commands require a combobox"));
        }
        if self == Self::SelectChanged && !matches!(node.props, Props::Select(_)) {
            return Err(Error::InvalidProps("selection event requires a select"));
        }
        if self == Self::ScrollKeyboard && !matches!(node.props, Props::View) {
            return Err(Error::InvalidProps(
                "scroll keyboard requires a viewport view",
            ));
        }
        if self == Self::ImageStatus && !matches!(node.props, Props::Image(_)) {
            return Err(Error::InvalidProps("image status requires an image"));
        }
        if matches!(self, Self::Submit | Self::Reset) && node.field_part() != Some(FieldPart::Form)
        {
            return Err(Error::InvalidProps("form request requires a form"));
        }
        if matches!(
            node.role,
            Some(Role::Separator | Role::Tooltip | Role::ProgressBar)
        ) && matches!(
            self,
            Self::Activate
                | Self::Keyboard
                | Self::Palette
                | Self::ScrollKeyboard
                | Self::Drag
                | Self::Navigate
                | Self::Typeahead
                | Self::Menu
                | Self::NavigationPanel
                | Self::Range
        ) && !(node.role == Some(Role::Separator)
            && node
                .semantics
                .as_ref()
                .is_some_and(|s| s.splitter.is_some())
            && matches!(self, Self::Range | Self::Drag))
        {
            return Err(Error::Unsupported("passive separator has no interaction"));
        }
        // Interests may be registered before layer metadata bindings run.
        if self == Self::Dismiss && !matches!(node.props, Props::View) {
            return Err(Error::InvalidProps("dismiss requires a view"));
        }
        if matches!(self, Self::Drag | Self::ColorSchemeChanged)
            && !matches!(node.props, Props::View)
        {
            return Err(Error::Unsupported(
                "host observation requires a semantic View",
            ));
        }
        if self == Self::Palette
            && matches!(
                node.props,
                Props::Group | Props::Input(_) | Props::Select(_)
            )
        {
            return Err(Error::Unsupported(
                "palette shortcut requires a non-editor physical scope or origin",
            ));
        }
        if matches!(self, Self::ValueChanged | Self::Commit)
            && !matches!(node.props, Props::Input(_))
            || self == Self::Composition
                && !matches!(node.props, Props::Input(_) | Props::RichEditor(_))
            || matches!(self, Self::CheckedChanged) && !matches!(node.props, Props::Check(_))
        {
            return Err(Error::InvalidProps("event does not belong to this control"));
        }
        if matches!(node.props, Props::Group)
            && matches!(
                self,
                Self::Resize
                    | Self::Scroll
                    | Self::Anchor
                    | Self::FocusChanged
                    | Self::Drag
                    | Self::Pointer
            )
        {
            return Err(Error::Unsupported("group has no physical event target"));
        }
        Ok(())
    }
}

impl Event {
    /// User input is suppressed by inherited inert regions. Resource/layout
    /// observations and terminal cleanup remain available to live Owners.
    pub fn is_user_interaction(&self) -> bool {
        !self.is_terminal_loss()
            && !matches!(
                self,
                Self::Clipboard { .. }
                    | Self::ImageStatus { .. }
                    | Self::ColorSchemeChanged { .. }
                    | Self::Scroll { .. }
                    | Self::Resize { .. }
                    | Self::Anchor { .. }
            )
    }
    /// Cleanup observations still reach live scopes after suspension. Retired
    /// identities never become valid again because an event is terminal.
    pub fn is_terminal_loss(&self) -> bool {
        if let Self::Files(event) = self {
            return !matches!(event.outcome, FileOutcome::Selected(_));
        }
        matches!(
            self,
            Self::Clipboard { .. }
                | Self::CollapseComplete { .. }
                | Self::PresenceComplete { .. }
                | Self::FocusChanged(false)
                | Self::Composition { active: false }
                | Self::FocusWithin { focused: false, .. }
                | Self::Swipe {
                    phase: DragPhase::Cancel,
                    ..
                }
                | Self::Drag {
                    phase: DragPhase::Cancel,
                    ..
                }
                | Self::PlotPointer {
                    pointer: PlotPointer {
                        phase: PlotPointerPhase::Leave | PlotPointerPhase::Cancel,
                        ..
                    },
                    ..
                }
                | Self::Pointer {
                    phase: PointerPhase::Leave,
                    ..
                }
                | Self::PointerWithin {
                    phase: PointerPhase::Leave,
                    ..
                }
        )
    }

    pub(crate) fn origin(&self) -> Option<NodeId> {
        match self {
            Self::TreeNavigate { from, .. } => Some(*from),
            Self::GridNavigate { from, .. } => Some(*from),
            Self::ContextMenu { from, .. } => Some(*from),
            Self::Tags { from, .. } => Some(*from),
            Self::Submit { submitter } => *submitter,
            Self::FocusWithin { node, .. } => Some(*node),
            Self::Navigate { from, .. } => Some(*from),
            Self::Menu { from, .. }
            | Self::PlotPointer { from, .. }
            | Self::Pointer { from, .. }
            | Self::PointerWithin { from, .. } => Some(*from),
            Self::Typeahead { from, .. } => Some(*from),
            Self::Choice { from, .. } | Self::Keyboard { from, .. } | Self::Palette { from } => {
                Some(*from)
            }
            Self::ScrollKeyboard { from, .. } => Some(*from),
            Self::Spin { from, .. } | Self::Range { from, .. } => Some(*from),
            Self::Sheet { from, .. } => Some(*from),
            Self::NavigationPanel { from, .. } => Some(*from),
            Self::Swipe { from, .. } | Self::Drag { from, .. } => Some(*from),
            Self::Anchor { row, .. } => Some(*row),
            _ => None,
        }
    }

    /// Check typed host input before business handlers. Embedded identities'
    /// liveness/ancestry require a tree and are checked by Memory::validate_event.
    /// Scroll offsets may be negative; local geometry must have x/y=0.
    pub fn validate_payload<'a>(
        &self,
        target: NodeId,
        node: impl Into<DescriptorView<'a>>,
    ) -> Result<(), Error> {
        self.validate_payload_view(target, node.into())
    }

    // One implementation for live descriptors and borrowed construction values;
    // conversion at the API boundary should not duplicate all event validation.
    fn validate_payload_view(&self, target: NodeId, node: DescriptorView<'_>) -> Result<(), Error> {
        if let Self::DisplayClick(slot) = self
            && (*slot >= 256
                || !node
                    .options
                    .get::<DisplayEvents>()
                    .is_some_and(|events| events.0.contains(slot)))
        {
            return Err(Error::InvalidEvent("undeclared display activation slot"));
        }
        if let Self::RichRejected { revision } | Self::RichCommand { revision, .. } = self {
            let Props::RichEditor(editor) = node.props else {
                return Err(Error::InvalidEvent("rich rejection requires its editor"));
            };
            if *revision > editor.revision {
                return Err(Error::InputRevision {
                    current: editor.revision,
                    incoming: *revision,
                });
            }
        }
        if let Self::RichEdit(snapshot) | Self::RichSelection(snapshot) = self {
            let Props::RichEditor(editor) = node.props else {
                return Err(Error::InvalidEvent("rich input requires its RichEditor"));
            };
            snapshot.validate_input(editor)?;
        }
        if let Self::Swipe {
            from,
            x,
            y,
            revision,
            ..
        } = self
        {
            EventKind::Swipe.validate_target(node)?;
            if from.runtime() != target.runtime() {
                return Err(Error::ForeignRuntime);
            }
            if *from != target || !x.is_finite() || !y.is_finite() {
                return Err(Error::InvalidEvent(
                    "swipe requires its exact finite boxed origin",
                ));
            }
            let capture = node
                .semantics
                .as_ref()
                .and_then(|s| s.swipe_capture)
                .expect("validated swipe capture");
            if *revision > capture.revision {
                return Err(Error::InputRevision {
                    current: capture.revision,
                    incoming: *revision,
                });
            }
        }
        if let Self::Files(event) = self {
            let Props::File(props) = node.props else {
                return Err(Error::InvalidEvent(
                    "file observations require a File control",
                ));
            };
            event.validate_node(target, props)?;
        }

        if let Self::TreeNavigate { from, command } = self {
            EventKind::TreeNavigate.validate_target(node)?;
            command.validate()?;
            if from.runtime() != target.runtime() {
                return Err(Error::ForeignRuntime);
            }
            if *from == target {
                return Err(Error::InvalidEvent(
                    "tree command requires a descendant TreeItem",
                ));
            }
            if matches!(command, TreeCommand::Search { .. })
                && node
                    .semantics
                    .as_ref()
                    .and_then(|s| s.tree_navigation)
                    .is_none_or(|s| !s.typeahead)
            {
                return Err(Error::InvalidEvent("tree search is not enabled"));
            }
        }
        if let Self::Clipboard {
            revision, request, ..
        } = self
        {
            EventKind::Clipboard.validate_target(node)?;
            let source = node
                .semantics
                .as_ref()
                .and_then(|s| s.clipboard.as_ref())
                .expect("validated source");
            if *request == 0 || *revision > source.revision {
                return Err(Error::InvalidEvent(
                    "clipboard completion has a future revision or zero request",
                ));
            }
        }
        if let Self::GridNavigate { from, .. } = self {
            EventKind::GridNavigate.validate_target(node)?;
            if from.runtime() != target.runtime() {
                return Err(Error::ForeignRuntime);
            }
            if *from == target {
                return Err(Error::InvalidEvent(
                    "grid navigation requires a real descendant Button",
                ));
            }
        }
        if let Self::InputEdit(edit) = self {
            EventKind::InputEdit.validate_target(node)?;
            let capture = node
                .semantics
                .as_ref()
                .and_then(|s| s.input_edit)
                .ok_or(Error::InvalidEvent("input edit capture is absent"))?;
            edit.validate(capture)?;
            if let Props::Input(input) = node.props
                && edit.revision() > input.revision
            {
                return Err(Error::InputRevision {
                    current: input.revision,
                    incoming: edit.revision(),
                });
            }
        }
        if let Self::PresenceComplete { revision } = self {
            let config = node
                .semantics
                .as_ref()
                .and_then(|s| s.presence.as_ref())
                .ok_or(Error::InvalidEvent(
                    "presence completion requires a presence View",
                ))?;
            if *revision > config.revision {
                return Err(Error::PresenceRevision {
                    current: config.revision,
                    incoming: *revision,
                });
            }
        }
        if let Self::CollapseComplete { revision } = self {
            let config = node
                .semantics
                .as_ref()
                .and_then(|s| s.collapse.as_ref())
                .ok_or(Error::InvalidEvent(
                    "collapse completion requires a collapse View",
                ))?;
            if *revision > config.revision {
                return Err(Error::CollapseRevision {
                    current: config.revision,
                    incoming: *revision,
                });
            }
        }
        if let Self::Sheet {
            from,
            revision,
            command,
        } = self
        {
            if from.runtime() != target.runtime() {
                return Err(Error::ForeignRuntime);
            }
            let config = node
                .semantics
                .as_ref()
                .and_then(|s| s.layer.as_ref())
                .and_then(|layer| layer.sheet.as_ref())
                .ok_or(Error::InvalidEvent("sheet command requires a sheet"))?;
            if *from != target {
                return Err(Error::InvalidEvent(
                    "sheet command origin must equal its target",
                ));
            }
            if *revision > config.revision {
                return Err(Error::SheetRevision {
                    current: config.revision,
                    incoming: *revision,
                });
            }
            if *revision == config.revision
                && match command {
                    SheetCommand::Snap(index) => *index >= config.fractions.len(),
                    SheetCommand::Dismiss => !config.dismissible,
                }
            {
                return Err(Error::InvalidEvent(
                    "sheet command exceeds its accepted configuration",
                ));
            }
        }
        if let Self::Dismiss(reason) = self {
            let layer = node
                .semantics
                .as_ref()
                .and_then(|s| s.layer.as_ref())
                .ok_or(Error::InvalidEvent("dismiss requires a layer"))?;
            if !match reason {
                DismissReason::Gesture => {
                    layer.sheet.as_ref().is_some_and(|sheet| sheet.dismissible)
                }
                DismissReason::Escape => layer.escape,
                DismissReason::Outside => layer.outside,
                DismissReason::AnchorLost => layer.anchor.is_some(),
            } {
                return Err(Error::InvalidEvent("disabled layer dismissal"));
            }
        }
        if self
            .origin()
            .is_some_and(|id| id.runtime() != target.runtime())
        {
            return Err(Error::ForeignRuntime);
        }
        self.kind().validate_target(node)?;
        if matches!(
            self,
            Self::Choice {
                command: ChoiceCommand::RemoveLast,
                ..
            }
        ) && node.semantics.as_ref().and_then(|value| value.combobox)
            != Some(ComboboxKind::Multiple)
        {
            return Err(Error::InvalidEvent(
                "remove-last requires a multiple combobox",
            ));
        }
        let local = |rect: &Rect| {
            rect.x == 0.0
                && rect.y == 0.0
                && rect.width.is_finite()
                && rect.height.is_finite()
                && rect.width >= 0.0
                && rect.height >= 0.0
        };
        match self {
            Self::PlotPointer { from, pointer } => {
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "plot pointer requires its observed viewport origin",
                    ));
                }
                pointer.validate()?;
            }
            Self::ContextMenu { from, point, .. } => {
                if from.runtime() != target.runtime() {
                    return Err(Error::ForeignRuntime);
                }
                point.validate()?;
                EventKind::ContextMenu.validate_target(node)?;
            }
            Self::Spin { from, command } => {
                EventKind::Spin.validate_target(node)?;
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "spin command requires its physical origin",
                    ));
                }
                let spin = node
                    .semantics
                    .as_ref()
                    .filter(|s| !s.disabled && !s.readonly && node.props.enabled())
                    .and_then(|s| s.spinbutton.as_ref())
                    .ok_or(Error::InvalidEvent(
                        "spin command requires an enabled writable input",
                    ))?;
                spin.validate_command(*command)?;
            }
            Self::Range { from, command } => {
                let range = node
                    .semantics
                    .as_ref()
                    .filter(|s| !s.disabled)
                    .and_then(|s| {
                        s.splitter
                            .or_else(|| s.slider.as_ref().map(|slider| slider.range))
                    })
                    .ok_or(Error::InvalidEvent(
                        "range command requires an enabled slider or splitter",
                    ))?;
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "range command requires its physical origin",
                    ));
                }
                command.validate(range)?;
            }
            Self::Choice { from, .. } => {
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "choice command requires the combobox physical origin",
                    ));
                }
            }
            Self::ScrollKeyboard { from, command } => {
                if *from != target
                    || !node
                        .semantics
                        .as_ref()
                        .and_then(|s| s.scroll_keyboard)
                        .is_some_and(|axes| axes.allows(command.axis))
                {
                    return Err(Error::InvalidEvent(
                        "scroll keyboard requires its opted-in physical viewport and axis",
                    ));
                }
            }
            Self::PointerWithin { related, .. } => {
                if related.is_some_and(|related| related.runtime() != target.runtime()) {
                    return Err(Error::ForeignRuntime);
                }
            }
            Self::NavigationPanel { from, command } => {
                if *from != target || matches!(node.props, Props::Group) {
                    return Err(Error::InvalidEvent(
                        "navigation panel requires its exact physical origin",
                    ));
                }
                let marker = node.semantics.as_ref().and_then(|s| s.navigation_panel);
                let member = node.semantics.as_ref().is_some_and(|s| s.navigation_item);
                if *command == NavigationPanelCommand::Close {
                    if !member && marker != Some(NavigationPanel::Content) {
                        return Err(Error::InvalidEvent(
                            "navigation close requires a content member",
                        ));
                    }
                } else if marker != Some(NavigationPanel::Trigger) {
                    return Err(Error::InvalidEvent(
                        "navigation entry requires a disclosure trigger",
                    ));
                }
            }
            Self::Menu { from, .. } | Self::Pointer { from, .. } => {
                if *from != target || matches!(node.props, Props::Group) {
                    return Err(Error::InvalidEvent(
                        "menu/pointer requires its physical origin",
                    ));
                }
                if matches!(self, Self::Menu { .. })
                    && node.role != Some(Role::Menu)
                    && !node.semantics.as_ref().is_some_and(|s| {
                        s.menu_item.is_some()
                            || s.menu_search.is_some()
                            || s.popup == Some(PopupKind::Menu)
                    })
                {
                    return Err(Error::InvalidEvent(
                        "menu command requires a menu or menu trigger/item",
                    ));
                }
                if matches!(
                    self,
                    Self::Menu {
                        command: MenuCommand::SearchNext
                            | MenuCommand::SearchPrevious
                            | MenuCommand::SearchCommit,
                        ..
                    }
                ) && node
                    .semantics
                    .as_ref()
                    .is_none_or(|s| s.menu_search.is_none())
                {
                    return Err(Error::InvalidEvent(
                        "search commands require a declared menu search editor",
                    ));
                }
                if node
                    .semantics
                    .as_ref()
                    .is_some_and(|s| s.menu_search.is_some())
                    && matches!(self, Self::Menu { command, .. } if !matches!(command, MenuCommand::SearchNext | MenuCommand::SearchPrevious | MenuCommand::SearchCommit | MenuCommand::Exit { .. }))
                {
                    return Err(Error::InvalidEvent(
                        "menu search editors accept search navigation and exit commands only",
                    ));
                }
                if let Self::Pointer {
                    related: Some(related),
                    ..
                } = self
                    && related.runtime() != target.runtime()
                {
                    return Err(Error::ForeignRuntime);
                }
            }
            Self::Typeahead {
                from,
                text,
                at_millis,
            } => {
                if *from != target || matches!(node.props, Props::Group) {
                    return Err(Error::InvalidEvent(
                        "typeahead requires its physical origin",
                    ));
                }
                validate_typeahead(text, *at_millis)?;
            }
            Self::Drag { from, phase, x, y } => {
                if !x.is_finite() || !y.is_finite() {
                    return Err(Error::InvalidEvent("drag coordinates must be finite"));
                }
                if *phase != DragPhase::Drop && *from != target {
                    return Err(Error::InvalidEvent("drag phase requires source target"));
                }
            }
            Self::Keyboard { from, command } => {
                if *from != target || matches!(node.props, Props::Group) {
                    return Err(Error::InvalidEvent("keyboard requires its physical origin"));
                }
                if *command == KeyboardCommand::Submit && !matches!(node.props, Props::Input(_)) {
                    return Err(Error::InvalidEvent("submit requires a text control"));
                }
            }
            Self::Palette { from } => {
                if from.runtime() != target.runtime() {
                    return Err(Error::ForeignRuntime);
                }
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "palette shortcut requires its physical origin",
                    ));
                }
                EventKind::Palette.validate_target(node)?;
            }
            Self::Navigate { from, .. } if *from != target => {
                return Err(Error::InvalidEvent(
                    "navigation origin must match its event target",
                ));
            }
            Self::Scroll {
                x,
                y,
                viewport,
                ack,
            } => {
                if !x.is_finite() || !y.is_finite() || !local(viewport) {
                    return Err(Error::InvalidEvent("invalid scroll geometry"));
                }
                if ack.is_some_and(|ack| {
                    !ack.requested.x.is_finite()
                        || !ack.requested.y.is_finite()
                        || ack.requested.x < 0.0
                        || ack.requested.y < 0.0
                        || !ack.x.is_finite()
                        || !ack.y.is_finite()
                }) {
                    return Err(Error::InvalidEvent("invalid scroll acknowledgement"));
                }
            }
            Self::Resize { size, viewport } if !local(size) || !local(viewport) => {
                return Err(Error::InvalidEvent("invalid resize geometry"));
            }
            Self::Anchor {
                within, viewport, ..
            } if !within.is_finite() || *within < 0.0 || !local(viewport) => {
                return Err(Error::InvalidEvent("invalid anchor geometry"));
            }
            Self::SelectChanged { keys, revision } => {
                if let Props::Select(select) = node.props {
                    select.validate_user_selection(keys)?;
                    if *revision > select.selection.revision {
                        return Err(Error::SelectRevision {
                            current: select.selection.revision,
                            incoming: *revision,
                        });
                    }
                }
            }
            Self::ImageStatus { revision, .. } => {
                if let Props::Image(image) = node.props
                    && *revision > image.revision
                {
                    return Err(Error::ImageRevision {
                        current: image.revision,
                        incoming: *revision,
                    });
                }
            }
            Self::ValueChanged {
                value, revision, ..
            }
            | Self::Commit { value, revision } => {
                if matches!(&node.props, Props::Input(input) if !input.multiline && value.contains(['\r', '\n']))
                {
                    return Err(Error::InvalidEvent(
                        "single-line input event cannot contain line breaks",
                    ));
                }
                if value.contains(['\0', '\r']) {
                    return Err(Error::InvalidEvent("input event text is not normalized"));
                }
                if let Props::Input(input) = &node.props
                    && *revision > input.revision
                {
                    return Err(Error::InputRevision {
                        current: input.revision,
                        incoming: *revision,
                    });
                }
            }
            Self::Tags {
                from,
                revision,
                command,
            } => {
                if *from != target {
                    return Err(Error::InvalidEvent(
                        "tags command requires its exact input origin",
                    ));
                }
                command.validate()?;
                if let Props::Input(input) = node.props
                    && *revision > input.revision
                {
                    return Err(Error::InputRevision {
                        current: input.revision,
                        incoming: *revision,
                    });
                }
            }
            _ => {}
        }
        Ok(())
    }

    pub fn kind(&self) -> EventKind {
        match self {
            Self::RichCommand { .. } => EventKind::RichCommand,
            Self::RichRejected { .. } => EventKind::RichRejected,
            Self::TreeNavigate { .. } => EventKind::TreeNavigate,
            Self::Files(_) => EventKind::Files,
            Self::Clipboard { .. } => EventKind::Clipboard,
            Self::GridNavigate { .. } => EventKind::GridNavigate,
            Self::InputEdit(_) => EventKind::InputEdit,
            Self::CollapseComplete { .. } => EventKind::CollapseComplete,
            Self::PresenceComplete { .. } => EventKind::PresenceComplete,
            Self::ContextMenu { .. } => EventKind::ContextMenu,
            Self::Tags { .. } => EventKind::Tags,
            Self::Spin { .. } => EventKind::Spin,
            Self::Range { .. } => EventKind::Range,
            Self::Sheet { .. } => EventKind::Sheet,
            Self::NavigationPanel { .. } => EventKind::NavigationPanel,
            Self::ScrollKeyboard { .. } => EventKind::ScrollKeyboard,
            Self::ImageStatus { .. } => EventKind::ImageStatus,
            Self::Menu { .. } => EventKind::Menu,
            Self::PlotPointer { .. } => EventKind::PlotPointer,
            Self::Pointer { .. } => EventKind::Pointer,
            Self::PointerWithin { .. } => EventKind::PointerWithin,
            Self::Submit { .. } => EventKind::Submit,
            Self::Reset => EventKind::Reset,
            Self::Activate => EventKind::Activate,
            Self::DisplayClick(_) => EventKind::DisplayClick,
            Self::Dismiss(_) => EventKind::Dismiss,
            Self::ColorSchemeChanged { .. } => EventKind::ColorSchemeChanged,
            Self::Keyboard { .. } => EventKind::Keyboard,
            Self::Palette { .. } => EventKind::Palette,
            Self::RichEdit(_) => EventKind::RichEdit,
            Self::RichSelection(_) => EventKind::RichSelection,
            Self::Swipe { .. } => EventKind::Swipe,
            Self::Drag { .. } => EventKind::Drag,
            Self::ValueChanged { .. } => EventKind::ValueChanged,
            Self::Commit { .. } => EventKind::Commit,
            Self::CheckedChanged(_) => EventKind::CheckedChanged,
            Self::SelectChanged { .. } => EventKind::SelectChanged,
            Self::Choice { .. } => EventKind::Choice,
            Self::FocusChanged(_) => EventKind::FocusChanged,
            Self::FocusWithin { .. } => EventKind::FocusWithin,
            Self::Navigate { .. } => EventKind::Navigate,
            Self::Typeahead { .. } => EventKind::Typeahead,
            Self::Composition { .. } => EventKind::Composition,
            Self::Scroll { .. } => EventKind::Scroll,
            Self::Resize { .. } => EventKind::Resize,
            Self::Anchor { .. } => EventKind::Anchor,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Input {
    Event {
        node: NodeId,
        event: Event,
    },
    Response {
        token: QueryToken,
        /// Applied mutation watermark observed by this request.
        applied: u64,
        result: Result<QueryValue, Error>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    Backend(String),
    ForeignRuntime,
    NodeGone(NodeId),
    StaleNode(NodeId),
    DuplicateNode(NodeId),
    InvalidPlacement(&'static str),
    InvalidProps(&'static str),
    Unsupported(&'static str),
    UnsupportedStyle {
        profile: &'static str,
        version: u32,
        requirement: style::Unsupported,
    },
    InvalidReceipt {
        previous: u64,
        applied: u64,
    },
    QueryWatermark {
        expected: u64,
        applied: u64,
    },
    InvalidResponse(&'static str),
    InvalidEvent(&'static str),
    InputRevision {
        current: u64,
        incoming: u64,
    },
    InputRevisionExhausted,
    SelectRevision {
        current: u64,
        incoming: u64,
    },
    SelectRevisionExhausted,
    ImageRevision {
        current: u64,
        incoming: u64,
    },
    ImageRevisionExhausted,
    SheetRevision {
        current: u64,
        incoming: u64,
    },
    SheetRevisionExhausted,
    CollapseRevision {
        current: u64,
        incoming: u64,
    },
    CollapseRevisionExhausted,
    PresenceRevision {
        current: u64,
        incoming: u64,
    },
    PresenceRevisionExhausted,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl std::error::Error for Error {}

/// Applying nodes does not imply pixels have been displayed.
/// Successful nonempty apply calls strictly advance this renderer-local
/// watermark; empty calls preserve it. It is not a displayed-frame sequence.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Receipt {
    pub applied: u64,
}

/// Local calls are typed and require no serialization. Each request observes
/// every preceding successful apply; adapters must not coalesce across requests.
/// A response carries the watermark at request acceptance, even if delivered
/// after later commits. Capture results at that barrier, not from a newer tree.
/// Errors may leave an applied prefix; adapters do not promise rollback.
pub trait Render {
    /// Commit adapter-owned display slots after semantic mutations and before
    /// actions/queries. This does not allocate semantic element identities.
    fn flush_display(&mut self) -> Result<(), Error> {
        Ok(())
    }
    /// Reject descriptor-local limitations before the App changes its logical
    /// tree or queues output. None checks creation; Some checks a patch against
    /// the supplied current descriptor, including earlier uncommitted changes.
    /// Read only these arguments and immutable adapter configuration: no host
    /// calls, layout, application callbacks, or committed-tree lookups. Adapters
    /// must enforce the same restrictions in apply for callers without an App.
    /// This is not a transaction or a guarantee that later host work succeeds.
    fn preflight(&self, _node: DescriptorView<'_>, _patch: Option<&Patch>) -> Result<(), Error> {
        Ok(())
    }
    /// Validate adapter-specific ancestor/content constraints against the App's
    /// staged semantic tree, including uncommitted Create/Patch/Place changes.
    /// New children are checked before identity allocation; existing children
    /// before Place/Resume changes the model or output queue. Read only these
    /// arguments/configuration: no host tree, layout, I/O or application code.
    /// The App checks shared identity/placement semantics first. Default adds
    /// no restrictions. Direct apply must enforce the same content rules.
    fn preflight_place(
        &self,
        _tree: &memory::Memory,
        _child: memory::Subtree<'_>,
        _parent: Option<NodeId>,
    ) -> Result<(), Error> {
        Ok(())
    }
    /// Optional local diagnostics. Return an unused or retired handle so its
    /// captured clock is dropped outside the caller's renderer borrow.
    fn set_profile(&mut self, profile: Option<profile::Profile>) -> Option<profile::Profile> {
        profile
    }
    /// Another local observation can make progress without awaiting I/O, an
    /// animation timestamp or a future browser frame. Read-only and never runs
    /// application code. Hosts with asynchronous observation keep the default.
    fn needs_observe(&self) -> bool {
        false
    }
    /// Declared once per App. Default rejects nonempty inline styles; adapters
    /// opt into exactly the declarations/values they preserve or implement.
    fn style_profile(&self) -> style::Profile {
        style::Profile::NONE
    }
    /// Event interest is frame metadata. Hosts may use it to avoid observing
    /// thousands of nodes whose resize/scroll events nobody consumes.
    fn listen(&mut self, _node: NodeId, _kind: EventKind, _enabled: bool) -> Result<(), Error> {
        Ok(())
    }
    /// Whether this host implements the finite local-coordinate plot channel.
    /// Static adapters may record interests for later adoption; input adapters
    /// must opt in explicitly. This does not enable ordinary Pointer events.
    fn supports_plot_pointer(&self) -> bool {
        false
    }
    fn capabilities(&self) -> Capabilities;
    fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error>;
    /// Optional immediate physical read at the caller's committed barrier.
    /// None means the host requires the queued Bounds query. Never call user code.
    fn bounds_now(&mut self, _node: NodeId) -> Option<Result<Rect, Error>> {
        None
    }
    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error>;
    /// Actions run after a frame's mutations and before subsequent queries.
    /// Unsupported focus refusal leaves the semantic tree valid: App treats it
    /// as an unfulfilled intent and continues later intents. Backend errors remain
    /// fatal. Never synthesize FocusChanged(true) merely for accepting Focus.
    fn action(&mut self, _action: Action) -> Result<(), Error> {
        Err(Error::Unsupported("platform action"))
    }
    /// Return queued inputs, never synchronously reenter business closures.
    fn drain(&mut self, inputs: &mut Vec<Input>);
}

mod environment;
mod table;
pub use environment::{Environment, LanguageTag};
pub use table::{MAX_CELL_HEADERS, MAX_TABLE_SPAN, SortDirection, TableMetadata};

mod swipe;
pub use swipe::SwipeCapture;

mod rich_document;
pub use rich_document::{
    MAX_RICH_BLOCKS, MAX_RICH_LINK_BYTES, MAX_RICH_METADATA_BYTES, MAX_RICH_RUNS,
    MAX_RICH_TEXT_BYTES, RichBlock, RichBlockKind, RichDocument, RichFormat, RichMarks, RichPoint,
    RichRun, RichSelection,
};
mod rich;
pub use rich::{RichCommand, RichEditorProps, RichSnapshot};