cranpose-foundation 0.26.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
//! 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, cell::Cell, fmt, hash::Hash, rc::Rc};

pub use cranpose_ui_graphics::{DrawScope, Size};
pub use cranpose_ui_layout::{Constraints, Measurable};

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

mod any_element;
mod chain;
mod chain_node_ref;
mod node_capabilities;
mod node_element;
mod scroll_axis_range;
mod semantics_configuration;

pub use any_element::*;
pub use chain::*;
pub use chain_node_ref::{ModifierChainIter, ModifierChainNodeRef};
pub use node_capabilities::NodeCapabilities;
pub use node_element::ModifierNodeElement;
pub use scroll_axis_range::ScrollAxisRange;
pub use semantics_configuration::{SemanticsConfiguration, SemanticsSpec};

/// 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
    }
}

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
    }
}

/// 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
    }
}

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