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