cranpose-ui 0.0.60

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! Modifier system for Cranpose
//!
//! This module now acts as a thin builder around modifier elements. Each
//! [`Modifier`] stores the element chain required by the modifier node system
//! together with inspector metadata while resolved state is computed directly
//! from the modifier nodes.

#![allow(non_snake_case)]

use std::fmt;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::OnceLock;

use cranpose_core::hash::default;

mod alignment;
mod background;
mod blur;
mod chain;
mod clickable;
mod draw_cache;
mod fill;
mod focus;
mod graphics_layer;
mod local;
mod offset;
mod padding;
mod pointer_input;
mod scroll;
mod semantics;
mod shadow;
mod size;
mod slices;
mod weight;

pub use crate::draw::{DrawCacheBuilder, DrawCommand};
#[allow(unused_imports)]
pub use chain::{ModifierChainHandle, ModifierChainInspectorNode, ModifierLocalsHandle};
pub use cranpose_foundation::{
    modifier_element, AnyModifierElement, DynModifierElement, FocusState, PointerEvent,
    PointerEventKind, SemanticsConfiguration,
};
use cranpose_foundation::{ModifierNodeElement, NodeCapabilities};
#[allow(unused_imports)]
pub use cranpose_ui_graphics::{
    BlendMode, BlurredEdgeTreatment, Brush, Color, ColorFilter, CompositingStrategy, CornerRadii,
    CutDirection, Dp, DpOffset, EdgeInsets, GradientCutMaskSpec, GradientFadeMaskSpec,
    GraphicsLayer, LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader,
    Shadow, ShadowScope, Size, TransformOrigin,
};
use cranpose_ui_layout::{Alignment, HorizontalAlignment, IntrinsicSize, VerticalAlignment};
#[allow(unused_imports)]
pub use focus::{FocusDirection, FocusRequester};
pub(crate) use local::{
    ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
};
#[allow(unused_imports)]
pub use local::{ModifierLocalKey, ModifierLocalReadScope};
#[allow(unused_imports)]
pub use pointer_input::{AwaitPointerEventScope, PointerInputScope};
pub use semantics::{collect_semantics_from_chain, collect_semantics_from_modifier};
pub use slices::{
    collect_modifier_slices, collect_modifier_slices_into, collect_slices_from_modifier,
    ModifierNodeSlices, ModifierNodeSlicesDebugStats,
};
// Test accessibility for fling velocity (only with test-helpers feature)
#[cfg(feature = "test-helpers")]
pub use scroll::{last_fling_velocity, reset_last_fling_velocity};

use crate::modifier_nodes::ClipToBoundsElement;
use focus::{FocusRequesterElement, FocusTargetElement};
use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
use semantics::SemanticsElement;

/// Minimal inspector metadata storage.
#[derive(Clone, Debug, Default)]
pub struct InspectorInfo {
    properties: Vec<InspectorProperty>,
}

impl InspectorInfo {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
        self.properties.push(InspectorProperty {
            name,
            value: value.into(),
        });
    }

    pub fn properties(&self) -> &[InspectorProperty] {
        &self.properties
    }

    pub fn is_empty(&self) -> bool {
        self.properties.is_empty()
    }

    pub fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
        self.add_property(name, describe_dimension(constraint));
    }

    pub fn add_offset_components(
        &mut self,
        x_name: &'static str,
        y_name: &'static str,
        offset: Point,
    ) {
        self.add_property(x_name, offset.x.to_string());
        self.add_property(y_name, offset.y.to_string());
    }

    pub fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
    where
        A: fmt::Debug,
    {
        self.add_property(name, format!("{alignment:?}"));
    }
}

/// Single inspector entry recording a property exposed by a modifier.
#[derive(Clone, Debug, PartialEq)]
pub struct InspectorProperty {
    pub name: &'static str,
    pub value: String,
}

/// Structured inspector payload describing a modifier element.
#[derive(Clone, Debug, PartialEq)]
pub struct ModifierInspectorRecord {
    pub name: &'static str,
    pub properties: Vec<InspectorProperty>,
}

/// Helper describing the metadata contributed by a modifier factory.
#[derive(Clone, Debug)]
pub(crate) struct InspectorMetadata {
    name: &'static str,
    info: InspectorInfo,
}

