Skip to main content

nativeview_store/tx/
children.rs

1//! Parent/child tree operations of [`Transaction`].
2
3use crate::id::{NodeId, NodeIndex};
4use crate::store::{ANCESTOR_MARK, CHILD_SEEN, CHILDREN_DIRTY, CONNECTED, LIVE, NodeStore};
5use crate::tx::{touch, TxCore};
6use nativeview_abi::table::effect;
7
8impl TxCore<'_> {
9    #[inline]
10    fn mark_children(&mut self, parent: NodeIndex) {
11        let s = &mut *self.store;
12        let row = &mut s.nodes[parent];
13        let first = row.flags & CHILDREN_DIRTY == 0;
14        row.flags |= CHILDREN_DIRTY;
15        s.reparented.push_if(parent, first);
16        touch(row, &mut s.touched, parent, effect::LAYOUT);
17    }
18
19    /// A child that joined another parent: its row (`parent`) changed and it inherits a new
20    /// context (typography, layout), so it is dirty in its own right — not merely moved.
21    #[inline]
22    fn mark_reparented(&mut self, child: NodeIndex) {
23        let s = &mut *self.store;
24        touch(
25            &mut s.nodes[child],
26            &mut s.touched,
27            child,
28            effect::LAYOUT | effect::MEASURE | effect::PAINT,
29        );
30    }
31
32    /// A still-live child that left its parent without joining another: its row (`parent`)
33    /// changed and it no longer renders, so hosts and layout must see it.
34    const DETACHED_EFFECTS: u8 = effect::LAYOUT | effect::PAINT;
35
36    /// `set`: clears the parent pointer of every child of `parent` and flags it `CHILD_SEEN`;
37    /// `!set`: drops those flags again, touching every flagged child that stayed detached and
38    /// clearing `CONNECTED` down its subtree when transitioning out of a connected parent (zero
39    /// steady-state allocations).
40    fn flag_children(&mut self, parent: NodeId, set: bool) {
41        let owner = self.store.nodes[parent.node_index()].children;
42        let (off, len) = (owner.off as usize, owner.len as usize);
43        for k in 0..len {
44            let c = self.store.children.data()[off + k];
45            let idx = c.node_index();
46            if set {
47                let Some(r) = self.store.nodes.get_mut(idx) else {
48                    continue;
49                };
50                if r.parent == parent {
51                    r.parent = NodeId::NULL;
52                    r.flags |= CHILD_SEEN;
53                }
54            } else {
55                let mut should_disconnect = false;
56                {
57                    let NodeStore { nodes, touched, .. } = &mut *self.store;
58                    let Some(r) = nodes.get_mut(idx) else {
59                        continue;
60                    };
61                    if r.flags & CHILD_SEEN != 0 && r.parent.is_null() {
62                        touch(r, touched, idx, Self::DETACHED_EFFECTS);
63                        should_disconnect = (r.flags & CONNECTED) != 0;
64                    }
65                    r.flags &= !CHILD_SEEN;
66                }
67                if should_disconnect {
68                    self.store.propagate_connected(idx, false);
69                }
70            }
71        }
72    }
73
74    /// Returns `true` if `candidate` equals `node` or is an ancestor of `node`.
75    fn is_ancestor_or_self(&self, candidate: NodeId, mut node: NodeId) -> bool {
76        let mut hops = 0usize;
77        let limit = self.store.nodes.len();
78        while !node.is_null() {
79            if node == candidate {
80                return true;
81            }
82            hops += 1;
83            if hops > limit {
84                return true;
85            }
86            let Some(p) = self.store.parent(node) else {
87                break;
88            };
89            node = p;
90        }
91        false
92    }
93
94    /// Validated child-list replacement returning `false` without mutating the tree if `parent` is
95    /// dead, any child is non-live/`NULL`, any child is duplicated, or any child would form a cycle.
96    /// Fallible version of [`Self::set_children`] returning `false` on dead/NULL/duplicate/cyclic input.
97    pub fn try_set_children(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
98        if !self.store.is_live(parent) {
99            return false;
100        }
101        // O(K) unchanged fast path: existing children are already live, unique, and acyclic.
102        if self.store.children(parent) == new_children {
103            return true;
104        }
105        // Mark `parent` and its ancestor chain once so cycle detection across K children is
106        // O(K + depth) instead of O(K * depth), with zero heap allocations.
107        let limit = self.store.nodes.len();
108        let mut cur = parent;
109        let mut anc_hops = 0usize;
110        while !cur.is_null() && anc_hops <= limit {
111            let cidx = cur.node_index();
112            self.store.nodes[cidx].flags |= ANCESTOR_MARK;
113            anc_hops += 1;
114            let p = self.store.nodes[cidx].parent;
115            if p.is_null() || !self.store.is_live(p) {
116                break;
117            }
118            cur = p;
119        }
120
121        let mut valid = true;
122        let mut marked = 0usize;
123        for &c in new_children {
124            if c == NodeId::ROOT || !self.store.is_live(c) {
125                valid = false;
126                break;
127            }
128            let idx = c.node_index();
129            if self.store.nodes[idx].flags & (ANCESTOR_MARK | CHILD_SEEN) != 0 {
130                valid = false;
131                break;
132            }
133            self.store.nodes[idx].flags |= CHILD_SEEN;
134            marked += 1;
135        }
136        for &c in &new_children[..marked] {
137            self.store.nodes[c.node_index()].flags &= !CHILD_SEEN;
138        }
139        // Clear ancestor scratch marks.
140        let mut cur = parent;
141        let mut clr_hops = 0usize;
142        while !cur.is_null() && clr_hops <= limit {
143            let cidx = cur.node_index();
144            self.store.nodes[cidx].flags &= !ANCESTOR_MARK;
145            clr_hops += 1;
146            let p = self.store.nodes[cidx].parent;
147            if p.is_null() || !self.store.is_live(p) {
148                break;
149            }
150            cur = p;
151        }
152        if !valid {
153            return false;
154        }
155        let parent_idx = parent.node_index();
156        let parent_connected = (self.store.nodes[parent_idx].flags & CONNECTED) != 0;
157        // Clear previous parent pointers, flagging the old children (`CHILD_SEEN` scratch) so a
158        // child that stays is told apart from one that arrives — without a temporary Vec.
159        self.flag_children(parent, true);
160        for &c in new_children {
161            let idx = c.node_index();
162            if self.store.nodes[idx].flags & CHILD_SEEN == 0 {
163                if self.store.parent(c).is_some() {
164                    self.detach_child_inner(c, false);
165                }
166                self.mark_reparented(idx);
167            }
168            self.store.nodes[idx].parent = parent;
169            if ((self.store.nodes[idx].flags & CONNECTED) != 0) != parent_connected {
170                self.store.propagate_connected(idx, parent_connected);
171            }
172        }
173        self.flag_children(parent, false);
174        let s = &mut *self.store;
175        let old_span = s.nodes[parent_idx].children;
176        let span = s.children.replace(old_span, new_children);
177        s.nodes[parent_idx].children = span;
178        self.mark_children(parent_idx);
179        true
180    }
181
182    /// Replaces the ordered child list of `parent` (no-op when unchanged or invalid, zero heap
183    /// allocations). Rejects dead/null nodes, duplicates, and cycles; detaches moved children from
184    /// any previous parent.
185    pub fn set_children(&mut self, parent: NodeId, new_children: &[NodeId]) {
186        let _ = self.try_set_children(parent, new_children);
187    }
188
189    /// Inserts `child` at `index` (clamped) in `parent`'s child list, moving it from any previous
190    /// parent (zero heap allocations via `SpanPool::insert_at`). Ignores dead nodes or cycles.
191    pub fn insert_child(&mut self, parent: NodeId, index: usize, child: NodeId) {
192        if child == NodeId::ROOT
193            || !self.store.is_live(parent)
194            || !self.store.is_live(child)
195            || self.is_ancestor_or_self(child, parent)
196        {
197            return;
198        }
199        let parent_idx = parent.node_index();
200        let child_idx = child.node_index();
201        let parent_connected = (self.store.nodes[parent_idx].flags & CONNECTED) != 0;
202        let moved_in = self.store.parent(child) != Some(parent);
203        self.detach_child_inner(child, false);
204        let s = &mut *self.store;
205        let old_span = s.nodes[parent_idx].children;
206        let new_span = s.children.insert_at(old_span, index, child);
207        s.nodes[parent_idx].children = new_span;
208        s.nodes[child_idx].parent = parent;
209        if ((s.nodes[child_idx].flags & CONNECTED) != 0) != parent_connected {
210            s.propagate_connected(child_idx, parent_connected);
211        }
212        self.mark_children(parent_idx);
213        if moved_in {
214            self.mark_reparented(child_idx);
215        }
216    }
217
218    /// Appends `child` to `parent` (zero heap allocations).
219    #[inline]
220    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
221        let len = self.store.children(parent).len();
222        self.insert_child(parent, len, child);
223    }
224
225    /// Detaches `child` from its parent (the child stays alive).
226    pub fn detach_child(&mut self, child: NodeId) {
227        self.detach_child_inner(child, true);
228    }
229
230    pub(crate) fn detach_child_inner(&mut self, child: NodeId, propagate_disconnect: bool) {
231        let Some(parent) = self.store.parent(child) else {
232            return;
233        };
234        let parent_idx = parent.node_index();
235        let s = &mut *self.store;
236        let span = s.nodes[parent_idx].children;
237        if let Some(at) = s.children.get(span).iter().position(|&c| c == child) {
238            let new_span = s.children.remove_at(span, at);
239            s.nodes[parent_idx].children = new_span;
240        }
241        let child_idx = child.node_index();
242        s.nodes[child_idx].parent = NodeId::NULL;
243        touch(&mut s.nodes[child_idx], &mut s.touched, child_idx, Self::DETACHED_EFFECTS);
244        if propagate_disconnect && (s.nodes[child_idx].flags & CONNECTED) != 0 {
245            s.propagate_connected(child_idx, false);
246        }
247        self.mark_children(parent_idx);
248    }
249}
250
251impl NodeStore {
252    /// Propagates `CONNECTED` across `root_idx`'s live subtree when its connectivity flips.
253    /// Each child is flipped before pushing, so every node is visited at most once (`<= nodes.len()`).
254    pub(crate) fn propagate_connected(&mut self, root_idx: NodeIndex, connected: bool) {
255        let root_node_idx = NodeId::ROOT.node_index();
256        let root_gen = NodeId::ROOT.generation();
257        let Some(row) = self.nodes.get_mut(root_idx) else {
258            return;
259        };
260        if (row.flags & LIVE) == 0
261            || (!connected && root_idx == root_node_idx && row.generation == root_gen)
262        {
263            return;
264        }
265        if ((row.flags & CONNECTED) != 0) == connected {
266            return;
267        }
268        if connected {
269            row.flags |= CONNECTED;
270        } else {
271            row.flags &= !CONNECTED;
272        }
273        if row.children.len == 0 {
274            return;
275        }
276        self.connected_stack.clear();
277        self.connected_stack.push(root_idx);
278        while let Some(parent_idx) = self.connected_stack.pop() {
279            let span = self.nodes[parent_idx].children;
280            let (off, len) = (span.off as usize, span.len as usize);
281            for k in 0..len {
282                let cid = self.children.data()[off + k];
283                let cidx = cid.node_index();
284                let Some(crow) = self.nodes.get_mut(cidx) else {
285                    continue;
286                };
287                if (crow.flags & LIVE) == 0 || crow.generation != cid.generation() {
288                    continue;
289                }
290                if !connected && cidx == root_node_idx && crow.generation == root_gen {
291                    continue;
292                }
293                if ((crow.flags & CONNECTED) != 0) != connected {
294                    if connected {
295                        crow.flags |= CONNECTED;
296                    } else {
297                        crow.flags &= !CONNECTED;
298                    }
299                    if crow.children.len > 0 {
300                        self.connected_stack.push(cidx);
301                    }
302                }
303            }
304        }
305    }
306}