gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 227Rust 7TOML 3CSS 1307 Definiciones

⎇ 9e53f03adea2b770d68954e404d2fa407dfc7d40 src/node.rs Rust · 695 líneas · 24.7 KB Historia Quién tocó qué crudo

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