cranpose-ui 0.0.59

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
#![allow(private_interfaces)]

#[allow(unused_imports)] // Used in tests
use cranpose_foundation::InvalidationKind;

use cranpose_core::NodeId;
use cranpose_foundation::{
    BasicModifierNodeContext, ModifierInvalidation, ModifierNodeChain, ModifierNodeContext,
    NodeCapabilities,
};

use super::{
    local::ModifierLocalManager, modifier_debug_enabled, DimensionConstraint, EdgeInsets,
    LayoutProperties, Modifier, ModifierInspectorRecord, ModifierLocalAncestorResolver,
    ModifierLocalToken, Point, ResolvedModifierLocal, ResolvedModifiers,
};
use crate::modifier_nodes::{
    AlignmentNode, FillDirection, FillNode, IntrinsicAxis, IntrinsicSizeNode, OffsetNode,
    PaddingNode, SizeNode, WeightNode,
};
use std::any::type_name_of_val;
use std::cell::RefCell;
use std::rc::Rc;

/// Snapshot of a modifier node inside a reconciled chain for debugging & inspector tooling.
#[derive(Clone, Debug, PartialEq)]
pub struct ModifierChainInspectorNode {
    pub depth: usize,
    pub entry_index: Option<usize>,
    pub type_name: &'static str,
    pub capabilities: NodeCapabilities,
    pub aggregate_child_capabilities: NodeCapabilities,
    pub inspector: Option<ModifierInspectorRecord>,
}

/// Runtime helper that keeps a [`ModifierNodeChain`] in sync with a [`Modifier`].
///
/// This is the first step toward Jetpack Compose parity: callers can keep a handle
/// per layout node, feed it the latest `Modifier`, and then drive layout/draw/input
/// phases through the reconciled chain.
pub type ModifierLocalsHandle = Rc<RefCell<ModifierLocalManager>>;

pub struct ModifierChainHandle {
    chain: ModifierNodeChain,
    context: RefCell<BasicModifierNodeContext>,
    resolved: ResolvedModifiers,
    capabilities: NodeCapabilities,
    aggregate_child_capabilities: NodeCapabilities,
    modifier_locals: ModifierLocalsHandle,
    inspector_snapshot: Vec<ModifierChainInspectorNode>,
    inspector_entry_scratch: Vec<Option<ModifierInspectorRecord>>,
    debug_logging: bool,
}

