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