Skip to main content

cranpose_ui/modifier/
mod.rs

1//! Modifier system for Cranpose
2//!
3//! This module now acts as a thin builder around modifier elements. Each
4//! [`Modifier`] stores the element chain required by the modifier node system
5//! together with inspector metadata while resolved state is computed directly
6//! from the modifier nodes.
7
8use std::{fmt, rc::Rc};
9
10use cranpose_core::ProvidedValue;
11use smallvec::SmallVec;
12
13mod alignment;
14mod background;
15mod blur;
16mod border;
17mod chain;
18mod clickable;
19mod coordinator_rect;
20mod drag_and_drop;
21mod draw_cache;
22mod element_match;
23mod fill;
24pub(crate) mod focus;
25mod focus_ring;
26mod graphics_layer;
27mod key_input;
28mod layout_data;
29mod local;
30mod long_press;
31mod minimum_interactive;
32mod offset;
33mod padding;
34mod pointer_icon;
35pub(crate) mod pointer_input;
36mod pointer_opaque;
37mod resolved_modifiers;
38mod rotary_input;
39mod scroll;
40mod selectable;
41mod semantics;
42mod shadow;
43mod size;
44mod slices;
45mod toggleable;
46mod weight;
47mod window_root;
48mod wrap_content;
49mod z_index;
50
51pub(crate) use chain::{
52    InPlaceReach, InPlaceUpdate, ModifierChainHandle, ModifierChainInspectorNode,
53    ModifierLocalsHandle, SharedParentData,
54};
55pub(crate) use coordinator_rect::CoordinatorRect;
56use cranpose_foundation::{
57    DynModifierElement, ModifierNodeElement, ProgressBarRangeInfo, SemanticsConfiguration,
58    modifier_element, plain_element,
59};
60pub use cranpose_foundation::{
61    PointerButton, PointerButtons, PointerEvent, PointerEventKind, PointerSource, RotaryScrollEvent,
62};
63pub use cranpose_ui_graphics::{
64    BlendMode, Brush, Color, CompositingStrategy, CornerRadii, DpOffset, EdgeInsets, GraphicsLayer,
65    LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader, Shadow, ShadowScope,
66    Size, TransformOrigin,
67};
68use cranpose_ui_layout::{Alignment, HorizontalAlignment, VerticalAlignment};
69pub use drag_and_drop::{
70    DragAndDropEvent, DragAndDropOutcome, DragAndDropPayload, DragAndDropPoint, DragAndDropSource,
71    DragAndDropSourceElement, DragAndDropSourceNode, DragAndDropState, DragAndDropTarget,
72    DragAndDropTargetElement, DragAndDropTargetNode,
73};
74pub(crate) use element_match::ElementMatch;
75#[cfg(test)]
76pub(crate) use focus::FocusRequesterElement;
77pub use focus::{FocusDirection, FocusRequestError, FocusRequester};
78pub use graphics_layer::GlassMaterial;
79pub use key_input::KeyEventRoute;
80pub(crate) use local::{
81    ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
82};
83use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
84pub use local::{ModifierLocalKey, ModifierLocalReadScope};
85pub use pointer_input::PointerInputScope;
86pub(crate) use resolved_modifiers::{DimensionConstraint, LayoutProperties, LayoutWeight};
87pub use resolved_modifiers::{ResolvedBackground, ResolvedModifiers};
88pub use rotary_input::RotaryInputModifierNode;
89#[cfg(feature = "test-helpers")]
90pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
91use semantics::SemanticsElement;
92pub use semantics::{SemanticsRequester, collect_semantics_from_modifier};
93pub(crate) use semantics::{
94    SemanticsRequesterElement, collect_semantics_from_chain, semantics_reach_of_chain,
95};
96pub(crate) use slices::SlicesSnapshot;
97pub use slices::{
98    ModifierNodeSlices, ModifierNodeSlicesDebugStats, SliceTextRef, collect_modifier_slices,
99    collect_slices_from_modifier,
100};
101pub use window_root::{
102    WindowRootDescriptor, WindowRootElement, WindowRootEntry, WindowRootNode, WindowRootRegistry,
103    WindowRootRoutingScratch, is_window_root, nearest_window_root, nearest_window_roots,
104    nearest_window_roots_into, window_roots, window_roots_revision,
105};
106pub use z_index::{z_index_in_use, z_index_modifier_in_use};
107
108pub(crate) use crate::draw::{DrawCacheBuilder, DrawCommand};
109use crate::modifier_nodes::ClipToBoundsElement;
110
111#[derive(Clone, Debug, Default)]
112pub(crate) struct InspectorInfo {
113    properties: Vec<InspectorProperty>,
114}
115
116impl InspectorInfo {
117    pub(crate) fn new() -> Self {
118        Self::default()
119    }
120
121    pub(crate) fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
122        self.properties.push(InspectorProperty {
123            name,
124            value: value.into(),
125        });
126    }
127
128    pub(crate) fn properties(&self) -> &[InspectorProperty] {
129        &self.properties
130    }
131
132    pub(crate) fn is_empty(&self) -> bool {
133        self.properties.is_empty()
134    }
135
136    pub(crate) fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
137        self.add_property(name, describe_dimension(constraint));
138    }
139
140    pub(crate) fn add_offset_components(
141        &mut self,
142        x_name: &'static str,
143        y_name: &'static str,
144        offset: Point,
145    ) {
146        self.add_property(x_name, offset.x.to_string());
147        self.add_property(y_name, offset.y.to_string());
148    }
149
150    pub(crate) fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
151    where
152        A: fmt::Debug,
153    {
154        self.add_property(name, format!("{alignment:?}"));
155    }
156}
157
158#[derive(Clone, Debug, PartialEq)]
159pub struct InspectorProperty {
160    pub name: &'static str,
161    pub value: String,
162}
163
164#[derive(Clone, Debug, PartialEq)]
165pub struct ModifierInspectorRecord {
166    pub name: &'static str,
167    pub properties: Vec<InspectorProperty>,
168}
169
170#[derive(Clone, Debug)]
171pub(crate) struct InspectorMetadata {
172    name: &'static str,
173    info: InspectorInfo,
174}
175
176impl InspectorMetadata {
177    pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
178    where
179        F: FnOnce(&mut InspectorInfo),
180    {
181        let mut info = InspectorInfo::new();
182        recorder(&mut info);
183        Self { name, info }
184    }
185
186    fn is_empty(&self) -> bool {
187        self.info.is_empty()
188    }
189
190    fn to_record(&self) -> ModifierInspectorRecord {
191        ModifierInspectorRecord {
192            name: self.name,
193            properties: self.info.properties().to_vec(),
194        }
195    }
196}
197
198fn describe_dimension(constraint: DimensionConstraint) -> String {
199    match constraint {
200        DimensionConstraint::Unspecified => "unspecified".to_string(),
201        DimensionConstraint::Points(value) => value.to_string(),
202        DimensionConstraint::Fraction(value) => format!("fraction({value})"),
203        DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
204    }
205}
206
207fn inspector_slice(inspector: &Option<Rc<Vec<InspectorMetadata>>>) -> &[InspectorMetadata] {
208    inspector.as_deref().map_or(&[], Vec::as_slice)
209}
210
211/// The inspector metadata of two modifiers joined, first `first`'s, or
212/// `None` when neither has any.
213fn merged_inspector(
214    first: &[InspectorMetadata],
215    second: &[InspectorMetadata],
216) -> Option<Rc<Vec<InspectorMetadata>>> {
217    if first.is_empty() && second.is_empty() {
218        return None;
219    }
220    Some(Rc::new(first.iter().chain(second).cloned().collect()))
221}
222
223pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
224where
225    F: FnOnce(&mut InspectorInfo),
226{
227    if !inspector_metadata_enabled() {
228        return InspectorMetadata::new(name, |_| {});
229    }
230    InspectorMetadata::new(name, recorder)
231}
232
233pub(crate) fn modifier_debug_enabled() -> bool {
234    #[cfg(not(target_arch = "wasm32"))]
235    {
236        cranpose_core::DIAGNOSTICS.compose_debug_modifiers.is_set()
237    }
238    #[cfg(target_arch = "wasm32")]
239    {
240        false
241    }
242}
243
244fn inspector_metadata_enabled() -> bool {
245    cfg!(any(test, feature = "inspection")) || modifier_debug_enabled()
246}
247
248/// A modifier's elements: a chain of up to four lives inline in its one
249/// shared allocation.
250type ModifierElements = SmallVec<[DynModifierElement; 4]>;
251
252/// The elements of a non-empty modifier. A lone element, as each link of a
253/// builder chain starts out, is held as it is; joining it to more moves the
254/// chain into one shared allocation, which the chain's later links extend
255/// in place while it is the only owner.
256#[derive(Clone)]
257enum Elements {
258    One(DynModifierElement),
259    Many(Rc<ModifierElements>),
260}
261
262impl Elements {
263    /// These elements followed by `more`. Elements move into the joined
264    /// chain; only those another modifier also holds are copied.
265    fn joined(self, more: Self) -> Self {
266        let mut chain = match self {
267            Self::One(first) => {
268                let mut chain = ModifierElements::new();
269                chain.push(first);
270                Rc::new(chain)
271            }
272            Self::Many(chain) => chain,
273        };
274        match Rc::get_mut(&mut chain) {
275            Some(owned) => more.move_into(owned),
276            None => {
277                let mut copy: ModifierElements = chain.iter().cloned().collect();
278                more.move_into(&mut copy);
279                chain = Rc::new(copy);
280            }
281        }
282        Self::Many(chain)
283    }
284
285    fn move_into(self, chain: &mut ModifierElements) {
286        match self {
287            Self::One(element) => chain.push(element),
288            Self::Many(shared) => match Rc::try_unwrap(shared) {
289                Ok(owned) => chain.extend(owned),
290                Err(shared) => chain.extend(shared.iter().cloned()),
291            },
292        }
293    }
294
295    /// Whether both are the same storage, so equal without comparing.
296    fn shares_storage(&self, other: &Self) -> bool {
297        match (self, other) {
298            (Self::One(a), Self::One(b)) => Rc::ptr_eq(a, b),
299            (Self::Many(a), Self::Many(b)) => Rc::ptr_eq(a, b),
300            _ => false,
301        }
302    }
303}
304
305impl std::ops::Deref for Elements {
306    type Target = [DynModifierElement];
307
308    fn deref(&self) -> &[DynModifierElement] {
309        match self {
310            Self::One(element) => std::slice::from_ref(element),
311            Self::Many(elements) => elements.as_slice(),
312        }
313    }
314}
315
316#[derive(Clone)]
317enum ModifierKind {
318    Empty,
319    Single {
320        elements: Elements,
321        /// `None` when no element records inspector metadata, which is
322        /// always outside tests and modifier debugging: no allocation.
323        inspector: Option<Rc<Vec<InspectorMetadata>>>,
324    },
325}
326
327// A modifier's elements and its inspector metadata, in order.
328pub(crate) type ModifierElementIterator<'a> = std::slice::Iter<'a, DynModifierElement>;
329pub(crate) type ModifierInspectorIterator<'a> = std::slice::Iter<'a, InspectorMetadata>;
330
331/// A modifier chain that can be applied to composable elements.
332///
333/// Modifiers allow you to decorate or augment a composable. Common operations include:
334/// - Adjusting layout (e.g., `padding`, `fill_max_size`)
335/// - Adding behavior (e.g., `clickable`, `scrollable`)
336/// - Drawing (e.g., `background`, `border`)
337///
338/// Modifiers are immutable and form a chain using the builder pattern.
339/// The order of modifiers matters: previous modifiers wrap subsequent ones.
340///
341/// # Example
342///
343/// ```rust,ignore
344/// Modifier::padding(16.0)     // Applied first (outer)
345///     .background(Color::Red) // Applied second
346///     .clickable(|| println!("Clicked")) // Applied last (inner)
347/// ```
348#[derive(Clone)]
349#[must_use = "a modifier does nothing until a composable receives it"]
350pub struct Modifier {
351    kind: ModifierKind,
352    provides_composition_locals: bool,
353}
354
355impl Default for Modifier {
356    fn default() -> Self {
357        Self {
358            kind: ModifierKind::Empty,
359            provides_composition_locals: false,
360        }
361    }
362}
363
364impl Modifier {
365    /// Returns a modifier that changes nothing.
366    pub fn empty() -> Self {
367        Self::default()
368    }
369
370    /// Creates a modifier from a custom modifier node element.
371    pub fn from_element<E>(element: E) -> Self
372    where
373        E: ModifierNodeElement,
374    {
375        Self::with_element(element)
376    }
377
378    /// Clip the content to the bounds of this modifier.
379    ///
380    /// Example: `Modifier::empty().clip_to_bounds()`
381    pub fn clip_to_bounds(self) -> Self {
382        let modifier = crate::thread_state::with(|state| {
383            state
384                .clip_to_bounds
385                .get_or_init(|| Self::from_dyn_element(plain_element(ClipToBoundsElement)))
386                .clone()
387        });
388        let modifier =
389            modifier.with_inspector_metadata(inspector_metadata("clipToBounds", |info| {
390                info.add_property("clipToBounds", "true");
391            }));
392        self.then(modifier)
393    }
394
395    /// Provides the value that `value` returns for `key` to later modifiers in this chain and to
396    /// nodes below. Compose's `Modifier.modifierLocalProvider`.
397    pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
398    where
399        T: 'static,
400        F: Fn() -> T + 'static,
401    {
402        let element = ModifierLocalProviderElement::new(key, value);
403        let modifier = Self::from_dyn_element(modifier_element(element));
404        self.then(modifier)
405    }
406
407    /// Calls `consumer` to read modifier local values through a [`ModifierLocalReadScope`]. It runs
408    /// again when a value it read changes. Compose's `Modifier.modifierLocalConsumer`.
409    pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
410    where
411        F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
412    {
413        let element = ModifierLocalConsumerElement::new(consumer);
414        let modifier = Self::from_dyn_element(modifier_element(element));
415        self.then(modifier)
416    }
417
418    /// Says what a screen reader reads for this node, as one spec value.
419    ///
420    /// This is [`Modifier::semantics`] with a value in place of a closure.
421    /// Compose has only the closure form, because Kotlin's receiver lambda
422    /// makes `semantics { contentDescription = "Save" }` read well; Rust has
423    /// none, so a spec value reads better, costs one chain element rather
424    /// than one per property, and can be compared with another.
425    ///
426    /// Example:
427    /// `Modifier::empty().semantics_spec(SemanticsSpec::new().content_description("Amount").error("needs a number"))`
428    pub fn semantics_spec(self, spec: cranpose_foundation::SemanticsSpec) -> Self {
429        self.stable_semantics(move |config: &mut SemanticsConfiguration| config.merge(&spec))
430    }
431
432    /// Records what a screen reader reads for this node. The recorder may
433    /// read live state, so every semantics update runs it again; one whose
434    /// answer changes without the node changing can say so with a
435    /// [`SemanticsRequester`](crate::SemanticsRequester).
436    pub fn semantics<F>(self, recorder: F) -> Self
437    where
438        F: Fn(&mut SemanticsConfiguration) + 'static,
439    {
440        self.semantics_recorder(Rc::new(recorder), true)
441    }
442
443    /// [`Modifier::semantics`] for a recorder that reads nothing but what it
444    /// captured. Its answer changes only when the modifier is set again, which
445    /// invalidates the node's semantics, so a semantics update keeps what it
446    /// reported instead of running it.
447    ///
448    /// Example: `Modifier::empty().stable_semantics(move |config| config.content_description = Some(label.clone()))`
449    pub fn stable_semantics<F>(self, recorder: F) -> Self
450    where
451        F: Fn(&mut SemanticsConfiguration) + 'static,
452    {
453        self.semantics_recorder(Rc::new(recorder), false)
454    }
455
456    fn semantics_recorder(
457        self,
458        recorder: Rc<dyn Fn(&mut SemanticsConfiguration)>,
459        reads_live_state: bool,
460    ) -> Self {
461        let metadata = if inspector_metadata_enabled() {
462            let mut preview = SemanticsConfiguration::default();
463            recorder(&mut preview);
464            let description = preview.content_description.clone();
465            let state_description = preview.state_description.clone();
466            let role = preview.role;
467            let is_clickable = preview.is_activatable();
468            let canvas_children = preview.canvas_children.len();
469            inspector_metadata("semantics", move |info| {
470                if let Some(desc) = &description {
471                    info.add_property("contentDescription", desc.clone());
472                }
473                if let Some(state) = &state_description {
474                    info.add_property("stateDescription", state.clone());
475                }
476                if let Some(role) = role {
477                    info.add_property("role", format!("{role:?}"));
478                }
479                if is_clickable {
480                    info.add_property("isClickable", "true");
481                }
482                if canvas_children > 0 {
483                    info.add_property("canvasSemanticsChildren", canvas_children.to_string());
484                }
485            })
486        } else {
487            inspector_metadata("semantics", |_| {})
488        };
489        let element = SemanticsElement::new(recorder, reads_live_state);
490        let modifier =
491            Self::from_dyn_element(modifier_element(element)).with_inspector_metadata(metadata);
492        self.then(modifier)
493    }
494
495    /// Tells a screen reader the value this control holds inside a range, so
496    /// it reads the value and offers its own way to change it.
497    ///
498    /// This is Compose's `Modifier.progressSemantics(value, valueRange,
499    /// steps)`. Without it a slider reads as text and a person who cannot see
500    /// the screen has no way to move it.
501    ///
502    /// Example: `Modifier::empty().progress_semantics(0.35, 0.0, 1.0, 0)`
503    pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
504        let info = ProgressBarRangeInfo::new(current, start, end, steps);
505        self.stable_semantics(move |config| config.progress = Some(info))
506    }
507
508    /// Marks this control as one that opens a list of choices, so a reader
509    /// says "combo box" rather than "button" and knows to look for the
510    /// choice it holds. Compose's `Role.DropdownList`.
511    pub fn dropdown_list(self) -> Self {
512        self.role(cranpose_foundation::SemanticsWidgetRole::DropdownList)
513    }
514
515    /// Marks this control as one that holds one value out of an ordered set,
516    /// so a reader steps through them. Compose's `Role.ValuePicker`.
517    pub fn value_picker(self) -> Self {
518        self.role(cranpose_foundation::SemanticsWidgetRole::ValuePicker)
519    }
520
521    /// Says what this control does when a screen reader asks it to open, and
522    /// marks it as closed right now: a reader offers "expand" and says the
523    /// control is collapsed. Compose's
524    /// `Modifier.semantics { expand { … } }`.
525    pub fn expand(self, action: impl Fn() -> bool + 'static) -> Self {
526        let action = cranpose_foundation::SemanticsExpand::new(action);
527        self.stable_semantics(move |config| config.expand = Some(action.clone()))
528    }
529
530    /// Says what a long press on this control does, so a screen reader can
531    /// ask for it and read the label out first: "Remove receipt". Compose's
532    /// `Modifier.semantics { onLongClick("Remove receipt") { … } }`, which
533    /// `Modifier.combinedClickable(onLongClickLabel = …)` fills in for a
534    /// control that takes a long press from a finger too.
535    ///
536    /// The label is asked for, not optional as in Compose: Android is the one
537    /// platform of the four with a long press of its own, and the other three
538    /// list the action by name, so a nameless one reads as nothing.
539    pub fn on_long_click(
540        self,
541        label: impl Into<String>,
542        action: impl Fn() -> bool + 'static,
543    ) -> Self {
544        let label = label.into();
545        let action = cranpose_foundation::SemanticsLongClick::new(action);
546        self.stable_semantics(move |config| {
547            config.on_long_click_label = Some(label.clone());
548            config.on_long_click = Some(action.clone());
549        })
550    }
551
552    /// Says what this control does on VoiceOver's magic tap, the two finger
553    /// double tap for the main action of a screen, and the verb phrase the
554    /// other platforms list it under: "Take the photo". SwiftUI's
555    /// `accessibilityAction(.magicTap)`.
556    pub fn on_magic_tap(
557        self,
558        label: impl Into<String>,
559        action: impl Fn() -> bool + 'static,
560    ) -> Self {
561        let label = label.into();
562        let action = cranpose_foundation::SemanticsMagicTap::new(action);
563        self.stable_semantics(move |config| {
564            config.on_magic_tap_label = Some(label.clone());
565            config.on_magic_tap = Some(action.clone());
566        })
567    }
568
569    /// The short names a person says to Voice Control to reach this control,
570    /// when the name a reader hears is too long to say. SwiftUI's
571    /// `accessibilityInputLabels`.
572    pub fn input_labels<S: Into<String>>(self, labels: impl IntoIterator<Item = S>) -> Self {
573        let labels: Vec<String> = labels.into_iter().map(Into::into).collect();
574        self.stable_semantics(move |config| config.input_labels.clone_from(&labels))
575    }
576
577    /// The language of this control's text, as a BCP 47 tag such as "de" or
578    /// "pt-BR", so a reader picks the right voice. SwiftUI's
579    /// `accessibilityLanguage`, ARIA's `lang`.
580    pub fn language(self, tag: impl Into<String>) -> Self {
581        let tag = tag.into();
582        self.stable_semantics(move |config| config.language = Some(tag.clone()))
583    }
584
585    /// Says what this control does when a screen reader asks it to close, and
586    /// marks it as open right now. Compose's
587    /// `Modifier.semantics { collapse { … } }`.
588    pub fn collapse(self, action: impl Fn() -> bool + 'static) -> Self {
589        let action = cranpose_foundation::SemanticsExpand::new(action);
590        self.stable_semantics(move |config| config.collapse = Some(action.clone()))
591    }
592
593    /// Says what this control does when a screen reader asks to send it away:
594    /// a row a sighted person swipes off, a sheet a sighted person taps
595    /// outside of. A reader that cannot make the gesture gets the same way
596    /// out. Compose's `Modifier.semantics { dismiss { … } }`.
597    pub fn dismiss(self, action: impl Fn() -> bool + 'static) -> Self {
598        let action = cranpose_foundation::SemanticsDismiss::new(action);
599        self.stable_semantics(move |config| config.dismiss = Some(action.clone()))
600    }
601
602    /// Says what this list does when a screen reader asks for the row at an
603    /// index, so a reader reaches row 300 of a long list at once instead of
604    /// paging to it. The index counts rows from zero and the answer says
605    /// whether the list moved. `LazyColumn` and `LazyRow` declare it on their
606    /// own. Compose's `Modifier.semantics { scrollToIndex { … } }`.
607    pub fn scroll_to_index(self, action: impl Fn(usize) -> bool + 'static) -> Self {
608        let action = cranpose_foundation::SemanticsScrollToIndex::new(action);
609        self.stable_semantics(move |config| config.scroll_to_index = Some(action.clone()))
610    }
611
612    /// Moves this node in the order a screen reader visits the nodes beside
613    /// it: a smaller number comes first, and a node left alone keeps the
614    /// order the app laid it out in. A search field drawn last but meant to
615    /// be read first takes a negative number. Compose's
616    /// `Modifier.semantics { traversalIndex = -1f }`.
617    pub fn traversal_index(self, index: f32) -> Self {
618        self.stable_semantics(move |config| config.traversal_index = index)
619    }
620
621    /// Marks a field as one that holds a secret, so no screen reader reads
622    /// its text out: a reader hears the name the app gave the field, and
623    /// "password" in place of the text. Compose's
624    /// `Modifier.semantics { password() }`.
625    pub fn password(self) -> Self {
626        self.stable_semantics(|config| config.password = true)
627    }
628
629    /// Says why the control's content is wrong, so a screen reader reads
630    /// "invalid, the amount needs a number" after the control's state.
631    /// Compose's `Modifier.semantics { error("...") }`.
632    pub fn error(self, message: impl Into<String>) -> Self {
633        let message = message.into();
634        self.stable_semantics(move |config| config.error = Some(message.clone()))
635    }
636
637    /// Tells a screen reader what using the control does or what it wants,
638    /// read after its other words: "double tap to choose a color", "a name of
639    /// up to 20 letters". Compose's `Modifier.semantics { hintText = "..." }`.
640    pub fn hint_text(self, hint: impl Into<String>) -> Self {
641        let hint = hint.into();
642        self.stable_semantics(move |config| config.hint_text = Some(hint.clone()))
643    }
644
645    /// Names the screen or pane this node is the root of, so a screen reader
646    /// hears where it is when the app moves on: "Library" as the library
647    /// opens. Compose's `Modifier.semantics { paneTitle = "..." }`.
648    pub fn pane_title(self, title: impl Into<String>) -> Self {
649        let title = title.into();
650        self.stable_semantics(move |config| config.pane_title = Some(title.clone()))
651    }
652
653    /// Makes the selectable controls under this node one group, so a screen
654    /// reader says which of how many a tab or a radio button is: "Library,
655    /// tab, 2 of 5". `LiquidTabBar` declares it on its own. Compose's
656    /// `Modifier.selectableGroup()`.
657    pub fn selectable_group(self) -> Self {
658        self.stable_semantics(|config| config.selectable_group = true)
659    }
660
661    /// Makes a screen reader take this node and the text under it as one
662    /// stop, the way it does for a button: a row whose name, count and price
663    /// belong together reads as "Milk, 2, 3.40" and not as three stops.
664    /// Compose's `Modifier.semantics(mergeDescendants = true) {}`.
665    pub fn merge_descendants(self) -> Self {
666        self.stable_semantics(|config| config.merge_descendants = true)
667    }
668
669    /// Takes this node and everything under it out of what a screen reader
670    /// sees: a decorative image, or a placeholder drawn under a field that
671    /// carries the same words as its name. Compose's
672    /// `semantics { hideFromAccessibility() }`.
673    pub fn hide_from_accessibility(self) -> Self {
674        self.stable_semantics(|config| config.hidden = true)
675    }
676
677    /// Marks this component as a heading, so a screen reader lists it among
678    /// the headings of the screen and a person can jump between them.
679    ///
680    /// This is Compose's `Modifier.semantics { heading() }`.
681    pub fn heading(self) -> Self {
682        self.role(cranpose_foundation::SemanticsWidgetRole::Header)
683    }
684
685    /// Tells a screen reader what kind of control this is, when the widget
686    /// does not say so on its own.
687    ///
688    /// This is Compose's `Modifier.semantics { role = Role.Button }`.
689    pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
690        self.stable_semantics(move |config| config.role = Some(role))
691    }
692
693    /// Makes a screen reader read this component's text out whenever it
694    /// changes, without the reader's cursor on it: a status line, a toast, a
695    /// count that moves.
696    ///
697    /// This is Compose's `Modifier.semantics { liveRegion = LiveRegionMode.Polite }`.
698    pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
699        self.stable_semantics(move |config| config.live_region = Some(mode))
700    }
701
702    /// Gives this component the text a screen reader reads for it, for a
703    /// drawing, an icon or a control with no text of its own.
704    ///
705    /// This is Compose's `Modifier.semantics { contentDescription = "..." }`.
706    pub fn content_description(self, description: impl Into<String>) -> Self {
707        let description = description.into();
708        self.stable_semantics(move |config| config.content_description = Some(description.clone()))
709    }
710
711    /// Names this component for tests, which find it by the name instead of its text or
712    /// position. [`SemanticsConfiguration::test_tag`] lists where each platform publishes it.
713    ///
714    /// This is Compose's `Modifier.testTag(tag)`.
715    pub fn test_tag(self, tag: impl Into<String>) -> Self {
716        let tag = tag.into();
717        self.stable_semantics(move |config| config.test_tag = Some(tag.clone()))
718    }
719
720    /// Binds a [`SemanticsRequester`] to this node, so an app can mark the
721    /// node's semantics for re-collection without recomposing or laying out.
722    ///
723    /// Pair it with [`semantics`](Self::semantics) on the same node when the
724    /// recorder reads state the composition does not observe — app state behind
725    /// a `RefCell`, a game's own model — which is the case a recorder cannot
726    /// signal for itself.
727    pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
728        let element = SemanticsRequesterElement::new(requester.clone());
729        let modifier = Self::from_dyn_element(modifier_element(element));
730        self.then(modifier)
731    }
732
733    /// Enables debug logging for this modifier chain.
734    ///
735    /// When enabled, logs the entire modifier chain structure including:
736    /// - Element types and their properties
737    /// - Inspector metadata
738    /// - Capability flags
739    ///
740    /// This is useful for debugging modifier composition issues and understanding
741    /// how the modifier chain is structured at runtime.
742    ///
743    /// Example:
744    /// ```text
745    /// Modifier::empty()
746    ///     .padding(8.0)
747    ///     .background(Color(1.0, 0.0, 0.0, 1.0))
748    ///     .debug_chain("MyWidget")
749    /// ```
750    pub fn debug_chain(self, tag: &'static str) -> Self {
751        use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
752
753        #[derive(Clone)]
754        struct DebugChainElement {
755            tag: &'static str,
756        }
757
758        impl fmt::Debug for DebugChainElement {
759            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760                f.debug_struct("DebugChainElement")
761                    .field("tag", &self.tag)
762                    .finish()
763            }
764        }
765
766        impl PartialEq for DebugChainElement {
767            fn eq(&self, other: &Self) -> bool {
768                self.tag == other.tag
769            }
770        }
771
772        impl Eq for DebugChainElement {}
773
774        impl std::hash::Hash for DebugChainElement {
775            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
776                self.tag.hash(state);
777            }
778        }
779
780        impl ModifierNodeElement for DebugChainElement {
781            type Node = DebugChainNode;
782
783            fn create(&self) -> Self::Node {
784                DebugChainNode::new(self.tag)
785            }
786
787            fn update(&self, node: &mut Self::Node) {
788                node.tag = self.tag;
789            }
790
791            fn capabilities(&self) -> NodeCapabilities {
792                NodeCapabilities::empty()
793            }
794        }
795
796        struct DebugChainNode {
797            tag: &'static str,
798            state: NodeState,
799        }
800
801        impl DebugChainNode {
802            fn new(tag: &'static str) -> Self {
803                Self {
804                    tag,
805                    state: NodeState::new(),
806                }
807            }
808        }
809
810        #[expect(clippy::print_stderr, reason = "debug_chain prints its lifecycle")]
811        impl ModifierNode for DebugChainNode {
812            fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
813                eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
814            }
815
816            fn on_detach(&mut self) {
817                eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
818            }
819
820            fn on_reset(&mut self) {
821                eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
822            }
823        }
824
825        impl cranpose_foundation::DelegatableNode for DebugChainNode {
826            fn node_state(&self) -> &NodeState {
827                &self.state
828            }
829        }
830
831        let element = DebugChainElement { tag };
832        let modifier = Self::from_dyn_element(modifier_element(element));
833        self.then(modifier)
834            .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
835                info.add_property("tag", tag);
836            }))
837    }
838
839    /// This modifier followed by `next`.
840    ///
841    /// It takes `self`: a modifier built link by link owns its elements
842    /// alone, so each link joins them in place instead of copying the chain.
843    /// Clone a modifier first to keep using it; the join then copies it.
844    pub fn then(self, next: Self) -> Self {
845        let ModifierKind::Single {
846            elements,
847            inspector,
848        } = self.kind
849        else {
850            return next;
851        };
852        let ModifierKind::Single {
853            elements: next_elements,
854            inspector: next_inspector,
855        } = next.kind
856        else {
857            return Self {
858                kind: ModifierKind::Single {
859                    elements,
860                    inspector,
861                },
862                ..self
863            };
864        };
865
866        let inspector = if next_inspector.is_none() {
867            inspector
868        } else {
869            merged_inspector(
870                inspector_slice(&inspector),
871                inspector_slice(&next_inspector),
872            )
873        };
874        Self {
875            kind: ModifierKind::Single {
876                elements: elements.joined(next_elements),
877                inspector,
878            },
879            provides_composition_locals: self.provides_composition_locals
880                || next.provides_composition_locals,
881        }
882    }
883
884    /// How many elements the modifier holds.
885    pub(crate) fn element_count(&self) -> usize {
886        match &self.kind {
887            ModifierKind::Empty => 0,
888            ModifierKind::Single { elements, .. } => elements.len(),
889        }
890    }
891
892    pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
893        self.as_elements().iter()
894    }
895
896    pub(crate) fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
897        if !self.provides_composition_locals {
898            return Vec::new();
899        }
900        self.iter_elements()
901            .flat_map(|element| element.provided_composition_locals())
902            .collect()
903    }
904
905    pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
906        match &self.kind {
907            ModifierKind::Empty => [].iter(),
908            ModifierKind::Single { inspector, .. } => inspector_slice(inspector).iter(),
909        }
910    }
911
912    #[cfg(test)]
913    pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
914        match &self.kind {
915            ModifierKind::Empty => Vec::new(),
916            ModifierKind::Single { elements, .. } => elements.to_vec(),
917        }
918    }
919
920    pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
921        match &self.kind {
922            ModifierKind::Empty => Vec::new(),
923            ModifierKind::Single { inspector, .. } => {
924                inspector.as_deref().cloned().unwrap_or_default()
925            }
926        }
927    }
928
929    /// Returns the largest of the four edge paddings, in logical pixels.
930    pub fn total_padding(&self) -> f32 {
931        let padding = self.padding_values();
932        padding
933            .left
934            .max(padding.right)
935            .max(padding.top)
936            .max(padding.bottom)
937    }
938
939    /// Returns the size when both width and height are fixed lengths in logical pixels, or `None`
940    /// otherwise.
941    pub fn explicit_size(&self) -> Option<Size> {
942        let props = self.layout_properties();
943        match (props.width, props.height) {
944            (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
945                Some(Size { width, height })
946            }
947            _ => None,
948        }
949    }
950
951    /// Returns the padding on each edge that the chain adds, in logical pixels.
952    pub fn padding_values(&self) -> EdgeInsets {
953        self.resolved_modifiers().padding()
954    }
955
956    pub(crate) fn layout_properties(&self) -> LayoutProperties {
957        self.resolved_modifiers().layout_properties()
958    }
959
960    /// Returns the alignment set by [`Self::align`] for a `Box` parent, or `None` when none is set.
961    pub fn box_alignment(&self) -> Option<Alignment> {
962        self.layout_properties().box_alignment()
963    }
964
965    /// Returns the horizontal alignment set for a `Column` parent, or `None` when none is set.
966    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
967        self.layout_properties().column_alignment()
968    }
969
970    /// Returns the vertical alignment set for a `Row` parent, or `None` when none is set.
971    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
972        self.layout_properties().row_alignment()
973    }
974
975    /// Returns the draw commands of the chain in the order they draw.
976    pub fn draw_commands(&self) -> Vec<DrawCommand> {
977        collect_slices_from_modifier(self).draw_commands().to_vec()
978    }
979
980    /// Returns whether the chain clips content to the node's bounds.
981    pub fn clips_to_bounds(&self) -> bool {
982        collect_slices_from_modifier(self).clip_to_bounds()
983    }
984
985    /// Returns structured inspector records for each modifier element.
986    pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
987        self.inspector_metadata()
988            .iter()
989            .map(InspectorMetadata::to_record)
990            .collect()
991    }
992
993    /// Resolves the chain into its padding, layout properties and offset.
994    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
995        let mut handle = ModifierChainHandle::new();
996        let _ = handle.update(self);
997        handle.resolved_modifiers()
998    }
999
1000    /// A modifier of the one `element`. Platform crates build their own
1001    /// modifiers on it, the way [`Modifier::window_root`] is built.
1002    pub fn with_element<E>(element: E) -> Self
1003    where
1004        E: ModifierNodeElement,
1005    {
1006        Self::from_dyn_element(modifier_element(element))
1007    }
1008
1009    /// A modifier of the one `element`.
1010    pub(crate) fn from_dyn_element(element: DynModifierElement) -> Self {
1011        Self {
1012            provides_composition_locals: element.provides_composition_locals(),
1013            kind: ModifierKind::Single {
1014                elements: Elements::One(element),
1015                inspector: None,
1016            },
1017        }
1018    }
1019
1020    pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
1021        if metadata.is_empty() {
1022            return self;
1023        }
1024        match self.kind {
1025            ModifierKind::Empty => self,
1026            ModifierKind::Single {
1027                elements,
1028                inspector,
1029            } => {
1030                let mut list = inspector.as_deref().cloned().unwrap_or_default();
1031                list.push(metadata);
1032                let new_inspector = Rc::new(list);
1033                Self {
1034                    kind: ModifierKind::Single {
1035                        elements,
1036                        inspector: Some(new_inspector),
1037                    },
1038                    provides_composition_locals: self.provides_composition_locals,
1039                }
1040            }
1041        }
1042    }
1043
1044    /// Checks whether two modifiers are structurally equivalent for layout decisions.
1045    ///
1046    /// This ignores identity-sensitive modifier elements (e.g., draw closures) so
1047    /// draw-only updates do not force measure/layout invalidation.
1048    pub fn structural_eq(&self, other: &Self) -> bool {
1049        element_match::modifiers_match(self, other, ElementMatch::Structural)
1050    }
1051
1052    fn as_elements(&self) -> &[DynModifierElement] {
1053        match &self.kind {
1054            ModifierKind::Empty => &[],
1055            ModifierKind::Single { elements, .. } => elements,
1056        }
1057    }
1058}
1059
1060impl PartialEq for Modifier {
1061    fn eq(&self, other: &Self) -> bool {
1062        element_match::modifiers_match(self, other, ElementMatch::Equal)
1063    }
1064}
1065
1066impl Eq for Modifier {}
1067
1068impl fmt::Display for Modifier {
1069    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1070        match &self.kind {
1071            ModifierKind::Empty => write!(f, "Modifier.empty"),
1072            ModifierKind::Single { elements, .. } => {
1073                if elements.is_empty() {
1074                    return write!(f, "Modifier.empty");
1075                }
1076                write!(f, "Modifier[")?;
1077                for (index, element) in elements.iter().enumerate() {
1078                    if index > 0 {
1079                        write!(f, ", ")?;
1080                    }
1081                    let name = element.inspector_name();
1082                    let mut properties = Vec::new();
1083                    element.record_inspector_properties(&mut |prop, value| {
1084                        properties.push(format!("{prop}={value}"));
1085                    });
1086                    if properties.is_empty() {
1087                        write!(f, "{name}")?;
1088                    } else {
1089                        write!(f, "{name}({})", properties.join(", "))?;
1090                    }
1091                }
1092                write!(f, "]")
1093            }
1094        }
1095    }
1096}
1097
1098impl fmt::Debug for Modifier {
1099    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100        fmt::Display::fmt(self, f)
1101    }
1102}
1103
1104#[cfg(test)]
1105#[path = "tests/modifier_tests.rs"]
1106mod tests;