gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

⎇ ff58be174437ec68447b7e7edf40e7fcc382fdbd src/tree/taffy_tree.rs Rust · 1341 lines · 48.4 KB History Who touched what raw

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