Skip to main content

cranpose_core/
node.rs

1use std::any::{Any, TypeId};
2
3use smallvec::SmallVec;
4
5use crate::{
6    Applier, Command, Composer, DirtyBubble, NodeError, NodeId, composer_context,
7    with_current_composer,
8};
9
10/// Runs `f` on the node `id` as an `N`, using the current composer. Returns an error if the node
11/// does not exist or is not an `N`. Must be called during composition.
12pub fn with_node_mut<N: Node + 'static, R>(
13    id: NodeId,
14    f: impl FnOnce(&mut N) -> R,
15) -> Result<R, NodeError> {
16    with_current_composer(|composer| composer.with_node_mut(id, f))
17}
18
19/// Makes the node `id` the parent of the nodes emitted next, using the current composer. Needs a
20/// matching `pop_parent`. Must be called during composition.
21pub fn push_parent(id: NodeId) {
22    with_current_composer(|composer| composer.push_parent(id));
23}
24
25/// Closes the parent that the matching `push_parent` opened, using the current composer. Must be
26/// called during composition.
27pub fn pop_parent() {
28    with_current_composer(Composer::pop_parent);
29}
30
31/// A node of the tree that a composition builds. An applier stores the nodes by id. Every method
32/// has a default, so a simple node implements none of them.
33pub trait Node: Any {
34    /// Called once the node has its id, as the composition makes the node.
35    fn mount(&mut self) {}
36    /// Called just before the node is removed from the applier.
37    fn unmount(&mut self) {}
38    /// Adds `child` to this node's child list, returning whether the list
39    /// actually changed. A node that already holds the child returns `false`:
40    /// callers record a structural change from this answer, and a structural
41    /// change re-lowers the whole subtree, so claiming one for a no-op costs a
42    /// full rebuild per call.
43    fn insert_child(&mut self, _child: NodeId) -> bool {
44        false
45    }
46    /// Removes `child` from this node's child list, returning whether the list
47    /// actually changed. Only this node can answer that: a caller inspecting
48    /// the child's parent pointer gets it wrong when the child was reparented
49    /// while still listed here.
50    fn remove_child(&mut self, _child: NodeId) -> bool {
51        false
52    }
53    /// Moves the child at the first index to the second index in the child list.
54    fn move_child(&mut self, _from: usize, _to: usize) {}
55    /// Replaces the child list with `children`, in order. The default takes
56    /// out each child the node holds and puts in each of `children`.
57    fn update_children(&mut self, children: &[NodeId]) {
58        let mut held = SmallVec::<[NodeId; 8]>::new();
59        self.collect_children_into(&mut held);
60        for child in held {
61            self.remove_child(child);
62        }
63        for &child in children {
64            self.insert_child(child);
65        }
66    }
67    /// Whether the node adds and drops its children itself, as a
68    /// subcomposition host does with its slot hosts: the child sync a
69    /// composition pass ends with then leaves its list alone. The default
70    /// keeps the list the passes compose.
71    fn keeps_own_children(&self) -> bool {
72        false
73    }
74    /// Copies child IDs into the provided scratch buffer without allocating a
75    /// fresh container for every traversal. A node without children leaves
76    /// the buffer empty.
77    fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
78        out.clear();
79    }
80    /// Runs `f` on each child id in the order [`Node::collect_children_into`]
81    /// lists them. A node that holds its list in place overrides this to
82    /// visit it without a copy.
83    fn for_each_child(&self, f: &mut dyn FnMut(NodeId)) {
84        let mut children = SmallVec::<[NodeId; 8]>::new();
85        self.collect_children_into(&mut children);
86        for child in children {
87            f(child);
88        }
89    }
90    /// Copies the ids of the children this node owns, in order, into `out`. A node whose
91    /// `collect_children_into` leaves some children out overrides this to list them all. The
92    /// default calls `collect_children_into`.
93    fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
94        self.collect_children_into(out);
95    }
96    /// Finds a child in the order returned by [`Node::collect_owned_children_into`].
97    /// Nodes with slice-backed child storage should override this to avoid
98    /// materializing the whole list for a single lookup.
99    ///
100    /// ```
101    /// use cranpose_core::{Node, NodeId};
102    ///
103    /// fn child_is_first(parent: &dyn Node, child: NodeId) -> bool {
104    ///     parent.owned_child_index(child) == Some(0)
105    /// }
106    /// ```
107    fn owned_child_index(&self, child: NodeId) -> Option<usize> {
108        let mut children = SmallVec::<[NodeId; 8]>::new();
109        self.collect_owned_children_into(&mut children);
110        children.iter().position(|&id| id == child)
111    }
112    /// Called after the node is created to record its own ID.
113    /// Useful for nodes that need to store their ID for later operations.
114    fn set_node_id(&mut self, _id: NodeId) {}
115    /// Called once, in place of [`Node::set_node_id`] and [`Node::mount`],
116    /// for a node a composition pass made under a `parent` the same pass
117    /// made: the node takes its parent, its `id` and its mount at once, and
118    /// joins the parent's children when the parent's composition closes. The
119    /// pass bubbles no dirt from the node: it is new, as is the parent, and
120    /// the attach of the new subtree's root carries the dirt above it.
121    fn mount_under(&mut self, parent: NodeId, id: NodeId) {
122        self.on_attached_to_parent(parent);
123        self.set_node_id(id);
124        self.mount();
125    }
126    /// Called when this node is attached to a parent.
127    /// Nodes with parent tracking should set their parent reference here.
128    fn on_attached_to_parent(&mut self, _parent: NodeId) {}
129    /// Called when this node is removed from its parent.
130    /// Nodes with parent tracking should clear their parent reference here.
131    fn on_removed_from_parent(&mut self) {}
132    /// Get this node's parent ID (for nodes that track parents).
133    /// Returns None if node has no parent or doesn't track parents.
134    fn parent(&self) -> Option<NodeId> {
135        None
136    }
137    /// Mark this node as needing layout (for nodes with dirty flags).
138    /// Called during bubbling to propagate dirtiness up the tree.
139    fn mark_needs_layout(&self) {}
140    /// Check if this node needs layout (for nodes with dirty flags).
141    fn needs_layout(&self) -> bool {
142        false
143    }
144    /// Mark this node as needing measure (size may have changed).
145    /// Called during bubbling when children are added/removed.
146    fn mark_needs_measure(&self) {}
147    /// Check if this node needs measure (for nodes with dirty flags).
148    fn needs_measure(&self) -> bool {
149        false
150    }
151    /// Mark that a node below this one needs layout, or measure when
152    /// `measure` is set: a layout pass has to visit this node to reach it,
153    /// while this node's own measurement may still hold. A node that does not
154    /// track the difference marks itself dirty.
155    fn mark_descendant_needs_layout(&self, measure: bool) {
156        if measure {
157            self.mark_needs_measure();
158        } else {
159            self.mark_needs_layout();
160        }
161    }
162    /// Check if a node below this one needs layout or measure.
163    fn descendant_needs_layout(&self) -> bool {
164        false
165    }
166    /// Check if a node below this one needs measure.
167    fn descendant_needs_measure(&self) -> bool {
168        false
169    }
170    /// Check if a layout pass has to visit this node: the node or a node
171    /// below it needs layout or measure.
172    fn layout_dirty(&self) -> bool {
173        self.needs_measure() || self.needs_layout() || self.descendant_needs_layout()
174    }
175    /// Whether the node lays out nothing itself and its parent lays out its
176    /// children, so a change of its own is a change of its parent's.
177    fn is_virtual(&self) -> bool {
178        false
179    }
180    /// Mark this node as needing semantics recomputation.
181    fn mark_needs_semantics(&self) {}
182    /// Mark that the semantics tree has to read this node again while its
183    /// own semantics are unchanged: a node below it changed its semantics,
184    /// or its own placement or children changed.
185    fn mark_descendant_needs_semantics(&self) {
186        self.mark_needs_semantics();
187    }
188    /// Check if this node or a node below it needs semantics recomputation.
189    fn needs_semantics(&self) -> bool {
190        false
191    }
192    /// Set parent reference for dirty flag bubbling ONLY.
193    /// This is a minimal version of on_attached_to_parent that doesn't trigger
194    /// registry updates or other side effects. Used during measurement when we
195    /// need to establish parent connections for bubble_measure_dirty without
196    /// causing the full attachment lifecycle.
197    ///
198    /// An existing parent is preserved until the structural attach operation
199    /// removes the node from its previous container.
200    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
201        if self.parent().is_none() {
202            self.on_attached_to_parent(parent);
203        }
204    }
205
206    /// Returns a recycle pool key when this node supports shell reuse.
207    fn recycle_key(&self) -> Option<TypeId> {
208        None
209    }
210
211    /// Bounds how many recyclable shells of this node type should be retained.
212    fn recycle_pool_limit(&self) -> Option<usize> {
213        None
214    }
215
216    /// Clears live attachments before the node shell enters a recycle pool.
217    fn prepare_for_recycle(&mut self) {}
218
219    /// Optionally provides a compact replacement box for this recycled shell.
220    ///
221    /// Returning `Some` lets nodes move pooled survivors onto fresh compact
222    /// storage so the recycle pool does not pin large spike-era allocations.
223    fn rehouse_for_recycle(&self) -> Option<Box<dyn Node>> {
224        None
225    }
226
227    /// Optionally moves a live node onto a fresh box during applier compaction.
228    ///
229    /// This is used after large-majority teardowns where a small surviving live
230    /// tree can otherwise pin allocator pages from a much larger spike-era node
231    /// population. Implementations must preserve the node's live state.
232    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn Node>> {
233        None
234    }
235
236    /// Returns the node-owned heap retained beyond the node's own box allocation.
237    fn debug_heap_bytes(&self) -> usize {
238        0
239    }
240}
241
242// forwards on purpose: DirtyBubble is crate-private, and this is the public entry
243/// Unified API for bubbling layout dirty flags from a node to the root (Applier context).
244///
245/// This is the canonical function for dirty bubbling during the apply phase (structural changes).
246/// Call this after mutations like insert/remove/move that happen during apply.
247///
248/// # Behavior
249/// 1. Marks the starting node as needing layout
250/// 2. Walks up the parent chain, marking each ancestor
251/// 3. Stops at the root (node with no parent)
252///
253/// # Performance
254/// This function is O(height): a scoped layout repass can leave a dirty node
255/// under a clean ancestor, so the walk does not stop at a dirty ancestor.
256///
257/// # Usage
258/// - Call from composer mutations (insert/remove/move) during apply phase
259/// - Call from applier-level operations that modify the tree structure
260pub fn bubble_layout_dirty(applier: &mut dyn Applier, node_id: NodeId) {
261    DirtyBubble::LAYOUT.apply(applier, node_id);
262}
263
264// forwards on purpose: DirtyBubble is crate-private, and this is the public entry
265/// Unified API for bubbling measure dirty flags from a node to the root (Applier context).
266///
267/// Call this when a node's size may have changed (children added/removed, modifier changed).
268/// This ensures that measure_layout will increment the cache epoch and re-measure the subtree.
269///
270/// # Behavior
271/// 1. Marks the starting node as needing measure
272/// 2. Walks up the parent chain, marking each ancestor
273/// 3. Stops at the root (node with no parent)
274pub fn bubble_measure_dirty(applier: &mut dyn Applier, node_id: NodeId) {
275    DirtyBubble::MEASURE.apply(applier, node_id);
276}
277
278// forwards on purpose: DirtyBubble is crate-private, and this is the public entry
279/// Unified API for bubbling semantics dirty flags from a node to the root (Applier context).
280///
281/// This mirrors [`bubble_layout_dirty`] but toggles semantics-specific dirty
282/// flags instead of layout ones, allowing semantics updates to propagate during
283/// the apply phase without forcing layout work.
284pub fn bubble_semantics_dirty(applier: &mut dyn Applier, node_id: NodeId) {
285    DirtyBubble::SEMANTICS.apply(applier, node_id);
286}
287
288/// Schedules semantics bubbling for a node using the active composer if present.
289///
290/// This defers the work to the apply phase where we can safely mutate the
291/// applier tree without re-entrantly borrowing the composer during composition.
292pub fn queue_semantics_invalidation(node_id: NodeId) {
293    let _ = composer_context::try_with_composer(|composer| {
294        composer.enqueue_semantics_invalidation(node_id);
295    });
296}
297
298/// Unified API for bubbling layout dirty flags from a node to the root (Composer context).
299///
300/// This is the canonical function for dirty bubbling during composition (property changes).
301/// Call this after property changes that happen during composition via with_node_mut.
302///
303/// # Behavior
304/// 1. Marks the starting node as needing layout
305/// 2. Walks up the parent chain, marking each ancestor
306/// 3. Stops at the root (node with no parent)
307///
308/// # Performance
309/// This function is O(height): a scoped layout repass can leave a dirty node
310/// under a clean ancestor, so the walk does not stop at a dirty ancestor.
311///
312/// # Type Requirements
313/// The node type N must implement Node (which includes mark_needs_layout, parent, etc.).
314/// Typically this will be LayoutNode or similar layout-aware node types.
315///
316/// # Usage
317/// - Call from property setters during composition (e.g., set_modifier, set_measure_policy)
318/// - Call from widget composition when layout-affecting state changes
319pub fn bubble_layout_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
320    bubble_layout_dirty_composer::<N>(node_id);
321}
322
323/// Unified API for bubbling measure dirty flags from a node to the root during composition.
324///
325/// This queues a dirty-bubble command on the active composer so measure invalidation
326/// runs during the apply phase, avoiding re-entrant applier borrows while widgets are
327/// mutating nodes via `with_node_mut`.
328pub fn bubble_measure_dirty_in_composer(node_id: NodeId) {
329    with_current_composer(|composer| {
330        composer.commands_mut().push(Command::BubbleDirty {
331            node_id,
332            bubble: DirtyBubble {
333                layout: false,
334                measure: true,
335                semantics: false,
336            },
337        });
338    });
339}
340
341/// Unified API for bubbling semantics dirty flags from a node to the root (Composer context).
342///
343/// This mirrors [`bubble_layout_dirty_in_composer`] but routes through the semantics
344/// dirty flag instead of the layout one. Modifier nodes can request semantics
345/// invalidations without triggering measure/layout work, and the runtime can
346/// query the root to determine whether the semantics tree needs rebuilding.
347pub fn bubble_semantics_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
348    bubble_semantics_dirty_composer::<N>(node_id);
349}
350
351fn bubble_layout_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
352    let _ = with_node_mut(node_id, |node: &mut N| {
353        node.mark_needs_layout();
354    });
355    with_current_composer(|composer| composer.borrow_applier().note_layout_dirt(node_id));
356
357    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
358        let parent_id = pid;
359
360        let advanced = with_node_mut(parent_id, |node: &mut N| {
361            node.mark_descendant_needs_layout(false);
362            true
363        })
364        .unwrap_or(false);
365
366        if advanced {
367            node_id = parent_id;
368        } else {
369            break;
370        }
371    }
372}
373
374fn bubble_semantics_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
375    let _ = with_node_mut(node_id, |node: &mut N| {
376        node.mark_needs_semantics();
377    });
378
379    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
380        let parent_id = pid;
381
382        let advanced = with_node_mut(parent_id, |node: &mut N| {
383            if !node.needs_semantics() {
384                node.mark_descendant_needs_semantics();
385            }
386            true
387        })
388        .unwrap_or(false);
389
390        if advanced {
391            node_id = parent_id;
392        } else {
393            break;
394        }
395    }
396}
397
398impl dyn Node {
399    /// Returns the node as `Any`, for downcasting to its concrete type.
400    pub fn as_any_mut(&mut self) -> &mut dyn Any {
401        self
402    }
403}