tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5544Rust 88Markdown 11TOML 91926 Sutichaykuna

Refactor flexbox algorithm into smaller parts (#88)

* Extract cache check into new function

* Move flexbox algorithm constants to a struct

This will make it easier to pass them around to the functions implementing each step of the algorithm.

* Fix Clippy error

* Move flexbox algorithm step 2 to new function

* Move flexbox algorithm step 1 to new function

* Move flexbox algorithm step 3 to new function

* Move flexbox algorithm step 5 to new function

* Move flexbox algorithm step 6 to new function

* Move flexbox algorithm step 7 to new function

* Move flexbox algorithm step 8 to new function

* Move flexbox algorithm step 9 to new function

* Move flexbox algorithm step 11 to new function

* Fix copy & paste error in documentation

* Move flexbox algorithm step 12 to new function

* Move flexbox algorithm step 13 to new function

* Move flexbox algorithm step 14 to new function

* Move flexbox algorithm step 15 to new function

* Move flexbox algorithm step 16 to new function

* Move flexbox algorithm final layout step to new function

* Move flexbox algorithm absolute layout step to new function

* Move flexbox algorithm calculate children baseline step to new function

* Remove allow(clippy::cognitive_complexity) for flexbox algorithm

* Add inline annotations to flexbox algorithm steps

* Add TODO

Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>

* Add TODO

Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>

* Fix broken import

Co-authored-by: Tim Jentzsch <tim-jentzsch@gmx.de>
Co-authored-by: Andreas Weibye <13300393+Weibye@users.noreply.github.com>

1ea60b5f6120d9e25e3736f092c39b069444eea9 · ruwaq Alice Cecile · (4 wata ñawpaq) · tayta 7d9382ab9 · kay commitpi sach'ata qhaway

Semántico sayk'uy · 21

1 qillqakuna · +1078 −726

diff --git a/src/algo.rs b/src/algo.rs
index 3ae8aa712..8a43094d6 100644
--- a/src/algo.rs
+++ b/src/algo.rs
@@ -9,6 +9,7 @@ use crate::number::{MinMax, OrElse};
 use crate::prelude::Number;
 use crate::result;
 use crate::style::{AlignContent, AlignSelf, Dimension, Display, FlexWrap, JustifyContent, PositionType};
+use crate::style::{FlexDirection, Style};
 use crate::sys;
 
 #[derive(Debug, Clone)]
@@ -53,6 +54,22 @@ struct FlexLine<'a> {
     offset_cross: f32,
 }
 