impl InspectorMetadata {
    pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
    where
        F: FnOnce(&mut InspectorInfo),
    {
        let mut info = InspectorInfo::new();
        recorder(&mut info);
        Self { name, info }
    }

    fn is_empty(&self) -> bool {
        self.info.is_empty()
    }

    fn to_record(&self) -> ModifierInspectorRecord {
        ModifierInspectorRecord {
            name: self.name,
            properties: self.info.properties().to_vec(),
        }
    }
}

fn describe_dimension(constraint: DimensionConstraint) -> String {
    match constraint {
        DimensionConstraint::Unspecified => "unspecified".to_string(),
        DimensionConstraint::Points(value) => value.to_string(),
        DimensionConstraint::Fraction(value) => format!("fraction({value})"),
        DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
    }
}

pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
where
    F: FnOnce(&mut InspectorInfo),
{
    // Inspector metadata is debug tooling. Avoid building string-heavy metadata in
    // optimized runtime unless modifier debugging is explicitly enabled.
    if !inspector_metadata_enabled() {
        return InspectorMetadata::new(name, |_| {});
    }
    InspectorMetadata::new(name, recorder)
}

pub(crate) fn modifier_debug_enabled() -> bool {
    #[cfg(not(target_arch = "wasm32"))]
    {
        static ENV_DEBUG: OnceLock<bool> = OnceLock::new();
        *ENV_DEBUG.get_or_init(|| std::env::var_os("COMPOSE_DEBUG_MODIFIERS").is_some())
    }
    #[cfg(target_arch = "wasm32")]
    {
        false
    }
}

fn inspector_metadata_enabled() -> bool {
    cfg!(test) || modifier_debug_enabled()
}

/// Internal representation of modifier composition structure.
///
/// All modifiers are either empty or a flat vector of elements. The `then()`
/// method eagerly concatenates elements, eliminating recursive tree traversal
/// and Rc drop overhead from the old `Combined` variant.
#[derive(Clone)]
enum ModifierKind {
    /// Empty modifier (like Modifier.companion in Kotlin)
    Empty,
    /// Flat modifier with all elements and inspector metadata concatenated
    Single {
        elements: Rc<Vec<DynModifierElement>>,
        inspector: Rc<Vec<InspectorMetadata>>,
    },
}

const FINGERPRINT_KIND_EMPTY: u8 = 0;
const FINGERPRINT_KIND_SINGLE: u8 = 1;

const FINGERPRINT_EMPTY_STRICT_SEED: u64 = 0x243f_6a88_85a3_08d3;
const FINGERPRINT_EMPTY_STRUCTURAL_SEED: u64 = 0x1319_8a2e_0370_7344;
const FINGERPRINT_SINGLE_STRICT_SEED: u64 = 0xa409_3822_299f_31d0;
const FINGERPRINT_SINGLE_STRUCTURAL_SEED: u64 = 0x082e_fa98_ec4e_6c89;
const FINGERPRINT_SEQUENCE_MUL: u64 = 0x9e37_79b1_85eb_ca87;
const FINGERPRINT_STRICT_UPDATE_TAG: u64 = 0xdbe6_d5d5_fe4c_ce2f;
const FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG: u64 = 0x94d0_49bb_1331_11eb;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ModifierFingerprints {
    strict: u64,
    structural: u64,
}

#[inline]
fn mix_fingerprint_bits(mut value: u64) -> u64 {
    value ^= value >> 33;
    value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
    value ^= value >> 33;
    value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
    value ^ (value >> 33)
}

#[inline]
fn fold_fingerprint(state: u64, value: u64) -> u64 {
    mix_fingerprint_bits(state ^ value.wrapping_add(FINGERPRINT_SEQUENCE_MUL))
        .wrapping_mul(FINGERPRINT_SEQUENCE_MUL)
}

#[inline]
fn empty_fingerprints() -> ModifierFingerprints {
    ModifierFingerprints {
        strict: fold_fingerprint(FINGERPRINT_EMPTY_STRICT_SEED, FINGERPRINT_KIND_EMPTY as u64),
        structural: fold_fingerprint(
            FINGERPRINT_EMPTY_STRUCTURAL_SEED,
            FINGERPRINT_KIND_EMPTY as u64,
        ),
    }
}

