gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5544Rust 88Markdown 11TOML 91926 Definitions

⎇ 563d5dcee7b9138b4c3f865155d036a8b7597e65 src/tree/taffy_tree.rs Rust · 1125 lines · 41.5 KB History Who touched what raw

Call measure function on leaf nodes even if the node does not have context (#598) 563d5dcee · Nico Burns ·

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    /// Whether the node has context data associated with it or not
96    pub(crate) has_context: 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            has_context: 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 has_context = tree.taffy.nodes[node_key].has_context;
321                    let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
322                    let measure_function = |known_dimensions, available_space| {
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.has_context = 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].has_context = true;
458            self.node_context_data.insert(key, measure);
459        } else {
460            self.nodes[key].has_context = 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    /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
480    pub fn get_disjoint_node_context_mut<const N: usize>(
481        &mut self,
482        keys: [NodeId; N],
483    ) -> Option<[&mut NodeContext; N]> {
484        self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
485    }
486
487    /// Adds a `child` node under the supplied `parent`
488    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
489        let parent_key = parent.into();
490        let child_key = child.into();
491        self.parents[child_key] = Some(parent);
492        self.children[parent_key].push(child);
493        self.mark_dirty(parent)?;
494
495        Ok(())
496    }
497
498    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
499    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
500        let parent_key = parent.into();
501
502        let child_count = self.children[parent_key].len();
503        if child_index > child_count {
504            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
505        }
506
507        self.parents[child.into()] = Some(parent);
508        self.children[parent_key].insert(child_index, child);
509        self.mark_dirty(parent)?;
510
511        Ok(())
512    }
513
514    /// Directly sets the `children` of the supplied `parent`
515    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
516        let parent_key = parent.into();
517
518        // Remove node as parent from all its current children.
519        for child in &self.children[parent_key] {
520            self.parents[(*child).into()] = None;
521        }
522
523        // Build up relation node <-> child
524        for child in children {
525            self.parents[(*child).into()] = Some(parent);
526        }
527
528        let parent_children = &mut self.children[parent_key];
529        parent_children.clear();
530        children.iter().for_each(|child| parent_children.push(*child));
531
532        self.mark_dirty(parent)?;
533
534        Ok(())
535    }
536
537    /// Removes the `child` of the parent `node`
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(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
541        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
542        self.remove_child_at_index(parent, index)
543    }
544
545    /// Removes the child at the given `index` from the `parent`
546    ///
547    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
548    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
549        let parent_key = parent.into();
550        let child_count = self.children[parent_key].len();
551        if child_index >= child_count {
552            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
553        }
554
555        let child = self.children[parent_key].remove(child_index);
556        self.parents[child.into()] = None;
557
558        self.mark_dirty(parent)?;
559
560        Ok(child)
561    }
562
563    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
564    ///
565    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
566    pub fn replace_child_at_index(
567        &mut self,
568        parent: NodeId,
569        child_index: usize,
570        new_child: NodeId,
571    ) -> TaffyResult<NodeId> {
572        let parent_key = parent.into();
573
574        let child_count = self.children[parent_key].len();
575        if child_index >= child_count {
576            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
577        }
578
579        self.parents[new_child.into()] = Some(parent);
580        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
581        self.parents[old_child.into()] = None;
582
583        self.mark_dirty(parent)?;
584
585        Ok(old_child)
586    }
587
588    /// Returns the child node of the parent `node` at the provided `child_index`
589    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
590        let parent_key = parent.into();
591        let child_count = self.children[parent_key].len();
592        if child_index >= child_count {
593            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
594        }
595
596        Ok(self.children[parent_key][child_index])
597    }
598
599    /// Returns the total number of nodes in the tree
600    pub fn total_node_count(&self) -> usize {
601        self.nodes.len()
602    }
603
604    /// Returns a list of children that belong to the parent node
605    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
606        Ok(self.children[parent.into()].iter().copied().collect::<_>())
607    }
608
609    /// Sets the [`Style`] of the provided `node`
610    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
611        self.nodes[node.into()].style = style;
612        self.mark_dirty(node)?;
613        Ok(())
614    }
615
616    /// Gets the [`Style`] of the provided `node`
617    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
618        Ok(&self.nodes[node.into()].style)
619    }
620
621    /// Return this node layout relative to its parent
622    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
623        if self.config.use_rounding {
624            Ok(&self.nodes[node.into()].final_layout)
625        } else {
626            Ok(&self.nodes[node.into()].unrounded_layout)
627        }
628    }
629
630    /// Marks the layout computation of this node and its children as outdated
631    ///
632    /// Performs a recursive depth-first search up the tree until the root node is reached
633    ///
634    /// WARNING: this will stack-overflow if the tree contains a cycle
635    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
636        /// WARNING: this will stack-overflow if the tree contains a cycle
637        fn mark_dirty_recursive(
638            nodes: &mut SlotMap<DefaultKey, NodeData>,
639            parents: &SlotMap<DefaultKey, Option<NodeId>>,
640            node_key: DefaultKey,
641        ) {
642            nodes[node_key].mark_dirty();
643
644            if let Some(Some(node)) = parents.get(node_key) {
645                mark_dirty_recursive(nodes, parents, (*node).into());
646            }
647        }
648
649        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
650
651        Ok(())
652    }
653
654    /// Indicates whether the layout of this node (and its children) need to be recomputed
655    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
656        Ok(self.nodes[node.into()].cache.is_empty())
657    }
658
659    /// Updates the stored layout of the provided `node` and its children
660    pub fn compute_layout_with_measure<MeasureFunction>(
661        &mut self,
662        node_id: NodeId,
663        available_space: Size<AvailableSpace>,
664        measure_function: MeasureFunction,
665    ) -> Result<(), TaffyError>
666    where
667        MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
668    {
669        let use_rounding = self.config.use_rounding;
670        let mut taffy_view = TaffyView { taffy: self, measure_function };
671        compute_root_layout(&mut taffy_view, node_id, available_space);
672        if use_rounding {
673            round_layout(&mut taffy_view, node_id);
674        }
675        Ok(())
676    }
677
678    /// Updates the stored layout of the provided `node` and its children
679    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
680        self.compute_layout_with_measure(node, available_space, |_, _, _, _| Size::ZERO)
681    }
682
683    /// Prints a debug representation of the tree's layout
684    #[cfg(feature = "std")]
685    pub fn print_tree(&mut self, root: NodeId) {
686        crate::util::print_tree(self, root)
687    }
688
689    /// Returns an instance of LayoutTree representing the TaffyTree
690    #[cfg(test)]
691    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + '_ {
692        TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO }
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    #![allow(clippy::bool_assert_comparison)]
699
700    use super::*;
701    use crate::style::{Dimension, Display, FlexDirection};
702    use crate::style_helpers::*;
703    use crate::util::sys;
704
705    fn size_measure_function(
706        known_dimensions: Size<Option<f32>>,
707        _available_space: Size<AvailableSpace>,
708        _node_id: NodeId,
709        node_context: Option<&mut Size<f32>>,
710    ) -> Size<f32> {
711        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
712    }
713
714    #[test]
715    fn new_should_allocate_default_capacity() {
716        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
717        let taffy: TaffyTree<()> = TaffyTree::new();
718
719        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
720        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
721        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
722    }
723
724    #[test]
725    fn test_with_capacity() {
726        const CAPACITY: usize = 8;
727        let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
728
729        assert!(taffy.children.capacity() >= CAPACITY);
730        assert!(taffy.parents.capacity() >= CAPACITY);
731        assert!(taffy.nodes.capacity() >= CAPACITY);
732    }
733
734    #[test]
735    fn test_new_leaf() {
736        let mut taffy: TaffyTree<()> = TaffyTree::new();
737
738        let res = taffy.new_leaf(Style::default());
739        assert!(res.is_ok());
740        let node = res.unwrap();
741
742        // node should be in the taffy tree and have no children
743        assert!(taffy.child_count(node) == 0);
744    }
745
746    #[test]
747    fn new_leaf_with_context() {
748        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
749
750        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
751        assert!(res.is_ok());
752        let node = res.unwrap();
753
754        // node should be in the taffy tree and have no children
755        assert!(taffy.child_count(node) == 0);
756    }
757
758    /// Test that new_with_children works as expected
759    #[test]
760    fn test_new_with_children() {
761        let mut taffy: TaffyTree<()> = TaffyTree::new();
762        let child0 = taffy.new_leaf(Style::default()).unwrap();
763        let child1 = taffy.new_leaf(Style::default()).unwrap();
764        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
765
766        // node should have two children
767        assert_eq!(taffy.child_count(node), 2);
768        assert_eq!(taffy.children(node).unwrap()[0], child0);
769        assert_eq!(taffy.children(node).unwrap()[1], child1);
770    }
771
772    #[test]
773    fn remove_node_should_remove() {
774        let mut taffy: TaffyTree<()> = TaffyTree::new();
775
776        let node = taffy.new_leaf(Style::default()).unwrap();
777
778        let _ = taffy.remove(node).unwrap();
779    }
780
781    #[test]
782    fn remove_node_should_detach_herarchy() {
783        let mut taffy: TaffyTree<()> = TaffyTree::new();
784
785        // Build a linear tree layout: <0> <- <1> <- <2>
786        let node2 = taffy.new_leaf(Style::default()).unwrap();
787        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
788        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
789
790        // Both node0 and node1 should have 1 child nodes
791        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
792        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
793
794        // Disconnect the tree: <0> <2>
795        let _ = taffy.remove(node1).unwrap();
796
797        // Both remaining nodes should have no child nodes
798        assert!(taffy.children(node0).unwrap().is_empty());
799        assert!(taffy.children(node2).unwrap().is_empty());
800    }
801
802    #[test]
803    fn remove_last_node() {
804        let mut taffy: TaffyTree<()> = TaffyTree::new();
805
806        let parent = taffy.new_leaf(Style::default()).unwrap();
807        let child = taffy.new_leaf(Style::default()).unwrap();
808        taffy.add_child(parent, child).unwrap();
809
810        taffy.remove(child).unwrap();
811        taffy.remove(parent).unwrap();
812    }
813
814    #[test]
815    fn set_measure() {
816        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
817        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
818        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
819        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
820
821        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
822        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
823        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
824    }
825
826    #[test]
827    fn set_measure_of_previously_unmeasured_node() {
828        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
829        let node = taffy.new_leaf(Style::default()).unwrap();
830        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
831        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
832
833        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
834        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
835        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
836    }
837
838    /// Test that adding `add_child()` works
839    #[test]
840    fn add_child() {
841        let mut taffy: TaffyTree<()> = TaffyTree::new();
842        let node = taffy.new_leaf(Style::default()).unwrap();
843        assert_eq!(taffy.child_count(node), 0);
844
845        let child0 = taffy.new_leaf(Style::default()).unwrap();
846        taffy.add_child(node, child0).unwrap();
847        assert_eq!(taffy.child_count(node), 1);
848
849        let child1 = taffy.new_leaf(Style::default()).unwrap();
850        taffy.add_child(node, child1).unwrap();
851        assert_eq!(taffy.child_count(node), 2);
852    }
853
854    #[test]
855    fn insert_child_at_index() {
856        let mut taffy: TaffyTree<()> = TaffyTree::new();
857
858        let child0 = taffy.new_leaf(Style::default()).unwrap();
859        let child1 = taffy.new_leaf(Style::default()).unwrap();
860        let child2 = taffy.new_leaf(Style::default()).unwrap();
861
862        let node = taffy.new_leaf(Style::default()).unwrap();
863        assert_eq!(taffy.child_count(node), 0);
864
865        taffy.insert_child_at_index(node, 0, child0).unwrap();
866        assert_eq!(taffy.child_count(node), 1);
867        assert_eq!(taffy.children(node).unwrap()[0], child0);
868
869        taffy.insert_child_at_index(node, 0, child1).unwrap();
870        assert_eq!(taffy.child_count(node), 2);
871        assert_eq!(taffy.children(node).unwrap()[0], child1);
872        assert_eq!(taffy.children(node).unwrap()[1], child0);
873
874        taffy.insert_child_at_index(node, 1, child2).unwrap();
875        assert_eq!(taffy.child_count(node), 3);
876        assert_eq!(taffy.children(node).unwrap()[0], child1);
877        assert_eq!(taffy.children(node).unwrap()[1], child2);
878        assert_eq!(taffy.children(node).unwrap()[2], child0);
879    }
880
881    #[test]
882    fn set_children() {
883        let mut taffy: TaffyTree<()> = TaffyTree::new();
884
885        let child0 = taffy.new_leaf(Style::default()).unwrap();
886        let child1 = taffy.new_leaf(Style::default()).unwrap();
887        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
888
889        assert_eq!(taffy.child_count(node), 2);
890        assert_eq!(taffy.children(node).unwrap()[0], child0);
891        assert_eq!(taffy.children(node).unwrap()[1], child1);
892
893        let child2 = taffy.new_leaf(Style::default()).unwrap();
894        let child3 = taffy.new_leaf(Style::default()).unwrap();
895        taffy.set_children(node, &[child2, child3]).unwrap();
896
897        assert_eq!(taffy.child_count(node), 2);
898        assert_eq!(taffy.children(node).unwrap()[0], child2);
899        assert_eq!(taffy.children(node).unwrap()[1], child3);
900    }
901
902    /// Test that removing a child works
903    #[test]
904    fn remove_child() {
905        let mut taffy: TaffyTree<()> = TaffyTree::new();
906        let child0 = taffy.new_leaf(Style::default()).unwrap();
907        let child1 = taffy.new_leaf(Style::default()).unwrap();
908        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
909
910        assert_eq!(taffy.child_count(node), 2);
911
912        taffy.remove_child(node, child0).unwrap();
913        assert_eq!(taffy.child_count(node), 1);
914        assert_eq!(taffy.children(node).unwrap()[0], child1);
915
916        taffy.remove_child(node, child1).unwrap();
917        assert_eq!(taffy.child_count(node), 0);
918    }
919
920    #[test]
921    fn remove_child_at_index() {
922        let mut taffy: TaffyTree<()> = TaffyTree::new();
923        let child0 = taffy.new_leaf(Style::default()).unwrap();
924        let child1 = taffy.new_leaf(Style::default()).unwrap();
925        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
926
927        assert_eq!(taffy.child_count(node), 2);
928
929        taffy.remove_child_at_index(node, 0).unwrap();
930        assert_eq!(taffy.child_count(node), 1);
931        assert_eq!(taffy.children(node).unwrap()[0], child1);
932
933        taffy.remove_child_at_index(node, 0).unwrap();
934        assert_eq!(taffy.child_count(node), 0);
935    }
936
937    // Related to: https://github.com/DioxusLabs/taffy/issues/510
938    #[test]
939    fn remove_child_updates_parents() {
940        let mut taffy: TaffyTree<()> = TaffyTree::new();
941
942        let parent = taffy.new_leaf(Style::default()).unwrap();
943        let child = taffy.new_leaf(Style::default()).unwrap();
944
945        taffy.add_child(parent, child).unwrap();
946
947        taffy.remove(parent).unwrap();
948
949        // Once the parent is removed this shouldn't panic.
950        assert!(taffy.set_children(child, &[]).is_ok());
951    }
952
953    #[test]
954    fn replace_child_at_index() {
955        let mut taffy: TaffyTree<()> = TaffyTree::new();
956
957        let child0 = taffy.new_leaf(Style::default()).unwrap();
958        let child1 = taffy.new_leaf(Style::default()).unwrap();
959
960        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
961        assert_eq!(taffy.child_count(node), 1);
962        assert_eq!(taffy.children(node).unwrap()[0], child0);
963
964        taffy.replace_child_at_index(node, 0, child1).unwrap();
965        assert_eq!(taffy.child_count(node), 1);
966        assert_eq!(taffy.children(node).unwrap()[0], child1);
967    }
968    #[test]
969    fn test_child_at_index() {
970        let mut taffy: TaffyTree<()> = TaffyTree::new();
971        let child0 = taffy.new_leaf(Style::default()).unwrap();
972        let child1 = taffy.new_leaf(Style::default()).unwrap();
973        let child2 = taffy.new_leaf(Style::default()).unwrap();
974        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
975
976        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
977        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
978        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
979    }
980    #[test]
981    fn test_child_count() {
982        let mut taffy: TaffyTree<()> = TaffyTree::new();
983        let child0 = taffy.new_leaf(Style::default()).unwrap();
984        let child1 = taffy.new_leaf(Style::default()).unwrap();
985        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
986
987        assert!(taffy.child_count(node) == 2);
988        assert!(taffy.child_count(child0) == 0);
989        assert!(taffy.child_count(child1) == 0);
990    }
991
992    #[allow(clippy::vec_init_then_push)]
993    #[test]
994    fn test_children() {
995        let mut taffy: TaffyTree<()> = TaffyTree::new();
996        let child0 = taffy.new_leaf(Style::default()).unwrap();
997        let child1 = taffy.new_leaf(Style::default()).unwrap();
998        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
999
1000        let mut children = sys::Vec::new();
1001        children.push(child0);
1002        children.push(child1);
1003
1004        let children_result = taffy.children(node).unwrap();
1005        assert_eq!(children_result, children);
1006
1007        assert!(taffy.children(child0).unwrap().is_empty());
1008    }
1009    #[test]
1010    fn test_set_style() {
1011        let mut taffy: TaffyTree<()> = TaffyTree::new();
1012
1013        let node = taffy.new_leaf(Style::default()).unwrap();
1014        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1015
1016        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1017        assert_eq!(taffy.style(node).unwrap().display, Display::None);
1018    }
1019    #[test]
1020    fn test_style() {
1021        let mut taffy: TaffyTree<()> = TaffyTree::new();
1022
1023        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1024
1025        let node = taffy.new_leaf(style.clone()).unwrap();
1026
1027        let res = taffy.style(node);
1028        assert!(res.is_ok());
1029        assert!(res.unwrap() == &style);
1030    }
1031    #[test]
1032    fn test_layout() {
1033        let mut taffy: TaffyTree<()> = TaffyTree::new();
1034        let node = taffy.new_leaf(Style::default()).unwrap();
1035
1036        // TODO: Improve this test?
1037        let res = taffy.layout(node);
1038        assert!(res.is_ok());
1039    }
1040
1041    #[test]
1042    fn test_mark_dirty() {
1043        let mut taffy: TaffyTree<()> = TaffyTree::new();
1044        let child0 = taffy.new_leaf(Style::default()).unwrap();
1045        let child1 = taffy.new_leaf(Style::default()).unwrap();
1046        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1047
1048        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1049
1050        assert_eq!(taffy.dirty(child0).unwrap(), false);
1051        assert_eq!(taffy.dirty(child1).unwrap(), false);
1052        assert_eq!(taffy.dirty(node).unwrap(), false);
1053
1054        taffy.mark_dirty(node).unwrap();
1055        assert_eq!(taffy.dirty(child0).unwrap(), false);
1056        assert_eq!(taffy.dirty(child1).unwrap(), false);
1057        assert_eq!(taffy.dirty(node).unwrap(), true);
1058
1059        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1060        taffy.mark_dirty(child0).unwrap();
1061        assert_eq!(taffy.dirty(child0).unwrap(), true);
1062        assert_eq!(taffy.dirty(child1).unwrap(), false);
1063        assert_eq!(taffy.dirty(node).unwrap(), true);
1064    }
1065
1066    #[test]
1067    fn compute_layout_should_produce_valid_result() {
1068        let mut taffy: TaffyTree<()> = TaffyTree::new();
1069        let node_result = taffy.new_leaf(Style {
1070            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1071            ..Default::default()
1072        });
1073        assert!(node_result.is_ok());
1074        let node = node_result.unwrap();
1075        let layout_result = taffy.compute_layout(
1076            node,
1077            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1078        );
1079        assert!(layout_result.is_ok());
1080    }
1081
1082    #[test]
1083    fn make_sure_layout_location_is_top_left() {
1084        use crate::prelude::Rect;
1085
1086        let mut taffy: TaffyTree<()> = TaffyTree::new();
1087
1088        let node = taffy
1089            .new_leaf(Style {
1090                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1091                ..Default::default()
1092            })
1093            .unwrap();
1094
1095        let root = taffy
1096            .new_with_children(
1097                Style {
1098                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1099                    padding: Rect {
1100                        left: length(10f32),
1101                        right: length(20f32),
1102                        top: length(30f32),
1103                        bottom: length(40f32),
1104                    },
1105                    ..Default::default()
1106                },
1107                &[node],
1108            )
1109            .unwrap();
1110
1111        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1112
1113        // If Layout::location represents top-left coord, 'node' location
1114        // must be (due applied 'root' padding): {x: 10, y: 30}.
1115        //
1116        // It's important, since result will be different for each other
1117        // coordinate space:
1118        // - bottom-left:  {x: 10, y: 40}
1119        // - top-right:    {x: 20, y: 30}
1120        // - bottom-right: {x: 20, y: 40}
1121        let layout = taffy.layout(node).unwrap();
1122        assert_eq!(layout.location.x, 10f32);
1123        assert_eq!(layout.location.y, 30f32);
1124    }
1125}