Skip to main content

nativeview_layout/paragraph/
sync.rs

1//! Incremental `ChangeSet` synchronization, `box <-> inline` transition tracking, and O(runs)
2//! interaction-state recompilation for [`ParagraphStore`].
3
4use nativeview_abi::{NodeId, NV_PARAGRAPH_NONE};
5use nativeview_engine::InteractionTracker;
6use nativeview_store::{ChangeSet, NodeStore};
7
8use crate::measure::ResolvedTextStyle;
9use crate::taffy_store::responsive::text::ResponsiveTextEnv;
10
11use super::InheritedText;
12use crate::MAX_TREE_DEPTH;
13
14use super::ParagraphStore;
15
16impl ParagraphStore {
17    /// Unlinks and frees `id`'s compiled paragraph span in O(1) via swap-remove without traversing
18    /// descendants (safe to call from inside [`Self::sync_subtree_inline_transitions`]).
19    ///
20    /// Leaves `was_inline` and `inline_to_box` untouched so [`Self::sync_subtree_inline_transitions`]
21    /// remains the single source of truth for subtree `inline -> box` transitions and promoted
22    /// descendant paragraph roots.
23    fn unlink_paragraph_span(&mut self, id: NodeId) -> bool {
24        let idx = id.index();
25        if idx >= self.node_to_para.len() {
26            return false;
27        }
28        let slot = self.node_to_para[idx];
29        if slot == NV_PARAGRAPH_NONE {
30            return false;
31        }
32        let slot_usize = slot as usize;
33        self.node_to_para[idx] = NV_PARAGRAPH_NONE;
34
35        let old_meta = self.meta[slot_usize];
36        let old_run_span = old_meta.run_span;
37        let old_text_span = old_meta.text_span;
38
39        let run_start = old_run_span.off() as usize;
40        let run_len = old_run_span.len() as usize;
41        for k in 0..run_len {
42            let rid = self.runs.data()[run_start + k].node_id;
43            if rid != id
44                && !rid.is_null()
45                && rid.index() < self.owner_paragraph.len()
46                && self.owner_paragraph[rid.index()] == id
47            {
48                self.owner_paragraph[rid.index()] = NodeId::NULL;
49            }
50        }
51
52        self.runs.free(old_run_span);
53        self.text.free(old_text_span);
54
55        let last = self.spans.len() - 1;
56        if slot_usize != last {
57            let moved_owner = self.spans[last].owner_node_id;
58            self.spans.swap_remove(slot_usize);
59            self.meta.swap_remove(slot_usize);
60            if moved_owner.index() < self.node_to_para.len() {
61                self.node_to_para[moved_owner.index()] = slot;
62            }
63        } else {
64            self.spans.pop();
65            self.meta.pop();
66        }
67        true
68    }
69
70    /// Removes `id`'s compiled paragraph span in O(1) via swap-remove and synchronizes any
71    /// descendant `inline <-> box` transitions.
72    pub(super) fn remove_paragraph_span(&mut self, store: &NodeStore, id: NodeId, push_list: bool) {
73        if !self.unlink_paragraph_span(id) {
74            return;
75        }
76        if store.is_live(id) {
77            self.sync_subtree_inline_transitions(store, id, push_list);
78        }
79    }
80
81    /// Walks live descendants of `root` whenever an inline/box flip occurs, keeping `was_inline`,
82    /// `owner_paragraph`, `box_to_inline`, and `inline_to_box` exact even for deep subtrees.
83    fn sync_subtree_inline_transitions(&mut self, store: &NodeStore, root: NodeId, push_list: bool) {
84        let base = self.subtree_stack.len();
85        self.subtree_stack.push(root);
86        let mut visited = 0usize;
87        let cap = store.capacity().max(1);
88        while self.subtree_stack.len() > base {
89            let Some(nid) = self.subtree_stack.pop() else {
90                break;
91            };
92            if visited > cap || !store.is_live(nid) {
93                continue;
94            }
95            visited += 1;
96            let idx = nid.index();
97            let now_inline = store.is_inline(nid);
98            let prev_inline = self.was_inline[idx];
99            if prev_inline != now_inline {
100                self.was_inline[idx] = now_inline;
101                if now_inline {
102                    if !self.is_created_this_frame(nid) {
103                        self.box_to_inline.push(nid);
104                    }
105                    if self.node_to_para[idx] != NV_PARAGRAPH_NONE {
106                        self.unlink_paragraph_span(nid);
107                    }
108                } else {
109                    self.owner_paragraph[idx] = NodeId::NULL;
110                    if !self.is_created_this_frame(nid) {
111                        self.inline_to_box.push(nid);
112                    }
113                    if store.is_inline_context_root(nid) {
114                        self.queue_dirty(nid, push_list);
115                    }
116                }
117                for &child in store.children(nid) {
118                    self.subtree_stack.push(child);
119                }
120            } else if !now_inline && nid == root {
121                for &child in store.children(nid) {
122                    let cidx = child.index();
123                    if cidx < self.was_inline.len()
124                        && store.is_live(child)
125                        && self.was_inline[cidx] != store.is_inline(child)
126                    {
127                        self.subtree_stack.push(child);
128                    }
129                }
130            }
131        }
132        self.subtree_stack.truncate(base);
133    }
134
135    fn find_paragraph_root(store: &NodeStore, mut id: NodeId) -> Option<NodeId> {
136        for _ in 0..MAX_TREE_DEPTH {
137            let p = store.parent(id)?;
138            if store.is_inline_context_root(p) {
139                return Some(p);
140            }
141            if !store.is_inline(p) {
142                return None;
143            }
144            id = p;
145        }
146        None
147    }
148
149    fn lift_to_paragraph(&mut self, store: &NodeStore, id: NodeId, push_list: bool) {
150        let idx = id.index();
151        if idx < self.owner_paragraph.len() {
152            let prev_owner = self.owner_paragraph[idx];
153            if !prev_owner.is_null() {
154                if store.is_live(prev_owner) && store.is_inline_context_root(prev_owner) {
155                    self.queue_dirty(prev_owner, push_list);
156                }
157                if !store.is_live(id) || !store.is_inline(id) {
158                    self.owner_paragraph[idx] = NodeId::NULL;
159                }
160            }
161        }
162        if store.is_live(id) {
163            if store.is_inline(id) {
164                if let Some(root) = Self::find_paragraph_root(store, id) {
165                    self.queue_dirty(root, push_list);
166                }
167            } else if store.is_inline_context_root(id) {
168                self.queue_dirty(id, push_list);
169            } else if idx < self.node_to_para.len() && self.node_to_para[idx] != NV_PARAGRAPH_NONE
170            {
171                self.remove_paragraph_span(store, id, push_list);
172            }
173        }
174    }
175
176    /// Synchronizes paragraph spans for one committed `ChangeSet`.
177    pub fn sync_changes(
178        &mut self,
179        store: &NodeStore,
180        changes: &ChangeSet,
181        inherited: InheritedText<'_>,
182        interaction: Option<&InteractionTracker>,
183        defer_compile: bool,
184    ) {
185        self.ensure_capacity(store.capacity());
186        self.reset_frame_deltas();
187        let push_list = !defer_compile;
188
189        // Pre-reserve paragraph slabs in O(1) allocations for bulk loads (e.g. Frame-0 boot).
190        if !changes.created.is_empty() {
191            let mut new_paras = 0usize;
192            for &id in &changes.created {
193                if store.is_live(id) && store.is_inline_context_root(id) {
194                    new_paras += 1;
195                }
196            }
197            if new_paras > 0 {
198                self.spans.reserve(new_paras);
199                self.meta.reserve(new_paras);
200                self.dirty_layout_paras.reserve(new_paras);
201                self.dirty_paint_paras.reserve(new_paras);
202                let _ = self
203                    .runs
204                    .try_reserve_data(self.runs.data().len().saturating_add(new_paras));
205                if push_list {
206                    self.dirty_paras.reserve(new_paras);
207                }
208            }
209        }
210
211        Self::bump_epoch(&mut self.created_epoch, &mut self.created_stamp);
212        for &id in &changes.created {
213            let idx = id.index();
214            if idx < self.created_stamp.len() {
215                self.created_stamp[idx] = self.created_epoch;
216            }
217        }
218
219        for &id in &changes.removed {
220            let idx = id.index();
221            if idx < self.owner_paragraph.len() {
222                let owner = self.owner_paragraph[idx];
223                if !owner.is_null() && store.is_live(owner) && store.is_inline_context_root(owner) {
224                    self.queue_dirty(owner, push_list);
225                }
226                self.owner_paragraph[idx] = NodeId::NULL;
227                self.was_inline[idx] = false;
228            }
229            if idx < self.node_to_para.len() && self.node_to_para[idx] != NV_PARAGRAPH_NONE {
230                self.remove_paragraph_span(store, id, push_list);
231            }
232        }
233
234        for &id in &changes.created {
235            if !store.is_live(id) {
236                continue;
237            }
238            let idx = id.index();
239            self.was_inline[idx] = store.is_inline(id);
240            self.owner_paragraph[idx] = NodeId::NULL;
241            self.lift_to_paragraph(store, id, push_list);
242        }
243
244        for &parent in &changes.children {
245            if !store.is_live(parent) {
246                continue;
247            }
248            self.sync_subtree_inline_transitions(store, parent, push_list);
249            self.lift_to_paragraph(store, parent, push_list);
250            if store.is_inline_context_root(parent) || store.is_inline(parent) {
251                for &child in store.children(parent) {
252                    if store.is_live(child) {
253                        self.sync_subtree_inline_transitions(store, child, push_list);
254                    }
255                }
256            }
257        }
258
259        for &id in &changes.touched {
260            if !store.is_live(id) {
261                continue;
262            }
263            let idx = id.index();
264            if self.was_inline[idx] != store.is_inline(id) {
265                self.sync_subtree_inline_transitions(store, id, push_list);
266            } else if idx < self.node_to_para.len()
267                && self.node_to_para[idx] != NV_PARAGRAPH_NONE
268                && !store.is_inline_context_root(id)
269            {
270                self.remove_paragraph_span(store, id, push_list);
271            }
272            self.lift_to_paragraph(store, id, push_list);
273        }
274
275        if push_list {
276            let count = self.dirty_paras.len();
277            for i in 0..count {
278                let pid = self.dirty_paras[i];
279                if !store.is_live(pid) || !store.is_inline_context_root(pid) {
280                    continue;
281                }
282                let (base_text, base_rtl) = self.cached_or_parent_base(
283                    store,
284                    pid,
285                    inherited.text,
286                    inherited.rtl,
287                );
288                let (layout_changed, paint_changed) = self.compile_paragraph(
289                    store,
290                    pid,
291                    base_text,
292                    base_rtl,
293                    interaction,
294                    inherited.responsive,
295                );
296                // Clear the dirty stamp now that `pid` is compiled under `base_text`/`base_rtl`:
297                // a subsequent localized `sync_inherited_paragraph` will still recompile if the
298                // inherited base actually changed (`base_changed`), avoiding double compiles.
299                self.dirty_stamp[pid.index()] = 0;
300                if layout_changed {
301                    self.record_layout_dirty(pid);
302                }
303                if paint_changed {
304                    self.record_paint_dirty(pid);
305                }
306            }
307            self.dirty_paras.clear();
308        }
309    }
310
311    #[inline]
312    fn cached_or_parent_base(
313        &self,
314        store: &NodeStore,
315        pid: NodeId,
316        resolved_text: &[ResolvedTextStyle],
317        resolved_rtl: &[bool],
318    ) -> (ResolvedTextStyle, bool) {
319        if !resolved_text.is_empty() && !resolved_rtl.is_empty() {
320            return match store.parent(pid) {
321                Some(p) if p.index() < resolved_text.len() && p.index() < resolved_rtl.len() => {
322                    (resolved_text[p.index()], resolved_rtl[p.index()])
323                }
324                _ => (ResolvedTextStyle::default(), false),
325            };
326        }
327        if let Some(slot) = self.paragraph_slot(pid) {
328            let m = self.meta[slot as usize];
329            return (m.base_style, m.base_rtl);
330        }
331        (ResolvedTextStyle::default(), false)
332    }
333
334    /// Compiles or updates paragraph root `pid` during a box-tree inheritance walk (`parent_text`,
335    /// `parent_rtl` are the resolved inherited values of `pid`'s parent box). Returns
336    /// `(layout_changed, paint_changed)`.
337    pub fn sync_inherited_paragraph(
338        &mut self,
339        store: &NodeStore,
340        pid: NodeId,
341        parent_text: ResolvedTextStyle,
342        parent_rtl: bool,
343        interaction: Option<&InteractionTracker>,
344        responsive: Option<ResponsiveTextEnv<'_>>,
345    ) -> (bool, bool) {
346        self.ensure_capacity(store.capacity());
347        if !store.is_live(pid) || !store.is_inline_context_root(pid) {
348            return (false, false);
349        }
350        let idx = pid.index();
351        let queued = self.dirty_stamp[idx] == self.dirty_epoch;
352        let existing_slot = self.paragraph_slot(pid);
353        let base_changed = existing_slot.is_none_or(|slot| {
354            let m = self.meta[slot as usize];
355            m.base_rtl != parent_rtl || !m.base_style.style_eq(&parent_text)
356        });
357        if !queued && !base_changed {
358            return (false, false);
359        }
360        self.dirty_stamp[idx] = 0;
361        self.recompile_paragraph(store, pid, parent_text, parent_rtl, interaction, responsive)
362    }
363
364    /// Unconditionally recompiles paragraph root `pid` (e.g. after its responsive environment
365    /// changed). Returns `(layout_changed, paint_changed)`.
366    pub fn recompile_paragraph(
367        &mut self,
368        store: &NodeStore,
369        pid: NodeId,
370        parent_text: ResolvedTextStyle,
371        parent_rtl: bool,
372        interaction: Option<&InteractionTracker>,
373        responsive: Option<ResponsiveTextEnv<'_>>,
374    ) -> (bool, bool) {
375        self.ensure_capacity(store.capacity());
376        if !store.is_live(pid) || !store.is_inline_context_root(pid) {
377            return (false, false);
378        }
379        let (layout_changed, paint_changed) =
380            self.compile_paragraph(store, pid, parent_text, parent_rtl, interaction, responsive);
381        if layout_changed {
382            self.record_layout_dirty(pid);
383        }
384        if paint_changed {
385            self.record_paint_dirty(pid);
386        }
387        (layout_changed, paint_changed)
388    }
389
390    /// Recompiles only the paragraphs affected by interactive pseudo-state changes (`:hover`,
391    /// `:active`, `:focus`, `:disabled`) in O(dirty * runs) with 0 tree walks and 0 allocations.
392    pub fn sync_interaction_dirty(
393        &mut self,
394        store: &NodeStore,
395        interaction: &InteractionTracker,
396        dirty_nodes: &[NodeId],
397        responsive: Option<ResponsiveTextEnv<'_>>,
398    ) -> (&[NodeId], &[NodeId]) {
399        self.ensure_capacity(store.capacity());
400        self.dirty_layout_paras.clear();
401        self.dirty_paint_paras.clear();
402        self.dirty_paras.clear();
403        Self::bump_epoch(&mut self.dirty_epoch, &mut self.dirty_stamp);
404        Self::bump_epoch(&mut self.paint_dirty_epoch, &mut self.paint_dirty_stamp);
405        Self::bump_epoch(&mut self.layout_dirty_epoch, &mut self.layout_dirty_stamp);
406
407        for &nid in dirty_nodes {
408            if !store.is_live(nid) {
409                continue;
410            }
411            if let Some(owner) = self.owner_paragraph(nid) {
412                if store.is_live(owner) && store.is_inline_context_root(owner) {
413                    self.queue_dirty(owner, true);
414                }
415            } else if store.is_inline_context_root(nid) {
416                self.queue_dirty(nid, true);
417            }
418        }
419
420        let count = self.dirty_paras.len();
421        for i in 0..count {
422            let pid = self.dirty_paras[i];
423            let Some(slot) = self.paragraph_slot(pid) else {
424                continue;
425            };
426            let m = self.meta[slot as usize];
427            let (layout_changed, paint_changed) = self.compile_paragraph(
428                store,
429                pid,
430                m.base_style,
431                m.base_rtl,
432                Some(interaction),
433                responsive,
434            );
435            if layout_changed {
436                self.record_layout_dirty(pid);
437            }
438            if paint_changed {
439                self.record_paint_dirty(pid);
440            }
441        }
442        self.dirty_paras.clear();
443        (&self.dirty_layout_paras, &self.dirty_paint_paras)
444    }
445}