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::{
9    fmt,
10    hash::{Hash, Hasher},
11    rc::Rc,
12};
13
14use cranpose_core::{ProvidedValue, hash::default};
15use smallvec::SmallVec;
16
17mod alignment;
18mod background;
19mod blur;
20mod border;
21mod chain;
22mod clickable;
23mod coordinator_geometry;
24mod drag_and_drop;
25mod draw_cache;
26mod fill;
27mod focus;
28mod focus_ring;
29mod graphics_layer;
30mod key_input;
31mod local;
32mod minimum_interactive;
33mod offset;
34mod padding;
35mod pointer_icon;
36pub(crate) mod pointer_input;
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;
48
49pub use chain::{ModifierChainHandle, ModifierChainInspectorNode, ModifierLocalsHandle};
50pub(crate) use coordinator_geometry::{CoordinatorGeometry, CoordinatorRect};
51pub use cranpose_foundation::{
52    AnyModifierElement, DynModifierElement, FocusState, PointerEvent, PointerEventKind,
53    PointerSource, RotaryScrollEvent, SemanticsConfiguration, modifier_element,
54};
55use cranpose_foundation::{ModifierNodeElement, NodeCapabilities, ProgressBarRangeInfo};
56#[expect(unused_imports)]
57pub use cranpose_ui_graphics::{
58    BlendMode, BlurredEdgeTreatment, Brush, Color, ColorFilter, CompositingStrategy, CornerRadii,
59    CursorIcon, CustomPointerIcon, CutDirection, Dp, DpOffset, EdgeInsets, GradientCutMaskSpec,
60    GradientFadeMaskSpec, GraphicsLayer, LayerShape, Point, PointerIcon, PointerIconError, Rect,
61    RenderEffect, RoundedCornerShape, RuntimeShader, Shadow, ShadowScope, Size, TransformOrigin,
62};
63use cranpose_ui_layout::{Alignment, HorizontalAlignment, IntrinsicSize, VerticalAlignment};
64pub use drag_and_drop::{
65    DragAndDropEvent, DragAndDropOutcome, DragAndDropPayload, DragAndDropPoint, DragAndDropSource,
66    DragAndDropSourceElement, DragAndDropSourceNode, DragAndDropState, DragAndDropTarget,
67    DragAndDropTargetElement, DragAndDropTargetNode,
68};
69use focus::FocusTargetElement;
70pub use focus::{FocusDirection, FocusRequestError, FocusRequester, FocusRequesterElement};
71pub use graphics_layer::GlassMaterial;
72pub use key_input::KeyEventRoute;
73pub(crate) use local::{
74    ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
75};
76use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
77pub use local::{ModifierLocalKey, ModifierLocalReadScope};
78#[expect(unused_imports)]
79pub use pointer_input::{AwaitPointerEventScope, PointerInputScope};
80pub use rotary_input::RotaryInputModifierNode;
81#[cfg(test)]
82pub(crate) use scroll::lazy_scroll_semantics;
83#[cfg(feature = "test-helpers")]
84pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
85use semantics::SemanticsElement;
86pub use semantics::{
87    SemanticsRequester, SemanticsRequesterElement, collect_semantics_from_chain,
88    collect_semantics_from_modifier, semantics_reach_of_chain,
89};
90pub(crate) use slices::SlicesSnapshot;
91pub use slices::{
92    ModifierNodeSlices, ModifierNodeSlicesDebugStats, SliceTextRef, collect_modifier_slices,
93    collect_slices_from_modifier,
94};
95pub use window_root::{
96    WindowRootDescriptor, WindowRootElement, WindowRootEntry, WindowRootNode, WindowRootRegistry,
97    WindowRootRoutingScratch, is_window_root, nearest_window_root, nearest_window_roots,
98    nearest_window_roots_into, window_roots, window_roots_revision,
99};
100
101pub use crate::draw::{DrawCacheBuilder, DrawCommand};
102use crate::modifier_nodes::ClipToBoundsElement;
103
104#[derive(Clone, Debug, Default)]
105pub struct InspectorInfo {
106    properties: Vec<InspectorProperty>,
107}
108
109impl InspectorInfo {
110    pub fn new() -> Self {
111        Self::default()
112    }
113
114    pub fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
115        self.properties.push(InspectorProperty {
116            name,
117            value: value.into(),
118        });
119    }
120
121    pub fn properties(&self) -> &[InspectorProperty] {
122        &self.properties
123    }
124
125    pub fn is_empty(&self) -> bool {
126        self.properties.is_empty()
127    }
128
129    pub fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
130        self.add_property(name, describe_dimension(constraint));
131    }
132
133    pub fn add_offset_components(
134        &mut self,
135        x_name: &'static str,
136        y_name: &'static str,
137        offset: Point,
138    ) {
139        self.add_property(x_name, offset.x.to_string());
140        self.add_property(y_name, offset.y.to_string());
141    }
142
143    pub fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
144    where
145        A: fmt::Debug,
146    {
147        self.add_property(name, format!("{alignment:?}"));
148    }
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub struct InspectorProperty {
153    pub name: &'static str,
154    pub value: String,
155}
156
157#[derive(Clone, Debug, PartialEq)]
158pub struct ModifierInspectorRecord {
159    pub name: &'static str,
160    pub properties: Vec<InspectorProperty>,
161}
162
163#[derive(Clone, Debug)]
164pub(crate) struct InspectorMetadata {
165    name: &'static str,
166    info: InspectorInfo,
167}
168
169impl InspectorMetadata {
170    pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
171    where
172        F: FnOnce(&mut InspectorInfo),
173    {
174        let mut info = InspectorInfo::new();
175        recorder(&mut info);
176        Self { name, info }
177    }
178
179    fn is_empty(&self) -> bool {
180        self.info.is_empty()
181    }
182
183    fn to_record(&self) -> ModifierInspectorRecord {
184        ModifierInspectorRecord {
185            name: self.name,
186            properties: self.info.properties().to_vec(),
187        }
188    }
189}
190
191fn describe_dimension(constraint: DimensionConstraint) -> String {
192    match constraint {
193        DimensionConstraint::Unspecified => "unspecified".to_string(),
194        DimensionConstraint::Points(value) => value.to_string(),
195        DimensionConstraint::Fraction(value) => format!("fraction({value})"),
196        DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
197    }
198}
199
200fn inspector_slice(inspector: &Option<Rc<[InspectorMetadata]>>) -> &[InspectorMetadata] {
201    inspector.as_deref().unwrap_or(&[])
202}
203
204/// The inspector metadata of two modifiers joined, first `first`'s, or
205/// `None` when neither has any.
206fn merged_inspector(
207    first: &[InspectorMetadata],
208    second: &[InspectorMetadata],
209) -> Option<Rc<[InspectorMetadata]>> {
210    if first.is_empty() && second.is_empty() {
211        return None;
212    }
213    Some(first.iter().chain(second).cloned().collect())
214}
215
216pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
217where
218    F: FnOnce(&mut InspectorInfo),
219{
220    if !inspector_metadata_enabled() {
221        return InspectorMetadata::new(name, |_| {});
222    }
223    InspectorMetadata::new(name, recorder)
224}
225
226pub(crate) fn modifier_debug_enabled() -> bool {
227    #[cfg(not(target_arch = "wasm32"))]
228    {
229        cranpose_core::env_flag!("COMPOSE_DEBUG_MODIFIERS")
230    }
231    #[cfg(target_arch = "wasm32")]
232    {
233        false
234    }
235}
236
237fn inspector_metadata_enabled() -> bool {
238    cfg!(any(test, feature = "inspection")) || modifier_debug_enabled()
239}
240
241/// A modifier's elements: a chain of up to four lives inline in its one
242/// shared allocation.
243type ModifierElements = SmallVec<[DynModifierElement; 4]>;
244
245/// The elements of a non-empty modifier. A lone element, as each link of a
246/// builder chain starts out, is held as it is; joining it to more moves the
247/// chain into one shared allocation, which the chain's later links extend
248/// in place while it is the only owner.
249#[derive(Clone)]
250enum Elements {
251    One(DynModifierElement),
252    Many(Rc<ModifierElements>),
253}
254
255impl Elements {
256    fn from_slice(elements: &[DynModifierElement]) -> Self {
257        match elements {
258            [element] => Self::One(element.clone()),
259            _ => Self::Many(Rc::new(elements.iter().cloned().collect())),
260        }
261    }
262
263    fn extend_from(&mut self, more: &[DynModifierElement]) {
264        match self {
265            Self::Many(shared) => match Rc::get_mut(shared) {
266                Some(owned) => owned.extend(more.iter().cloned()),
267                None => *shared = Rc::new(shared.iter().chain(more).cloned().collect()),
268            },
269            Self::One(first) => {
270                *self = Self::Many(Rc::new(
271                    std::iter::once(&*first).chain(more).cloned().collect(),
272                ));
273            }
274        }
275    }
276
277    /// Whether both are the same storage, so equal without comparing.
278    fn shares_storage(&self, other: &Self) -> bool {
279        match (self, other) {
280            (Self::One(a), Self::One(b)) => Rc::ptr_eq(a, b),
281            (Self::Many(a), Self::Many(b)) => Rc::ptr_eq(a, b),
282            _ => false,
283        }
284    }
285}
286
287impl std::ops::Deref for Elements {
288    type Target = [DynModifierElement];
289
290    fn deref(&self) -> &[DynModifierElement] {
291        match self {
292            Self::One(element) => std::slice::from_ref(element),
293            Self::Many(elements) => elements.as_slice(),
294        }
295    }
296}
297
298#[derive(Clone)]
299enum ModifierKind {
300    Empty,
301    Single {
302        elements: Elements,
303        /// `None` when no element records inspector metadata, which is
304        /// always outside tests and modifier debugging: no allocation.
305        inspector: Option<Rc<[InspectorMetadata]>>,
306    },
307}
308
309const FINGERPRINT_KIND_EMPTY: u8 = 0;
310const FINGERPRINT_KIND_SINGLE: u8 = 1;
311
312const FINGERPRINT_EMPTY_STRICT_SEED: u64 = 0x243f_6a88_85a3_08d3;
313const FINGERPRINT_EMPTY_STRUCTURAL_SEED: u64 = 0x1319_8a2e_0370_7344;
314const FINGERPRINT_SINGLE_STRICT_SEED: u64 = 0xa409_3822_299f_31d0;
315const FINGERPRINT_SINGLE_STRUCTURAL_SEED: u64 = 0x082e_fa98_ec4e_6c89;
316const FINGERPRINT_SEQUENCE_MUL: u64 = 0x9e37_79b1_85eb_ca87;
317const FINGERPRINT_STRICT_UPDATE_TAG: u64 = 0xdbe6_d5d5_fe4c_ce2f;
318const FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG: u64 = 0x94d0_49bb_1331_11eb;
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321struct ModifierFingerprints {
322    strict: u64,
323    structural: u64,
324}
325
326#[inline]
327fn mix_fingerprint_bits(mut value: u64) -> u64 {
328    value ^= value >> 33;
329    value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
330    value ^= value >> 33;
331    value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
332    value ^ (value >> 33)
333}
334
335#[inline]
336fn fold_fingerprint(state: u64, value: u64) -> u64 {
337    mix_fingerprint_bits(state ^ value.wrapping_add(FINGERPRINT_SEQUENCE_MUL))
338        .wrapping_mul(FINGERPRINT_SEQUENCE_MUL)
339}
340
341#[inline]
342fn empty_fingerprints() -> ModifierFingerprints {
343    ModifierFingerprints {
344        strict: fold_fingerprint(FINGERPRINT_EMPTY_STRICT_SEED, FINGERPRINT_KIND_EMPTY as u64),
345        structural: fold_fingerprint(
346            FINGERPRINT_EMPTY_STRUCTURAL_SEED,
347            FINGERPRINT_KIND_EMPTY as u64,
348        ),
349    }
350}
351
352#[inline]
353fn single_fingerprint_seed() -> ModifierFingerprints {
354    let strict = fold_fingerprint(
355        FINGERPRINT_SINGLE_STRICT_SEED,
356        FINGERPRINT_KIND_SINGLE as u64,
357    );
358    let structural = fold_fingerprint(
359        FINGERPRINT_SINGLE_STRUCTURAL_SEED,
360        FINGERPRINT_KIND_SINGLE as u64,
361    );
362    ModifierFingerprints { strict, structural }
363}
364
365#[inline]
366fn element_common_fingerprint(element: &DynModifierElement) -> u64 {
367    let mut hasher = default::new();
368    element.element_type().hash(&mut hasher);
369    element.capabilities().bits().hash(&mut hasher);
370    hasher.finish()
371}
372
373#[inline]
374fn element_fingerprints(element: &DynModifierElement) -> ModifierFingerprints {
375    let common = element_common_fingerprint(element);
376    let requires_update = element.requires_update();
377    let strict_payload = if requires_update {
378        let element_ptr = Rc::as_ptr(element) as *const () as usize as u64;
379        element_ptr ^ FINGERPRINT_STRICT_UPDATE_TAG
380    } else {
381        element.hash_code()
382    };
383    let strict = mix_fingerprint_bits(common ^ strict_payload);
384
385    let is_draw_only = element.capabilities() == NodeCapabilities::DRAW;
386    let structural_payload = if is_draw_only {
387        FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG
388    } else {
389        element.hash_code()
390    };
391    let structural = mix_fingerprint_bits(common ^ structural_payload);
392
393    ModifierFingerprints { strict, structural }
394}
395
396#[inline]
397fn append_fingerprints(
398    mut fingerprints: ModifierFingerprints,
399    elements: &[DynModifierElement],
400) -> ModifierFingerprints {
401    for element in elements {
402        let element_fingerprints = element_fingerprints(element);
403        fingerprints.strict = fold_fingerprint(fingerprints.strict, element_fingerprints.strict);
404        fingerprints.structural =
405            fold_fingerprint(fingerprints.structural, element_fingerprints.structural);
406    }
407    fingerprints
408}
409
410fn single_fingerprints(elements: &[DynModifierElement]) -> ModifierFingerprints {
411    append_fingerprints(single_fingerprint_seed(), elements)
412}
413
414pub struct ModifierElementIterator<'a> {
415    inner: std::slice::Iter<'a, DynModifierElement>,
416}
417
418impl<'a> Iterator for ModifierElementIterator<'a> {
419    type Item = &'a DynModifierElement;
420
421    #[inline]
422    fn next(&mut self) -> Option<Self::Item> {
423        self.inner.next()
424    }
425
426    #[inline]
427    fn size_hint(&self) -> (usize, Option<usize>) {
428        self.inner.size_hint()
429    }
430}
431
432impl ExactSizeIterator for ModifierElementIterator<'_> {}
433
434pub(crate) struct ModifierInspectorIterator<'a> {
435    inner: std::slice::Iter<'a, InspectorMetadata>,
436}
437
438impl<'a> Iterator for ModifierInspectorIterator<'a> {
439    type Item = &'a InspectorMetadata;
440
441    #[inline]
442    fn next(&mut self) -> Option<Self::Item> {
443        self.inner.next()
444    }
445
446    #[inline]
447    fn size_hint(&self) -> (usize, Option<usize>) {
448        self.inner.size_hint()
449    }
450}
451
452impl ExactSizeIterator for ModifierInspectorIterator<'_> {}
453
454/// A modifier chain that can be applied to composable elements.
455///
456/// Modifiers allow you to decorate or augment a composable. Common operations include:
457/// - Adjusting layout (e.g., `padding`, `fill_max_size`)
458/// - Adding behavior (e.g., `clickable`, `scrollable`)
459/// - Drawing (e.g., `background`, `border`)
460///
461/// Modifiers are immutable and form a chain using the builder pattern.
462/// The order of modifiers matters: previous modifiers wrap subsequent ones.
463///
464/// # Example
465///
466/// ```rust,ignore
467/// Modifier::padding(16.0)     // Applied first (outer)
468///     .background(Color::Red) // Applied second
469///     .clickable(|| println!("Clicked")) // Applied last (inner)
470/// ```
471#[derive(Clone)]
472pub struct Modifier {
473    kind: ModifierKind,
474    strict_fingerprint: u64,
475    structural_fingerprint: u64,
476    element_count: usize,
477    provides_composition_locals: bool,
478}
479
480impl Default for Modifier {
481    fn default() -> Self {
482        let fingerprints = empty_fingerprints();
483        Self {
484            kind: ModifierKind::Empty,
485            strict_fingerprint: fingerprints.strict,
486            structural_fingerprint: fingerprints.structural,
487            element_count: 0,
488            provides_composition_locals: false,
489        }
490    }
491}
492
493impl Modifier {
494    pub fn empty() -> Self {
495        Self::default()
496    }
497
498    /// Creates a modifier from a custom modifier node element.
499    pub fn from_element<E>(element: E) -> Self
500    where
501        E: ModifierNodeElement,
502    {
503        Self::with_element(element)
504    }
505
506    /// Clip the content to the bounds of this modifier.
507    ///
508    /// Example: `Modifier::empty().clip_to_bounds()`
509    pub fn clip_to_bounds(self) -> Self {
510        let modifier = crate::thread_state::with(|state| {
511            state
512                .clip_to_bounds
513                .get_or_init(|| Modifier::with_element(ClipToBoundsElement::new()))
514                .clone()
515        });
516        let modifier =
517            modifier.with_inspector_metadata(inspector_metadata("clipToBounds", |info| {
518                info.add_property("clipToBounds", "true");
519            }));
520        self.then(modifier)
521    }
522
523    pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
524    where
525        T: 'static,
526        F: Fn() -> T + 'static,
527    {
528        let element = ModifierLocalProviderElement::new(key, value);
529        let modifier = Modifier::from_parts(&[modifier_element(element)]);
530        self.then(modifier)
531    }
532
533    pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
534    where
535        F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
536    {
537        let element = ModifierLocalConsumerElement::new(consumer);
538        let modifier = Modifier::from_parts(&[modifier_element(element)]);
539        self.then(modifier)
540    }
541
542    /// Says what a screen reader reads for this node, as one spec value.
543    ///
544    /// This is [`Modifier::semantics`] with a value in place of a closure.
545    /// Compose has only the closure form, because Kotlin's receiver lambda
546    /// makes `semantics { contentDescription = "Save" }` read well; Rust has
547    /// none, so a spec value reads better, costs one chain element rather
548    /// than one per property, and can be compared with another.
549    ///
550    /// Example:
551    /// `Modifier::empty().semantics_spec(SemanticsSpec::new().content_description("Amount").error("needs a number"))`
552    pub fn semantics_spec(self, spec: cranpose_foundation::SemanticsSpec) -> Self {
553        self.stable_semantics(move |config: &mut SemanticsConfiguration| config.merge(&spec))
554    }
555
556    /// Records what a screen reader reads for this node. The recorder may
557    /// read live state, so every semantics update runs it again; one whose
558    /// answer changes without the node changing can say so with a
559    /// [`SemanticsRequester`](crate::SemanticsRequester).
560    pub fn semantics<F>(self, recorder: F) -> Self
561    where
562        F: Fn(&mut SemanticsConfiguration) + 'static,
563    {
564        self.semantics_recorder(std::rc::Rc::new(recorder), true)
565    }
566
567    /// [`Modifier::semantics`] for a recorder that reads nothing but what it
568    /// captured. Its answer changes only when the modifier is set again, which
569    /// invalidates the node's semantics, so a semantics update keeps what it
570    /// reported instead of running it.
571    ///
572    /// Example: `Modifier::empty().stable_semantics(move |config| config.content_description = Some(label.clone()))`
573    pub fn stable_semantics<F>(self, recorder: F) -> Self
574    where
575        F: Fn(&mut SemanticsConfiguration) + 'static,
576    {
577        self.semantics_recorder(std::rc::Rc::new(recorder), false)
578    }
579
580    fn semantics_recorder(
581        self,
582        recorder: std::rc::Rc<dyn Fn(&mut SemanticsConfiguration)>,
583        reads_live_state: bool,
584    ) -> Self {
585        let metadata = if inspector_metadata_enabled() {
586            let mut preview = SemanticsConfiguration::default();
587            recorder(&mut preview);
588            let description = preview.content_description.clone();
589            let state_description = preview.state_description.clone();
590            let role = preview.role;
591            let is_clickable = preview.is_activatable();
592            let canvas_children = preview.canvas_children.len();
593            inspector_metadata("semantics", move |info| {
594                if let Some(desc) = &description {
595                    info.add_property("contentDescription", desc.clone());
596                }
597                if let Some(state) = &state_description {
598                    info.add_property("stateDescription", state.clone());
599                }
600                if let Some(role) = role {
601                    info.add_property("role", format!("{role:?}"));
602                }
603                if is_clickable {
604                    info.add_property("isClickable", "true");
605                }
606                if canvas_children > 0 {
607                    info.add_property("canvasSemanticsChildren", canvas_children.to_string());
608                }
609            })
610        } else {
611            inspector_metadata("semantics", |_| {})
612        };
613        let element = SemanticsElement::new(recorder, reads_live_state);
614        let modifier =
615            Modifier::from_parts(&[modifier_element(element)]).with_inspector_metadata(metadata);
616        self.then(modifier)
617    }
618
619    /// Tells a screen reader the value this control holds inside a range, so
620    /// it reads the value and offers its own way to change it.
621    ///
622    /// This is Compose's `Modifier.progressSemantics(value, valueRange,
623    /// steps)`. Without it a slider reads as text and a person who cannot see
624    /// the screen has no way to move it.
625    ///
626    /// Example: `Modifier::empty().progress_semantics(0.35, 0.0, 1.0, 0)`
627    pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
628        let info = ProgressBarRangeInfo::new(current, start, end, steps);
629        self.stable_semantics(move |config| config.progress = Some(info))
630    }
631
632    /// Marks this control as one that opens a list of choices, so a reader
633    /// says "combo box" rather than "button" and knows to look for the
634    /// choice it holds. Compose's `Role.DropdownList`.
635    pub fn dropdown_list(self) -> Self {
636        self.role(cranpose_foundation::SemanticsWidgetRole::DropdownList)
637    }
638
639    /// Marks this control as one that holds one value out of an ordered set,
640    /// so a reader steps through them. Compose's `Role.ValuePicker`.
641    pub fn value_picker(self) -> Self {
642        self.role(cranpose_foundation::SemanticsWidgetRole::ValuePicker)
643    }
644
645    /// Says what this control does when a screen reader asks it to open, and
646    /// marks it as closed right now: a reader offers "expand" and says the
647    /// control is collapsed. Compose's
648    /// `Modifier.semantics { expand { … } }`.
649    pub fn expand(self, action: impl Fn() -> bool + 'static) -> Self {
650        let action = cranpose_foundation::SemanticsExpand::new(action);
651        self.stable_semantics(move |config| config.expand = Some(action.clone()))
652    }
653
654    /// Says what a long press on this control does, so a screen reader can
655    /// ask for it and read the label out first: "Remove receipt". Compose's
656    /// `Modifier.semantics { onLongClick("Remove receipt") { … } }`, which
657    /// `Modifier.combinedClickable(onLongClickLabel = …)` fills in for a
658    /// control that takes a long press from a finger too.
659    ///
660    /// The label is asked for, not optional as in Compose: Android is the one
661    /// platform of the four with a long press of its own, and the other three
662    /// list the action by name, so a nameless one reads as nothing.
663    pub fn on_long_click(
664        self,
665        label: impl Into<String>,
666        action: impl Fn() -> bool + 'static,
667    ) -> Self {
668        let label = label.into();
669        let action = cranpose_foundation::SemanticsLongClick::new(action);
670        self.stable_semantics(move |config| {
671            config.on_long_click_label = Some(label.clone());
672            config.on_long_click = Some(action.clone());
673        })
674    }
675
676    /// Says what this control does on VoiceOver's magic tap, the two finger
677    /// double tap for the main action of a screen, and the verb phrase the
678    /// other platforms list it under: "Take the photo". SwiftUI's
679    /// `accessibilityAction(.magicTap)`.
680    pub fn on_magic_tap(
681        self,
682        label: impl Into<String>,
683        action: impl Fn() -> bool + 'static,
684    ) -> Self {
685        let label = label.into();
686        let action = cranpose_foundation::SemanticsMagicTap::new(action);
687        self.stable_semantics(move |config| {
688            config.on_magic_tap_label = Some(label.clone());
689            config.on_magic_tap = Some(action.clone());
690        })
691    }
692
693    /// The short names a person says to Voice Control to reach this control,
694    /// when the name a reader hears is too long to say. SwiftUI's
695    /// `accessibilityInputLabels`.
696    pub fn input_labels<S: Into<String>>(self, labels: impl IntoIterator<Item = S>) -> Self {
697        let labels: Vec<String> = labels.into_iter().map(Into::into).collect();
698        self.stable_semantics(move |config| config.input_labels.clone_from(&labels))
699    }
700
701    /// The language of this control's text, as a BCP 47 tag such as "de" or
702    /// "pt-BR", so a reader picks the right voice. SwiftUI's
703    /// `accessibilityLanguage`, ARIA's `lang`.
704    pub fn language(self, tag: impl Into<String>) -> Self {
705        let tag = tag.into();
706        self.stable_semantics(move |config| config.language = Some(tag.clone()))
707    }
708
709    /// Says what this control does when a screen reader asks it to close, and
710    /// marks it as open right now. Compose's
711    /// `Modifier.semantics { collapse { … } }`.
712    pub fn collapse(self, action: impl Fn() -> bool + 'static) -> Self {
713        let action = cranpose_foundation::SemanticsExpand::new(action);
714        self.stable_semantics(move |config| config.collapse = Some(action.clone()))
715    }
716
717    /// Says what this control does when a screen reader asks to send it away:
718    /// a row a sighted person swipes off, a sheet a sighted person taps
719    /// outside of. A reader that cannot make the gesture gets the same way
720    /// out. Compose's `Modifier.semantics { dismiss { … } }`.
721    pub fn dismiss(self, action: impl Fn() -> bool + 'static) -> Self {
722        let action = cranpose_foundation::SemanticsDismiss::new(action);
723        self.stable_semantics(move |config| config.dismiss = Some(action.clone()))
724    }
725
726    /// Says what this list does when a screen reader asks for the row at an
727    /// index, so a reader reaches row 300 of a long list at once instead of
728    /// paging to it. The index counts rows from zero and the answer says
729    /// whether the list moved. `LazyColumn` and `LazyRow` declare it on their
730    /// own. Compose's `Modifier.semantics { scrollToIndex { … } }`.
731    pub fn scroll_to_index(self, action: impl Fn(usize) -> bool + 'static) -> Self {
732        let action = cranpose_foundation::SemanticsScrollToIndex::new(action);
733        self.stable_semantics(move |config| config.scroll_to_index = Some(action.clone()))
734    }
735
736    /// Moves this node in the order a screen reader visits the nodes beside
737    /// it: a smaller number comes first, and a node left alone keeps the
738    /// order the app laid it out in. A search field drawn last but meant to
739    /// be read first takes a negative number. Compose's
740    /// `Modifier.semantics { traversalIndex = -1f }`.
741    pub fn traversal_index(self, index: f32) -> Self {
742        self.stable_semantics(move |config| config.traversal_index = index)
743    }
744
745    /// Marks a field as one that holds a secret, so no screen reader reads
746    /// its text out: a reader hears the name the app gave the field, and
747    /// "password" in place of the text. Compose's
748    /// `Modifier.semantics { password() }`.
749    pub fn password(self) -> Self {
750        self.stable_semantics(|config| config.password = true)
751    }
752
753    /// Says why the control's content is wrong, so a screen reader reads
754    /// "invalid, the amount needs a number" after the control's state.
755    /// Compose's `Modifier.semantics { error("...") }`.
756    pub fn error(self, message: impl Into<String>) -> Self {
757        let message = message.into();
758        self.stable_semantics(move |config| config.error = Some(message.clone()))
759    }
760
761    /// Names the screen or pane this node is the root of, so a screen reader
762    /// hears where it is when the app moves on: "Library" as the library
763    /// opens. Compose's `Modifier.semantics { paneTitle = "..." }`.
764    pub fn pane_title(self, title: impl Into<String>) -> Self {
765        let title = title.into();
766        self.stable_semantics(move |config| config.pane_title = Some(title.clone()))
767    }
768
769    /// Makes the selectable controls under this node one group, so a screen
770    /// reader says which of how many a tab or a radio button is: "Library,
771    /// tab, 2 of 5". `LiquidTabBar` declares it on its own. Compose's
772    /// `Modifier.selectableGroup()`.
773    pub fn selectable_group(self) -> Self {
774        self.stable_semantics(|config| config.selectable_group = true)
775    }
776
777    /// Makes a screen reader take this node and the text under it as one
778    /// stop, the way it does for a button: a row whose name, count and price
779    /// belong together reads as "Milk, 2, 3.40" and not as three stops.
780    /// Compose's `Modifier.semantics(mergeDescendants = true) {}`.
781    pub fn merge_descendants(self) -> Self {
782        self.stable_semantics(|config| config.merge_descendants = true)
783    }
784
785    /// Takes this node and everything under it out of what a screen reader
786    /// sees: a decorative image, or a placeholder drawn under a field that
787    /// carries the same words as its name. Compose's
788    /// `semantics { hideFromAccessibility() }`.
789    pub fn hide_from_accessibility(self) -> Self {
790        self.stable_semantics(|config| config.hidden = true)
791    }
792
793    /// Marks this component as a heading, so a screen reader lists it among
794    /// the headings of the screen and a person can jump between them.
795    ///
796    /// This is Compose's `Modifier.semantics { heading() }`.
797    pub fn heading(self) -> Self {
798        self.role(cranpose_foundation::SemanticsWidgetRole::Header)
799    }
800
801    /// Tells a screen reader what kind of control this is, when the widget
802    /// does not say so on its own.
803    ///
804    /// This is Compose's `Modifier.semantics { role = Role.Button }`.
805    pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
806        self.stable_semantics(move |config| config.role = Some(role))
807    }
808
809    /// Makes a screen reader read this component's text out whenever it
810    /// changes, without the reader's cursor on it: a status line, a toast, a
811    /// count that moves.
812    ///
813    /// This is Compose's `Modifier.semantics { liveRegion = LiveRegionMode.Polite }`.
814    pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
815        self.stable_semantics(move |config| config.live_region = Some(mode))
816    }
817
818    /// Gives this component the text a screen reader reads for it, for a
819    /// drawing, an icon or a control with no text of its own.
820    ///
821    /// This is Compose's `Modifier.semantics { contentDescription = "..." }`.
822    pub fn content_description(self, description: impl Into<String>) -> Self {
823        let description = description.into();
824        self.stable_semantics(move |config| config.content_description = Some(description.clone()))
825    }
826
827    /// Names this component for tests, which find it by the name instead of
828    /// its text or position. Screen readers never receive the name.
829    ///
830    /// This is Compose's `Modifier.testTag(tag)`.
831    pub fn test_tag(self, tag: impl Into<String>) -> Self {
832        let tag = tag.into();
833        self.stable_semantics(move |config| config.test_tag = Some(tag.clone()))
834    }
835
836    /// Makes this component focusable.
837    ///
838    /// This adds a focus target node that can receive focus and participate
839    /// in focus traversal. The component will be included in tab order and
840    /// can be focused programmatically.
841    pub fn focus_target(self) -> Self {
842        let element = FocusTargetElement::new();
843        let modifier = Modifier::from_parts(&[modifier_element(element)]);
844        self.then(modifier)
845    }
846
847    /// Makes this component focusable with a callback for focus changes.
848    ///
849    /// The callback is invoked whenever the focus state changes, allowing
850    /// components to react to gaining or losing focus.
851    pub fn on_focus_changed<F>(self, callback: F) -> Self
852    where
853        F: Fn(FocusState) + 'static,
854    {
855        let element = FocusTargetElement::with_callback(callback);
856        let modifier = Modifier::from_parts(&[modifier_element(element)]);
857        self.then(modifier)
858    }
859
860    /// Binds a [`FocusRequester`] to this node, so an app can move focus onto
861    /// it imperatively with [`FocusRequester::request_focus`].
862    ///
863    /// Pair it with [`focus_target`](Self::focus_target) (or
864    /// [`on_focus_changed`](Self::on_focus_changed)) on the same node —
865    /// `request_focus` moves whichever focus targets are attached there.
866    pub fn focus_requester(self, requester: &FocusRequester) -> Self {
867        let element = FocusRequesterElement::new(requester.clone());
868        let modifier = Modifier::from_parts(&[modifier_element(element)]);
869        self.then(modifier)
870    }
871
872    /// Binds a [`SemanticsRequester`] to this node, so an app can mark the
873    /// node's semantics for re-collection without recomposing or laying out.
874    ///
875    /// Pair it with [`semantics`](Self::semantics) on the same node when the
876    /// recorder reads state the composition does not observe — app state behind
877    /// a `RefCell`, a game's own model — which is the case a recorder cannot
878    /// signal for itself.
879    pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
880        let element = SemanticsRequesterElement::new(requester.clone());
881        let modifier = Modifier::from_parts(&[modifier_element(element)]);
882        self.then(modifier)
883    }
884
885    /// Enables debug logging for this modifier chain.
886    ///
887    /// When enabled, logs the entire modifier chain structure including:
888    /// - Element types and their properties
889    /// - Inspector metadata
890    /// - Capability flags
891    ///
892    /// This is useful for debugging modifier composition issues and understanding
893    /// how the modifier chain is structured at runtime.
894    ///
895    /// Example:
896    /// ```text
897    /// Modifier::empty()
898    ///     .padding(8.0)
899    ///     .background(Color(1.0, 0.0, 0.0, 1.0))
900    ///     .debug_chain("MyWidget")
901    /// ```
902    pub fn debug_chain(self, tag: &'static str) -> Self {
903        use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
904
905        #[derive(Clone)]
906        struct DebugChainElement {
907            tag: &'static str,
908        }
909
910        impl fmt::Debug for DebugChainElement {
911            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912                f.debug_struct("DebugChainElement")
913                    .field("tag", &self.tag)
914                    .finish()
915            }
916        }
917
918        impl PartialEq for DebugChainElement {
919            fn eq(&self, other: &Self) -> bool {
920                self.tag == other.tag
921            }
922        }
923
924        impl Eq for DebugChainElement {}
925
926        impl std::hash::Hash for DebugChainElement {
927            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
928                self.tag.hash(state);
929            }
930        }
931
932        impl ModifierNodeElement for DebugChainElement {
933            type Node = DebugChainNode;
934
935            fn create(&self) -> Self::Node {
936                DebugChainNode::new(self.tag)
937            }
938
939            fn update(&self, node: &mut Self::Node) {
940                node.tag = self.tag;
941            }
942
943            fn capabilities(&self) -> NodeCapabilities {
944                NodeCapabilities::empty()
945            }
946        }
947
948        struct DebugChainNode {
949            tag: &'static str,
950            state: NodeState,
951        }
952
953        impl DebugChainNode {
954            fn new(tag: &'static str) -> Self {
955                Self {
956                    tag,
957                    state: NodeState::new(),
958                }
959            }
960        }
961
962        impl ModifierNode for DebugChainNode {
963            fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
964                eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
965            }
966
967            fn on_detach(&mut self) {
968                eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
969            }
970
971            fn on_reset(&mut self) {
972                eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
973            }
974        }
975
976        impl cranpose_foundation::DelegatableNode for DebugChainNode {
977            fn node_state(&self) -> &NodeState {
978                &self.state
979            }
980        }
981
982        let element = DebugChainElement { tag };
983        let modifier = Modifier::from_parts(&[modifier_element(element)]);
984        self.then(modifier)
985            .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
986                info.add_property("tag", tag);
987            }))
988    }
989
990    /// This modifier followed by `next`.
991    ///
992    /// It takes `self`: a modifier built link by link owns its elements
993    /// alone, so each link joins them in place instead of copying the chain.
994    /// Clone a modifier first to keep using it; the join then copies it.
995    pub fn then(self, next: Modifier) -> Modifier {
996        let Modifier {
997            kind,
998            strict_fingerprint,
999            structural_fingerprint,
1000            element_count,
1001            provides_composition_locals,
1002        } = self;
1003        let ModifierKind::Single {
1004            mut elements,
1005            inspector,
1006        } = kind
1007        else {
1008            return next;
1009        };
1010        let ModifierKind::Single {
1011            elements: next_elements,
1012            inspector: next_inspector,
1013        } = &next.kind
1014        else {
1015            return Modifier {
1016                kind: ModifierKind::Single {
1017                    elements,
1018                    inspector,
1019                },
1020                strict_fingerprint,
1021                structural_fingerprint,
1022                element_count,
1023                provides_composition_locals,
1024            };
1025        };
1026
1027        let fingerprints = append_fingerprints(
1028            ModifierFingerprints {
1029                strict: strict_fingerprint,
1030                structural: structural_fingerprint,
1031            },
1032            next_elements,
1033        );
1034        elements.extend_from(next_elements);
1035        let inspector = if next_inspector.is_none() {
1036            inspector
1037        } else {
1038            merged_inspector(inspector_slice(&inspector), inspector_slice(next_inspector))
1039        };
1040        Modifier {
1041            kind: ModifierKind::Single {
1042                elements,
1043                inspector,
1044            },
1045            strict_fingerprint: fingerprints.strict,
1046            structural_fingerprint: fingerprints.structural,
1047            element_count: element_count + next.element_count,
1048            provides_composition_locals: provides_composition_locals
1049                || next.provides_composition_locals,
1050        }
1051    }
1052
1053    /// How many elements the modifier holds.
1054    pub(crate) fn element_count(&self) -> usize {
1055        self.element_count
1056    }
1057
1058    pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
1059        match &self.kind {
1060            ModifierKind::Empty => ModifierElementIterator { inner: [].iter() },
1061            ModifierKind::Single { elements, .. } => ModifierElementIterator {
1062                inner: elements.iter(),
1063            },
1064        }
1065    }
1066
1067    pub(crate) fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
1068        if !self.provides_composition_locals {
1069            return Vec::new();
1070        }
1071        self.iter_elements()
1072            .flat_map(|element| element.provided_composition_locals())
1073            .collect()
1074    }
1075
1076    pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
1077        match &self.kind {
1078            ModifierKind::Empty => ModifierInspectorIterator { inner: [].iter() },
1079            ModifierKind::Single { inspector, .. } => ModifierInspectorIterator {
1080                inner: inspector_slice(inspector).iter(),
1081            },
1082        }
1083    }
1084
1085    #[cfg(test)]
1086    pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
1087        match &self.kind {
1088            ModifierKind::Empty => Vec::new(),
1089            ModifierKind::Single { elements, .. } => elements.to_vec(),
1090        }
1091    }
1092
1093    pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
1094        match &self.kind {
1095            ModifierKind::Empty => Vec::new(),
1096            ModifierKind::Single { inspector, .. } => {
1097                inspector.as_deref().map(<[_]>::to_vec).unwrap_or_default()
1098            }
1099        }
1100    }
1101
1102    pub fn total_padding(&self) -> f32 {
1103        let padding = self.padding_values();
1104        padding
1105            .left
1106            .max(padding.right)
1107            .max(padding.top)
1108            .max(padding.bottom)
1109    }
1110
1111    pub fn explicit_size(&self) -> Option<Size> {
1112        let props = self.layout_properties();
1113        match (props.width, props.height) {
1114            (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
1115                Some(Size { width, height })
1116            }
1117            _ => None,
1118        }
1119    }
1120
1121    pub fn padding_values(&self) -> EdgeInsets {
1122        self.resolved_modifiers().padding()
1123    }
1124
1125    pub(crate) fn layout_properties(&self) -> LayoutProperties {
1126        self.resolved_modifiers().layout_properties()
1127    }
1128
1129    pub fn box_alignment(&self) -> Option<Alignment> {
1130        self.layout_properties().box_alignment()
1131    }
1132
1133    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1134        self.layout_properties().column_alignment()
1135    }
1136
1137    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1138        self.layout_properties().row_alignment()
1139    }
1140
1141    pub fn draw_commands(&self) -> Vec<DrawCommand> {
1142        collect_slices_from_modifier(self).draw_commands().to_vec()
1143    }
1144
1145    pub fn clips_to_bounds(&self) -> bool {
1146        collect_slices_from_modifier(self).clip_to_bounds()
1147    }
1148
1149    /// Returns structured inspector records for each modifier element.
1150    pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
1151        self.inspector_metadata()
1152            .iter()
1153            .map(InspectorMetadata::to_record)
1154            .collect()
1155    }
1156
1157    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
1158        let mut handle = ModifierChainHandle::new();
1159        let _ = handle.update(self);
1160        handle.resolved_modifiers()
1161    }
1162
1163    /// A modifier of the one `element`. Platform crates build their own
1164    /// modifiers on it, the way [`Modifier::window_root`] is built.
1165    pub fn with_element<E>(element: E) -> Self
1166    where
1167        E: ModifierNodeElement,
1168    {
1169        Self::from_parts(&[modifier_element(element)])
1170    }
1171
1172    /// A modifier of `elements`, held in one shared allocation.
1173    pub(crate) fn from_parts(elements: &[DynModifierElement]) -> Self {
1174        if elements.is_empty() {
1175            Self::default()
1176        } else {
1177            let element_count = elements.len();
1178            let provides_composition_locals = elements
1179                .iter()
1180                .any(|element| element.provides_composition_locals());
1181            let fingerprints = single_fingerprints(elements);
1182            Self {
1183                kind: ModifierKind::Single {
1184                    elements: Elements::from_slice(elements),
1185                    inspector: None,
1186                },
1187                strict_fingerprint: fingerprints.strict,
1188                structural_fingerprint: fingerprints.structural,
1189                element_count,
1190                provides_composition_locals,
1191            }
1192        }
1193    }
1194
1195    pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
1196        if metadata.is_empty() {
1197            return self;
1198        }
1199        match self.kind {
1200            ModifierKind::Empty => self,
1201            ModifierKind::Single {
1202                elements,
1203                inspector,
1204            } => {
1205                let new_inspector = inspector_slice(&inspector)
1206                    .iter()
1207                    .cloned()
1208                    .chain(std::iter::once(metadata))
1209                    .collect();
1210                Self {
1211                    kind: ModifierKind::Single {
1212                        elements,
1213                        inspector: Some(new_inspector),
1214                    },
1215                    strict_fingerprint: self.strict_fingerprint,
1216                    structural_fingerprint: self.structural_fingerprint,
1217                    element_count: self.element_count,
1218                    provides_composition_locals: self.provides_composition_locals,
1219                }
1220            }
1221        }
1222    }
1223
1224    /// Checks whether two modifiers are structurally equivalent for layout decisions.
1225    ///
1226    /// This ignores identity-sensitive modifier elements (e.g., draw closures) so
1227    /// draw-only updates do not force measure/layout invalidation.
1228    pub fn structural_eq(&self, other: &Self) -> bool {
1229        self.eq_internal(other, false)
1230    }
1231
1232    /// Whether `other` has this modifier's elements in the same order, equal
1233    /// except elements of type `E`, which may differ. An element that asks
1234    /// for an update on every set counts as different.
1235    pub(crate) fn differs_only_in<E: 'static>(&self, other: &Self) -> bool {
1236        if self.element_count != other.element_count {
1237            return false;
1238        }
1239        let differing = std::any::TypeId::of::<E>();
1240        self.iter_elements()
1241            .zip(other.iter_elements())
1242            .all(|(a, b)| {
1243                if a.requires_update() || b.requires_update() {
1244                    false
1245                } else if a.element_type() == differing {
1246                    b.element_type() == differing
1247                } else {
1248                    a.equals_element(&**b)
1249                }
1250            })
1251    }
1252
1253    fn eq_internal(&self, other: &Self, consider_always_update: bool) -> bool {
1254        if self.element_count != other.element_count {
1255            return false;
1256        }
1257        if consider_always_update {
1258            if self.strict_fingerprint != other.strict_fingerprint {
1259                return false;
1260            }
1261        } else if self.structural_fingerprint != other.structural_fingerprint {
1262            return false;
1263        }
1264
1265        match (&self.kind, &other.kind) {
1266            (ModifierKind::Empty, ModifierKind::Empty) => true,
1267            (
1268                ModifierKind::Single {
1269                    elements: e1,
1270                    inspector: _,
1271                },
1272                ModifierKind::Single {
1273                    elements: e2,
1274                    inspector: _,
1275                },
1276            ) => {
1277                if e1.shares_storage(e2) {
1278                    return true;
1279                }
1280
1281                if e1.len() != e2.len() {
1282                    return false;
1283                }
1284
1285                for (a, b) in e1.iter().zip(e2.iter()) {
1286                    if !consider_always_update
1287                        && a.element_type() == b.element_type()
1288                        && a.capabilities() == NodeCapabilities::DRAW
1289                        && b.capabilities() == NodeCapabilities::DRAW
1290                    {
1291                        continue;
1292                    }
1293
1294                    if consider_always_update && (a.requires_update() || b.requires_update()) {
1295                        if !Rc::ptr_eq(a, b) {
1296                            return false;
1297                        }
1298                        continue;
1299                    }
1300
1301                    if !a.equals_element(&**b) {
1302                        return false;
1303                    }
1304                }
1305
1306                true
1307            }
1308            _ => false,
1309        }
1310    }
1311}
1312
1313impl PartialEq for Modifier {
1314    fn eq(&self, other: &Self) -> bool {
1315        self.eq_internal(other, true)
1316    }
1317}
1318
1319impl Eq for Modifier {}
1320
1321impl fmt::Display for Modifier {
1322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1323        match &self.kind {
1324            ModifierKind::Empty => write!(f, "Modifier.empty"),
1325            ModifierKind::Single { elements, .. } => {
1326                if elements.is_empty() {
1327                    return write!(f, "Modifier.empty");
1328                }
1329                write!(f, "Modifier[")?;
1330                for (index, element) in elements.iter().enumerate() {
1331                    if index > 0 {
1332                        write!(f, ", ")?;
1333                    }
1334                    let name = element.inspector_name();
1335                    let mut properties = Vec::new();
1336                    element.record_inspector_properties(&mut |prop, value| {
1337                        properties.push(format!("{prop}={value}"));
1338                    });
1339                    if properties.is_empty() {
1340                        write!(f, "{name}")?;
1341                    } else {
1342                        write!(f, "{name}({})", properties.join(", "))?;
1343                    }
1344                }
1345                write!(f, "]")
1346            }
1347        }
1348    }
1349}
1350
1351impl fmt::Debug for Modifier {
1352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1353        fmt::Display::fmt(self, f)
1354    }
1355}
1356
1357#[derive(Clone, Copy, Debug, PartialEq)]
1358pub struct ResolvedBackground {
1359    color: Color,
1360    shape: Option<RoundedCornerShape>,
1361}
1362
1363impl ResolvedBackground {
1364    pub fn new(color: Color, shape: Option<RoundedCornerShape>) -> Self {
1365        Self { color, shape }
1366    }
1367
1368    pub fn color(&self) -> Color {
1369        self.color
1370    }
1371
1372    pub fn shape(&self) -> Option<RoundedCornerShape> {
1373        self.shape
1374    }
1375
1376    pub fn set_shape(&mut self, shape: Option<RoundedCornerShape>) {
1377        self.shape = shape;
1378    }
1379}
1380
1381#[derive(Clone, Copy, Debug, PartialEq, Default)]
1382pub struct ResolvedModifiers {
1383    padding: EdgeInsets,
1384    layout: LayoutProperties,
1385    offset: Point,
1386}
1387
1388impl ResolvedModifiers {
1389    pub fn padding(&self) -> EdgeInsets {
1390        self.padding
1391    }
1392
1393    pub fn layout_properties(&self) -> LayoutProperties {
1394        self.layout
1395    }
1396
1397    pub fn offset(&self) -> Point {
1398        self.offset
1399    }
1400
1401    pub(crate) fn set_padding(&mut self, padding: EdgeInsets) {
1402        self.padding = padding;
1403    }
1404
1405    pub(crate) fn set_layout_properties(&mut self, layout: LayoutProperties) {
1406        self.layout = layout;
1407    }
1408
1409    pub(crate) fn set_offset(&mut self, offset: Point) {
1410        self.offset = offset;
1411    }
1412
1413    /// These modifiers with every length on a whole device pixel of
1414    /// `density`, as Compose's `roundToPx` puts padding, sizes and offsets.
1415    pub(crate) fn on_device_grid(&self, density: f32) -> Self {
1416        use cranpose_ui_layout::round_to_px;
1417
1418        let round = |value: Option<f32>| value.map(|value| round_to_px(value, density));
1419        let dimension = |dimension: DimensionConstraint| match dimension {
1420            DimensionConstraint::Points(value) => {
1421                DimensionConstraint::Points(round_to_px(value, density))
1422            }
1423            other => other,
1424        };
1425        Self {
1426            padding: crate::modifier_nodes::device_padding(self.padding, density),
1427            layout: LayoutProperties {
1428                padding: crate::modifier_nodes::device_padding(self.layout.padding, density),
1429                width: dimension(self.layout.width),
1430                height: dimension(self.layout.height),
1431                min_width: round(self.layout.min_width),
1432                min_height: round(self.layout.min_height),
1433                max_width: round(self.layout.max_width),
1434                max_height: round(self.layout.max_height),
1435                ..self.layout
1436            },
1437            offset: Point {
1438                x: round_to_px(self.offset.x, density),
1439                y: round_to_px(self.offset.y, density),
1440            },
1441        }
1442    }
1443}
1444
1445#[derive(Clone, Copy, Debug, Default, PartialEq)]
1446pub enum DimensionConstraint {
1447    #[default]
1448    Unspecified,
1449    Points(f32),
1450    Fraction(f32),
1451    Intrinsic(IntrinsicSize),
1452}
1453
1454#[derive(Clone, Copy, Debug, Default, PartialEq)]
1455pub struct LayoutWeight {
1456    pub weight: f32,
1457    pub fill: bool,
1458}
1459
1460#[derive(Clone, Copy, Debug, Default, PartialEq)]
1461pub struct LayoutProperties {
1462    padding: EdgeInsets,
1463    width: DimensionConstraint,
1464    height: DimensionConstraint,
1465    min_width: Option<f32>,
1466    min_height: Option<f32>,
1467    max_width: Option<f32>,
1468    max_height: Option<f32>,
1469    weight: Option<LayoutWeight>,
1470    box_alignment: Option<Alignment>,
1471    column_alignment: Option<HorizontalAlignment>,
1472    row_alignment: Option<VerticalAlignment>,
1473    row_baseline: bool,
1474}
1475
1476impl LayoutProperties {
1477    pub fn padding(&self) -> EdgeInsets {
1478        self.padding
1479    }
1480
1481    pub fn width(&self) -> DimensionConstraint {
1482        self.width
1483    }
1484
1485    pub fn height(&self) -> DimensionConstraint {
1486        self.height
1487    }
1488
1489    pub fn min_width(&self) -> Option<f32> {
1490        self.min_width
1491    }
1492
1493    pub fn min_height(&self) -> Option<f32> {
1494        self.min_height
1495    }
1496
1497    pub fn max_width(&self) -> Option<f32> {
1498        self.max_width
1499    }
1500
1501    pub fn max_height(&self) -> Option<f32> {
1502        self.max_height
1503    }
1504
1505    pub fn weight(&self) -> Option<LayoutWeight> {
1506        self.weight
1507    }
1508
1509    pub fn box_alignment(&self) -> Option<Alignment> {
1510        self.box_alignment
1511    }
1512
1513    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1514        self.column_alignment
1515    }
1516
1517    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1518        self.row_alignment
1519    }
1520
1521    /// Whether the parent Row aligns this child's first baseline with its siblings.
1522    pub fn row_baseline(&self) -> bool {
1523        self.row_baseline
1524    }
1525}
1526
1527#[cfg(test)]
1528#[path = "tests/modifier_tests.rs"]
1529mod tests;