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