tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 788HTML 740Markdown 12TOML 62536 Definiciones

⎇ 859cd5182556840aff0fbdcdf1635c3df028e321 src/tree/taffy_tree.rs Rust · 1326 líneas · 47.8 KB Historia Quién tocó qué crudo

Add API to expose computed grid information (#772) 859cd5182 · Steven Novaryo ·

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 compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
340        // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
341        // and thus that we should lay out this node using hidden layout regardless of it's own display style.
342        if inputs.run_mode == RunMode::PerformHiddenLayout {
343            debug_log!("HIDDEN");
344            return compute_hidden_layout(self, node);
345        }
346
347        // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
348        //   - Return that entry if exists
349        //   - Else call the passed closure (below) to compute the result
350        //
351        // If there was no cache match and a new result needs to be computed then that result will be added to the cache
352        compute_cached_layout(self, node, inputs, |tree, node, inputs| {
353            let display_mode = tree.taffy.nodes[node.into()].style.display;
354            let has_children = tree.child_count(node) > 0;
355
356            debug_log!(display_mode);
357            debug_log_node!(
358                inputs.known_dimensions,
359                inputs.parent_size,
360                inputs.available_space,
361                inputs.run_mode,
362                inputs.sizing_mode
363            );
364
365            // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
366            match (display_mode, has_children) {
367                (Display::None, _) => compute_hidden_layout(tree, node),
368                #[cfg(feature = "block_layout")]
369                (Display::Block, true) => compute_block_layout(tree, node, inputs),
370                #[cfg(feature = "flexbox")]
371                (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
372                #[cfg(feature = "grid")]
373                (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
374                (_, false) => {
375                    let node_key = node.into();
376                    let style = &tree.taffy.nodes[node_key].style;
377                    let has_context = tree.taffy.nodes[node_key].has_context;
378                    let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
379                    let measure_function = |known_dimensions, available_space| {
380                        (tree.measure_function)(known_dimensions, available_space, node, node_context, style)
381                    };
382                    compute_leaf_layout(inputs, style, measure_function)
383                }
384            }
385        })
386    }
387}
388
389impl<NodeContext, MeasureFunction> CacheTree for TaffyView<'_, NodeContext, MeasureFunction>
390where
391    MeasureFunction:
392        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
393{
394    fn cache_get(
395        &self,
396        node_id: NodeId,
397        known_dimensions: Size<Option<f32>>,
398        available_space: Size<AvailableSpace>,
399        run_mode: RunMode,
400    ) -> Option<LayoutOutput> {
401        self.taffy.nodes[node_id.into()].cache.get(known_dimensions, available_space, run_mode)
402    }
403
404    fn cache_store(
405        &mut self,
406        node_id: NodeId,
407        known_dimensions: Size<Option<f32>>,
408        available_space: Size<AvailableSpace>,
409        run_mode: RunMode,
410        layout_output: LayoutOutput,
411    ) {
412        self.taffy.nodes[node_id.into()].cache.store(known_dimensions, available_space, run_mode, layout_output)
413    }
414
415    fn cache_clear(&mut self, node_id: NodeId) {
416        self.taffy.nodes[node_id.into()].cache.clear()
417    }
418}
419
420#[cfg(feature = "block_layout")]
421impl<NodeContext, MeasureFunction> LayoutBlockContainer for TaffyView<'_, NodeContext, MeasureFunction>
422where
423    MeasureFunction:
424        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
425{
426    type BlockContainerStyle<'a>
427        = &'a Style
428    where
429        Self: 'a;
430    type BlockItemStyle<'a>
431        = &'a Style
432    where
433        Self: 'a;
434
435    #[inline(always)]
436    fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
437        self.get_core_container_style(node_id)
438    }
439
440    #[inline(always)]
441    fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
442        self.get_core_container_style(child_node_id)
443    }
444}
445
446#[cfg(feature = "flexbox")]
447impl<NodeContext, MeasureFunction> LayoutFlexboxContainer for TaffyView<'_, NodeContext, MeasureFunction>
448where
449    MeasureFunction:
450        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
451{
452    type FlexboxContainerStyle<'a>
453        = &'a Style
454    where
455        Self: 'a;
456    type FlexboxItemStyle<'a>
457        = &'a Style
458    where
459        Self: 'a;
460
461    #[inline(always)]
462    fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
463        &self.taffy.nodes[node_id.into()].style
464    }
465
466    #[inline(always)]
467    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
468        &self.taffy.nodes[child_node_id.into()].style
469    }
470}
471
472#[cfg(feature = "grid")]
473impl<NodeContext, MeasureFunction> LayoutGridContainer for TaffyView<'_, NodeContext, MeasureFunction>
474where
475    MeasureFunction:
476        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
477{
478    type GridContainerStyle<'a>
479        = &'a Style
480    where
481        Self: 'a;
482    type GridItemStyle<'a>
483        = &'a Style
484    where
485        Self: 'a;
486
487    #[inline(always)]
488    fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
489        &self.taffy.nodes[node_id.into()].style
490    }
491
492    #[inline(always)]
493    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
494        &self.taffy.nodes[child_node_id.into()].style
495    }
496
497    #[inline(always)]
498    #[cfg(feature = "detailed_layout_info")]
499    fn set_detailed_grid_info(&mut self, node_id: NodeId, detailed_grid_info: DetailedGridInfo) {
500        self.taffy.nodes[node_id.into()].detailed_layout_info = DetailedLayoutInfo::Grid(Box::new(detailed_grid_info));
501    }
502}
503
504// RoundTree impl for TaffyView
505impl<NodeContext, MeasureFunction> RoundTree for TaffyView<'_, NodeContext, MeasureFunction>
506where
507    MeasureFunction:
508        FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
509{
510    #[inline(always)]
511    fn get_unrounded_layout(&self, node: NodeId) -> &Layout {
512        &self.taffy.nodes[node.into()].unrounded_layout
513    }
514
515    #[inline(always)]
516    fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
517        self.taffy.nodes[node_id.into()].final_layout = *layout;
518    }
519}
520
521#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
522impl<NodeContext> TaffyTree<NodeContext> {
523    /// Creates a new [`TaffyTree`]
524    ///
525    /// The default capacity of a [`TaffyTree`] is 16 nodes.
526    #[must_use]
527    pub fn new() -> Self {
528        Self::with_capacity(16)
529    }
530
531    /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
532    #[must_use]
533    pub fn with_capacity(capacity: usize) -> Self {
534        TaffyTree {
535            // TODO: make this method const upstream,
536            // so constructors here can be const
537            nodes: SlotMap::with_capacity(capacity),
538            children: SlotMap::with_capacity(capacity),
539            parents: SlotMap::with_capacity(capacity),
540            node_context_data: SecondaryMap::with_capacity(capacity),
541            config: TaffyConfig::default(),
542        }
543    }
544
545    /// Enable rounding of layout values. Rounding is enabled by default.
546    pub fn enable_rounding(&mut self) {
547        self.config.use_rounding = true;
548    }
549
550    /// Disable rounding of layout values. Rounding is enabled by default.
551    pub fn disable_rounding(&mut self) {
552        self.config.use_rounding = false;
553    }
554
555    /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
556    pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
557        let id = self.nodes.insert(NodeData::new(layout));
558        let _ = self.children.insert(new_vec_with_capacity(0));
559        let _ = self.parents.insert(None);
560
561        Ok(id.into())
562    }
563
564    /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
565    ///
566    /// Creates and adds a new leaf node with a supplied context
567    pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
568        let mut data = NodeData::new(layout);
569        data.has_context = true;
570
571        let id = self.nodes.insert(data);
572        self.node_context_data.insert(id, context);
573
574        let _ = self.children.insert(new_vec_with_capacity(0));
575        let _ = self.parents.insert(None);
576
577        Ok(id.into())
578    }
579
580    /// Creates and adds a new node, which may have any number of `children`
581    pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
582        let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
583
584        for child in children {
585            self.parents[(*child).into()] = Some(id);
586        }
587
588        let _ = self.children.insert(children.iter().copied().collect::<_>());
589        let _ = self.parents.insert(None);
590
591        Ok(id)
592    }
593
594    /// Drops all nodes in the tree
595    pub fn clear(&mut self) {
596        self.nodes.clear();
597        self.children.clear();
598        self.parents.clear();
599    }
600
601    /// Remove a specific node from the tree and drop it
602    ///
603    /// Returns the id of the node removed.
604    pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
605        let key = node.into();
606        if let Some(parent) = self.parents[key] {
607            if let Some(children) = self.children.get_mut(parent.into()) {
608                children.retain(|f| *f != node);
609            }
610        }
611
612        // Remove "parent" references to a node when removing that node
613        if let Some(children) = self.children.get(key) {
614            for child in children.iter().copied() {
615                self.parents[child.into()] = None;
616            }
617        }
618
619        let _ = self.children.remove(key);
620        let _ = self.parents.remove(key);
621        let _ = self.nodes.remove(key);
622
623        Ok(node)
624    }
625
626    /// Sets the context data associated with the node
627    pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
628        let key = node.into();
629        if let Some(measure) = measure {
630            self.nodes[key].has_context = true;
631            self.node_context_data.insert(key, measure);
632        } else {
633            self.nodes[key].has_context = false;
634            self.node_context_data.remove(key);
635        }
636
637        self.mark_dirty(node)?;
638
639        Ok(())
640    }
641
642    /// Gets a reference to the the context data associated with the node
643    pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
644        self.node_context_data.get(node.into())
645    }
646
647    /// Gets a mutable reference to the the context data associated with the node
648    pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
649        self.node_context_data.get_mut(node.into())
650    }
651
652    /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
653    pub fn get_disjoint_node_context_mut<const N: usize>(
654        &mut self,
655        keys: [NodeId; N],
656    ) -> Option<[&mut NodeContext; N]> {
657        self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
658    }
659
660    /// Adds a `child` node under the supplied `parent`
661    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
662        let parent_key = parent.into();
663        let child_key = child.into();
664        self.parents[child_key] = Some(parent);
665        self.children[parent_key].push(child);
666        self.mark_dirty(parent)?;
667
668        Ok(())
669    }
670
671    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
672    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
673        let parent_key = parent.into();
674
675        let child_count = self.children[parent_key].len();
676        if child_index > child_count {
677            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
678        }
679
680        self.parents[child.into()] = Some(parent);
681        self.children[parent_key].insert(child_index, child);
682        self.mark_dirty(parent)?;
683
684        Ok(())
685    }
686
687    /// Directly sets the `children` of the supplied `parent`
688    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
689        let parent_key = parent.into();
690
691        // Remove node as parent from all its current children.
692        for child in &self.children[parent_key] {
693            self.parents[(*child).into()] = None;
694        }
695
696        // Build up relation node <-> child
697        for &child in children {
698            // Remove child from previous parent
699            if let Some(previous_parent) = self.parents[child.into()] {
700                self.remove_child(previous_parent, child).unwrap();
701            }
702            self.parents[child.into()] = Some(parent);
703        }
704
705        let parent_children = &mut self.children[parent_key];
706        parent_children.clear();
707        children.iter().for_each(|child| parent_children.push(*child));
708
709        self.mark_dirty(parent)?;
710
711        Ok(())
712    }
713
714    /// Removes the `child` of the parent `node`
715    ///
716    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
717    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
718        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
719        self.remove_child_at_index(parent, index)
720    }
721
722    /// Removes the child at the given `index` from the `parent`
723    ///
724    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
725    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
726        let parent_key = parent.into();
727        let child_count = self.children[parent_key].len();
728        if child_index >= child_count {
729            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
730        }
731
732        let child = self.children[parent_key].remove(child_index);
733        self.parents[child.into()] = None;
734
735        self.mark_dirty(parent)?;
736
737        Ok(child)
738    }
739
740    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
741    ///
742    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
743    pub fn replace_child_at_index(
744        &mut self,
745        parent: NodeId,
746        child_index: usize,
747        new_child: NodeId,
748    ) -> TaffyResult<NodeId> {
749        let parent_key = parent.into();
750
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        self.parents[new_child.into()] = Some(parent);
757        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
758        self.parents[old_child.into()] = None;
759
760        self.mark_dirty(parent)?;
761
762        Ok(old_child)
763    }
764
765    /// Returns the child node of the parent `node` at the provided `child_index`
766    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
767        let parent_key = parent.into();
768        let child_count = self.children[parent_key].len();
769        if child_index >= child_count {
770            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
771        }
772
773        Ok(self.children[parent_key][child_index])
774    }
775
776    /// Returns the total number of nodes in the tree
777    pub fn total_node_count(&self) -> usize {
778        self.nodes.len()
779    }
780
781    /// Returns the `NodeId` of the parent node of the specified node (if it exists)
782    ///
783    /// - Return None if the specified node has no parent
784    /// - Panics if the specified node does not exist
785    pub fn parent(&self, child_id: NodeId) -> Option<NodeId> {
786        self.parents[child_id.into()]
787    }
788
789    /// Returns a list of children that belong to the parent node
790    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
791        Ok(self.children[parent.into()].iter().copied().collect::<_>())
792    }
793
794    /// Sets the [`Style`] of the provided `node`
795    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
796        self.nodes[node.into()].style = style;
797        self.mark_dirty(node)?;
798        Ok(())
799    }
800
801    /// Gets the [`Style`] of the provided `node`
802    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
803        Ok(&self.nodes[node.into()].style)
804    }
805
806    /// Return this node layout relative to its parent
807    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
808        if self.config.use_rounding {
809            Ok(&self.nodes[node.into()].final_layout)
810        } else {
811            Ok(&self.nodes[node.into()].unrounded_layout)
812        }
813    }
814
815    /// Returns this node layout with unrounded values relative to its parent.
816    pub fn unrounded_layout(&self, node: NodeId) -> &Layout {
817        &self.nodes[node.into()].unrounded_layout
818    }
819
820    /// Marks the layout of this node and its ancestors as outdated
821    ///
822    /// WARNING: this may stack-overflow if the tree contains a cycle
823    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
824        /// WARNING: this will stack-overflow if the tree contains a cycle
825        fn mark_dirty_recursive(
826            nodes: &mut SlotMap<DefaultKey, NodeData>,
827            parents: &SlotMap<DefaultKey, Option<NodeId>>,
828            node_key: DefaultKey,
829        ) {
830            nodes[node_key].mark_dirty();
831
832            if let Some(Some(node)) = parents.get(node_key) {
833                mark_dirty_recursive(nodes, parents, (*node).into());
834            }
835        }
836
837        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
838
839        Ok(())
840    }
841
842    /// Indicates whether the layout of this node needs to be recomputed
843    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
844        Ok(self.nodes[node.into()].cache.is_empty())
845    }
846
847    /// Updates the stored layout of the provided `node` and its children
848    pub fn compute_layout_with_measure<MeasureFunction>(
849        &mut self,
850        node_id: NodeId,
851        available_space: Size<AvailableSpace>,
852        measure_function: MeasureFunction,
853    ) -> Result<(), TaffyError>
854    where
855        MeasureFunction:
856            FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
857    {
858        let use_rounding = self.config.use_rounding;
859        let mut taffy_view = TaffyView { taffy: self, measure_function };
860        compute_root_layout(&mut taffy_view, node_id, available_space);
861        if use_rounding {
862            round_layout(&mut taffy_view, node_id);
863        }
864        Ok(())
865    }
866
867    /// Updates the stored layout of the provided `node` and its children
868    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
869        self.compute_layout_with_measure(node, available_space, |_, _, _, _, _| Size::ZERO)
870    }
871
872    /// Prints a debug representation of the tree's layout
873    #[cfg(feature = "std")]
874    pub fn print_tree(&mut self, root: NodeId) {
875        crate::util::print_tree(self, root)
876    }
877
878    /// Returns an instance of LayoutTree representing the TaffyTree
879    #[cfg(test)]
880    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + CacheTree + '_ {
881        TaffyView { taffy: self, measure_function: |_, _, _, _, _| Size::ZERO }
882    }
883}
884
885#[cfg(test)]
886mod tests {
887
888    use super::*;
889    use crate::style::{Dimension, Display, FlexDirection};
890    use crate::style_helpers::*;
891    use crate::util::sys;
892
893    fn size_measure_function(
894        known_dimensions: Size<Option<f32>>,
895        _available_space: Size<AvailableSpace>,
896        _node_id: NodeId,
897        node_context: Option<&mut Size<f32>>,
898        _style: &Style,
899    ) -> Size<f32> {
900        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
901    }
902
903    #[test]
904    fn new_should_allocate_default_capacity() {
905        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
906        let taffy: TaffyTree<()> = TaffyTree::new();
907
908        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
909        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
910        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
911    }
912
913    #[test]
914    fn test_with_capacity() {
915        const CAPACITY: usize = 8;
916        let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
917
918        assert!(taffy.children.capacity() >= CAPACITY);
919        assert!(taffy.parents.capacity() >= CAPACITY);
920        assert!(taffy.nodes.capacity() >= CAPACITY);
921    }
922
923    #[test]
924    fn test_new_leaf() {
925        let mut taffy: TaffyTree<()> = TaffyTree::new();
926
927        let res = taffy.new_leaf(Style::default());
928        assert!(res.is_ok());
929        let node = res.unwrap();
930
931        // node should be in the taffy tree and have no children
932        assert!(taffy.child_count(node) == 0);
933    }
934
935    #[test]
936    fn new_leaf_with_context() {
937        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
938
939        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
940        assert!(res.is_ok());
941        let node = res.unwrap();
942
943        // node should be in the taffy tree and have no children
944        assert!(taffy.child_count(node) == 0);
945    }
946
947    /// Test that new_with_children works as expected
948    #[test]
949    fn test_new_with_children() {
950        let mut taffy: TaffyTree<()> = TaffyTree::new();
951        let child0 = taffy.new_leaf(Style::default()).unwrap();
952        let child1 = taffy.new_leaf(Style::default()).unwrap();
953        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
954
955        // node should have two children
956        assert_eq!(taffy.child_count(node), 2);
957        assert_eq!(taffy.children(node).unwrap()[0], child0);
958        assert_eq!(taffy.children(node).unwrap()[1], child1);
959    }
960
961    #[test]
962    fn remove_node_should_remove() {
963        let mut taffy: TaffyTree<()> = TaffyTree::new();
964
965        let node = taffy.new_leaf(Style::default()).unwrap();
966
967        let _ = taffy.remove(node).unwrap();
968    }
969
970    #[test]
971    fn remove_node_should_detach_hierarchy() {
972        let mut taffy: TaffyTree<()> = TaffyTree::new();
973
974        // Build a linear tree layout: <0> <- <1> <- <2>
975        let node2 = taffy.new_leaf(Style::default()).unwrap();
976        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
977        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
978
979        // Both node0 and node1 should have 1 child nodes
980        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
981        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
982
983        // Disconnect the tree: <0> <2>
984        let _ = taffy.remove(node1).unwrap();
985
986        // Both remaining nodes should have no child nodes
987        assert!(taffy.children(node0).unwrap().is_empty());
988        assert!(taffy.children(node2).unwrap().is_empty());
989    }
990
991    #[test]
992    fn remove_last_node() {
993        let mut taffy: TaffyTree<()> = TaffyTree::new();
994
995        let parent = taffy.new_leaf(Style::default()).unwrap();
996        let child = taffy.new_leaf(Style::default()).unwrap();
997        taffy.add_child(parent, child).unwrap();
998
999        taffy.remove(child).unwrap();
1000        taffy.remove(parent).unwrap();
1001    }
1002
1003    #[test]
1004    fn set_measure() {
1005        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
1006        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
1007        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1008        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
1009
1010        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
1011        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1012        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
1013    }
1014
1015    #[test]
1016    fn set_measure_of_previously_unmeasured_node() {
1017        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
1018        let node = taffy.new_leaf(Style::default()).unwrap();
1019        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1020        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
1021
1022        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
1023        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1024        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
1025    }
1026
1027    /// Test that adding `add_child()` works
1028    #[test]
1029    fn add_child() {
1030        let mut taffy: TaffyTree<()> = TaffyTree::new();
1031        let node = taffy.new_leaf(Style::default()).unwrap();
1032        assert_eq!(taffy.child_count(node), 0);
1033
1034        let child0 = taffy.new_leaf(Style::default()).unwrap();
1035        taffy.add_child(node, child0).unwrap();
1036        assert_eq!(taffy.child_count(node), 1);
1037
1038        let child1 = taffy.new_leaf(Style::default()).unwrap();
1039        taffy.add_child(node, child1).unwrap();
1040        assert_eq!(taffy.child_count(node), 2);
1041    }
1042
1043    #[test]
1044    fn insert_child_at_index() {
1045        let mut taffy: TaffyTree<()> = TaffyTree::new();
1046
1047        let child0 = taffy.new_leaf(Style::default()).unwrap();
1048        let child1 = taffy.new_leaf(Style::default()).unwrap();
1049        let child2 = taffy.new_leaf(Style::default()).unwrap();
1050
1051        let node = taffy.new_leaf(Style::default()).unwrap();
1052        assert_eq!(taffy.child_count(node), 0);
1053
1054        taffy.insert_child_at_index(node, 0, child0).unwrap();
1055        assert_eq!(taffy.child_count(node), 1);
1056        assert_eq!(taffy.children(node).unwrap()[0], child0);
1057
1058        taffy.insert_child_at_index(node, 0, child1).unwrap();
1059        assert_eq!(taffy.child_count(node), 2);
1060        assert_eq!(taffy.children(node).unwrap()[0], child1);
1061        assert_eq!(taffy.children(node).unwrap()[1], child0);
1062
1063        taffy.insert_child_at_index(node, 1, child2).unwrap();
1064        assert_eq!(taffy.child_count(node), 3);
1065        assert_eq!(taffy.children(node).unwrap()[0], child1);
1066        assert_eq!(taffy.children(node).unwrap()[1], child2);
1067        assert_eq!(taffy.children(node).unwrap()[2], child0);
1068    }
1069
1070    #[test]
1071    fn set_children() {
1072        let mut taffy: TaffyTree<()> = TaffyTree::new();
1073
1074        let child0 = taffy.new_leaf(Style::default()).unwrap();
1075        let child1 = taffy.new_leaf(Style::default()).unwrap();
1076        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1077
1078        assert_eq!(taffy.child_count(node), 2);
1079        assert_eq!(taffy.children(node).unwrap()[0], child0);
1080        assert_eq!(taffy.children(node).unwrap()[1], child1);
1081
1082        let child2 = taffy.new_leaf(Style::default()).unwrap();
1083        let child3 = taffy.new_leaf(Style::default()).unwrap();
1084        taffy.set_children(node, &[child2, child3]).unwrap();
1085
1086        assert_eq!(taffy.child_count(node), 2);
1087        assert_eq!(taffy.children(node).unwrap()[0], child2);
1088        assert_eq!(taffy.children(node).unwrap()[1], child3);
1089    }
1090
1091    /// Test that removing a child works
1092    #[test]
1093    fn remove_child() {
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(node, child0).unwrap();
1102        assert_eq!(taffy.child_count(node), 1);
1103        assert_eq!(taffy.children(node).unwrap()[0], child1);
1104
1105        taffy.remove_child(node, child1).unwrap();
1106        assert_eq!(taffy.child_count(node), 0);
1107    }
1108
1109    #[test]
1110    fn remove_child_at_index() {
1111        let mut taffy: TaffyTree<()> = TaffyTree::new();
1112        let child0 = taffy.new_leaf(Style::default()).unwrap();
1113        let child1 = taffy.new_leaf(Style::default()).unwrap();
1114        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1115
1116        assert_eq!(taffy.child_count(node), 2);
1117
1118        taffy.remove_child_at_index(node, 0).unwrap();
1119        assert_eq!(taffy.child_count(node), 1);
1120        assert_eq!(taffy.children(node).unwrap()[0], child1);
1121
1122        taffy.remove_child_at_index(node, 0).unwrap();
1123        assert_eq!(taffy.child_count(node), 0);
1124    }
1125
1126    // Related to: https://github.com/DioxusLabs/taffy/issues/510
1127    #[test]
1128    fn remove_child_updates_parents() {
1129        let mut taffy: TaffyTree<()> = TaffyTree::new();
1130
1131        let parent = taffy.new_leaf(Style::default()).unwrap();
1132        let child = taffy.new_leaf(Style::default()).unwrap();
1133
1134        taffy.add_child(parent, child).unwrap();
1135
1136        taffy.remove(parent).unwrap();
1137
1138        // Once the parent is removed this shouldn't panic.
1139        assert!(taffy.set_children(child, &[]).is_ok());
1140    }
1141
1142    #[test]
1143    fn replace_child_at_index() {
1144        let mut taffy: TaffyTree<()> = TaffyTree::new();
1145
1146        let child0 = taffy.new_leaf(Style::default()).unwrap();
1147        let child1 = taffy.new_leaf(Style::default()).unwrap();
1148
1149        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
1150        assert_eq!(taffy.child_count(node), 1);
1151        assert_eq!(taffy.children(node).unwrap()[0], child0);
1152
1153        taffy.replace_child_at_index(node, 0, child1).unwrap();
1154        assert_eq!(taffy.child_count(node), 1);
1155        assert_eq!(taffy.children(node).unwrap()[0], child1);
1156    }
1157    #[test]
1158    fn test_child_at_index() {
1159        let mut taffy: TaffyTree<()> = TaffyTree::new();
1160        let child0 = taffy.new_leaf(Style::default()).unwrap();
1161        let child1 = taffy.new_leaf(Style::default()).unwrap();
1162        let child2 = taffy.new_leaf(Style::default()).unwrap();
1163        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
1164
1165        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
1166        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
1167        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
1168    }
1169    #[test]
1170    fn test_child_count() {
1171        let mut taffy: TaffyTree<()> = TaffyTree::new();
1172        let child0 = taffy.new_leaf(Style::default()).unwrap();
1173        let child1 = taffy.new_leaf(Style::default()).unwrap();
1174        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1175
1176        assert!(taffy.child_count(node) == 2);
1177        assert!(taffy.child_count(child0) == 0);
1178        assert!(taffy.child_count(child1) == 0);
1179    }
1180
1181    #[allow(clippy::vec_init_then_push)]
1182    #[test]
1183    fn test_children() {
1184        let mut taffy: TaffyTree<()> = TaffyTree::new();
1185        let child0 = taffy.new_leaf(Style::default()).unwrap();
1186        let child1 = taffy.new_leaf(Style::default()).unwrap();
1187        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1188
1189        let mut children = sys::Vec::new();
1190        children.push(child0);
1191        children.push(child1);
1192
1193        let children_result = taffy.children(node).unwrap();
1194        assert_eq!(children_result, children);
1195
1196        assert!(taffy.children(child0).unwrap().is_empty());
1197    }
1198    #[test]
1199    fn test_set_style() {
1200        let mut taffy: TaffyTree<()> = TaffyTree::new();
1201
1202        let node = taffy.new_leaf(Style::default()).unwrap();
1203        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1204
1205        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1206        assert_eq!(taffy.style(node).unwrap().display, Display::None);
1207    }
1208    #[test]
1209    fn test_style() {
1210        let mut taffy: TaffyTree<()> = TaffyTree::new();
1211
1212        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1213
1214        let node = taffy.new_leaf(style.clone()).unwrap();
1215
1216        let res = taffy.style(node);
1217        assert!(res.is_ok());
1218        assert!(res.unwrap() == &style);
1219    }
1220    #[test]
1221    fn test_layout() {
1222        let mut taffy: TaffyTree<()> = TaffyTree::new();
1223        let node = taffy.new_leaf(Style::default()).unwrap();
1224
1225        // TODO: Improve this test?
1226        let res = taffy.layout(node);
1227        assert!(res.is_ok());
1228    }
1229
1230    #[test]
1231    fn test_mark_dirty() {
1232        let mut taffy: TaffyTree<()> = TaffyTree::new();
1233        let child0 = taffy.new_leaf(Style::default()).unwrap();
1234        let child1 = taffy.new_leaf(Style::default()).unwrap();
1235        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1236
1237        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1238
1239        assert_eq!(taffy.dirty(child0), Ok(false));
1240        assert_eq!(taffy.dirty(child1), Ok(false));
1241        assert_eq!(taffy.dirty(node), Ok(false));
1242
1243        taffy.mark_dirty(node).unwrap();
1244        assert_eq!(taffy.dirty(child0), Ok(false));
1245        assert_eq!(taffy.dirty(child1), Ok(false));
1246        assert_eq!(taffy.dirty(node), Ok(true));
1247
1248        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1249        taffy.mark_dirty(child0).unwrap();
1250        assert_eq!(taffy.dirty(child0), Ok(true));
1251        assert_eq!(taffy.dirty(child1), Ok(false));
1252        assert_eq!(taffy.dirty(node), Ok(true));
1253    }
1254
1255    #[test]
1256    fn compute_layout_should_produce_valid_result() {
1257        let mut taffy: TaffyTree<()> = TaffyTree::new();
1258        let node_result = taffy.new_leaf(Style {
1259            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1260            ..Default::default()
1261        });
1262        assert!(node_result.is_ok());
1263        let node = node_result.unwrap();
1264        let layout_result = taffy.compute_layout(
1265            node,
1266            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1267        );
1268        assert!(layout_result.is_ok());
1269    }
1270
1271    #[test]
1272    fn make_sure_layout_location_is_top_left() {
1273        use crate::prelude::Rect;
1274
1275        let mut taffy: TaffyTree<()> = TaffyTree::new();
1276
1277        let node = taffy
1278            .new_leaf(Style {
1279                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1280                ..Default::default()
1281            })
1282            .unwrap();
1283
1284        let root = taffy
1285            .new_with_children(
1286                Style {
1287                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1288                    padding: Rect {
1289                        left: length(10f32),
1290                        right: length(20f32),
1291                        top: length(30f32),
1292                        bottom: length(40f32),
1293                    },
1294                    ..Default::default()
1295                },
1296                &[node],
1297            )
1298            .unwrap();
1299
1300        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1301
1302        // If Layout::location represents top-left coord, 'node' location
1303        // must be (due applied 'root' padding): {x: 10, y: 30}.
1304        //
1305        // It's important, since result will be different for each other
1306        // coordinate space:
1307        // - bottom-left:  {x: 10, y: 40}
1308        // - top-right:    {x: 20, y: 30}
1309        // - bottom-right: {x: 20, y: 40}
1310        let layout = taffy.layout(node).unwrap();
1311        assert_eq!(layout.location.x, 10f32);
1312        assert_eq!(layout.location.y, 30f32);
1313    }
1314
1315    #[test]
1316    fn set_children_reparents() {
1317        let mut taffy: TaffyTree<()> = TaffyTree::new();
1318        let child = taffy.new_leaf(Style::default()).unwrap();
1319        let old_parent = taffy.new_with_children(Style::default(), &[child]).unwrap();
1320
1321        let new_parent = taffy.new_leaf(Style::default()).unwrap();
1322        taffy.set_children(new_parent, &[child]).unwrap();
1323
1324        assert!(taffy.children(old_parent).unwrap().is_empty());
1325    }
1326}