impl Default for ModifierChainHandle {
    fn default() -> Self {
        Self {
            chain: ModifierNodeChain::new(),
            context: RefCell::new(BasicModifierNodeContext::new()),
            resolved: ResolvedModifiers::default(),
            capabilities: NodeCapabilities::default(),
            aggregate_child_capabilities: NodeCapabilities::default(),
            modifier_locals: Rc::new(RefCell::new(ModifierLocalManager::new())),
            inspector_snapshot: Vec::new(),
            inspector_entry_scratch: Vec::new(),
            debug_logging: false,
        }
    }
}

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

    /// Reconciles the underlying [`ModifierNodeChain`] with the elements stored in `modifier`.
    pub fn update(&mut self, modifier: &Modifier) -> Vec<ModifierInvalidation> {
        let mut resolver = |_: ModifierLocalToken| None;
        self.update_with_resolver(modifier, &mut resolver)
    }

    pub fn update_with_resolver(
        &mut self,
        modifier: &Modifier,
        resolver: &mut ModifierLocalAncestorResolver<'_>,
    ) -> Vec<ModifierInvalidation> {
        // Use iterator-based update to avoid allocation entirely
        self.chain
            .update_from_ref_iter(modifier.iter_elements(), &mut *self.context.borrow_mut());
        self.capabilities = self.chain.capabilities();
        self.aggregate_child_capabilities = self.chain.head().aggregate_child_capabilities();
        let modifier_local_invalidations = self
            .modifier_locals
            .borrow_mut()
            .sync(&self.chain, resolver);

        // Only recompute resolved modifiers if layout-affecting nodes changed.
        // Check if any LAYOUT invalidation was produced during update.
        let needs_resolved_update = {
            let ctx = self.context.borrow();
            ctx.invalidations()
                .iter()
                .any(|inv| inv.kind() == InvalidationKind::Layout)
        };
        if needs_resolved_update {
            self.resolved = self.compute_resolved();
        }

        // Only collect inspector snapshot when debugging is enabled (lazy collection)
        let should_log = self.debug_logging || modifier_debug_enabled();
        if should_log {
            self.collect_inspector_snapshot(modifier);
            crate::debug::log_modifier_chain(self.chain(), self.inspector_snapshot());
            crate::debug::emit_modifier_chain_trace(self.inspector_snapshot());
        }
        modifier_local_invalidations
    }

    /// Enables or disables per-handle modifier debug logging.
    pub fn set_debug_logging(&mut self, enabled: bool) {
        self.debug_logging = enabled;
    }

    pub fn set_node_id(&mut self, id: Option<NodeId>) {
        // Check if the ID is actually changing
        let old_id = self.context.borrow().node_id();
        if old_id == id {
            // ID hasn't changed, nothing to do
            return;
        }

        self.context.borrow_mut().set_node_id(id);

        // When a valid ID is provided AND it changed, force a reset of the modifier chain's lifecycle.
        // This ensures that nodes can access the new ID via the context during `on_attach`.
        if id.is_some() {
            self.chain.detach_nodes();
            self.chain.repair_chain();
            self.chain.attach_nodes(&mut *self.context.borrow_mut());
        }
    }

    /// Returns the modifier node chain for read-only traversal.
    pub fn chain(&self) -> &ModifierNodeChain {
        &self.chain
    }

    /// Returns mutable access to the modifier node chain.
    pub fn chain_mut(&mut self) -> &mut ModifierNodeChain {
        &mut self.chain
    }

    /// Returns mutable access to the modifier node context.
    pub fn context_mut(&self) -> std::cell::RefMut<'_, BasicModifierNodeContext> {
        self.context.borrow_mut()
    }

    /// Returns mutable references to both the chain and context.
    /// This is a convenience method for measurement that avoids borrow conflicts.
    pub fn chain_and_context_mut(
        &mut self,
    ) -> (
        &mut ModifierNodeChain,
        std::cell::RefMut<'_, BasicModifierNodeContext>,
    ) {
        (&mut self.chain, self.context.borrow_mut())
    }

    /// Returns the aggregated capability mask for the reconciled chain.
    pub fn capabilities(&self) -> NodeCapabilities {
        self.capabilities
    }

    /// Returns the aggregate child capability mask rooted at the sentinel head.
    pub fn aggregate_child_capabilities(&self) -> NodeCapabilities {
        self.aggregate_child_capabilities
    }

    pub fn has_layout_nodes(&self) -> bool {
        self.capabilities.contains(NodeCapabilities::LAYOUT)
    }

    pub fn has_draw_nodes(&self) -> bool {
        self.capabilities.contains(NodeCapabilities::DRAW)
    }

    pub fn has_pointer_input_nodes(&self) -> bool {
        self.capabilities.contains(NodeCapabilities::POINTER_INPUT)
    }

    pub fn has_semantics_nodes(&self) -> bool {
        self.capabilities.contains(NodeCapabilities::SEMANTICS)
    }

    /// Drains invalidations requested during the last update cycle.
    pub fn take_invalidations(&self) -> Vec<ModifierInvalidation> {
        self.context.borrow_mut().take_invalidations()
    }

    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
        self.resolved
    }

    pub fn resolve_modifier_local(
        &self,
        token: ModifierLocalToken,
    ) -> Option<ResolvedModifierLocal> {
        self.modifier_locals.borrow().resolve(token)
    }

    pub fn modifier_locals_handle(&self) -> ModifierLocalsHandle {
        Rc::clone(&self.modifier_locals)
    }

    pub fn inspector_snapshot(&self) -> &[ModifierChainInspectorNode] {
        &self.inspector_snapshot
    }

    /// Explicitly collects the inspector snapshot for testing purposes.
    /// Unlike `update()` which only collects when debug logging is enabled,
    /// this method always populates the snapshot.
    #[cfg(test)]
    pub fn refresh_inspector_snapshot(&mut self, modifier: &Modifier) {
        self.collect_inspector_snapshot(modifier);
    }

    fn compute_resolved(&self) -> ResolvedModifiers {
        let mut resolved = ResolvedModifiers::default();
        let mut layout = LayoutProperties::default();
        let mut padding = EdgeInsets::default();
        let mut offset = Point::default();

        self.chain.for_each_forward(|node_ref| {
            node_ref.with_node(|node| {
                let any = node.as_any();
                if let Some(padding_node) = any.downcast_ref::<PaddingNode>() {
                    padding += padding_node.padding();
                } else if let Some(size_node) = any.downcast_ref::<SizeNode>() {
                    apply_size_node(&mut layout, size_node);
                } else if let Some(fill_node) = any.downcast_ref::<FillNode>() {
                    apply_fill_node(&mut layout, fill_node);
                } else if let Some(intrinsic_node) = any.downcast_ref::<IntrinsicSizeNode>() {
                    apply_intrinsic_size_node(&mut layout, intrinsic_node);
                } else if let Some(weight_node) = any.downcast_ref::<WeightNode>() {
                    layout.weight = Some(weight_node.layout_weight());
                } else if let Some(alignment_node) = any.downcast_ref::<AlignmentNode>() {
                    if let Some(alignment) = alignment_node.box_alignment() {
                        layout.box_alignment = Some(alignment);
                    }
                    if let Some(alignment) = alignment_node.column_alignment() {
                        layout.column_alignment = Some(alignment);
                    }
                    if let Some(alignment) = alignment_node.row_alignment() {
                        layout.row_alignment = Some(alignment);
                    }
                } else if let Some(offset_node) = any.downcast_ref::<OffsetNode>() {
                    let delta = offset_node.offset();
                    offset.x += delta.x;
                    offset.y += delta.y;
                }
                // Note: BackgroundNode, CornerShapeNode, and GraphicsLayerNode are no longer
                // tracked in ResolvedModifiers. Visual rendering now flows through modifier slices
                // collected from the node chain at draw time.
            });
        });

        resolved.set_padding(padding);
        resolved.set_layout_properties(layout);
        resolved.set_offset(offset);
        resolved
    }

    fn collect_inspector_snapshot(&mut self, modifier: &Modifier) {
        if self.chain.is_empty() {
            self.inspector_snapshot.clear();
            return;
        }

        let chain_len = self.chain.len();
        self.inspector_entry_scratch.clear();
        self.inspector_entry_scratch.resize_with(chain_len, || None);
        for (index, metadata) in modifier.iter_inspector_metadata().enumerate() {
            if index >= chain_len {
                break;
            }
            self.inspector_entry_scratch[index] = Some(metadata.to_record());
        }

        self.inspector_snapshot.clear();
        self.inspector_snapshot.reserve(chain_len);

        let chain = &self.chain;
        let inspector_entry_scratch = &mut self.inspector_entry_scratch;
        let inspector_snapshot = &mut self.inspector_snapshot;

        chain.for_each_forward(|node_ref| {
            node_ref.with_node(|node| {
                let depth = node_ref.delegate_depth();
                let entry_index = node_ref.entry_index();
                let inspector = if depth == 0 {
                    entry_index
                        .and_then(|idx| inspector_entry_scratch.get_mut(idx))
                        .and_then(|slot| slot.take())
                } else {
                    None
                };
                inspector_snapshot.push(ModifierChainInspectorNode {
                    depth,
                    entry_index,
                    type_name: type_name_of_val(node),
                    capabilities: node_ref.kind_set(),
                    aggregate_child_capabilities: node_ref.aggregate_child_capabilities(),
                    inspector,
                });
            });
        });
    }

    /// Access a text field modifier node in the chain with a mutable callback.
    ///
    /// Searches for `TextFieldModifierNode` and calls the callback if found.
    /// Returns `None` if no text field modifier is in the chain.
    pub fn with_text_field_modifier_mut<R>(
        &mut self,
        mut f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
    ) -> Option<R> {
        let mut result = None;
        self.chain.visit_nodes_mut(|node, capabilities| {
            if capabilities.contains(NodeCapabilities::LAYOUT) {
                let any = node.as_any_mut();
                if let Some(text_field) = any.downcast_mut::<crate::TextFieldModifierNode>() {
                    if result.is_none() {
                        result = Some(f(text_field));
                    }
                }
            }
        });
        result
    }
}

