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
8#![allow(non_snake_case)]
9
10use std::{
11    fmt,
12    hash::{Hash, Hasher},
13    rc::Rc,
14};
15
16use cranpose_core::hash::default;
17
18mod alignment;
19mod background;
20mod blur;
21mod chain;
22mod clickable;
23mod draw_cache;
24mod fill;
25mod focus;
26mod graphics_layer;
27mod local;
28mod offset;
29mod padding;
30pub(crate) mod pointer_input;
31mod rotary_input;
32mod scroll;
33mod semantics;
34mod shadow;
35mod size;
36mod slices;
37mod toggleable;
38mod weight;
39
40#[allow(unused_imports)]
41pub use chain::{ModifierChainHandle, ModifierChainInspectorNode, ModifierLocalsHandle};
42pub use cranpose_foundation::{
43    AnyModifierElement, DynModifierElement, FocusState, PointerEvent, PointerEventKind,
44    PointerSource, RotaryScrollEvent, SemanticsConfiguration, modifier_element,
45};
46use cranpose_foundation::{ModifierNodeElement, NodeCapabilities};
47#[allow(unused_imports)]
48pub use cranpose_ui_graphics::{
49    BlendMode, BlurredEdgeTreatment, Brush, Color, ColorFilter, CompositingStrategy, CornerRadii,
50    CutDirection, Dp, DpOffset, EdgeInsets, GradientCutMaskSpec, GradientFadeMaskSpec,
51    GraphicsLayer, LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader,
52    Shadow, ShadowScope, Size, TransformOrigin,
53};
54use cranpose_ui_layout::{Alignment, HorizontalAlignment, IntrinsicSize, VerticalAlignment};
55#[allow(unused_imports)]
56pub use focus::FocusDirection;
57use focus::FocusTargetElement;
58pub use graphics_layer::GlassMaterial;
59pub(crate) use local::{
60    ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
61};
62use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
63#[allow(unused_imports)]
64pub use local::{ModifierLocalKey, ModifierLocalReadScope};
65#[allow(unused_imports)]
66pub use pointer_input::{AwaitPointerEventScope, PointerInputScope};
67pub use rotary_input::RotaryInputModifierNode;
68#[cfg(feature = "test-helpers")]
69pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
70use semantics::SemanticsElement;
71pub use semantics::{
72    SemanticsRequester, SemanticsRequesterElement, collect_semantics_from_chain,
73    collect_semantics_from_modifier,
74};
75pub use slices::{
76    ModifierNodeSlices, ModifierNodeSlicesDebugStats, collect_modifier_slices,
77    collect_modifier_slices_into, collect_slices_from_modifier,
78};
79
80pub use crate::draw::{DrawCacheBuilder, DrawCommand};
81use crate::modifier_nodes::ClipToBoundsElement;
82
83#[derive(Clone, Debug, Default)]
84pub struct InspectorInfo {
85    properties: Vec<InspectorProperty>,
86}
87
88impl InspectorInfo {
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    pub fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
94        self.properties.push(InspectorProperty {
95            name,
96            value: value.into(),
97        });
98    }
99
100    pub fn properties(&self) -> &[InspectorProperty] {
101        &self.properties
102    }
103
104    pub fn is_empty(&self) -> bool {
105        self.properties.is_empty()
106    }
107
108    pub fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
109        self.add_property(name, describe_dimension(constraint));
110    }
111
112    pub fn add_offset_components(
113        &mut self,
114        x_name: &'static str,
115        y_name: &'static str,
116        offset: Point,
117    ) {
118        self.add_property(x_name, offset.x.to_string());
119        self.add_property(y_name, offset.y.to_string());
120    }
121
122    pub fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
123    where
124        A: fmt::Debug,
125    {
126        self.add_property(name, format!("{alignment:?}"));
127    }
128}
129
130#[derive(Clone, Debug, PartialEq)]
131pub struct InspectorProperty {
132    pub name: &'static str,
133    pub value: String,
134}
135
136#[derive(Clone, Debug, PartialEq)]
137pub struct ModifierInspectorRecord {
138    pub name: &'static str,
139    pub properties: Vec<InspectorProperty>,
140}
141
142#[derive(Clone, Debug)]
143pub(crate) struct InspectorMetadata {
144    name: &'static str,
145    info: InspectorInfo,
146}
147
148impl InspectorMetadata {
149    pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
150    where
151        F: FnOnce(&mut InspectorInfo),
152    {
153        let mut info = InspectorInfo::new();
154        recorder(&mut info);
155        Self { name, info }
156    }
157
158    fn is_empty(&self) -> bool {
159        self.info.is_empty()
160    }
161
162    fn to_record(&self) -> ModifierInspectorRecord {
163        ModifierInspectorRecord {
164            name: self.name,
165            properties: self.info.properties().to_vec(),
166        }
167    }
168}
169
170fn describe_dimension(constraint: DimensionConstraint) -> String {
171    match constraint {
172        DimensionConstraint::Unspecified => "unspecified".to_string(),
173        DimensionConstraint::Points(value) => value.to_string(),
174        DimensionConstraint::Fraction(value) => format!("fraction({value})"),
175        DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
176    }
177}
178
179pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
180where
181    F: FnOnce(&mut InspectorInfo),
182{
183    if !inspector_metadata_enabled() {
184        return InspectorMetadata::new(name, |_| {});
185    }
186    InspectorMetadata::new(name, recorder)
187}
188
189pub(crate) fn modifier_debug_enabled() -> bool {
190    #[cfg(not(target_arch = "wasm32"))]
191    {
192        cranpose_core::env_flag!("COMPOSE_DEBUG_MODIFIERS")
193    }
194    #[cfg(target_arch = "wasm32")]
195    {
196        false
197    }
198}
199
200fn inspector_metadata_enabled() -> bool {
201    cfg!(test) || modifier_debug_enabled()
202}
203
204#[derive(Clone)]
205enum ModifierKind {
206    Empty,
207    Single {
208        elements: Rc<Vec<DynModifierElement>>,
209        inspector: Rc<Vec<InspectorMetadata>>,
210    },
211}
212
213const FINGERPRINT_KIND_EMPTY: u8 = 0;
214const FINGERPRINT_KIND_SINGLE: u8 = 1;
215
216const FINGERPRINT_EMPTY_STRICT_SEED: u64 = 0x243f_6a88_85a3_08d3;
217const FINGERPRINT_EMPTY_STRUCTURAL_SEED: u64 = 0x1319_8a2e_0370_7344;
218const FINGERPRINT_SINGLE_STRICT_SEED: u64 = 0xa409_3822_299f_31d0;
219const FINGERPRINT_SINGLE_STRUCTURAL_SEED: u64 = 0x082e_fa98_ec4e_6c89;
220const FINGERPRINT_SEQUENCE_MUL: u64 = 0x9e37_79b1_85eb_ca87;
221const FINGERPRINT_STRICT_UPDATE_TAG: u64 = 0xdbe6_d5d5_fe4c_ce2f;
222const FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG: u64 = 0x94d0_49bb_1331_11eb;
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
225struct ModifierFingerprints {
226    strict: u64,
227    structural: u64,
228}
229
230#[inline]
231fn mix_fingerprint_bits(mut value: u64) -> u64 {
232    value ^= value >> 33;
233    value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
234    value ^= value >> 33;
235    value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
236    value ^ (value >> 33)
237}
238
239#[inline]
240fn fold_fingerprint(state: u64, value: u64) -> u64 {
241    mix_fingerprint_bits(state ^ value.wrapping_add(FINGERPRINT_SEQUENCE_MUL))
242        .wrapping_mul(FINGERPRINT_SEQUENCE_MUL)
243}
244
245#[inline]
246fn empty_fingerprints() -> ModifierFingerprints {
247    ModifierFingerprints {
248        strict: fold_fingerprint(FINGERPRINT_EMPTY_STRICT_SEED, FINGERPRINT_KIND_EMPTY as u64),
249        structural: fold_fingerprint(
250            FINGERPRINT_EMPTY_STRUCTURAL_SEED,
251            FINGERPRINT_KIND_EMPTY as u64,
252        ),
253    }
254}
255
256#[inline]
257fn single_fingerprint_seed() -> ModifierFingerprints {
258    let strict = fold_fingerprint(
259        FINGERPRINT_SINGLE_STRICT_SEED,
260        FINGERPRINT_KIND_SINGLE as u64,
261    );
262    let structural = fold_fingerprint(
263        FINGERPRINT_SINGLE_STRUCTURAL_SEED,
264        FINGERPRINT_KIND_SINGLE as u64,
265    );
266    ModifierFingerprints { strict, structural }
267}
268
269#[inline]
270fn element_common_fingerprint(element: &DynModifierElement) -> u64 {
271    let mut hasher = default::new();
272    element.element_type().hash(&mut hasher);
273    element.capabilities().bits().hash(&mut hasher);
274    hasher.finish()
275}
276
277#[inline]
278fn element_fingerprints(element: &DynModifierElement) -> ModifierFingerprints {
279    let common = element_common_fingerprint(element);
280    let requires_update = element.requires_update();
281    let strict_payload = if requires_update {
282        let element_ptr = Rc::as_ptr(element) as *const () as usize as u64;
283        element_ptr ^ FINGERPRINT_STRICT_UPDATE_TAG
284    } else {
285        element.hash_code()
286    };
287    let strict = mix_fingerprint_bits(common ^ strict_payload);
288
289    let is_draw_only = element.capabilities() == NodeCapabilities::DRAW;
290    let structural_payload = if is_draw_only {
291        FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG
292    } else {
293        element.hash_code()
294    };
295    let structural = mix_fingerprint_bits(common ^ structural_payload);
296
297    ModifierFingerprints { strict, structural }
298}
299
300#[inline]
301fn append_fingerprints(
302    mut fingerprints: ModifierFingerprints,
303    elements: &[DynModifierElement],
304) -> ModifierFingerprints {
305    for element in elements {
306        let element_fingerprints = element_fingerprints(element);
307        fingerprints.strict = fold_fingerprint(fingerprints.strict, element_fingerprints.strict);
308        fingerprints.structural =
309            fold_fingerprint(fingerprints.structural, element_fingerprints.structural);
310    }
311    fingerprints
312}
313
314fn single_fingerprints(elements: &[DynModifierElement]) -> ModifierFingerprints {
315    append_fingerprints(single_fingerprint_seed(), elements)
316}
317
318pub struct ModifierElementIterator<'a> {
319    inner: std::slice::Iter<'a, DynModifierElement>,
320}
321
322impl<'a> Iterator for ModifierElementIterator<'a> {
323    type Item = &'a DynModifierElement;
324
325    #[inline]
326    fn next(&mut self) -> Option<Self::Item> {
327        self.inner.next()
328    }
329
330    #[inline]
331    fn size_hint(&self) -> (usize, Option<usize>) {
332        self.inner.size_hint()
333    }
334}
335
336impl ExactSizeIterator for ModifierElementIterator<'_> {}
337
338pub(crate) struct ModifierInspectorIterator<'a> {
339    inner: std::slice::Iter<'a, InspectorMetadata>,
340}
341
342impl<'a> Iterator for ModifierInspectorIterator<'a> {
343    type Item = &'a InspectorMetadata;
344
345    #[inline]
346    fn next(&mut self) -> Option<Self::Item> {
347        self.inner.next()
348    }
349
350    #[inline]
351    fn size_hint(&self) -> (usize, Option<usize>) {
352        self.inner.size_hint()
353    }
354}
355
356impl ExactSizeIterator for ModifierInspectorIterator<'_> {}
357
358/// A modifier chain that can be applied to composable elements.
359///
360/// Modifiers allow you to decorate or augment a composable. Common operations include:
361/// - Adjusting layout (e.g., `padding`, `fill_max_size`)
362/// - Adding behavior (e.g., `clickable`, `scrollable`)
363/// - Drawing (e.g., `background`, `border`)
364///
365/// Modifiers are immutable and form a chain using the builder pattern.
366/// The order of modifiers matters: previous modifiers wrap subsequent ones.
367///
368/// # Example
369///
370/// ```rust,ignore
371/// Modifier::padding(16.0)     // Applied first (outer)
372///     .background(Color::Red) // Applied second
373///     .clickable(|| println!("Clicked")) // Applied last (inner)
374/// ```
375#[derive(Clone)]
376pub struct Modifier {
377    kind: ModifierKind,
378    strict_fingerprint: u64,
379    structural_fingerprint: u64,
380    element_count: usize,
381}
382
383impl Default for Modifier {
384    fn default() -> Self {
385        let fingerprints = empty_fingerprints();
386        Self {
387            kind: ModifierKind::Empty,
388            strict_fingerprint: fingerprints.strict,
389            structural_fingerprint: fingerprints.structural,
390            element_count: 0,
391        }
392    }
393}
394
395impl Modifier {
396    pub fn empty() -> Self {
397        Self::default()
398    }
399
400    /// Creates a modifier from a custom modifier node element.
401    pub fn from_element<E>(element: E) -> Self
402    where
403        E: ModifierNodeElement,
404    {
405        Self::with_element(element)
406    }
407
408    /// Clip the content to the bounds of this modifier.
409    ///
410    /// Example: `Modifier::empty().clip_to_bounds()`
411    pub fn clip_to_bounds(self) -> Self {
412        let modifier = Self::with_element(ClipToBoundsElement::new()).with_inspector_metadata(
413            inspector_metadata("clipToBounds", |info| {
414                info.add_property("clipToBounds", "true");
415            }),
416        );
417        self.then(modifier)
418    }
419
420    pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
421    where
422        T: 'static,
423        F: Fn() -> T + 'static,
424    {
425        let element = ModifierLocalProviderElement::new(key, value);
426        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
427        self.then(modifier)
428    }
429
430    pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
431    where
432        F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
433    {
434        let element = ModifierLocalConsumerElement::new(consumer);
435        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
436        self.then(modifier)
437    }
438
439    pub fn semantics<F>(self, recorder: F) -> Self
440    where
441        F: Fn(&mut SemanticsConfiguration) + 'static,
442    {
443        let recorder: std::rc::Rc<dyn Fn(&mut SemanticsConfiguration)> = std::rc::Rc::new(recorder);
444        let metadata = if inspector_metadata_enabled() {
445            let mut preview = SemanticsConfiguration::default();
446            recorder(&mut preview);
447            let description = preview.content_description.clone();
448            let state_description = preview.state_description.clone();
449            let role = preview.role;
450            let is_clickable = preview.is_activatable();
451            let canvas_children = preview.canvas_children.len();
452            inspector_metadata("semantics", move |info| {
453                if let Some(desc) = &description {
454                    info.add_property("contentDescription", desc.clone());
455                }
456                if let Some(state) = &state_description {
457                    info.add_property("stateDescription", state.clone());
458                }
459                if let Some(role) = role {
460                    info.add_property("role", format!("{role:?}"));
461                }
462                if is_clickable {
463                    info.add_property("isClickable", "true");
464                }
465                if canvas_children > 0 {
466                    info.add_property("canvasSemanticsChildren", canvas_children.to_string());
467                }
468            })
469        } else {
470            inspector_metadata("semantics", |_| {})
471        };
472        let element = SemanticsElement::new(recorder);
473        let modifier =
474            Modifier::from_parts(vec![modifier_element(element)]).with_inspector_metadata(metadata);
475        self.then(modifier)
476    }
477
478    /// Makes this component focusable.
479    ///
480    /// This adds a focus target node that can receive focus and participate
481    /// in focus traversal. The component will be included in tab order and
482    /// can be focused programmatically.
483    pub fn focus_target(self) -> Self {
484        let element = FocusTargetElement::new();
485        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
486        self.then(modifier)
487    }
488
489    /// Makes this component focusable with a callback for focus changes.
490    ///
491    /// The callback is invoked whenever the focus state changes, allowing
492    /// components to react to gaining or losing focus.
493    pub fn on_focus_changed<F>(self, callback: F) -> Self
494    where
495        F: Fn(FocusState) + 'static,
496    {
497        let element = FocusTargetElement::with_callback(callback);
498        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
499        self.then(modifier)
500    }
501
502    /// Binds a [`SemanticsRequester`] to this node, so an app can mark the
503    /// node's semantics for re-collection without recomposing or laying out.
504    ///
505    /// Pair it with [`semantics`](Self::semantics) on the same node when the
506    /// recorder reads state the composition does not observe — app state behind
507    /// a `RefCell`, a game's own model — which is the case a recorder cannot
508    /// signal for itself.
509    pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
510        let element = SemanticsRequesterElement::new(requester.clone());
511        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
512        self.then(modifier)
513    }
514
515    /// Enables debug logging for this modifier chain.
516    ///
517    /// When enabled, logs the entire modifier chain structure including:
518    /// - Element types and their properties
519    /// - Inspector metadata
520    /// - Capability flags
521    ///
522    /// This is useful for debugging modifier composition issues and understanding
523    /// how the modifier chain is structured at runtime.
524    ///
525    /// Example:
526    /// ```text
527    /// Modifier::empty()
528    ///     .padding(8.0)
529    ///     .background(Color(1.0, 0.0, 0.0, 1.0))
530    ///     .debug_chain("MyWidget")
531    /// ```
532    pub fn debug_chain(self, tag: &'static str) -> Self {
533        use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
534
535        #[derive(Clone)]
536        struct DebugChainElement {
537            tag: &'static str,
538        }
539
540        impl fmt::Debug for DebugChainElement {
541            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542                f.debug_struct("DebugChainElement")
543                    .field("tag", &self.tag)
544                    .finish()
545            }
546        }
547
548        impl PartialEq for DebugChainElement {
549            fn eq(&self, other: &Self) -> bool {
550                self.tag == other.tag
551            }
552        }
553
554        impl Eq for DebugChainElement {}
555
556        impl std::hash::Hash for DebugChainElement {
557            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
558                self.tag.hash(state);
559            }
560        }
561
562        impl ModifierNodeElement for DebugChainElement {
563            type Node = DebugChainNode;
564
565            fn create(&self) -> Self::Node {
566                DebugChainNode::new(self.tag)
567            }
568
569            fn update(&self, node: &mut Self::Node) {
570                node.tag = self.tag;
571            }
572
573            fn capabilities(&self) -> NodeCapabilities {
574                NodeCapabilities::empty()
575            }
576        }
577
578        struct DebugChainNode {
579            tag: &'static str,
580            state: NodeState,
581        }
582
583        impl DebugChainNode {
584            fn new(tag: &'static str) -> Self {
585                Self {
586                    tag,
587                    state: NodeState::new(),
588                }
589            }
590        }
591
592        impl ModifierNode for DebugChainNode {
593            fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
594                eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
595            }
596
597            fn on_detach(&mut self) {
598                eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
599            }
600
601            fn on_reset(&mut self) {
602                eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
603            }
604        }
605
606        impl cranpose_foundation::DelegatableNode for DebugChainNode {
607            fn node_state(&self) -> &NodeState {
608                &self.state
609            }
610        }
611
612        let element = DebugChainElement { tag };
613        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
614        self.then(modifier)
615            .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
616                info.add_property("tag", tag);
617            }))
618    }
619
620    /// Concatenates this modifier with another.
621    ///
622    /// Eagerly concatenates both element vectors into a single flat `Single`
623    /// variant, avoiding recursive Rc tree overhead on drop and comparison.
624    pub fn then(&self, next: Modifier) -> Modifier {
625        if self.is_trivially_empty() {
626            return next;
627        }
628        if next.is_trivially_empty() {
629            return self.clone();
630        }
631
632        let Some((self_elements, self_inspector)) = self.single_parts() else {
633            return next;
634        };
635        let Some((next_elements, next_inspector)) = next.single_parts() else {
636            return self.clone();
637        };
638
639        let mut merged_elements = Vec::with_capacity(self_elements.len() + next_elements.len());
640        merged_elements.extend_from_slice(self_elements);
641        merged_elements.extend_from_slice(next_elements);
642
643        let mut merged_inspector = Vec::with_capacity(self_inspector.len() + next_inspector.len());
644        merged_inspector.extend_from_slice(self_inspector);
645        merged_inspector.extend_from_slice(next_inspector);
646
647        let fingerprints = append_fingerprints(
648            ModifierFingerprints {
649                strict: self.strict_fingerprint,
650                structural: self.structural_fingerprint,
651            },
652            next_elements,
653        );
654        Modifier {
655            kind: ModifierKind::Single {
656                elements: Rc::new(merged_elements),
657                inspector: Rc::new(merged_inspector),
658            },
659            strict_fingerprint: fingerprints.strict,
660            structural_fingerprint: fingerprints.structural,
661            element_count: self.element_count + next.element_count,
662        }
663    }
664
665    pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
666        match &self.kind {
667            ModifierKind::Empty => ModifierElementIterator { inner: [].iter() },
668            ModifierKind::Single { elements, .. } => ModifierElementIterator {
669                inner: elements.iter(),
670            },
671        }
672    }
673
674    pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
675        match &self.kind {
676            ModifierKind::Empty => ModifierInspectorIterator { inner: [].iter() },
677            ModifierKind::Single { inspector, .. } => ModifierInspectorIterator {
678                inner: inspector.iter(),
679            },
680        }
681    }
682
683    #[cfg(test)]
684    pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
685        match &self.kind {
686            ModifierKind::Empty => Vec::new(),
687            ModifierKind::Single { elements, .. } => elements.as_ref().clone(),
688        }
689    }
690
691    pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
692        match &self.kind {
693            ModifierKind::Empty => Vec::new(),
694            ModifierKind::Single { inspector, .. } => inspector.as_ref().clone(),
695        }
696    }
697
698    pub(crate) fn rehouse_for_live_compaction(&self) -> Self {
699        match &self.kind {
700            ModifierKind::Empty => Self::default(),
701            ModifierKind::Single {
702                elements,
703                inspector,
704            } => Self {
705                kind: ModifierKind::Single {
706                    elements: Rc::new(elements.iter().cloned().collect()),
707                    inspector: Rc::new(inspector.as_ref().clone()),
708                },
709                strict_fingerprint: self.strict_fingerprint,
710                structural_fingerprint: self.structural_fingerprint,
711                element_count: self.element_count,
712            },
713        }
714    }
715
716    pub fn total_padding(&self) -> f32 {
717        let padding = self.padding_values();
718        padding
719            .left
720            .max(padding.right)
721            .max(padding.top)
722            .max(padding.bottom)
723    }
724
725    pub fn explicit_size(&self) -> Option<Size> {
726        let props = self.layout_properties();
727        match (props.width, props.height) {
728            (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
729                Some(Size { width, height })
730            }
731            _ => None,
732        }
733    }
734
735    pub fn padding_values(&self) -> EdgeInsets {
736        self.resolved_modifiers().padding()
737    }
738
739    pub(crate) fn layout_properties(&self) -> LayoutProperties {
740        self.resolved_modifiers().layout_properties()
741    }
742
743    pub fn box_alignment(&self) -> Option<Alignment> {
744        self.layout_properties().box_alignment()
745    }
746
747    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
748        self.layout_properties().column_alignment()
749    }
750
751    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
752        self.layout_properties().row_alignment()
753    }
754
755    pub fn draw_commands(&self) -> Vec<DrawCommand> {
756        collect_slices_from_modifier(self).draw_commands().to_vec()
757    }
758
759    pub fn clips_to_bounds(&self) -> bool {
760        collect_slices_from_modifier(self).clip_to_bounds()
761    }
762
763    /// Returns structured inspector records for each modifier element.
764    pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
765        self.inspector_metadata()
766            .iter()
767            .map(|metadata| metadata.to_record())
768            .collect()
769    }
770
771    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
772        let mut handle = ModifierChainHandle::new();
773        let _ = handle.update(self);
774        handle.resolved_modifiers()
775    }
776
777    pub(crate) fn with_element<E>(element: E) -> Self
778    where
779        E: ModifierNodeElement,
780    {
781        let dyn_element = modifier_element(element);
782        Self::from_parts(vec![dyn_element])
783    }
784
785    pub(crate) fn from_parts(elements: Vec<DynModifierElement>) -> Self {
786        if elements.is_empty() {
787            Self::default()
788        } else {
789            let element_count = elements.len();
790            let fingerprints = single_fingerprints(elements.as_slice());
791            Self {
792                kind: ModifierKind::Single {
793                    elements: Rc::new(elements),
794                    inspector: Rc::new(Vec::new()),
795                },
796                strict_fingerprint: fingerprints.strict,
797                structural_fingerprint: fingerprints.structural,
798                element_count,
799            }
800        }
801    }
802
803    fn is_trivially_empty(&self) -> bool {
804        matches!(self.kind, ModifierKind::Empty)
805    }
806
807    fn single_parts(&self) -> Option<(&[DynModifierElement], &[InspectorMetadata])> {
808        match &self.kind {
809            ModifierKind::Empty => None,
810            ModifierKind::Single {
811                elements,
812                inspector,
813            } => Some((elements.as_slice(), inspector.as_slice())),
814        }
815    }
816
817    pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
818        if metadata.is_empty() {
819            return self;
820        }
821        match self.kind {
822            ModifierKind::Empty => self,
823            ModifierKind::Single {
824                elements,
825                inspector,
826            } => {
827                let mut new_inspector = inspector.as_ref().clone();
828                new_inspector.push(metadata);
829                Self {
830                    kind: ModifierKind::Single {
831                        elements,
832                        inspector: Rc::new(new_inspector),
833                    },
834                    strict_fingerprint: self.strict_fingerprint,
835                    structural_fingerprint: self.structural_fingerprint,
836                    element_count: self.element_count,
837                }
838            }
839        }
840    }
841
842    /// Checks whether two modifiers are structurally equivalent for layout decisions.
843    ///
844    /// This ignores identity-sensitive modifier elements (e.g., draw closures) so
845    /// draw-only updates do not force measure/layout invalidation.
846    pub fn structural_eq(&self, other: &Self) -> bool {
847        self.eq_internal(other, false)
848    }
849
850    fn eq_internal(&self, other: &Self, consider_always_update: bool) -> bool {
851        if self.element_count != other.element_count {
852            return false;
853        }
854        if consider_always_update {
855            if self.strict_fingerprint != other.strict_fingerprint {
856                return false;
857            }
858        } else if self.structural_fingerprint != other.structural_fingerprint {
859            return false;
860        }
861
862        match (&self.kind, &other.kind) {
863            (ModifierKind::Empty, ModifierKind::Empty) => true,
864            (
865                ModifierKind::Single {
866                    elements: e1,
867                    inspector: _,
868                },
869                ModifierKind::Single {
870                    elements: e2,
871                    inspector: _,
872                },
873            ) => {
874                if Rc::ptr_eq(e1, e2) {
875                    return true;
876                }
877
878                if e1.len() != e2.len() {
879                    return false;
880                }
881
882                for (a, b) in e1.iter().zip(e2.iter()) {
883                    if !consider_always_update
884                        && a.element_type() == b.element_type()
885                        && a.capabilities() == NodeCapabilities::DRAW
886                        && b.capabilities() == NodeCapabilities::DRAW
887                    {
888                        continue;
889                    }
890
891                    if consider_always_update && (a.requires_update() || b.requires_update()) {
892                        if !Rc::ptr_eq(a, b) {
893                            return false;
894                        }
895                        continue;
896                    }
897
898                    if !a.equals_element(&**b) {
899                        return false;
900                    }
901                }
902
903                true
904            }
905            _ => false,
906        }
907    }
908}
909
910impl PartialEq for Modifier {
911    fn eq(&self, other: &Self) -> bool {
912        self.eq_internal(other, true)
913    }
914}
915
916impl Eq for Modifier {}
917
918impl fmt::Display for Modifier {
919    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
920        match &self.kind {
921            ModifierKind::Empty => write!(f, "Modifier.empty"),
922            ModifierKind::Single { elements, .. } => {
923                if elements.is_empty() {
924                    return write!(f, "Modifier.empty");
925                }
926                write!(f, "Modifier[")?;
927                for (index, element) in elements.iter().enumerate() {
928                    if index > 0 {
929                        write!(f, ", ")?;
930                    }
931                    let name = element.inspector_name();
932                    let mut properties = Vec::new();
933                    element.record_inspector_properties(&mut |prop, value| {
934                        properties.push(format!("{prop}={value}"));
935                    });
936                    if properties.is_empty() {
937                        write!(f, "{name}")?;
938                    } else {
939                        write!(f, "{name}({})", properties.join(", "))?;
940                    }
941                }
942                write!(f, "]")
943            }
944        }
945    }
946}
947
948impl fmt::Debug for Modifier {
949    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950        fmt::Display::fmt(self, f)
951    }
952}
953
954#[derive(Clone, Copy, Debug, PartialEq)]
955pub struct ResolvedBackground {
956    color: Color,
957    shape: Option<RoundedCornerShape>,
958}
959
960impl ResolvedBackground {
961    pub fn new(color: Color, shape: Option<RoundedCornerShape>) -> Self {
962        Self { color, shape }
963    }
964
965    pub fn color(&self) -> Color {
966        self.color
967    }
968
969    pub fn shape(&self) -> Option<RoundedCornerShape> {
970        self.shape
971    }
972
973    pub fn set_shape(&mut self, shape: Option<RoundedCornerShape>) {
974        self.shape = shape;
975    }
976}
977
978#[derive(Clone, Copy, Debug, PartialEq, Default)]
979pub struct ResolvedModifiers {
980    padding: EdgeInsets,
981    layout: LayoutProperties,
982    offset: Point,
983}
984
985impl ResolvedModifiers {
986    pub fn padding(&self) -> EdgeInsets {
987        self.padding
988    }
989
990    pub fn layout_properties(&self) -> LayoutProperties {
991        self.layout
992    }
993
994    pub fn offset(&self) -> Point {
995        self.offset
996    }
997
998    pub(crate) fn set_padding(&mut self, padding: EdgeInsets) {
999        self.padding = padding;
1000    }
1001
1002    pub(crate) fn set_layout_properties(&mut self, layout: LayoutProperties) {
1003        self.layout = layout;
1004    }
1005
1006    pub(crate) fn set_offset(&mut self, offset: Point) {
1007        self.offset = offset;
1008    }
1009}
1010
1011#[derive(Clone, Copy, Debug, Default, PartialEq)]
1012pub enum DimensionConstraint {
1013    #[default]
1014    Unspecified,
1015    Points(f32),
1016    Fraction(f32),
1017    Intrinsic(IntrinsicSize),
1018}
1019
1020#[derive(Clone, Copy, Debug, Default, PartialEq)]
1021pub struct LayoutWeight {
1022    pub weight: f32,
1023    pub fill: bool,
1024}
1025
1026#[derive(Clone, Copy, Debug, Default, PartialEq)]
1027pub struct LayoutProperties {
1028    padding: EdgeInsets,
1029    width: DimensionConstraint,
1030    height: DimensionConstraint,
1031    min_width: Option<f32>,
1032    min_height: Option<f32>,
1033    max_width: Option<f32>,
1034    max_height: Option<f32>,
1035    weight: Option<LayoutWeight>,
1036    box_alignment: Option<Alignment>,
1037    column_alignment: Option<HorizontalAlignment>,
1038    row_alignment: Option<VerticalAlignment>,
1039}
1040
1041impl LayoutProperties {
1042    pub fn padding(&self) -> EdgeInsets {
1043        self.padding
1044    }
1045
1046    pub fn width(&self) -> DimensionConstraint {
1047        self.width
1048    }
1049
1050    pub fn height(&self) -> DimensionConstraint {
1051        self.height
1052    }
1053
1054    pub fn min_width(&self) -> Option<f32> {
1055        self.min_width
1056    }
1057
1058    pub fn min_height(&self) -> Option<f32> {
1059        self.min_height
1060    }
1061
1062    pub fn max_width(&self) -> Option<f32> {
1063        self.max_width
1064    }
1065
1066    pub fn max_height(&self) -> Option<f32> {
1067        self.max_height
1068    }
1069
1070    pub fn weight(&self) -> Option<LayoutWeight> {
1071        self.weight
1072    }
1073
1074    pub fn box_alignment(&self) -> Option<Alignment> {
1075        self.box_alignment
1076    }
1077
1078    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1079        self.column_alignment
1080    }
1081
1082    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1083        self.row_alignment
1084    }
1085}
1086
1087#[cfg(test)]
1088#[path = "tests/modifier_tests.rs"]
1089mod tests;