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