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