fn apply_size_node(layout: &mut LayoutProperties, node: &SizeNode) {
    if let Some(width) = node.max_width().or(node.min_width()) {
        layout.width = DimensionConstraint::Points(width);
    }
    if let Some(height) = node.max_height().or(node.min_height()) {
        layout.height = DimensionConstraint::Points(height);
    }
    if !node.enforce_incoming() {
        if let Some(min_width) = node.min_width() {
            layout.min_width = Some(min_width);
        }
        if let Some(max_width) = node.max_width() {
            layout.max_width = Some(max_width);
        }
        if let Some(min_height) = node.min_height() {
            layout.min_height = Some(min_height);
        }
        if let Some(max_height) = node.max_height() {
            layout.max_height = Some(max_height);
        }
    }
}

fn apply_fill_node(layout: &mut LayoutProperties, node: &FillNode) {
    let fraction = node.fraction();
    match node.direction() {
        FillDirection::Horizontal => {
            layout.width = DimensionConstraint::Fraction(fraction);
        }
        FillDirection::Vertical => {
            layout.height = DimensionConstraint::Fraction(fraction);
        }
        FillDirection::Both => {
            layout.width = DimensionConstraint::Fraction(fraction);
            layout.height = DimensionConstraint::Fraction(fraction);
        }
    }
}

