gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 708HTML 661Markdown 12TOML 62346 Definitions

⎇ 3803328e1128146be5a3592e6d16fa8714930828 src/node.rs Rust · 756 lines · 26.6 KB History Who touched what raw

update parents list on remove (#511) 3803328e1 · Nico Burns ·

1//! UI [`Node`] types and related data structures.
2//!
3//! Layouts are composed of multiple nodes, which live in a tree-like data structure.
4use slotmap::{DefaultKey, SlotMap, SparseSecondaryMap};
5
6/// A node in a layout.
7pub type Node = slotmap::DefaultKey;
8
9use crate::error::{TaffyError, TaffyResult};
10use crate::geometry::Size;
11use crate::layout::{Cache, Layout};
12use crate::prelude::LayoutTree;
13use crate::style::{AvailableSpace, Style};
14#[cfg(any(feature = "std", feature = "alloc"))]
15use crate::sys::Box;
16use crate::sys::{new_vec_with_capacity, ChildrenVec, Vec};
17use crate::{data::NodeData, error};
18
19/// A function type that can be used in a [`MeasureFunc`]
20///
21/// This trait is automatically implemented for all types (including closures) that define a function with the appropriate type signature.
22pub trait Measurable: Send + Sync + Fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32> {}
23impl<F: Send + Sync + Fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>> Measurable for F {}
24
25/// A function that can be used to compute the intrinsic size of a node
26pub enum MeasureFunc {
27    /// Stores an unboxed function
28    Raw(fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>),
29
30    /// Stores a boxed function
31    #[cfg(any(feature = "std", feature = "alloc"))]
32    Boxed(Box<dyn Measurable>),
33}
34
35/// Global configuration values for a Taffy instance
36pub(crate) struct TaffyConfig {
37    /// Whether to round layout values
38    pub(crate) use_rounding: bool,
39}
40
41impl Default for TaffyConfig {
42    fn default() -> Self {
43        Self { use_rounding: true }
44    }
45}
46
47/// A tree of UI [`Nodes`](`Node`), suitable for UI layout
48pub struct Taffy {
49    /// The [`NodeData`] for each node stored in this tree
50    pub(crate) nodes: SlotMap<Node, NodeData>,
51
52    /// Functions/closures that compute the intrinsic size of leaf nodes
53    pub(crate) measure_funcs: SparseSecondaryMap<Node, MeasureFunc>,
54
55    /// The children of each node
56    ///
57    /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
58    pub(crate) children: SlotMap<Node, ChildrenVec<Node>>,
59
60    /// The parents of each node
61    ///
62    /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
63    pub(crate) parents: SlotMap<Node, Option<Node>>,
64
65    /// Layout mode configuration
66    pub(crate) config: TaffyConfig,
67
68    /// Hack to allow the `LayoutTree::layout_mut` function to expose the `NodeData.unrounded_layout` of a node to
69    /// the layout algorithms during layout, while exposing the `NodeData.final_layout` when called by external users.
70    /// This allows us to fix <https://github.com/DioxusLabs/taffy/issues/501> without breaking backwards compatibility
71    pub(crate) is_layouting: bool,
72}
73
74impl Default for Taffy {
75    fn default() -> Self {
76        Taffy::new()
77    }
78}
79
80impl LayoutTree for Taffy {
81    type ChildIter<'a> = core::slice::Iter<'a, DefaultKey>;
82
83    fn children(&self, node: Node) -> Self::ChildIter<'_> {
84        self.children[node].iter()
85    }
86
87    fn child_count(&self, node: Node) -> usize {
88        self.children[node].len()
89    }
90
91    fn is_childless(&self, node: Node) -> bool {
92        self.children[node].is_empty()
93    }
94
95    fn parent(&self, node: Node) -> Option<Node> {
96        self.parents.get(node).copied().flatten()
97    }
98
99    fn style(&self, node: Node) -> &Style {
100        &self.nodes[node].style
101    }
102
103    #[inline(always)]
104    fn layout(&self, node: Node) -> &Layout {
105        if self.is_layouting && self.config.use_rounding {
106            &self.nodes[node].unrounded_layout
107        } else {
108            &self.nodes[node].final_layout
109        }
110    }
111
112    #[inline(always)]
113    fn layout_mut(&mut self, node: Node) -> &mut Layout {
114        if self.is_layouting && self.config.use_rounding {
115            &mut self.nodes[node].unrounded_layout
116        } else {
117            &mut self.nodes[node].final_layout
118        }
119    }
120
121    #[inline(always)]
122    fn mark_dirty(&mut self, node: Node) -> TaffyResult<()> {
123        self.mark_dirty_internal(node)
124    }
125
126    fn measure_node(
127        &self,
128        node: Node,
129        known_dimensions: Size<Option<f32>>,
130        available_space: Size<AvailableSpace>,
131    ) -> Size<f32> {
132        match &self.measure_funcs[node] {
133            MeasureFunc::Raw(measure) => measure(known_dimensions, available_space),
134
135            #[cfg(any(feature = "std", feature = "alloc"))]
136            MeasureFunc::Boxed(measure) => (measure as &dyn Fn(_, _) -> _)(known_dimensions, available_space),
137        }
138    }
139
140    fn needs_measure(&self, node: Node) -> bool {
141        self.nodes[node].needs_measure && self.measure_funcs.get(node).is_some()
142    }
143
144    fn cache_mut(&mut self, node: Node, index: usize) -> &mut Option<Cache> {
145        &mut self.nodes[node].size_cache[index]
146    }
147
148    fn child(&self, node: Node, id: usize) -> Node {
149        self.children[node][id]
150    }
151}
152
153#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
154impl Taffy {
155    /// Creates a new [`Taffy`]
156    ///
157    /// The default capacity of a [`Taffy`] is 16 nodes.
158    #[must_use]
159    pub fn new() -> Self {
160        Self::with_capacity(16)
161    }
162
163    /// Creates a new [`Taffy`] that can store `capacity` nodes before reallocation
164    #[must_use]
165    pub fn with_capacity(capacity: usize) -> Self {
166        Self {
167            // TODO: make this method const upstream,
168            // so constructors here can be const
169            nodes: SlotMap::with_capacity(capacity),
170            children: SlotMap::with_capacity(capacity),
171            parents: SlotMap::with_capacity(capacity),
172            measure_funcs: SparseSecondaryMap::with_capacity(capacity),
173            config: TaffyConfig::default(),
174            is_layouting: false,
175        }
176    }
177
178    /// Enable rounding of layout values. Rounding is enabled by default.
179    pub fn enable_rounding(&mut self) {
180        self.config.use_rounding = true;
181    }
182
183    /// Disable rounding of layout values. Rounding is enabled by default.
184    pub fn disable_rounding(&mut self) {
185        self.config.use_rounding = false;
186    }
187
188    /// Creates and adds a new unattached leaf node to the tree, and returns the [`Node`] of the new node
189    pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<Node> {
190        let id = self.nodes.insert(NodeData::new(layout));
191        let _ = self.children.insert(new_vec_with_capacity(0));
192        let _ = self.parents.insert(None);
193
194        Ok(id)
195    }
196
197    /// Creates and adds a new unattached leaf node to the tree, and returns the [`Node`] of the new node
198    ///
199    /// Creates and adds a new leaf node with a supplied [`MeasureFunc`]
200    pub fn new_leaf_with_measure(&mut self, layout: Style, measure: MeasureFunc) -> TaffyResult<Node> {
201        let mut data = NodeData::new(layout);
202        data.needs_measure = true;
203
204        let id = self.nodes.insert(data);
205        self.measure_funcs.insert(id, measure);
206
207        let _ = self.children.insert(new_vec_with_capacity(0));
208        let _ = self.parents.insert(None);
209
210        Ok(id)
211    }
212
213    /// Creates and adds a new node, which may have any number of `children`
214    pub fn new_with_children(&mut self, layout: Style, children: &[Node]) -> TaffyResult<Node> {
215        let id = self.nodes.insert(NodeData::new(layout));
216
217        for child in children {
218            self.parents[*child] = Some(id);
219        }
220
221        let _ = self.children.insert(children.iter().copied().collect::<_>());
222        let _ = self.parents.insert(None);
223
224        Ok(id)
225    }
226
227    /// Drops all nodes in the tree
228    pub fn clear(&mut self) {
229        self.nodes.clear();
230        self.children.clear();
231        self.parents.clear();
232    }
233
234    /// Remove a specific [`Node`] from the tree and drops it
235    ///
236    /// Returns the id of the node removed.
237    pub fn remove(&mut self, node: Node) -> TaffyResult<Node> {
238        if let Some(parent) = self.parents[node] {
239            if let Some(children) = self.children.get_mut(parent) {
240                children.retain(|f| *f != node);
241            }
242        }
243
244        if let Some(children) = self.children.get(node) {
245            for child in children.iter().copied() {
246                self.parents[child] = None;
247            }
248        }
249
250        let _ = self.children.remove(node);
251        let _ = self.parents.remove(node);
252        let _ = self.nodes.remove(node);
253
254        Ok(node)
255    }
256
257    /// Sets the [`MeasureFunc`] of the associated node
258    pub fn set_measure(&mut self, node: Node, measure: Option<MeasureFunc>) -> TaffyResult<()> {
259        if let Some(measure) = measure {
260            self.nodes[node].needs_measure = true;
261            self.measure_funcs.insert(node, measure);
262        } else {
263            self.nodes[node].needs_measure = false;
264            self.measure_funcs.remove(node);
265        }
266
267        self.mark_dirty_internal(node)?;
268
269        Ok(())
270    }
271
272    /// Adds a `child` [`Node`] under the supplied `parent`
273    pub fn add_child(&mut self, parent: Node, child: Node) -> TaffyResult<()> {
274        self.parents[child] = Some(parent);
275        self.children[parent].push(child);
276        self.mark_dirty_internal(parent)?;
277
278        Ok(())
279    }
280
281    /// Directly sets the `children` of the supplied `parent`
282    pub fn set_children(&mut self, parent: Node, children: &[Node]) -> TaffyResult<()> {
283        // Remove node as parent from all its current children.
284        for child in &self.children[parent] {
285            self.parents[*child] = None;
286        }
287
288        // Build up relation node <-> child
289        for child in children {
290            self.parents[*child] = Some(parent);
291        }
292
293        self.children[parent] = children.iter().copied().collect::<_>();
294
295        self.mark_dirty_internal(parent)?;
296
297        Ok(())
298    }
299
300    /// Removes the `child` of the parent `node`
301    ///
302    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
303    pub fn remove_child(&mut self, parent: Node, child: Node) -> TaffyResult<Node> {
304        let index = self.children[parent].iter().position(|n| *n == child).unwrap();
305        self.remove_child_at_index(parent, index)
306    }
307
308    /// Removes the child at the given `index` from the `parent`
309    ///
310    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
311    pub fn remove_child_at_index(&mut self, parent: Node, child_index: usize) -> TaffyResult<Node> {
312        let child_count = self.children[parent].len();
313        if child_index >= child_count {
314            return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
315        }
316
317        let child = self.children[parent].remove(child_index);
318        self.parents[child] = None;
319
320        self.mark_dirty_internal(parent)?;
321
322        Ok(child)
323    }
324
325    /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
326    ///
327    /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
328    pub fn replace_child_at_index(&mut self, parent: Node, child_index: usize, new_child: Node) -> TaffyResult<Node> {
329        let child_count = self.children[parent].len();
330        if child_index >= child_count {
331            return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
332        }
333
334        self.parents[new_child] = Some(parent);
335        let old_child = core::mem::replace(&mut self.children[parent][child_index], new_child);
336        self.parents[old_child] = None;
337
338        self.mark_dirty_internal(parent)?;
339
340        Ok(old_child)
341    }
342
343    /// Returns the child [`Node`] of the parent `node` at the provided `child_index`
344    pub fn child_at_index(&self, parent: Node, child_index: usize) -> TaffyResult<Node> {
345        let child_count = self.children[parent].len();
346        if child_index >= child_count {
347            return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
348        }
349
350        Ok(self.children[parent][child_index])
351    }
352
353    /// Returns the number of children of the `parent` [`Node`]
354    pub fn child_count(&self, parent: Node) -> TaffyResult<usize> {
355        Ok(self.children[parent].len())
356    }
357
358    /// Returns a list of children that belong to the parent [`Node`]
359    pub fn children(&self, parent: Node) -> TaffyResult<Vec<Node>> {
360        Ok(self.children[parent].iter().copied().collect::<_>())
361    }
362
363    /// Sets the [`Style`] of the provided `node`
364    pub fn set_style(&mut self, node: Node, style: Style) -> TaffyResult<()> {
365        self.nodes[node].style = style;
366        self.mark_dirty_internal(node)?;
367        Ok(())
368    }
369
370    /// Gets the [`Style`] of the provided `node`
371    pub fn style(&self, node: Node) -> TaffyResult<&Style> {
372        Ok(&self.nodes[node].style)
373    }
374
375    /// Return this node layout relative to its parent
376    pub fn layout(&self, node: Node) -> TaffyResult<&Layout> {
377        Ok(&self.nodes[node].final_layout)
378    }
379
380    /// Marks the layout computation of this node and its children as outdated
381    ///
382    /// Performs a recursive depth-first search up the tree until the root node is reached
383    ///
384    /// WARNING: this will stack-overflow if the tree contains a cycle
385    fn mark_dirty_internal(&mut self, node: Node) -> TaffyResult<()> {
386        /// WARNING: this will stack-overflow if the tree contains a cycle
387        fn mark_dirty_recursive(
388            nodes: &mut SlotMap<Node, NodeData>,
389            parents: &SlotMap<Node, Option<Node>>,
390            node_id: Node,
391        ) {
392            nodes[node_id].mark_dirty();
393
394            if let Some(Some(node)) = parents.get(node_id) {
395                mark_dirty_recursive(nodes, parents, *node);
396            }
397        }
398
399        mark_dirty_recursive(&mut self.nodes, &self.parents, node);
400
401        Ok(())
402    }
403
404    /// Indicates whether the layout of this node (and its children) need to be recomputed
405    pub fn dirty(&self, node: Node) -> TaffyResult<bool> {
406        Ok(self.nodes[node].size_cache.iter().all(|entry| entry.is_none()))
407    }
408
409    /// Updates the stored layout of the provided `node` and its children
410    pub fn compute_layout(&mut self, node: Node, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
411        crate::compute::compute_layout(self, node, available_space)
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    #![allow(clippy::bool_assert_comparison)]
418
419    use super::*;
420    use crate::style::{Dimension, Display, FlexDirection};
421    use crate::style_helpers::*;
422    use crate::sys;
423
424    #[test]
425    fn new_should_allocate_default_capacity() {
426        const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
427        let taffy = Taffy::new();
428
429        assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
430        assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
431        assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
432    }
433
434    #[test]
435    fn test_with_capacity() {
436        const CAPACITY: usize = 8;
437        let taffy = Taffy::with_capacity(CAPACITY);
438
439        assert!(taffy.children.capacity() >= CAPACITY);
440        assert!(taffy.parents.capacity() >= CAPACITY);
441        assert!(taffy.nodes.capacity() >= CAPACITY);
442    }
443
444    #[test]
445    fn test_new_leaf() {
446        let mut taffy = Taffy::new();
447
448        let res = taffy.new_leaf(Style::default());
449        assert!(res.is_ok());
450        let node = res.unwrap();
451
452        // node should be in the taffy tree and have no children
453        assert!(taffy.child_count(node).unwrap() == 0);
454    }
455
456    #[test]
457    fn new_leaf_with_measure() {
458        let mut taffy = Taffy::new();
459
460        let res = taffy.new_leaf_with_measure(Style::default(), MeasureFunc::Raw(|_, _| Size::ZERO));
461        assert!(res.is_ok());
462        let node = res.unwrap();
463
464        // node should be in the taffy tree and have no children
465        assert!(taffy.child_count(node).unwrap() == 0);
466    }
467
468    /// Test that new_with_children works as expected
469    #[test]
470    fn test_new_with_children() {
471        let mut taffy = Taffy::new();
472        let child0 = taffy.new_leaf(Style::default()).unwrap();
473        let child1 = taffy.new_leaf(Style::default()).unwrap();
474        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
475
476        // node should have two children
477        assert_eq!(taffy.child_count(node).unwrap(), 2);
478        assert_eq!(taffy.children(node).unwrap()[0], child0);
479        assert_eq!(taffy.children(node).unwrap()[1], child1);
480    }
481
482    #[test]
483    fn remove_node_should_remove() {
484        let mut taffy = Taffy::new();
485
486        let node = taffy.new_leaf(Style::default()).unwrap();
487
488        let _ = taffy.remove(node).unwrap();
489    }
490
491    #[test]
492    fn remove_node_should_detach_herarchy() {
493        let mut taffy = Taffy::new();
494
495        // Build a linear tree layout: <0> <- <1> <- <2>
496        let node2 = taffy.new_leaf(Style::default()).unwrap();
497        let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
498        let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
499
500        // Both node0 and node1 should have 1 child nodes
501        assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
502        assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
503
504        // Disconnect the tree: <0> <2>
505        let _ = taffy.remove(node1).unwrap();
506
507        // Both remaining nodes should have no child nodes
508        assert!(taffy.children(node0).unwrap().is_empty());
509        assert!(taffy.children(node2).unwrap().is_empty());
510    }
511
512    #[test]
513    fn remove_last_node() {
514        let mut taffy = Taffy::new();
515
516        let parent = taffy.new_leaf(Style::default()).unwrap();
517        let child = taffy.new_leaf(Style::default()).unwrap();
518        taffy.add_child(parent, child).unwrap();
519
520        taffy.remove(child).unwrap();
521        taffy.remove(parent).unwrap();
522    }
523
524    #[test]
525    fn set_measure() {
526        let mut taffy = Taffy::new();
527        let node = taffy
528            .new_leaf_with_measure(Style::default(), MeasureFunc::Raw(|_, _| Size { width: 200.0, height: 200.0 }))
529            .unwrap();
530        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
531        assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
532
533        taffy.set_measure(node, Some(MeasureFunc::Raw(|_, _| Size { width: 100.0, height: 100.0 }))).unwrap();
534        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
535        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
536    }
537
538    #[test]
539    fn set_measure_of_previously_unmeasured_node() {
540        let mut taffy = Taffy::new();
541        let node = taffy.new_leaf(Style::default()).unwrap();
542        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
543        assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
544
545        taffy.set_measure(node, Some(MeasureFunc::Raw(|_, _| Size { width: 100.0, height: 100.0 }))).unwrap();
546        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
547        assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
548    }
549
550    /// Test that adding `add_child()` works
551    #[test]
552    fn add_child() {
553        let mut taffy = Taffy::new();
554        let node = taffy.new_leaf(Style::default()).unwrap();
555        assert_eq!(taffy.child_count(node).unwrap(), 0);
556
557        let child0 = taffy.new_leaf(Style::default()).unwrap();
558        taffy.add_child(node, child0).unwrap();
559        assert_eq!(taffy.child_count(node).unwrap(), 1);
560
561        let child1 = taffy.new_leaf(Style::default()).unwrap();
562        taffy.add_child(node, child1).unwrap();
563        assert_eq!(taffy.child_count(node).unwrap(), 2);
564    }
565
566    #[test]
567    fn set_children() {
568        let mut taffy = Taffy::new();
569
570        let child0 = taffy.new_leaf(Style::default()).unwrap();
571        let child1 = taffy.new_leaf(Style::default()).unwrap();
572        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
573
574        assert_eq!(taffy.child_count(node).unwrap(), 2);
575        assert_eq!(taffy.children(node).unwrap()[0], child0);
576        assert_eq!(taffy.children(node).unwrap()[1], child1);
577
578        let child2 = taffy.new_leaf(Style::default()).unwrap();
579        let child3 = taffy.new_leaf(Style::default()).unwrap();
580        taffy.set_children(node, &[child2, child3]).unwrap();
581
582        assert_eq!(taffy.child_count(node).unwrap(), 2);
583        assert_eq!(taffy.children(node).unwrap()[0], child2);
584        assert_eq!(taffy.children(node).unwrap()[1], child3);
585    }
586
587    /// Test that removing a child works
588    #[test]
589    fn remove_child() {
590        let mut taffy = Taffy::new();
591        let child0 = taffy.new_leaf(Style::default()).unwrap();
592        let child1 = taffy.new_leaf(Style::default()).unwrap();
593        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
594
595        assert_eq!(taffy.child_count(node).unwrap(), 2);
596
597        taffy.remove_child(node, child0).unwrap();
598        assert_eq!(taffy.child_count(node).unwrap(), 1);
599        assert_eq!(taffy.children(node).unwrap()[0], child1);
600
601        taffy.remove_child(node, child1).unwrap();
602        assert_eq!(taffy.child_count(node).unwrap(), 0);
603    }
604
605    #[test]
606    fn remove_child_at_index() {
607        let mut taffy = Taffy::new();
608        let child0 = taffy.new_leaf(Style::default()).unwrap();
609        let child1 = taffy.new_leaf(Style::default()).unwrap();
610        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
611
612        assert_eq!(taffy.child_count(node).unwrap(), 2);
613
614        taffy.remove_child_at_index(node, 0).unwrap();
615        assert_eq!(taffy.child_count(node).unwrap(), 1);
616        assert_eq!(taffy.children(node).unwrap()[0], child1);
617
618        taffy.remove_child_at_index(node, 0).unwrap();
619        assert_eq!(taffy.child_count(node).unwrap(), 0);
620    }
621
622    #[test]
623    fn replace_child_at_index() {
624        let mut taffy = Taffy::new();
625
626        let child0 = taffy.new_leaf(Style::default()).unwrap();
627        let child1 = taffy.new_leaf(Style::default()).unwrap();
628
629        let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
630        assert_eq!(taffy.child_count(node).unwrap(), 1);
631        assert_eq!(taffy.children(node).unwrap()[0], child0);
632
633        taffy.replace_child_at_index(node, 0, child1).unwrap();
634        assert_eq!(taffy.child_count(node).unwrap(), 1);
635        assert_eq!(taffy.children(node).unwrap()[0], child1);
636    }
637    #[test]
638    fn test_child_at_index() {
639        let mut taffy = Taffy::new();
640        let child0 = taffy.new_leaf(Style::default()).unwrap();
641        let child1 = taffy.new_leaf(Style::default()).unwrap();
642        let child2 = taffy.new_leaf(Style::default()).unwrap();
643        let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
644
645        assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
646        assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
647        assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
648    }
649    #[test]
650    fn test_child_count() {
651        let mut taffy = Taffy::new();
652        let child0 = taffy.new_leaf(Style::default()).unwrap();
653        let child1 = taffy.new_leaf(Style::default()).unwrap();
654        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
655
656        assert!(if let Ok(count) = taffy.child_count(node) { count == 2 } else { false });
657        assert!(if let Ok(count) = taffy.child_count(child0) { count == 0 } else { false });
658        assert!(if let Ok(count) = taffy.child_count(child1) { count == 0 } else { false });
659    }
660
661    #[allow(clippy::vec_init_then_push)]
662    #[test]
663    fn test_children() {
664        let mut taffy = Taffy::new();
665        let child0 = taffy.new_leaf(Style::default()).unwrap();
666        let child1 = taffy.new_leaf(Style::default()).unwrap();
667        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
668
669        let mut children: sys::Vec<Node> = sys::Vec::new();
670        children.push(child0);
671        children.push(child1);
672
673        let children_result = taffy.children(node).unwrap();
674        assert_eq!(children_result, children);
675
676        assert!(taffy.children(child0).unwrap().is_empty());
677    }
678    #[test]
679    fn test_set_style() {
680        let mut taffy = Taffy::new();
681
682        let node = taffy.new_leaf(Style::default()).unwrap();
683        assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
684
685        taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
686        assert_eq!(taffy.style(node).unwrap().display, Display::None);
687    }
688    #[test]
689    fn test_style() {
690        let mut taffy = Taffy::new();
691
692        let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
693
694        let node = taffy.new_leaf(style.clone()).unwrap();
695
696        let res = taffy.style(node);
697        assert!(res.is_ok());
698        assert!(res.unwrap() == &style);
699    }
700    #[test]
701    fn test_layout() {
702        let mut taffy = Taffy::new();
703        let node = taffy.new_leaf(Style::default()).unwrap();
704
705        // TODO: Improve this test?
706        let res = taffy.layout(node);
707        assert!(res.is_ok());
708    }
709
710    #[test]
711    fn test_mark_dirty() {
712        let mut taffy = Taffy::new();
713        let child0 = taffy.new_leaf(Style::default()).unwrap();
714        let child1 = taffy.new_leaf(Style::default()).unwrap();
715        let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
716
717        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
718
719        assert_eq!(taffy.dirty(child0).unwrap(), false);
720        assert_eq!(taffy.dirty(child1).unwrap(), false);
721        assert_eq!(taffy.dirty(node).unwrap(), false);
722
723        taffy.mark_dirty(node).unwrap();
724        assert_eq!(taffy.dirty(child0).unwrap(), false);
725        assert_eq!(taffy.dirty(child1).unwrap(), false);
726        assert_eq!(taffy.dirty(node).unwrap(), true);
727
728        taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
729        taffy.mark_dirty(child0).unwrap();
730        assert_eq!(taffy.dirty(child0).unwrap(), true);
731        assert_eq!(taffy.dirty(child1).unwrap(), false);
732        assert_eq!(taffy.dirty(node).unwrap(), true);
733    }
734
735    #[test]
736    fn compute_layout_should_produce_valid_result() {
737        let mut taffy = Taffy::new();
738        let node_result = taffy.new_leaf(Style {
739            size: Size { width: Dimension::Points(10f32), height: Dimension::Points(10f32) },
740            ..Default::default()
741        });
742        assert!(node_result.is_ok());
743        let node = node_result.unwrap();
744        let layout_result = taffy.compute_layout(
745            node,
746            Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
747        );
748        assert!(layout_result.is_ok());
749    }
750
751    #[test]
752    fn measure_func_is_send_and_sync() {
753        fn is_send_and_sync<T: Send + Sync>() {}
754        is_send_and_sync::<MeasureFunc>();
755    }
756}