#[inline]
fn single_fingerprint_seed() -> ModifierFingerprints {
    let strict = fold_fingerprint(
        FINGERPRINT_SINGLE_STRICT_SEED,
        FINGERPRINT_KIND_SINGLE as u64,
    );
    let structural = fold_fingerprint(
        FINGERPRINT_SINGLE_STRUCTURAL_SEED,
        FINGERPRINT_KIND_SINGLE as u64,
    );
    ModifierFingerprints { strict, structural }
}

#[inline]
fn element_common_fingerprint(element: &DynModifierElement) -> u64 {
    let mut hasher = default::new();
    element.element_type().hash(&mut hasher);
    element.capabilities().bits().hash(&mut hasher);
    hasher.finish()
}

#[inline]
fn element_fingerprints(element: &DynModifierElement) -> ModifierFingerprints {
    let common = element_common_fingerprint(element);
    let requires_update = element.requires_update();
    let strict_payload = if requires_update {
        let element_ptr = Rc::as_ptr(element) as *const () as usize as u64;
        element_ptr ^ FINGERPRINT_STRICT_UPDATE_TAG
    } else {
        element.hash_code()
    };
    let strict = mix_fingerprint_bits(common ^ strict_payload);

    let is_draw_only = element.capabilities() == NodeCapabilities::DRAW;
    let structural_payload = if is_draw_only {
        FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG
    } else {
        element.hash_code()
    };
    let structural = mix_fingerprint_bits(common ^ structural_payload);

    ModifierFingerprints { strict, structural }
}

#[inline]
fn append_fingerprints(
    mut fingerprints: ModifierFingerprints,
    elements: &[DynModifierElement],
) -> ModifierFingerprints {
    for element in elements {
        let element_fingerprints = element_fingerprints(element);
        fingerprints.strict = fold_fingerprint(fingerprints.strict, element_fingerprints.strict);
        fingerprints.structural =
            fold_fingerprint(fingerprints.structural, element_fingerprints.structural);
    }
    fingerprints
}

fn single_fingerprints(elements: &[DynModifierElement]) -> ModifierFingerprints {
    append_fingerprints(single_fingerprint_seed(), elements)
}

/// Iterator over modifier elements — simple slice iteration since modifiers
/// are always flat after `then()` eagerly concatenates.
pub struct ModifierElementIterator<'a> {
    inner: std::slice::Iter<'a, DynModifierElement>,
}

impl<'a> Iterator for ModifierElementIterator<'a> {
    type Item = &'a DynModifierElement;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModifierElementIterator<'_> {}

/// Iterator over inspector metadata — simple slice iteration.
pub(crate) struct ModifierInspectorIterator<'a> {
    inner: std::slice::Iter<'a, InspectorMetadata>,
}

impl<'a> Iterator for ModifierInspectorIterator<'a> {
    type Item = &'a InspectorMetadata;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModifierInspectorIterator<'_> {}

/// A modifier chain that can be applied to composable elements.
///
/// Modifiers allow you to decorate or augment a composable. Common operations include:
/// - Adjusting layout (e.g., `padding`, `fill_max_size`)
/// - Adding behavior (e.g., `clickable`, `scrollable`)
/// - Drawing (e.g., `background`, `border`)
///
/// Modifiers are immutable and form a chain using the builder pattern.
/// The order of modifiers matters: previous modifiers wrap subsequent ones.
///
/// # Example
///
/// ```rust,ignore
/// Modifier::padding(16.0)     // Applied first (outer)
///     .background(Color::Red) // Applied second
///     .clickable(|| println!("Clicked")) // Applied last (inner)
/// ```
#[derive(Clone)]
pub struct Modifier {
    kind: ModifierKind,
    strict_fingerprint: u64,
    structural_fingerprint: u64,
    element_count: usize,
}

impl Default for Modifier {
    fn default() -> Self {
        let fingerprints = empty_fingerprints();
        Self {
            kind: ModifierKind::Empty,
            strict_fingerprint: fingerprints.strict,
            structural_fingerprint: fingerprints.structural,
            element_count: 0,
        }
    }
}

impl Modifier {
    pub fn empty() -> Self {
        Self::default()
    }

