tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 496HTML 245JavaScript 8CSS 61214 Sutichaykuna

⎇ b3aeb2ecb74fed0c86761b57213e95048efc1de9 src/tree/taffy_tree.rs Rust · 1309 siq'ikuna · 47.0 KB Ñawpa willay Pi imata llamkarqan ch'uya

`unrounded_layout` helper method (#765) b3aeb2ecb · ickshonpe ·

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