tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 520HTML 244Markdown 7TOML 41339 Definitions

⎇ 09c7a718b2eaee87aa9d0505d5a98bd1d33a32db src/tree/taffy_tree.rs Rust · 1139 lines · 41.9 KB History Who touched what raw

Enable correct image measure functions (#661) 09c7a718b · 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:
225        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
226{
227    /// A reference to the TaffyTree
228    pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
229    /// The context provided for passing to measure functions if layout is run over this struct
230    pub(crate) measure_function: MeasureFunction,
231}
232
233// TraversePartialTree impl for TaffyView
234impl<'t, NodeContext, MeasureFunction> TraversePartialTree for TaffyView<'t, NodeContext, MeasureFunction>
235where
236    MeasureFunction:
237        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
238{
239    type ChildIter<'a> = TaffyTreeChildIter<'a> where Self: 'a;
240
241    #[inline(always)]
242    fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
243        self.taffy.child_ids(parent_node_id)
244    }
245
246    #[inline(always)]
247    fn child_count(&self, parent_node_id: NodeId) -> usize {
248        self.taffy.child_count(parent_node_id)
249    }
250
251    #[inline(always)]
252    fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
253        self.taffy.get_child_id(parent_node_id, child_index)
254    }
255}
256
257// TraverseTree impl for TaffyView
258impl<'t, NodeContext, MeasureFunction> TraverseTree for TaffyView<'t, NodeContext, MeasureFunction> where
259    MeasureFunction:
260        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>
261{
262}
263
264// LayoutPartialTree impl for TaffyView
265impl<'t, NodeContext, MeasureFunction> LayoutPartialTree for TaffyView<'t, NodeContext, MeasureFunction>
266where
267    MeasureFunction:
268        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
269{
270    #[inline(always)]
271    fn get_style(&self, node: NodeId) -> &Style {
272        &self.taffy.nodes[node.into()].style
273    }
274
275    #[inline(always)]
276    fn get_cache_mut(&mut self, node: NodeId) -> &mut Cache {
277        &mut self.taffy.nodes[node.into()].cache
278    }
279
280    #[inline(always)]
281    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
282        self.taffy.nodes[node_id.into()].unrounded_layout = *layout;
283    }
284
285    #[inline(always)]
286    fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
287        // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
288        // and thus that we should lay out this node using hidden layout regardless of it's own display style.
289        if inputs.run_mode == RunMode::PerformHiddenLayout {
290            debug_log!("HIDDEN");
291            return compute_hidden_layout(self, node);
292        }
293
294        // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
295        //   - Return that entry if exists
296        //   - Else call the passed closure (below) to compute the result
297        //
298        // If there was no cache match and a new result needs to be computed then that result will be added to the cache
299        compute_cached_layout(self, node, inputs, |tree, node, inputs| {
300            let display_mode = tree.get_style(node).display;
301            let has_children = tree.child_count(node) > 0;
302
303            debug_log!(display_mode);
304            debug_log_node!(
305                inputs.known_dimensions,
306                inputs.parent_size,
307                inputs.available_space,
308                inputs.run_mode,
309                inputs.sizing_mode
310            );
311
312            // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
313            match (display_mode, has_children) {
314                (Display::None, _) => compute_hidden_layout(tree, node),
315                #[cfg(feature = "block_layout")]
316                (Display::Block, true) => compute_block_layout(tree, node, inputs),
317                #[cfg(feature = "flexbox")]
318                (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
319                #[cfg(feature = "grid")]
320                (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
321                (_, false) => {
322                    let node_key = node.into();
323                    let style = &tree.taffy.nodes[node_key].style;
324                    let has_context = tree.taffy.nodes[node_key].has_context;
325                    let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
326                    let measure_function = |known_dimensions, available_space| {
327                        (tree.measure_function)(known_dimensions, available_space, node, node_context, style)
328                    };
329                    compute_leaf_layout(inputs, style, measure_function)
330                }
331            }
332        })
333    }
334}
335
336// RoundTree impl for TaffyView
337impl<'t, NodeContext, MeasureFunction> RoundTree for TaffyView<'t, NodeContext, MeasureFunction>
338where
339    MeasureFunction:
340        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
341{
342    #[inline(always)]
343    fn get_unrounded_layout(&self, node: NodeId) -> &Layout {
344        &self.taffy.nodes[node.into()].unrounded_layout
345    }
346
347    #[inline(always)]
348    fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
349        self.taffy.nodes[node_id.into()].final_layout = *layout;
350    }
351}
352
353#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
354impl<NodeContext> TaffyTree<NodeContext> {
355    /// Creates a new [`TaffyTree`]
356    ///
357    /// The default capacity of a [`TaffyTree`] is 16 nodes.
358    #[must_use]
359    pub fn new() -> Self {
360        Self::with_capacity(16)
361    }
362
363    /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
364    #[must_use]
365    pub fn with_capacity(capacity: usize) -> Self {
366        TaffyTree {
367            // TODO: make this method const upstream,
368            // so constructors here can be const
369            nodes: SlotMap::with_capacity(capacity),
370            children: SlotMap::with_capacity(capacity),
371            parents: SlotMap::with_capacity(capacity),
372            node_context_data: SecondaryMap::with_capacity(capacity),
373            config: TaffyConfig::default(),
374        }
375    }
376
377    /// Enable rounding of layout values. Rounding is enabled by default.
378    pub fn enable_rounding(&mut self) {
379        self.config.use_rounding = true;
380    }
381
382    /// Disable rounding of layout values. Rounding is enabled by default.
383    pub fn disable_rounding(&mut self) {
384        self.config.use_rounding = false;
385    }
386
387    /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
388    pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
389        let id = self.nodes.insert(NodeData::new(layout));
390        let _ = self.children.insert(new_vec_with_capacity(0));
391        let _ = self.parents.insert(None);
392
393        Ok(id.into())
394    }
395
396    /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
397    ///
398    /// Creates and adds a new leaf node with a supplied context
399    pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
400        let mut data = NodeData::new(layout);
401        data.has_context = true;
402
403        let id = self.nodes.insert(data);
404        self.node_context_data.insert(id, context);
405
406        let _ = self.children.insert(new_vec_with_capacity(0));
407        let _ = self.parents.insert(None);
408
409        Ok(id.into())
410    }
411
412    /// Creates and adds a new node, which may have any number of `children`
413    pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
414        let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
415
416        for child in children {
417            self.parents[(*child).into()] = Some(id);
418        }
419
420        let _ = self.children.insert(children.iter().copied().collect::<_>());
421        let _ = self.parents.insert(None);
422
423        Ok(id)
424    }
425
426    /// Drops all nodes in the tree
427    pub fn clear(&mut self) {
428        self.nodes.clear();
429        self.children.clear();
430        self.parents.clear();
431    }
432
433    /// Remove a specific node from the tree and drop it
434    ///
435    /// Returns the id of the node removed.
436    pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
437        let key = node.into();
438        if let Some(parent) = self.parents[key] {
439            if let Some(children) = self.children.get_mut(parent.into()) {
440                children.retain(|f| *f != node);
441            }
442        }
443
444        // Remove "parent" references to a node when removing that node
445        if let Some(children) = self.children.get(key) {
446            for child in children.iter().copied() {
447                self.parents[child.into()] = None;
448            }
449        }
450
451        let _ = self.children.remove(key);
452        let _ = self.parents.remove(key);
453        let _ = self.nodes.remove(key);
454
455        Ok(node)
456    }
457
458    /// Sets the context data associated with the node
459    pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
460        let key = node.into();
461        if let Some(measure) = measure {
462            self.nodes[key].has_context = true;
463            self.node_context_data.insert(key, measure);
464        } else {
465            self.nodes[key].has_context = false;
466            self.node_context_data.remove(key);
467        }
468
469        self.mark_dirty(node)?;
470
471        Ok(())
472    }
473
474    /// Gets a reference to the the context data associated with the node
475    pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
476        self.node_context_data.get(node.into())
477    }
478
479    /// Gets a mutable reference to the the context data associated with the node
480    pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
481        self.node_context_data.get_mut(node.into())
482    }
483
484    /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
485    pub fn get_disjoint_node_context_mut<const N: usize>(
486        &mut self,
487        keys: [NodeId; N],
488    ) -> Option<[&mut NodeContext; N]> {
489        self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
490    }
491
492    /// Adds a `child` node under the supplied `parent`
493    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
494        let parent_key = parent.into();
495        let child_key = child.into();
496        self.parents[child_key] = Some(parent);
497        self.children[parent_key].push(child);
498        self.mark_dirty(parent)?;
499
500        Ok(())
501    }
502
503    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
504    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
505        let parent_key = parent.into();
506
507        let child_count = self.children[parent_key].len();
508        if child_index > child_count {
509            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
510        }
511
512        self.parents[child.into()] = Some(parent);
513        self.children[parent_key].insert(child_index, child);
514        self.mark_dirty(parent)?;
515
516        Ok(())
517    }
518
519    /// Directly sets the `children` of the supplied `parent`
520    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
521        let parent_key = parent.into();
522
523        // Remove node as parent from all its current children.
524        for child in &self.children[parent_key] {
525            self.parents[(*child).into()] = None;
526        }
527
528        // Build up relation node <-> child
529        for child in children {
530            self.parents[(*child).into()] = Some(parent);
531        }
532
533        let parent_children = &mut self.children[parent_key];
534        parent_children.clear();
535        children.iter().for_each(|child| parent_children.push(*child));
536
537        self.mark_dirty(parent)?;
538
539        Ok(())
540    }
541
542    /// Removes the `child` of the parent `node`
543    ///
544    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
545    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
546        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
547        self.remove_child_at_index(parent, index)
548    }
549
550    /// Removes the child at the given `index` from the `parent`
551    ///
552    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
553    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
554        let parent_key = parent.into();
555        let child_count = self.children[parent_key].len();
556        if child_index >= child_count {
557            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
558        }
559
560        let child = self.children[parent_key].remove(child_index);
561        self.parents[child.into()] = None;
562
563        self.mark_dirty(parent)?;
564
565        Ok(child)
566    }
567
568    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
569    ///
570    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
571    pub fn replace_child_at_index(
572        &mut self,
573        parent: NodeId,
574        child_index: usize,
575        new_child: NodeId,
576    ) -> TaffyResult<NodeId> {
577        let parent_key = parent.into();
578
579        let child_count = self.children[parent_key].len();
580        if child_index >= child_count {
581            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
582        }
583
584        self.parents[new_child.into()] = Some(parent);
585        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
586        self.parents[old_child.into()] = None;
587
588        self.mark_dirty(parent)?;
589
590        Ok(old_child)
591    }
592
593    /// Returns the child node of the parent `node` at the provided `child_index`
594    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
595        let parent_key = parent.into();
596        let child_count = self.children[parent_key].len();
597        if child_index >= child_count {
598            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
599        }
600
601        Ok(self.children[parent_key][child_index])
602    }
603
604    /// Returns the total number of nodes in the tree
605    pub fn total_node_count(&self) -> usize {
606        self.nodes.len()
607    }
608
609    /// Returns the `NodeId` of the parent node of the specified node (if it exists)
610    ///
611    /// - Return None if the specified node has no parent
612    /// - Panics if the specified node does not exist
613    pub fn parent(&self, child_id: NodeId) -> Option<NodeId> {
614        self.parents[child_id.into()]
615    }
616
617    /// Returns a list of children that belong to the parent node
618    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
619        Ok(self.children[parent.into()].iter().copied().collect::<_>())
620    }
621
622    /// Sets the [`Style`] of the provided `node`
623    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
624        self.nodes[node.into()].style = style;
625        self.mark_dirty(node)?;
626        Ok(())
627    }
628
629    /// Gets the [`Style`] of the provided `node`
630    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
631        Ok(&self.nodes[node.into()].style)
632    }
633
634    /// Return this node layout relative to its parent
635    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
636        if self.config.use_rounding {
637            Ok(&self.nodes[node.into()].final_layout)
638        } else {
639            Ok(&self.nodes[node.into()].unrounded_layout)
640        }
641    }
642
643    /// Marks the layout computation of this node and its children as outdated
644    ///
645    /// Performs a recursive depth-first search up the tree until the root node is reached
646    ///
647    /// WARNING: this will stack-overflow if the tree contains a cycle
648    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
649        /// WARNING: this will stack-overflow if the tree contains a cycle
650        fn mark_dirty_recursive(
651            nodes: &mut SlotMap<DefaultKey, NodeData>,
652            parents: &SlotMap<DefaultKey, Option<NodeId>>,
653            node_key: DefaultKey,
654        ) {
655            nodes[node_key].mark_dirty();
656
657            if let Some(Some(node)) = parents.get(node_key) {
658                mark_dirty_recursive(nodes, parents, (*node).into());
659            }
660        }
661
662        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
663
664        Ok(())
665    }
666
667    /// Indicates whether the layout of this node (and its children) need to be recomputed
668    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
669        Ok(self.nodes[node.into()].cache.is_empty())
670    }
671
672    /// Updates the stored layout of the provided `node` and its children
673    pub fn compute_layout_with_measure<MeasureFunction>(
674        &mut self,
675        node_id: NodeId,
676        available_space: Size<AvailableSpace>,
677        measure_function: MeasureFunction,
678    ) -> Result<(), TaffyError>
679    where
680        MeasureFunction:
681            FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
682    {
683        let use_rounding = self.config.use_rounding;
684        let mut taffy_view = TaffyView { taffy: self, measure_function };
685        compute_root_layout(&mut taffy_view, node_id, available_space);
686        if use_rounding {
687            round_layout(&mut taffy_view, node_id);
688        }
689        Ok(())
690    }
691
692    /// Updates the stored layout of the provided `node` and its children
693    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
694        self.compute_layout_with_measure(node, available_space, |_, _, _, _, _| Size::ZERO)
695    }
696
697    /// Prints a debug representation of the tree's layout
698    #[cfg(feature = "std")]
699    pub fn print_tree(&mut self, root: NodeId) {
700        crate::util::print_tree(self, root)
701    }
702
703    /// Returns an instance of LayoutTree representing the TaffyTree
704    #[cfg(test)]
705    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + '_ {
706        TaffyView { taffy: self, measure_function: |_, _, _, _, _| Size::ZERO }
707    }
708}
709
710#[cfg(test)]
711mod tests {
712
713    use super::*;
714    use crate::style::{Dimension, Display, FlexDirection};
715    use crate::style_helpers::*;
716    use crate::util::sys;
717
718    fn size_measure_function(
719        known_dimensions: Size<Option<f32>>,
720        _available_space: Size<AvailableSpace>,
721        _node_id: NodeId,
722        node_context: Option<&mut Size<f32>>,
723        _style: &Style,
724    ) -> Size<f32> {
725        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
726    }
727
728    #[test]
729    fn new_should_allocate_default_capacity() {
730        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
731        let taffy: TaffyTree<()> = TaffyTree::new();
732
733        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
734        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
735        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
736    }
737
738    #[test]
739    fn test_with_capacity() {
740        const CAPACITY: usize = 8;
741        let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
742
743        assert!(taffy.children.capacity() >= CAPACITY);
744        assert!(taffy.parents.capacity() >= CAPACITY);
745        assert!(taffy.nodes.capacity() >= CAPACITY);
746    }
747
748    #[test]
749    fn test_new_leaf() {
750        let mut taffy: TaffyTree<()> = TaffyTree::new();
751
752        let res = taffy.new_leaf(Style::default());
753        assert!(res.is_ok());
754        let node = res.unwrap();
755
756        // node should be in the taffy tree and have no children
757        assert!(taffy.child_count(node) == 0);
758    }
759
760    #[test]
761    fn new_leaf_with_context() {
762        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
763
764        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
765        assert!(res.is_ok());
766        let node = res.unwrap();
767
768        // node should be in the taffy tree and have no children
769        assert!(taffy.child_count(node) == 0);
770    }
771
772    /// Test that new_with_children works as expected
773    #[test]
774    fn test_new_with_children() {
775        let mut taffy: TaffyTree<()> = TaffyTree::new();
776        let child0 = taffy.new_leaf(Style::default()).unwrap();
777        let child1 = taffy.new_leaf(Style::default()).unwrap();
778        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
779
780        // node should have two children
781        assert_eq!(taffy.child_count(node), 2);
782        assert_eq!(taffy.children(node).unwrap()[0], child0);
783        assert_eq!(taffy.children(node).unwrap()[1], child1);
784    }
785
786    #[test]
787    fn remove_node_should_remove() {
788        let mut taffy: TaffyTree<()> = TaffyTree::new();
789
790        let node = taffy.new_leaf(Style::default()).unwrap();
791
792        let _ = taffy.remove(node).unwrap();
793    }
794
795    #[test]
796    fn remove_node_should_detach_hierarchy() {
797        let mut taffy: TaffyTree<()> = TaffyTree::new();
798
799        // Build a linear tree layout: <0> <- <1> <- <2>
800        let node2 = taffy.new_leaf(Style::default()).unwrap();
801        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
802        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
803
804        // Both node0 and node1 should have 1 child nodes
805        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
806        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
807
808        // Disconnect the tree: <0> <2>
809        let _ = taffy.remove(node1).unwrap();
810
811        // Both remaining nodes should have no child nodes
812        assert!(taffy.children(node0).unwrap().is_empty());
813        assert!(taffy.children(node2).unwrap().is_empty());
814    }
815
816    #[test]
817    fn remove_last_node() {
818        let mut taffy: TaffyTree<()> = TaffyTree::new();
819
820        let parent = taffy.new_leaf(Style::default()).unwrap();
821        let child = taffy.new_leaf(Style::default()).unwrap();
822        taffy.add_child(parent, child).unwrap();
823
824        taffy.remove(child).unwrap();
825        taffy.remove(parent).unwrap();
826    }
827
828    #[test]
829    fn set_measure() {
830        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
831        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
832        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
833        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
834
835        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
836        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
837        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
838    }
839
840    #[test]
841    fn set_measure_of_previously_unmeasured_node() {
842        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
843        let node = taffy.new_leaf(Style::default()).unwrap();
844        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
845        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
846
847        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
848        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
849        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
850    }
851
852    /// Test that adding `add_child()` works
853    #[test]
854    fn add_child() {
855        let mut taffy: TaffyTree<()> = TaffyTree::new();
856        let node = taffy.new_leaf(Style::default()).unwrap();
857        assert_eq!(taffy.child_count(node), 0);
858
859        let child0 = taffy.new_leaf(Style::default()).unwrap();
860        taffy.add_child(node, child0).unwrap();
861        assert_eq!(taffy.child_count(node), 1);
862
863        let child1 = taffy.new_leaf(Style::default()).unwrap();
864        taffy.add_child(node, child1).unwrap();
865        assert_eq!(taffy.child_count(node), 2);
866    }
867
868    #[test]
869    fn insert_child_at_index() {
870        let mut taffy: TaffyTree<()> = TaffyTree::new();
871
872        let child0 = taffy.new_leaf(Style::default()).unwrap();
873        let child1 = taffy.new_leaf(Style::default()).unwrap();
874        let child2 = taffy.new_leaf(Style::default()).unwrap();
875
876        let node = taffy.new_leaf(Style::default()).unwrap();
877        assert_eq!(taffy.child_count(node), 0);
878
879        taffy.insert_child_at_index(node, 0, child0).unwrap();
880        assert_eq!(taffy.child_count(node), 1);
881        assert_eq!(taffy.children(node).unwrap()[0], child0);
882
883        taffy.insert_child_at_index(node, 0, child1).unwrap();
884        assert_eq!(taffy.child_count(node), 2);
885        assert_eq!(taffy.children(node).unwrap()[0], child1);
886        assert_eq!(taffy.children(node).unwrap()[1], child0);
887
888        taffy.insert_child_at_index(node, 1, child2).unwrap();
889        assert_eq!(taffy.child_count(node), 3);
890        assert_eq!(taffy.children(node).unwrap()[0], child1);
891        assert_eq!(taffy.children(node).unwrap()[1], child2);
892        assert_eq!(taffy.children(node).unwrap()[2], child0);
893    }
894
895    #[test]
896    fn set_children() {
897        let mut taffy: TaffyTree<()> = TaffyTree::new();
898
899        let child0 = taffy.new_leaf(Style::default()).unwrap();
900        let child1 = taffy.new_leaf(Style::default()).unwrap();
901        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
902
903        assert_eq!(taffy.child_count(node), 2);
904        assert_eq!(taffy.children(node).unwrap()[0], child0);
905        assert_eq!(taffy.children(node).unwrap()[1], child1);
906
907        let child2 = taffy.new_leaf(Style::default()).unwrap();
908        let child3 = taffy.new_leaf(Style::default()).unwrap();
909        taffy.set_children(node, &[child2, child3]).unwrap();
910
911        assert_eq!(taffy.child_count(node), 2);
912        assert_eq!(taffy.children(node).unwrap()[0], child2);
913        assert_eq!(taffy.children(node).unwrap()[1], child3);
914    }
915
916    /// Test that removing a child works
917    #[test]
918    fn remove_child() {
919        let mut taffy: TaffyTree<()> = TaffyTree::new();
920        let child0 = taffy.new_leaf(Style::default()).unwrap();
921        let child1 = taffy.new_leaf(Style::default()).unwrap();
922        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
923
924        assert_eq!(taffy.child_count(node), 2);
925
926        taffy.remove_child(node, child0).unwrap();
927        assert_eq!(taffy.child_count(node), 1);
928        assert_eq!(taffy.children(node).unwrap()[0], child1);
929
930        taffy.remove_child(node, child1).unwrap();
931        assert_eq!(taffy.child_count(node), 0);
932    }
933
934    #[test]
935    fn remove_child_at_index() {
936        let mut taffy: TaffyTree<()> = TaffyTree::new();
937        let child0 = taffy.new_leaf(Style::default()).unwrap();
938        let child1 = taffy.new_leaf(Style::default()).unwrap();
939        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
940
941        assert_eq!(taffy.child_count(node), 2);
942
943        taffy.remove_child_at_index(node, 0).unwrap();
944        assert_eq!(taffy.child_count(node), 1);
945        assert_eq!(taffy.children(node).unwrap()[0], child1);
946
947        taffy.remove_child_at_index(node, 0).unwrap();
948        assert_eq!(taffy.child_count(node), 0);
949    }
950
951    // Related to: https://github.com/DioxusLabs/taffy/issues/510
952    #[test]
953    fn remove_child_updates_parents() {
954        let mut taffy: TaffyTree<()> = TaffyTree::new();
955
956        let parent = taffy.new_leaf(Style::default()).unwrap();
957        let child = taffy.new_leaf(Style::default()).unwrap();
958
959        taffy.add_child(parent, child).unwrap();
960
961        taffy.remove(parent).unwrap();
962
963        // Once the parent is removed this shouldn't panic.
964        assert!(taffy.set_children(child, &[]).is_ok());
965    }
966
967    #[test]
968    fn replace_child_at_index() {
969        let mut taffy: TaffyTree<()> = TaffyTree::new();
970
971        let child0 = taffy.new_leaf(Style::default()).unwrap();
972        let child1 = taffy.new_leaf(Style::default()).unwrap();
973
974        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
975        assert_eq!(taffy.child_count(node), 1);
976        assert_eq!(taffy.children(node).unwrap()[0], child0);
977
978        taffy.replace_child_at_index(node, 0, child1).unwrap();
979        assert_eq!(taffy.child_count(node), 1);
980        assert_eq!(taffy.children(node).unwrap()[0], child1);
981    }
982    #[test]
983    fn test_child_at_index() {
984        let mut taffy: TaffyTree<()> = TaffyTree::new();
985        let child0 = taffy.new_leaf(Style::default()).unwrap();
986        let child1 = taffy.new_leaf(Style::default()).unwrap();
987        let child2 = taffy.new_leaf(Style::default()).unwrap();
988        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
989
990        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
991        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
992        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
993    }
994    #[test]
995    fn test_child_count() {
996        let mut taffy: TaffyTree<()> = TaffyTree::new();
997        let child0 = taffy.new_leaf(Style::default()).unwrap();
998        let child1 = taffy.new_leaf(Style::default()).unwrap();
999        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1000
1001        assert!(taffy.child_count(node) == 2);
1002        assert!(taffy.child_count(child0) == 0);
1003        assert!(taffy.child_count(child1) == 0);
1004    }
1005
1006    #[allow(clippy::vec_init_then_push)]
1007    #[test]
1008    fn test_children() {
1009        let mut taffy: TaffyTree<()> = TaffyTree::new();
1010        let child0 = taffy.new_leaf(Style::default()).unwrap();
1011        let child1 = taffy.new_leaf(Style::default()).unwrap();
1012        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1013
1014        let mut children = sys::Vec::new();
1015        children.push(child0);
1016        children.push(child1);
1017
1018        let children_result = taffy.children(node).unwrap();
1019        assert_eq!(children_result, children);
1020
1021        assert!(taffy.children(child0).unwrap().is_empty());
1022    }
1023    #[test]
1024    fn test_set_style() {
1025        let mut taffy: TaffyTree<()> = TaffyTree::new();
1026
1027        let node = taffy.new_leaf(Style::default()).unwrap();
1028        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1029
1030        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1031        assert_eq!(taffy.style(node).unwrap().display, Display::None);
1032    }
1033    #[test]
1034    fn test_style() {
1035        let mut taffy: TaffyTree<()> = TaffyTree::new();
1036
1037        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1038
1039        let node = taffy.new_leaf(style.clone()).unwrap();
1040
1041        let res = taffy.style(node);
1042        assert!(res.is_ok());
1043        assert!(res.unwrap() == &style);
1044    }
1045    #[test]
1046    fn test_layout() {
1047        let mut taffy: TaffyTree<()> = TaffyTree::new();
1048        let node = taffy.new_leaf(Style::default()).unwrap();
1049
1050        // TODO: Improve this test?
1051        let res = taffy.layout(node);
1052        assert!(res.is_ok());
1053    }
1054
1055    #[test]
1056    fn test_mark_dirty() {
1057        let mut taffy: TaffyTree<()> = TaffyTree::new();
1058        let child0 = taffy.new_leaf(Style::default()).unwrap();
1059        let child1 = taffy.new_leaf(Style::default()).unwrap();
1060        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1061
1062        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1063
1064        assert_eq!(taffy.dirty(child0).unwrap(), false);
1065        assert_eq!(taffy.dirty(child1).unwrap(), false);
1066        assert_eq!(taffy.dirty(node).unwrap(), false);
1067
1068        taffy.mark_dirty(node).unwrap();
1069        assert_eq!(taffy.dirty(child0).unwrap(), false);
1070        assert_eq!(taffy.dirty(child1).unwrap(), false);
1071        assert_eq!(taffy.dirty(node).unwrap(), true);
1072
1073        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1074        taffy.mark_dirty(child0).unwrap();
1075        assert_eq!(taffy.dirty(child0).unwrap(), true);
1076        assert_eq!(taffy.dirty(child1).unwrap(), false);
1077        assert_eq!(taffy.dirty(node).unwrap(), true);
1078    }
1079
1080    #[test]
1081    fn compute_layout_should_produce_valid_result() {
1082        let mut taffy: TaffyTree<()> = TaffyTree::new();
1083        let node_result = taffy.new_leaf(Style {
1084            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1085            ..Default::default()
1086        });
1087        assert!(node_result.is_ok());
1088        let node = node_result.unwrap();
1089        let layout_result = taffy.compute_layout(
1090            node,
1091            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1092        );
1093        assert!(layout_result.is_ok());
1094    }
1095
1096    #[test]
1097    fn make_sure_layout_location_is_top_left() {
1098        use crate::prelude::Rect;
1099
1100        let mut taffy: TaffyTree<()> = TaffyTree::new();
1101
1102        let node = taffy
1103            .new_leaf(Style {
1104                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1105                ..Default::default()
1106            })
1107            .unwrap();
1108
1109        let root = taffy
1110            .new_with_children(
1111                Style {
1112                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1113                    padding: Rect {
1114                        left: length(10f32),
1115                        right: length(20f32),
1116                        top: length(30f32),
1117                        bottom: length(40f32),
1118                    },
1119                    ..Default::default()
1120                },
1121                &[node],
1122            )
1123            .unwrap();
1124
1125        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1126
1127        // If Layout::location represents top-left coord, 'node' location
1128        // must be (due applied 'root' padding): {x: 10, y: 30}.
1129        //
1130        // It's important, since result will be different for each other
1131        // coordinate space:
1132        // - bottom-left:  {x: 10, y: 40}
1133        // - top-right:    {x: 20, y: 30}
1134        // - bottom-right: {x: 20, y: 40}
1135        let layout = taffy.layout(node).unwrap();
1136        assert_eq!(layout.location.x, 10f32);
1137        assert_eq!(layout.location.y, 30f32);
1138    }
1139}