    /// Clip the content to the bounds of this modifier.
    ///
    /// Example: `Modifier::empty().clip_to_bounds()`
    pub fn clip_to_bounds(self) -> Self {
        let modifier = Self::with_element(ClipToBoundsElement::new()).with_inspector_metadata(
            inspector_metadata("clipToBounds", |info| {
                info.add_property("clipToBounds", "true");
            }),
        );
        self.then(modifier)
    }

    pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
    where
        T: 'static,
        F: Fn() -> T + 'static,
    {
        let element = ModifierLocalProviderElement::new(key, value);
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
    }

    pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
    where
        F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
    {
        let element = ModifierLocalConsumerElement::new(consumer);
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
    }

    pub fn semantics<F>(self, recorder: F) -> Self
    where
        F: Fn(&mut SemanticsConfiguration) + 'static,
    {
        let mut preview = SemanticsConfiguration::default();
        recorder(&mut preview);
        let description = preview.content_description.clone();
        let is_button = preview.is_button;
        let is_clickable = preview.is_clickable;
        let metadata = inspector_metadata("semantics", move |info| {
            if let Some(desc) = &description {
                info.add_property("contentDescription", desc.clone());
            }
            if is_button {
                info.add_property("isButton", "true");
            }
            if is_clickable {
                info.add_property("isClickable", "true");
            }
        });
        let element = SemanticsElement::new(recorder);
        let modifier =
            Modifier::from_parts(vec![modifier_element(element)]).with_inspector_metadata(metadata);
        self.then(modifier)
    }

    /// Makes this component focusable.
    ///
    /// This adds a focus target node that can receive focus and participate
    /// in focus traversal. The component will be included in tab order and
    /// can be focused programmatically.
    pub fn focus_target(self) -> Self {
        let element = FocusTargetElement::new();
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
    }

    /// Makes this component focusable with a callback for focus changes.
    ///
    /// The callback is invoked whenever the focus state changes, allowing
    /// components to react to gaining or losing focus.
    pub fn on_focus_changed<F>(self, callback: F) -> Self
    where
        F: Fn(FocusState) + 'static,
    {
        let element = FocusTargetElement::with_callback(callback);
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
    }

    /// Attaches a focus requester to this component.
    ///
    /// The requester can be used to programmatically request focus for
    /// this component from application code.
    pub fn focus_requester(self, requester: &FocusRequester) -> Self {
        let element = FocusRequesterElement::new(requester.id());
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
    }

    /// Enables debug logging for this modifier chain.
    ///
    /// When enabled, logs the entire modifier chain structure including:
    /// - Element types and their properties
    /// - Inspector metadata
    /// - Capability flags
    ///
    /// This is useful for debugging modifier composition issues and understanding
    /// how the modifier chain is structured at runtime.
    ///
    /// Example:
    /// ```text
    /// Modifier::empty()
    ///     .padding(8.0)
    ///     .background(Color(1.0, 0.0, 0.0, 1.0))
    ///     .debug_chain("MyWidget")
    /// ```
    pub fn debug_chain(self, tag: &'static str) -> Self {
        use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};

        #[derive(Clone)]
        struct DebugChainElement {
            tag: &'static str,
        }

        impl fmt::Debug for DebugChainElement {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct("DebugChainElement")
                    .field("tag", &self.tag)
                    .finish()
            }
        }

        impl PartialEq for DebugChainElement {
            fn eq(&self, other: &Self) -> bool {
                self.tag == other.tag
            }
        }

        impl Eq for DebugChainElement {}

