tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 790HTML 742Markdown 12TOML 62540 Definiciones

⎇ 440843c700455363383e0a4fc365a15deebd4717 src/tree/taffy_tree.rs Rust · 1117 líneas · 41.2 KB Historia Quién tocó qué crudo

Make `slotmap` dependency compatible with `no_std` environments (#594) 440843c70 · Conall Keane ·

1//! Contains [TaffyTree](crate::tree::TaffyTree): the default implementation of [LayoutTree](crate::tree::LayoutTree), and the error type for Taffy.
2#[cfg(not(feature = "std"))]
3use slotmap::SecondaryMap;
4#[cfg(feature = "std")]
5use slotmap::SparseSecondaryMap as SecondaryMap;
6use slotmap::{DefaultKey, SlotMap};
7
8use crate::geometry::Size;
9use crate::style::{AvailableSpace, Display, Style};
10use crate::tree::{
11    Cache, Layout, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, PrintTree, RoundTree, RunMode,
12    TraversePartialTree, TraverseTree,
13};
14use crate::util::debug::{debug_log, debug_log_node};
15use crate::util::sys::{new_vec_with_capacity, ChildrenVec, Vec};
16
17#[cfg(feature = "block_layout")]
18use crate::compute::compute_block_layout;
19#[cfg(feature = "flexbox")]
20use crate::compute::compute_flexbox_layout;
21#[cfg(feature = "grid")]
22use crate::compute::compute_grid_layout;
23use crate::compute::{
24    compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_root_layout, round_layout,
25};
26
27/// The error Taffy generates on invalid operations
28pub type TaffyResult<T> = Result<T, TaffyError>;
29
30/// An error that occurs while trying to access or modify a node's children by index.
31#[derive(Debug)]
32pub enum TaffyError {
33    /// The parent node does not have a child at `child_index`. It only has `child_count` children
34    ChildIndexOutOfBounds {
35        /// The parent node whose child was being looked up
36        parent: NodeId,
37        /// The index that was looked up
38        child_index: usize,
39        /// The total number of children the parent has
40        child_count: usize,
41    },
42    /// The parent node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
43    InvalidParentNode(NodeId),
44    /// The child node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
45    InvalidChildNode(NodeId),
46    /// The supplied node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
47    InvalidInputNode(NodeId),
48}
49
50impl core::fmt::Display for TaffyError {
51    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
52        match self {
53            TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count } => {
54                write!(f, "Index (is {child_index}) should be < child_count ({child_count}) for parent node {parent:?}")
55            }
56            TaffyError::InvalidParentNode(parent) => {
57                write!(f, "Parent Node {parent:?} is not in the TaffyTree instance")
58            }
59            TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the TaffyTree instance"),
60            TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the TaffyTree instance"),
61        }
62    }
63}
64
65#[cfg(feature = "std")]
66impl std::error::Error for TaffyError {}
67
68/// Global configuration values for a TaffyTree instance
69pub(crate) struct TaffyConfig {
70    /// Whether to round layout values
71    pub(crate) use_rounding: bool,
72}
73
74impl Default for TaffyConfig {
75    fn default() -> Self {
76        Self { use_rounding: true }
77    }
78}
79
80/// Layout information for a given [`Node`](crate::node::Node)
81///
82/// Stored in a [`TaffyTree`].
83struct NodeData {
84    /// The layout strategy used by this node
85    pub(crate) style: Style,
86
87    /// The always unrounded results of the layout computation. We must store this separately from the rounded
88    /// layout to avoid errors from rounding already-rounded values. See <https://github.com/DioxusLabs/taffy/issues/501>.
89    pub(crate) unrounded_layout: Layout,
90
91    /// The final results of the layout computation.
92    /// These may be rounded or unrounded depending on what the `use_rounding` config setting is set to.
93    pub(crate) final_layout: Layout,
94
95    /// Should we try and measure this node?
96    pub(crate) needs_measure: bool,
97
98    /// The cached results of the layout computation
99    pub(crate) cache: Cache,
100}
101
102impl NodeData {
103    /// Create the data for a new node
104    #[must_use]
105    pub const fn new(style: Style) -> Self {
106        Self {
107            style,
108            cache: Cache::new(),
109            unrounded_layout: Layout::new(),
110            final_layout: Layout::new(),
111            needs_measure: false,
112        }
113    }
114
115    /// Marks a node and all of its parents (recursively) as dirty
116    ///
117    /// This clears any cached data and signals that the data must be recomputed.
118    #[inline]
119    pub fn mark_dirty(&mut self) {
120        self.cache.clear()
121    }
122}
123
124/// An entire tree of UI nodes. The entry point to Taffy's high-level API.
125///
126/// Allows you to build a tree of UI nodes, run Taffy's layout algorithms over that tree, and then access the resultant layout.
127pub struct TaffyTree<NodeContext = ()> {
128    /// The [`NodeData`] for each node stored in this tree
129    nodes: SlotMap<DefaultKey, NodeData>,
130
131    /// Functions/closures that compute the intrinsic size of leaf nodes
132    node_context_data: SecondaryMap<DefaultKey, NodeContext>,
133
134    /// The children of each node
135    ///
136    /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
137    children: SlotMap<DefaultKey, ChildrenVec<NodeId>>,
138
139    /// The parents of each node
140    ///
141    /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
142    parents: SlotMap<DefaultKey, Option<NodeId>>,
143
144    /// Layout mode configuration
145    config: TaffyConfig,
146}
147
148impl Default for TaffyTree {
149    fn default() -> TaffyTree<()> {
150        TaffyTree::new()
151    }
152}
153
154/// Iterator that wraps a slice of nodes, lazily converting them to u64
155pub struct TaffyTreeChildIter<'a>(core::slice::Iter<'a, NodeId>);
156impl<'a> Iterator for TaffyTreeChildIter<'a> {
157    type Item = NodeId;
158
159    fn next(&mut self) -> Option<Self::Item> {
160        self.0.next().copied()
161    }
162}
163
164// TraversePartialTree impl for TaffyTree
165impl<NodeContext> TraversePartialTree for TaffyTree<NodeContext> {
166    type ChildIter<'a> = TaffyTreeChildIter<'a> where Self: 'a;
167
168    #[inline(always)]
169    fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
170        TaffyTreeChildIter(self.children[parent_node_id.into()].iter())
171    }
172
173    #[inline(always)]
174    fn child_count(&self, parent_node_id: NodeId) -> usize {
175        self.children[parent_node_id.into()].len()
176    }
177
178    #[inline(always)]
179    fn get_child_id(&self, parent_node_id: NodeId, id: usize) -> NodeId {
180        self.children[parent_node_id.into()][id]
181    }
182}
183
184// TraverseTree impl for TaffyTree
185impl<NodeContext> TraverseTree for TaffyTree<NodeContext> {}
186
187// PrintTree impl for TaffyTree
188impl<NodeContext> PrintTree for TaffyTree<NodeContext> {
189    #[inline(always)]
190    fn get_debug_label(&self, node_id: NodeId) -> &'static str {
191        let node = &self.nodes[node_id.into()];
192        let display = node.style.display;
193        let num_children = self.child_count(node_id);
194
195        match (num_children, display) {
196            (_, Display::None) => "NONE",
197            (0, _) => "LEAF",
198            #[cfg(feature = "block_layout")]
199            (_, Display::Block) => "BLOCK",
200            #[cfg(feature = "flexbox")]
201            (_, Display::Flex) => {
202                use crate::FlexDirection;
203                match node.style.flex_direction {
204                    FlexDirection::Row | FlexDirection::RowReverse => "FLEX ROW",
205                    FlexDirection::Column | FlexDirection::ColumnReverse => "FLEX COL",
206                }
207            }
208            #[cfg(feature = "grid")]
209            (_, Display::Grid) => "GRID",
210        }
211    }
212
213    #[inline(always)]
214    fn get_final_layout(&self, node_id: NodeId) -> &Layout {
215        &self.nodes[node_id.into()].final_layout
216    }
217}
218
219/// View over the Taffy tree that holds the tree itself along with a reference to the context
220/// and implements LayoutTree. This allows the context to be stored outside of the TaffyTree struct
221/// which makes the lifetimes of the context much more flexible.
222pub(crate) struct TaffyView<'t, NodeContext, MeasureFunction>
223where
224    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
225{
226    /// A reference to the TaffyTree
227    pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
228    /// The context provided for passing to measure functions if layout is run over this struct
229    pub(crate) measure_function: MeasureFunction,
230}
231
232// TraversePartialTree impl for TaffyView
233impl<'t, NodeContext, MeasureFunction> TraversePartialTree for TaffyView<'t, NodeContext, MeasureFunction>
234where
235    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
236{
237    type ChildIter<'a> = TaffyTreeChildIter<'a> where Self: 'a;
238
239    #[inline(always)]
240    fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
241        self.taffy.child_ids(parent_node_id)
242    }
243
244    #[inline(always)]
245    fn child_count(&self, parent_node_id: NodeId) -> usize {
246        self.taffy.child_count(parent_node_id)
247    }
248
249    #[inline(always)]
250    fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
251        self.taffy.get_child_id(parent_node_id, child_index)
252    }
253}
254
255// TraverseTree impl for TaffyView
256impl<'t, NodeContext, MeasureFunction> TraverseTree for TaffyView<'t, NodeContext, MeasureFunction> where
257    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>
258{
259}
260
261// LayoutPartialTree impl for TaffyView
262impl<'t, NodeContext, MeasureFunction> LayoutPartialTree for TaffyView<'t, NodeContext, MeasureFunction>
263where
264    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
265{
266    #[inline(always)]
267    fn get_style(&self, node: NodeId) -> &Style {
268        &self.taffy.nodes[node.into()].style
269    }
270
271    #[inline(always)]
272    fn get_cache_mut(&mut self, node: NodeId) -> &mut Cache {
273        &mut self.taffy.nodes[node.into()].cache
274    }
275
276    #[inline(always)]
277    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
278        self.taffy.nodes[node_id.into()].unrounded_layout = *layout;
279    }
280
281    #[inline(always)]
282    fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
283        // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
284        // and thus that we should lay out this node using hidden layout regardless of it's own display style.
285        if inputs.run_mode == RunMode::PerformHiddenLayout {
286            debug_log!("HIDDEN");
287            return compute_hidden_layout(self, node);
288        }
289
290        // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
291        //   - Return that entry if exists
292        //   - Else call the passed closure (below) to compute the result
293        //
294        // If there was no cache match and a new result needs to be computed then that result will be added to the cache
295        compute_cached_layout(self, node, inputs, |tree, node, inputs| {
296            let display_mode = tree.get_style(node).display;
297            let has_children = tree.child_count(node) > 0;
298
299            debug_log!(display_mode);
300            debug_log_node!(
301                inputs.known_dimensions,
302                inputs.parent_size,
303                inputs.available_space,
304                inputs.run_mode,
305                inputs.sizing_mode
306            );
307
308            // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
309            match (display_mode, has_children) {
310                (Display::None, _) => compute_hidden_layout(tree, node),
311                #[cfg(feature = "block_layout")]
312                (Display::Block, true) => compute_block_layout(tree, node, inputs),
313                #[cfg(feature = "flexbox")]
314                (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
315                #[cfg(feature = "grid")]
316                (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
317                (_, false) => {
318                    let node_key = node.into();
319                    let style = &tree.taffy.nodes[node_key].style;
320                    let needs_measure = tree.taffy.nodes[node_key].needs_measure;
321                    let measure_function = needs_measure.then_some(|known_dimensions, available_space| {
322                        let node_context = tree.taffy.node_context_data.get_mut(node_key);
323                        (tree.measure_function)(known_dimensions, available_space, node, node_context)
324                    });
325                    compute_leaf_layout(inputs, style, measure_function)
326                }
327            }
328        })
329    }
330}
331
332// RoundTree impl for TaffyView
333impl<'t, NodeContext, MeasureFunction> RoundTree for TaffyView<'t, NodeContext, MeasureFunction>
334where
335    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
336{
337    #[inline(always)]
338    fn get_unrounded_layout(&self, node: NodeId) -> &Layout {
339        &self.taffy.nodes[node.into()].unrounded_layout
340    }
341
342    #[inline(always)]
343    fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
344        self.taffy.nodes[node_id.into()].final_layout = *layout;
345    }
346}
347
348#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
349impl<NodeContext> TaffyTree<NodeContext> {
350    /// Creates a new [`TaffyTree`]
351    ///
352    /// The default capacity of a [`TaffyTree`] is 16 nodes.
353    #[must_use]
354    pub fn new() -> Self {
355        Self::with_capacity(16)
356    }
357
358    /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
359    #[must_use]
360    pub fn with_capacity(capacity: usize) -> Self {
361        TaffyTree {
362            // TODO: make this method const upstream,
363            // so constructors here can be const
364            nodes: SlotMap::with_capacity(capacity),
365            children: SlotMap::with_capacity(capacity),
366            parents: SlotMap::with_capacity(capacity),
367            node_context_data: SecondaryMap::with_capacity(capacity),
368            config: TaffyConfig::default(),
369        }
370    }
371
372    /// Enable rounding of layout values. Rounding is enabled by default.
373    pub fn enable_rounding(&mut self) {
374        self.config.use_rounding = true;
375    }
376
377    /// Disable rounding of layout values. Rounding is enabled by default.
378    pub fn disable_rounding(&mut self) {
379        self.config.use_rounding = false;
380    }
381
382    /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
383    pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
384        let id = self.nodes.insert(NodeData::new(layout));
385        let _ = self.children.insert(new_vec_with_capacity(0));
386        let _ = self.parents.insert(None);
387
388        Ok(id.into())
389    }
390
391    /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
392    ///
393    /// Creates and adds a new leaf node with a supplied context
394    pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
395        let mut data = NodeData::new(layout);
396        data.needs_measure = true;
397
398        let id = self.nodes.insert(data);
399        self.node_context_data.insert(id, context);
400
401        let _ = self.children.insert(new_vec_with_capacity(0));
402        let _ = self.parents.insert(None);
403
404        Ok(id.into())
405    }
406
407    /// Creates and adds a new node, which may have any number of `children`
408    pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
409        let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
410
411        for child in children {
412            self.parents[(*child).into()] = Some(id);
413        }
414
415        let _ = self.children.insert(children.iter().copied().collect::<_>());
416        let _ = self.parents.insert(None);
417
418        Ok(id)
419    }
420
421    /// Drops all nodes in the tree
422    pub fn clear(&mut self) {
423        self.nodes.clear();
424        self.children.clear();
425        self.parents.clear();
426    }
427
428    /// Remove a specific node from the tree and drop it
429    ///
430    /// Returns the id of the node removed.
431    pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
432        let key = node.into();
433        if let Some(parent) = self.parents[key] {
434            if let Some(children) = self.children.get_mut(parent.into()) {
435                children.retain(|f| *f != node);
436            }
437        }
438
439        // Remove "parent" references to a node when removing that node
440        if let Some(children) = self.children.get(key) {
441            for child in children.iter().copied() {
442                self.parents[child.into()] = None;
443            }
444        }
445
446        let _ = self.children.remove(key);
447        let _ = self.parents.remove(key);
448        let _ = self.nodes.remove(key);
449
450        Ok(node)
451    }
452
453    /// Sets the context data associated with the node
454    pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
455        let key = node.into();
456        if let Some(measure) = measure {
457            self.nodes[key].needs_measure = true;
458            self.node_context_data.insert(key, measure);
459        } else {
460            self.nodes[key].needs_measure = false;
461            self.node_context_data.remove(key);
462        }
463
464        self.mark_dirty(node)?;
465
466        Ok(())
467    }
468
469    /// Gets a reference to the the context data associated with the node
470    pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
471        self.node_context_data.get(node.into())
472    }
473
474    /// Gets a mutable reference to the the context data associated with the node
475    pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
476        self.node_context_data.get_mut(node.into())
477    }
478
479    /// Adds a `child` node under the supplied `parent`
480    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
481        let parent_key = parent.into();
482        let child_key = child.into();
483        self.parents[child_key] = Some(parent);
484        self.children[parent_key].push(child);
485        self.mark_dirty(parent)?;
486
487        Ok(())
488    }
489
490    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
491    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
492        let parent_key = parent.into();
493
494        let child_count = self.children[parent_key].len();
495        if child_index > child_count {
496            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
497        }
498
499        self.parents[child.into()] = Some(parent);
500        self.children[parent_key].insert(child_index, child);
501        self.mark_dirty(parent)?;
502
503        Ok(())
504    }
505
506    /// Directly sets the `children` of the supplied `parent`
507    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
508        let parent_key = parent.into();
509
510        // Remove node as parent from all its current children.
511        for child in &self.children[parent_key] {
512            self.parents[(*child).into()] = None;
513        }
514
515        // Build up relation node <-> child
516        for child in children {
517            self.parents[(*child).into()] = Some(parent);
518        }
519
520        let parent_children = &mut self.children[parent_key];
521        parent_children.clear();
522        children.iter().for_each(|child| parent_children.push(*child));
523
524        self.mark_dirty(parent)?;
525
526        Ok(())
527    }
528
529    /// Removes the `child` of the parent `node`
530    ///
531    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
532    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
533        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
534        self.remove_child_at_index(parent, index)
535    }
536
537    /// Removes the child at the given `index` from the `parent`
538    ///
539    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
540    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
541        let parent_key = parent.into();
542        let child_count = self.children[parent_key].len();
543        if child_index >= child_count {
544            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
545        }
546
547        let child = self.children[parent_key].remove(child_index);
548        self.parents[child.into()] = None;
549
550        self.mark_dirty(parent)?;
551
552        Ok(child)
553    }
554
555    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
556    ///
557    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
558    pub fn replace_child_at_index(
559        &mut self,
560        parent: NodeId,
561        child_index: usize,
562        new_child: NodeId,
563    ) -> TaffyResult<NodeId> {
564        let parent_key = parent.into();
565
566        let child_count = self.children[parent_key].len();
567        if child_index >= child_count {
568            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
569        }
570
571        self.parents[new_child.into()] = Some(parent);
572        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
573        self.parents[old_child.into()] = None;
574
575        self.mark_dirty(parent)?;
576
577        Ok(old_child)
578    }
579
580    /// Returns the child node of the parent `node` at the provided `child_index`
581    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
582        let parent_key = parent.into();
583        let child_count = self.children[parent_key].len();
584        if child_index >= child_count {
585            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
586        }
587
588        Ok(self.children[parent_key][child_index])
589    }
590
591    /// Returns the total number of nodes in the tree
592    pub fn total_node_count(&self) -> usize {
593        self.nodes.len()
594    }
595
596    /// Returns a list of children that belong to the parent node
597    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
598        Ok(self.children[parent.into()].iter().copied().collect::<_>())
599    }
600
601    /// Sets the [`Style`] of the provided `node`
602    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
603        self.nodes[node.into()].style = style;
604        self.mark_dirty(node)?;
605        Ok(())
606    }
607
608    /// Gets the [`Style`] of the provided `node`
609    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
610        Ok(&self.nodes[node.into()].style)
611    }
612
613    /// Return this node layout relative to its parent
614    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
615        if self.config.use_rounding {
616            Ok(&self.nodes[node.into()].final_layout)
617        } else {
618            Ok(&self.nodes[node.into()].unrounded_layout)
619        }
620    }
621
622    /// Marks the layout computation of this node and its children as outdated
623    ///
624    /// Performs a recursive depth-first search up the tree until the root node is reached
625    ///
626    /// WARNING: this will stack-overflow if the tree contains a cycle
627    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
628        /// WARNING: this will stack-overflow if the tree contains a cycle
629        fn mark_dirty_recursive(
630            nodes: &mut SlotMap<DefaultKey, NodeData>,
631            parents: &SlotMap<DefaultKey, Option<NodeId>>,
632            node_key: DefaultKey,
633        ) {
634            nodes[node_key].mark_dirty();
635
636            if let Some(Some(node)) = parents.get(node_key) {
637                mark_dirty_recursive(nodes, parents, (*node).into());
638            }
639        }
640
641        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
642
643        Ok(())
644    }
645
646    /// Indicates whether the layout of this node (and its children) need to be recomputed
647    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
648        Ok(self.nodes[node.into()].cache.is_empty())
649    }
650
651    /// Updates the stored layout of the provided `node` and its children
652    pub fn compute_layout_with_measure<MeasureFunction>(
653        &mut self,
654        node_id: NodeId,
655        available_space: Size<AvailableSpace>,
656        measure_function: MeasureFunction,
657    ) -> Result<(), TaffyError>
658    where
659        MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
660    {
661        let use_rounding = self.config.use_rounding;
662        let mut taffy_view = TaffyView { taffy: self, measure_function };
663        compute_root_layout(&mut taffy_view, node_id, available_space);
664        if use_rounding {
665            round_layout(&mut taffy_view, node_id);
666        }
667        Ok(())
668    }
669
670    /// Updates the stored layout of the provided `node` and its children
671    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
672        self.compute_layout_with_measure(node, available_space, |_, _, _, _| Size::ZERO)
673    }
674
675    /// Prints a debug representation of the tree's layout
676    #[cfg(feature = "std")]
677    pub fn print_tree(&mut self, root: NodeId) {
678        crate::util::print_tree(self, root)
679    }
680
681    /// Returns an instance of LayoutTree representing the TaffyTree
682    #[cfg(test)]
683    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + '_ {
684        TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO }
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    #![allow(clippy::bool_assert_comparison)]
691
692    use super::*;
693    use crate::style::{Dimension, Display, FlexDirection};
694    use crate::style_helpers::*;
695    use crate::util::sys;
696
697    fn size_measure_function(
698        known_dimensions: Size<Option<f32>>,
699        _available_space: Size<AvailableSpace>,
700        _node_id: NodeId,
701        node_context: Option<&mut Size<f32>>,
702    ) -> Size<f32> {
703        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
704    }
705
706    #[test]
707    fn new_should_allocate_default_capacity() {
708        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
709        let taffy: TaffyTree<()> = TaffyTree::new();
710
711        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
712        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
713        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
714    }
715
716    #[test]
717    fn test_with_capacity() {
718        const CAPACITY: usize = 8;
719        let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
720
721        assert!(taffy.children.capacity() >= CAPACITY);
722        assert!(taffy.parents.capacity() >= CAPACITY);
723        assert!(taffy.nodes.capacity() >= CAPACITY);
724    }
725
726    #[test]
727    fn test_new_leaf() {
728        let mut taffy: TaffyTree<()> = TaffyTree::new();
729
730        let res = taffy.new_leaf(Style::default());
731        assert!(res.is_ok());
732        let node = res.unwrap();
733
734        // node should be in the taffy tree and have no children
735        assert!(taffy.child_count(node) == 0);
736    }
737
738    #[test]
739    fn new_leaf_with_context() {
740        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
741
742        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
743        assert!(res.is_ok());
744        let node = res.unwrap();
745
746        // node should be in the taffy tree and have no children
747        assert!(taffy.child_count(node) == 0);
748    }
749
750    /// Test that new_with_children works as expected
751    #[test]
752    fn test_new_with_children() {
753        let mut taffy: TaffyTree<()> = TaffyTree::new();
754        let child0 = taffy.new_leaf(Style::default()).unwrap();
755        let child1 = taffy.new_leaf(Style::default()).unwrap();
756        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
757
758        // node should have two children
759        assert_eq!(taffy.child_count(node), 2);
760        assert_eq!(taffy.children(node).unwrap()[0], child0);
761        assert_eq!(taffy.children(node).unwrap()[1], child1);
762    }
763
764    #[test]
765    fn remove_node_should_remove() {
766        let mut taffy: TaffyTree<()> = TaffyTree::new();
767
768        let node = taffy.new_leaf(Style::default()).unwrap();
769
770        let _ = taffy.remove(node).unwrap();
771    }
772
773    #[test]
774    fn remove_node_should_detach_herarchy() {
775        let mut taffy: TaffyTree<()> = TaffyTree::new();
776
777        // Build a linear tree layout: <0> <- <1> <- <2>
778        let node2 = taffy.new_leaf(Style::default()).unwrap();
779        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
780        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
781
782        // Both node0 and node1 should have 1 child nodes
783        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
784        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
785
786        // Disconnect the tree: <0> <2>
787        let _ = taffy.remove(node1).unwrap();
788
789        // Both remaining nodes should have no child nodes
790        assert!(taffy.children(node0).unwrap().is_empty());
791        assert!(taffy.children(node2).unwrap().is_empty());
792    }
793
794    #[test]
795    fn remove_last_node() {
796        let mut taffy: TaffyTree<()> = TaffyTree::new();
797
798        let parent = taffy.new_leaf(Style::default()).unwrap();
799        let child = taffy.new_leaf(Style::default()).unwrap();
800        taffy.add_child(parent, child).unwrap();
801
802        taffy.remove(child).unwrap();
803        taffy.remove(parent).unwrap();
804    }
805
806    #[test]
807    fn set_measure() {
808        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
809        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
810        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
811        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
812
813        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
814        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
815        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
816    }
817
818    #[test]
819    fn set_measure_of_previously_unmeasured_node() {
820        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
821        let node = taffy.new_leaf(Style::default()).unwrap();
822        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
823        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
824
825        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
826        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
827        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
828    }
829
830    /// Test that adding `add_child()` works
831    #[test]
832    fn add_child() {
833        let mut taffy: TaffyTree<()> = TaffyTree::new();
834        let node = taffy.new_leaf(Style::default()).unwrap();
835        assert_eq!(taffy.child_count(node), 0);
836
837        let child0 = taffy.new_leaf(Style::default()).unwrap();
838        taffy.add_child(node, child0).unwrap();
839        assert_eq!(taffy.child_count(node), 1);
840
841        let child1 = taffy.new_leaf(Style::default()).unwrap();
842        taffy.add_child(node, child1).unwrap();
843        assert_eq!(taffy.child_count(node), 2);
844    }
845
846    #[test]
847    fn insert_child_at_index() {
848        let mut taffy: TaffyTree<()> = TaffyTree::new();
849
850        let child0 = taffy.new_leaf(Style::default()).unwrap();
851        let child1 = taffy.new_leaf(Style::default()).unwrap();
852        let child2 = taffy.new_leaf(Style::default()).unwrap();
853
854        let node = taffy.new_leaf(Style::default()).unwrap();
855        assert_eq!(taffy.child_count(node), 0);
856
857        taffy.insert_child_at_index(node, 0, child0).unwrap();
858        assert_eq!(taffy.child_count(node), 1);
859        assert_eq!(taffy.children(node).unwrap()[0], child0);
860
861        taffy.insert_child_at_index(node, 0, child1).unwrap();
862        assert_eq!(taffy.child_count(node), 2);
863        assert_eq!(taffy.children(node).unwrap()[0], child1);
864        assert_eq!(taffy.children(node).unwrap()[1], child0);
865
866        taffy.insert_child_at_index(node, 1, child2).unwrap();
867        assert_eq!(taffy.child_count(node), 3);
868        assert_eq!(taffy.children(node).unwrap()[0], child1);
869        assert_eq!(taffy.children(node).unwrap()[1], child2);
870        assert_eq!(taffy.children(node).unwrap()[2], child0);
871    }
872
873    #[test]
874    fn set_children() {
875        let mut taffy: TaffyTree<()> = TaffyTree::new();
876
877        let child0 = taffy.new_leaf(Style::default()).unwrap();
878        let child1 = taffy.new_leaf(Style::default()).unwrap();
879        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
880
881        assert_eq!(taffy.child_count(node), 2);
882        assert_eq!(taffy.children(node).unwrap()[0], child0);
883        assert_eq!(taffy.children(node).unwrap()[1], child1);
884
885        let child2 = taffy.new_leaf(Style::default()).unwrap();
886        let child3 = taffy.new_leaf(Style::default()).unwrap();
887        taffy.set_children(node, &[child2, child3]).unwrap();
888
889        assert_eq!(taffy.child_count(node), 2);
890        assert_eq!(taffy.children(node).unwrap()[0], child2);
891        assert_eq!(taffy.children(node).unwrap()[1], child3);
892    }
893
894    /// Test that removing a child works
895    #[test]
896    fn remove_child() {
897        let mut taffy: TaffyTree<()> = TaffyTree::new();
898        let child0 = taffy.new_leaf(Style::default()).unwrap();
899        let child1 = taffy.new_leaf(Style::default()).unwrap();
900        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
901
902        assert_eq!(taffy.child_count(node), 2);
903
904        taffy.remove_child(node, child0).unwrap();
905        assert_eq!(taffy.child_count(node), 1);
906        assert_eq!(taffy.children(node).unwrap()[0], child1);
907
908        taffy.remove_child(node, child1).unwrap();
909        assert_eq!(taffy.child_count(node), 0);
910    }
911
912    #[test]
913    fn remove_child_at_index() {
914        let mut taffy: TaffyTree<()> = TaffyTree::new();
915        let child0 = taffy.new_leaf(Style::default()).unwrap();
916        let child1 = taffy.new_leaf(Style::default()).unwrap();
917        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
918
919        assert_eq!(taffy.child_count(node), 2);
920
921        taffy.remove_child_at_index(node, 0).unwrap();
922        assert_eq!(taffy.child_count(node), 1);
923        assert_eq!(taffy.children(node).unwrap()[0], child1);
924
925        taffy.remove_child_at_index(node, 0).unwrap();
926        assert_eq!(taffy.child_count(node), 0);
927    }
928
929    // Related to: https://github.com/DioxusLabs/taffy/issues/510
930    #[test]
931    fn remove_child_updates_parents() {
932        let mut taffy: TaffyTree<()> = TaffyTree::new();
933
934        let parent = taffy.new_leaf(Style::default()).unwrap();
935        let child = taffy.new_leaf(Style::default()).unwrap();
936
937        taffy.add_child(parent, child).unwrap();
938
939        taffy.remove(parent).unwrap();
940
941        // Once the parent is removed this shouldn't panic.
942        assert!(taffy.set_children(child, &[]).is_ok());
943    }
944
945    #[test]
946    fn replace_child_at_index() {
947        let mut taffy: TaffyTree<()> = TaffyTree::new();
948
949        let child0 = taffy.new_leaf(Style::default()).unwrap();
950        let child1 = taffy.new_leaf(Style::default()).unwrap();
951
952        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
953        assert_eq!(taffy.child_count(node), 1);
954        assert_eq!(taffy.children(node).unwrap()[0], child0);
955
956        taffy.replace_child_at_index(node, 0, child1).unwrap();
957        assert_eq!(taffy.child_count(node), 1);
958        assert_eq!(taffy.children(node).unwrap()[0], child1);
959    }
960    #[test]
961    fn test_child_at_index() {
962        let mut taffy: TaffyTree<()> = TaffyTree::new();
963        let child0 = taffy.new_leaf(Style::default()).unwrap();
964        let child1 = taffy.new_leaf(Style::default()).unwrap();
965        let child2 = taffy.new_leaf(Style::default()).unwrap();
966        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
967
968        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
969        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
970        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
971    }
972    #[test]
973    fn test_child_count() {
974        let mut taffy: TaffyTree<()> = TaffyTree::new();
975        let child0 = taffy.new_leaf(Style::default()).unwrap();
976        let child1 = taffy.new_leaf(Style::default()).unwrap();
977        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
978
979        assert!(taffy.child_count(node) == 2);
980        assert!(taffy.child_count(child0) == 0);
981        assert!(taffy.child_count(child1) == 0);
982    }
983
984    #[allow(clippy::vec_init_then_push)]
985    #[test]
986    fn test_children() {
987        let mut taffy: TaffyTree<()> = TaffyTree::new();
988        let child0 = taffy.new_leaf(Style::default()).unwrap();
989        let child1 = taffy.new_leaf(Style::default()).unwrap();
990        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
991
992        let mut children = sys::Vec::new();
993        children.push(child0);
994        children.push(child1);
995
996        let children_result = taffy.children(node).unwrap();
997        assert_eq!(children_result, children);
998
999        assert!(taffy.children(child0).unwrap().is_empty());
1000    }
1001    #[test]
1002    fn test_set_style() {
1003        let mut taffy: TaffyTree<()> = TaffyTree::new();
1004
1005        let node = taffy.new_leaf(Style::default()).unwrap();
1006        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1007
1008        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1009        assert_eq!(taffy.style(node).unwrap().display, Display::None);
1010    }
1011    #[test]
1012    fn test_style() {
1013        let mut taffy: TaffyTree<()> = TaffyTree::new();
1014
1015        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1016
1017        let node = taffy.new_leaf(style.clone()).unwrap();
1018
1019        let res = taffy.style(node);
1020        assert!(res.is_ok());
1021        assert!(res.unwrap() == &style);
1022    }
1023    #[test]
1024    fn test_layout() {
1025        let mut taffy: TaffyTree<()> = TaffyTree::new();
1026        let node = taffy.new_leaf(Style::default()).unwrap();
1027
1028        // TODO: Improve this test?
1029        let res = taffy.layout(node);
1030        assert!(res.is_ok());
1031    }
1032
1033    #[test]
1034    fn test_mark_dirty() {
1035        let mut taffy: TaffyTree<()> = TaffyTree::new();
1036        let child0 = taffy.new_leaf(Style::default()).unwrap();
1037        let child1 = taffy.new_leaf(Style::default()).unwrap();
1038        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1039
1040        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1041
1042        assert_eq!(taffy.dirty(child0).unwrap(), false);
1043        assert_eq!(taffy.dirty(child1).unwrap(), false);
1044        assert_eq!(taffy.dirty(node).unwrap(), false);
1045
1046        taffy.mark_dirty(node).unwrap();
1047        assert_eq!(taffy.dirty(child0).unwrap(), false);
1048        assert_eq!(taffy.dirty(child1).unwrap(), false);
1049        assert_eq!(taffy.dirty(node).unwrap(), true);
1050
1051        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1052        taffy.mark_dirty(child0).unwrap();
1053        assert_eq!(taffy.dirty(child0).unwrap(), true);
1054        assert_eq!(taffy.dirty(child1).unwrap(), false);
1055        assert_eq!(taffy.dirty(node).unwrap(), true);
1056    }
1057
1058    #[test]
1059    fn compute_layout_should_produce_valid_result() {
1060        let mut taffy: TaffyTree<()> = TaffyTree::new();
1061        let node_result = taffy.new_leaf(Style {
1062            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1063            ..Default::default()
1064        });
1065        assert!(node_result.is_ok());
1066        let node = node_result.unwrap();
1067        let layout_result = taffy.compute_layout(
1068            node,
1069            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1070        );
1071        assert!(layout_result.is_ok());
1072    }
1073
1074    #[test]
1075    fn make_sure_layout_location_is_top_left() {
1076        use crate::prelude::Rect;
1077
1078        let mut taffy: TaffyTree<()> = TaffyTree::new();
1079
1080        let node = taffy
1081            .new_leaf(Style {
1082                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1083                ..Default::default()
1084            })
1085            .unwrap();
1086
1087        let root = taffy
1088            .new_with_children(
1089                Style {
1090                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1091                    padding: Rect {
1092                        left: length(10f32),
1093                        right: length(20f32),
1094                        top: length(30f32),
1095                        bottom: length(40f32),
1096                    },
1097                    ..Default::default()
1098                },
1099                &[node],
1100            )
1101            .unwrap();
1102
1103        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1104
1105        // If Layout::location represents top-left coord, 'node' location
1106        // must be (due applied 'root' padding): {x: 10, y: 30}.
1107        //
1108        // It's important, since result will be different for each other
1109        // coordinate space:
1110        // - bottom-left:  {x: 10, y: 40}
1111        // - top-right:    {x: 20, y: 30}
1112        // - bottom-right: {x: 20, y: 40}
1113        let layout = taffy.layout(node).unwrap();
1114        assert_eq!(layout.location.x, 10f32);
1115        assert_eq!(layout.location.y, 30f32);
1116    }
1117}