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