        impl std::hash::Hash for DebugChainElement {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.tag.hash(state);
            }
        }

        impl ModifierNodeElement for DebugChainElement {
            type Node = DebugChainNode;

            fn create(&self) -> Self::Node {
                DebugChainNode::new(self.tag)
            }

            fn update(&self, node: &mut Self::Node) {
                node.tag = self.tag;
            }

            fn capabilities(&self) -> NodeCapabilities {
                NodeCapabilities::empty()
            }
        }

        struct DebugChainNode {
            tag: &'static str,
            state: NodeState,
        }

        impl DebugChainNode {
            fn new(tag: &'static str) -> Self {
                Self {
                    tag,
                    state: NodeState::new(),
                }
            }
        }

        impl ModifierNode for DebugChainNode {
            fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
                eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
            }

            fn on_detach(&mut self) {
                eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
            }

            fn on_reset(&mut self) {
                eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
            }
        }

        impl cranpose_foundation::DelegatableNode for DebugChainNode {
            fn node_state(&self) -> &NodeState {
                &self.state
            }
        }

        let element = DebugChainElement { tag };
        let modifier = Modifier::from_parts(vec![modifier_element(element)]);
        self.then(modifier)
            .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
                info.add_property("tag", tag);
            }))
    }

    /// Concatenates this modifier with another.
    ///
    /// Eagerly concatenates both element vectors into a single flat `Single`
    /// variant, avoiding recursive Rc tree overhead on drop and comparison.
    pub fn then(&self, next: Modifier) -> Modifier {
        if self.is_trivially_empty() {
            return next;
        }
        if next.is_trivially_empty() {
            return self.clone();
        }

        // Collect elements from both sides into a single Vec
        let (self_elements, self_inspector) = match &self.kind {
            ModifierKind::Empty => unreachable!(),
            ModifierKind::Single {
                elements,
                inspector,
                ..
            } => (elements.as_ref(), inspector.as_ref()),
        };
        let (next_elements, next_inspector) = match &next.kind {
            ModifierKind::Empty => unreachable!(),
            ModifierKind::Single {
                elements,
                inspector,
                ..
            } => (elements.as_ref(), inspector.as_ref()),
        };

        let mut merged_elements = Vec::with_capacity(self_elements.len() + next_elements.len());
        merged_elements.extend_from_slice(self_elements);
        merged_elements.extend_from_slice(next_elements);

        let mut merged_inspector = Vec::with_capacity(self_inspector.len() + next_inspector.len());
        merged_inspector.extend_from_slice(self_inspector);
        merged_inspector.extend_from_slice(next_inspector);

        let fingerprints = append_fingerprints(
            ModifierFingerprints {
                strict: self.strict_fingerprint,
                structural: self.structural_fingerprint,
            },
            next_elements,
        );
        Modifier {
            kind: ModifierKind::Single {
                elements: Rc::new(merged_elements),
                inspector: Rc::new(merged_inspector),
            },
            strict_fingerprint: fingerprints.strict,
            structural_fingerprint: fingerprints.structural,
            element_count: self.element_count + next.element_count,
        }
    }

    /// Returns an iterator over the modifier elements without allocation.
    pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
        match &self.kind {
            ModifierKind::Empty => ModifierElementIterator { inner: [].iter() },
            ModifierKind::Single { elements, .. } => ModifierElementIterator {
                inner: elements.iter(),
            },
        }
    }

    pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
        match &self.kind {
            ModifierKind::Empty => ModifierInspectorIterator { inner: [].iter() },
            ModifierKind::Single { inspector, .. } => ModifierInspectorIterator {
                inner: inspector.iter(),
            },
        }
    }

    /// Returns the list of elements in this modifier chain.
    ///
    /// **Note:** Consider using `iter_elements()` instead to avoid cloning.
    #[cfg(test)]
    pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
        match &self.kind {
            ModifierKind::Empty => Vec::new(),
            ModifierKind::Single { elements, .. } => elements.as_ref().clone(),
        }
    }

    /// Returns the list of inspector metadata in this modifier chain.
    pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
        match &self.kind {
            ModifierKind::Empty => Vec::new(),
            ModifierKind::Single { inspector, .. } => inspector.as_ref().clone(),
        }
    }

    pub(crate) fn rehouse_for_live_compaction(&self) -> Self {
        match &self.kind {
            ModifierKind::Empty => Self::default(),
            ModifierKind::Single {
                elements,
                inspector,
            } => Self {
                kind: ModifierKind::Single {
                    elements: Rc::new(elements.iter().cloned().collect()),
                    inspector: Rc::new(inspector.as_ref().clone()),
                },
                strict_fingerprint: self.strict_fingerprint,
                structural_fingerprint: self.structural_fingerprint,
                element_count: self.element_count,
            },
        }
    }

    pub fn total_padding(&self) -> f32 {
        let padding = self.padding_values();
        padding
            .left
            .max(padding.right)
            .max(padding.top)
            .max(padding.bottom)
    }

    pub fn explicit_size(&self) -> Option<Size> {
        let props = self.layout_properties();
        match (props.width, props.height) {
            (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
                Some(Size { width, height })
            }
            _ => None,
        }
    }

    pub fn padding_values(&self) -> EdgeInsets {
        self.resolved_modifiers().padding()
    }

    pub(crate) fn layout_properties(&self) -> LayoutProperties {
        self.resolved_modifiers().layout_properties()
    }

    pub fn box_alignment(&self) -> Option<Alignment> {
        self.layout_properties().box_alignment()
    }

    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
        self.layout_properties().column_alignment()
    }

    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
        self.layout_properties().row_alignment()
    }

    pub fn draw_commands(&self) -> Vec<DrawCommand> {
        collect_slices_from_modifier(self).draw_commands().to_vec()
    }

    pub fn clips_to_bounds(&self) -> bool {
        collect_slices_from_modifier(self).clip_to_bounds()
    }

    /// Returns structured inspector records for each modifier element.
    pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
        self.inspector_metadata()
            .iter()
            .map(|metadata| metadata.to_record())
            .collect()
    }

    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
        let mut handle = ModifierChainHandle::new();
        let _ = handle.update(self);
        handle.resolved_modifiers()
    }

    fn with_element<E>(element: E) -> Self
    where
        E: ModifierNodeElement,
    {
        let dyn_element = modifier_element(element);
        Self::from_parts(vec![dyn_element])
    }

    pub(crate) fn from_parts(elements: Vec<DynModifierElement>) -> Self {
        if elements.is_empty() {
            Self::default()
        } else {
            let element_count = elements.len();
            let fingerprints = single_fingerprints(elements.as_slice());
            Self {
                kind: ModifierKind::Single {
                    elements: Rc::new(elements),
                    inspector: Rc::new(Vec::new()),
                },
                strict_fingerprint: fingerprints.strict,
                structural_fingerprint: fingerprints.structural,
                element_count,
            }
        }
    }

    fn is_trivially_empty(&self) -> bool {
        matches!(self.kind, ModifierKind::Empty)
    }

    pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
        if metadata.is_empty() {
            return self;
        }
        match self.kind {
            ModifierKind::Empty => self,
            ModifierKind::Single {
                elements,
                inspector,
            } => {
                let mut new_inspector = inspector.as_ref().clone();
                new_inspector.push(metadata);
                Self {
                    kind: ModifierKind::Single {
                        elements,
                        inspector: Rc::new(new_inspector),
                    },
                    strict_fingerprint: self.strict_fingerprint,
                    structural_fingerprint: self.structural_fingerprint,
                    element_count: self.element_count,
                }
            }
        }
    }

    /// Checks whether two modifiers are structurally equivalent for layout decisions.
    ///
    /// This ignores identity-sensitive modifier elements (e.g., draw closures) so
    /// draw-only updates do not force measure/layout invalidation.
    pub fn structural_eq(&self, other: &Self) -> bool {
        self.eq_internal(other, false)
    }

    fn eq_internal(&self, other: &Self, consider_always_update: bool) -> bool {
        if self.element_count != other.element_count {
            return false;
        }
        if consider_always_update {
            if self.strict_fingerprint != other.strict_fingerprint {
                return false;
            }
        } else if self.structural_fingerprint != other.structural_fingerprint {
            return false;
        }

        match (&self.kind, &other.kind) {
            (ModifierKind::Empty, ModifierKind::Empty) => true,
            (
                ModifierKind::Single {
                    elements: e1,
                    inspector: _,
                },
                ModifierKind::Single {
                    elements: e2,
                    inspector: _,
                },
            ) => {
                if Rc::ptr_eq(e1, e2) {
                    return true;
                }

                if e1.len() != e2.len() {
                    return false;
                }

                for (a, b) in e1.iter().zip(e2.iter()) {
                    // structural_eq() is used for layout decisions, so draw-only
                    // elements of the same type are considered structurally equal
                    // even when their draw-time payload differs.
                    if !consider_always_update
                        && a.element_type() == b.element_type()
                        && a.capabilities() == NodeCapabilities::DRAW
                        && b.capabilities() == NodeCapabilities::DRAW
                    {
                        continue;
                    }

                    if consider_always_update && (a.requires_update() || b.requires_update()) {
                        if !Rc::ptr_eq(a, b) {
                            return false;
                        }
                        continue;
                    }

                    if !a.equals_element(&**b) {
                        return false;
                    }
                }

                true
            }
            _ => false,
        }
    }
}

