tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 231Rust 9TOML 3CSS 1345 Sutichaykuna

⎇ b63c2ae07043a077af961ec863b5a89b16b704d5 src/tree/taffy_tree.rs Rust · 1001 siq'ikuna · 37.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

Add `TaffyTree.get_node_context` function (get immutable ref to context) b63c2ae07 · Nico Burns ·

1//! Contains [TaffyTree](crate::tree::TaffyTree): the default implementation of [LayoutTree](crate::tree::LayoutTree), and the error type for Taffy.
2use slotmap::{DefaultKey, SlotMap, SparseSecondaryMap};
3
4use crate::geometry::Size;
5use crate::style::{AvailableSpace, Display, Style};
6use crate::tree::{Cache, Layout, LayoutInput, LayoutOutput, LayoutTree, NodeData, NodeId, PartialLayoutTree, RunMode};
7use crate::util::debug::{debug_log, debug_log_node};
8use crate::util::sys::{new_vec_with_capacity, ChildrenVec, Vec};
9
10#[cfg(feature = "block_layout")]
11use crate::compute::compute_block_layout;
12#[cfg(feature = "flexbox")]
13use crate::compute::compute_flexbox_layout;
14#[cfg(feature = "grid")]
15use crate::compute::compute_grid_layout;
16use crate::compute::{compute_cached_layout, compute_hidden_layout, compute_layout, compute_leaf_layout, round_layout};
17
18/// The error Taffy generates on invalid operations
19pub type TaffyResult<T> = Result<T, TaffyError>;
20
21/// An error that occurs while trying to access or modify a node's children by index.
22#[derive(Debug)]
23pub enum TaffyError {
24    /// The parent node does not have a child at `child_index`. It only has `child_count` children
25    ChildIndexOutOfBounds {
26        /// The parent node whose child was being looked up
27        parent: NodeId,
28        /// The index that was looked up
29        child_index: usize,
30        /// The total number of children the parent has
31        child_count: usize,
32    },
33    /// The parent node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
34    InvalidParentNode(NodeId),
35    /// The child node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
36    InvalidChildNode(NodeId),
37    /// The supplied node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
38    InvalidInputNode(NodeId),
39}
40
41impl core::fmt::Display for TaffyError {
42    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
43        match self {
44            TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count } => {
45                write!(f, "Index (is {child_index}) should be < child_count ({child_count}) for parent node {parent:?}")
46            }
47            TaffyError::InvalidParentNode(parent) => {
48                write!(f, "Parent Node {parent:?} is not in the TaffyTree instance")
49            }
50            TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the TaffyTree instance"),
51            TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the TaffyTree instance"),
52        }
53    }
54}
55
56#[cfg(feature = "std")]
57impl std::error::Error for TaffyError {}
58
59/// Global configuration values for a TaffyTree instance
60pub(crate) struct TaffyConfig {
61    /// Whether to round layout values
62    pub(crate) use_rounding: bool,
63}
64
65impl Default for TaffyConfig {
66    fn default() -> Self {
67        Self { use_rounding: true }
68    }
69}
70
71/// An entire tree of UI nodes. The entry point to Taffy's high-level API.
72///
73/// Allows you to build a tree of UI nodes, run Taffy's layout algorithms over that tree, and then access the resultant layout.
74pub struct TaffyTree<NodeContext = ()> {
75    /// The [`NodeData`] for each node stored in this tree
76    pub(crate) nodes: SlotMap<DefaultKey, NodeData>,
77
78    /// Functions/closures that compute the intrinsic size of leaf nodes
79    pub(crate) node_context_data: SparseSecondaryMap<DefaultKey, NodeContext>,
80
81    /// The children of each node
82    ///
83    /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
84    pub(crate) children: SlotMap<DefaultKey, ChildrenVec<NodeId>>,
85
86    /// The parents of each node
87    ///
88    /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
89    pub(crate) parents: SlotMap<DefaultKey, Option<NodeId>>,
90
91    /// Layout mode configuration
92    pub(crate) config: TaffyConfig,
93}
94
95impl Default for TaffyTree {
96    fn default() -> TaffyTree<()> {
97        TaffyTree::new()
98    }
99}
100
101/// Iterator that wraps a slice of nodes, lazily converting them to u64
102pub(crate) struct TaffyChildIter<'a>(core::slice::Iter<'a, NodeId>);
103impl<'a> Iterator for TaffyChildIter<'a> {
104    type Item = NodeId;
105
106    fn next(&mut self) -> Option<Self::Item> {
107        self.0.next().copied()
108    }
109}
110
111/// View over the Taffy tree that holds the tree itself along with a reference to the context
112/// and implements LayoutTree. This allows the context to be stored outside of the TaffyTree struct
113/// which makes the lifetimes of the context much more flexible.
114pub(crate) struct TaffyView<'t, NodeContext, MeasureFunction>
115where
116    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
117{
118    /// A reference to the TaffyTree
119    pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
120    /// The context provided for passing to measure functions if layout is run over this struct
121    pub(crate) measure_function: MeasureFunction,
122}
123
124impl<'t, NodeContext, MeasureFunction> PartialLayoutTree for TaffyView<'t, NodeContext, MeasureFunction>
125where
126    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
127{
128    type ChildIter<'a> = TaffyChildIter<'a> where Self: 'a;
129
130    #[inline(always)]
131    fn child_ids(&self, node: NodeId) -> Self::ChildIter<'_> {
132        TaffyChildIter(self.taffy.children[node.into()].iter())
133    }
134
135    #[inline(always)]
136    fn child_count(&self, node: NodeId) -> usize {
137        self.taffy.children[node.into()].len()
138    }
139
140    #[inline(always)]
141    fn get_child_id(&self, node: NodeId, id: usize) -> NodeId {
142        self.taffy.children[node.into()][id]
143    }
144
145    #[inline(always)]
146    fn get_style(&self, node: NodeId) -> &Style {
147        &self.taffy.nodes[node.into()].style
148    }
149
150    #[inline(always)]
151    fn get_cache_mut(&mut self, node: NodeId) -> &mut Cache {
152        &mut self.taffy.nodes[node.into()].cache
153    }
154
155    #[inline(always)]
156    fn get_unrounded_layout_mut(&mut self, node: NodeId) -> &mut Layout {
157        &mut self.taffy.nodes[node.into()].unrounded_layout
158    }
159
160    #[inline(always)]
161    fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
162        // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
163        // and thus that we should lay out this node using hidden layout regardless of it's own display style.
164        if inputs.run_mode == RunMode::PerformHiddenLayout {
165            debug_log!("HIDDEN");
166            return compute_hidden_layout(self, node);
167        }
168
169        // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
170        //   - Return that entry if exists
171        //   - Else call the passed closure (below) to compute the result
172        //
173        // If there was no cache match and a new result needs to be computed then that result will be added to the cache
174        compute_cached_layout(self, node, inputs, |tree, node, inputs| {
175            let display_mode = tree.get_style(node).display;
176            let has_children = tree.child_count(node) > 0;
177
178            debug_log!(display_mode);
179            debug_log_node!(
180                inputs.known_dimensions,
181                inputs.parent_size,
182                inputs.available_space,
183                inputs.run_mode,
184                inputs.sizing_mode
185            );
186
187            // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
188            match (display_mode, has_children) {
189                (Display::None, _) => compute_hidden_layout(tree, node),
190                #[cfg(feature = "block_layout")]
191                (Display::Block, true) => compute_block_layout(tree, node, inputs),
192                #[cfg(feature = "flexbox")]
193                (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
194                #[cfg(feature = "grid")]
195                (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
196                (_, false) => {
197                    let node_key = node.into();
198                    let style = &tree.taffy.nodes[node_key].style;
199                    let needs_measure = tree.taffy.nodes[node_key].needs_measure;
200                    let measure_function = needs_measure.then_some(|known_dimensions, available_space| {
201                        let node_context = tree.taffy.node_context_data.get_mut(node_key);
202                        (tree.measure_function)(known_dimensions, available_space, node, node_context)
203                    });
204                    compute_leaf_layout(inputs, style, measure_function)
205                }
206            }
207        })
208    }
209}
210
211impl<'t, NodeContext, MeasureFunction> LayoutTree for TaffyView<'t, NodeContext, MeasureFunction>
212where
213    MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
214{
215    #[inline(always)]
216    fn get_final_layout(&self, node: NodeId) -> &Layout {
217        &self.taffy.nodes[node.into()].final_layout
218    }
219
220    #[inline(always)]
221    fn get_final_layout_mut(&mut self, node: NodeId) -> &mut Layout {
222        &mut self.taffy.nodes[node.into()].final_layout
223    }
224}
225
226#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
227impl<NodeContext> TaffyTree<NodeContext> {
228    /// Creates a new [`TaffyTree`]
229    ///
230    /// The default capacity of a [`TaffyTree`] is 16 nodes.
231    #[must_use]
232    pub fn new() -> Self {
233        Self::with_capacity(16)
234    }
235
236    /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
237    #[must_use]
238    pub fn with_capacity(capacity: usize) -> Self {
239        TaffyTree {
240            // TODO: make this method const upstream,
241            // so constructors here can be const
242            nodes: SlotMap::with_capacity(capacity),
243            children: SlotMap::with_capacity(capacity),
244            parents: SlotMap::with_capacity(capacity),
245            node_context_data: SparseSecondaryMap::with_capacity(capacity),
246            config: TaffyConfig::default(),
247        }
248    }
249
250    /// Enable rounding of layout values. Rounding is enabled by default.
251    pub fn enable_rounding(&mut self) {
252        self.config.use_rounding = true;
253    }
254
255    /// Disable rounding of layout values. Rounding is enabled by default.
256    pub fn disable_rounding(&mut self) {
257        self.config.use_rounding = false;
258    }
259
260    /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
261    pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
262        let id = self.nodes.insert(NodeData::new(layout));
263        let _ = self.children.insert(new_vec_with_capacity(0));
264        let _ = self.parents.insert(None);
265
266        Ok(id.into())
267    }
268
269    /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
270    ///
271    /// Creates and adds a new leaf node with a supplied context
272    pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
273        let mut data = NodeData::new(layout);
274        data.needs_measure = true;
275
276        let id = self.nodes.insert(data);
277        self.node_context_data.insert(id, context);
278
279        let _ = self.children.insert(new_vec_with_capacity(0));
280        let _ = self.parents.insert(None);
281
282        Ok(id.into())
283    }
284
285    /// Creates and adds a new node, which may have any number of `children`
286    pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
287        let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
288
289        for child in children {
290            self.parents[(*child).into()] = Some(id);
291        }
292
293        let _ = self.children.insert(children.iter().copied().collect::<_>());
294        let _ = self.parents.insert(None);
295
296        Ok(id)
297    }
298
299    /// Drops all nodes in the tree
300    pub fn clear(&mut self) {
301        self.nodes.clear();
302        self.children.clear();
303        self.parents.clear();
304    }
305
306    /// Remove a specific node from the tree and drop it
307    ///
308    /// Returns the id of the node removed.
309    pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
310        let key = node.into();
311        if let Some(parent) = self.parents[key] {
312            if let Some(children) = self.children.get_mut(parent.into()) {
313                children.retain(|f| *f != node);
314            }
315        }
316
317        // Remove "parent" references to a node when removing that node
318        if let Some(children) = self.children.get(key) {
319            for child in children.iter().copied() {
320                self.parents[child.into()] = None;
321            }
322        }
323
324        let _ = self.children.remove(key);
325        let _ = self.parents.remove(key);
326        let _ = self.nodes.remove(key);
327
328        Ok(node)
329    }
330
331    /// Sets the context data associated with the node
332    pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
333        let key = node.into();
334        if let Some(measure) = measure {
335            self.nodes[key].needs_measure = true;
336            self.node_context_data.insert(key, measure);
337        } else {
338            self.nodes[key].needs_measure = false;
339            self.node_context_data.remove(key);
340        }
341
342        self.mark_dirty(node)?;
343
344        Ok(())
345    }
346
347    /// Gets a reference to the the context data associated with the node
348    pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
349        self.node_context_data.get(node.into())
350    }
351
352    /// Gets a mutable reference to the the context data associated with the node
353    pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
354        self.node_context_data.get_mut(node.into())
355    }
356
357    /// Adds a `child` node under the supplied `parent`
358    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
359        let parent_key = parent.into();
360        let child_key = child.into();
361        self.parents[child_key] = Some(parent);
362        self.children[parent_key].push(child);
363        self.mark_dirty(parent)?;
364
365        Ok(())
366    }
367
368    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
369    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
370        let parent_key = parent.into();
371
372        let child_count = self.children[parent_key].len();
373        if child_index > child_count {
374            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
375        }
376
377        self.parents[child.into()] = Some(parent);
378        self.children[parent_key].insert(child_index, child);
379        self.mark_dirty(parent)?;
380
381        Ok(())
382    }
383
384    /// Directly sets the `children` of the supplied `parent`
385    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
386        let parent_key = parent.into();
387
388        // Remove node as parent from all its current children.
389        for child in &self.children[parent_key] {
390            self.parents[(*child).into()] = None;
391        }
392
393        // Build up relation node <-> child
394        for child in children {
395            self.parents[(*child).into()] = Some(parent);
396        }
397
398        let parent_children = &mut self.children[parent_key];
399        parent_children.clear();
400        children.iter().for_each(|child| parent_children.push(*child));
401
402        self.mark_dirty(parent)?;
403
404        Ok(())
405    }
406
407    /// Removes the `child` of the parent `node`
408    ///
409    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
410    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
411        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
412        self.remove_child_at_index(parent, index)
413    }
414
415    /// Removes the child at the given `index` from the `parent`
416    ///
417    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
418    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
419        let parent_key = parent.into();
420        let child_count = self.children[parent_key].len();
421        if child_index >= child_count {
422            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
423        }
424
425        let child = self.children[parent_key].remove(child_index);
426        self.parents[child.into()] = None;
427
428        self.mark_dirty(parent)?;
429
430        Ok(child)
431    }
432
433    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
434    ///
435    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
436    pub fn replace_child_at_index(
437        &mut self,
438        parent: NodeId,
439        child_index: usize,
440        new_child: NodeId,
441    ) -> TaffyResult<NodeId> {
442        let parent_key = parent.into();
443
444        let child_count = self.children[parent_key].len();
445        if child_index >= child_count {
446            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
447        }
448
449        self.parents[new_child.into()] = Some(parent);
450        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
451        self.parents[old_child.into()] = None;
452
453        self.mark_dirty(parent)?;
454
455        Ok(old_child)
456    }
457
458    /// Returns the child node of the parent `node` at the provided `child_index`
459    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
460        let parent_key = parent.into();
461        let child_count = self.children[parent_key].len();
462        if child_index >= child_count {
463            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
464        }
465
466        Ok(self.children[parent_key][child_index])
467    }
468
469    /// Returns the total number of nodes in the tree
470    pub fn total_node_count(&self) -> usize {
471        self.nodes.len()
472    }
473
474    /// Returns the number of children of the `parent` node
475    pub fn child_count(&self, parent: NodeId) -> TaffyResult<usize> {
476        Ok(self.children[parent.into()].len())
477    }
478
479    /// Returns a list of children that belong to the parent node
480    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
481        Ok(self.children[parent.into()].iter().copied().collect::<_>())
482    }
483
484    /// Sets the [`Style`] of the provided `node`
485    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
486        self.nodes[node.into()].style = style;
487        self.mark_dirty(node)?;
488        Ok(())
489    }
490
491    /// Gets the [`Style`] of the provided `node`
492    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
493        Ok(&self.nodes[node.into()].style)
494    }
495
496    /// Return this node layout relative to its parent
497    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
498        if self.config.use_rounding {
499            Ok(&self.nodes[node.into()].final_layout)
500        } else {
501            Ok(&self.nodes[node.into()].unrounded_layout)
502        }
503    }
504
505    /// Marks the layout computation of this node and its children as outdated
506    ///
507    /// Performs a recursive depth-first search up the tree until the root node is reached
508    ///
509    /// WARNING: this will stack-overflow if the tree contains a cycle
510    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
511        /// WARNING: this will stack-overflow if the tree contains a cycle
512        fn mark_dirty_recursive(
513            nodes: &mut SlotMap<DefaultKey, NodeData>,
514            parents: &SlotMap<DefaultKey, Option<NodeId>>,
515            node_key: DefaultKey,
516        ) {
517            nodes[node_key].mark_dirty();
518
519            if let Some(Some(node)) = parents.get(node_key) {
520                mark_dirty_recursive(nodes, parents, (*node).into());
521            }
522        }
523
524        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
525
526        Ok(())
527    }
528
529    /// Indicates whether the layout of this node (and its children) need to be recomputed
530    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
531        Ok(self.nodes[node.into()].cache.is_empty())
532    }
533
534    /// Updates the stored layout of the provided `node` and its children
535    pub fn compute_layout_with_measure<MeasureFunction>(
536        &mut self,
537        node_id: NodeId,
538        available_space: Size<AvailableSpace>,
539        measure_function: MeasureFunction,
540    ) -> Result<(), TaffyError>
541    where
542        MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
543    {
544        let use_rounding = self.config.use_rounding;
545        let mut taffy_view = TaffyView { taffy: self, measure_function };
546        compute_layout(&mut taffy_view, node_id, available_space);
547        if use_rounding {
548            round_layout(&mut taffy_view, node_id);
549        }
550        Ok(())
551    }
552
553    /// Updates the stored layout of the provided `node` and its children
554    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
555        self.compute_layout_with_measure(node, available_space, |_, _, _, _| Size::ZERO)
556    }
557
558    /// Prints a debug representation of the tree's layout
559    #[cfg(feature = "std")]
560    pub fn print_tree(&mut self, root: NodeId) {
561        let taffy_view = TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO };
562        crate::util::print_tree(&taffy_view, root)
563    }
564
565    /// Returns an instance of LayoutTree representing the TaffyTree
566    #[cfg(test)]
567    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutTree + '_ {
568        TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO }
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    #![allow(clippy::bool_assert_comparison)]
575
576    use super::*;
577    use crate::style::{Dimension, Display, FlexDirection};
578    use crate::style_helpers::*;
579    use crate::util::sys;
580
581    fn size_measure_function(
582        known_dimensions: Size<Option<f32>>,
583        _available_space: Size<AvailableSpace>,
584        _node_id: NodeId,
585        node_context: Option<&mut Size<f32>>,
586    ) -> Size<f32> {
587        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
588    }
589
590    #[test]
591    fn new_should_allocate_default_capacity() {
592        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
593        let taffy: TaffyTree<()> = TaffyTree::new();
594
595        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
596        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
597        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
598    }
599
600    #[test]
601    fn test_with_capacity() {
602        const CAPACITY: usize = 8;
603        let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
604
605        assert!(taffy.children.capacity() >= CAPACITY);
606        assert!(taffy.parents.capacity() >= CAPACITY);
607        assert!(taffy.nodes.capacity() >= CAPACITY);
608    }
609
610    #[test]
611    fn test_new_leaf() {
612        let mut taffy: TaffyTree<()> = TaffyTree::new();
613
614        let res = taffy.new_leaf(Style::default());
615        assert!(res.is_ok());
616        let node = res.unwrap();
617
618        // node should be in the taffy tree and have no children
619        assert!(taffy.child_count(node).unwrap() == 0);
620    }
621
622    #[test]
623    fn new_leaf_with_context() {
624        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
625
626        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
627        assert!(res.is_ok());
628        let node = res.unwrap();
629
630        // node should be in the taffy tree and have no children
631        assert!(taffy.child_count(node).unwrap() == 0);
632    }
633
634    /// Test that new_with_children works as expected
635    #[test]
636    fn test_new_with_children() {
637        let mut taffy: TaffyTree<()> = TaffyTree::new();
638        let child0 = taffy.new_leaf(Style::default()).unwrap();
639        let child1 = taffy.new_leaf(Style::default()).unwrap();
640        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
641
642        // node should have two children
643        assert_eq!(taffy.child_count(node).unwrap(), 2);
644        assert_eq!(taffy.children(node).unwrap()[0], child0);
645        assert_eq!(taffy.children(node).unwrap()[1], child1);
646    }
647
648    #[test]
649    fn remove_node_should_remove() {
650        let mut taffy: TaffyTree<()> = TaffyTree::new();
651
652        let node = taffy.new_leaf(Style::default()).unwrap();
653
654        let _ = taffy.remove(node).unwrap();
655    }
656
657    #[test]
658    fn remove_node_should_detach_herarchy() {
659        let mut taffy: TaffyTree<()> = TaffyTree::new();
660
661        // Build a linear tree layout: <0> <- <1> <- <2>
662        let node2 = taffy.new_leaf(Style::default()).unwrap();
663        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
664        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
665
666        // Both node0 and node1 should have 1 child nodes
667        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
668        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
669
670        // Disconnect the tree: <0> <2>
671        let _ = taffy.remove(node1).unwrap();
672
673        // Both remaining nodes should have no child nodes
674        assert!(taffy.children(node0).unwrap().is_empty());
675        assert!(taffy.children(node2).unwrap().is_empty());
676    }
677
678    #[test]
679    fn remove_last_node() {
680        let mut taffy: TaffyTree<()> = TaffyTree::new();
681
682        let parent = taffy.new_leaf(Style::default()).unwrap();
683        let child = taffy.new_leaf(Style::default()).unwrap();
684        taffy.add_child(parent, child).unwrap();
685
686        taffy.remove(child).unwrap();
687        taffy.remove(parent).unwrap();
688    }
689
690    #[test]
691    fn set_measure() {
692        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
693        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
694        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
695        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
696
697        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
698        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
699        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
700    }
701
702    #[test]
703    fn set_measure_of_previously_unmeasured_node() {
704        let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
705        let node = taffy.new_leaf(Style::default()).unwrap();
706        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
707        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
708
709        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
710        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
711        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
712    }
713
714    /// Test that adding `add_child()` works
715    #[test]
716    fn add_child() {
717        let mut taffy: TaffyTree<()> = TaffyTree::new();
718        let node = taffy.new_leaf(Style::default()).unwrap();
719        assert_eq!(taffy.child_count(node).unwrap(), 0);
720
721        let child0 = taffy.new_leaf(Style::default()).unwrap();
722        taffy.add_child(node, child0).unwrap();
723        assert_eq!(taffy.child_count(node).unwrap(), 1);
724
725        let child1 = taffy.new_leaf(Style::default()).unwrap();
726        taffy.add_child(node, child1).unwrap();
727        assert_eq!(taffy.child_count(node).unwrap(), 2);
728    }
729
730    #[test]
731    fn insert_child_at_index() {
732        let mut taffy: TaffyTree<()> = TaffyTree::new();
733
734        let child0 = taffy.new_leaf(Style::default()).unwrap();
735        let child1 = taffy.new_leaf(Style::default()).unwrap();
736        let child2 = taffy.new_leaf(Style::default()).unwrap();
737
738        let node = taffy.new_leaf(Style::default()).unwrap();
739        assert_eq!(taffy.child_count(node).unwrap(), 0);
740
741        taffy.insert_child_at_index(node, 0, child0).unwrap();
742        assert_eq!(taffy.child_count(node).unwrap(), 1);
743        assert_eq!(taffy.children(node).unwrap()[0], child0);
744
745        taffy.insert_child_at_index(node, 0, child1).unwrap();
746        assert_eq!(taffy.child_count(node).unwrap(), 2);
747        assert_eq!(taffy.children(node).unwrap()[0], child1);
748        assert_eq!(taffy.children(node).unwrap()[1], child0);
749
750        taffy.insert_child_at_index(node, 1, child2).unwrap();
751        assert_eq!(taffy.child_count(node).unwrap(), 3);
752        assert_eq!(taffy.children(node).unwrap()[0], child1);
753        assert_eq!(taffy.children(node).unwrap()[1], child2);
754        assert_eq!(taffy.children(node).unwrap()[2], child0);
755    }
756
757    #[test]
758    fn set_children() {
759        let mut taffy: TaffyTree<()> = TaffyTree::new();
760
761        let child0 = taffy.new_leaf(Style::default()).unwrap();
762        let child1 = taffy.new_leaf(Style::default()).unwrap();
763        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
764
765        assert_eq!(taffy.child_count(node).unwrap(), 2);
766        assert_eq!(taffy.children(node).unwrap()[0], child0);
767        assert_eq!(taffy.children(node).unwrap()[1], child1);
768
769        let child2 = taffy.new_leaf(Style::default()).unwrap();
770        let child3 = taffy.new_leaf(Style::default()).unwrap();
771        taffy.set_children(node, &[child2, child3]).unwrap();
772
773        assert_eq!(taffy.child_count(node).unwrap(), 2);
774        assert_eq!(taffy.children(node).unwrap()[0], child2);
775        assert_eq!(taffy.children(node).unwrap()[1], child3);
776    }
777
778    /// Test that removing a child works
779    #[test]
780    fn remove_child() {
781        let mut taffy: TaffyTree<()> = TaffyTree::new();
782        let child0 = taffy.new_leaf(Style::default()).unwrap();
783        let child1 = taffy.new_leaf(Style::default()).unwrap();
784        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
785
786        assert_eq!(taffy.child_count(node).unwrap(), 2);
787
788        taffy.remove_child(node, child0).unwrap();
789        assert_eq!(taffy.child_count(node).unwrap(), 1);
790        assert_eq!(taffy.children(node).unwrap()[0], child1);
791
792        taffy.remove_child(node, child1).unwrap();
793        assert_eq!(taffy.child_count(node).unwrap(), 0);
794    }
795
796    #[test]
797    fn remove_child_at_index() {
798        let mut taffy: TaffyTree<()> = TaffyTree::new();
799        let child0 = taffy.new_leaf(Style::default()).unwrap();
800        let child1 = taffy.new_leaf(Style::default()).unwrap();
801        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
802
803        assert_eq!(taffy.child_count(node).unwrap(), 2);
804
805        taffy.remove_child_at_index(node, 0).unwrap();
806        assert_eq!(taffy.child_count(node).unwrap(), 1);
807        assert_eq!(taffy.children(node).unwrap()[0], child1);
808
809        taffy.remove_child_at_index(node, 0).unwrap();
810        assert_eq!(taffy.child_count(node).unwrap(), 0);
811    }
812
813    // Related to: https://github.com/DioxusLabs/taffy/issues/510
814    #[test]
815    fn remove_child_updates_parents() {
816        let mut taffy: TaffyTree<()> = TaffyTree::new();
817
818        let parent = taffy.new_leaf(Style::default()).unwrap();
819        let child = taffy.new_leaf(Style::default()).unwrap();
820
821        taffy.add_child(parent, child).unwrap();
822
823        taffy.remove(parent).unwrap();
824
825        // Once the parent is removed this shouldn't panic.
826        assert!(taffy.set_children(child, &[]).is_ok());
827    }
828
829    #[test]
830    fn replace_child_at_index() {
831        let mut taffy: TaffyTree<()> = TaffyTree::new();
832
833        let child0 = taffy.new_leaf(Style::default()).unwrap();
834        let child1 = taffy.new_leaf(Style::default()).unwrap();
835
836        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
837        assert_eq!(taffy.child_count(node).unwrap(), 1);
838        assert_eq!(taffy.children(node).unwrap()[0], child0);
839
840        taffy.replace_child_at_index(node, 0, child1).unwrap();
841        assert_eq!(taffy.child_count(node).unwrap(), 1);
842        assert_eq!(taffy.children(node).unwrap()[0], child1);
843    }
844    #[test]
845    fn test_child_at_index() {
846        let mut taffy: TaffyTree<()> = TaffyTree::new();
847        let child0 = taffy.new_leaf(Style::default()).unwrap();
848        let child1 = taffy.new_leaf(Style::default()).unwrap();
849        let child2 = taffy.new_leaf(Style::default()).unwrap();
850        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
851
852        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
853        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
854        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
855    }
856    #[test]
857    fn test_child_count() {
858        let mut taffy: TaffyTree<()> = TaffyTree::new();
859        let child0 = taffy.new_leaf(Style::default()).unwrap();
860        let child1 = taffy.new_leaf(Style::default()).unwrap();
861        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
862
863        assert!(if let Ok(count) = taffy.child_count(node) { count == 2 } else { false });
864        assert!(if let Ok(count) = taffy.child_count(child0) { count == 0 } else { false });
865        assert!(if let Ok(count) = taffy.child_count(child1) { count == 0 } else { false });
866    }
867
868    #[allow(clippy::vec_init_then_push)]
869    #[test]
870    fn test_children() {
871        let mut taffy: TaffyTree<()> = TaffyTree::new();
872        let child0 = taffy.new_leaf(Style::default()).unwrap();
873        let child1 = taffy.new_leaf(Style::default()).unwrap();
874        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
875
876        let mut children = sys::Vec::new();
877        children.push(child0);
878        children.push(child1);
879
880        let children_result = taffy.children(node).unwrap();
881        assert_eq!(children_result, children);
882
883        assert!(taffy.children(child0).unwrap().is_empty());
884    }
885    #[test]
886    fn test_set_style() {
887        let mut taffy: TaffyTree<()> = TaffyTree::new();
888
889        let node = taffy.new_leaf(Style::default()).unwrap();
890        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
891
892        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
893        assert_eq!(taffy.style(node).unwrap().display, Display::None);
894    }
895    #[test]
896    fn test_style() {
897        let mut taffy: TaffyTree<()> = TaffyTree::new();
898
899        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
900
901        let node = taffy.new_leaf(style.clone()).unwrap();
902
903        let res = taffy.style(node);
904        assert!(res.is_ok());
905        assert!(res.unwrap() == &style);
906    }
907    #[test]
908    fn test_layout() {
909        let mut taffy: TaffyTree<()> = TaffyTree::new();
910        let node = taffy.new_leaf(Style::default()).unwrap();
911
912        // TODO: Improve this test?
913        let res = taffy.layout(node);
914        assert!(res.is_ok());
915    }
916
917    #[test]
918    fn test_mark_dirty() {
919        let mut taffy: TaffyTree<()> = TaffyTree::new();
920        let child0 = taffy.new_leaf(Style::default()).unwrap();
921        let child1 = taffy.new_leaf(Style::default()).unwrap();
922        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
923
924        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
925
926        assert_eq!(taffy.dirty(child0).unwrap(), false);
927        assert_eq!(taffy.dirty(child1).unwrap(), false);
928        assert_eq!(taffy.dirty(node).unwrap(), false);
929
930        taffy.mark_dirty(node).unwrap();
931        assert_eq!(taffy.dirty(child0).unwrap(), false);
932        assert_eq!(taffy.dirty(child1).unwrap(), false);
933        assert_eq!(taffy.dirty(node).unwrap(), true);
934
935        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
936        taffy.mark_dirty(child0).unwrap();
937        assert_eq!(taffy.dirty(child0).unwrap(), true);
938        assert_eq!(taffy.dirty(child1).unwrap(), false);
939        assert_eq!(taffy.dirty(node).unwrap(), true);
940    }
941
942    #[test]
943    fn compute_layout_should_produce_valid_result() {
944        let mut taffy: TaffyTree<()> = TaffyTree::new();
945        let node_result = taffy.new_leaf(Style {
946            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
947            ..Default::default()
948        });
949        assert!(node_result.is_ok());
950        let node = node_result.unwrap();
951        let layout_result = taffy.compute_layout(
952            node,
953            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
954        );
955        assert!(layout_result.is_ok());
956    }
957
958    #[test]
959    fn make_sure_layout_location_is_top_left() {
960        use crate::prelude::Rect;
961
962        let mut taffy: TaffyTree<()> = TaffyTree::new();
963
964        let node = taffy
965            .new_leaf(Style {
966                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
967                ..Default::default()
968            })
969            .unwrap();
970
971        let root = taffy
972            .new_with_children(
973                Style {
974                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
975                    padding: Rect {
976                        left: length(10f32),
977                        right: length(20f32),
978                        top: length(30f32),
979                        bottom: length(40f32),
980                    },
981                    ..Default::default()
982                },
983                &[node],
984            )
985            .unwrap();
986
987        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
988
989        // If Layout::location represents top-left coord, 'node' location
990        // must be (due applied 'root' padding): {x: 10, y: 30}.
991        //
992        // It's important, since result will be different for each other
993        // coordinate space:
994        // - bottom-left:  {x: 10, y: 40}
995        // - top-right:    {x: 20, y: 30}
996        // - bottom-right: {x: 20, y: 40}
997        let layout = taffy.layout(node).unwrap();
998        assert_eq!(layout.location.x, 10f32);
999        assert_eq!(layout.location.y, 30f32);
1000    }
1001}