gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5544Rust 88Markdown 11TOML 91926 Definiciones

⎇ e8674f92096988bc8777b52c6eb4a717c842dab3 src/tree/taffy_tree.rs Rust · 1237 líneas · 44.6 KB Historia Quién tocó qué crudo

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