impl PartialEq for Modifier {
    fn eq(&self, other: &Self) -> bool {
        self.eq_internal(other, true)
    }
}

impl Eq for Modifier {}

impl fmt::Display for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ModifierKind::Empty => write!(f, "Modifier.empty"),
            ModifierKind::Single { elements, .. } => {
                if elements.is_empty() {
                    return write!(f, "Modifier.empty");
                }
                write!(f, "Modifier[")?;
                for (index, element) in elements.iter().enumerate() {
                    if index > 0 {
                        write!(f, ", ")?;
                    }
                    let name = element.inspector_name();
                    let mut properties = Vec::new();
                    element.record_inspector_properties(&mut |prop, value| {
                        properties.push(format!("{prop}={value}"));
                    });
                    if properties.is_empty() {
                        write!(f, "{name}")?;
                    } else {
                        write!(f, "{name}({})", properties.join(", "))?;
                    }
                }
                write!(f, "]")
            }
        }
    }
}

impl fmt::Debug for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ResolvedBackground {
    color: Color,
    shape: Option<RoundedCornerShape>,
}

impl ResolvedBackground {
    pub fn new(color: Color, shape: Option<RoundedCornerShape>) -> Self {
        Self { color, shape }
    }

    pub fn color(&self) -> Color {
        self.color
    }

