⎇ 717471c1093c3097f92883c2a422a451b4b6af72
src/tree/taffy_tree.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
Detailed layout info cleanup (#774)
1//! Contains [TaffyTree](crate::tree::TaffyTree): the default implementation of [LayoutTree](crate::tree::LayoutTree), and the error type for Taffy.
2#[cfg(not(feature = "std"))]
3use slotmap::SecondaryMap;
4#[cfg(feature = "std")]
5use slotmap::SparseSecondaryMap as SecondaryMap;
6use slotmap::{DefaultKey, SlotMap};
7
8use crate::geometry::Size;
9use crate::style::{AvailableSpace, Display, Style};
10use crate::tree::{
11 Cache, Layout, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, PrintTree, RoundTree, RunMode,
12 TraversePartialTree, TraverseTree,
13};
14use crate::util::debug::{debug_log, debug_log_node};
15use crate::util::sys::{new_vec_with_capacity, ChildrenVec, Vec};
16
17use crate::compute::{
18 compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_root_layout, round_layout,
19};
20use crate::CacheTree;
21#[cfg(feature = "block_layout")]
22use crate::{compute::compute_block_layout, LayoutBlockContainer};
23#[cfg(feature = "flexbox")]
24use crate::{compute::compute_flexbox_layout, LayoutFlexboxContainer};
25#[cfg(feature = "grid")]
26use crate::{compute::compute_grid_layout, LayoutGridContainer};
27
28#[cfg(all(feature = "detailed_layout_info", feature = "grid"))]
29use crate::compute::grid::DetailedGridInfo;
30#[cfg(feature = "detailed_layout_info")]
31use crate::tree::layout::DetailedLayoutInfo;
32
33/// The error Taffy generates on invalid operations
34pub type TaffyResult<T> = Result<T, TaffyError>;
35
36/// An error that occurs while trying to access or modify a node's children by index.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum TaffyError {
39 /// The parent node does not have a child at `child_index`. It only has `child_count` children
40 ChildIndexOutOfBounds {
41 /// The parent node whose child was being looked up
42 parent: NodeId,
43 /// The index that was looked up
44 child_index: usize,
45 /// The total number of children the parent has
46 child_count: usize,
47 },
48 /// The parent node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
49 InvalidParentNode(NodeId),
50 /// The child node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
51 InvalidChildNode(NodeId),
52 /// The supplied node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
53 InvalidInputNode(NodeId),
54}
55
56impl core::fmt::Display for TaffyError {
57 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
58 match self {
59 TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count } => {
60 write!(f, "Index (is {child_index}) should be < child_count ({child_count}) for parent node {parent:?}")
61 }
62 TaffyError::InvalidParentNode(parent) => {
63 write!(f, "Parent Node {parent:?} is not in the TaffyTree instance")
64 }
65 TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the TaffyTree instance"),
66 TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the TaffyTree instance"),
67 }
68 }
69}
70
71#[cfg(feature = "std")]
72impl std::error::Error for TaffyError {}
73
74/// Global configuration values for a TaffyTree instance
75#[derive(Debug, Clone, Copy)]
76pub(crate) struct TaffyConfig {
77 /// Whether to round layout values
78 pub(crate) use_rounding: bool,
79}
80
81impl Default for TaffyConfig {
82 fn default() -> Self {
83 Self { use_rounding: true }
84 }
85}
86
87/// Layout information for a given [`Node`](crate::node::Node)
88///
89/// Stored in a [`TaffyTree`].
90#[derive(Debug, Clone, PartialEq)]
91struct NodeData {
92 /// The layout strategy used by this node
93 pub(crate) style: Style,
94
95 /// The always unrounded results of the layout computation. We must store this separately from the rounded
96 /// layout to avoid errors from rounding already-rounded values. See <https://github.com/DioxusLabs/taffy/issues/501>.
97 pub(crate) unrounded_layout: Layout,
98
99 /// The final results of the layout computation.
100 /// These may be rounded or unrounded depending on what the `use_rounding` config setting is set to.
101 pub(crate) final_layout: Layout,
102
103 /// Whether the node has context data associated with it or not
104 pub(crate) has_context: bool,
105
106 /// The cached results of the layout computation
107 pub(crate) cache: Cache,
108
109 /// The computation result from layout algorithm
110 #[cfg(feature = "detailed_layout_info")]
111 pub(crate) detailed_layout_info: DetailedLayoutInfo,
112}
113
114impl NodeData {
115 /// Create the data for a new node
116 #[must_use]
117 pub const fn new(style: Style) -> Self {
118 Self {
119 style,
120 cache: Cache::new(),
121 unrounded_layout: Layout::new(),
122 final_layout: Layout::new(),
123 has_context: false,
124 #[cfg(feature = "detailed_layout_info")]
125 detailed_layout_info: DetailedLayoutInfo::None,
126 }
127 }
128
129 /// Marks a node and all of its ancestors as requiring relayout
130 ///
131 /// This clears any cached data and signals that the data must be recomputed.
132 #[inline]
133 pub fn mark_dirty(&mut self) {
134 self.cache.clear()
135 }
136}
137
138/// An entire tree of UI nodes. The entry point to Taffy's high-level API.
139///
140/// Allows you to build a tree of UI nodes, run Taffy's layout algorithms over that tree, and then access the resultant layout.]
141#[derive(Debug, Clone)]
142pub struct TaffyTree<NodeContext = ()> {
143 /// The [`NodeData`] for each node stored in this tree
144 nodes: SlotMap<DefaultKey, NodeData>,
145
146 /// Functions/closures that compute the intrinsic size of leaf nodes
147 node_context_data: SecondaryMap<DefaultKey, NodeContext>,
148
149 /// The children of each node
150 ///
151 /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
152 children: SlotMap<DefaultKey, ChildrenVec<NodeId>>,
153
154 /// The parents of each node
155 ///
156 /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
157 parents: SlotMap<DefaultKey, Option<NodeId>>,
158
159 /// Layout mode configuration
160 config: TaffyConfig,
161}
162
163impl Default for TaffyTree {
164 fn default() -> TaffyTree<()> {
165 TaffyTree::new()
166 }
167}
168
169/// Iterator that wraps a slice of nodes, lazily converting them to u64
170pub struct TaffyTreeChildIter<'a>(core::slice::Iter<'a, NodeId>);
171impl Iterator for TaffyTreeChildIter<'_> {
172 type Item = NodeId;
173
174 fn next(&mut self) -> Option<Self::Item> {
175 self.0.next().copied()
176 }
177}
178
179// TraversePartialTree impl for TaffyTree
180impl<NodeContext> TraversePartialTree for TaffyTree<NodeContext> {
181 type ChildIter<'a>
182 = TaffyTreeChildIter<'a>
183 where
184 Self: 'a;
185
186 #[inline(always)]
187 fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
188 TaffyTreeChildIter(self.children[parent_node_id.into()].iter())
189 }
190
191 #[inline(always)]
192 fn child_count(&self, parent_node_id: NodeId) -> usize {
193 self.children[parent_node_id.into()].len()
194 }
195
196 #[inline(always)]
197 fn get_child_id(&self, parent_node_id: NodeId, id: usize) -> NodeId {
198 self.children[parent_node_id.into()][id]
199 }
200}
201
202// TraverseTree impl for TaffyTree
203impl<NodeContext> TraverseTree for TaffyTree<NodeContext> {}
204
205// CacheTree impl for TaffyTree
206impl<NodeContext> CacheTree for TaffyTree<NodeContext> {
207 fn cache_get(
208 &self,
209 node_id: NodeId,
210 known_dimensions: Size<Option<f32>>,
211 available_space: Size<AvailableSpace>,
212 run_mode: RunMode,
213 ) -> Option<LayoutOutput> {
214 self.nodes[node_id.into()].cache.get(known_dimensions, available_space, run_mode)
215 }
216
217 fn cache_store(
218 &mut self,
219 node_id: NodeId,
220 known_dimensions: Size<Option<f32>>,
221 available_space: Size<AvailableSpace>,
222 run_mode: RunMode,
223 layout_output: LayoutOutput,
224 ) {
225 self.nodes[node_id.into()].cache.store(known_dimensions, available_space, run_mode, layout_output)
226 }
227
228 fn cache_clear(&mut self, node_id: NodeId) {
229 self.nodes[node_id.into()].cache.clear()
230 }
231}
232
233// PrintTree impl for TaffyTree
234impl<NodeContext> PrintTree for TaffyTree<NodeContext> {
235 #[inline(always)]
236 fn get_debug_label(&self, node_id: NodeId) -> &'static str {
237 let node = &self.nodes[node_id.into()];
238 let display = node.style.display;
239 let num_children = self.child_count(node_id);
240
241 match (num_children, display) {
242 (_, Display::None) => "NONE",
243 (0, _) => "LEAF",
244 #[cfg(feature = "block_layout")]
245 (_, Display::Block) => "BLOCK",
246 #[cfg(feature = "flexbox")]
247 (_, Display::Flex) => {
248 use crate::FlexDirection;
249 match node.style.flex_direction {
250 FlexDirection::Row | FlexDirection::RowReverse => "FLEX ROW",
251 FlexDirection::Column | FlexDirection::ColumnReverse => "FLEX COL",
252 }
253 }
254 #[cfg(feature = "grid")]
255 (_, Display::Grid) => "GRID",
256 }
257 }
258
259 #[inline(always)]
260 fn get_final_layout(&self, node_id: NodeId) -> &Layout {
261 if self.config.use_rounding {
262 &self.nodes[node_id.into()].final_layout
263 } else {
264 &self.nodes[node_id.into()].unrounded_layout
265 }
266 }
267}
268
269/// View over the Taffy tree that holds the tree itself along with a reference to the context
270/// and implements LayoutTree. This allows the context to be stored outside of the TaffyTree struct
271/// which makes the lifetimes of the context much more flexible.
272pub(crate) struct TaffyView<'t, NodeContext, MeasureFunction>
273where
274 MeasureFunction:
275 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
276{
277 /// A reference to the TaffyTree
278 pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
279 /// The context provided for passing to measure functions if layout is run over this struct
280 pub(crate) measure_function: MeasureFunction,
281}
282
283// TraversePartialTree impl for TaffyView
284impl<NodeContext, MeasureFunction> TraversePartialTree for TaffyView<'_, NodeContext, MeasureFunction>
285where
286 MeasureFunction:
287 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
288{
289 type ChildIter<'a>
290 = TaffyTreeChildIter<'a>
291 where
292 Self: 'a;
293
294 #[inline(always)]
295 fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
296 self.taffy.child_ids(parent_node_id)
297 }
298
299 #[inline(always)]
300 fn child_count(&self, parent_node_id: NodeId) -> usize {
301 self.taffy.child_count(parent_node_id)
302 }
303
304 #[inline(always)]
305 fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
306 self.taffy.get_child_id(parent_node_id, child_index)
307 }
308}
309
310// TraverseTree impl for TaffyView
311impl<NodeContext, MeasureFunction> TraverseTree for TaffyView<'_, NodeContext, MeasureFunction> where
312 MeasureFunction:
313 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>
314{
315}
316
317// LayoutPartialTree impl for TaffyView
318impl<NodeContext, MeasureFunction> LayoutPartialTree for TaffyView<'_, NodeContext, MeasureFunction>
319where
320 MeasureFunction:
321 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
322{
323 type CoreContainerStyle<'a>
324 = &'a Style
325 where
326 Self: 'a;
327
328 #[inline(always)]
329 fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
330 &self.taffy.nodes[node_id.into()].style
331 }
332
333 #[inline(always)]
334 fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
335 self.taffy.nodes[node_id.into()].unrounded_layout = *layout;
336 }
337
338 #[inline(always)]
339 fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
340 // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
341 // and thus that we should lay out this node using hidden layout regardless of it's own display style.
342 if inputs.run_mode == RunMode::PerformHiddenLayout {
343 debug_log!("HIDDEN");
344 return compute_hidden_layout(self, node);
345 }
346
347 // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
348 // - Return that entry if exists
349 // - Else call the passed closure (below) to compute the result
350 //
351 // If there was no cache match and a new result needs to be computed then that result will be added to the cache
352 compute_cached_layout(self, node, inputs, |tree, node, inputs| {
353 let display_mode = tree.taffy.nodes[node.into()].style.display;
354 let has_children = tree.child_count(node) > 0;
355
356 debug_log!(display_mode);
357 debug_log_node!(
358 inputs.known_dimensions,
359 inputs.parent_size,
360 inputs.available_space,
361 inputs.run_mode,
362 inputs.sizing_mode
363 );
364
365 // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
366 match (display_mode, has_children) {
367 (Display::None, _) => compute_hidden_layout(tree, node),
368 #[cfg(feature = "block_layout")]
369 (Display::Block, true) => compute_block_layout(tree, node, inputs),
370 #[cfg(feature = "flexbox")]
371 (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
372 #[cfg(feature = "grid")]
373 (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
374 (_, false) => {
375 let node_key = node.into();
376 let style = &tree.taffy.nodes[node_key].style;
377 let has_context = tree.taffy.nodes[node_key].has_context;
378 let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
379 let measure_function = |known_dimensions, available_space| {
380 (tree.measure_function)(known_dimensions, available_space, node, node_context, style)
381 };
382 compute_leaf_layout(inputs, style, measure_function)
383 }
384 }
385 })
386 }
387}
388
389impl<NodeContext, MeasureFunction> CacheTree for TaffyView<'_, NodeContext, MeasureFunction>
390where
391 MeasureFunction:
392 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
393{
394 fn cache_get(
395 &self,
396 node_id: NodeId,
397 known_dimensions: Size<Option<f32>>,
398 available_space: Size<AvailableSpace>,
399 run_mode: RunMode,
400 ) -> Option<LayoutOutput> {
401 self.taffy.nodes[node_id.into()].cache.get(known_dimensions, available_space, run_mode)
402 }
403
404 fn cache_store(
405 &mut self,
406 node_id: NodeId,
407 known_dimensions: Size<Option<f32>>,
408 available_space: Size<AvailableSpace>,
409 run_mode: RunMode,
410 layout_output: LayoutOutput,
411 ) {
412 self.taffy.nodes[node_id.into()].cache.store(known_dimensions, available_space, run_mode, layout_output)
413 }
414
415 fn cache_clear(&mut self, node_id: NodeId) {
416 self.taffy.nodes[node_id.into()].cache.clear()
417 }
418}
419
420#[cfg(feature = "block_layout")]
421impl<NodeContext, MeasureFunction> LayoutBlockContainer for TaffyView<'_, NodeContext, MeasureFunction>
422where
423 MeasureFunction:
424 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
425{
426 type BlockContainerStyle<'a>
427 = &'a Style
428 where
429 Self: 'a;
430 type BlockItemStyle<'a>
431 = &'a Style
432 where
433 Self: 'a;
434
435 #[inline(always)]
436 fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
437 self.get_core_container_style(node_id)
438 }
439
440 #[inline(always)]
441 fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
442 self.get_core_container_style(child_node_id)
443 }
444}
445
446#[cfg(feature = "flexbox")]
447impl<NodeContext, MeasureFunction> LayoutFlexboxContainer for TaffyView<'_, NodeContext, MeasureFunction>
448where
449 MeasureFunction:
450 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
451{
452 type FlexboxContainerStyle<'a>
453 = &'a Style
454 where
455 Self: 'a;
456 type FlexboxItemStyle<'a>
457 = &'a Style
458 where
459 Self: 'a;
460
461 #[inline(always)]
462 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
463 &self.taffy.nodes[node_id.into()].style
464 }
465
466 #[inline(always)]
467 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
468 &self.taffy.nodes[child_node_id.into()].style
469 }
470}
471
472#[cfg(feature = "grid")]
473impl<NodeContext, MeasureFunction> LayoutGridContainer for TaffyView<'_, NodeContext, MeasureFunction>
474where
475 MeasureFunction:
476 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
477{
478 type GridContainerStyle<'a>
479 = &'a Style
480 where
481 Self: 'a;
482 type GridItemStyle<'a>
483 = &'a Style
484 where
485 Self: 'a;
486
487 #[inline(always)]
488 fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
489 &self.taffy.nodes[node_id.into()].style
490 }
491
492 #[inline(always)]
493 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
494 &self.taffy.nodes[child_node_id.into()].style
495 }
496
497 #[inline(always)]
498 #[cfg(feature = "detailed_layout_info")]
499 fn set_detailed_grid_info(&mut self, node_id: NodeId, detailed_grid_info: DetailedGridInfo) {
500 self.taffy.nodes[node_id.into()].detailed_layout_info = DetailedLayoutInfo::Grid(Box::new(detailed_grid_info));
501 }
502}
503
504// RoundTree impl for TaffyView
505impl<NodeContext, MeasureFunction> RoundTree for TaffyView<'_, NodeContext, MeasureFunction>
506where
507 MeasureFunction:
508 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
509{
510 #[inline(always)]
511 fn get_unrounded_layout(&self, node: NodeId) -> &Layout {
512 &self.taffy.nodes[node.into()].unrounded_layout
513 }
514
515 #[inline(always)]
516 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
517 self.taffy.nodes[node_id.into()].final_layout = *layout;
518 }
519}
520
521#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
522impl<NodeContext> TaffyTree<NodeContext> {
523 /// Creates a new [`TaffyTree`]
524 ///
525 /// The default capacity of a [`TaffyTree`] is 16 nodes.
526 #[must_use]
527 pub fn new() -> Self {
528 Self::with_capacity(16)
529 }
530
531 /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
532 #[must_use]
533 pub fn with_capacity(capacity: usize) -> Self {
534 TaffyTree {
535 // TODO: make this method const upstream,
536 // so constructors here can be const
537 nodes: SlotMap::with_capacity(capacity),
538 children: SlotMap::with_capacity(capacity),
539 parents: SlotMap::with_capacity(capacity),
540 node_context_data: SecondaryMap::with_capacity(capacity),
541 config: TaffyConfig::default(),
542 }
543 }
544
545 /// Enable rounding of layout values. Rounding is enabled by default.
546 pub fn enable_rounding(&mut self) {
547 self.config.use_rounding = true;
548 }
549
550 /// Disable rounding of layout values. Rounding is enabled by default.
551 pub fn disable_rounding(&mut self) {
552 self.config.use_rounding = false;
553 }
554
555 /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
556 pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
557 let id = self.nodes.insert(NodeData::new(layout));
558 let _ = self.children.insert(new_vec_with_capacity(0));
559 let _ = self.parents.insert(None);
560
561 Ok(id.into())
562 }
563
564 /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
565 ///
566 /// Creates and adds a new leaf node with a supplied context
567 pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
568 let mut data = NodeData::new(layout);
569 data.has_context = true;
570
571 let id = self.nodes.insert(data);
572 self.node_context_data.insert(id, context);
573
574 let _ = self.children.insert(new_vec_with_capacity(0));
575 let _ = self.parents.insert(None);
576
577 Ok(id.into())
578 }
579
580 /// Creates and adds a new node, which may have any number of `children`
581 pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
582 let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
583
584 for child in children {
585 self.parents[(*child).into()] = Some(id);
586 }
587
588 let _ = self.children.insert(children.iter().copied().collect::<_>());
589 let _ = self.parents.insert(None);
590
591 Ok(id)
592 }
593
594 /// Drops all nodes in the tree
595 pub fn clear(&mut self) {
596 self.nodes.clear();
597 self.children.clear();
598 self.parents.clear();
599 }
600
601 /// Remove a specific node from the tree and drop it
602 ///
603 /// Returns the id of the node removed.
604 pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
605 let key = node.into();
606 if let Some(parent) = self.parents[key] {
607 if let Some(children) = self.children.get_mut(parent.into()) {
608 children.retain(|f| *f != node);
609 }
610 }
611
612 // Remove "parent" references to a node when removing that node
613 if let Some(children) = self.children.get(key) {
614 for child in children.iter().copied() {
615 self.parents[child.into()] = None;
616 }
617 }
618
619 let _ = self.children.remove(key);
620 let _ = self.parents.remove(key);
621 let _ = self.nodes.remove(key);
622
623 Ok(node)
624 }
625
626 /// Sets the context data associated with the node
627 pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
628 let key = node.into();
629 if let Some(measure) = measure {
630 self.nodes[key].has_context = true;
631 self.node_context_data.insert(key, measure);
632 } else {
633 self.nodes[key].has_context = false;
634 self.node_context_data.remove(key);
635 }
636
637 self.mark_dirty(node)?;
638
639 Ok(())
640 }
641
642 /// Gets a reference to the the context data associated with the node
643 pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
644 self.node_context_data.get(node.into())
645 }
646
647 /// Gets a mutable reference to the the context data associated with the node
648 pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
649 self.node_context_data.get_mut(node.into())
650 }
651
652 /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
653 pub fn get_disjoint_node_context_mut<const N: usize>(
654 &mut self,
655 keys: [NodeId; N],
656 ) -> Option<[&mut NodeContext; N]> {
657 self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
658 }
659
660 /// Adds a `child` node under the supplied `parent`
661 pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
662 let parent_key = parent.into();
663 let child_key = child.into();
664 self.parents[child_key] = Some(parent);
665 self.children[parent_key].push(child);
666 self.mark_dirty(parent)?;
667
668 Ok(())
669 }
670
671 /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
672 pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
673 let parent_key = parent.into();
674
675 let child_count = self.children[parent_key].len();
676 if child_index > child_count {
677 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
678 }
679
680 self.parents[child.into()] = Some(parent);
681 self.children[parent_key].insert(child_index, child);
682 self.mark_dirty(parent)?;
683
684 Ok(())
685 }
686
687 /// Directly sets the `children` of the supplied `parent`
688 pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
689 let parent_key = parent.into();
690
691 // Remove node as parent from all its current children.
692 for child in &self.children[parent_key] {
693 self.parents[(*child).into()] = None;
694 }
695
696 // Build up relation node <-> child
697 for &child in children {
698 // Remove child from previous parent
699 if let Some(previous_parent) = self.parents[child.into()] {
700 self.remove_child(previous_parent, child).unwrap();
701 }
702 self.parents[child.into()] = Some(parent);
703 }
704
705 let parent_children = &mut self.children[parent_key];
706 parent_children.clear();
707 children.iter().for_each(|child| parent_children.push(*child));
708
709 self.mark_dirty(parent)?;
710
711 Ok(())
712 }
713
714 /// Removes the `child` of the parent `node`
715 ///
716 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
717 pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
718 let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
719 self.remove_child_at_index(parent, index)
720 }
721
722 /// Removes the child at the given `index` from the `parent`
723 ///
724 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
725 pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
726 let parent_key = parent.into();
727 let child_count = self.children[parent_key].len();
728 if child_index >= child_count {
729 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
730 }
731
732 let child = self.children[parent_key].remove(child_index);
733 self.parents[child.into()] = None;
734
735 self.mark_dirty(parent)?;
736
737 Ok(child)
738 }
739
740 /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
741 ///
742 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
743 pub fn replace_child_at_index(
744 &mut self,
745 parent: NodeId,
746 child_index: usize,
747 new_child: NodeId,
748 ) -> TaffyResult<NodeId> {
749 let parent_key = parent.into();
750
751 let child_count = self.children[parent_key].len();
752 if child_index >= child_count {
753 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
754 }
755
756 self.parents[new_child.into()] = Some(parent);
757 let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
758 self.parents[old_child.into()] = None;
759
760 self.mark_dirty(parent)?;
761
762 Ok(old_child)
763 }
764
765 /// Returns the child node of the parent `node` at the provided `child_index`
766 pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
767 let parent_key = parent.into();
768 let child_count = self.children[parent_key].len();
769 if child_index >= child_count {
770 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
771 }
772
773 Ok(self.children[parent_key][child_index])
774 }
775
776 /// Returns the total number of nodes in the tree
777 pub fn total_node_count(&self) -> usize {
778 self.nodes.len()
779 }
780
781 /// Returns the `NodeId` of the parent node of the specified node (if it exists)
782 ///
783 /// - Return None if the specified node has no parent
784 /// - Panics if the specified node does not exist
785 pub fn parent(&self, child_id: NodeId) -> Option<NodeId> {
786 self.parents[child_id.into()]
787 }
788
789 /// Returns a list of children that belong to the parent node
790 pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
791 Ok(self.children[parent.into()].iter().copied().collect::<_>())
792 }
793
794 /// Sets the [`Style`] of the provided `node`
795 pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
796 self.nodes[node.into()].style = style;
797 self.mark_dirty(node)?;
798 Ok(())
799 }
800
801 /// Gets the [`Style`] of the provided `node`
802 pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
803 Ok(&self.nodes[node.into()].style)
804 }
805
806 /// Return this node layout relative to its parent
807 pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
808 if self.config.use_rounding {
809 Ok(&self.nodes[node.into()].final_layout)
810 } else {
811 Ok(&self.nodes[node.into()].unrounded_layout)
812 }
813 }
814
815 /// Returns this node layout with unrounded values relative to its parent.
816 pub fn unrounded_layout(&self, node: NodeId) -> &Layout {
817 &self.nodes[node.into()].unrounded_layout
818 }
819
820 /// Get the "detailed layout info" for a node.
821 ///
822 /// Currently this is only implemented for CSS Grid containers where it contains
823 /// the computed size of each grid track and the computed placement of each grid item
824 #[cfg(feature = "detailed_layout_info")]
825 pub fn detailed_layout_info(&mut self, node_id: NodeId) -> &DetailedLayoutInfo {
826 &self.nodes[node_id.into()].detailed_layout_info
827 }
828
829 /// Marks the layout of this node and its ancestors as outdated
830 ///
831 /// WARNING: this may stack-overflow if the tree contains a cycle
832 pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
833 /// WARNING: this will stack-overflow if the tree contains a cycle
834 fn mark_dirty_recursive(
835 nodes: &mut SlotMap<DefaultKey, NodeData>,
836 parents: &SlotMap<DefaultKey, Option<NodeId>>,
837 node_key: DefaultKey,
838 ) {
839 nodes[node_key].mark_dirty();
840
841 if let Some(Some(node)) = parents.get(node_key) {
842 mark_dirty_recursive(nodes, parents, (*node).into());
843 }
844 }
845
846 mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
847
848 Ok(())
849 }
850
851 /// Indicates whether the layout of this node needs to be recomputed
852 pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
853 Ok(self.nodes[node.into()].cache.is_empty())
854 }
855
856 /// Updates the stored layout of the provided `node` and its children
857 pub fn compute_layout_with_measure<MeasureFunction>(
858 &mut self,
859 node_id: NodeId,
860 available_space: Size<AvailableSpace>,
861 measure_function: MeasureFunction,
862 ) -> Result<(), TaffyError>
863 where
864 MeasureFunction:
865 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
866 {
867 let use_rounding = self.config.use_rounding;
868 let mut taffy_view = TaffyView { taffy: self, measure_function };
869 compute_root_layout(&mut taffy_view, node_id, available_space);
870 if use_rounding {
871 round_layout(&mut taffy_view, node_id);
872 }
873 Ok(())
874 }
875
876 /// Updates the stored layout of the provided `node` and its children
877 pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
878 self.compute_layout_with_measure(node, available_space, |_, _, _, _, _| Size::ZERO)
879 }
880
881 /// Prints a debug representation of the tree's layout
882 #[cfg(feature = "std")]
883 pub fn print_tree(&mut self, root: NodeId) {
884 crate::util::print_tree(self, root)
885 }
886
887 /// Returns an instance of LayoutTree representing the TaffyTree
888 #[cfg(test)]
889 pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + CacheTree + '_ {
890 TaffyView { taffy: self, measure_function: |_, _, _, _, _| Size::ZERO }
891 }
892}
893
894#[cfg(test)]
895mod tests {
896
897 use super::*;
898 use crate::style::{Dimension, Display, FlexDirection};
899 use crate::style_helpers::*;
900 use crate::util::sys;
901
902 fn size_measure_function(
903 known_dimensions: Size<Option<f32>>,
904 _available_space: Size<AvailableSpace>,
905 _node_id: NodeId,
906 node_context: Option<&mut Size<f32>>,
907 _style: &Style,
908 ) -> Size<f32> {
909 known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
910 }
911
912 #[test]
913 fn new_should_allocate_default_capacity() {
914 const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
915 let taffy: TaffyTree<()> = TaffyTree::new();
916
917 assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
918 assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
919 assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
920 }
921
922 #[test]
923 fn test_with_capacity() {
924 const CAPACITY: usize = 8;
925 let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
926
927 assert!(taffy.children.capacity() >= CAPACITY);
928 assert!(taffy.parents.capacity() >= CAPACITY);
929 assert!(taffy.nodes.capacity() >= CAPACITY);
930 }
931
932 #[test]
933 fn test_new_leaf() {
934 let mut taffy: TaffyTree<()> = TaffyTree::new();
935
936 let res = taffy.new_leaf(Style::default());
937 assert!(res.is_ok());
938 let node = res.unwrap();
939
940 // node should be in the taffy tree and have no children
941 assert!(taffy.child_count(node) == 0);
942 }
943
944 #[test]
945 fn new_leaf_with_context() {
946 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
947
948 let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
949 assert!(res.is_ok());
950 let node = res.unwrap();
951
952 // node should be in the taffy tree and have no children
953 assert!(taffy.child_count(node) == 0);
954 }
955
956 /// Test that new_with_children works as expected
957 #[test]
958 fn test_new_with_children() {
959 let mut taffy: TaffyTree<()> = TaffyTree::new();
960 let child0 = taffy.new_leaf(Style::default()).unwrap();
961 let child1 = taffy.new_leaf(Style::default()).unwrap();
962 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
963
964 // node should have two children
965 assert_eq!(taffy.child_count(node), 2);
966 assert_eq!(taffy.children(node).unwrap()[0], child0);
967 assert_eq!(taffy.children(node).unwrap()[1], child1);
968 }
969
970 #[test]
971 fn remove_node_should_remove() {
972 let mut taffy: TaffyTree<()> = TaffyTree::new();
973
974 let node = taffy.new_leaf(Style::default()).unwrap();
975
976 let _ = taffy.remove(node).unwrap();
977 }
978
979 #[test]
980 fn remove_node_should_detach_hierarchy() {
981 let mut taffy: TaffyTree<()> = TaffyTree::new();
982
983 // Build a linear tree layout: <0> <- <1> <- <2>
984 let node2 = taffy.new_leaf(Style::default()).unwrap();
985 let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
986 let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
987
988 // Both node0 and node1 should have 1 child nodes
989 assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
990 assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
991
992 // Disconnect the tree: <0> <2>
993 let _ = taffy.remove(node1).unwrap();
994
995 // Both remaining nodes should have no child nodes
996 assert!(taffy.children(node0).unwrap().is_empty());
997 assert!(taffy.children(node2).unwrap().is_empty());
998 }
999
1000 #[test]
1001 fn remove_last_node() {
1002 let mut taffy: TaffyTree<()> = TaffyTree::new();
1003
1004 let parent = taffy.new_leaf(Style::default()).unwrap();
1005 let child = taffy.new_leaf(Style::default()).unwrap();
1006 taffy.add_child(parent, child).unwrap();
1007
1008 taffy.remove(child).unwrap();
1009 taffy.remove(parent).unwrap();
1010 }
1011
1012 #[test]
1013 fn set_measure() {
1014 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
1015 let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
1016 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1017 assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
1018
1019 taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
1020 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1021 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
1022 }
1023
1024 #[test]
1025 fn set_measure_of_previously_unmeasured_node() {
1026 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
1027 let node = taffy.new_leaf(Style::default()).unwrap();
1028 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1029 assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
1030
1031 taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
1032 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
1033 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
1034 }
1035
1036 /// Test that adding `add_child()` works
1037 #[test]
1038 fn add_child() {
1039 let mut taffy: TaffyTree<()> = TaffyTree::new();
1040 let node = taffy.new_leaf(Style::default()).unwrap();
1041 assert_eq!(taffy.child_count(node), 0);
1042
1043 let child0 = taffy.new_leaf(Style::default()).unwrap();
1044 taffy.add_child(node, child0).unwrap();
1045 assert_eq!(taffy.child_count(node), 1);
1046
1047 let child1 = taffy.new_leaf(Style::default()).unwrap();
1048 taffy.add_child(node, child1).unwrap();
1049 assert_eq!(taffy.child_count(node), 2);
1050 }
1051
1052 #[test]
1053 fn insert_child_at_index() {
1054 let mut taffy: TaffyTree<()> = TaffyTree::new();
1055
1056 let child0 = taffy.new_leaf(Style::default()).unwrap();
1057 let child1 = taffy.new_leaf(Style::default()).unwrap();
1058 let child2 = taffy.new_leaf(Style::default()).unwrap();
1059
1060 let node = taffy.new_leaf(Style::default()).unwrap();
1061 assert_eq!(taffy.child_count(node), 0);
1062
1063 taffy.insert_child_at_index(node, 0, child0).unwrap();
1064 assert_eq!(taffy.child_count(node), 1);
1065 assert_eq!(taffy.children(node).unwrap()[0], child0);
1066
1067 taffy.insert_child_at_index(node, 0, child1).unwrap();
1068 assert_eq!(taffy.child_count(node), 2);
1069 assert_eq!(taffy.children(node).unwrap()[0], child1);
1070 assert_eq!(taffy.children(node).unwrap()[1], child0);
1071
1072 taffy.insert_child_at_index(node, 1, child2).unwrap();
1073 assert_eq!(taffy.child_count(node), 3);
1074 assert_eq!(taffy.children(node).unwrap()[0], child1);
1075 assert_eq!(taffy.children(node).unwrap()[1], child2);
1076 assert_eq!(taffy.children(node).unwrap()[2], child0);
1077 }
1078
1079 #[test]
1080 fn set_children() {
1081 let mut taffy: TaffyTree<()> = TaffyTree::new();
1082
1083 let child0 = taffy.new_leaf(Style::default()).unwrap();
1084 let child1 = taffy.new_leaf(Style::default()).unwrap();
1085 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1086
1087 assert_eq!(taffy.child_count(node), 2);
1088 assert_eq!(taffy.children(node).unwrap()[0], child0);
1089 assert_eq!(taffy.children(node).unwrap()[1], child1);
1090
1091 let child2 = taffy.new_leaf(Style::default()).unwrap();
1092 let child3 = taffy.new_leaf(Style::default()).unwrap();
1093 taffy.set_children(node, &[child2, child3]).unwrap();
1094
1095 assert_eq!(taffy.child_count(node), 2);
1096 assert_eq!(taffy.children(node).unwrap()[0], child2);
1097 assert_eq!(taffy.children(node).unwrap()[1], child3);
1098 }
1099
1100 /// Test that removing a child works
1101 #[test]
1102 fn remove_child() {
1103 let mut taffy: TaffyTree<()> = TaffyTree::new();
1104 let child0 = taffy.new_leaf(Style::default()).unwrap();
1105 let child1 = taffy.new_leaf(Style::default()).unwrap();
1106 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1107
1108 assert_eq!(taffy.child_count(node), 2);
1109
1110 taffy.remove_child(node, child0).unwrap();
1111 assert_eq!(taffy.child_count(node), 1);
1112 assert_eq!(taffy.children(node).unwrap()[0], child1);
1113
1114 taffy.remove_child(node, child1).unwrap();
1115 assert_eq!(taffy.child_count(node), 0);
1116 }
1117
1118 #[test]
1119 fn remove_child_at_index() {
1120 let mut taffy: TaffyTree<()> = TaffyTree::new();
1121 let child0 = taffy.new_leaf(Style::default()).unwrap();
1122 let child1 = taffy.new_leaf(Style::default()).unwrap();
1123 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1124
1125 assert_eq!(taffy.child_count(node), 2);
1126
1127 taffy.remove_child_at_index(node, 0).unwrap();
1128 assert_eq!(taffy.child_count(node), 1);
1129 assert_eq!(taffy.children(node).unwrap()[0], child1);
1130
1131 taffy.remove_child_at_index(node, 0).unwrap();
1132 assert_eq!(taffy.child_count(node), 0);
1133 }
1134
1135 // Related to: https://github.com/DioxusLabs/taffy/issues/510
1136 #[test]
1137 fn remove_child_updates_parents() {
1138 let mut taffy: TaffyTree<()> = TaffyTree::new();
1139
1140 let parent = taffy.new_leaf(Style::default()).unwrap();
1141 let child = taffy.new_leaf(Style::default()).unwrap();
1142
1143 taffy.add_child(parent, child).unwrap();
1144
1145 taffy.remove(parent).unwrap();
1146
1147 // Once the parent is removed this shouldn't panic.
1148 assert!(taffy.set_children(child, &[]).is_ok());
1149 }
1150
1151 #[test]
1152 fn replace_child_at_index() {
1153 let mut taffy: TaffyTree<()> = TaffyTree::new();
1154
1155 let child0 = taffy.new_leaf(Style::default()).unwrap();
1156 let child1 = taffy.new_leaf(Style::default()).unwrap();
1157
1158 let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
1159 assert_eq!(taffy.child_count(node), 1);
1160 assert_eq!(taffy.children(node).unwrap()[0], child0);
1161
1162 taffy.replace_child_at_index(node, 0, child1).unwrap();
1163 assert_eq!(taffy.child_count(node), 1);
1164 assert_eq!(taffy.children(node).unwrap()[0], child1);
1165 }
1166 #[test]
1167 fn test_child_at_index() {
1168 let mut taffy: TaffyTree<()> = TaffyTree::new();
1169 let child0 = taffy.new_leaf(Style::default()).unwrap();
1170 let child1 = taffy.new_leaf(Style::default()).unwrap();
1171 let child2 = taffy.new_leaf(Style::default()).unwrap();
1172 let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
1173
1174 assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
1175 assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
1176 assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
1177 }
1178 #[test]
1179 fn test_child_count() {
1180 let mut taffy: TaffyTree<()> = TaffyTree::new();
1181 let child0 = taffy.new_leaf(Style::default()).unwrap();
1182 let child1 = taffy.new_leaf(Style::default()).unwrap();
1183 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1184
1185 assert!(taffy.child_count(node) == 2);
1186 assert!(taffy.child_count(child0) == 0);
1187 assert!(taffy.child_count(child1) == 0);
1188 }
1189
1190 #[allow(clippy::vec_init_then_push)]
1191 #[test]
1192 fn test_children() {
1193 let mut taffy: TaffyTree<()> = TaffyTree::new();
1194 let child0 = taffy.new_leaf(Style::default()).unwrap();
1195 let child1 = taffy.new_leaf(Style::default()).unwrap();
1196 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1197
1198 let mut children = sys::Vec::new();
1199 children.push(child0);
1200 children.push(child1);
1201
1202 let children_result = taffy.children(node).unwrap();
1203 assert_eq!(children_result, children);
1204
1205 assert!(taffy.children(child0).unwrap().is_empty());
1206 }
1207 #[test]
1208 fn test_set_style() {
1209 let mut taffy: TaffyTree<()> = TaffyTree::new();
1210
1211 let node = taffy.new_leaf(Style::default()).unwrap();
1212 assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1213
1214 taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1215 assert_eq!(taffy.style(node).unwrap().display, Display::None);
1216 }
1217 #[test]
1218 fn test_style() {
1219 let mut taffy: TaffyTree<()> = TaffyTree::new();
1220
1221 let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1222
1223 let node = taffy.new_leaf(style.clone()).unwrap();
1224
1225 let res = taffy.style(node);
1226 assert!(res.is_ok());
1227 assert!(res.unwrap() == &style);
1228 }
1229 #[test]
1230 fn test_layout() {
1231 let mut taffy: TaffyTree<()> = TaffyTree::new();
1232 let node = taffy.new_leaf(Style::default()).unwrap();
1233
1234 // TODO: Improve this test?
1235 let res = taffy.layout(node);
1236 assert!(res.is_ok());
1237 }
1238
1239 #[test]
1240 fn test_mark_dirty() {
1241 let mut taffy: TaffyTree<()> = TaffyTree::new();
1242 let child0 = taffy.new_leaf(Style::default()).unwrap();
1243 let child1 = taffy.new_leaf(Style::default()).unwrap();
1244 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1245
1246 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1247
1248 assert_eq!(taffy.dirty(child0), Ok(false));
1249 assert_eq!(taffy.dirty(child1), Ok(false));
1250 assert_eq!(taffy.dirty(node), Ok(false));
1251
1252 taffy.mark_dirty(node).unwrap();
1253 assert_eq!(taffy.dirty(child0), Ok(false));
1254 assert_eq!(taffy.dirty(child1), Ok(false));
1255 assert_eq!(taffy.dirty(node), Ok(true));
1256
1257 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1258 taffy.mark_dirty(child0).unwrap();
1259 assert_eq!(taffy.dirty(child0), Ok(true));
1260 assert_eq!(taffy.dirty(child1), Ok(false));
1261 assert_eq!(taffy.dirty(node), Ok(true));
1262 }
1263
1264 #[test]
1265 fn compute_layout_should_produce_valid_result() {
1266 let mut taffy: TaffyTree<()> = TaffyTree::new();
1267 let node_result = taffy.new_leaf(Style {
1268 size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1269 ..Default::default()
1270 });
1271 assert!(node_result.is_ok());
1272 let node = node_result.unwrap();
1273 let layout_result = taffy.compute_layout(
1274 node,
1275 Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1276 );
1277 assert!(layout_result.is_ok());
1278 }
1279
1280 #[test]
1281 fn make_sure_layout_location_is_top_left() {
1282 use crate::prelude::Rect;
1283
1284 let mut taffy: TaffyTree<()> = TaffyTree::new();
1285
1286 let node = taffy
1287 .new_leaf(Style {
1288 size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1289 ..Default::default()
1290 })
1291 .unwrap();
1292
1293 let root = taffy
1294 .new_with_children(
1295 Style {
1296 size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1297 padding: Rect {
1298 left: length(10f32),
1299 right: length(20f32),
1300 top: length(30f32),
1301 bottom: length(40f32),
1302 },
1303 ..Default::default()
1304 },
1305 &[node],
1306 )
1307 .unwrap();
1308
1309 taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1310
1311 // If Layout::location represents top-left coord, 'node' location
1312 // must be (due applied 'root' padding): {x: 10, y: 30}.
1313 //
1314 // It's important, since result will be different for each other
1315 // coordinate space:
1316 // - bottom-left: {x: 10, y: 40}
1317 // - top-right: {x: 20, y: 30}
1318 // - bottom-right: {x: 20, y: 40}
1319 let layout = taffy.layout(node).unwrap();
1320 assert_eq!(layout.location.x, 10f32);
1321 assert_eq!(layout.location.y, 30f32);
1322 }
1323
1324 #[test]
1325 fn set_children_reparents() {
1326 let mut taffy: TaffyTree<()> = TaffyTree::new();
1327 let child = taffy.new_leaf(Style::default()).unwrap();
1328 let old_parent = taffy.new_with_children(Style::default(), &[child]).unwrap();
1329
1330 let new_parent = taffy.new_leaf(Style::default()).unwrap();
1331 taffy.set_children(new_parent, &[child]).unwrap();
1332
1333 assert!(taffy.children(old_parent).unwrap().is_empty());
1334 }
1335}