gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 1061HTML 997Markdown 12TOML 83120 Definitions

⎇ 7eee673c5ea65f64f35c53f5ee2fe5faf62b9c1e src/tree/taffy_tree.rs Rust · 996 lines · 37.3 KB History Who touched what raw

Improve main module (lib.rs) docs + re-export more types at the crate root (#444) 7eee673c5 · Nico Burns ·

1//! Contains [Taffy](crate::tree::Taffy): 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 [`Taffy`](crate::Taffy) instance.
34    InvalidParentNode(NodeId),
35    /// The child node was not found in the [`Taffy`](crate::Taffy) instance.
36    InvalidChildNode(NodeId),
37    /// The supplied node was not found in the [`Taffy`](crate::Taffy) 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 Taffy instance")
49            }
50            TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the Taffy instance"),
51            TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the Taffy instance"),
52        }
53    }
54}
55
56#[cfg(feature = "std")]
57impl std::error::Error for TaffyError {}
58
59/// Global configuration values for a Taffy 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 Taffy<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 Taffy {
96    fn default() -> Taffy<()> {
97        Taffy::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 Taffy 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 Taffy tree
119    pub(crate) taffy: &'t mut Taffy<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> Taffy<NodeContext> {
228    /// Creates a new [`Taffy`]
229    ///
230    /// The default capacity of a [`Taffy`] is 16 nodes.
231    #[must_use]
232    pub fn new() -> Self {
233        Self::with_capacity(16)
234    }
235
236    /// Creates a new [`Taffy`] that can store `capacity` nodes before reallocation
237    #[must_use]
238    pub fn with_capacity(capacity: usize) -> Self {
239        Taffy {
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    /// Get's a mutable reference to the the context data associated with the node
348    pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
349        self.node_context_data.get_mut(node.into())
350    }
351
352    /// Adds a `child` node under the supplied `parent`
353    pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
354        let parent_key = parent.into();
355        let child_key = child.into();
356        self.parents[child_key] = Some(parent);
357        self.children[parent_key].push(child);
358        self.mark_dirty(parent)?;
359
360        Ok(())
361    }
362
363    /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
364    pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
365        let parent_key = parent.into();
366
367        let child_count = self.children[parent_key].len();
368        if child_index > child_count {
369            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
370        }
371
372        self.parents[child.into()] = Some(parent);
373        self.children[parent_key].insert(child_index, child);
374        self.mark_dirty(parent)?;
375
376        Ok(())
377    }
378
379    /// Directly sets the `children` of the supplied `parent`
380    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
381        let parent_key = parent.into();
382
383        // Remove node as parent from all its current children.
384        for child in &self.children[parent_key] {
385            self.parents[(*child).into()] = None;
386        }
387
388        // Build up relation node <-> child
389        for child in children {
390            self.parents[(*child).into()] = Some(parent);
391        }
392
393        let parent_children = &mut self.children[parent_key];
394        parent_children.clear();
395        children.iter().for_each(|child| parent_children.push(*child));
396
397        self.mark_dirty(parent)?;
398
399        Ok(())
400    }
401
402    /// Removes the `child` of the parent `node`
403    ///
404    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
405    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
406        let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
407        self.remove_child_at_index(parent, index)
408    }
409
410    /// Removes the child at the given `index` from the `parent`
411    ///
412    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
413    pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
414        let parent_key = parent.into();
415        let child_count = self.children[parent_key].len();
416        if child_index >= child_count {
417            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
418        }
419
420        let child = self.children[parent_key].remove(child_index);
421        self.parents[child.into()] = None;
422
423        self.mark_dirty(parent)?;
424
425        Ok(child)
426    }
427
428    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
429    ///
430    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
431    pub fn replace_child_at_index(
432        &mut self,
433        parent: NodeId,
434        child_index: usize,
435        new_child: NodeId,
436    ) -> TaffyResult<NodeId> {
437        let parent_key = parent.into();
438
439        let child_count = self.children[parent_key].len();
440        if child_index >= child_count {
441            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
442        }
443
444        self.parents[new_child.into()] = Some(parent);
445        let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
446        self.parents[old_child.into()] = None;
447
448        self.mark_dirty(parent)?;
449
450        Ok(old_child)
451    }
452
453    /// Returns the child node of the parent `node` at the provided `child_index`
454    pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
455        let parent_key = parent.into();
456        let child_count = self.children[parent_key].len();
457        if child_index >= child_count {
458            return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
459        }
460
461        Ok(self.children[parent_key][child_index])
462    }
463
464    /// Returns the total number of nodes in the tree
465    pub fn total_node_count(&self) -> usize {
466        self.nodes.len()
467    }
468
469    /// Returns the number of children of the `parent` node
470    pub fn child_count(&self, parent: NodeId) -> TaffyResult<usize> {
471        Ok(self.children[parent.into()].len())
472    }
473
474    /// Returns a list of children that belong to the parent node
475    pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
476        Ok(self.children[parent.into()].iter().copied().collect::<_>())
477    }
478
479    /// Sets the [`Style`] of the provided `node`
480    pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
481        self.nodes[node.into()].style = style;
482        self.mark_dirty(node)?;
483        Ok(())
484    }
485
486    /// Gets the [`Style`] of the provided `node`
487    pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
488        Ok(&self.nodes[node.into()].style)
489    }
490
491    /// Return this node layout relative to its parent
492    pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
493        if self.config.use_rounding {
494            Ok(&self.nodes[node.into()].final_layout)
495        } else {
496            Ok(&self.nodes[node.into()].unrounded_layout)
497        }
498    }
499
500    /// Marks the layout computation of this node and its children as outdated
501    ///
502    /// Performs a recursive depth-first search up the tree until the root node is reached
503    ///
504    /// WARNING: this will stack-overflow if the tree contains a cycle
505    pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
506        /// WARNING: this will stack-overflow if the tree contains a cycle
507        fn mark_dirty_recursive(
508            nodes: &mut SlotMap<DefaultKey, NodeData>,
509            parents: &SlotMap<DefaultKey, Option<NodeId>>,
510            node_key: DefaultKey,
511        ) {
512            nodes[node_key].mark_dirty();
513
514            if let Some(Some(node)) = parents.get(node_key) {
515                mark_dirty_recursive(nodes, parents, (*node).into());
516            }
517        }
518
519        mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
520
521        Ok(())
522    }
523
524    /// Indicates whether the layout of this node (and its children) need to be recomputed
525    pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
526        Ok(self.nodes[node.into()].cache.is_empty())
527    }
528
529    /// Updates the stored layout of the provided `node` and its children
530    pub fn compute_layout_with_measure<MeasureFunction>(
531        &mut self,
532        node_id: NodeId,
533        available_space: Size<AvailableSpace>,
534        measure_function: MeasureFunction,
535    ) -> Result<(), TaffyError>
536    where
537        MeasureFunction: FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>) -> Size<f32>,
538    {
539        let use_rounding = self.config.use_rounding;
540        let mut taffy_view = TaffyView { taffy: self, measure_function };
541        compute_layout(&mut taffy_view, node_id, available_space);
542        if use_rounding {
543            round_layout(&mut taffy_view, node_id);
544        }
545        Ok(())
546    }
547
548    /// Updates the stored layout of the provided `node` and its children
549    pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
550        self.compute_layout_with_measure(node, available_space, |_, _, _, _| Size::ZERO)
551    }
552
553    /// Prints a debug representation of the tree's layout
554    #[cfg(feature = "std")]
555    pub fn print_tree(&mut self, root: NodeId) {
556        let taffy_view = TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO };
557        crate::util::print_tree(&taffy_view, root)
558    }
559
560    /// Returns an instance of LayoutTree representing the Taffy
561    #[cfg(test)]
562    pub(crate) fn as_layout_tree(&mut self) -> impl LayoutTree + '_ {
563        TaffyView { taffy: self, measure_function: |_, _, _, _| Size::ZERO }
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    #![allow(clippy::bool_assert_comparison)]
570
571    use super::*;
572    use crate::style::{Dimension, Display, FlexDirection};
573    use crate::style_helpers::*;
574    use crate::util::sys;
575
576    fn size_measure_function(
577        known_dimensions: Size<Option<f32>>,
578        _available_space: Size<AvailableSpace>,
579        _node_id: NodeId,
580        node_context: Option<&mut Size<f32>>,
581    ) -> Size<f32> {
582        known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
583    }
584
585    #[test]
586    fn new_should_allocate_default_capacity() {
587        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
588        let taffy: Taffy<()> = Taffy::new();
589
590        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
591        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
592        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
593    }
594
595    #[test]
596    fn test_with_capacity() {
597        const CAPACITY: usize = 8;
598        let taffy: Taffy<()> = Taffy::with_capacity(CAPACITY);
599
600        assert!(taffy.children.capacity() >= CAPACITY);
601        assert!(taffy.parents.capacity() >= CAPACITY);
602        assert!(taffy.nodes.capacity() >= CAPACITY);
603    }
604
605    #[test]
606    fn test_new_leaf() {
607        let mut taffy: Taffy<()> = Taffy::new();
608
609        let res = taffy.new_leaf(Style::default());
610        assert!(res.is_ok());
611        let node = res.unwrap();
612
613        // node should be in the taffy tree and have no children
614        assert!(taffy.child_count(node).unwrap() == 0);
615    }
616
617    #[test]
618    fn new_leaf_with_context() {
619        let mut taffy: Taffy<Size<f32>> = Taffy::new();
620
621        let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
622        assert!(res.is_ok());
623        let node = res.unwrap();
624
625        // node should be in the taffy tree and have no children
626        assert!(taffy.child_count(node).unwrap() == 0);
627    }
628
629    /// Test that new_with_children works as expected
630    #[test]
631    fn test_new_with_children() {
632        let mut taffy: Taffy<()> = Taffy::new();
633        let child0 = taffy.new_leaf(Style::default()).unwrap();
634        let child1 = taffy.new_leaf(Style::default()).unwrap();
635        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
636
637        // node should have two children
638        assert_eq!(taffy.child_count(node).unwrap(), 2);
639        assert_eq!(taffy.children(node).unwrap()[0], child0);
640        assert_eq!(taffy.children(node).unwrap()[1], child1);
641    }
642
643    #[test]
644    fn remove_node_should_remove() {
645        let mut taffy: Taffy<()> = Taffy::new();
646
647        let node = taffy.new_leaf(Style::default()).unwrap();
648
649        let _ = taffy.remove(node).unwrap();
650    }
651
652    #[test]
653    fn remove_node_should_detach_herarchy() {
654        let mut taffy: Taffy<()> = Taffy::new();
655
656        // Build a linear tree layout: <0> <- <1> <- <2>
657        let node2 = taffy.new_leaf(Style::default()).unwrap();
658        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
659        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
660
661        // Both node0 and node1 should have 1 child nodes
662        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
663        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
664
665        // Disconnect the tree: <0> <2>
666        let _ = taffy.remove(node1).unwrap();
667
668        // Both remaining nodes should have no child nodes
669        assert!(taffy.children(node0).unwrap().is_empty());
670        assert!(taffy.children(node2).unwrap().is_empty());
671    }
672
673    #[test]
674    fn remove_last_node() {
675        let mut taffy: Taffy<()> = Taffy::new();
676
677        let parent = taffy.new_leaf(Style::default()).unwrap();
678        let child = taffy.new_leaf(Style::default()).unwrap();
679        taffy.add_child(parent, child).unwrap();
680
681        taffy.remove(child).unwrap();
682        taffy.remove(parent).unwrap();
683    }
684
685    #[test]
686    fn set_measure() {
687        let mut taffy: Taffy<Size<f32>> = Taffy::new();
688        let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
689        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
690        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
691
692        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
693        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
694        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
695    }
696
697    #[test]
698    fn set_measure_of_previously_unmeasured_node() {
699        let mut taffy: Taffy<Size<f32>> = Taffy::new();
700        let node = taffy.new_leaf(Style::default()).unwrap();
701        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
702        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
703
704        taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
705        taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
706        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
707    }
708
709    /// Test that adding `add_child()` works
710    #[test]
711    fn add_child() {
712        let mut taffy: Taffy<()> = Taffy::new();
713        let node = taffy.new_leaf(Style::default()).unwrap();
714        assert_eq!(taffy.child_count(node).unwrap(), 0);
715
716        let child0 = taffy.new_leaf(Style::default()).unwrap();
717        taffy.add_child(node, child0).unwrap();
718        assert_eq!(taffy.child_count(node).unwrap(), 1);
719
720        let child1 = taffy.new_leaf(Style::default()).unwrap();
721        taffy.add_child(node, child1).unwrap();
722        assert_eq!(taffy.child_count(node).unwrap(), 2);
723    }
724
725    #[test]
726    fn insert_child_at_index() {
727        let mut taffy: Taffy<()> = Taffy::new();
728
729        let child0 = taffy.new_leaf(Style::default()).unwrap();
730        let child1 = taffy.new_leaf(Style::default()).unwrap();
731        let child2 = taffy.new_leaf(Style::default()).unwrap();
732
733        let node = taffy.new_leaf(Style::default()).unwrap();
734        assert_eq!(taffy.child_count(node).unwrap(), 0);
735
736        taffy.insert_child_at_index(node, 0, child0).unwrap();
737        assert_eq!(taffy.child_count(node).unwrap(), 1);
738        assert_eq!(taffy.children(node).unwrap()[0], child0);
739
740        taffy.insert_child_at_index(node, 0, child1).unwrap();
741        assert_eq!(taffy.child_count(node).unwrap(), 2);
742        assert_eq!(taffy.children(node).unwrap()[0], child1);
743        assert_eq!(taffy.children(node).unwrap()[1], child0);
744
745        taffy.insert_child_at_index(node, 1, child2).unwrap();
746        assert_eq!(taffy.child_count(node).unwrap(), 3);
747        assert_eq!(taffy.children(node).unwrap()[0], child1);
748        assert_eq!(taffy.children(node).unwrap()[1], child2);
749        assert_eq!(taffy.children(node).unwrap()[2], child0);
750    }
751
752    #[test]
753    fn set_children() {
754        let mut taffy: Taffy<()> = Taffy::new();
755
756        let child0 = taffy.new_leaf(Style::default()).unwrap();
757        let child1 = taffy.new_leaf(Style::default()).unwrap();
758        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
759
760        assert_eq!(taffy.child_count(node).unwrap(), 2);
761        assert_eq!(taffy.children(node).unwrap()[0], child0);
762        assert_eq!(taffy.children(node).unwrap()[1], child1);
763
764        let child2 = taffy.new_leaf(Style::default()).unwrap();
765        let child3 = taffy.new_leaf(Style::default()).unwrap();
766        taffy.set_children(node, &[child2, child3]).unwrap();
767
768        assert_eq!(taffy.child_count(node).unwrap(), 2);
769        assert_eq!(taffy.children(node).unwrap()[0], child2);
770        assert_eq!(taffy.children(node).unwrap()[1], child3);
771    }
772
773    /// Test that removing a child works
774    #[test]
775    fn remove_child() {
776        let mut taffy: Taffy<()> = Taffy::new();
777        let child0 = taffy.new_leaf(Style::default()).unwrap();
778        let child1 = taffy.new_leaf(Style::default()).unwrap();
779        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
780
781        assert_eq!(taffy.child_count(node).unwrap(), 2);
782
783        taffy.remove_child(node, child0).unwrap();
784        assert_eq!(taffy.child_count(node).unwrap(), 1);
785        assert_eq!(taffy.children(node).unwrap()[0], child1);
786
787        taffy.remove_child(node, child1).unwrap();
788        assert_eq!(taffy.child_count(node).unwrap(), 0);
789    }
790
791    #[test]
792    fn remove_child_at_index() {
793        let mut taffy: Taffy<()> = Taffy::new();
794        let child0 = taffy.new_leaf(Style::default()).unwrap();
795        let child1 = taffy.new_leaf(Style::default()).unwrap();
796        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
797
798        assert_eq!(taffy.child_count(node).unwrap(), 2);
799
800        taffy.remove_child_at_index(node, 0).unwrap();
801        assert_eq!(taffy.child_count(node).unwrap(), 1);
802        assert_eq!(taffy.children(node).unwrap()[0], child1);
803
804        taffy.remove_child_at_index(node, 0).unwrap();
805        assert_eq!(taffy.child_count(node).unwrap(), 0);
806    }
807
808    // Related to: https://github.com/DioxusLabs/taffy/issues/510
809    #[test]
810    fn remove_child_updates_parents() {
811        let mut taffy: Taffy<()> = Taffy::new();
812
813        let parent = taffy.new_leaf(Style::default()).unwrap();
814        let child = taffy.new_leaf(Style::default()).unwrap();
815
816        taffy.add_child(parent, child).unwrap();
817
818        taffy.remove(parent).unwrap();
819
820        // Once the parent is removed this shouldn't panic.
821        assert!(taffy.set_children(child, &[]).is_ok());
822    }
823
824    #[test]
825    fn replace_child_at_index() {
826        let mut taffy: Taffy<()> = Taffy::new();
827
828        let child0 = taffy.new_leaf(Style::default()).unwrap();
829        let child1 = taffy.new_leaf(Style::default()).unwrap();
830
831        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
832        assert_eq!(taffy.child_count(node).unwrap(), 1);
833        assert_eq!(taffy.children(node).unwrap()[0], child0);
834
835        taffy.replace_child_at_index(node, 0, child1).unwrap();
836        assert_eq!(taffy.child_count(node).unwrap(), 1);
837        assert_eq!(taffy.children(node).unwrap()[0], child1);
838    }
839    #[test]
840    fn test_child_at_index() {
841        let mut taffy: Taffy<()> = Taffy::new();
842        let child0 = taffy.new_leaf(Style::default()).unwrap();
843        let child1 = taffy.new_leaf(Style::default()).unwrap();
844        let child2 = taffy.new_leaf(Style::default()).unwrap();
845        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
846
847        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
848        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
849        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
850    }
851    #[test]
852    fn test_child_count() {
853        let mut taffy: Taffy<()> = Taffy::new();
854        let child0 = taffy.new_leaf(Style::default()).unwrap();
855        let child1 = taffy.new_leaf(Style::default()).unwrap();
856        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
857
858        assert!(if let Ok(count) = taffy.child_count(node) { count == 2 } else { false });
859        assert!(if let Ok(count) = taffy.child_count(child0) { count == 0 } else { false });
860        assert!(if let Ok(count) = taffy.child_count(child1) { count == 0 } else { false });
861    }
862
863    #[allow(clippy::vec_init_then_push)]
864    #[test]
865    fn test_children() {
866        let mut taffy: Taffy<()> = Taffy::new();
867        let child0 = taffy.new_leaf(Style::default()).unwrap();
868        let child1 = taffy.new_leaf(Style::default()).unwrap();
869        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
870
871        let mut children = sys::Vec::new();
872        children.push(child0);
873        children.push(child1);
874
875        let children_result = taffy.children(node).unwrap();
876        assert_eq!(children_result, children);
877
878        assert!(taffy.children(child0).unwrap().is_empty());
879    }
880    #[test]
881    fn test_set_style() {
882        let mut taffy: Taffy<()> = Taffy::new();
883
884        let node = taffy.new_leaf(Style::default()).unwrap();
885        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
886
887        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
888        assert_eq!(taffy.style(node).unwrap().display, Display::None);
889    }
890    #[test]
891    fn test_style() {
892        let mut taffy: Taffy<()> = Taffy::new();
893
894        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
895
896        let node = taffy.new_leaf(style.clone()).unwrap();
897
898        let res = taffy.style(node);
899        assert!(res.is_ok());
900        assert!(res.unwrap() == &style);
901    }
902    #[test]
903    fn test_layout() {
904        let mut taffy: Taffy<()> = Taffy::new();
905        let node = taffy.new_leaf(Style::default()).unwrap();
906
907        // TODO: Improve this test?
908        let res = taffy.layout(node);
909        assert!(res.is_ok());
910    }
911
912    #[test]
913    fn test_mark_dirty() {
914        let mut taffy: Taffy<()> = Taffy::new();
915        let child0 = taffy.new_leaf(Style::default()).unwrap();
916        let child1 = taffy.new_leaf(Style::default()).unwrap();
917        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
918
919        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
920
921        assert_eq!(taffy.dirty(child0).unwrap(), false);
922        assert_eq!(taffy.dirty(child1).unwrap(), false);
923        assert_eq!(taffy.dirty(node).unwrap(), false);
924
925        taffy.mark_dirty(node).unwrap();
926        assert_eq!(taffy.dirty(child0).unwrap(), false);
927        assert_eq!(taffy.dirty(child1).unwrap(), false);
928        assert_eq!(taffy.dirty(node).unwrap(), true);
929
930        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
931        taffy.mark_dirty(child0).unwrap();
932        assert_eq!(taffy.dirty(child0).unwrap(), true);
933        assert_eq!(taffy.dirty(child1).unwrap(), false);
934        assert_eq!(taffy.dirty(node).unwrap(), true);
935    }
936
937    #[test]
938    fn compute_layout_should_produce_valid_result() {
939        let mut taffy: Taffy<()> = Taffy::new();
940        let node_result = taffy.new_leaf(Style {
941            size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
942            ..Default::default()
943        });
944        assert!(node_result.is_ok());
945        let node = node_result.unwrap();
946        let layout_result = taffy.compute_layout(
947            node,
948            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
949        );
950        assert!(layout_result.is_ok());
951    }
952
953    #[test]
954    fn make_sure_layout_location_is_top_left() {
955        use crate::prelude::Rect;
956
957        let mut taffy: Taffy<()> = Taffy::new();
958
959        let node = taffy
960            .new_leaf(Style {
961                size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
962                ..Default::default()
963            })
964            .unwrap();
965
966        let root = taffy
967            .new_with_children(
968                Style {
969                    size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
970                    padding: Rect {
971                        left: length(10f32),
972                        right: length(20f32),
973                        top: length(30f32),
974                        bottom: length(40f32),
975                    },
976                    ..Default::default()
977                },
978                &[node],
979            )
980            .unwrap();
981
982        taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
983
984        // If Layout::location represents top-left coord, 'node' location
985        // must be (due applied 'root' padding): {x: 10, y: 30}.
986        //
987        // It's important, since result will be different for each other
988        // coordinate space:
989        // - bottom-left:  {x: 10, y: 40}
990        // - top-right:    {x: 20, y: 30}
991        // - bottom-right: {x: 20, y: 40}
992        let layout = taffy.layout(node).unwrap();
993        assert_eq!(layout.location.x, 10f32);
994        assert_eq!(layout.location.y, 30f32);
995    }
996}