    pub fn shape(&self) -> Option<RoundedCornerShape> {
        self.shape
    }

    pub fn set_shape(&mut self, shape: Option<RoundedCornerShape>) {
        self.shape = shape;
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct ResolvedModifiers {
    padding: EdgeInsets,
    layout: LayoutProperties,
    offset: Point,
}

impl ResolvedModifiers {
    pub fn padding(&self) -> EdgeInsets {
        self.padding
    }

    pub fn layout_properties(&self) -> LayoutProperties {
        self.layout
    }

    pub fn offset(&self) -> Point {
        self.offset
    }

    pub(crate) fn set_padding(&mut self, padding: EdgeInsets) {
        self.padding = padding;
    }

    pub(crate) fn set_layout_properties(&mut self, layout: LayoutProperties) {
        self.layout = layout;
    }

    pub(crate) fn set_offset(&mut self, offset: Point) {
        self.offset = offset;
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum DimensionConstraint {
    #[default]
    Unspecified,
    Points(f32),
    Fraction(f32),
    Intrinsic(IntrinsicSize),
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LayoutWeight {
    pub weight: f32,
    pub fill: bool,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LayoutProperties {
    padding: EdgeInsets,
    width: DimensionConstraint,
    height: DimensionConstraint,
    min_width: Option<f32>,
    min_height: Option<f32>,
    max_width: Option<f32>,
    max_height: Option<f32>,
    weight: Option<LayoutWeight>,
    box_alignment: Option<Alignment>,
    column_alignment: Option<HorizontalAlignment>,
    row_alignment: Option<VerticalAlignment>,
}

impl LayoutProperties {
    pub fn padding(&self) -> EdgeInsets {
        self.padding
    }

    pub fn width(&self) -> DimensionConstraint {
        self.width
    }

    pub fn height(&self) -> DimensionConstraint {
        self.height
    }

    pub fn min_width(&self) -> Option<f32> {
        self.min_width
    }

    pub fn min_height(&self) -> Option<f32> {
        self.min_height
    }

    pub fn max_width(&self) -> Option<f32> {
        self.max_width
    }

    pub fn max_height(&self) -> Option<f32> {
        self.max_height
    }

    pub fn weight(&self) -> Option<LayoutWeight> {
        self.weight
    }

    pub fn box_alignment(&self) -> Option<Alignment> {
        self.box_alignment
    }

    pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
        self.column_alignment
    }

    pub fn row_alignment(&self) -> Option<VerticalAlignment> {
        self.row_alignment
    }
}

#[cfg(test)]
#[path = "tests/modifier_tests.rs"]
mod tests;