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