Skip to main content

nativeview_layout/taffy_store/
sync.rs

1//! Change-set synchronization, invalidation, and box-tree inheritance propagation for
2//! [`TaffyStoreLayout`].
3
4use nativeview_abi::table::effect;
5use nativeview_engine::InteractionTracker;
6use nativeview_store::{ChangeSet, NodeId, NodeStore, NvTable};
7use nativeview_tables::tables::{
8    Direction as NvDirection, Interaction, Layout as NvLayout, Overlay, Responsive,
9    Transform as TransformTable, Typography, is_display_contents,
10};
11use taffy::tree::ClearState;
12
13use crate::{InheritedText, ResolvedBoxEdges, ResolvedTextStyle};
14
15use super::container::scope::committed_container_env;
16use super::responsive::text::ResponsiveTextEnv;
17use super::transform_cb::{has_store_transform, subtree_has_out_of_flow};
18use crate::scene::state_rules_patch_box;
19use super::responsive::sync::NodeStyleFlags;
20use super::{TaffyStoreLayout, UnroundedBox};
21
22impl TaffyStoreLayout {
23    /// Invalidates cached Taffy entries for all layout/measure/structural changes in `changes`.
24    pub fn sync_changes(&mut self, store: &NodeStore, changes: &ChangeSet) {
25        self.sync_changes_with_interaction(store, changes, None);
26    }
27
28    pub fn sync_changes_with_interaction(
29        &mut self,
30        store: &NodeStore,
31        changes: &ChangeSet,
32        interaction: Option<&InteractionTracker>,
33    ) {
34        self.ensure_capacity(store.capacity());
35        // Refresh `style_flags` and responsive/container counters BEFORE `top_layer.sync`,
36        // `enqueue_inherit_root`, and `paragraphs.sync_changes` so `0 -> 1` transitions enable
37        // `display_env!` media/container resolution on the very same commit.
38        for &id in &changes.removed {
39            let idx = id.index();
40            if idx < self.style_flags.len() {
41                self.set_style_flags(idx, NodeStyleFlags::empty());
42            }
43        }
44        for &id in &changes.created {
45            if store.is_live(id) {
46                self.sync_node_responsive_counters(store, id);
47            }
48        }
49        if let Some(resp_td) = changes.table(Responsive::slot()) {
50            for &id in resp_td.nodes.iter().chain(&resp_td.detached) {
51                if store.is_live(id) {
52                    self.sync_node_responsive_counters(store, id);
53                }
54            }
55            self.responsive_changed_this_pass = true;
56            // `@media { display: none }` or `show_on` on open overlays/ancestors may flip hoisting.
57            self.top_layer.invalidate();
58        }
59        let flag_words =
60            (1u32 << NvLayout::CONTAINER_TYPE.word()) | (1u32 << NvLayout::POSITION.word());
61        if let Some(layout_td) = changes.table(NvLayout::slot()) {
62            for (&id, &m) in layout_td.nodes.iter().zip(&layout_td.masks) {
63                if (m & flag_words) != 0 && store.is_live(id) {
64                    self.sync_node_responsive_counters(store, id);
65                }
66            }
67            for &id in &layout_td.detached {
68                if store.is_live(id) {
69                    self.sync_node_responsive_counters(store, id);
70                }
71            }
72        }
73        // A state rule may patch `position` (OOF candidacy), `container_type`, or `display`.
74        if let Some(td) = changes.table(Interaction::slot()) {
75            for &id in td.nodes.iter().chain(&td.detached) {
76                if store.is_live(id) {
77                    self.sync_node_responsive_counters(store, id);
78                }
79            }
80        }
81
82        // Hoisting changes reshape only the affected DOM parents and the root (below), never the
83        // whole box tree: a `display` / `OPEN` change triggers the inheritance
84        // walk only when it flips `display: contents` (or direction).
85        let top_layer_changed =
86            self.top_layer
87                .sync(store, changes, &display_env!(self, interaction));
88
89        let root_id = self.last_viewport.map_or(NodeId::ROOT, |(r, _, _)| r);
90        let dir_bit = 1u32 << NvLayout::DIRECTION.word();
91        let disp_bit = 1u32 << NvLayout::DISPLAY.word();
92        let layout_bits = dir_bit | disp_bit;
93        if let Some(td) = changes.table(NvLayout::slot()) {
94            for &id in &td.detached {
95                if !store.is_inline(id) {
96                    self.enqueue_inherit_root(store, id, true, interaction);
97                }
98            }
99            for (&id, &m) in td.nodes.iter().zip(&td.masks) {
100                if !store.is_inline(id) && m & layout_bits != 0 {
101                    if m & disp_bit != 0
102                        && self.display_change_reshapes_boxes(store, id, interaction)
103                    {
104                        self.enqueue_inherit_root(store, id, true, interaction);
105                    } else if m & dir_bit != 0 && self.direction_changed(store, id) {
106                        self.enqueue_inherit_root(store, id, false, interaction);
107                    }
108                }
109            }
110        }
111        for (slot, bit) in [(Overlay::slot(), 1u32 << Overlay::OPTIONS.word())] {
112            if let Some(td) = changes.table(slot) {
113                for (&id, &m) in td.nodes.iter().zip(&td.masks) {
114                    if m & bit != 0
115                        && !store.is_inline(id)
116                        && self.display_change_reshapes_boxes(store, id, interaction)
117                    {
118                        self.enqueue_inherit_root(store, id, true, interaction);
119                    }
120                }
121                for &id in &td.detached {
122                    if !store.is_inline(id)
123                        && self.display_change_reshapes_boxes(store, id, interaction)
124                    {
125                        self.enqueue_inherit_root(store, id, true, interaction);
126                    }
127                }
128            }
129        }
130        // Non-inline Typography edits require subtree inheritance propagation; pure inline edits
131        // are handled O(1) directly inside `ParagraphStore::sync_changes`.
132        if let Some(td) = changes.table(Typography::slot()) {
133            for &id in td.nodes.iter().chain(&td.detached) {
134                if !store.is_inline(id) {
135                    self.enqueue_inherit_root(store, id, false, interaction);
136                }
137            }
138        }
139        let responsive_changed = if let Some(td) = changes.table(Responsive::slot()) {
140            for &id in td.nodes.iter().chain(&td.detached) {
141                if !store.is_inline(id) {
142                    self.enqueue_inherit_root(store, id, true, interaction);
143                }
144            }
145            true
146        } else {
147            false
148        };
149        let box_topology_changed = changes.created.iter().any(|&id| !store.is_inline(id))
150            || changes
151                .removed
152                .iter()
153                .any(|&id| self.paragraphs.owner_paragraph(id).is_none())
154            || changes
155                .children
156                .iter()
157                .any(|&id| !store.is_inline(id) && !store.is_inline_context_root(id));
158        if box_topology_changed {
159            for &id in &changes.children {
160                if !store.is_inline(id) && !store.is_inline_context_root(id) {
161                    self.enqueue_inherit_root(store, id, true, interaction);
162                }
163            }
164            for &id in &changes.created {
165                if store.is_live(id) && !store.is_inline(id) {
166                    if id == root_id {
167                        self.mark_inherit_full();
168                    } else if store
169                        .parent(id)
170                        .is_none_or(|p| !changes.children.contains(&p))
171                    {
172                        self.enqueue_inherit_root(store, id, true, interaction);
173                    }
174                }
175            }
176            if !changes.removed.is_empty() && !self.inherit_dirty {
177                // Removed node without a parent in `changes.children` (e.g. root or orphan).
178                self.committed_store_rev = None;
179            }
180        }
181        if changes
182            .children
183            .iter()
184            .any(|&id| !store.is_inline(id) && !store.is_inline_context_root(id))
185        {
186            // Non-inline `set_children` may detach a live box without removing it; a full-root
187            // pass bumps `rect_valid_gen` so `layout_of(detached)` becomes `None`.
188            self.full_layout_needed = true;
189        }
190        if box_topology_changed || responsive_changed {
191            self.responsive_tree_dirty = true;
192        }
193
194        // Sync compiled paragraphs (lifting inline edits to owning paragraph roots). Defer
195        // compilation only when a full-tree inheritance walk will visit every paragraph anyway;
196        // localized subtree walks leave untouched branches to this pass.
197        let cenvs = &self.resolved_container_env;
198        let lookup = |n: NodeId| committed_container_env(cenvs, n);
199        self.paragraphs.sync_changes(
200            store,
201            changes,
202            InheritedText {
203                text: &self.resolved_text,
204                rtl: &self.resolved_rtl,
205                responsive: (self.responsive_node_count > 0).then_some(ResponsiveTextEnv {
206                    media: &self.media_env,
207                    container_env_of: &lookup,
208                }),
209            },
210            interaction,
211            self.inherit_full,
212        );
213        if !self.paragraphs.box_to_inline_transitions().is_empty()
214            || !self.paragraphs.inline_to_box_transitions().is_empty()
215        {
216            self.full_layout_needed = true;
217            if self.responsive_node_count > 0 {
218                self.responsive_tree_dirty = true;
219            }
220        }
221
222        for &id in &changes.removed {
223            let idx = id.index();
224            if idx < self.caches.len() {
225                if self.rect_gen[idx] != 0 || self.was_contents[idx] {
226                    self.layout_dirty = true;
227                    self.full_layout_needed = true;
228                }
229                self.caches[idx].clear();
230                self.boxes[idx] = UnroundedBox::default();
231                if self.capture_box_edges && idx < self.box_edges.len() {
232                    self.box_edges[idx] = ResolvedBoxEdges::default();
233                }
234                self.rects[idx] = nativeview_engine::LayoutRect::default();
235                self.rect_gen[idx] = 0;
236                self.node_gens[idx] = 0;
237                self.resolved_rtl[idx] = false;
238                self.was_contents[idx] = false;
239                self.was_transformed[idx] = false;
240                if idx < self.cached_env_hash.len() {
241                    self.cached_env_hash[idx] = 0;
242                    self.para_last_env_hash[idx] = 0;
243                }
244                self.container_records.clear_slot(idx);
245                self.boundary_records.clear_slot(idx);
246                self.resolved_container_env.clear_slot(idx);
247                self.resolved_text[idx] = ResolvedTextStyle::default();
248                self.hoisted.release(idx);
249                self.box_children.release(idx);
250            }
251        }
252        for &id in &changes.created {
253            if !store.is_live(id) || store.is_inline(id) {
254                continue;
255            }
256            let idx = id.index();
257            self.caches[idx].clear();
258            self.boxes[idx] = UnroundedBox::default();
259            if self.capture_box_edges && idx < self.box_edges.len() {
260                self.box_edges[idx] = ResolvedBoxEdges::default();
261            }
262            self.rects[idx] = nativeview_engine::LayoutRect::default();
263            self.rect_gen[idx] = 0;
264            // Leave `node_gens[idx] = 0` (unvisited) until `propagate_inheritance` /
265            // `commit_round_walk` resolves this node, so `resolve_inherit_roots` detects unvisited
266            // parents accurately and slot-reused nodes always report in `changed_rects`.
267            self.node_gens[idx] = 0;
268            self.was_contents[idx] = false;
269            self.was_transformed[idx] = has_store_transform(store, id);
270            if idx < self.cached_env_hash.len() {
271                self.cached_env_hash[idx] = 0;
272                self.para_last_env_hash[idx] = 0;
273            }
274            self.container_records.clear_slot(idx);
275            self.boundary_records.clear_slot(idx);
276            self.resolved_container_env.clear_slot(idx);
277            self.hoisted.release(idx);
278            self.box_children.release(idx);
279            self.mark_dirty(store, id);
280        }
281        if let Some(resp_td) = changes.table(Responsive::slot()) {
282            for &id in resp_td.nodes.iter().chain(&resp_td.detached) {
283                if store.is_live(id) {
284                    if id.index() < self.para_last_env_hash.len() {
285                        self.para_last_env_hash[id.index()] = 0;
286                    }
287                    if store.is_inline(id) {
288                        if let Some(owner) = self.paragraphs.owner_paragraph(id)
289                            && store.is_live(owner)
290                        {
291                            if owner.index() < self.para_last_env_hash.len() {
292                                self.para_last_env_hash[owner.index()] = 0;
293                            }
294                            self.mark_dirty(store, owner);
295                        }
296                    } else {
297                        self.mark_dirty(store, id);
298                    }
299                }
300            }
301        }
302        for &id in &changes.children {
303            if !store.is_inline(id) && !store.is_inline_context_root(id) {
304                self.mark_dirty(store, id);
305            }
306        }
307        for (&id, &fx) in changes.touched.iter().zip(changes.effects.iter()) {
308            if store.is_inline(id) {
309                continue;
310            }
311            if fx & effect::LAYOUT != 0
312                || (fx & effect::MEASURE != 0
313                    && (!store.is_inline_context_root(id)
314                        || (!self.measure_hooks.is_empty()
315                            && self
316                                .paragraphs
317                                .paragraph_view(store, id)
318                                .is_none_or(|p| p.text.len == 0 || p.run_count == 0))))
319            {
320                self.mark_dirty(store, id);
321            }
322        }
323        if let Some(tf_td) = changes.table(TransformTable::slot()) {
324            for &id in tf_td.nodes.iter().chain(&tf_td.detached) {
325                if store.is_live(id) && !store.is_inline(id) {
326                    let now_tf = has_store_transform(store, id);
327                    if self.was_transformed[id.index()] != now_tf {
328                        self.was_transformed[id.index()] = now_tf;
329                        if subtree_has_out_of_flow(store, id) {
330                            self.mark_dirty(store, id);
331                        }
332                    }
333                }
334            }
335        }
336        for i in 0..self.paragraphs.box_to_inline_transitions().len() {
337            let id = self.paragraphs.box_to_inline_transitions()[i];
338            let idx = id.index();
339            self.sync_node_responsive_counters(store, id);
340            if idx < self.caches.len() {
341                self.caches[idx].clear();
342                self.boxes[idx] = UnroundedBox::default();
343                self.rects[idx] = nativeview_engine::LayoutRect::default();
344                self.rect_gen[idx] = 0;
345                self.container_records.clear_slot(idx);
346                self.boundary_records.clear_slot(idx);
347                self.hoisted.release(idx);
348                self.box_children.release(idx);
349            }
350            if let Some(p) = store.parent(id) {
351                self.enqueue_inherit_root(store, p, true, interaction);
352                self.mark_dirty(store, p);
353            } else {
354                self.mark_inherit_full();
355            }
356        }
357        for i in 0..self.paragraphs.inline_to_box_transitions().len() {
358            let id = self.paragraphs.inline_to_box_transitions()[i];
359            self.sync_node_responsive_counters(store, id);
360            if let Some(p) = store.parent(id) {
361                self.enqueue_inherit_root(store, p, true, interaction);
362            } else {
363                self.mark_inherit_full();
364            }
365            self.mark_dirty(store, id);
366        }
367        for i in 0..self.paragraphs.dirty_layout_paragraphs().len() {
368            let pid = self.paragraphs.dirty_layout_paragraphs()[i];
369            self.mark_dirty(store, pid);
370        }
371        if top_layer_changed {
372            self.reshape_top_layer(store, root_id, interaction);
373        }
374        if self.inherit_dirty || self.layout_dirty {
375            self.dry.invalidate();
376        }
377        if !self.inherit_dirty && self.committed_store_rev.is_some() {
378            // Inherited state is untouched by this commit: dry runs may keep reusing it.
379            self.committed_store_rev = Some((store.instance_id(), store.frame()));
380        }
381    }
382
383    /// After a pass committed new `@container` environments, re-resolves hoisting against them.
384    /// Returns `true` (with the box lists reshaped) when the hoisted set changed.
385    pub(super) fn refresh_top_layer_after_pass(
386        &mut self,
387        store: &NodeStore,
388        root: NodeId,
389        interaction: Option<&InteractionTracker>,
390    ) -> bool {
391        if self.container_node_count == 0 {
392            return false;
393        }
394        self.top_layer.invalidate();
395        let changed = self
396            .top_layer
397            .refresh(store, root, &display_env!(self, interaction));
398        if changed {
399            self.reshape_top_layer(store, root, interaction);
400        }
401        changed
402    }
403
404    /// Re-attaches top-layer roots whose state changed without an inheritance walk: each one's
405    /// nearest box-generating DOM parent rebuilds its box children (dropping or regaining it)
406    /// and the layout root rebuilds with the new hoisted set appended.
407    pub(super) fn reshape_top_layer(
408        &mut self,
409        store: &NodeStore,
410        root: NodeId,
411        interaction: Option<&InteractionTracker>,
412    ) {
413        self.layout_dirty = true;
414        self.full_layout_needed = true;
415        if let Some(c) = self.caches.get_mut(root.index()) {
416            c.clear();
417        }
418        if self.inherit_full {
419            // The pending full inheritance walk rebuilds every list.
420            return;
421        }
422        for i in 0..self.top_layer.transitions().len() {
423            let id = self.top_layer.transitions()[i];
424            if !store.is_live(id) || store.is_inline(id) {
425                continue;
426            }
427            if let Some(c) = self.caches.get_mut(id.index()) {
428                c.clear();
429            }
430            let mut parent = store.parent(id);
431            for _ in 0..crate::MAX_TREE_DEPTH {
432                match parent {
433                    Some(p)
434                        if p != root
435                            && display_env!(self, interaction).is_display_contents(store, p) =>
436                    {
437                        parent = store.parent(p).filter(|&gp| gp != p);
438                    }
439                    _ => break,
440                }
441            }
442            if let Some(p) = parent
443                && p != root
444                && store.is_live(p)
445            {
446                let env = display_env!(self, interaction);
447                self.box_children
448                    .rebuild(store, &self.top_layer, p, &[], &env);
449                self.mark_dirty(store, p);
450            }
451        }
452        if store.is_live(root) && !store.is_inline_context_root(root) {
453            let env = display_env!(self, interaction);
454            self.box_children
455                .rebuild(store, &self.top_layer, root, self.top_layer.hoisted(), &env);
456        }
457        self.box_children.compact_if_fragmented();
458    }
459
460    pub fn sync_interaction_paragraphs(
461        &mut self,
462        store: &NodeStore,
463        interaction: &InteractionTracker,
464        dirty_nodes: &[NodeId],
465    ) -> (&[NodeId], &[NodeId]) {
466        let cenvs = &self.resolved_container_env;
467        let lookup = |n: NodeId| committed_container_env(cenvs, n);
468        let responsive = (self.responsive_node_count > 0).then_some(ResponsiveTextEnv {
469            media: &self.media_env,
470            container_env_of: &lookup,
471        });
472        let layout_count = self
473            .paragraphs
474            .sync_interaction_dirty(store, interaction, dirty_nodes, responsive)
475            .0
476            .len();
477        if layout_count > 0 {
478            for i in 0..layout_count {
479                let pid = self.paragraphs.dirty_layout_paragraphs()[i];
480                self.mark_dirty(store, pid);
481            }
482            self.dry.invalidate();
483        }
484        // Pseudo-state `StateRules` that patch `display` / `position` / `container_type` reflow
485        // their node (Web parity): a `display: contents` flip reshapes box lists, any other change
486        // re-lays out.
487        for &id in dirty_nodes {
488            if store.is_live(id) && !store.is_inline(id) && state_rules_patch_box(store, id) {
489                if self.display_change_reshapes_boxes(store, id, Some(interaction)) {
490                    self.enqueue_inherit_root(store, id, true, Some(interaction));
491                }
492                self.mark_dirty(store, id);
493                if let Some(parent) = store.parent(id) {
494                    self.mark_dirty(store, parent);
495                }
496                self.dry.invalidate();
497            }
498        }
499        // The same patches on an overlay's chain re-hoist it.
500        if self
501            .top_layer
502            .sync_nodes(store, dirty_nodes, &display_env!(self, Some(interaction)))
503        {
504            let root = self.last_viewport.map_or(NodeId::ROOT, |(r, _, _)| r);
505            self.reshape_top_layer(store, root, Some(interaction));
506            self.dry.invalidate();
507        }
508        (
509            self.paragraphs.dirty_layout_paragraphs(),
510            self.paragraphs.dirty_paint_paragraphs(),
511        )
512    }
513
514    /// Whether `id`'s resolved direction differs from the one recorded by the last inheritance
515    /// walk (its parent's recorded direction stands in for `inherit`; a parent whose own
516    /// direction changed in the same frame triggers the walk itself).
517    fn direction_changed(&self, store: &NodeStore, id: NodeId) -> bool {
518        let parent_rtl = store
519            .parent(id)
520            .is_some_and(|p| self.resolved_rtl.get(p.index()).copied().unwrap_or(false));
521        let rtl = match store.try_row::<NvLayout>(id).map(|l| l.direction()) {
522            Some(NvDirection::Ltr) => false,
523            Some(NvDirection::Rtl) => true,
524            _ => parent_rtl,
525        };
526        self.resolved_rtl.get(id.index()).copied() != Some(rtl)
527    }
528
529
530    /// A `display` / hidden-input / pseudo-state change on `id` reshapes box children only when
531    /// it flips whether `id` is `display: contents`.
532    pub(super) fn display_change_reshapes_boxes(
533        &self,
534        store: &NodeStore,
535        id: NodeId,
536        interaction: Option<&InteractionTracker>,
537    ) -> bool {
538        display_env!(self, interaction).is_display_contents(store, id)
539            != self.was_contents.get(id.index()).copied().unwrap_or(false)
540    }
541
542    /// Marks every live node dirty (used after full replica load or measurer swap).
543    pub fn invalidate_all(&mut self, store: &NodeStore) {
544        self.hoisted.reset();
545        self.box_children.reset();
546        self.ensure_capacity(store.capacity());
547        for c in &mut self.caches {
548            c.clear();
549        }
550        self.resolved_rtl.fill(false);
551        self.resolved_text.fill(ResolvedTextStyle::default());
552        self.paragraphs.reset();
553        self.was_contents.fill(false);
554        self.was_transformed.fill(false);
555        self.top_layer.invalidate();
556        self.style_flags.fill(NodeStyleFlags::empty());
557        self.responsive_node_count = 0;
558        self.container_node_count = 0;
559        self.size_container_count = 0;
560        self.responsive_changed_this_pass = true;
561        self.counts_dirty = true;
562        self.responsive_tree_dirty = true;
563        self.cached_env_hash.fill(0);
564        self.para_last_env_hash.fill(0);
565        self.container_records.reset_all();
566        self.boundary_records.reset_all();
567        self.dirty_boundaries.clear();
568        self.resolved_container_env.reset_all();
569        self.pass_root = None;
570        self.dry.invalidate();
571        self.mark_inherit_full();
572        self.layout_dirty = true;
573        self.full_layout_needed = true;
574    }
575
576    #[inline]
577    pub(super) fn mark_dirty(&mut self, store: &NodeStore, mut id: NodeId) {
578        self.layout_dirty = true;
579        let root = self.last_viewport.map_or(NodeId::ROOT, |(r, _, _)| r);
580        let mut steps = 0usize;
581        while store.is_live(id) {
582            steps += 1;
583            debug_assert!(
584                steps <= crate::MAX_TREE_DEPTH + 1,
585                "parent cycle detected in mark_dirty at node {:?}",
586                id
587            );
588            if steps > crate::MAX_TREE_DEPTH + 1 {
589                self.full_layout_needed = true;
590                break;
591            }
592            let idx = id.index();
593            if idx >= self.caches.len() {
594                self.full_layout_needed = true;
595                break;
596            }
597            let is_hoisted = id != root && self.top_layer.is_hoisted(id);
598            let cleared = self.caches[idx].clear();
599            if is_hoisted {
600                // Hoisted overlays are laid out directly under `root`; jump straight there so
601                // already-empty DOM ancestors cannot short-circuit `caches[root]` invalidation.
602                let ridx = root.index();
603                if ridx < self.caches.len() {
604                    self.caches[ridx].clear();
605                }
606                self.full_layout_needed = true;
607                break;
608            }
609            if steps > 1 && self.try_record_dirty_boundary(id, root) {
610                break;
611            }
612            if matches!(cleared, ClearState::AlreadyEmpty)
613                && steps > 1
614                && !self.was_contents[idx]
615                && !is_display_contents(store, id)
616            {
617                break;
618            }
619            if id == root {
620                self.full_layout_needed = true;
621                break;
622            }
623            let Some(p) = store.parent(id) else {
624                self.full_layout_needed = true;
625                break;
626            };
627            id = p;
628        }
629    }
630}