cranpose_foundation/modifier.rs
1//! Modifier node scaffolding for Cranpose.
2//!
3//! This module defines the foundational pieces of the Cranpose
4//! `Modifier.Node` system. It introduces traits for modifier nodes and their
5//! contexts as well as a lightweight chain container that reconciles nodes
6//! across updates.
7
8use std::{any::Any, cell::Cell, fmt, hash::Hash, rc::Rc};
9
10pub use cranpose_ui_graphics::{DrawScope, Size};
11pub use cranpose_ui_layout::{Constraints, Measurable};
12
13use crate::nodes::input::types::PointerEvent;
14
15mod any_element;
16mod chain;
17mod chain_node_ref;
18mod node_capabilities;
19mod node_element;
20mod scroll_axis_range;
21mod semantics_configuration;
22
23pub use any_element::*;
24pub use chain::*;
25pub use chain_node_ref::{ModifierChainIter, ModifierChainNodeRef};
26pub use node_capabilities::NodeCapabilities;
27pub use node_element::ModifierNodeElement;
28pub use scroll_axis_range::ScrollAxisRange;
29pub use semantics_configuration::{SemanticsConfiguration, SemanticsSpec};
30
31/// Identifies which part of the rendering pipeline should be invalidated
32/// after a modifier node changes state.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum InvalidationKind {
35 /// The node's size or placement may have changed, so layout runs again.
36 Layout,
37 /// The node's drawn output changed, so it draws again.
38 Draw,
39 /// The node's pointer input handling changed.
40 PointerInput,
41 /// The node's accessibility semantics changed.
42 Semantics,
43 /// The node's focus behavior changed.
44 Focus,
45}
46
47/// Runtime services exposed to modifier nodes while attached to a tree.
48pub trait ModifierNodeContext {
49 /// Requests that a particular pipeline stage be invalidated.
50 fn invalidate(&mut self, _kind: InvalidationKind) {}
51
52 /// Requests that the node's `update` method run again outside of a
53 /// regular composition pass.
54 fn request_update(&mut self) {}
55
56 /// Returns the ID of the layout node this modifier is attached to, if known.
57 /// This is used by modifiers that need to register callbacks for invalidation (e.g. Scroll).
58 fn node_id(&self) -> Option<cranpose_core::NodeId> {
59 None
60 }
61
62 /// Signals that a node with `capabilities` is about to interact with this context.
63 fn push_active_capabilities(&mut self, _capabilities: NodeCapabilities) {}
64
65 /// Signals that the most recent node interaction has completed.
66 fn pop_active_capabilities(&mut self) {}
67
68 /// The device pixels per layout point of the grid a layout modifier
69 /// measures on, Compose's `MeasureScope` density: lengths it places land
70 /// on whole device pixels of it. A context outside a layout pass answers
71 /// a unit grid.
72 fn density(&self) -> f32 {
73 1.0
74 }
75}
76
77/// Lightweight [`ModifierNodeContext`] implementation that records
78/// invalidation requests and update signals.
79///
80/// The context intentionally avoids leaking runtime details so the core
81/// crate can evolve independently from higher level UI crates. It simply
82/// stores the sequence of requested invalidation kinds and whether an
83/// explicit update was requested. Callers can inspect or drain this state
84/// after driving a [`ModifierNodeChain`] reconciliation pass.
85#[derive(Default, Debug, Clone)]
86pub struct BasicModifierNodeContext {
87 invalidations: ModifierInvalidations,
88 update_requested: bool,
89 /// The capabilities of the nodes interacting with the context, the
90 /// innermost last; nesting stays shallow, so the stack lives inline.
91 active_capabilities: smallvec::SmallVec<[NodeCapabilities; 4]>,
92 node_id: Option<cranpose_core::NodeId>,
93}
94
95impl BasicModifierNodeContext {
96 /// Creates a new empty context.
97 pub fn new() -> Self {
98 Self::default()
99 }
100
101 /// A context for the modifier nodes of node `node_id`, holding
102 /// `invalidations` an earlier operation left for this one to report.
103 pub fn for_node(
104 node_id: Option<cranpose_core::NodeId>,
105 invalidations: ModifierInvalidations,
106 ) -> Self {
107 Self {
108 invalidations,
109 node_id,
110 ..Self::default()
111 }
112 }
113
114 /// Returns the ordered list of invalidation kinds that were requested
115 /// since the last call to `clear_invalidations`. Duplicate requests for
116 /// the same kind are coalesced.
117 pub fn invalidations(&self) -> &[ModifierInvalidation] {
118 &self.invalidations
119 }
120
121 /// Removes all currently recorded invalidation kinds.
122 pub fn clear_invalidations(&mut self) {
123 self.invalidations.clear();
124 }
125
126 /// Drains the recorded invalidations and returns them to the caller.
127 pub fn take_invalidations(&mut self) -> ModifierInvalidations {
128 std::mem::take(&mut self.invalidations)
129 }
130
131 /// Returns whether an update was requested since the last call to
132 /// `take_update_requested`.
133 pub fn update_requested(&self) -> bool {
134 self.update_requested
135 }
136
137 /// Returns whether an update was requested and clears the flag.
138 pub fn take_update_requested(&mut self) -> bool {
139 std::mem::take(&mut self.update_requested)
140 }
141
142 /// Sets the node ID associated with this context.
143 pub fn set_node_id(&mut self, id: Option<cranpose_core::NodeId>) {
144 self.node_id = id;
145 }
146
147 fn push_invalidation(&mut self, kind: InvalidationKind) {
148 let mut capabilities = self.current_capabilities();
149 capabilities.insert(NodeCapabilities::for_invalidation(kind));
150 if let Some(existing) = self
151 .invalidations
152 .iter_mut()
153 .find(|entry| entry.kind() == kind)
154 {
155 let updated = existing.capabilities() | capabilities;
156 *existing = ModifierInvalidation::new(kind, updated);
157 } else {
158 self.invalidations
159 .push(ModifierInvalidation::new(kind, capabilities));
160 }
161 }
162
163 fn current_capabilities(&self) -> NodeCapabilities {
164 self.active_capabilities
165 .last()
166 .copied()
167 .unwrap_or_else(NodeCapabilities::empty)
168 }
169}
170
171impl ModifierNodeContext for BasicModifierNodeContext {
172 fn invalidate(&mut self, kind: InvalidationKind) {
173 self.push_invalidation(kind);
174 }
175
176 fn request_update(&mut self) {
177 self.update_requested = true;
178 }
179
180 fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
181 self.active_capabilities.push(capabilities);
182 }
183
184 fn pop_active_capabilities(&mut self) {
185 self.active_capabilities.pop();
186 }
187
188 fn node_id(&self) -> Option<cranpose_core::NodeId> {
189 self.node_id
190 }
191}
192
193const MAX_DELEGATE_DEPTH: usize = 3;
194
195#[derive(Copy, Clone, Debug, PartialEq, Eq)]
196pub(crate) struct NodePath {
197 /// The chain entry, 32 bits wide: a path sits in every link of a
198 /// chain's order, and no chain nears four billion entries.
199 entry: u32,
200 delegate_buf: [u8; MAX_DELEGATE_DEPTH],
201 delegate_len: u8,
202}
203
204impl NodePath {
205 #[inline]
206 fn root(entry: usize) -> Self {
207 debug_assert!(entry <= u32::MAX as usize, "chain entry exceeds u32 range");
208 Self {
209 entry: entry as u32,
210 delegate_buf: [0; MAX_DELEGATE_DEPTH],
211 delegate_len: 0,
212 }
213 }
214
215 #[inline]
216 fn from_slice(entry: usize, path: &[usize]) -> Self {
217 debug_assert!(
218 path.len() <= MAX_DELEGATE_DEPTH,
219 "delegate depth {} exceeds MAX_DELEGATE_DEPTH {}",
220 path.len(),
221 MAX_DELEGATE_DEPTH
222 );
223 debug_assert!(
224 path.iter().all(|&i| i <= u8::MAX as usize),
225 "delegate index exceeds u8 range"
226 );
227 let mut delegate_buf = [0u8; MAX_DELEGATE_DEPTH];
228 for (i, &v) in path.iter().enumerate().take(MAX_DELEGATE_DEPTH) {
229 delegate_buf[i] = v as u8;
230 }
231 Self {
232 delegate_buf,
233 delegate_len: path.len().min(MAX_DELEGATE_DEPTH) as u8,
234 ..Self::root(entry)
235 }
236 }
237
238 #[inline]
239 fn entry(&self) -> usize {
240 self.entry as usize
241 }
242
243 #[inline]
244 fn delegates(&self) -> &[u8] {
245 &self.delegate_buf[..self.delegate_len as usize]
246 }
247}
248
249/// Runtime state tracked for every [`ModifierNode`].
250///
251/// This type is part of the internal node system API and should not be directly
252/// constructed or manipulated by external code. Modifier nodes automatically receive
253/// and manage their NodeState through the modifier chain infrastructure.
254#[derive(Debug)]
255pub struct NodeState {
256 capabilities: Cell<NodeCapabilities>,
257 attached: Cell<bool>,
258}
259
260impl Default for NodeState {
261 fn default() -> Self {
262 Self::new()
263 }
264}
265
266impl NodeState {
267 /// Creates the state of a node that is not attached to a chain yet and has no capabilities.
268 pub const fn new() -> Self {
269 Self {
270 capabilities: Cell::new(NodeCapabilities::empty()),
271 attached: Cell::new(false),
272 }
273 }
274
275 /// Records the capabilities of the node that owns this state. The chain calls it when it adds
276 /// or updates the node.
277 pub fn set_capabilities(&self, capabilities: NodeCapabilities) {
278 self.capabilities.set(capabilities);
279 }
280
281 /// The capabilities of the node that owns this state.
282 #[inline]
283 pub fn capabilities(&self) -> NodeCapabilities {
284 self.capabilities.get()
285 }
286
287 // The chain marks a node attached before `on_attach` and detached after `on_detach`.
288 pub(crate) fn set_attached(&self, attached: bool) {
289 self.attached.set(attached);
290 }
291
292 /// Whether the node is attached to a chain. It is true after `on_attach` ran and before
293 /// `on_detach` runs.
294 pub fn is_attached(&self) -> bool {
295 self.attached.get()
296 }
297}
298
299/// Provides traversal helpers that mirror Jetpack Compose's [`DelegatableNode`] contract.
300pub trait DelegatableNode {
301 /// The runtime state of this node. Return a `NodeState` field of the node; the chain uses it to
302 /// track the node's capabilities and attachment.
303 fn node_state(&self) -> &NodeState;
304}
305
306/// Core trait implemented by modifier nodes.
307///
308/// # Capability-Driven Architecture
309///
310/// This trait follows Jetpack Compose's `Modifier.Node` pattern where nodes declare
311/// their capabilities via [`NodeCapabilities`] and implement specialized traits
312/// ([`DrawModifierNode`], [`PointerInputNode`], [`SemanticsNode`], [`FocusNode`], etc.)
313/// to participate in specific pipeline stages.
314///
315/// ## How to Implement a Modifier Node
316///
317/// 1. **Declare capabilities** in your [`ModifierNodeElement::capabilities()`] implementation
318/// 2. **Implement specialized traits** for the capabilities you declared
319/// 3. **Use helper macros** to reduce boilerplate (recommended)
320///
321/// ### Example: Draw Node
322///
323/// ```text
324/// use cranpose_foundation::*;
325///
326/// struct MyDrawNode {
327/// state: NodeState,
328/// color: Color,
329/// }
330///
331/// impl DelegatableNode for MyDrawNode {
332/// fn node_state(&self) -> &NodeState {
333/// &self.state
334/// }
335/// }
336///
337/// impl ModifierNode for MyDrawNode {
338/// // Use the helper macro instead of manual as_* implementations
339/// impl_modifier_node!(draw);
340/// }
341///
342/// impl DrawModifierNode for MyDrawNode {
343/// fn draw(&mut self, _context: &mut dyn ModifierNodeContext, draw_scope: &mut dyn DrawScope) {
344/// // Drawing logic here
345/// }
346/// }
347/// ```
348///
349/// ### Example: Multi-Capability Node
350///
351/// ```text
352/// impl ModifierNode for MyComplexNode {
353/// // This node participates in draw, pointer input, and semantics
354/// impl_modifier_node!(draw, pointer_input, semantics);
355/// }
356/// ```
357///
358/// ## Lifecycle Callbacks
359///
360/// Nodes receive lifecycle callbacks when they attach to or detach from a
361/// composition and may optionally react to resets triggered by the runtime
362/// (for example, when reusing nodes across modifier list changes).
363pub trait ModifierNode: Any + DelegatableNode {
364 /// Called once when the node joins an attached chain. `context` receives the invalidation
365 /// requests of the node.
366 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {}
367
368 /// Called when the node leaves the chain or when the chain detaches. Release here whatever
369 /// `on_attach` acquired.
370 fn on_detach(&mut self) {}
371
372 /// Called when the chain is reset, as Compose's `onReset`. Clear state that belongs to an
373 /// earlier use of the node.
374 fn on_reset(&mut self) {}
375
376 /// Returns this node as a draw modifier if it implements the trait.
377 fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
378 None
379 }
380
381 /// Returns this node as a mutable draw modifier if it implements the trait.
382 fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
383 None
384 }
385
386 /// Returns this node as a pointer-input modifier if it implements the trait.
387 fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
388 None
389 }
390
391 /// Returns this node as a mutable pointer-input modifier if it implements the trait.
392 fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
393 None
394 }
395
396 /// Returns this node as a semantics modifier if it implements the trait.
397 fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
398 None
399 }
400
401 /// Returns this node as a mutable semantics modifier if it implements the trait.
402 fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
403 None
404 }
405
406 /// Returns this node as a focus modifier if it implements the trait.
407 fn as_focus_node(&self) -> Option<&dyn FocusNode> {
408 None
409 }
410
411 /// Returns this node as a mutable focus modifier if it implements the trait.
412 fn as_focus_node_mut(&mut self) -> Option<&mut dyn FocusNode> {
413 None
414 }
415
416 /// Returns this node as a layout modifier if it implements the trait.
417 fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
418 None
419 }
420
421 /// Returns this node as a mutable layout modifier if it implements the trait.
422 fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
423 None
424 }
425
426 /// Visits every delegate node owned by this modifier.
427 fn for_each_delegate<'b>(&'b self, _visitor: &mut dyn FnMut(&'b dyn ModifierNode)) {}
428
429 /// Visits every delegate node mutably.
430 fn for_each_delegate_mut<'b>(&'b mut self, _visitor: &mut dyn FnMut(&'b mut dyn ModifierNode)) {
431 }
432}
433
434/// Marker trait for layout-specific modifier nodes.
435///
436/// Layout nodes participate in the measure and layout passes of the render
437/// pipeline. They can intercept and modify the measurement and placement of
438/// their wrapped content.
439pub trait LayoutModifierNode: ModifierNode {
440 /// Measures the wrapped content and returns both the size this modifier
441 /// occupies and where the wrapped content should be placed.
442 ///
443 /// The node receives a measurable representing the wrapped content and
444 /// the incoming constraints from the parent.
445 ///
446 /// Returns a `LayoutModifierMeasureResult` containing:
447 /// - `size`: The final size this modifier will occupy
448 /// - `placement_offset_x/y`: Where to place the wrapped content relative
449 /// to this modifier's top-left corner
450 ///
451 /// For example, a padding modifier would:
452 /// - Measure child with deflated constraints
453 /// - Return size = child size + padding
454 /// - Return placement offset = (padding.left, padding.top)
455 ///
456 /// The default implementation delegates to the wrapped content without
457 /// modification (size = child size, offset = 0).
458 ///
459 /// NOTE: This takes `&self` not `&mut self` to match Jetpack Compose semantics.
460 /// Nodes that need mutable state should use interior mutability (Cell/RefCell).
461 fn measure(
462 &self,
463 _context: &mut dyn ModifierNodeContext,
464 measurable: &dyn Measurable,
465 constraints: Constraints,
466 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
467 let placeable = measurable.measure(constraints);
468 cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size {
469 width: placeable.width(),
470 height: placeable.height(),
471 })
472 }
473
474 /// The incoming constraints the last measure of this node, which gave
475 /// `size` under `constraints`, holds for: every constraints inside give
476 /// the same result. `wrapped` is what the content this node wraps
477 /// measured. `None`, the default, holds for `constraints` alone; a node
478 /// that tells must give the range its own measure keeps its result and
479 /// hands its content constraints that `wrapped` holds for.
480 fn measure_hold(
481 &self,
482 _density: f32,
483 _constraints: Constraints,
484 _size: Size,
485 _wrapped: cranpose_ui_layout::WrappedHold,
486 ) -> Option<cranpose_ui_layout::ConstraintsHold> {
487 None
488 }
489
490 /// Returns the minimum intrinsic width of this modifier node. The default is
491 /// the wrapped content's, for a node that keeps the content's size.
492 fn min_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
493 measurable.min_intrinsic_width(height)
494 }
495
496 /// Returns the maximum intrinsic width of this modifier node. The default is
497 /// the wrapped content's, for a node that keeps the content's size.
498 fn max_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
499 measurable.max_intrinsic_width(height)
500 }
501
502 /// Returns the minimum intrinsic height of this modifier node. The default is
503 /// the wrapped content's, for a node that keeps the content's size.
504 fn min_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
505 measurable.min_intrinsic_height(width)
506 }
507
508 /// Returns the maximum intrinsic height of this modifier node. The default is
509 /// the wrapped content's, for a node that keeps the content's size.
510 fn max_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
511 measurable.max_intrinsic_height(width)
512 }
513}
514
515/// Marker trait for draw-specific modifier nodes.
516///
517/// Draw nodes participate in the draw pass of the render pipeline. A node
518/// draws through the closures it hands out, which the renderer runs at render
519/// time with a live scope of the node's size; slice collection only gathers
520/// them.
521pub trait DrawModifierNode: ModifierNode {
522 /// Creates a closure for deferred drawing that will be evaluated at render time.
523 ///
524 /// This is the preferred method for nodes with dynamic content like:
525 /// - Blinking cursors (visibility changes over time)
526 /// - Live selection during drag (selection changes during mouse move)
527 ///
528 /// The returned closure captures the node's internal state (via Rc) and
529 /// evaluates at render time, not at slice collection time.
530 ///
531 /// Returns None by default. Override for nodes needing deferred draw.
532 fn create_draw_closure(&self) -> Option<NodeDrawClosure> {
533 None
534 }
535
536 /// Like [`create_draw_closure`](Self::create_draw_closure), but the
537 /// primitives render BEHIND the node's content — e.g. a text field's
538 /// selection highlight, which must sit under the glyphs (a highlight
539 /// drawn over them tints the text with its translucent fill).
540 fn create_behind_draw_closure(&self) -> Option<NodeDrawClosure> {
541 None
542 }
543}
544
545/// A deferred draw closure returned by
546/// [`DrawModifierNode::create_draw_closure`]: it records into a scope the
547/// renderer provides at render time, so the recording's identity stays with
548/// the consumer rather than with a closure-owned vector.
549pub type NodeDrawClosure = Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>;
550
551/// Marker trait for pointer input modifier nodes.
552///
553/// Pointer input nodes participate in hit-testing and pointer event
554/// dispatch. They can intercept pointer events and handle them before
555/// they reach the wrapped content.
556pub trait PointerInputNode: ModifierNode {
557 /// Called when a pointer event occurs within the bounds of this node.
558 /// Returns true if the event was consumed and should not propagate further.
559 fn on_pointer_event(
560 &mut self,
561 _context: &mut dyn ModifierNodeContext,
562 _event: &PointerEvent,
563 ) -> bool {
564 false
565 }
566
567 /// Returns true if this node should participate in hit-testing for the
568 /// given pointer position.
569 fn hit_test(&self, _x: f32, _y: f32) -> bool {
570 true
571 }
572
573 /// Returns an event handler closure if the node wants to participate in pointer dispatch.
574 fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
575 None
576 }
577
578 /// Returns the cell this node reads its owning layout node's resolved size
579 /// from, if it exposes a size to its handler (Compose's
580 /// `PointerInputScope.size`).
581 ///
582 /// The cell is shared with the node, so the layout pass publishes the size
583 /// into it once per pass and every read — including reads that happen
584 /// before any pointer event arrives — observes the current size. The size
585 /// is the node's layout box in the same local coordinate space the
586 /// dispatched [`PointerEvent`] positions use, so
587 /// `event.local_position / size` is a well-defined fraction of the node.
588 ///
589 /// Returns `None` for pointer nodes with no size-bearing scope.
590 fn layout_size_sink(&self) -> Option<Rc<Cell<Size>>> {
591 None
592 }
593}
594
595/// Marker trait for semantics modifier nodes.
596///
597/// Semantics nodes participate in the semantics tree construction. They can
598/// add or modify semantic properties of their wrapped content for
599/// accessibility and testing purposes.
600pub trait SemanticsNode: ModifierNode {
601 /// Merges semantic properties into the provided configuration.
602 fn merge_semantics(&self, _config: &mut SemanticsConfiguration) {}
603
604 /// Whether this node makes its subtree modal or hides it, and whether
605 /// what it merges can change without its semantics being invalidated.
606 /// The default merges into a fresh configuration, reads the two flags and
607 /// counts the node as reading live state; a node that can declare
608 /// neither flag and reports only what its updates bring overrides it to
609 /// skip that work.
610 fn reach(&self) -> SemanticsReach {
611 SemanticsReach::merged_by(self, true)
612 }
613}
614
615/// The semantics flags that decide how a node's semantics reach the tree:
616/// which part of a window is live ([`SemanticsConfiguration::is_modal`] and
617/// [`SemanticsConfiguration::hidden`]), and whether a tree update may keep
618/// what the node reported last.
619#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
620pub struct SemanticsReach {
621 /// The subtree takes over the screen.
622 pub is_modal: bool,
623 /// The subtree is skipped by readers.
624 pub hidden: bool,
625 /// What the node merges can change without its semantics being
626 /// invalidated, as a `.semantics { }` recorder reading live state can,
627 /// so every tree update merges it again.
628 pub merges_live_state: bool,
629}
630
631impl SemanticsReach {
632 /// The modal and hidden flags `node` merges into a fresh configuration,
633 /// with whether what it merges can change without an invalidation.
634 pub fn merged_by(node: &(impl SemanticsNode + ?Sized), merges_live_state: bool) -> Self {
635 let mut config = SemanticsConfiguration::default();
636 node.merge_semantics(&mut config);
637 Self {
638 is_modal: config.is_modal,
639 hidden: config.hidden,
640 merges_live_state,
641 }
642 }
643
644 /// Every flag of `self` and `other`.
645 pub fn union(self, other: Self) -> Self {
646 Self {
647 is_modal: self.is_modal || other.is_modal,
648 hidden: self.hidden || other.hidden,
649 merges_live_state: self.merges_live_state || other.merges_live_state,
650 }
651 }
652}
653
654/// Whether a check box or switch is on, off or partly on: Compose's
655/// `ToggleableState`. A check box over a list whose items are partly checked
656/// is `Indeterminate`.
657#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
658pub enum ToggleableState {
659 /// The control is on or checked.
660 On,
661 /// The control is off or unchecked.
662 Off,
663 /// The control is partly on, as a check box over items of which some are checked.
664 Indeterminate,
665}
666
667impl From<bool> for ToggleableState {
668 fn from(on: bool) -> Self {
669 if on { Self::On } else { Self::Off }
670 }
671}
672
673/// Focus state of a focus target node.
674///
675/// This mirrors Jetpack Compose's FocusState enum which tracks whether
676/// a node is focused, has a focused child, or is inactive.
677#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
678pub enum FocusState {
679 /// The focusable component is currently active (i.e. it receives key events).
680 Active,
681 /// One of the descendants of the focusable component is Active.
682 ActiveParent,
683 /// The focusable component is currently active (has focus), and is in a state
684 /// where it does not want to give up focus. (Eg. a text field with an invalid
685 /// phone number).
686 Captured,
687 /// The focusable component does not receive any key events. (ie it is not active,
688 /// nor are any of its descendants active).
689 #[default]
690 Inactive,
691}
692
693impl FocusState {
694 /// Returns whether the component is focused (Active or Captured).
695 pub fn is_focused(self) -> bool {
696 matches!(self, Self::Active | Self::Captured)
697 }
698
699 /// Returns whether this node or any descendant has focus.
700 pub fn has_focus(self) -> bool {
701 matches!(self, Self::Active | Self::ActiveParent | Self::Captured)
702 }
703
704 /// Returns whether focus is captured.
705 pub fn is_captured(self) -> bool {
706 matches!(self, Self::Captured)
707 }
708}
709
710/// Marker trait for focus modifier nodes.
711///
712/// Focus nodes participate in focus management. They can request focus,
713/// track focus state, and participate in focus traversal.
714pub trait FocusNode: ModifierNode {
715 /// Returns the current focus state of this node.
716 fn focus_state(&self) -> FocusState;
717
718 /// Called when focus state changes for this node.
719 fn on_focus_changed(&mut self, _context: &mut dyn ModifierNodeContext, _state: FocusState) {}
720}
721
722/// What kind of control a node is, as screen readers announce it.
723///
724/// This is Compose's `SemanticsProperties.Role` (`Modifier.semantics { role =
725/// Role.RadioButton }`), not a description of where the node sits in the tree.
726/// A screen reader turns it into the trailing noun it speaks after the label —
727/// TalkBack says "CAMPAIGN, radio button, selected" — and into the on/off
728/// wording it uses for a switch. Compose keeps this separate from the node's
729/// structural kind for the same reason Cranpose does: a `Row` that happens to
730/// be clickable is still a row, and a drawn ring segment that is a radio button
731/// has no layout node of its own at all.
732#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
733pub enum SemanticsWidgetRole {
734 /// A control that acts when pressed. Compose's `Role.Button`.
735 Button,
736 /// A control that is checked or unchecked. Compose's `Role.Checkbox`.
737 Checkbox,
738 /// A control that is on or off. Compose's `Role.Switch`.
739 Switch,
740 /// One choice of a set in which only one choice is selected. Compose's `Role.RadioButton`.
741 RadioButton,
742 /// One page selector of a tab bar. Compose's `Role.Tab`.
743 Tab,
744 /// A picture. Compose's `Role.Image`.
745 Image,
746 /// A control that opens a list of choices and holds the one that is
747 /// picked. Compose's `Role.DropdownList`.
748 DropdownList,
749 /// A control that holds one value out of an ordered set and steps through
750 /// them. Compose's `Role.ValuePicker`.
751 ValuePicker,
752 /// Compose's `heading()`, which is a property rather than a `Role`, but
753 /// reaches the platform through the same field on every backend Cranpose
754 /// targets (`AccessibilityNodeInfo.setHeading`, `Role::Heading`,
755 /// `<h*>`/`UIAccessibilityTraitHeader`).
756 Header,
757 /// A modal surface that takes over the screen until it is dismissed.
758 /// Screen readers announce it and confine their traversal to it, which is
759 /// the accessible half of what makes a dialog modal.
760 Dialog,
761 /// Text that takes the user somewhere else when pressed. Compose has no
762 /// such `Role`; SwiftUI's `.isLink`, ARIA's `link`.
763 Link,
764 /// A field that narrows what is on the screen as the user types. ARIA's
765 /// `searchbox`, VoiceOver's search field trait.
766 SearchField,
767 /// A control that shows how far work has come and takes no input. ARIA's
768 /// `progressbar`.
769 ProgressBar,
770 /// A button that stays pressed or released. ARIA's `button` with
771 /// `aria-pressed`.
772 ToggleButton,
773 /// A message a reader speaks as soon as it shows, with no move to it.
774 /// ARIA's `alert`.
775 Alert,
776 /// A row of controls that act on the content beside them. ARIA's
777 /// `toolbar`.
778 Toolbar,
779 /// A list of commands that opens on a press. ARIA's `menu`.
780 Menu,
781 /// One command inside a menu. ARIA's `menuitem`.
782 MenuItem,
783 /// The row that holds the tabs of a screen. ARIA's `tablist`, VoiceOver's
784 /// tab bar trait.
785 TabBar,
786 /// A container whose rows a reader counts and walks into. ARIA's `list`.
787 List,
788 /// One row of a list. ARIA's `listitem`.
789 ListItem,
790 /// A set of mutually exclusive radio choices. ARIA's `radiogroup`.
791 RadioGroup,
792}
793
794/// The value a control holds inside a range, for a slider, a dial or a
795/// progress bar.
796///
797/// This is Compose's `ProgressBarRangeInfo` (`Modifier.progressSemantics(value,
798/// range, steps)`). A control without it reads as plain text: a screen reader
799/// user hears "47 percent" and has no way to change it, because nothing tells
800/// the platform the control is adjustable.
801#[derive(Clone, Copy, Debug, PartialEq)]
802pub struct ProgressBarRangeInfo {
803 /// The current value, between `start` and `end`.
804 pub current: f32,
805 /// The value at the low end of the range.
806 pub start: f32,
807 /// The value at the high end of the range.
808 pub end: f32,
809 /// How many stops sit between `start` and `end`, as Compose counts them.
810 /// Zero means the value moves without stops.
811 pub steps: u32,
812}
813
814impl ProgressBarRangeInfo {
815 /// Creates range info for `current` between `start` and `end`, with `steps` stops between the
816 /// two ends.
817 pub fn new(current: f32, start: f32, end: f32, steps: u32) -> Self {
818 Self {
819 current,
820 start,
821 end,
822 steps,
823 }
824 }
825
826 /// Where the value sits between the two ends, from 0 to 1.
827 pub fn fraction(&self) -> f32 {
828 let span = self.end - self.start;
829 if span.abs() < f32::EPSILON {
830 return 0.0;
831 }
832 ((self.current - self.start) / span).clamp(0.0, 1.0)
833 }
834
835 /// How far one stop moves the value. With no stops, one tenth of the
836 /// range, which is what a screen reader's swipe up and down expects.
837 pub fn step(&self) -> f32 {
838 let span = self.end - self.start;
839 if self.steps == 0 {
840 span / 10.0
841 } else {
842 span / (self.steps as f32 + 1.0)
843 }
844 }
845}
846
847/// How many rows and columns a list holds, so a screen reader can say
848/// "list, 12 items" as its cursor enters. Compose's `CollectionInfo`.
849#[derive(Clone, Copy, Debug, PartialEq, Eq)]
850pub struct CollectionInfo {
851 /// The number of rows the collection holds. A plain list reports its item count here.
852 pub rows: usize,
853 /// The number of columns the collection holds. A plain list reports 1.
854 pub columns: usize,
855}
856
857/// What a container does when a screen reader pages it, e.g. TalkBack's
858/// scroll forward action or an accesskit scroll down. The two deltas are in
859/// layout pixels; the answer says whether anything moved.
860///
861/// This is Compose's `SemanticsActions.ScrollBy`.
862#[derive(Clone)]
863pub struct SemanticsScrollBy {
864 handler: Rc<dyn Fn(f32, f32) -> bool>,
865}
866
867impl SemanticsScrollBy {
868 /// Wraps `handler`, which receives the horizontal and the vertical distance in layout pixels
869 /// and returns whether the container moved.
870 pub fn new(handler: impl Fn(f32, f32) -> bool + 'static) -> Self {
871 Self {
872 handler: Rc::new(handler),
873 }
874 }
875
876 /// Runs the handler with the distances `dx` and `dy`, in layout pixels. Returns whether the
877 /// container moved.
878 pub fn invoke(&self, dx: f32, dy: f32) -> bool {
879 (self.handler)(dx, dy)
880 }
881}
882
883impl fmt::Debug for SemanticsScrollBy {
884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 f.debug_struct("SemanticsScrollBy").finish_non_exhaustive()
886 }
887}
888
889impl PartialEq for SemanticsScrollBy {
890 fn eq(&self, _other: &Self) -> bool {
891 true
892 }
893}
894
895impl Eq for SemanticsScrollBy {}
896
897/// What a list does when a screen reader asks for the row at an index, e.g. a
898/// TalkBack scroll-to-position action.
899///
900/// This is Compose's `SemanticsActions.ScrollToIndex`. The index counts rows
901/// from zero, and the answer says whether the list moved.
902#[derive(Clone)]
903pub struct SemanticsScrollToIndex {
904 handler: Rc<dyn Fn(usize) -> bool>,
905}
906
907impl SemanticsScrollToIndex {
908 /// Wraps `handler`, which receives a row index counted from zero and returns whether the list
909 /// moved.
910 pub fn new(handler: impl Fn(usize) -> bool + 'static) -> Self {
911 Self {
912 handler: Rc::new(handler),
913 }
914 }
915
916 /// Runs the handler for the row at `index`, counted from zero. Returns whether the list moved.
917 pub fn invoke(&self, index: usize) -> bool {
918 (self.handler)(index)
919 }
920}
921
922impl fmt::Debug for SemanticsScrollToIndex {
923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 f.debug_struct("SemanticsScrollToIndex")
925 .finish_non_exhaustive()
926 }
927}
928
929impl PartialEq for SemanticsScrollToIndex {
930 fn eq(&self, _other: &Self) -> bool {
931 true
932 }
933}
934
935impl Eq for SemanticsScrollToIndex {}
936
937/// What a control does when a screen reader moves its value, e.g. a VoiceOver
938/// swipe up or a TalkBack set-progress action.
939///
940/// This is Compose's `SemanticsActions.SetProgress`. The value comes in the
941/// control's own range, and the answer says whether the control took it.
942#[derive(Clone)]
943pub struct SemanticsSetProgress {
944 handler: Rc<dyn Fn(f32) -> bool>,
945}
946
947impl SemanticsSetProgress {
948 /// Wraps `handler`, which receives a value in the range of the control and returns whether the
949 /// control took it.
950 pub fn new(handler: impl Fn(f32) -> bool + 'static) -> Self {
951 Self {
952 handler: Rc::new(handler),
953 }
954 }
955
956 /// Runs the handler with `value`, in the range of the control. Returns whether the control took
957 /// it.
958 pub fn invoke(&self, value: f32) -> bool {
959 (self.handler)(value)
960 }
961}
962
963impl fmt::Debug for SemanticsSetProgress {
964 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
965 f.debug_struct("SemanticsSetProgress")
966 .finish_non_exhaustive()
967 }
968}
969
970/// What a text field does when a screen reader or a voice tool hands it new
971/// text. This is Compose's `SemanticsActions.SetText`; the answer says
972/// whether the field took the text.
973#[derive(Clone)]
974pub struct SemanticsSetText(Rc<dyn Fn(&str) -> bool>);
975
976impl SemanticsSetText {
977 /// Wraps `handler`, which receives the new text and returns whether the field took it.
978 pub fn new(handler: impl Fn(&str) -> bool + 'static) -> Self {
979 Self(Rc::new(handler))
980 }
981
982 /// Runs the handler with `text`. Returns whether the field took it.
983 pub fn invoke(&self, text: &str) -> bool {
984 (self.0)(text)
985 }
986}
987
988impl fmt::Debug for SemanticsSetText {
989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 f.write_str("SemanticsSetText")
991 }
992}
993
994/// What a text field does when a screen reader moves its caret or picks a
995/// stretch of its text: the two ends of the new selection, as byte offsets
996/// into the field's text, the anchor first and the end that moves second. Equal
997/// ends are a caret. This is Compose's `SemanticsActions.SetSelection`; the
998/// answer says whether the field took the selection.
999#[derive(Clone)]
1000pub struct SemanticsSetSelection(Rc<dyn Fn(usize, usize) -> bool>);
1001
1002impl SemanticsSetSelection {
1003 /// Wraps `handler`, which receives the anchor and the focus offsets of the selection and
1004 /// returns whether the field took it.
1005 pub fn new(handler: impl Fn(usize, usize) -> bool + 'static) -> Self {
1006 Self(Rc::new(handler))
1007 }
1008
1009 /// Runs the handler with the selection from byte offset `anchor` to byte offset `focus`.
1010 /// Returns whether the field took it.
1011 pub fn invoke(&self, anchor: usize, focus: usize) -> bool {
1012 (self.0)(anchor, focus)
1013 }
1014}
1015
1016impl fmt::Debug for SemanticsSetSelection {
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 f.write_str("SemanticsSetSelection")
1019 }
1020}
1021
1022/// What a control does when a screen reader asks it to open or to close.
1023/// Compose's `expand` and `collapse` actions.
1024#[derive(Clone)]
1025pub struct SemanticsExpand(Rc<dyn Fn() -> bool>);
1026
1027impl SemanticsExpand {
1028 /// Wraps `handler`, which returns whether the control opened or closed.
1029 pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
1030 Self(Rc::new(handler))
1031 }
1032
1033 /// Runs the handler. Returns whether the control opened or closed.
1034 pub fn invoke(&self) -> bool {
1035 (self.0)()
1036 }
1037}
1038
1039impl fmt::Debug for SemanticsExpand {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041 f.write_str("SemanticsExpand")
1042 }
1043}
1044
1045/// What a control does when a screen reader asks for its long press. This is
1046/// Compose's `SemanticsActions.OnLongClick`; the answer says whether the
1047/// control took the ask.
1048#[derive(Clone)]
1049pub struct SemanticsLongClick(Rc<dyn Fn() -> bool>);
1050
1051impl SemanticsLongClick {
1052 /// Wraps `handler`, which returns whether the control took the long press.
1053 pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
1054 Self(Rc::new(handler))
1055 }
1056
1057 /// Runs the handler. Returns whether the control took the long press.
1058 pub fn invoke(&self) -> bool {
1059 (self.0)()
1060 }
1061}
1062
1063impl fmt::Debug for SemanticsLongClick {
1064 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 f.write_str("SemanticsLongClick")
1066 }
1067}
1068
1069impl PartialEq for SemanticsLongClick {
1070 fn eq(&self, _other: &Self) -> bool {
1071 true
1072 }
1073}
1074
1075impl PartialEq for SemanticsExpand {
1076 fn eq(&self, _other: &Self) -> bool {
1077 true
1078 }
1079}
1080
1081/// What a control does when a screen reader asks to send it away: a row a
1082/// sighted person swipes off, a sheet a sighted person taps outside of.
1083/// Compose's `dismiss` action.
1084#[derive(Clone)]
1085pub struct SemanticsDismiss(Rc<dyn Fn() -> bool>);
1086
1087impl SemanticsDismiss {
1088 /// Wraps `handler`, which returns whether the control was dismissed.
1089 pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
1090 Self(Rc::new(handler))
1091 }
1092
1093 /// Runs the handler. Returns whether the control was dismissed.
1094 pub fn invoke(&self) -> bool {
1095 (self.0)()
1096 }
1097}
1098
1099impl fmt::Debug for SemanticsDismiss {
1100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1101 f.write_str("SemanticsDismiss")
1102 }
1103}
1104
1105impl PartialEq for SemanticsDismiss {
1106 fn eq(&self, _other: &Self) -> bool {
1107 true
1108 }
1109}
1110
1111impl PartialEq for SemanticsSetText {
1112 fn eq(&self, _other: &Self) -> bool {
1113 true
1114 }
1115}
1116
1117impl PartialEq for SemanticsSetSelection {
1118 fn eq(&self, _other: &Self) -> bool {
1119 true
1120 }
1121}
1122
1123/// What a control does when a VoiceOver user makes the magic tap, the two
1124/// finger double tap that starts or stops the main action of a screen. On
1125/// the other platforms the action is listed by its label among the control's
1126/// actions. SwiftUI's `accessibilityAction(.magicTap)`; the answer says
1127/// whether the control took the tap.
1128#[derive(Clone)]
1129pub struct SemanticsMagicTap(Rc<dyn Fn() -> bool>);
1130
1131impl SemanticsMagicTap {
1132 /// Wraps `handler`, which returns whether the control took the magic tap.
1133 pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
1134 Self(Rc::new(handler))
1135 }
1136
1137 /// Runs the handler. Returns whether the control took the magic tap.
1138 pub fn invoke(&self) -> bool {
1139 (self.0)()
1140 }
1141}
1142
1143impl fmt::Debug for SemanticsMagicTap {
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145 f.write_str("SemanticsMagicTap")
1146 }
1147}
1148
1149impl PartialEq for SemanticsMagicTap {
1150 fn eq(&self, _other: &Self) -> bool {
1151 true
1152 }
1153}
1154
1155impl PartialEq for SemanticsSetProgress {
1156 fn eq(&self, _other: &Self) -> bool {
1157 true
1158 }
1159}
1160
1161impl Eq for SemanticsSetProgress {}
1162
1163/// How urgently a screen reader reads a node whose text changed on its own.
1164///
1165/// This is Compose's `LiveRegionMode` (`Modifier.semantics { liveRegion =
1166/// LiveRegionMode.Polite }`). A node without it stays silent until the reader
1167/// lands on it, which is wrong for a timer, a countdown, a status line, or an
1168/// error that appears next to a text field: a blind user hears nothing.
1169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1170pub enum LiveRegionMode {
1171 /// Read the new text once the reader finishes what it says now.
1172 Polite,
1173 /// Cut off what the reader says now and read the new text at once. For
1174 /// text a user must hear immediately, such as an error that stops them.
1175 Assertive,
1176}
1177
1178/// A named accessibility operation, e.g. Compose's
1179/// `customActions = listOf(CustomAccessibilityAction("Pause") { … })`.
1180///
1181/// TalkBack surfaces these through its actions menu rather than by activating
1182/// the node, which is the only way to reach a command that has no on-screen
1183/// control — pausing a game whose whole surface is one tap-to-launch target.
1184#[derive(Clone)]
1185pub struct SemanticsCustomAction {
1186 /// What the screen reader reads out in its actions menu.
1187 pub label: String,
1188 handler: Rc<dyn Fn()>,
1189}
1190
1191impl SemanticsCustomAction {
1192 /// Creates an action that a screen reader lists as `label` and that runs `handler` when chosen.
1193 pub fn new(label: impl Into<String>, handler: impl Fn() + 'static) -> Self {
1194 Self {
1195 label: label.into(),
1196 handler: Rc::new(handler),
1197 }
1198 }
1199
1200 /// Runs the handler of the action.
1201 pub fn invoke(&self) {
1202 (self.handler)();
1203 }
1204}
1205
1206impl fmt::Debug for SemanticsCustomAction {
1207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1208 f.debug_struct("SemanticsCustomAction")
1209 .field("label", &self.label)
1210 .finish_non_exhaustive()
1211 }
1212}
1213
1214impl PartialEq for SemanticsCustomAction {
1215 fn eq(&self, other: &Self) -> bool {
1216 self.label == other.label
1217 }
1218}
1219
1220impl Eq for SemanticsCustomAction {}
1221
1222/// A semantics node for content that is *drawn* rather than laid out.
1223///
1224/// An immediate-mode surface — one `Canvas` that paints a whole screen — has
1225/// exactly one layout node, so the semantics tree built from layout has exactly
1226/// one node to offer a screen reader. This is the escape hatch: the drawing
1227/// code already knows where it put every control, so it publishes those
1228/// rectangles as semantics directly. Android's own answer for a canvas-drawn
1229/// `View` is the same shape (`ExploreByTouchHelper` feeding virtual view ids
1230/// into an `AccessibilityNodeProvider`), and Cranpose's Android bridge is
1231/// already an `AccessibilityNodeProvider`, so these land as first-class
1232/// virtual views next to the ones layout produces.
1233///
1234/// `bounds` is in the publishing node's own coordinates (logical px, origin at
1235/// that node's top-left), because that is what a draw scope works in.
1236#[derive(Clone, Debug, PartialEq)]
1237pub struct CanvasSemanticsNode {
1238 /// Identity that must survive a redraw.
1239 ///
1240 /// A screen reader parks its cursor on a virtual view id; if the id for
1241 /// "the Haptics switch" changes when the list scrolls, the cursor jumps.
1242 /// Derive this from what the control *is* (a row index, an enum
1243 /// discriminant), never from where it currently sits.
1244 pub key: u64,
1245 /// Where the control was drawn, relative to the publishing node.
1246 pub bounds: cranpose_ui_graphics::Rect,
1247 /// What the screen reader reads for the control.
1248 pub label: String,
1249 /// What kind of control it is, as the screen reader announces it.
1250 pub role: Option<SemanticsWidgetRole>,
1251 /// Compose's `stateDescription` — what the control currently reads as
1252 /// ("CAMPAIGN", "3 of 18 gold"), spoken after the label and re-spoken on
1253 /// its own when only the state changed.
1254 pub state_description: Option<String>,
1255 /// Compose's `onClick(label = …)`. TalkBack reads it as "double tap to
1256 /// `<label>`", so it is a verb phrase, not a repeat of the label.
1257 pub on_click_label: Option<String>,
1258 /// Whether the control can be activated.
1259 pub clickable: bool,
1260 /// Compose's `selected`, for `Role.RadioButton`/`Role.Tab`.
1261 pub selected: Option<bool>,
1262 /// Compose's `toggleableState`, for `Role.Switch`/`Role.Checkbox`.
1263 pub toggled: Option<ToggleableState>,
1264 /// Whether the control accepts input. A disabled control is announced as such.
1265 pub enabled: bool,
1266 /// Named actions that the screen reader lists in its actions menu for the control.
1267 pub custom_actions: Vec<SemanticsCustomAction>,
1268}
1269
1270impl Default for CanvasSemanticsNode {
1271 fn default() -> Self {
1272 Self {
1273 key: 0,
1274 bounds: cranpose_ui_graphics::Rect {
1275 x: 0.0,
1276 y: 0.0,
1277 width: 0.0,
1278 height: 0.0,
1279 },
1280 label: String::new(),
1281 role: None,
1282 state_description: None,
1283 on_click_label: None,
1284 clickable: false,
1285 selected: None,
1286 toggled: None,
1287 enabled: true,
1288 custom_actions: Vec::new(),
1289 }
1290 }
1291}
1292
1293impl CanvasSemanticsNode {
1294 /// A clickable control drawn at `bounds`.
1295 pub fn control(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
1296 Self {
1297 key,
1298 bounds,
1299 label: label.into(),
1300 clickable: true,
1301 ..Self::default()
1302 }
1303 }
1304
1305 /// A drawn label that is read but not activated.
1306 pub fn text(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
1307 Self {
1308 key,
1309 bounds,
1310 label: label.into(),
1311 ..Self::default()
1312 }
1313 }
1314
1315 /// Returns the node with `role` set.
1316 pub fn with_role(mut self, role: SemanticsWidgetRole) -> Self {
1317 self.role = Some(role);
1318 self
1319 }
1320
1321 /// Returns the node with the state description `state` set. Compose's `stateDescription`.
1322 pub fn with_state_description(mut self, state: impl Into<String>) -> Self {
1323 self.state_description = Some(state.into());
1324 self
1325 }
1326
1327 /// Returns the node with `label` set as the verb phrase for activation. The node becomes
1328 /// clickable.
1329 pub fn with_click_label(mut self, label: impl Into<String>) -> Self {
1330 self.on_click_label = Some(label.into());
1331 self.clickable = true;
1332 self
1333 }
1334
1335 /// Returns the node with its selected state set to `selected`.
1336 pub fn with_selected(mut self, selected: bool) -> Self {
1337 self.selected = Some(selected);
1338 self
1339 }
1340
1341 /// Returns the node with its toggle state set to `toggled`. A `bool` converts to `On` or `Off`.
1342 pub fn with_toggled(mut self, toggled: impl Into<ToggleableState>) -> Self {
1343 self.toggled = Some(toggled.into());
1344 self
1345 }
1346
1347 /// Returns the node with `enabled` set. A disabled node is announced as such.
1348 pub fn with_enabled(mut self, enabled: bool) -> Self {
1349 self.enabled = enabled;
1350 self
1351 }
1352
1353 /// Returns the node with `action` added to its custom actions.
1354 pub fn with_custom_action(mut self, action: SemanticsCustomAction) -> Self {
1355 self.custom_actions.push(action);
1356 self
1357 }
1358}
1359
1360impl fmt::Debug for dyn ModifierNode {
1361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1362 f.debug_struct("ModifierNode").finish_non_exhaustive()
1363 }
1364}
1365
1366impl dyn ModifierNode {
1367 /// Returns the node as `Any`, for downcasting to its concrete type.
1368 pub fn as_any(&self) -> &dyn Any {
1369 self
1370 }
1371
1372 /// Returns the node as mutable `Any`, for downcasting to its concrete type.
1373 pub fn as_any_mut(&mut self) -> &mut dyn Any {
1374 self
1375 }
1376}
1377
1378/// The invalidations a node's modifier update requested: at most one per
1379/// [`InvalidationKind`], held inline so handing them over allocates nothing.
1380pub type ModifierInvalidations = smallvec::SmallVec<[ModifierInvalidation; 5]>;
1381
1382/// Records an invalidation request together with the capability mask that triggered it.
1383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1384pub struct ModifierInvalidation {
1385 kind: InvalidationKind,
1386 capabilities: NodeCapabilities,
1387}
1388
1389impl ModifierInvalidation {
1390 /// Creates a new modifier invalidation entry.
1391 pub const fn new(kind: InvalidationKind, capabilities: NodeCapabilities) -> Self {
1392 Self { kind, capabilities }
1393 }
1394
1395 /// Returns the invalidated pipeline kind.
1396 pub const fn kind(self) -> InvalidationKind {
1397 self.kind
1398 }
1399
1400 /// Returns the capability mask associated with the invalidation.
1401 pub const fn capabilities(self) -> NodeCapabilities {
1402 self.capabilities
1403 }
1404}
1405
1406#[cfg(test)]
1407#[path = "tests/modifier_tests.rs"]
1408mod tests;