fn apply_intrinsic_size_node(layout: &mut LayoutProperties, node: &IntrinsicSizeNode) {
    let constraint = DimensionConstraint::Intrinsic(node.intrinsic_size());
    match node.axis() {
        IntrinsicAxis::Width => {
            layout.width = constraint;
        }
        IntrinsicAxis::Height => {
            layout.height = constraint;
        }
    }
}

#[cfg(test)]
mod tests {
    use cranpose_foundation::{
        InvalidationKind, ModifierInvalidation, ModifierNode, NodeCapabilities,
    };

    use super::*;
    use crate::modifier::Color;
    use crate::modifier_nodes::PaddingNode;

    #[test]
    fn attaches_padding_node_and_invalidates_layout() {
        let mut handle = ModifierChainHandle::new();

        let _ = handle.update(&Modifier::empty().padding(8.0));

        assert_eq!(handle.chain().len(), 1);

        let invalidations = handle.take_invalidations();
        assert_eq!(
            invalidations,
            vec![ModifierInvalidation::new(
                InvalidationKind::Layout,
                NodeCapabilities::LAYOUT
            )]
        );
    }

    #[test]
    fn reuses_nodes_between_updates() {
        let mut handle = ModifierChainHandle::new();

        let _ = handle.update(&Modifier::empty().padding(12.0));
        let first_ptr = node_ptr::<PaddingNode>(&handle);
        handle.take_invalidations();

        let _ = handle.update(&Modifier::empty().padding(12.0));
        let second_ptr = node_ptr::<PaddingNode>(&handle);

        assert_eq!(first_ptr, second_ptr, "expected the node to be reused");
        assert!(
            handle.take_invalidations().is_empty(),
            "no additional invalidations should be issued for a pure update"
        );
    }

    #[test]
    fn modifier_slices_capture_background_and_shape() {
        use crate::modifier::slices::collect_modifier_slices;

        let mut handle = ModifierChainHandle::new();
        let _ = handle.update(
            &Modifier::empty()
                .background(Color(0.2, 0.3, 0.4, 1.0))
                .then(Modifier::empty().rounded_corners(8.0)),
        );

        // Background and shape are now captured in modifier slices as draw commands
        let slices = collect_modifier_slices(handle.chain());
        assert!(
            !slices.draw_commands().is_empty(),
            "Expected draw commands for background"
        );

        let _ = handle.update(
            &Modifier::empty()
                .rounded_corners(4.0)
                .then(Modifier::empty().background(Color(0.9, 0.1, 0.1, 1.0))),
        );
        let slices = collect_modifier_slices(handle.chain());
        assert!(
            !slices.draw_commands().is_empty(),
            "Expected draw commands after update"
        );

        let _ = handle.update(&Modifier::empty());
        let slices = collect_modifier_slices(handle.chain());
        assert!(
            slices.draw_commands().is_empty(),
            "Expected no draw commands with empty modifier"
        );
    }

    #[test]
    fn capability_mask_updates_with_chain() {
        let mut handle = ModifierChainHandle::new();
        let _ = handle.update(&Modifier::empty().padding(4.0));
        assert_eq!(handle.capabilities(), NodeCapabilities::LAYOUT);
        assert!(handle.has_layout_nodes());
        assert!(!handle.has_draw_nodes());
        handle.take_invalidations();

        let color = Color(0.5, 0.6, 0.7, 1.0);
        let _ = handle.update(&Modifier::empty().background(color));
        assert_eq!(handle.capabilities(), NodeCapabilities::DRAW);
        assert!(handle.has_draw_nodes());
        assert!(!handle.has_layout_nodes());
    }

    #[test]
    fn offset_update_invalidates_layout() {
        let mut handle = ModifierChainHandle::new();
        let _ = handle.update(&Modifier::empty().offset(0.0, 0.0));
        handle.take_invalidations();

        let _ = handle.update(&Modifier::empty().offset(12.0, 0.0));
        let invalidations = handle.take_invalidations();

        assert!(
            invalidations
                .iter()
                .any(|invalidation| invalidation.kind() == InvalidationKind::Layout),
            "expected offset changes to invalidate layout"
        );
    }

    fn node_ptr<N: ModifierNode + 'static>(handle: &ModifierChainHandle) -> *const N {
        handle
            .chain()
            .node::<N>(0)
            .map(|node| &*node as *const N)
            .expect("expected node to exist")
    }
}