+/// Constant values that can be reused for the flexbox algorithm.
+struct AlgoConstants {
+    dir: FlexDirection,
+    is_row: bool,
+    is_column: bool,
+    is_wrap_reverse: bool,
+
+    margin: Rect<f32>,
+    border: Rect<f32>,
+    padding_border: Rect<f32>,
+
+    node_inner_size: Size<Number>,
+    container_size: Size<f32>,
+    inner_container_size: Size<f32>,
+}
+
 impl Forest {
     pub(crate) fn compute(&mut self, root: NodeId, size: Size<Number>) {
         let style = self.nodes[root].style;
@@ -123,18 +140,16 @@ impl Forest {
         }
     }
 
-    #[allow(clippy::cognitive_complexity)]
-    fn compute_internal(
+    /// Try to get the computation result from the cache.
+    #[inline]
+    fn compute_from_cache(
         &mut self,
         node: NodeId,
         node_size: Size<Number>,
         parent_size: Size<Number>,
         perform_layout: bool,
         main_size: bool,
-    ) -> ComputeResult {
-        self.nodes[node].is_dirty = false;
-
-        // First we check if we have a result for the given input
+    ) -> Option<ComputeResult> {
         if let Some(ref cache) = self.cache(node, main_size) {
             if cache.perform_layout || !perform_layout {
                 let width_compatible = if let Number::Defined(width) = node_size.width {
@@ -150,18 +165,21 @@ impl Forest {
                 };
 
                 if width_compatible && height_compatible {
-                    return cache.result.clone();
+                    return Some(cache.result.clone());
                 }
 
                 if cache.node_size == node_size && cache.parent_size == parent_size {
-                    return cache.result.clone();
+                    return Some(cache.result.clone());
                 }
             }
         }
 
-        // Define some general constants we will need for the remainder
-        // of the algorithm.
+        None
+    }
 
+    /// Compute constants that can be reused during the flexbox algorithm.
+    #[inline]
+    fn compute_constants(&self, node: NodeId, node_size: Size<Number>, parent_size: Size<Number>) -> AlgoConstants {
         let dir = self.nodes[node].style.flex_direction;
         let is_row = dir.is_row();
         let is_column = dir.is_column();
@@ -183,66 +201,45 @@ impl Forest {
             height: node_size.height - padding_border.vertical(),
         };
 
-        let mut container_size = Size::zero();
-        let mut inner_container_size = Size::zero();
-
-        // If this is a leaf node we can skip a lot of this function in some cases
-        if self.children[node].is_empty() {
-            if node_size.width.is_defined() && node_size.height.is_defined() {
-                return ComputeResult { size: node_size.map(|s| s.or_else(0.0)) };
-            }
-
-            if let Some(ref measure) = self.nodes[node].measure {
-                let result = match measure {
-                    MeasureFunc::Raw(measure) => ComputeResult { size: measure(node_size) },
-                    #[cfg(any(feature = "std", feature = "alloc"))]
-                    MeasureFunc::Boxed(measure) => ComputeResult { size: measure(node_size) },
-                };
-                *self.cache(node, main_size) =
-                    Some(result::Cache { node_size, parent_size, perform_layout, result: result.clone() });
-                return result;
-            }
+        let container_size = Size::zero();
+        let inner_container_size = Size::zero();
 
-            return ComputeResult {
-                size: Size {
-                    width: node_size.width.or_else(0.0) + padding_border.horizontal(),
-                    height: node_size.height.or_else(0.0) + padding_border.vertical(),
-                },
-            };
+        AlgoConstants {
+            dir,
+            is_row,
+            is_column,
+            is_wrap_reverse,
+            margin,
+            border,
+            padding_border,
+            node_inner_size,
+            container_size,
+            inner_container_size,
         }
+    }
 
-        // 9.2. Line Length Determination
-
-        // 1. Generate anonymous flex items as described in §4 Flex Items.
-
-        // 2. Determine the available main and cross space for the flex items.
-        //    For each dimension, if that dimension of the flex container’s content box
-        //    is a definite size, use that; if that dimension of the flex container is
-        //    being sized under a min or max-content constraint, the available space in
-        //    that dimension is that constraint; otherwise, subtract the flex container’s
-        //    margin, border, and padding from the space available to the flex container
-        //    in that dimension and use that value. This might result in an infinite value.
-
-        let available_space = Size {
-            width: node_size.width.or_else(parent_size.width - margin.horizontal()) - padding_border.horizontal(),
-            height: node_size.height.or_else(parent_size.height - margin.vertical()) - padding_border.vertical(),
-        };
-
-        let mut flex_items: sys::Vec<FlexItem> = self.children[node]
+    /// Generate anonymous flex items.
+    ///
+    /// # [9.1. Initial Setup](https://www.w3.org/TR/css-flexbox-1/#box-manip)
+    ///
+    /// - [**Generate anonymous flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-anon-box) as described in [§4 Flex Items](https://www.w3.org/TR/css-flexbox-1/#flex-items).
+    #[inline]
+    fn generate_anonymous_flex_items(&self, node: NodeId, constants: &AlgoConstants) -> sys::Vec<FlexItem> {
+        self.children[node]
             .iter()
             .map(|child| (child, &self.nodes[*child].style))
             .filter(|(_, style)| style.position_type != PositionType::Absolute)
             .filter(|(_, style)| style.display != Display::None)
             .map(|(child, child_style)| FlexItem {
                 node: *child,
-                size: child_style.size.resolve(node_inner_size),
-                min_size: child_style.min_size.resolve(node_inner_size),
-                max_size: child_style.max_size.resolve(node_inner_size),
+                size: child_style.size.resolve(constants.node_inner_size),
+                min_size: child_style.min_size.resolve(constants.node_inner_size),
+                max_size: child_style.max_size.resolve(constants.node_inner_size),
 
-                position: child_style.position.zip_size(node_inner_size, |p, s| p.resolve(s)),
-                margin: child_style.margin.map(|m| m.resolve(node_inner_size.width).or_else(0.0)),
-                padding: child_style.padding.map(|p| p.resolve(node_inner_size.width).or_else(0.0)),
-                border: child_style.border.map(|b| b.resolve(node_inner_size.width).or_else(0.0)),
+                position: child_style.position.zip_size(constants.node_inner_size, |p, s| p.resolve(s)),
+                margin: child_style.margin.map(|m| m.resolve(constants.node_inner_size.width).or_else(0.0)),
+                padding: child_style.padding.map(|p| p.resolve(constants.node_inner_size.width).or_else(0.0)),
+                border: child_style.border.map(|b| b.resolve(constants.node_inner_size.width).or_else(0.0)),
 
                 flex_basis: 0.0,
                 inner_flex_basis: 0.0,
@@ -259,20 +256,75 @@ impl Forest {
                 offset_main: 0.0,
                 offset_cross: 0.0,
             })
-            .collect();
+            .collect()
+    }
 
-        let has_baseline_child = flex_items
-            .iter()
-            .any(|child| self.nodes[child.node].style.align_self(&self.nodes[node].style) == AlignSelf::Baseline);
+    /// Determine the available main and cross space for the flex items.
+    ///
+    /// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
+    ///
+    /// - [**Determine the available main and cross space for the flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-available).
+    /// For each dimension, if that dimension of the flex container’s content box is a definite size, use that;
+    /// if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint;
+    /// otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value.
+    /// **This might result in an infinite value**.
+    #[inline]
+    fn determine_available_space(
+        node_size: Size<Number>,
+        parent_size: Size<Number>,
+        constants: &AlgoConstants,
+    ) -> Size<Number> {
+        Size {
+            width: node_size.width.or_else(parent_size.width - constants.margin.horizontal())
+                - constants.padding_border.horizontal(),
+            height: node_size.height.or_else(parent_size.height - constants.margin.vertical())
+                - constants.padding_border.vertical(),
+        }
+    }
 
-        // TODO - this does not follow spec. See commented out code below
-        // 3. Determine the flex base size and hypothetical main size of each item:
-        for child in &mut flex_items {
+    /// Determine the flex base size and hypothetical main size of each item.
+    ///
+    /// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
+    ///
+    /// - [**Determine the flex base size and hypothetical main size of each item:**](https://www.w3.org/TR/css-flexbox-1/#algo-main-item)
+    ///
+    ///     - A. If the item has a definite used flex basis, that’s the flex base size.
+    ///
+    ///     - B. If the flex item has ...
+    ///
+    ///         - an intrinsic aspect ratio,
+    ///         - a used flex basis of content, and
+    ///         - a definite cross size,
+    ///
+    ///     then the flex base size is calculated from its inner cross size and the flex item’s intrinsic aspect ratio.
+    ///
+    ///     - C. If the used flex basis is content or depends on its available space, and the flex container is being sized under a min-content
+    ///         or max-content constraint (e.g. when performing automatic table layout \[CSS21\]), size the item under that constraint.
+    ///         The flex base size is the item’s resulting main size.
+    ///
+    ///     - E. Otherwise, size the item into the available space using its used flex basis in place of its main size, treating a value of content as max-content.
+    ///         If a cross size is needed to determine the main size (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
+    ///         in this calculation use fit-content as the flex item’s cross size. The flex base size is the item’s resulting main size.
+    ///
+    ///     When determining the flex base size, the item’s min and max main sizes are ignored (no clamping occurs).
+    ///     Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
+    ///     (For example, an item with a specified size of zero, positive padding, and box-sizing: border-box will have an outer flex base size of zero—and hence a negative inner flex base size.)
+    #[inline]
+    fn determine_flex_base_size(
+        &mut self,
+        node: NodeId,
+        node_size: Size<Number>,
+        constants: &AlgoConstants,
+        available_space: Size<Number>,
+        flex_items: &mut sys::Vec<FlexItem>,
+    ) {
+        // TODO - this does not follow spec. See the TODOs below
+        for child in flex_items.iter_mut() {
             let child_style = self.nodes[child.node].style;
 
             // A. If the item has a definite used flex basis, that’s the flex base size.
 
-            let flex_basis = child_style.flex_basis.resolve(node_inner_size.main(dir));
+            let flex_basis = child_style.flex_basis.resolve(constants.node_inner_size.main(constants.dir));
             if flex_basis.is_defined() {
                 child.flex_basis = flex_basis.or_else(0.0);
                 continue;
@@ -284,7 +336,7 @@ impl Forest {
             //    cross size and the flex item’s intrinsic aspect ratio.
 
             if let Defined(ratio) = child_style.aspect_ratio {
-                if let Defined(cross) = node_size.cross(dir) {
+                if let Defined(cross) = node_size.cross(constants.dir) {
                     if child_style.flex_basis == Dimension::Auto {
                         child.flex_basis = cross * ratio;
                         continue;
@@ -317,7 +369,7 @@ impl Forest {
 
             let width: Number = if !child.size.width.is_defined()
                 && child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
-                && is_column
+                && constants.is_column
             {
                 available_space.width
             } else {
@@ -326,7 +378,7 @@ impl Forest {
 
             let height: Number = if !child.size.height.is_defined()
                 && child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
-                && is_row
+                && constants.is_row
             {
                 available_space.height
             } else {
@@ -345,16 +397,17 @@ impl Forest {
                     true,
                 )
                 .size
-                .main(dir)
-                .maybe_max(child.min_size.main(dir))
-                .maybe_min(child.max_size.main(dir));
+                .main(constants.dir)
+                .maybe_max(child.min_size.main(constants.dir))
+                .maybe_min(child.max_size.main(constants.dir));
         }
 
         // The hypothetical main size is the item’s flex base size clamped according to its
         // used min and max main sizes (and flooring the content box size at zero).
 
-        for child in &mut flex_items {
-            child.inner_flex_basis = child.flex_basis - child.padding.main(dir) - child.border.main(dir);
+        for child in flex_items {
+            child.inner_flex_basis =
+                child.flex_basis - child.padding.main(constants.dir) - child.border.main(constants.dir);
 
             // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
             // The following logic was developed not from the spec but by trail and error looking into how
@@ -363,349 +416,371 @@ impl Forest {
             let min_main = self
                 .compute_internal(child.node, Size::undefined(), available_space, false, false)
                 .size
-                .main(dir)
-                .maybe_max(child.min_size.main(dir))
-                .maybe_min(child.size.main(dir))
+                .main(constants.dir)
+                .maybe_max(child.min_size.main(constants.dir))
+                .maybe_min(child.size.main(constants.dir))
                 .into();
 
-            child
-                .hypothetical_inner_size
-                .set_main(dir, child.flex_basis.maybe_max(min_main).maybe_min(child.max_size.main(dir)));
+            child.hypothetical_inner_size.set_main(
+                constants.dir,
+                child.flex_basis.maybe_max(min_main).maybe_min(child.max_size.main(constants.dir)),
+            );
 
-            child
-                .hypothetical_outer_size
-                .set_main(dir, child.hypothetical_inner_size.main(dir) + child.margin.main(dir));
+            child.hypothetical_outer_size.set_main(
+                constants.dir,
+                child.hypothetical_inner_size.main(constants.dir) + child.margin.main(constants.dir),
+            );
         }
+    }
 
-        // 9.3. Main Size Determination
+    /// Collect flex items into flex lines.
+    ///
+    /// # [9.3. Main Size Determination](https://www.w3.org/TR/css-flexbox-1/#main-sizing)
+    ///
+    /// - [**Collect flex items into flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-break):
+    ///
+    ///     - If the flex container is single-line, collect all the flex items into a single flex line.
+    ///
+    ///     - Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size
+    ///         (or until a forced break is encountered, see [§10 Fragmenting Flex Layout](https://www.w3.org/TR/css-flexbox-1/#pagination)).
+    ///         If the very first uncollected item wouldn’t fit, collect just it into the line.
+    ///         
+    ///         For this step, the size of a flex item is its outer hypothetical main size. (**Note: This can be negative**.)
+    ///
+    ///         Repeat until all flex items have been collected into flex lines.
+    ///         
+    ///         **Note that the "collect as many" line will collect zero-sized flex items onto the end of the previous line even if the last non-zero item exactly "filled up" the line**.
+    #[inline]
+    fn collect_flex_lines<'a>(
+        &self,
+        node: NodeId,
+        constants: &AlgoConstants,
+        available_space: Size<Number>,
+        flex_items: &'a mut sys::Vec<FlexItem>,
+    ) -> sys::Vec<FlexLine<'a>> {
+        let mut lines = sys::new_vec_with_capacity(1);
+
+        if self.nodes[node].style.flex_wrap == FlexWrap::NoWrap {
+            lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
+        } else {
+            let mut flex_items = &mut flex_items[..];
 
-        // 5. Collect flex items into flex lines:
-        //    - If the flex container is single-line, collect all the flex items into
-        //      a single flex line.
-        //    - Otherwise, starting from the first uncollected item, collect consecutive
-        //      items one by one until the first time that the next collected item would
-        //      not fit into the flex container’s inner main size (or until a forced break
-        //      is encountered, see §10 Fragmenting Flex Layout). If the very first
-        //      uncollected item wouldn’t fit, collect just it into the line.
-        //
-        //      For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)
-        //      Repeat until all flex items have been collected into flex lines
-        //
-        //      Note that the "collect as many" line will collect zero-sized flex items onto
-        //      the end of the previous line even if the last non-zero item exactly "filled up" the line.
+            while !flex_items.is_empty() {
+                let mut line_length = 0.0;
+                let index = flex_items
+                    .iter()
+                    .enumerate()
+                    .find(|&(idx, child)| {
+                        line_length += child.hypothetical_outer_size.main(constants.dir);
+                        if let Defined(main) = available_space.main(constants.dir) {
+                            line_length > main && idx != 0
+                        } else {
+                            false
+                        }
+                    })
+                    .map(|(idx, _)| idx)
+                    .unwrap_or(flex_items.len());
+
+                let (items, rest) = flex_items.split_at_mut(index);
+                lines.push(FlexLine { items, cross_size: 0.0, offset_cross: 0.0 });
+                flex_items = rest;
+            }
+        }
 
-        let mut flex_lines: sys::Vec<_> = {
-            let mut lines = sys::new_vec_with_capacity(1);
+        lines
+    }
 
-            if self.nodes[node].style.flex_wrap == FlexWrap::NoWrap {
-                lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
+    /// Resolve the flexible lengths of the items within a flex line.
+    ///
+    /// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
+    #[inline]
+    fn resolve_flexible_lengths(
+        &mut self,
+        line: &mut FlexLine,
+        constants: &AlgoConstants,
+        available_space: Size<Number>,
+    ) {
+        // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
+        //    items on the line. If the sum is less than the flex container’s inner main size,
+        //    use the flex grow factor for the rest of this algorithm; otherwise, use the
+        //    flex shrink factor.
+
+        let used_flex_factor: f32 =
+            line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum();
+        let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).or_else(0.0);
+        let shrinking = !growing;
+
+        // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
+        //    - Any item that has a flex factor of zero
+        //    - If using the flex grow factor: any item that has a flex base size
+        //      greater than its hypothetical main size
+        //    - If using the flex shrink factor: any item that has a flex base size
+        //      smaller than its hypothetical main size
+
+        for child in line.items.iter_mut() {
+            // TODO - This is not found by reading the spec. Maybe this can be done in some other place
+            // instead. This was found by trail and error fixing tests to align with webkit output.
+            if constants.node_inner_size.main(constants.dir).is_undefined() && constants.is_row {
+                child.target_size.set_main(
+                    constants.dir,
+                    self.compute_internal(
+                        child.node,
+                        Size {
+                            width: child.size.width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
+                            height: child.size.height.maybe_max(child.min_size.height).maybe_min(child.max_size.height),
+                        },
+                        available_space,
+                        false,
+                        false,
+                    )
+                    .size
+                    .main(constants.dir)
+                    .maybe_max(child.min_size.main(constants.dir))
+                    .maybe_min(child.max_size.main(constants.dir)),
+                );
             } else {
-                let mut flex_items = &mut flex_items[..];
+                child.target_size.set_main(constants.dir, child.hypothetical_inner_size.main(constants.dir));
+            }
 
-                while !flex_items.is_empty() {
-                    let mut line_length = 0.0;
-                    let index = flex_items
-                        .iter()
-                        .enumerate()
-                        .find(|&(idx, child)| {
-                            line_length += child.hypothetical_outer_size.main(dir);
-                            if let Defined(main) = available_space.main(dir) {
-                                line_length > main && idx != 0
-                            } else {
-                                false
-                            }
-                        })
-                        .map(|(idx, _)| idx)
-                        .unwrap_or(flex_items.len());
+            // TODO this should really only be set inside the if-statement below but
+            // that causes the target_main_size to never be set for some items
 
-                    let (items, rest) = flex_items.split_at_mut(index);
-                    lines.push(FlexLine { items, cross_size: 0.0, offset_cross: 0.0 });
-                    flex_items = rest;
-                }
-            }
+            child
+                .outer_target_size
+                .set_main(constants.dir, child.target_size.main(constants.dir) + child.margin.main(constants.dir));
 
-            lines
-        };
+            let child_style = &self.nodes[child.node].style;
+            if (child_style.flex_grow == 0.0 && child_style.flex_shrink == 0.0)
+                || (growing && child.flex_basis > child.hypothetical_inner_size.main(constants.dir))
+                || (shrinking && child.flex_basis < child.hypothetical_inner_size.main(constants.dir))
+            {
+                child.frozen = true;
+            }
+        }
 
-        // 6. Resolve the flexible lengths of all the flex items to find their used main size.
-        //    See §9.7 Resolving Flexible Lengths.
-        //
-        // 9.7. Resolving Flexible Lengths
+        // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
+        //    and subtract this from the flex container’s inner main size. For frozen items,
+        //    use their outer target main size; for other items, use their outer flex base size.
 
-        for line in &mut flex_lines {
-            // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
-            //    items on the line. If the sum is less than the flex container’s inner main size,
-            //    use the flex grow factor for the rest of this algorithm; otherwise, use the
-            //    flex shrink factor.
-
-            let used_flex_factor: f32 = line.items.iter().map(|child| child.hypothetical_outer_size.main(dir)).sum();
-            let growing = used_flex_factor < node_inner_size.main(dir).or_else(0.0);
-            let shrinking = !growing;
-
-            // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
-            //    - Any item that has a flex factor of zero
-            //    - If using the flex grow factor: any item that has a flex base size
-            //      greater than its hypothetical main size
-            //    - If using the flex shrink factor: any item that has a flex base size
-            //      smaller than its hypothetical main size
+        let used_space: f32 = line
+            .items
+            .iter()
+            .map(|child| {
+                child.margin.main(constants.dir)
+                    + if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
+            })
+            .sum();
 
-            for child in line.items.iter_mut() {
-                // TODO - This is not found by reading the spec. Maybe this can be done in some other place
-                // instead. This was found by trail and error fixing tests to align with webkit output.
-                if node_inner_size.main(dir).is_undefined() && is_row {
-                    child.target_size.set_main(
-                        dir,
-                        self.compute_internal(
-                            child.node,
-                            Size {
-                                width: child.size.width.maybe_max(child.min_size.width).maybe_min(child.max_size.width),
-                                height: child
-                                    .size
-                                    .height
-                                    .maybe_max(child.min_size.height)
-                                    .maybe_min(child.max_size.height),
-                            },
-                            available_space,
-                            false,
-                            false,
-                        )
-                        .size
-                        .main(dir)
-                        .maybe_max(child.min_size.main(dir))
-                        .maybe_min(child.max_size.main(dir)),
-                    );
-                } else {
-                    child.target_size.set_main(dir, child.hypothetical_inner_size.main(dir));
-                }
+        let initial_free_space = (constants.node_inner_size.main(constants.dir) - used_space).or_else(0.0);
 
-                // TODO this should really only be set inside the if-statement below but
-                // that causes the target_main_size to never be set for some items
+        // 4. Loop
 
-                child.outer_target_size.set_main(dir, child.target_size.main(dir) + child.margin.main(dir));
+        loop {
+            // a. Check for flexible items. If all the flex items on the line are frozen,
+            //    free space has been distributed; exit this loop.
 
-                let child_style = &self.nodes[child.node].style;
-                if (child_style.flex_grow == 0.0 && child_style.flex_shrink == 0.0)
-                    || (growing && child.flex_basis > child.hypothetical_inner_size.main(dir))
-                    || (shrinking && child.flex_basis < child.hypothetical_inner_size.main(dir))
-                {
-                    child.frozen = true;
-                }
+            if line.items.iter().all(|child| child.frozen) {
+                break;
             }
 
-            // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
-            //    and subtract this from the flex container’s inner main size. For frozen items,
-            //    use their outer target main size; for other items, use their outer flex base size.
+            // b. Calculate the remaining free space as for initial free space, above.
+            //    If the sum of the unfrozen flex items’ flex factors is less than one,
+            //    multiply the initial free space by this sum. If the magnitude of this
+            //    value is less than the magnitude of the remaining free space, use this
+            //    as the remaining free space.
 
             let used_space: f32 = line
                 .items
                 .iter()
                 .map(|child| {
-                    child.margin.main(dir) + if child.frozen { child.target_size.main(dir) } else { child.flex_basis }
+                    child.margin.main(constants.dir)
+                        + if child.frozen { child.target_size.main(constants.dir) } else { child.flex_basis }
                 })
                 .sum();
 
-            let initial_free_space = (node_inner_size.main(dir) - used_space).or_else(0.0);
-
-            // 4. Loop
-
-            loop {
-                // a. Check for flexible items. If all the flex items on the line are frozen,
-                //    free space has been distributed; exit this loop.
-
-                if line.items.iter().all(|child| child.frozen) {
-                    break;
-                }
-
-                // b. Calculate the remaining free space as for initial free space, above.
-                //    If the sum of the unfrozen flex items’ flex factors is less than one,
-                //    multiply the initial free space by this sum. If the magnitude of this
-                //    value is less than the magnitude of the remaining free space, use this
-                //    as the remaining free space.
-
-                let used_space: f32 = line
-                    .items
-                    .iter()
-                    .map(|child| {
-                        child.margin.main(dir)
-                            + if child.frozen { child.target_size.main(dir) } else { child.flex_basis }
-                    })
-                    .sum();
+            let mut unfrozen: sys::Vec<&mut FlexItem> = line.items.iter_mut().filter(|child| !child.frozen).collect();
 
-                let mut unfrozen: sys::Vec<&mut FlexItem> =
-                    line.items.iter_mut().filter(|child| !child.frozen).collect();
+            let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
+                unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
+                    let style = &self.nodes[item.node].style;
+                    (flex_grow + style.flex_grow, flex_shrink + style.flex_shrink)
+                });
 
-                let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
-                    unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
-                        let style = &self.nodes[item.node].style;
-                        (flex_grow + style.flex_grow, flex_shrink + style.flex_shrink)
-                    });
+            let free_space = if growing && sum_flex_grow < 1.0 {
+                (initial_free_space * sum_flex_grow)
+                    .maybe_min(constants.node_inner_size.main(constants.dir) - used_space)
+            } else if shrinking && sum_flex_shrink < 1.0 {
+                (initial_free_space * sum_flex_shrink)
+                    .maybe_max(constants.node_inner_size.main(constants.dir) - used_space)
+            } else {
+                (constants.node_inner_size.main(constants.dir) - used_space).or_else(0.0)
+            };
 
-                let free_space = if growing && sum_flex_grow < 1.0 {
-                    (initial_free_space * sum_flex_grow).maybe_min(node_inner_size.main(dir) - used_space)
-                } else if shrinking && sum_flex_shrink < 1.0 {
-                    (initial_free_space * sum_flex_shrink).maybe_max(node_inner_size.main(dir) - used_space)
-                } else {
-                    (node_inner_size.main(dir) - used_space).or_else(0.0)
-                };
+            // c. Distribute free space proportional to the flex factors.
+            //    - If the remaining free space is zero
+            //        Do Nothing
+            //    - If using the flex grow factor
+            //        Find the ratio of the item’s flex grow factor to the sum of the
+            //        flex grow factors of all unfrozen items on the line. Set the item’s
+            //        target main size to its flex base size plus a fraction of the remaining
+            //        free space proportional to the ratio.
+            //    - If using the flex shrink factor
+            //        For every unfrozen item on the line, multiply its flex shrink factor by
+            //        its inner flex base size, and note this as its scaled flex shrink factor.
+            //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
+            //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
+            //        target main size to its flex base size minus a fraction of the absolute value
+            //        of the remaining free space proportional to the ratio. Note this may result
+            //        in a negative inner main size; it will be corrected in the next step.
+            //    - Otherwise
+            //        Do Nothing
+
+            if free_space.is_normal() {
+                if growing && sum_flex_grow > 0.0 {
+                    for child in &mut unfrozen {
+                        child.target_size.set_main(
+                            constants.dir,
+                            child.flex_basis + free_space * (self.nodes[child.node].style.flex_grow / sum_flex_grow),
+                        );
+                    }
+                } else if shrinking && sum_flex_shrink > 0.0 {
+                    let sum_scaled_shrink_factor: f32 = unfrozen
+                        .iter()
+                        .map(|child| child.inner_flex_basis * self.nodes[child.node].style.flex_shrink)
+                        .sum();
 
-                // c. Distribute free space proportional to the flex factors.
-                //    - If the remaining free space is zero
-                //        Do Nothing
-                //    - If using the flex grow factor
-                //        Find the ratio of the item’s flex grow factor to the sum of the
-                //        flex grow factors of all unfrozen items on the line. Set the item’s
-                //        target main size to its flex base size plus a fraction of the remaining
-                //        free space proportional to the ratio.
-                //    - If using the flex shrink factor
-                //        For every unfrozen item on the line, multiply its flex shrink factor by
-                //        its inner flex base size, and note this as its scaled flex shrink factor.
-                //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
-                //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
-                //        target main size to its flex base size minus a fraction of the absolute value
-                //        of the remaining free space proportional to the ratio. Note this may result
-                //        in a negative inner main size; it will be corrected in the next step.
-                //    - Otherwise
-                //        Do Nothing
-
-                if free_space.is_normal() {
-                    if growing && sum_flex_grow > 0.0 {
+                    if sum_scaled_shrink_factor > 0.0 {
                         for child in &mut unfrozen {
+                            let scaled_shrink_factor =
+                                child.inner_flex_basis * self.nodes[child.node].style.flex_shrink;
                             child.target_size.set_main(
-                                dir,
-                                child.flex_basis
-                                    + free_space * (self.nodes[child.node].style.flex_grow / sum_flex_grow),
-                            );
-                        }
-                    } else if shrinking && sum_flex_shrink > 0.0 {
-                        let sum_scaled_shrink_factor: f32 = unfrozen
-                            .iter()
-                            .map(|child| child.inner_flex_basis * self.nodes[child.node].style.flex_shrink)
-                            .sum();
-
-                        if sum_scaled_shrink_factor > 0.0 {
-                            for child in &mut unfrozen {
-                                let scaled_shrink_factor =
-                                    child.inner_flex_basis * self.nodes[child.node].style.flex_shrink;
-                                child.target_size.set_main(
-                                    dir,
-                                    child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
-                                )
-                            }
+                                constants.dir,
+                                child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
+                            )
                         }
                     }
                 }
-
-                // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
-                //    used min and max main sizes and floor its content-box size at zero. If the
-                //    item’s target main size was made smaller by this, it’s a max violation.
-                //    If the item’s target main size was made larger by this, it’s a min violation.
-
-                let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
-                    // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
-                    // The following logic was developed not from the spec but by trail and error looking into how
-                    // webkit handled various scenarios. Can probably be solved better by passing in
-                    // min-content max-content constraints from the top. Need to figure out correct thing to do here as
-                    // just piling on more conditionals.
-                    let min_main = if is_row && self.nodes[child.node].measure.is_none() {
-                        self.compute_internal(child.node, Size::undefined(), available_space, false, false)
-                            .size
-                            .width
-                            .maybe_min(child.size.width)
-                            .maybe_max(child.min_size.width)
-                            .into()
-                    } else {
-                        child.min_size.main(dir)
-                    };
-
-                    let max_main = child.max_size.main(dir);
-                    let clamped = child.target_size.main(dir).maybe_min(max_main).maybe_max(min_main).max(0.0);
-                    child.violation = clamped - child.target_size.main(dir);
-                    child.target_size.set_main(dir, clamped);
-                    child.outer_target_size.set_main(dir, child.target_size.main(dir) + child.margin.main(dir));
-
-                    acc + child.violation
-                });
-
-                // e. Freeze over-flexed items. The total violation is the sum of the adjustments
-                //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
-                //    - Zero
-                //        Freeze all items.
-                //    - Positive
-                //        Freeze all the items with min violations.
-                //    - Negative
-                //        Freeze all the items with max violations.
-
-                for child in &mut unfrozen {
-                    match total_violation {
-                        v if v > 0.0 => child.frozen = child.violation > 0.0,
-                        v if v < 0.0 => child.frozen = child.violation < 0.0,
-                        _ => child.frozen = true,
-                    }
-                }
-
-                // f. Return to the start of this loop.
             }
-        }
 
-        // Not part of the spec from what i can see but seems correct
-        container_size.set_main(
-            dir,
-            node_size.main(dir).or_else({
-                let longest_line = flex_lines.iter().fold(f32::MIN, |acc, line| {
-                    let length: f32 = line.items.iter().map(|item| item.outer_target_size.main(dir)).sum();
-                    acc.max(length)
-                });
+            // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
+            //    used min and max main sizes and floor its content-box size at zero. If the
+            //    item’s target main size was made smaller by this, it’s a max violation.
+            //    If the item’s target main size was made larger by this, it’s a min violation.
+
+            let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
+                // TODO - not really spec abiding but needs to be done somewhere. probably somewhere else though.
+                // The following logic was developed not from the spec but by trail and error looking into how
+                // webkit handled various scenarios. Can probably be solved better by passing in
+                // min-content max-content constraints from the top. Need to figure out correct thing to do here as
+                // just piling on more conditionals.
+                let min_main = if constants.is_row && self.nodes[child.node].measure.is_none() {
+                    self.compute_internal(child.node, Size::undefined(), available_space, false, false)
+                        .size
+                        .width
+                        .maybe_min(child.size.width)
+                        .maybe_max(child.min_size.width)
+                        .into()
+                } else {
+                    child.min_size.main(constants.dir)
+                };
 
-                let size = longest_line + padding_border.main(dir);
-                match available_space.main(dir) {
-                    Defined(val) if flex_lines.len() > 1 && size < val => val,
-                    _ => size,
+                let max_main = child.max_size.main(constants.dir);
+                let clamped = child.target_size.main(constants.dir).maybe_min(max_main).maybe_max(min_main).max(0.0);
+                child.violation = clamped - child.target_size.main(constants.dir);
+                child.target_size.set_main(constants.dir, clamped);
+                child
+                    .outer_target_size
+                    .set_main(constants.dir, child.target_size.main(constants.dir) + child.margin.main(constants.dir));
+
+                acc + child.violation
+            });
+
+            // e. Freeze over-flexed items. The total violation is the sum of the adjustments
+            //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
+            //    - Zero
+            //        Freeze all items.
+            //    - Positive
+            //        Freeze all the items with min violations.
+            //    - Negative
+            //        Freeze all the items with max violations.
+
+            for child in &mut unfrozen {
+                match total_violation {
+                    v if v > 0.0 => child.frozen = child.violation > 0.0,
+                    v if v < 0.0 => child.frozen = child.violation < 0.0,
+                    _ => child.frozen = true,
                 }
-            }),
-        );
-
-        inner_container_size.set_main(dir, container_size.main(dir) - padding_border.main(dir));
-
-        // 9.4. Cross Size Determination
+            }
 
-        // 7. Determine the hypothetical cross size of each item by performing layout with the
-        //    used main size and the available space, treating auto as fit-content.
+            // f. Return to the start of this loop.
+        }
+    }
 
-        for line in &mut flex_lines {
-            for child in line.items.iter_mut() {
-                let child_cross =
-                    child.size.cross(dir).maybe_max(child.min_size.cross(dir)).maybe_min(child.max_size.cross(dir));
+    /// Determine the hypothetical cross size of each item.
+    ///
+    /// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
+    ///
+    /// - [**Determine the hypothetical cross size of each item**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-item)
+    ///     by performing layout with the used main size and the available space, treating auto as fit-content.
+    #[inline]
+    fn determine_hypothetical_cross_size(
+        &mut self,
+        line: &mut FlexLine,
+        constants: &AlgoConstants,
+        available_space: Size<Number>,
+    ) {
+        for child in line.items.iter_mut() {
+            let child_cross = child
+                .size
+                .cross(constants.dir)
+                .maybe_max(child.min_size.cross(constants.dir))
+                .maybe_min(child.max_size.cross(constants.dir));
 
-                child.hypothetical_inner_size.set_cross(
-                    dir,
-                    self.compute_internal(
-                        child.node,
-                        Size {
-                            width: if is_row { child.target_size.width.into() } else { child_cross },
-                            height: if is_row { child_cross } else { child.target_size.height.into() },
+            child.hypothetical_inner_size.set_cross(
+                constants.dir,
+                self.compute_internal(
+                    child.node,
+                    Size {
+                        width: if constants.is_row { child.target_size.width.into() } else { child_cross },
+                        height: if constants.is_row { child_cross } else { child.target_size.height.into() },
+                    },
+                    Size {
+                        width: if constants.is_row {
+                            constants.container_size.main(constants.dir).into()
+                        } else {
+                            available_space.width
                         },
-                        Size {
-                            width: if is_row { container_size.main(dir).into() } else { available_space.width },
-                            height: if is_row { available_space.height } else { container_size.main(dir).into() },
+                        height: if constants.is_row {
+                            available_space.height
+                        } else {
+                            constants.container_size.main(constants.dir).into()
                         },
-                        false,
-                        false,
-                    )
-                    .size
-                    .cross(dir)
-                    .maybe_max(child.min_size.cross(dir))
-                    .maybe_min(child.max_size.cross(dir)),
-                );
-
-                child
-                    .hypothetical_outer_size
-                    .set_cross(dir, child.hypothetical_inner_size.cross(dir) + child.margin.cross(dir));
-            }
+                    },
+                    false,
+                    false,
+                )
+                .size
+                .cross(constants.dir)
+                .maybe_max(child.min_size.cross(constants.dir))
+                .maybe_min(child.max_size.cross(constants.dir)),
+            );
+
+            child.hypothetical_outer_size.set_cross(
+                constants.dir,
+                child.hypothetical_inner_size.cross(constants.dir) + child.margin.cross(constants.dir),
+            );
         }
+    }
 
-        // TODO - probably should move this somewhere else as it doesn't make a ton of sense here but we need it below
-        // TODO - This is expensive and should only be done if we really require a baseline. aka, make it lazy
-
+    /// Calculate the base lines of the children.
+    #[inline]
+    fn calculate_children_base_lines(
+        &mut self,
+        node: NodeId,
+        node_size: Size<Number>,
+        flex_lines: &mut [FlexLine],
+        constants: &AlgoConstants,
+    ) {
         fn calc_baseline(db: &Forest, node: NodeId, layout: &result::Layout) -> f32 {
             if db.children[node].is_empty() {
                 layout.size.height
@@ -715,56 +790,80 @@ impl Forest {
             }
         }
 
-        if has_baseline_child {
-            for line in &mut flex_lines {
-                for child in line.items.iter_mut() {
-                    let result = self.compute_internal(
-                        child.node,
-                        Size {
-                            width: if is_row {
-                                child.target_size.width.into()
-                            } else {
-                                child.hypothetical_inner_size.width.into()
-                            },
-                            height: if is_row {
-                                child.hypothetical_inner_size.height.into()
-                            } else {
-                                child.target_size.height.into()
-                            },
+        for line in flex_lines {
+            for child in line.items.iter_mut() {
+                let result = self.compute_internal(
+                    child.node,
+                    Size {
+                        width: if constants.is_row {
+                            child.target_size.width.into()
+                        } else {
+                            child.hypothetical_inner_size.width.into()
                         },
-                        Size {
-                            width: if is_row { container_size.width.into() } else { node_size.width },
-                            height: if is_row { node_size.height } else { container_size.height.into() },
+                        height: if constants.is_row {
+                            child.hypothetical_inner_size.height.into()
+                        } else {
+                            child.target_size.height.into()
                         },
-                        true,
-                        false,
-                    );
-
-                    child.baseline = calc_baseline(
-                        self,
-                        child.node,
-                        &result::Layout {
-                            order: self.children[node].iter().position(|n| *n == child.node).unwrap() as u32,
-                            size: result.size,
-                            location: Point::zero(),
+                    },
+                    Size {
+                        width: if constants.is_row { constants.container_size.width.into() } else { node_size.width },
+                        height: if constants.is_row {
+                            node_size.height
+                        } else {
+                            constants.container_size.height.into()
                         },
-                    );
-                }
+                    },
+                    true,
+                    false,
+                );
+
+                child.baseline = calc_baseline(
+                    self,
+                    child.node,
+                    &result::Layout {
+                        order: self.children[node].iter().position(|n| *n == child.node).unwrap() as u32,
+                        size: result.size,
+                        location: Point::zero(),
+                    },
+                );
             }
         }
+    }
 
-        // 8. Calculate the cross size of each flex line.
-        //    If the flex container is single-line and has a definite cross size, the cross size
-        //    of the flex line is the flex container’s inner cross size. Otherwise, for each flex line:
-        //
-        //    If the flex container is single-line, then clamp the line’s cross-size to be within
-        //    the container’s computed min and max cross sizes. Note that if CSS 2.1’s definition
-        //    of min/max-width/height applied more generally, this behavior would fall out automatically.
-
-        if flex_lines.len() == 1 && node_size.cross(dir).is_defined() {
-            flex_lines[0].cross_size = (node_size.cross(dir) - padding_border.cross(dir)).or_else(0.0);
+    /// Calculate the cross size of each flex line.
+    ///
+    /// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
+    ///
+    /// - [**Calculate the cross size of each flex line**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-line).
+    ///
+    ///     If the flex container is single-line and has a definite cross size, the cross size of the flex line is the flex container’s inner cross size.
+    ///         
+    ///     Otherwise, for each flex line:
+    ///
+    ///     1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose align-self is baseline, and whose cross-axis margins are both non-auto.
+    ///         Find the largest of the distances between each item’s baseline and its hypothetical outer cross-start edge,
+    ///         and the largest of the distances between each item’s baseline and its hypothetical outer cross-end edge, and sum these two values.
+    ///
+    ///     2. Among all the items not collected by the previous step, find the largest outer hypothetical cross size.
+    ///
+    ///     3. The used cross-size of the flex line is the largest of the numbers found in the previous two steps and zero.
+    ///         
+    ///         If the flex container is single-line, then clamp the line’s cross-size to be within the container’s computed min and max cross sizes.
+    ///         **Note that if CSS 2.1’s definition of min/max-width/height applied more generally, this behavior would fall out automatically**.
+    #[inline]
+    fn calculate_cross_size(
+        &mut self,
+        flex_lines: &mut [FlexLine],
+        node: NodeId,
+        node_size: Size<Number>,
+        constants: &AlgoConstants,
+    ) {
+        if flex_lines.len() == 1 && node_size.cross(constants.dir).is_defined() {
+            flex_lines[0].cross_size =
+                (node_size.cross(constants.dir) - constants.padding_border.cross(constants.dir)).or_else(0.0);
         } else {
-            for line in &mut flex_lines {
+            for line in flex_lines.iter_mut() {
                 //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
                 //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
                 //       largest of the distances between each item’s baseline and its hypothetical outer
@@ -784,28 +883,40 @@ impl Forest {
                     .map(|child| {
                         let child_style = &self.nodes[child.node].style;
                         if child_style.align_self(&self.nodes[node].style) == AlignSelf::Baseline
-                            && child_style.cross_margin_start(dir) != Dimension::Auto
-                            && child_style.cross_margin_end(dir) != Dimension::Auto
-                            && child_style.cross_size(dir) == Dimension::Auto
+                            && child_style.cross_margin_start(constants.dir) != Dimension::Auto
+                            && child_style.cross_margin_end(constants.dir) != Dimension::Auto
+                            && child_style.cross_size(constants.dir) == Dimension::Auto
                         {
-                            max_baseline - child.baseline + child.hypothetical_outer_size.cross(dir)
+                            max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
                         } else {
-                            child.hypothetical_outer_size.cross(dir)
+                            child.hypothetical_outer_size.cross(constants.dir)
                         }
                     })
                     .fold(0.0, |acc, x| acc.max(x));
             }
         }
+    }
 
-        // 9. Handle 'align-content: stretch'. If the flex container has a definite cross size,
-        //    align-content is stretch, and the sum of the flex lines' cross sizes is less than
-        //    the flex container’s inner cross size, increase the cross size of each flex line
-        //    by equal amounts such that the sum of their cross sizes exactly equals the
-        //    flex container’s inner cross size.
-
-        if self.nodes[node].style.align_content == AlignContent::Stretch && node_size.cross(dir).is_defined() {
+    /// Handle 'align-content: stretch'.
+    ///
+    /// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
+    ///
+    /// - [**Handle 'align-content: stretch'**](https://www.w3.org/TR/css-flexbox-1/#algo-line-stretch). If the flex container has a definite cross size, align-content is stretch,
+    ///     and the sum of the flex lines' cross sizes is less than the flex container’s inner cross size,
+    ///     increase the cross size of each flex line by equal amounts such that the sum of their cross sizes exactly equals the flex container’s inner cross size.
+    #[inline]
+    fn handle_align_content_stretch(
+        &mut self,
+        flex_lines: &mut [FlexLine],
+        node: NodeId,
+        node_size: Size<Number>,
+        constants: &AlgoConstants,
+    ) {
+        if self.nodes[node].style.align_content == AlignContent::Stretch && node_size.cross(constants.dir).is_defined()
+        {
             let total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
-            let inner_cross = (node_size.cross(dir) - padding_border.cross(dir)).or_else(0.0);
+            let inner_cross =
+                (node_size.cross(constants.dir) - constants.padding_border.cross(constants.dir)).or_else(0.0);
 
             if total_cross < inner_cross {
                 let remaining = inner_cross - total_cross;
@@ -813,77 +924,77 @@ impl Forest {
                 flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
             }
         }
+    }
 
-        // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
-        //     note the cross size of the line they’re in as the item’s strut size, and restart
-        //     layout from the beginning.
-        //
-        //     In this second layout round, when collecting items into lines, treat the collapsed
-        //     items as having zero main size. For the rest of the algorithm following that step,
-        //     ignore the collapsed items entirely (as if they were display:none) except that after
-        //     calculating the cross size of the lines, if any line’s cross size is less than the
-        //     largest strut size among all the collapsed items in the line, set its cross size to
-        //     that strut size.
-        //
-        //     Skip this step in the second layout round.
-
-        // TODO implement once (if ever) we support visibility:collapse
-
-        // 11. Determine the used cross size of each flex item. If a flex item has align-self: stretch,
-        //     its computed cross size property is auto, and neither of its cross-axis margins are auto,
-        //     the used outer cross size is the used cross size of its flex line, clamped according to
-        //     the item’s used min and max cross sizes. Otherwise, the used cross size is the item’s
-        //     hypothetical cross size.
-        //
-        //     If the flex item has align-self: stretch, redo layout for its contents, treating this
-        //     used size as its definite cross size so that percentage-sized children can be resolved.
-        //
-        //     Note that this step does not affect the main size of the flex item, even if it has an
-        //     intrinsic aspect ratio.
-
-        for line in &mut flex_lines {
-            let line_cross_size = line.cross_size;
+    /// Determine the used cross size of each flex item.
+    ///
+    /// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
+    ///
+    /// - [**Determine the used cross size of each flex item**](https://www.w3.org/TR/css-flexbox-1/#algo-stretch). If a flex item has align-self: stretch, its computed cross size property is auto,
+    ///     and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s used min and max cross sizes.
+    ///     Otherwise, the used cross size is the item’s hypothetical cross size.
+    ///
+    ///     If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.
+    ///
+    ///     **Note that this step does not affect the main size of the flex item, even if it has an intrinsic aspect ratio**.
+    #[inline]
+    fn determine_used_cross_size(&mut self, flex_lines: &mut [FlexLine], node: NodeId, constants: &AlgoConstants) {
+        for line in flex_lines {
+            let line_cross_size = line.cross_size;
 
             for child in line.items.iter_mut() {
                 let child_style = &self.nodes[child.node].style;
                 child.target_size.set_cross(
-                    dir,
+                    constants.dir,
                     if child_style.align_self(&self.nodes[node].style) == AlignSelf::Stretch
-                        && child_style.cross_margin_start(dir) != Dimension::Auto
-                        && child_style.cross_margin_end(dir) != Dimension::Auto
-                        && child_style.cross_size(dir) == Dimension::Auto
+                        && child_style.cross_margin_start(constants.dir) != Dimension::Auto
+                        && child_style.cross_margin_end(constants.dir) != Dimension::Auto
+                        && child_style.cross_size(constants.dir) == Dimension::Auto
                     {
-                        (line_cross_size - child.margin.cross(dir))
-                            .maybe_max(child.min_size.cross(dir))
-                            .maybe_min(child.max_size.cross(dir))
+                        (line_cross_size - child.margin.cross(constants.dir))
+                            .maybe_max(child.min_size.cross(constants.dir))
+                            .maybe_min(child.max_size.cross(constants.dir))
                     } else {
-                        child.hypothetical_inner_size.cross(dir)
+                        child.hypothetical_inner_size.cross(constants.dir)
                     },
                 );
 
-                child.outer_target_size.set_cross(dir, child.target_size.cross(dir) + child.margin.cross(dir));
+                child.outer_target_size.set_cross(
+                    constants.dir,
+                    child.target_size.cross(constants.dir) + child.margin.cross(constants.dir),
+                );
             }
         }
+    }
 
-        // 9.5. Main-Axis Alignment
-
-        // 12. Distribute any remaining free space. For each flex line:
-        //     1. If the remaining free space is positive and at least one main-axis margin on this
-        //        line is auto, distribute the free space equally among these margins. Otherwise,
-        //        set all auto margins to zero.
-        //     2. Align the items along the main-axis per justify-content.
-
-        for line in &mut flex_lines {
-            let used_space: f32 = line.items.iter().map(|child| child.outer_target_size.main(dir)).sum();
-            let free_space = inner_container_size.main(dir) - used_space;
+    /// Distribute any remaining free space.
+    ///
+    /// # [9.5. Main-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#main-alignment)
+    ///
+    /// - [**Distribute any remaining free space**](https://www.w3.org/TR/css-flexbox-1/#algo-main-align). For each flex line:
+    ///
+    ///     1. If the remaining free space is positive and at least one main-axis margin on this line is `auto`, distribute the free space equally among these margins.
+    ///         Otherwise, set all `auto` margins to zero.
+    ///
+    ///     2. Align the items along the main-axis per `justify-content`.
+    #[inline]
+    fn distribute_remaining_free_space(
+        &mut self,
+        flex_lines: &mut [FlexLine],
+        node: NodeId,
+        constants: &AlgoConstants,
+    ) {
+        for line in flex_lines {
+            let used_space: f32 = line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum();
+            let free_space = constants.inner_container_size.main(constants.dir) - used_space;
             let mut num_auto_margins = 0;
 
             for child in line.items.iter_mut() {
                 let child_style = &self.nodes[child.node].style;
-                if child_style.main_margin_start(dir) == Dimension::Auto {
+                if child_style.main_margin_start(constants.dir) == Dimension::Auto {
                     num_auto_margins += 1;
                 }
-                if child_style.main_margin_end(dir) == Dimension::Auto {
+                if child_style.main_margin_end(constants.dir) == Dimension::Auto {
                     num_auto_margins += 1;
                 }
             }
@@ -893,15 +1004,15 @@ impl Forest {
 
                 for child in line.items.iter_mut() {
                     let child_style = &self.nodes[child.node].style;
-                    if child_style.main_margin_start(dir) == Dimension::Auto {
-                        if is_row {
+                    if child_style.main_margin_start(constants.dir) == Dimension::Auto {
+                        if constants.is_row {
                             child.margin.start = margin;
                         } else {
                             child.margin.top = margin;
                         }
                     }
-                    if child_style.main_margin_end(dir) == Dimension::Auto {
-                        if is_row {
+                    if child_style.main_margin_end(constants.dir) == Dimension::Auto {
+                        if constants.is_row {
                             child.margin.end = margin;
                         } else {
                             child.margin.bottom = margin;
@@ -910,7 +1021,7 @@ impl Forest {
                 }
             } else {
                 let num_items = line.items.len();
-                let layout_reverse = dir.is_reverse();
+                let layout_reverse = constants.dir.is_reverse();
 
                 let justify_item = |(i, child): (usize, &mut FlexItem)| {
                     let is_first = i == 0;
@@ -962,115 +1073,172 @@ impl Forest {
                 }
             }
         }
+    }
 
-        // 9.6. Cross-Axis Alignment
-
-        // 13. Resolve cross-axis auto margins. If a flex item has auto cross-axis margins:
-        //     - If its outer cross size (treating those auto margins as zero) is less than the
-        //       cross size of its flex line, distribute the difference in those sizes equally
-        //       to the auto margins.
-        //     - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis)
-        //       is auto, set it to zero. Set the opposite margin so that the outer cross size of the
-        //       item equals the cross size of its flex line.
-
-        for line in &mut flex_lines {
+    /// Resolve cross-axis `auto` margins.
+    ///
+    /// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
+    ///
+    /// - [**Resolve cross-axis `auto` margins**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-margins).
+    ///     If a flex item has auto cross-axis margins:
+    ///     
+    ///     - If its outer cross size (treating those auto margins as zero) is less than the cross size of its flex line,
+    ///         distribute the difference in those sizes equally to the auto margins.
+    ///     
+    ///     - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis) is auto, set it to zero.
+    ///         Set the opposite margin so that the outer cross size of the item equals the cross size of its flex line.
+    #[inline]
+    fn resolve_cross_axis_auto_margins(
+        &mut self,
+        flex_lines: &mut [FlexLine],
+        node: NodeId,
+        constants: &AlgoConstants,
+    ) {
+        for line in flex_lines {
             let line_cross_size = line.cross_size;
             let max_baseline: f32 = line.items.iter_mut().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
 
             for child in line.items.iter_mut() {
-                let free_space = line_cross_size - child.outer_target_size.cross(dir);
+                let free_space = line_cross_size - child.outer_target_size.cross(constants.dir);
                 let child_style = &self.nodes[child.node].style;
 
-                if child_style.cross_margin_start(dir) == Dimension::Auto
-                    && child_style.cross_margin_end(dir) == Dimension::Auto
+                if child_style.cross_margin_start(constants.dir) == Dimension::Auto
+                    && child_style.cross_margin_end(constants.dir) == Dimension::Auto
                 {
-                    if is_row {
+                    if constants.is_row {
                         child.margin.top = free_space / 2.0;
                         child.margin.bottom = free_space / 2.0;
                     } else {
                         child.margin.start = free_space / 2.0;
                         child.margin.end = free_space / 2.0;
                     }
-                } else if child_style.cross_margin_start(dir) == Dimension::Auto {
-                    if is_row {
+                } else if child_style.cross_margin_start(constants.dir) == Dimension::Auto {
+                    if constants.is_row {
                         child.margin.top = free_space;
                     } else {
                         child.margin.start = free_space;
                     }
-                } else if child_style.cross_margin_end(dir) == Dimension::Auto {
-                    if is_row {
+                } else if child_style.cross_margin_end(constants.dir) == Dimension::Auto {
+                    if constants.is_row {
                         child.margin.bottom = free_space;
                     } else {
                         child.margin.end = free_space;
                     }
                 } else {
-                    // 14. Align all flex items along the cross-axis per align-self, if neither of the item’s
-                    //     cross-axis margins are auto.
-
-                    child.offset_cross = match child_style.align_self(&self.nodes[node].style) {
-                        AlignSelf::Auto => 0.0, // Should never happen
-                        AlignSelf::FlexStart => {
-                            if is_wrap_reverse {
-                                free_space
-                            } else {
-                                0.0
-                            }
-                        }
-                        AlignSelf::FlexEnd => {
-                            if is_wrap_reverse {
-                                0.0
-                            } else {
-                                free_space
-                            }
-                        }
-                        AlignSelf::Center => free_space / 2.0,
-                        AlignSelf::Baseline => {
-                            if is_row {
-                                max_baseline - child.baseline
-                            } else {
-                                // baseline alignment only makes sense if the direction is row
-                                // we treat it as flex-start alignment in columns.
-                                if is_wrap_reverse {
-                                    free_space
-                                } else {
-                                    0.0
-                                }
-                            }
-                        }
-                        AlignSelf::Stretch => {
-                            if is_wrap_reverse {
-                                free_space
-                            } else {
-                                0.0
-                            }
-                        }
-                    };
+                    // 14. Align all flex items along the cross-axis.
+                    child.offset_cross = self.align_flex_items_along_cross_axis(
+                        node,
+                        child,
+                        child_style,
+                        free_space,
+                        max_baseline,
+                        constants,
+                    );
                 }
             }
         }
+    }
 
-        // 15. Determine the flex container’s used cross size:
-        //     - If the cross size property is a definite size, use that, clamped by the used
-        //       min and max cross sizes of the flex container.
-        //     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used
-        //       min and max cross sizes of the flex container.
+    /// Align all flex items along the cross-axis.
+    ///
+    /// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
+    ///
+    /// - [**Align all flex items along the cross-axis**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-align) per `align-self`,
+    ///     if neither of the item's cross-axis margins are `auto`.
+    #[inline]
+    fn align_flex_items_along_cross_axis(
+        &self,
+        node: NodeId,
+        child: &mut FlexItem,
+        child_style: &Style,
+        free_space: f32,
+        max_baseline: f32,
+        constants: &AlgoConstants,
+    ) -> f32 {
+        match child_style.align_self(&self.nodes[node].style) {
+            AlignSelf::Auto => 0.0, // Should never happen
+            AlignSelf::FlexStart => {
+                if constants.is_wrap_reverse {
+                    free_space
+                } else {
+                    0.0
+                }
+            }
+            AlignSelf::FlexEnd => {
+                if constants.is_wrap_reverse {
+                    0.0
+                } else {
+                    free_space
+                }
+            }
+            AlignSelf::Center => free_space / 2.0,
+            AlignSelf::Baseline => {
+                if constants.is_row {
+                    max_baseline - child.baseline
+                } else {
+                    // baseline alignment only makes sense if the constants.direction is row
+                    // we treat it as flex-start alignment in columns.
+                    if constants.is_wrap_reverse {
+                        free_space
+                    } else {
+                        0.0
+                    }
+                }
+            }
+            AlignSelf::Stretch => {
+                if constants.is_wrap_reverse {
+                    free_space
+                } else {
+                    0.0
+                }
+            }
+        }
+    }
 
+    /// Determine the flex container’s used cross size.
+    ///
+    /// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
+    ///
+    /// - [**Determine the flex container’s used cross size**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-container):
+    ///     
+    ///     - If the cross size property is a definite size, use that, clamped by the used min and max cross sizes of the flex container.
+    ///
+    ///     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used min and max cross sizes of the flex container.
+    #[inline]
+    fn determine_container_cross_size(
+        flex_lines: &mut [FlexLine],
+        node_size: Size<Number>,
+        constants: &mut AlgoConstants,
+    ) -> f32 {
         let total_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum();
-        container_size.set_cross(dir, node_size.cross(dir).or_else(total_cross_size + padding_border.cross(dir)));
-        inner_container_size.set_cross(dir, container_size.cross(dir) - padding_border.cross(dir));
 
-        // We have the container size. If our caller does not care about performing
-        // layout we are done now.
-        if !perform_layout {
-            let result = ComputeResult { size: container_size };
-            *self.cache(node, main_size) =
-                Some(result::Cache { node_size, parent_size, perform_layout, result: result.clone() });
-            return result;
-        }
+        constants.container_size.set_cross(
+            constants.dir,
+            node_size.cross(constants.dir).or_else(total_cross_size + constants.padding_border.cross(constants.dir)),
+        );
 
-        // 16. Align all flex lines per align-content.
+        constants.inner_container_size.set_cross(
+            constants.dir,
+            constants.container_size.cross(constants.dir) - constants.padding_border.cross(constants.dir),
+        );
+
+        total_cross_size
+    }
 
-        let free_space = inner_container_size.cross(dir) - total_cross_size;
+    /// Align all flex lines per `align-content`.
+    ///
+    /// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
+    ///
+    /// - [**Align all flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-align) per `align-content`.
+    #[inline]
+    fn align_flex_lines_per_align_content(
+        &self,
+        flex_lines: &mut [FlexLine],
+        node: NodeId,
+        constants: &AlgoConstants,
+        total_cross_size: f32,
+    ) {
+        let free_space = constants.inner_container_size.cross(constants.dir) - total_cross_size;
         let num_lines = flex_lines.len();
 
         let align_line = |(i, line): (usize, &mut FlexLine)| {
@@ -1078,14 +1246,14 @@ impl Forest {
 
             line.offset_cross = match self.nodes[node].style.align_content {
                 AlignContent::FlexStart => {
-                    if is_first && is_wrap_reverse {
+                    if is_first && constants.is_wrap_reverse {
                         free_space
                     } else {
                         0.0
                     }
                 }
                 AlignContent::FlexEnd => {
-                    if is_first && !is_wrap_reverse {
+                    if is_first && !constants.is_wrap_reverse {
                         free_space
                     } else {
                         0.0
@@ -1116,200 +1284,384 @@ impl Forest {
             };
         };
 
-        if is_wrap_reverse {
+        if constants.is_wrap_reverse {
             flex_lines.iter_mut().rev().enumerate().for_each(align_line);
         } else {
             flex_lines.iter_mut().enumerate().for_each(align_line);
         }
+    }
 
-        // Do a final layout pass and gather the resulting layouts
-        {
-            let mut total_offset_cross = padding_border.cross_start(dir);
-
-            let layout_line = |line: &mut FlexLine| {
-                let mut total_offset_main = padding_border.main_start(dir);
-                let line_offset_cross = line.offset_cross;
-
-                let layout_item = |child: &mut FlexItem| {
-                    let result = self.compute_internal(
-                        child.node,
-                        child.target_size.map(|s| s.into()),
-                        container_size.map(|s| s.into()),
-                        true,
-                        false,
-                    );
-
-                    let offset_main = total_offset_main
-                        + child.offset_main
-                        + child.margin.main_start(dir)
-                        + (child.position.main_start(dir).or_else(0.0) - child.position.main_end(dir).or_else(0.0));
+    /// Do a final layout pass and collect the resulting layouts.
+    #[inline]
+    fn final_layout_pass(&mut self, node: NodeId, flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
+        let mut total_offset_cross = constants.padding_border.cross_start(constants.dir);
 
-                    let offset_cross = total_offset_cross
-                        + child.offset_cross
-                        + line_offset_cross
-                        + child.margin.cross_start(dir)
-                        + (child.position.cross_start(dir).or_else(0.0) - child.position.cross_end(dir).or_else(0.0));
+        let layout_line = |line: &mut FlexLine| {
+            let mut total_offset_main = constants.padding_border.main_start(constants.dir);
+            let line_offset_cross = line.offset_cross;
 
-                    self.nodes[child.node].layout = result::Layout {
-                        order: self.children[node].iter().position(|n| *n == child.node).unwrap() as u32,
-                        size: result.size,
-                        location: Point {
-                            x: if is_row { offset_main } else { offset_cross },
-                            y: if is_column { offset_main } else { offset_cross },
-                        },
-                    };
+            let layout_item = |child: &mut FlexItem| {
+                let result = self.compute_internal(
+                    child.node,
+                    child.target_size.map(|s| s.into()),
+                    constants.container_size.map(|s| s.into()),
+                    true,
+                    false,
+                );
 
-                    total_offset_main += child.offset_main + child.margin.main(dir) + result.size.main(dir);
+                let offset_main = total_offset_main
+                    + child.offset_main
+                    + child.margin.main_start(constants.dir)
+                    + (child.position.main_start(constants.dir).or_else(0.0)
+                        - child.position.main_end(constants.dir).or_else(0.0));
+
+                let offset_cross = total_offset_cross
+                    + child.offset_cross
+                    + line_offset_cross
+                    + child.margin.cross_start(constants.dir)
+                    + (child.position.cross_start(constants.dir).or_else(0.0)
+                        - child.position.cross_end(constants.dir).or_else(0.0));
+
+                self.nodes[child.node].layout = result::Layout {
+                    order: self.children[node].iter().position(|n| *n == child.node).unwrap() as u32,
+                    size: result.size,
+                    location: Point {
+                        x: if constants.is_row { offset_main } else { offset_cross },
+                        y: if constants.is_column { offset_main } else { offset_cross },
+                    },
                 };
 
-                if dir.is_reverse() {
-                    line.items.iter_mut().rev().for_each(layout_item);
-                } else {
-                    line.items.iter_mut().for_each(layout_item);
-                }
-
-                total_offset_cross += line_offset_cross + line.cross_size;
+                total_offset_main +=
+                    child.offset_main + child.margin.main(constants.dir) + result.size.main(constants.dir);
             };
 
-            if is_wrap_reverse {
-                flex_lines.iter_mut().rev().for_each(layout_line);
+            if constants.dir.is_reverse() {
+                line.items.iter_mut().rev().for_each(layout_item);
             } else {
-                flex_lines.iter_mut().for_each(layout_line);
+                line.items.iter_mut().for_each(layout_item);
             }
+
+            total_offset_cross += line_offset_cross + line.cross_size;
+        };
+
+        if constants.is_wrap_reverse {
+            flex_lines.iter_mut().rev().for_each(layout_line);
+        } else {
+            flex_lines.iter_mut().for_each(layout_line);
         }
+    }
 
-        // Before returning we perform absolute layout on all absolutely positioned children
-        {
-            // TODO: remove number of Vec<_> generated
-            let candidates = self.children[node]
-                .iter()
-                .cloned()
-                .enumerate()
-                .filter(|(_, child)| self.nodes[*child].style.position_type == PositionType::Absolute)
-                .collect::<sys::Vec<_>>();
-
-            for (order, child) in candidates {
-                let container_width = container_size.width.into();
-                let container_height = container_size.height.into();
-
-                let child_style = self.nodes[child].style;
-
-                let start = child_style.position.start.resolve(container_width)
-                    + child_style.margin.start.resolve(container_width);
-                let end =
-                    child_style.position.end.resolve(container_width) + child_style.margin.end.resolve(container_width);
-                let top = child_style.position.top.resolve(container_height)
-                    + child_style.margin.top.resolve(container_height);
-                let bottom = child_style.position.bottom.resolve(container_height)
-                    + child_style.margin.bottom.resolve(container_height);
-
-                let (start_main, end_main) = if is_row { (start, end) } else { (top, bottom) };
-                let (start_cross, end_cross) = if is_row { (top, bottom) } else { (start, end) };
-
-                let width = child_style
-                    .size
-                    .width
-                    .resolve(container_width)
-                    .maybe_max(child_style.min_size.width.resolve(container_width))
-                    .maybe_min(child_style.max_size.width.resolve(container_width))
-                    .or_else(if start.is_defined() && end.is_defined() {
-                        container_width - start - end
-                    } else {
-                        Undefined
-                    });
+    /// Perform absolute layout on all absolutely positioned children.
+    #[inline]
+    fn perform_absolute_layout_on_absolute_children(&mut self, node: NodeId, constants: &AlgoConstants) {
+        // TODO: remove number of Vec<_> generated
+        let candidates = self.children[node]
+            .iter()
+            .cloned()
+            .enumerate()
+            .filter(|(_, child)| self.nodes[*child].style.position_type == PositionType::Absolute)
+            .collect::<sys::Vec<_>>();
+
+        for (order, child) in candidates {
+            let container_width = constants.container_size.width.into();
+            let container_height = constants.container_size.height.into();
+
+            let child_style = self.nodes[child].style;
+
+            let start =
+                child_style.position.start.resolve(container_width) + child_style.margin.start.resolve(container_width);
+            let end =
+                child_style.position.end.resolve(container_width) + child_style.margin.end.resolve(container_width);
+            let top =
+                child_style.position.top.resolve(container_height) + child_style.margin.top.resolve(container_height);
+            let bottom = child_style.position.bottom.resolve(container_height)
+                + child_style.margin.bottom.resolve(container_height);
+
+            let (start_main, end_main) = if constants.is_row { (start, end) } else { (top, bottom) };
+            let (start_cross, end_cross) = if constants.is_row { (top, bottom) } else { (start, end) };
+
+            let width = child_style
+                .size
+                .width
+                .resolve(container_width)
+                .maybe_max(child_style.min_size.width.resolve(container_width))
+                .maybe_min(child_style.max_size.width.resolve(container_width))
+                .or_else(if start.is_defined() && end.is_defined() {
+                    container_width - start - end
+                } else {
+                    Undefined
+                });
 
-                let height = child_style
-                    .size
-                    .height
-                    .resolve(container_height)
-                    .maybe_max(child_style.min_size.height.resolve(container_height))
-                    .maybe_min(child_style.max_size.height.resolve(container_height))
-                    .or_else(if top.is_defined() && bottom.is_defined() {
-                        container_height - top - bottom
-                    } else {
-                        Undefined
-                    });
+            let height = child_style
+                .size
+                .height
+                .resolve(container_height)
+                .maybe_max(child_style.min_size.height.resolve(container_height))
+                .maybe_min(child_style.max_size.height.resolve(container_height))
+                .or_else(if top.is_defined() && bottom.is_defined() {
+                    container_height - top - bottom
+                } else {
+                    Undefined
+                });
 
-                let result = self.compute_internal(
-                    child,
-                    Size { width, height },
-                    Size { width: container_width, height: container_height },
-                    true,
-                    false,
-                );
+            let result = self.compute_internal(
+                child,
+                Size { width, height },
+                Size { width: container_width, height: container_height },
+                true,
+                false,
+            );
 
-                let free_main_space = container_size.main(dir)
-                    - result
-                        .size
-                        .main(dir)
-                        .maybe_max(child_style.min_main_size(dir).resolve(node_inner_size.main(dir)))
-                        .maybe_min(child_style.max_main_size(dir).resolve(node_inner_size.main(dir)));
+            let free_main_space = constants.container_size.main(constants.dir)
+                - result
+                    .size
+                    .main(constants.dir)
+                    .maybe_max(
+                        child_style.min_main_size(constants.dir).resolve(constants.node_inner_size.main(constants.dir)),
+                    )
+                    .maybe_min(
+                        child_style.max_main_size(constants.dir).resolve(constants.node_inner_size.main(constants.dir)),
+                    );
 
-                let free_cross_space = container_size.cross(dir)
-                    - result
-                        .size
-                        .cross(dir)
-                        .maybe_max(child_style.min_cross_size(dir).resolve(node_inner_size.cross(dir)))
-                        .maybe_min(child_style.max_cross_size(dir).resolve(node_inner_size.cross(dir)));
-
-                let offset_main = if start_main.is_defined() {
-                    start_main.or_else(0.0) + border.main_start(dir)
-                } else if end_main.is_defined() {
-                    free_main_space - end_main.or_else(0.0) - border.main_end(dir)
-                } else {
-                    match self.nodes[node].style.justify_content {
-                        JustifyContent::SpaceBetween | JustifyContent::FlexStart => padding_border.main_start(dir),
-                        JustifyContent::FlexEnd => free_main_space - padding_border.main_end(dir),
-                        JustifyContent::SpaceEvenly | JustifyContent::SpaceAround | JustifyContent::Center => {
-                            free_main_space / 2.0
-                        }
+            let free_cross_space = constants.container_size.cross(constants.dir)
+                - result
+                    .size
+                    .cross(constants.dir)
+                    .maybe_max(
+                        child_style
+                            .min_cross_size(constants.dir)
+                            .resolve(constants.node_inner_size.cross(constants.dir)),
+                    )
+                    .maybe_min(
+                        child_style
+                            .max_cross_size(constants.dir)
+                            .resolve(constants.node_inner_size.cross(constants.dir)),
+                    );
+
+            let offset_main = if start_main.is_defined() {
+                start_main.or_else(0.0) + constants.border.main_start(constants.dir)
+            } else if end_main.is_defined() {
+                free_main_space - end_main.or_else(0.0) - constants.border.main_end(constants.dir)
+            } else {
+                match self.nodes[node].style.justify_content {
+                    JustifyContent::SpaceBetween | JustifyContent::FlexStart => {
+                        constants.padding_border.main_start(constants.dir)
                     }
-                };
+                    JustifyContent::FlexEnd => free_main_space - constants.padding_border.main_end(constants.dir),
+                    JustifyContent::SpaceEvenly | JustifyContent::SpaceAround | JustifyContent::Center => {
+                        free_main_space / 2.0
+                    }
+                }
+            };
 
-                let offset_cross = if start_cross.is_defined() {
-                    start_cross.or_else(0.0) + border.cross_start(dir)
-                } else if end_cross.is_defined() {
-                    free_cross_space - end_cross.or_else(0.0) - border.cross_end(dir)
-                } else {
-                    match child_style.align_self(&self.nodes[node].style) {
-                        AlignSelf::Auto => 0.0, // Should never happen
-                        AlignSelf::FlexStart => {
-                            if is_wrap_reverse {
-                                free_cross_space - padding_border.cross_end(dir)
-                            } else {
-                                padding_border.cross_start(dir)
-                            }
+            let offset_cross = if start_cross.is_defined() {
+                start_cross.or_else(0.0) + constants.border.cross_start(constants.dir)
+            } else if end_cross.is_defined() {
+                free_cross_space - end_cross.or_else(0.0) - constants.border.cross_end(constants.dir)
+            } else {
+                match child_style.align_self(&self.nodes[node].style) {
+                    AlignSelf::Auto => 0.0, // Should never happen
+                    AlignSelf::FlexStart => {
+                        if constants.is_wrap_reverse {
+                            free_cross_space - constants.padding_border.cross_end(constants.dir)
+                        } else {
+                            constants.padding_border.cross_start(constants.dir)
                         }
-                        AlignSelf::FlexEnd => {
-                            if is_wrap_reverse {
-                                padding_border.cross_start(dir)
-                            } else {
-                                free_cross_space - padding_border.cross_end(dir)
-                            }
+                    }
+                    AlignSelf::FlexEnd => {
+                        if constants.is_wrap_reverse {
+                            constants.padding_border.cross_start(constants.dir)
+                        } else {
+                            free_cross_space - constants.padding_border.cross_end(constants.dir)
                         }
-                        AlignSelf::Center => free_cross_space / 2.0,
-                        AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
-                        AlignSelf::Stretch => {
-                            if is_wrap_reverse {
-                                free_cross_space - padding_border.cross_end(dir)
-                            } else {
-                                padding_border.cross_start(dir)
-                            }
+                    }
+                    AlignSelf::Center => free_cross_space / 2.0,
+                    AlignSelf::Baseline => free_cross_space / 2.0, // Treat as center for now until we have baseline support
+                    AlignSelf::Stretch => {
+                        if constants.is_wrap_reverse {
+                            free_cross_space - constants.padding_border.cross_end(constants.dir)
+                        } else {
+                            constants.padding_border.cross_start(constants.dir)
                         }
                     }
-                };
+                }
+            };
 
-                self.nodes[child].layout = result::Layout {
-                    order: order as u32,
-                    size: result.size,
-                    location: Point {
-                        x: if is_row { offset_main } else { offset_cross },
-                        y: if is_column { offset_main } else { offset_cross },
-                    },
+            self.nodes[child].layout = result::Layout {
+                order: order as u32,
+                size: result.size,
+                location: Point {
+                    x: if constants.is_row { offset_main } else { offset_cross },
+                    y: if constants.is_column { offset_main } else { offset_cross },
+                },
+            };
+        }
+    }
+
+    fn compute_internal(
+        &mut self,
+        node: NodeId,
+        node_size: Size<Number>,
+        parent_size: Size<Number>,
+        perform_layout: bool,
+        main_size: bool,
+    ) -> ComputeResult {
+        self.nodes[node].is_dirty = false;
+
+        // First we check if we have a result for the given input
+        if let Some(result) = self.compute_from_cache(node, node_size, parent_size, perform_layout, main_size) {
+            return result;
+        }
+
+        // Define some general constants we will need for the remainder of the algorithm.
+        let mut constants = self.compute_constants(node, node_size, parent_size);
+
+        // If this is a leaf node we can skip a lot of this function in some cases
+        if self.children[node].is_empty() {
+            if node_size.width.is_defined() && node_size.height.is_defined() {
+                return ComputeResult { size: node_size.map(|s| s.or_else(0.0)) };
+            }
+
+            if let Some(ref measure) = self.nodes[node].measure {
+                let result = match measure {
+                    MeasureFunc::Raw(measure) => ComputeResult { size: measure(node_size) },
+                    #[cfg(any(feature = "std", feature = "alloc"))]
+                    MeasureFunc::Boxed(measure) => ComputeResult { size: measure(node_size) },
                 };
+                *self.cache(node, main_size) =
+                    Some(result::Cache { node_size, parent_size, perform_layout, result: result.clone() });
+                return result;
             }
+
+            return ComputeResult {
+                size: Size {
+                    width: node_size.width.or_else(0.0) + constants.padding_border.horizontal(),
+                    height: node_size.height.or_else(0.0) + constants.padding_border.vertical(),
+                },
+            };
         }
 
+        // 9. Flex Layout Algorithm
+
+        // 9.1. Initial Setup
+
+        // 1. Generate anonymous flex items as described in §4 Flex Items.
+        let mut flex_items = self.generate_anonymous_flex_items(node, &constants);
+
+        // 9.2. Line Length Determination
+
+        // 2. Determine the available main and cross space for the flex items.
+        let available_space = Self::determine_available_space(node_size, parent_size, &constants);
+
+        let has_baseline_child = flex_items
+            .iter()
+            .any(|child| self.nodes[child.node].style.align_self(&self.nodes[node].style) == AlignSelf::Baseline);
+
+        // 3. Determine the flex base size and hypothetical main size of each item.
+        self.determine_flex_base_size(node, node_size, &constants, available_space, &mut flex_items);
+
+        // TODO: Add step 4 according to spec: https://www.w3.org/TR/css-flexbox-1/#algo-main-container
+        // 9.3. Main Size Determination
+
+        // 5. Collect flex items into flex lines.
+        let mut flex_lines = self.collect_flex_lines(node, &constants, available_space, &mut flex_items);
+
+        // 6. Resolve the flexible lengths of all the flex items to find their used main size.
+        for line in &mut flex_lines {
+            self.resolve_flexible_lengths(line, &constants, available_space);
+        }
+
+        // TODO: Cleanup and make according to spec
+        // Not part of the spec from what i can see but seems correct
+        constants.container_size.set_main(
+            constants.dir,
+            node_size.main(constants.dir).or_else({
+                let longest_line = flex_lines.iter().fold(f32::MIN, |acc, line| {
+                    let length: f32 = line.items.iter().map(|item| item.outer_target_size.main(constants.dir)).sum();
+                    acc.max(length)
+                });
+
+                let size = longest_line + constants.padding_border.main(constants.dir);
+                match available_space.main(constants.dir) {
+                    Defined(val) if flex_lines.len() > 1 && size < val => val,
+                    _ => size,
+                }
+            }),
+        );
+
+        constants.inner_container_size.set_main(
+            constants.dir,
+            constants.container_size.main(constants.dir) - constants.padding_border.main(constants.dir),
+        );
+
+        // 9.4. Cross Size Determination
+
+        // 7. Determine the hypothetical cross size of each item.
+        for line in &mut flex_lines {
+            self.determine_hypothetical_cross_size(line, &constants, available_space);
+        }
+
+        // TODO - probably should move this somewhere else as it doesn't make a ton of sense here but we need it below
+        // TODO - This is expensive and should only be done if we really require a baseline. aka, make it lazy
+        if has_baseline_child {
+            self.calculate_children_base_lines(node, node_size, &mut flex_lines, &constants);
+        }
+
+        // 8. Calculate the cross size of each flex line.
+        self.calculate_cross_size(&mut flex_lines, node, node_size, &constants);
+
+        // 9. Handle 'align-content: stretch'.
+        self.handle_align_content_stretch(&mut flex_lines, node, node_size, &constants);
+
+        // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
+        //     note the cross size of the line they’re in as the item’s strut size, and restart
+        //     layout from the beginning.
+        //
+        //     In this second layout round, when collecting items into lines, treat the collapsed
+        //     items as having zero main size. For the rest of the algorithm following that step,
+        //     ignore the collapsed items entirely (as if they were display:none) except that after
+        //     calculating the cross size of the lines, if any line’s cross size is less than the
+        //     largest strut size among all the collapsed items in the line, set its cross size to
+        //     that strut size.
+        //
+        //     Skip this step in the second layout round.
+
+        // TODO implement once (if ever) we support visibility:collapse
+
+        // 11. Determine the used cross size of each flex item.
+        self.determine_used_cross_size(&mut flex_lines, node, &constants);
+
+        // 9.5. Main-Axis Alignment
+
+        // 12. Distribute any remaining free space.
+        self.distribute_remaining_free_space(&mut flex_lines, node, &constants);
+
+        // 9.6. Cross-Axis Alignment
+
+        // 13. Resolve cross-axis auto margins (also includes 14).
+        self.resolve_cross_axis_auto_margins(&mut flex_lines, node, &constants);
+
+        // 15. Determine the flex container’s used cross size.
+        let total_cross_size = Self::determine_container_cross_size(&mut flex_lines, node_size, &mut constants);
+
+        // We have the container size.
+        // If our caller does not care about performing layout we are done now.
+        if !perform_layout {
+            let result = ComputeResult { size: constants.container_size };
+            *self.cache(node, main_size) =
+                Some(result::Cache { node_size, parent_size, perform_layout, result: result.clone() });
+            return result;
+        }
+
+        // 16. Align all flex lines per align-content.
+        self.align_flex_lines_per_align_content(&mut flex_lines, node, &constants, total_cross_size);
+
+        // Do a final layout pass and gather the resulting layouts
+        self.final_layout_pass(node, &mut flex_lines, &constants);
+
+        // Before returning we perform absolute layout on all absolutely positioned children
+        self.perform_absolute_layout_on_absolute_children(node, &constants);
+
         fn hidden_layout(nodes: &mut [NodeData], children: &[sys::ChildrenVec<NodeId>], node: NodeId, order: u32) {
             nodes[node].layout = result::Layout { order, size: Size::zero(), location: Point::zero() };
 
@@ -1324,7 +1676,7 @@ impl Forest {
             }
         }
 
-        let result = ComputeResult { size: container_size };
+        let result = ComputeResult { size: constants.container_size };
         *self.cache(node, main_size) =
             Some(result::Cache { node_size, parent_size, perform_layout, result: result.clone() });