Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Small caps synthesised, flex lines with a 1/64 px tolerance, and a table's stray text in anonymous cells (#257)

shane845f7438d5d3
diff --git a/Cargo.lock b/Cargo.lock
index 5726baec..44dd9c59 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -20427,8 +20427,6 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
diff --git a/Cargo.toml b/Cargo.toml
index dd0e241c..d6a26193 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -407,6 +407,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
+# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
+# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
+# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
+taffy = { path = "vendor/taffy" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
diff --git a/systems/page/tests/layout_0112.rs b/systems/page/tests/layout_0112.rs
new file mode 100644
index 00000000..33bda5d2
--- /dev/null
+++ b/systems/page/tests/layout_0112.rs
@@ -0,0 +1,92 @@
+//! Three of 0.1.11's layout misses, each laid out from its issue's own repro: `font-variant: small-caps` drew in normal
+//! case (#249), a flex row whose items fit but for f32 rounding wrapped (#252), and a `display: table` element around
+//! its text drew nothing at all (#254).
+use bevy::math::UVec2;
+use blitz_dom::BaseDocument;
+use raea_sys_page::{Page, config};
+
+fn laid_out(body: &str) -> BaseDocument {
+ let html = format!("<!doctype html><html><body style=\"margin:0\">{body}</body></html>");
+ let mut doc = blitz_html::HtmlDocument::from_html(&html, config(Page { size: UVec2::new(700, 400), scale: 1.0 })).into_inner();
+ doc.resolve(0.0);
+ doc
+}
+
+/// The border box of the element with `id`: x, y, width, height.
+fn rect(doc: &BaseDocument, id: &str) -> (f64, f64, f64, f64) {
+ let node = doc.query_selector(&format!("#{id}")).unwrap().unwrap_or_else(|| panic!("no #{id}"));
+ let r = doc.get_client_bounding_rect(node).unwrap_or_else(|| panic!("#{id} has no box"));
+ (r.x, r.y, r.width, r.height)
+}
+
+/// #249: small capitals in a face without an `smcp` feature (Georgia) are synthesised as Chrome does: each lower-case
+/// letter drawn as its capital at 70% of the font size. So the line is as wide as those capitals written out at 28 px,
+/// and narrower than the text in full capitals.
+#[test]
+fn small_caps_are_synthesised_capitals_at_70_percent() {
+ let doc = laid_out(
+ r#"<div style="font-size: 40px; font-family: Georgia, serif">
+ <span id="caps" style="font-variant: small-caps">Compliance Audit</span><br>
+ <span id="spelled">C<span style="font-size: 28px">OMPLIANCE</span> A<span style="font-size: 28px">UDIT</span></span><br>
+ <span id="plain">Compliance Audit</span><br>
+ <span id="upper">COMPLIANCE AUDIT</span>
+ </div>"#,
+ );
+ let width = |id| rect(&doc, id).2;
+ let (caps, spelled, plain, upper) = (width("caps"), width("spelled"), width("plain"), width("upper"));
+ assert!((caps - spelled).abs() < 0.5, "small caps {caps} px wide, the capitals written out at 28 px {spelled}");
+ assert!(caps < upper - 20.0, "small caps {caps} px wide, full capitals {upper}");
+ assert!((caps - plain).abs() > 5.0, "small caps {caps} px wide, the text in normal case {plain}: drawn as it is");
+}
+
+/// #252: three 183.6 px items and two 54 px gaps add up to the 658.8 px container in exact arithmetic, a few ulps over
+/// it in f32. Chrome lays out in 1/64 px units and keeps them on one line: rows of 3 and 2, not 2, 2 and 1.
+#[test]
+fn a_flex_row_that_fits_but_for_rounding_stays_one_row() {
+ let (w, size, cols) = (1080.0_f64, 0.17, 3.0);
+ let items: String = (0..5).map(|i| format!(r#"<div id="i{i}" style="width: {}px; height: 60px"></div>"#, size * w)).collect();
+ let doc = laid_out(&format!(
+ r#"<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: {}px {}px; width: {}px">{items}</div>"#,
+ 0.04 * w,
+ 0.05 * w,
+ (cols * size + (cols - 1.0) * 0.05) * w
+ ));
+ let y = |i: usize| rect(&doc, &format!("i{i}")).1;
+ assert_eq!((y(1), y(2)), (y(0), y(0)), "the first three items share a row");
+ assert!(y(3) > y(0) && y(4) == y(3), "the last two share the second row: {:?}", (0..5).map(y).collect::<Vec<_>>());
+}
+
+/// #254: a `display: table` element holding only text is laid out as Chrome lays it out, its text in an anonymous row
+/// and cell: a block as wide as its text (shrink-to-fit), with the next block below it.
+#[test]
+fn a_table_around_its_text_is_as_wide_as_its_text() {
+ let doc = laid_out(
+ r#"<div style="font-size: 30px">
+ <div id="table" style="display: table; background: #FFD43B">Line one as a table</div>
+ <div id="next">Line two, block</div>
+ <span id="text">Line one as a table</span>
+ </div>"#,
+ );
+ let (tx, ty, tw, th) = rect(&doc, "table");
+ let text = rect(&doc, "text");
+ let next = rect(&doc, "next");
+ assert!(th > 30.0, "the table is a line tall: {th}");
+ assert!((tw - text.2).abs() < 0.5, "the table is {tw} px wide, its text {}", text.2);
+ assert_eq!((tx, ty), (0.0, 0.0));
+ assert!((next.1 - (ty + th)).abs() < 0.5, "the next block starts below the table: {} against {}", next.1, ty + th);
+}
+
+/// #254, the rest of css-tables-3's wrapping: a table's stray text beside a row of its own gets an anonymous row of its
+/// own above it, and a table of rows alone builds no anonymous box (its cells as before).
+#[test]
+fn stray_text_beside_a_row_gets_a_row_of_its_own() {
+ let doc = laid_out(
+ r#"<div id="t" style="display: table; font-size: 20px">loose
+ <div style="display: table-row"><div id="cell" style="display: table-cell">in a cell</div></div></div>
+ <table id="plain"><tr><td id="td">a</td></tr></table>"#,
+ );
+ let cell = rect(&doc, "cell");
+ assert!(cell.1 >= 20.0, "the cell is in the second row, below the loose text: {cell:?}");
+ let td = rect(&doc, "td");
+ assert!(td.2 > 0.0 && td.3 > 0.0, "a plain table's cell keeps its box: {td:?}");
+}
diff --git a/vendor/blitz-dom/src/font_metrics.rs b/vendor/blitz-dom/src/font_metrics.rs
index 5273cdfa..6d55bd3b 100644
--- a/vendor/blitz-dom/src/font_metrics.rs
+++ b/vendor/blitz-dom/src/font_metrics.rs
@@ -13,7 +13,8 @@ use style::{
};
/// Query fontique for the fonts matching `font_styles` (family list and attributes).
-fn query_for_font_styles<'a>(
+/// raea: small_caps.rs asks it for the face it checks for `smcp` (#249)
+pub(crate) fn query_for_font_styles<'a>(
font_ctx: &'a mut FontContext,
font_styles: &'a FontStyles,
) -> parley::fontique::Query<'a> {
diff --git a/vendor/blitz-dom/src/layout/construct.rs b/vendor/blitz-dom/src/layout/construct.rs
index 75580d28..6b247a07 100644
--- a/vendor/blitz-dom/src/layout/construct.rs
+++ b/vendor/blitz-dom/src/layout/construct.rs
@@ -573,7 +573,9 @@ fn collect_layout_children_with_wrap(
}
DisplayInside::Table => {
- let (table_context, tlayout_children) = build_table_context(doc, container_node_id);
+ let wrapped = wrap_table_strays(doc, container_node_id, out);
+ let (table_context, tlayout_children) =
+ build_table_context(doc, container_node_id, wrapped);
#[allow(clippy::arc_with_non_send_sync)]
let data = SpecialElementData::TableRoot(Arc::new(table_context));
doc.nodes[container_node_id]
@@ -802,6 +804,49 @@ fn flush_pseudo_elements(doc: &mut BaseDocument, node_id: NodeId) {
}
}
+/// raea: a table's children with each run of children that are no table box (text, a block or inline element, a
+/// table inside it) wrapped in an anonymous block, which table.rs lays out as an anonymous row holding one anonymous
+/// cell (css-tables-3 § 3.3, as Chrome does). Blitz dropped them, so a `display: table` element around its text (a
+/// shrink-wrapped line) drew nothing, not even its background (#254). None when there is no such run (no text but
+/// whitespace), so a table of rows builds no anonymous block. The blocks are `out`'s to free on reconstruction.
+fn wrap_table_strays(
+ doc: &mut BaseDocument,
+ table_id: NodeId,
+ out: &mut LayoutChildren,
+) -> Option<Vec<NodeId>> {
+ fn is_stray(node: &Node) -> bool {
+ match node.data.kind() {
+ NodeKind::Text => true,
+ NodeKind::Element => node.primary_styles().is_some_and(|style| {
+ let display = style.clone_display();
+ matches!(display.outside(), DisplayOutside::Block | DisplayOutside::Inline)
+ && display.inside() != DisplayInside::Contents
+ && !style.clone_position().is_absolutely_positioned()
+ }),
+ _ => false,
+ }
+ }
+ let children = doc.nodes[table_id].children.clone();
+ let any = children.iter().any(|&id| {
+ let node = &doc.nodes[id];
+ is_stray(node) && !node.is_whitespace_node()
+ });
+ if !any {
+ return None;
+ }
+ let mut runs = LayoutChildren::default();
+ for id in children {
+ match doc.nodes[id].data.kind() {
+ NodeKind::Comment => {}
+ _ if is_stray(&doc.nodes[id]) => runs.push_wrapped(table_id, id, doc),
+ _ => runs.push(id, doc),
+ }
+ }
+ runs.maybe_push_anon_block(doc);
+ out.anonymous_blocks.extend(runs.anonymous_blocks.iter().copied());
+ Some(runs.children.into_iter().collect())
+}
+
/// Handles the cases where there are text nodes or inline nodes that need to be wrapped in an anonymous block node
fn collect_complex_layout_children(
doc: &mut BaseDocument,
@@ -1085,6 +1130,10 @@ pub(crate) fn build_inline_layout_into(
..Default::default()
});
+ // raea: which of its elements' text gets synthesised small capitals, asked of the fonts before the builder holds
+ // them (#249)
+ let small_caps = super::small_caps::synthesized(nodes, inline_context_root_node_id, font_ctx);
+
// Create a parley tree builder
let mut builder = layout_ctx.tree_builder(font_ctx, scale, true, &parley_style);
if let Some(style) = root_node_style.as_deref() {
@@ -1124,6 +1173,7 @@ pub(crate) fn build_inline_layout_into(
};
// The marker is a separate box, so words in the content don't continue from it.
let mut text_transformer = TextTransformer::default();
+ text_transformer.small_caps = small_caps;
text_transformer.word_break(&builder);
// raea: the root's bidi override around its content (stylo_to_parley::bidi_controls)
@@ -1395,10 +1445,18 @@ pub(crate) fn build_inline_layout_into(
s.clone_white_space_collapse() != stylo_to_parley::stylo::WhiteSpaceCollapse::Collapse
});
let bidi = if keeps_newlines { std::mem::take(&mut text_transformer.bidi) } else { Vec::new() };
+ // raea: the font size its synthesised small capitals scale, when they're its parent's (#249)
+ let small_caps = node
+ .parent
+ .filter(|p| text_transformer.small_caps.contains(p))
+ .and_then(|p| nodes[p].primary_styles().map(|s| s.get_font().font_size.used_size.0.px()));
let text =
text_transformer.transform(&data.content, parent_text_transform, builder);
let start = builder.text().len();
- builder.push_text(&bidi_newlines(text, &bidi));
+ match small_caps {
+ Some(font_size) => super::small_caps::push(builder, &bidi_newlines(text, &bidi), font_size),
+ None => builder.push_text(&bidi_newlines(text, &bidi)),
+ }
text_transformer.texts.push((node_id, start, builder.text().len()));
if keeps_newlines {
text_transformer.bidi = bidi;
diff --git a/vendor/blitz-dom/src/layout/mod.rs b/vendor/blitz-dom/src/layout/mod.rs
index a261f63f..823c4e25 100644
--- a/vendor/blitz-dom/src/layout/mod.rs
+++ b/vendor/blitz-dom/src/layout/mod.rs
@@ -28,6 +28,8 @@ pub(crate) mod inline;
pub(crate) mod list;
pub(crate) mod paint_tree;
pub(crate) mod replaced;
+// raea: synthesised small capitals (#249)
+pub(crate) mod small_caps;
pub(crate) mod table;
pub(crate) mod text_transform;
#[cfg(feature = "writing-mode")]
diff --git a/vendor/blitz-dom/src/layout/small_caps.rs b/vendor/blitz-dom/src/layout/small_caps.rs
new file mode 100644
index 00000000..2d5c250b
--- /dev/null
+++ b/vendor/blitz-dom/src/layout/small_caps.rs
@@ -0,0 +1,143 @@
+//! raea: `font-variant: small-caps` as Chrome draws it (#249). A face with an `smcp` feature gets it
+//! (stylo_to_parley::font_variant_caps); for a face without one (Georgia, Times, Helvetica: most system faces) Chrome
+//! synthesises the small capitals, each lower-case letter drawn as its capital at 70% of the font size (Blink's
+//! kSmallCapsFontSizeMultiplier). Blitz only asked for the feature, so such text drew in normal case, with no warning.
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+
+use blitz_traits::node_id::NodeId;
+use parley::fontique::{QueryFont, QueryStatus};
+use parley::{FontContext, StyleProperty, TreeBuilder};
+use skrifa::MetadataProvider as _;
+use skrifa::raw::TableProvider as _;
+use style::properties::style_structs::Font as FontStyles;
+
+use crate::font_metrics::query_for_font_styles;
+use crate::node::TextBrush;
+use crate::stylo_to_parley::stylo::FontVariantCaps;
+
+/// The size of a synthesised small capital, as a fraction of the font size (Blink's)
+pub(crate) const SCALE: f32 = 0.7;
+
+thread_local! {
+ /// whether a face (its blob's id and index in it) has an `smcp` feature, read once
+ static SMCP: RefCell<HashMap<(u64, u32), bool>> = RefCell::new(HashMap::new());
+}
+
+/// The elements whose text under `root` (an inline layout's root) is drawn in synthesised small capitals: each text
+/// node's parent (its DOM parent, which an anonymous block wrapping the text isn't) whose font-variant-caps is
+/// small-caps, in a face whose lower-case letters have no `smcp` feature.
+pub(crate) fn synthesized(nodes: &crate::NodeTree, root: NodeId, fcx: &mut FontContext) -> Vec<NodeId> {
+ let mut out = Vec::new();
+ let mut stack = vec![root];
+ while let Some(id) = stack.pop() {
+ let node = &nodes[id];
+ if node.is_text_node() {
+ let Some(parent) = node.parent.filter(|p| !out.contains(p)) else { continue };
+ let Some(style) = nodes[parent].primary_styles() else { continue };
+ let font = style.get_font();
+ if font.font_variant_caps == FontVariantCaps::SmallCaps && !has_smcp(fcx, font) {
+ out.push(parent);
+ }
+ continue;
+ }
+ stack.extend(node.children.iter().copied());
+ stack.extend(node.before());
+ stack.extend(node.after());
+ }
+ out
+}
+
+/// Whether the face `font` draws a lower-case `a` in has an `smcp` feature (true when no face has the letter: then
+/// there is nothing to synthesise).
+fn has_smcp(fcx: &mut FontContext, font: &FontStyles) -> bool {
+ let mut query = query_for_font_styles(fcx, font);
+ let mut face = None;
+ query.matches_with(|q: &QueryFont| {
+ let maps = skrifa::FontRef::from_index(q.blob.as_ref(), q.index).is_ok_and(|f| f.charmap().map('a').is_some());
+ if !maps {
+ return QueryStatus::Continue;
+ }
+ face = Some((q.blob.clone(), q.index));
+ QueryStatus::Stop
+ });
+ let Some((blob, index)) = face else { return true };
+ SMCP.with(|seen| *seen.borrow_mut().entry((blob.id(), index)).or_insert_with(|| has_feature(blob.as_ref(), index, b"smcp")))
+}
+
+/// Whether the face at `index` in `data` lists the GSUB feature `tag`.
+pub(crate) fn has_feature(data: &[u8], index: u32, tag: &[u8; 4]) -> bool {
+ let tag = skrifa::Tag::new(tag);
+ let Ok(font) = skrifa::FontRef::from_index(data, index) else { return false };
+ let Ok(list) = font.gsub().and_then(|gsub| gsub.feature_list()) else { return false };
+ list.feature_records().iter().any(|record| record.feature_tag() == tag)
+}
+
+/// A lower-case letter a synthesised small capital replaces: one with a capital of its own.
+fn is_small(c: char) -> bool {
+ c.is_lowercase() && !c.to_uppercase().eq(std::iter::once(c))
+}
+
+/// `text` pushed with each run of lower-case letters as their capitals at SCALE of `font_size` (px), the rest as it is.
+pub(crate) fn push(builder: &mut TreeBuilder<TextBrush>, text: &str, font_size: f32) {
+ let mut rest = text;
+ while let Some(first) = rest.chars().next() {
+ let small = is_small(first);
+ let end = rest.char_indices().find(|&(_, c)| is_small(c) != small).map_or(rest.len(), |(i, _)| i);
+ let (run, tail) = rest.split_at(end);
+ if small {
+ builder.push_style_modification_span(&[StyleProperty::FontSize(font_size * SCALE)]);
+ builder.push_text(&run.to_uppercase());
+ builder.pop_style_span();
+ } else {
+ builder.push_text(run);
+ }
+ rest = tail;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use parley::{LayoutContext, TextStyle};
+
+ /// Each glyph run's text and font size, for `text` pushed as small capitals at 40 px.
+ fn runs(text: &str) -> Vec<(String, f32)> {
+ let mut font_ctx = FontContext::new();
+ let mut layout_ctx: LayoutContext<TextBrush> = LayoutContext::new();
+ let style = TextStyle { font_size: 40.0, ..TextStyle::default() };
+ let mut builder = layout_ctx.tree_builder(&mut font_ctx, 1.0, true, &style);
+ push(&mut builder, text, 40.0);
+ let mut layout = parley::Layout::new();
+ let built = builder.build_into(&mut layout);
+ layout.break_all_lines(None);
+ let mut out = Vec::new();
+ for line in layout.lines() {
+ for item in line.items() {
+ if let parley::PositionedLayoutItem::GlyphRun(run) = item {
+ out.push((built[run.run().text_range()].to_string(), run.run().font_size()));
+ }
+ }
+ }
+ out
+ }
+
+ #[test]
+ fn lower_case_letters_are_capitals_at_70_percent() {
+ let want = [("C", 40.0), ("OMPLIANCE", 28.0), (" A", 40.0), ("UDIT", 28.0)];
+ let want: Vec<(String, f32)> = want.iter().map(|(t, s)| (t.to_string(), *s)).collect();
+ assert_eq!(runs("Compliance Audit"), want);
+ }
+
+ #[test]
+ fn capitals_digits_and_spaces_keep_their_size() {
+ assert_eq!(runs("A1 B"), vec![("A1 B".to_string(), 40.0)]);
+ }
+
+ #[test]
+ fn a_letter_without_a_capital_of_its_own_keeps_its_size() {
+ // U+0138 kra is lower-case and has no capital
+ assert!(!is_small('ĸ') && is_small('a') && !is_small('A') && !is_small('1'));
+ }
+}
diff --git a/vendor/blitz-dom/src/layout/table.rs b/vendor/blitz-dom/src/layout/table.rs
index 041bbdd3..57efa0b2 100644
--- a/vendor/blitz-dom/src/layout/table.rs
+++ b/vendor/blitz-dom/src/layout/table.rs
@@ -208,9 +208,12 @@ fn percent_plus_length(
dim.into()
}
+/// raea: `wrapped` is the table's children with each run of children that are no table box (its text, a block or
+/// an inline element) in an anonymous block (construct.rs `wrap_table_strays`, #254); None when it has no such run
pub(crate) fn build_table_context(
doc: &mut BaseDocument,
table_root_node_id: NodeId,
+ wrapped: Option<Vec<NodeId>>,
) -> (TableContext, Vec<NodeId>) {
let mut cells: Vec<TableCell> = Vec::new();
let mut oof_children: Vec<(NodeId, taffy::Position)> = Vec::new();
@@ -221,7 +224,8 @@ pub(crate) fn build_table_context(
let wm = table_wm(doc, table_root_node_id);
let root_node = &mut doc.nodes[table_root_node_id];
- let children = std::mem::take(&mut root_node.children);
+ let dom_children = std::mem::take(&mut root_node.children);
+ let children = wrapped.unwrap_or_else(|| dom_children.to_vec());
let Some(stylo_styles) = root_node.primary_styles() else {
panic!("Ignoring table because it has no styles");
@@ -469,7 +473,7 @@ pub(crate) fn build_table_context(
.chain(oof_children.iter().map(|(node_id, _)| *node_id))
.collect();
let root_node = &mut doc.nodes[table_root_node_id];
- root_node.children = children;
+ root_node.children = dom_children;
(
TableContext {
@@ -582,7 +586,9 @@ fn collect_table_cells(
) {
let node = &mut doc.nodes[node_id];
- if !node.is_element() {
+ // raea: an anonymous block here is one construct.rs wrapped a run of the table's stray children in (#254)
+ let anonymous = node.is_anonymous();
+ if !node.is_element() && !anonymous {
return;
}
@@ -605,7 +611,16 @@ fn collect_table_cells(
return;
}
- match display.inside() {
+ // raea: it is an anonymous row holding one anonymous cell, as css-tables-3 § 3.3 wraps such a run (#254)
+ let inside = if anonymous {
+ *row += 1;
+ cursor.start_row();
+ rows.push(TableRow { node_id, group: None, height: None, is_constrained: false });
+ DisplayInside::TableCell
+ } else {
+ display.inside()
+ };
+ match inside {
DisplayInside::TableRowGroup
| DisplayInside::TableHeaderGroup
| DisplayInside::TableFooterGroup
diff --git a/vendor/blitz-dom/src/layout/text_transform.rs b/vendor/blitz-dom/src/layout/text_transform.rs
index 82ed9bbb..d167bac3 100644
--- a/vendor/blitz-dom/src/layout/text_transform.rs
+++ b/vendor/blitz-dom/src/layout/text_transform.rs
@@ -117,6 +117,8 @@ pub(crate) struct TextTransformer {
pub(crate) bidi: Vec<(&'static str, &'static str)>,
/// raea: each text node's bytes in the builder's text, as pushed (TextLayout::text_nodes)
pub(crate) texts: Vec<(blitz_traits::node_id::NodeId, usize, usize)>,
+ /// raea: the elements whose own text is drawn in synthesised small capitals (layout/small_caps.rs, #249)
+ pub(crate) small_caps: Vec<blitz_traits::node_id::NodeId>,
}
impl TextTransformer {
diff --git a/vendor/taffy/Cargo.toml b/vendor/taffy/Cargo.toml
new file mode 100644
index 00000000..cd172e25
--- /dev/null
+++ b/vendor/taffy/Cargo.toml
@@ -0,0 +1,168 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.71"
+name = "taffy"
+version = "0.15.0"
+authors = [
+ "Alice Cecile <[email protected]>",
+ "Johnathan Kelley <[email protected]>",
+ "Nico Burns <[email protected]>",
+]
+build = false
+include = [
+ "src/**/*",
+ "examples/**/*",
+ "Cargo.toml",
+ "README.md",
+]
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "A flexible UI layout library "
+readme = "README.md"
+keywords = [
+ "cross-platform",
+ "layout",
+ "flexbox",
+ "css-grid",
+ "grid",
+]
+categories = ["gui"]
+license = "MIT"
+repository = "https://github.com/DioxusLabs/taffy"
+
+[package.metadata.docs.rs]
+all-features = true
+cargo-args = [
+ "-Zunstable-options",
+ "-Zrustdoc-scrape-examples",
+]
+rustdoc-args = [
+ "--cfg",
+ "docsrs",
+]
+
+[features]
+alloc = []
+block_layout = []
+calc = []
+content_size = []
+debug = ["std"]
+default = [
+ "std",
+ "taffy_tree",
+ "flexbox",
+ "flexbox_balance",
+ "grid",
+ "block_layout",
+ "float_layout",
+ "calc",
+ "content_size",
+ "detailed_layout_info",
+]
+detailed_layout_info = []
+flexbox = []
+flexbox_balance = ["flexbox"]
+float_layout = []
+grid = ["dep:smallvec"]
+parse = ["dep:cssparser"]
+parse_faster = [
+ "parse",
+ "cssparser/fast_match_byte",
+]
+profile = ["std"]
+serde = [
+ "dep:serde",
+ "serde/alloc",
+]
+std = [
+ "serde?/std",
+ "slotmap?/std",
+]
+strict_provenance = []
+taffy_tree = ["dep:slotmap"]
+
+[lib]
+name = "taffy"
+path = "src/lib.rs"
+
+[[example]]
+name = "basic"
+path = "examples/basic.rs"
+doc-scrape-examples = true
+
+[[example]]
+name = "custom_tree_owned_partial"
+path = "examples/custom_tree_owned_partial.rs"
+
+[[example]]
+name = "custom_tree_owned_unsafe"
+path = "examples/custom_tree_owned_unsafe.rs"
+
+[[example]]
+name = "custom_tree_vec"
+path = "examples/custom_tree_vec.rs"
+
+[[example]]
+name = "flexbox_gap"
+path = "examples/flexbox_gap.rs"
+
+[[example]]
+name = "grid_holy_grail"
+path = "examples/grid_holy_grail.rs"
+
+[[example]]
+name = "measure"
+path = "examples/measure.rs"
+
+[[example]]
+name = "nested"
+path = "examples/nested.rs"
+
+[dependencies.cssparser]
+version = "0.37.0"
+optional = true
+default-features = false
+
+[dependencies.document-features]
+version = "0.2.7"
+optional = true
+
+[dependencies.serde]
+version = "1.0"
+features = ["serde_derive"]
+optional = true
+default-features = false
+
+[dependencies.slotmap]
+version = "1.0.6"
+optional = true
+default-features = false
+
+[dependencies.smallvec]
+version = "1.13"
+optional = true
+default-features = false
+
+[dev-dependencies.roxmltree]
+version = "0.21.1"
+
+[dev-dependencies.serde_json]
+version = "1.0.93"
+
+[profile.release]
+lto = true
+panic = "abort"
diff --git a/vendor/taffy/Cargo.toml.orig b/vendor/taffy/Cargo.toml.orig
new file mode 100644
index 00000000..09870c3a
--- /dev/null
+++ b/vendor/taffy/Cargo.toml.orig
@@ -0,0 +1,124 @@
+[package]
+name = "taffy"
+version = "0.15.0"
+authors = [
+ "Alice Cecile <[email protected]>",
+ "Johnathan Kelley <[email protected]>",
+ "Nico Burns <[email protected]>",
+]
+edition = "2021"
+rust-version = "1.71"
+include = ["src/**/*", "examples/**/*", "Cargo.toml", "README.md"]
+description = "A flexible UI layout library "
+repository = "https://github.com/DioxusLabs/taffy"
+keywords = ["cross-platform", "layout", "flexbox", "css-grid", "grid"]
+categories = ["gui"]
+license = "MIT"
+
+[dependencies]
+document-features = { version = "0.2.7", optional = true }
+serde = { version = "1.0", default-features = false, optional = true, features = ["serde_derive"] }
+slotmap = { version = "1.0.6", default-features = false, optional = true }
+smallvec = { version = "1.13", default-features = false, optional = true }
+cssparser = { version = "0.37.0", default-features = false, optional = true }
+
+[package.metadata.docs.rs]
+# To test all the documentation related features, run:
+# RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc -Zunstable-options -Zrustdoc-scrape-examples --all-features --no-deps --open
+
+all-features = true
+# see https://doc.rust-lang.org/nightly/rustdoc/scraped-examples.html
+cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
+rustdoc-args = ["--cfg", "docsrs"]
+
+[features]
+default = [
+ "std",
+ "taffy_tree",
+ "flexbox",
+ "flexbox_balance",
+ "grid",
+ "block_layout",
+ "float_layout",
+ "calc",
+ "content_size",
+ "detailed_layout_info",
+]
+#! ## Feature Flags
+#!
+#! ### Algorithms
+
+## Enables the Block layout algorithm. See [`compute_block_layout`](crate::compute_block_layout).
+block_layout = []
+## Enables the Float layout algorithm. This is a sub-feature of block layout.
+float_layout = []
+## Enables the Flexbox layout algorithm. See [`compute_flexbox_layout`](crate::compute_flexbox_layout).
+flexbox = []
+## Enables support for `flex-wrap: balance` and `flex-line-count` from [CSS Flexbox Level 2](https://drafts.csswg.org/css-flexbox-2/)
+flexbox_balance = ["flexbox"]
+## Enables the CSS Grid layout algorithm. See [`compute_grid_layout`](crate::compute_grid_layout).
+grid = ["dep:smallvec"]
+## Enables calc() values for all layout algorithms
+calc = []
+## Causes all algorithms to compute and output a content size for each node
+content_size = []
+## Causes algorithms to stores detailed information of the nodes in TaffyTree, with only CSS Grid supporting this.
+detailed_layout_info = []
+## Use strict provenance APIs for pointer manipulation. Using this feature requires Rust 1.84 or higher.
+strict_provenance = []
+
+#! ### Taffy Tree
+
+## Enable the built-in Taffy node tree. See [`TaffyTree`](crate::TaffyTree).
+taffy_tree = ["dep:slotmap"]
+
+#! ### Other
+
+## Add [`serde`] derives to Style structs
+serde = ["dep:serde", "serde/alloc"]
+## Implement `FromStr` trait for Taffy style types
+parse = ["dep:cssparser"]
+## Enable the `parse` feature with proc-macro dependent optimisations
+parse_faster = ["parse", "cssparser/fast_match_byte"]
+## Allow Taffy to depend on the [`Rust Standard Library`](std)
+std = ["serde?/std", "slotmap?/std"]
+## Deprecated no-op: Taffy always depends on the `alloc` library. Retained so that existing `features = ["alloc"]` configurations keep compiling.
+alloc = []
+## Internal feature for debugging
+debug = ["std"]
+## Internal feature for profiling
+profile = ["std"]
+
+[dev-dependencies]
+serde_json = "1.0.93"
+roxmltree = "0.21.1"
+taffy_test_helpers = { path = "tests/common"}
+
+# Enable default features for tests and examples
+taffy = { path = ".", features = ["parse"] }
+
+[profile.release]
+lto = true
+panic = 'abort'
+
+[[bench]]
+name = "dummy_benchmark"
+path = "benches/dummy_benchmark.rs"
+harness = false
+
+[[example]]
+name = "basic"
+# This causes all the examples to be scraped for documentation, not just the basic example
+doc-scrape-examples = true
+
+[workspace]
+members = [
+ "scripts/gentest",
+ "scripts/getchrome",
+ "scripts/format-fixtures",
+ "scripts/import-yoga-tests",
+ "tests/common",
+]
+# The Parley example and benches are excluded from the workspace as their dependencies require a newer
+# Rust version than Taffy's MSRV
+exclude = ["examples/parley", "benches"]
diff --git a/vendor/taffy/README.md b/vendor/taffy/README.md
new file mode 100644
index 00000000..11e2f478
--- /dev/null
+++ b/vendor/taffy/README.md
@@ -0,0 +1,139 @@
+<!-- markdownlint-disable-next-line MD041 -->
+<p>
+<picture>
+ <img src="assets/logo.svg" alt="Taffy" height="70">
+</picture>
+</p>
+
+[![GitHub CI](https://github.com/DioxusLabs/taffy/actions/workflows/ci.yml/badge.svg)](https://github.com/DioxusLabs/taffy/actions/workflows/ci.yml)
+[![crates.io](https://img.shields.io/crates/v/taffy.svg)](https://crates.io/crates/taffy)
+[![docs.rs](https://img.shields.io/docsrs/taffy)](https://docs.rs/taffy)
+![Crates.io MSRV](https://img.shields.io/crates/msrv/taffy)
+
+Taffy is a flexible, high-performance, cross-platform UI layout library written in [Rust](https://www.rust-lang.org).
+
+It currently implements the CSS **Block**, **Flexbox** and **CSS Grid** layout algorithms. Support for other paradigms is planned. For more information on this and other future development plans see the [roadmap issue](https://github.com/DioxusLabs/taffy/issues/345).
+
+This crate is a collaborative, cross-team project, and is designed to be used as a dependency for other UI and GUI libraries.
+Right now, it powers:
+
+- [Servo](https://github.com/servo/servo): an alternative web browser
+- [Blitz](https://github.com/DioxusLabs/blitz): a radically modular web engine
+- [Bevy](https://bevyengine.org/): an ergonomic, ECS-first Rust game engine
+- [Takumi](https://github.com/kane50613/takumi): Renders your React components to images
+- [iocraft](https://github.com/ccbrown/iocraft): crafting beautiful interfaces for the terminal
+- [Slint](https://github.com/slint-ui/slint): a declarative GUI toolkit for building native user interfaces
+- The [Lapce](https://lapce.dev/) text editor via the [Floem](https://github.com/lapce/floem) UI framework
+- The [Zed](https://zed.dev/) text editor via the [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui) UI framework
+
+## Usage
+
+```rust
+use taffy::prelude::*;
+
+// First create an instance of TaffyTree
+let mut tree : TaffyTree<()> = TaffyTree::new();
+
+// Create a tree of nodes using `TaffyTree.new_leaf` and `TaffyTree.new_with_children`.
+// These functions both return a node id which can be used to refer to that node
+// The Style struct is used to specify styling information
+let header_node = tree
+ .new_leaf(
+ Style {
+ size: Size { width: length(800.0), height: length(100.0) },
+ ..Default::default()
+ },
+ ).unwrap();
+
+let body_node = tree
+ .new_leaf(
+ Style {
+ size: Size { width: length(800.0), height: auto() },
+ flex_grow: 1.0,
+ ..Default::default()
+ },
+ ).unwrap();
+
+let root_node = tree
+ .new_with_children(
+ Style {
+ flex_direction: FlexDirection::Column,
+ size: Size { width: length(800.0), height: length(600.0) },
+ ..Default::default()
+ },
+ &[header_node, body_node],
+ )
+ .unwrap();
+
+// Call compute_layout on the root of your tree to run the layout algorithm
+tree.compute_layout(root_node, Size::MAX_CONTENT).unwrap();
+
+// Inspect the computed layout using `TaffyTree.layout`
+assert_eq!(tree.layout(root_node).unwrap().size.width, 800.0);
+assert_eq!(tree.layout(root_node).unwrap().size.height, 600.0);
+assert_eq!(tree.layout(header_node).unwrap().size.width, 800.0);
+assert_eq!(tree.layout(header_node).unwrap().size.height, 100.0);
+assert_eq!(tree.layout(body_node).unwrap().size.width, 800.0);
+assert_eq!(tree.layout(body_node).unwrap().size.height, 500.0); // This value was not set explicitly, but was computed by Taffy
+
+```
+
+## Bindings to other languages
+
+- Python via [stretchable](https://github.com/mortencombat/stretchable)
+- [WIP C bindings](https://github.com/DioxusLabs/taffy/pull/404)
+- [WIP WASM bindings](https://github.com/DioxusLabs/taffy/pull/394)
+
+## Learning Resources
+
+Taffy implements the Flexbox and CSS Grid specifications faithfully, so documentation designed for the web should translate cleanly to Taffy's implementation. For reference documentation on individual style properties we recommend the MDN documentation (for example [this page](https://developer.mozilla.org/en-US/docs/Web/CSS/width) on the `width` property). Such pages can usually be found by searching for "MDN property-name" using a search engine.
+
+If you are interested in guide-level documentation on CSS layout, then we recommend the following resources:
+
+### Flexbox
+
+- [Flexbox Froggy](https://flexboxfroggy.com/). This is an interactive tutorial/game that allows you to learn the essential parts of Flexbox in a fun engaging way.
+- [A Complete Guide To Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different Flexbox properties and how they work.
+
+### CSS Grid
+
+- [CSS Grid Garden](https://cssgridgarden.com/). This is an interactive tutorial/game that allows you to learn the essential parts of CSS Grid in a fun engaging way.
+- [A Complete Guide To CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different CSS Grid properties and how they work.
+
+## Benchmarks (vs. [Yoga](https://github.com/facebook/yoga))
+
+- Run on a 2021 MacBook Pro with M1 Pro processor using [criterion](https://github.com/bheisler/criterion.rs)
+- The benchmarks measure layout computation only. They do not measure tree creation.
+- Yoga benchmarks were run via the [yoga](https://github.com/bschwind/yoga-rs) crate (Rust bindings), version 0.5.0
+- Most popular websites seem to have between 3,000 and 10,000 nodes (although they also require text layout, which neither yoga nor taffy implement).
+
+Note that the table below contains multiple different units (seconds vs. milliseconds vs. microseconds)
+
+| Benchmark | Node Count | Depth | Yoga ([v3.2.1]) | Taffy ([e747f6e]) |
+| --- | --- | --- | --- | --- |
+| yoga 'huge nested' | 1,000 | 3 | 328.24 µs | 250.23 µs |
+| yoga 'huge nested' | 10,000 | 4 | 3.2892 ms | 2.6947 ms |
+| yoga 'huge nested' | 100,000 | 5 | 41.686 ms | 32.871 ms |
+| big trees (wide) | 1,000 | 2 | 468.66 µs | 471.14 µs |
+| big trees (wide) | 10,000 | 2 | 4.8667 ms | 4.8032 ms |
+| big trees (wide) | 100,000 | 2 | 63.304 ms | 58.111 ms |
+| absolutely positioned leaves | 1,000 | 2 | 408.51 µs | 259.91 µs |
+| absolutely positioned leaves | 10,000 | 2 | 4.3898 ms | 2.7890 ms |
+| absolutely positioned leaves | 100,000 | 2 | 56.490 ms | 41.270 ms |
+| big trees (deep, random size) | 4,000 | 12 | 1.7937 ms | 1.8160 ms |
+| big trees (deep, random size) | 10,000 | 14 | 4.4436 ms | 4.5843 ms |
+| big trees (deep, random size) | 100,000 | 17 | 63.555 ms | 69.952 ms |
+| big trees (deep, auto size) | 4,000 | 12 | 32.872 ms | 4.7357 ms |
+| big trees (deep, auto size) | 10,000 | 14 | 103.19 ms | 11.894 ms |
+| big trees (deep, auto size) | 100,000 | 17 | 2.3502 s | 164.24 ms |
+| super deep | 150 | 50 | 61.132 ms | 179.02 µs |
+| super deep | 300 | 100 | did not finish (>9min) | 366.89 µs |
+
+[v3.2.1]: https://github.com/facebook/yoga/commit/042f5013152eb81c1552dec945b88f7b95ca350f
+[e747f6e]: https://github.com/DioxusLabs/taffy/commit/e747f6e5b94e7b0586d807aeb681b48f9a005f04
+
+## Contributions
+
+[Contributions welcome](https://github.com/DioxusLabs/taffy/blob/main/CONTRIBUTING.md):
+if you'd like to use, improve or build `taffy`, feel free to join the conversation, open an [issue](https://github.com/DioxusLabs/taffy/issues) or submit a [PR](https://github.com/DioxusLabs/taffy/pulls).
+If you have questions about how to use `taffy`, open a [discussion](https://github.com/DioxusLabs/taffy/discussions) so we can answer your questions in a way that others can find.
diff --git a/vendor/taffy/src/compute/block.rs b/vendor/taffy/src/compute/block.rs
new file mode 100644
index 00000000..e63295e5
--- /dev/null
+++ b/vendor/taffy/src/compute/block.rs
@@ -0,0 +1,1824 @@
+//! Computes the CSS block layout algorithm in the case that the block container being laid out contains only block-level boxes
+use crate::geometry::{Line, Point, Rect, Size};
+use crate::style::{
+ AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
+ CoreStyle, LengthPercentageAuto, Overflow, Position,
+};
+use crate::style_helpers::TaffyMaxContent;
+use crate::tree::{
+ AxisStaticPosition, LayoutPartialTree, LayoutPartialTreeExt, NodeId, OofCandidate, OofCandidates,
+ OofPositioningArea,
+};
+use crate::tree::{Baselines, CollapsibleMarginSet, Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
+use crate::util::debug::debug_log;
+use crate::util::sys::f32_max;
+use crate::util::sys::Vec;
+use crate::util::MaybeMath;
+use crate::util::{MaybeResolve, ResolveOrZero};
+use crate::{
+ BlockContainerStyle, BlockItemStyle, BoxGenerationMode, BoxSizing, Contain, Dimension, Direction,
+ LayoutBlockContainer, RequestedAxis, TextAlign,
+};
+
+#[cfg(feature = "float_layout")]
+use super::float::{BfcSlot, ContentSlot, FloatContext, FloatIntrinsicWidthCalculator, FIT_TOLERANCE};
+#[cfg(feature = "float_layout")]
+use crate::{Clear, Float, FloatDirection};
+
+/// Compute the block-axis offset that `align-content` applies to the in-flow content of a block
+/// container, given the free space between the container's content box and its content.
+///
+/// The entire stack of in-flow content is treated as a single alignment subject, so the
+/// distribution keywords (`space-*`, `stretch`) invoke their single-subject fallbacks. This is
+/// used both by block layout and by inline formatting contexts (line boxes) which are laid out
+/// externally to Taffy.
+pub fn compute_block_align_content_offset(align_content: AlignContent, free_space: f32) -> f32 {
+ let keyword = apply_alignment_fallback(free_space, 1, align_content);
+ compute_alignment_offset(free_space, 1, 0.0, keyword, false, true)
+}
+
+/// Context for positioning Block and Float boxes within a Block Formatting Context
+pub struct BlockFormattingContext {
+ /// The float positioning context that handles positioning floats within this Block Formatting Context
+ #[cfg(feature = "float_layout")]
+ float_context: FloatContext,
+}
+
+impl Default for BlockFormattingContext {
+ fn default() -> Self {
+ Self {
+ #[cfg(feature = "float_layout")]
+ float_context: FloatContext::new(),
+ }
+ }
+}
+
+impl BlockFormattingContext {
+ /// Create a new `BlockFormattingContext` with the specified width constraint
+ pub fn new() -> Self {
+ Default::default()
+ }
+
+ /// Create an initial `BlockContext` for this `BlockFormattingContext`
+ pub fn root_block_context(&mut self) -> BlockContext<'_> {
+ BlockContext {
+ bfc: self,
+ y_offset: 0.0,
+ insets: [0.0, 0.0],
+ content_box_insets: [0.0, 0.0],
+ float_content_contribution: f32::NEG_INFINITY,
+ is_root: true,
+ #[cfg(feature = "float_layout")]
+ adjoining_floats: [false, false],
+ #[cfg(feature = "float_layout")]
+ top_adjoining_floats: None,
+ }
+ }
+}
+
+/// Context for each individual Block within a Block Formatting Context
+///
+/// Contains a mutable reference to the BlockFormattingContext + block-specific data
+pub struct BlockContext<'bfc> {
+ /// A mutable reference to the root BlockFormatttingContext that this BlockContext belongs to
+ bfc: &'bfc mut BlockFormattingContext,
+ /// The y-offset of the border-top of the block node, relative to the to the border-top of the
+ /// root node of the Block Formatting Context it belongs to.
+ y_offset: f32,
+ /// The x-inset of the border-box in from each side of the block node, relative to the root node of the Block Formatting Context it belongs to.
+ insets: [f32; 2],
+ /// The x-insets of the content box
+ content_box_insets: [f32; 2],
+ /// The height that floats take up in the element (`f32::NEG_INFINITY` if the element's
+ /// subtree does not contain any floats)
+ float_content_contribution: f32,
+ /// Whether the node is the root of the Block Formatting Context is belongs to.
+ is_root: bool,
+ /// Whether a float has been placed (on each side) whose position adjoins the current
+ /// margin-collapse strut of this block (i.e. whose final position can still be moved by
+ /// margins that collapse into that strut). Such floats force clearance on cleared elements
+ /// whose margins adjoin the same strut.
+ #[cfg(feature = "float_layout")]
+ adjoining_floats: [bool; 2],
+ /// The value of `adjoining_floats` frozen at the first point at which in-flow content was
+ /// committed within this block (resolving the position of the block's top margin strut).
+ /// `None` if no in-flow content has been committed yet.
+ #[cfg(feature = "float_layout")]
+ top_adjoining_floats: Option<[bool; 2]>,
+}
+
+impl BlockContext<'_> {
+ /// Create a sub-`BlockContext` for a child block node
+ pub fn sub_context(&mut self, additional_y_offset: f32, insets: [f32; 2]) -> BlockContext<'_> {
+ let insets = [self.insets[0] + insets[0], self.insets[1] + insets[1]];
+ BlockContext {
+ bfc: self.bfc,
+ y_offset: self.y_offset + additional_y_offset,
+ insets,
+ content_box_insets: insets,
+ float_content_contribution: f32::NEG_INFINITY,
+ is_root: false,
+ // Floats adjoining the parent's current strut also adjoin this block's top strut
+ // (if this block's top margin collapses with its first child's, which is checked separately)
+ #[cfg(feature = "float_layout")]
+ adjoining_floats: self.adjoining_floats,
+ #[cfg(feature = "float_layout")]
+ top_adjoining_floats: None,
+ }
+ }
+
+ /// Returns whether this block is the root block of it's Block Formatting Context
+ pub fn is_bfc_root(&self) -> bool {
+ self.is_root
+ }
+}
+
+#[cfg(feature = "float_layout")]
+impl BlockContext<'_> {
+ /// Set the width of the overall Block Formatting Context. This is used to resolve positions
+ /// that are relative to the right of the context such as right-floated boxes.
+ ///
+ /// Sub-blocks within a Block Formatting Context should use the `Self::sub_context` method to create
+ /// a sub-`BlockContext` with `insets` instead.
+ pub fn set_width(&mut self, available_width: f32) {
+ self.bfc.float_context.set_width(available_width);
+ }
+
+ /// Set the x-axis content-box insets of the `BlockContext`. These are the difference between the border-box
+ /// and the content-box of the box (padding + border + scrollbar_gutter).
+ pub fn apply_content_box_inset(&mut self, content_box_x_insets: [f32; 2]) {
+ self.content_box_insets[0] = self.insets[0] + content_box_x_insets[0];
+ self.content_box_insets[1] = self.insets[1] + content_box_x_insets[1];
+ }
+
+ /// Whether the float context contains any floats
+ #[inline(always)]
+ pub fn has_floats(&self) -> bool {
+ self.bfc.float_context.has_floats()
+ }
+
+ /// Whether the float context contains any floats that extend to or below min_y
+ #[inline(always)]
+ pub fn has_active_floats(&self, min_y: f32) -> bool {
+ self.bfc.float_context.has_active_floats(min_y + self.y_offset)
+ }
+
+ /// Position a floated box with the context
+ pub fn place_floated_box(
+ &mut self,
+ floated_box: Size<f32>,
+ min_y: f32,
+ direction: FloatDirection,
+ clear: Clear,
+ adjoins_unresolved_strut: bool,
+ ) -> Point<f32> {
+ if adjoins_unresolved_strut {
+ self.adjoining_floats[direction as usize] = true;
+ }
+ let mut pos = self.bfc.float_context.place_floated_box(
+ floated_box,
+ min_y + self.y_offset,
+ self.content_box_insets,
+ direction,
+ clear,
+ );
+ pos.y -= self.y_offset;
+ pos.x -= self.insets[0];
+
+ self.float_content_contribution = self.float_content_contribution.max(pos.y + floated_box.height);
+
+ pos
+ }
+
+ /// Search a space suitable for laying out non-floated content into
+ pub fn find_content_slot(&self, min_y: f32, clear: Clear, after: Option<usize>) -> ContentSlot {
+ let mut slot =
+ self.bfc.float_context.find_content_slot(min_y + self.y_offset, self.content_box_insets, clear, after);
+ slot.y -= self.y_offset;
+ slot.x -= self.insets[0];
+ slot
+ }
+
+ /// Search for a space suitable for laying out a box that establishes an independent
+ /// formatting context (whose border box must not overlap floats)
+ pub fn find_bfc_slot(
+ &self,
+ min_y: f32,
+ margins: [f32; 2],
+ direction: Direction,
+ clear: Clear,
+ after: Option<usize>,
+ ) -> BfcSlot {
+ let mut slot = self.bfc.float_context.find_bfc_slot(
+ min_y + self.y_offset,
+ self.content_box_insets,
+ margins,
+ direction,
+ clear,
+ after,
+ );
+ slot.y -= self.y_offset;
+ slot.x -= self.insets[0];
+ slot
+ }
+
+ /// Get the bottom of lowest relevant float for the specific clear property
+ pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
+ self.bfc.float_context.cleared_threshold(clear).map(|threshold| threshold - self.y_offset)
+ }
+
+ /// Whether a float that is adjoining the current margin-collapse strut has been placed
+ /// on the side(s) relevant to the passed clear property
+ pub fn has_adjoining_float(&self, clear: Clear) -> bool {
+ match clear {
+ Clear::Left => self.adjoining_floats[0],
+ Clear::Right => self.adjoining_floats[1],
+ Clear::Both => self.adjoining_floats[0] || self.adjoining_floats[1],
+ Clear::None => false,
+ }
+ }
+
+ /// Merge adjoining float flags propagated from a child block into this block's flags
+ fn merge_adjoining_floats(&mut self, flags: [bool; 2]) {
+ self.adjoining_floats[0] |= flags[0];
+ self.adjoining_floats[1] |= flags[1];
+ }
+
+ /// Record that in-flow content has been committed within this block, resolving the position of
+ /// the current margin-collapse strut. Floats placed before this point no longer adjoin the
+ /// current strut. The flags for the block's top strut are frozen at the first commit.
+ fn commit_strut(&mut self) {
+ if self.top_adjoining_floats.is_none() {
+ self.top_adjoining_floats = Some(self.adjoining_floats);
+ }
+ self.adjoining_floats = [false, false];
+ }
+
+ /// The adjoining float flags for this block's top margin strut: floats placed while the
+ /// position of the block's top strut was still unresolved
+ fn top_adjoining_floats(&self) -> [bool; 2] {
+ self.top_adjoining_floats.unwrap_or(self.adjoining_floats)
+ }
+
+ /// Update the height that descendent floats consume with the height that floats consume
+ /// within a particular child (`child_contribution` is relative to this block's border-top)
+ pub fn add_child_floated_content_height_contribution(&mut self, child_contribution: f32) {
+ self.float_content_contribution = self.float_content_contribution.max(child_contribution);
+ }
+
+ /// Returns the height that descendent floats consume
+ pub fn floated_content_height_contribution(&self) -> f32 {
+ self.float_content_contribution
+ }
+}
+
+#[cfg(not(feature = "float_layout"))]
+impl BlockContext<'_> {
+ #[inline(always)]
+ /// Returns the height that descendent floats consume (always 0.0 when the float feature is disabled)
+ fn float_content_contribution(&self) -> f32 {
+ 0.0
+ }
+}
+
+use super::common::alignment::{apply_alignment_fallback, compute_alignment_offset};
+#[cfg(feature = "content_size")]
+use super::common::scrollable_overflow::compute_scrollable_overflow_contribution;
+use super::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
+
+/// Per-child data that is accumulated and modified over the course of the layout algorithm
+struct BlockItem {
+ /// The identifier for the associated node
+ node_id: NodeId,
+
+ /// The "source order" of the item. This is the index of the item within the children iterator,
+ /// and controls the order in which the nodes are placed
+ order: u32,
+
+ /// Items that are tables don't have stretch sizing applied to them
+ is_table: bool,
+
+ /// Compressible replaced items resolve an auto width to their intrinsic size rather than
+ /// being stretch-sized <https://www.w3.org/TR/CSS22/visudet.html#block-replaced-width>
+ is_compressible_replaced: bool,
+
+ /// Whether the child is a non-independent block or inline node
+ is_in_same_bfc: bool,
+
+ #[cfg(feature = "float_layout")]
+ /// The `float` style of the node
+ float: Float,
+ #[cfg(feature = "float_layout")]
+ /// The `clear` style of the node
+ clear: Clear,
+
+ /// The size style of this item. Used to detect and resolve sizing keywords
+ /// (`min-content`, `max-content`, `fit-content`, `fit-content(...)`, and `stretch`).
+ /// In the height (block) axis only `stretch` requires resolution: the intrinsic sizing
+ /// keywords are all equal to the content size, which is what an auto height already
+ /// resolves to.
+ size_style: Size<Dimension>,
+
+ /// The base size of this item
+ size: Size<Option<f32>>,
+ /// The minimum allowable size of this item
+ min_size: Size<Option<f32>>,
+ /// The maximum allowable size of this item
+ max_size: Size<Option<f32>>,
+
+ /// The overflow style of the item
+ overflow: Point<Overflow>,
+ /// The contain style of the item
+ contain: Contain,
+ /// The width of the item's scrollbars (if it has scrollbars)
+ scrollbar_width: f32,
+
+ /// The position style of the item
+ position: Position,
+ /// The `direction` style of the item (used to resolve `self-start`/`self-end`)
+ direction: Direction,
+ /// The `align-self` style of the item (used to derive the static position of out-of-flow items)
+ align_self: Option<AlignSelf>,
+ /// The `justify-self` style of the item (used to align in-flow items and to derive the static position of
+ /// out-of-flow items)
+ justify_self: Option<AlignSelf>,
+ /// The final offset of this item
+ inset: Rect<LengthPercentageAuto>,
+ /// The margin of this item
+ margin: Rect<LengthPercentageAuto>,
+ /// The margin of this item
+ padding: Rect<f32>,
+ /// The margin of this item
+ border: Rect<f32>,
+ /// The sum of padding and border for this item
+ padding_border_sum: Size<f32>,
+
+ /// The computed border box size of this item
+ computed_size: Size<f32>,
+ /// The computed "static position" of this item. The static position is the position
+ /// taking into account padding, border, margins, and scrollbar_gutters but not inset
+ static_position: Point<f32>,
+ /// Whether margins can be collapsed through this item
+ can_be_collapsed_through: bool,
+
+ /// Pending layout for in-flow non-floated items. Held back from `set_unrounded_layout` so the
+ /// post-loop `align-content` pass in `compute_inner` can shift `location.y` before commit.
+ final_layout: Option<Layout>,
+
+ /// Out-of-flow candidates bubbled out of this (in-flow) item's subtree. Anchors are relative
+ /// to the item's border box until they are translated at merge time.
+ oof_candidates: OofCandidates,
+}
+
+/// Computes the layout of [`LayoutPartialTree`] according to the block layout algorithm
+pub fn compute_block_layout(
+ tree: &mut impl LayoutBlockContainer,
+ node_id: NodeId,
+ inputs: LayoutInput,
+ block_ctx: Option<&mut BlockContext<'_>>,
+) -> LayoutOutput {
+ let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
+ let style = tree.get_block_container_style(node_id);
+
+ // Pull these out earlier to avoid borrowing issues
+ let overflow = style.overflow();
+ let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
+ let contain = style.contain();
+ // css-align-3 §5.1.1: a non-`normal` `align-content` makes a block container establish an
+ // independent formatting context. <https://drafts.csswg.org/css-align-3/#distribution-block>
+ // Layout and paint containment also establish an independent formatting context.
+ // <https://drafts.csswg.org/css-contain-2/#containment-layout>
+ let establishes_new_bfc = is_scroll_container
+ || style.align_content().keyword != AlignContentKeyword::Normal
+ || contain.establishes_independent_formatting_context();
+ let aspect_ratio = style.aspect_ratio();
+ let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_size = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+
+ let min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
+ style
+ .size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .maybe_clamp(min_size, max_size)
+ } else {
+ Size::NONE
+ };
+
+ drop(style);
+
+ // If both min and max in a given axis are set and max <= min then this determines the size in that axis
+ let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
+ (Some(min), Some(max)) if max <= min => Some(min),
+ _ => None,
+ });
+
+ let styled_based_known_dimensions =
+ known_dimensions.or(min_max_definite_size).or(clamped_style_size).maybe_max(padding_border_size);
+
+ // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
+ // is ComputeSize (and thus the container's size is all that we're interested in)
+ if run_mode == RunMode::ComputeSize {
+ if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
+ return LayoutOutput::from_outer_size(Size { width, height });
+ }
+
+ // We can also short-circuit if the width is known and only the width has been requested.
+ if inputs.axis == RequestedAxis::Horizontal {
+ if let Some(width) = styled_based_known_dimensions.width {
+ return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
+ }
+ }
+ }
+
+ // Unwrap the block formatting context if one was passed, or else create a new one
+ debug_log!("BLOCK");
+ let mut output = match block_ctx {
+ Some(inherited_bfc) if !establishes_new_bfc => compute_inner(
+ tree,
+ node_id,
+ LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
+ inherited_bfc,
+ ),
+ _ => {
+ let mut root_bfc = BlockFormattingContext::new();
+ let mut root_ctx = root_bfc.root_block_context();
+ compute_inner(
+ tree,
+ node_id,
+ LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
+ &mut root_ctx,
+ )
+ }
+ };
+
+ // Layout containment suppresses the box's baseline for baseline-alignment purposes
+ if contain.suppresses_baseline() {
+ output.baselines = Baselines::NONE;
+ }
+
+ output
+}
+
+/// Computes the layout of [`LayoutBlockContainer`] according to the block layout algorithm
+fn compute_inner(
+ tree: &mut impl LayoutBlockContainer,
+ node_id: NodeId,
+ inputs: LayoutInput,
+ #[allow(unused_mut)] mut block_ctx: &mut BlockContext<'_>,
+) -> LayoutOutput {
+ let LayoutInput {
+ known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
+ } = inputs;
+
+ let style = tree.get_block_container_style(node_id);
+ let raw_padding = style.padding();
+ let raw_border = style.border();
+ let raw_margin = style.margin();
+ let aspect_ratio = style.aspect_ratio();
+ let padding = raw_padding.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = raw_border.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let direction = style.direction();
+
+ // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
+ // However, the axis are switched (transposed) because a node that scrolls vertically needs
+ // *horizontal* space to be reserved for a scrollbar
+ let scrollbar_gutter = {
+ let offsets = style.overflow().transpose().map(|overflow| match overflow {
+ Overflow::Scroll => style.scrollbar_width(),
+ _ => 0.0,
+ });
+ match direction {
+ Direction::Ltr => Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y },
+ Direction::Rtl => Rect { top: 0.0, left: offsets.x, right: 0.0, bottom: offsets.y },
+ }
+ };
+ let padding_border = padding + border;
+ let padding_border_size = padding_border.sum_axes();
+ let content_box_inset = padding_border + scrollbar_gutter;
+
+ // Apply content box inset
+ #[cfg(feature = "float_layout")]
+ block_ctx.apply_content_box_inset([content_box_inset.left, content_box_inset.right]);
+
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+ let size = style
+ .size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+
+ // css-sizing-4: a definite size in one axis transfers through `aspect-ratio`
+ // to make the other definite. Deriving it from `known_dimensions` self-gates
+ // the transfer — a block parent fills an axis only when it's a real
+ // constraint (e.g. the stretched width at final layout) and leaves it None
+ // while probing intrinsic sizes, so measure passes stay content-based. Only a
+ // newly-filled axis is adopted (and clamped); an incoming known size is left
+ // as the parent resolved it (re-clamping would undo padding/border overrides).
+ let known_dimensions = {
+ let derived = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
+ Size { width: known_dimensions.width.or(derived.width), height: known_dimensions.height.or(derived.height) }
+ };
+ let percentage_basis_dimensions = Size {
+ width: known_dimensions.width,
+ height: known_dimensions.height.filter(|_| inputs.known_dimensions_are_definite.height),
+ };
+ let container_content_box_size = percentage_basis_dimensions.maybe_sub(content_box_inset.sum_axes());
+
+ let overflow = style.overflow();
+ let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
+ let establishes_new_bfc = is_scroll_container
+ || style.align_content().keyword != AlignContentKeyword::Normal
+ || style.contain().establishes_independent_formatting_context();
+
+ // Determine margin collapsing behaviour
+ //
+ // Whether a child's margins could collapse through each of this box's block-axis edges: the
+ // box does not establish a new BFC and has neither border nor padding on that side.
+ let children_margins_adjoin_own_edges = Line {
+ start: vertical_margins_are_collapsible.start
+ && !establishes_new_bfc
+ && !style.position().is_out_of_flow()
+ && padding.top == 0.0
+ && border.top == 0.0,
+ end: vertical_margins_are_collapsible.end
+ && !establishes_new_bfc
+ && !style.position().is_out_of_flow()
+ && padding.bottom == 0.0
+ && border.bottom == 0.0,
+ };
+ let own_margins_collapse_with_children = Line {
+ start: children_margins_adjoin_own_edges.start,
+ end: children_margins_adjoin_own_edges.end && size.height.is_none(),
+ };
+ let has_styles_preventing_being_collapsed_through = !style.is_block()
+ || block_ctx.is_bfc_root()
+ || establishes_new_bfc
+ || style.position().is_out_of_flow()
+ || padding.top > 0.0
+ || padding.bottom > 0.0
+ || border.top > 0.0
+ || border.bottom > 0.0;
+
+ let text_align = style.text_align();
+ let align_content = style.align_content();
+ let justify_items = style.justify_items();
+ drop(style);
+
+ // 1. Generate items
+ let mut items = generate_item_list(tree, node_id, container_content_box_size);
+
+ // 2. Compute container width
+ let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
+ let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
+ let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
+ + content_box_inset.horizontal_axis_sum();
+ intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
+ });
+
+ // Short-circuit if computing size and both dimensions known
+ if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
+ return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: container_outer_height });
+ }
+
+ // We can also short-circuit if the width is known and only the width has been requested.
+ if run_mode == RunMode::ComputeSize && inputs.axis == RequestedAxis::Horizontal {
+ return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: 0.0 });
+ }
+
+ // Under `SizingMode::ContentSize` the container's own `height`/`min-height` are ignored,
+ // so they cannot serve as the percentage basis for children either
+ // (https://drafts.csswg.org/css-flexbox/#min-size-auto: the content size suggestion
+ // must not be influenced by the item's specified height).
+ let container_percentage_resolution_height = percentage_basis_dimensions
+ .height
+ .or(if inputs.sizing_mode == SizingMode::InherentSize { size.height.maybe_max(min_size.height) } else { None });
+
+ // 3. Perform final item layout and return content height
+ //
+ // Percentage padding and borders resolve against the *containing block's* width
+ // (`parent_size`), not the box's own width. These only differ when the box has a
+ // non-stretch width. Fall back to the box's own width when the parent size is
+ // unknown (e.g. at the root of the layout tree).
+ let percentage_resolution_width = parent_size.width.unwrap_or(container_outer_width);
+ let resolved_padding =
+ raw_padding.resolve_or_zero(Some(percentage_resolution_width), |val, basis| tree.calc(val, basis));
+ let resolved_border =
+ raw_border.resolve_or_zero(Some(percentage_resolution_width), |val, basis| tree.calc(val, basis));
+ let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
+ #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
+ let (
+ mut inflow_overflow_rect,
+ mut intrinsic_outer_height,
+ first_child_top_margin_set,
+ last_child_bottom_margin_set,
+ mut first_baseline,
+ ) = perform_final_layout_on_in_flow_children(
+ tree,
+ run_mode,
+ &mut items,
+ container_outer_width,
+ container_percentage_resolution_height,
+ content_box_inset,
+ resolved_content_box_inset,
+ resolved_border,
+ text_align,
+ justify_items,
+ direction,
+ own_margins_collapse_with_children,
+ children_margins_adjoin_own_edges,
+ #[cfg(feature = "content_size")]
+ is_scroll_container,
+ block_ctx,
+ );
+
+ // Root BFCs contain floats
+ #[cfg(feature = "float_layout")]
+ if block_ctx.is_bfc_root() || establishes_new_bfc {
+ intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
+ }
+
+ let container_outer_height = known_dimensions
+ .height
+ .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
+ .maybe_max(Some(padding_border_size.height));
+ let final_outer_size = Size { width: container_outer_width, height: container_outer_height };
+
+ // CSS2 §8.3.1: the bottom margin of a block with `height: auto` collapses with its last
+ // in-flow child's bottom margin only if the box's `min-height` is less than the box's
+ // used height. When `min-height` determines the used height, the last child's bottom
+ // margin no longer adjoins the box's bottom edge, so it stays inside the box instead of
+ // collapsing with the box's own bottom margin. (`max-height` has no such effect.)
+ let height_constrained_by_min_height = matches!(min_size.height, Some(h) if h > 0.0 && h >= container_outer_height);
+ let own_bottom_margin_collapses_with_children =
+ own_margins_collapse_with_children.end && !height_constrained_by_min_height;
+
+ // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
+ // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
+ //
+ // For block layout the entire stack of in-flow children is treated as a single alignment
+ // subject. That means distribution keywords (`space-between`, `space-around`,
+ // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
+ // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
+ // group then shifts by one offset, with zero inter-item gap.
+ if align_content.keyword != AlignContentKeyword::Normal {
+ let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
+ let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
+ let free_space = container_inner_height - inflow_content_height;
+ let group_offset = compute_block_align_content_offset(align_content, free_space);
+ first_baseline = first_baseline.map(|baseline| baseline + group_offset);
+ for item in items.iter_mut() {
+ if let Some(layout) = item.final_layout.as_mut() {
+ layout.location.y += group_offset;
+ }
+ // The static positions of out-of-flow children move with the in-flow content
+ if item.position.is_out_of_flow() {
+ item.static_position.y += group_offset;
+ }
+ }
+ let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
+ if any_in_flow {
+ #[cfg(feature = "content_size")]
+ {
+ inflow_overflow_rect = Rect::ZERO;
+ for item in items.iter() {
+ if let Some(layout) = item.final_layout.as_ref() {
+ let contribution_location = if direction.is_rtl() {
+ Point {
+ x: container_outer_width
+ - (layout.location.x + layout.size.width)
+ - resolved_border.right,
+ y: layout.location.y - resolved_border.top,
+ }
+ } else {
+ Point {
+ x: layout.location.x - resolved_border.left,
+ y: layout.location.y - resolved_border.top,
+ }
+ };
+ inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
+ contribution_location,
+ layout.size,
+ layout.scrollable_overflow_rect,
+ item.overflow,
+ item.contain,
+ is_scroll_container,
+ ));
+ }
+ }
+ }
+ }
+ }
+
+ // Determine whether this node can be collapsed through
+ let all_in_flow_children_can_be_collapsed_through = items.iter().all(|item| {
+ #[cfg(feature = "float_layout")]
+ if item.float.is_floated() {
+ return true;
+ }
+ item.position.is_out_of_flow() || item.can_be_collapsed_through
+ });
+ // CSS2 §8.3.1: a box's top and bottom margins collapse through it only if its *used* height
+ // is zero, so `height`/`min-height`/`max-height` are judged by the height they resolve to
+ // (e.g. `height: 1px; max-height: 0` collapses, `min-height: 1%` under an auto-height
+ // parent collapses) rather than by their computed values.
+ let can_be_collapsed_through = !has_styles_preventing_being_collapsed_through
+ && container_outer_height == 0.0
+ && all_in_flow_children_can_be_collapsed_through;
+
+ let mut output = LayoutOutput {
+ size: final_outer_size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: Rect::ZERO,
+ baselines: Baselines::from_first(first_baseline),
+ top_margin: if own_margins_collapse_with_children.start {
+ first_child_top_margin_set
+ } else {
+ let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ CollapsibleMarginSet::from_margin(margin_top)
+ },
+ bottom_margin: if own_bottom_margin_collapses_with_children {
+ last_child_bottom_margin_set
+ } else {
+ let margin_bottom =
+ raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ CollapsibleMarginSet::from_margin(margin_bottom)
+ },
+ margins_can_collapse_through: can_be_collapsed_through,
+ oof_candidates: OofCandidates::NONE,
+ oof_positioning_area: None,
+ };
+
+ // Short-circuit if computing size.
+ //
+ // Note: it is important that we return the margin-collapsing related outputs here as Parent block containers
+ // rely on the `top_margin`/`bottom_margin` of their children to compute their own intrinsic height.
+ if run_mode == RunMode::ComputeSize {
+ return output;
+ }
+
+ // Commit deferred child layouts to the tree.
+ for item in items.iter() {
+ if let Some(layout) = item.final_layout.as_ref() {
+ tree.set_unrounded_layout(item.node_id, layout);
+ }
+ }
+
+ // 4. Collect out-of-flow candidates in document order (direct out-of-flow children plus
+ // candidates bubbled from in-flow children's subtrees). These are laid out by the
+ // out-of-flow positioning pass (`compute_oof_layout`), which runs after this algorithm.
+ let mut candidates = OofCandidates::new();
+ for item in items.iter_mut() {
+ if item.position.is_out_of_flow() {
+ // The static-position rectangle of an out-of-flow child of a block container spans
+ // the container's content box in the inline axis, and is a zero-height line at the
+ // child's hypothetical position in the block axis. The child's self-alignment
+ // properties determine how it is aligned within that rectangle.
+ // <https://www.w3.org/TR/css-position-3/#staticpos-rect>
+ let inline_area = Line {
+ start: resolved_content_box_inset.left,
+ end: container_outer_width - resolved_content_box_inset.right,
+ };
+ let block_area = Line { start: item.static_position.y, end: item.static_position.y };
+ // A `justify_self` of `None` takes the container's `justify-items`. Block containers have
+ // no `align-items`, so an `align_self` of `None` behaves as `normal`.
+ let justify_self =
+ item.justify_self.unwrap_or(justify_items).resolve_self_relative(item.direction, direction, true);
+ let align_self =
+ item.align_self.unwrap_or(AlignItems::NORMAL).resolve_self_relative(item.direction, direction, false);
+ candidates.push(OofCandidate {
+ node: item.node_id,
+ order: item.order,
+ position: item.position,
+ static_position: Point {
+ x: AxisStaticPosition::from_alignment(justify_self, inline_area, direction.is_rtl()),
+ y: AxisStaticPosition::from_alignment(align_self, block_area, false),
+ },
+ });
+ } else if !item.oof_candidates.is_empty() {
+ // Translate anchors from item-relative to container-relative coordinates
+ if let Some(layout) = item.final_layout.as_ref() {
+ item.oof_candidates.translate(layout.location);
+ }
+ candidates.append(&mut item.oof_candidates);
+ }
+ }
+
+ let absolute_position_inset = resolved_border + scrollbar_gutter;
+ let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
+ let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
+ output.oof_candidates = candidates;
+ output.oof_positioning_area =
+ Some(OofPositioningArea { size: absolute_position_area, offset: absolute_position_offset });
+
+ #[cfg(feature = "content_size")]
+ {
+ // A scroll container's own padding at the end of the content is part of its scrollable
+ // overflow region, so it is included in the in-flow overflow rect. Boxes that are not
+ // scroll containers do not extend their overflow region by their own padding.
+ if is_scroll_container {
+ inflow_overflow_rect.right +=
+ if direction.is_rtl() { resolved_padding.left } else { resolved_padding.right };
+ inflow_overflow_rect.bottom += resolved_padding.bottom;
+ }
+ output.scrollable_overflow_rect = inflow_overflow_rect;
+ }
+
+ // 5. Perform hidden layout on hidden children
+ let len = tree.child_count(node_id);
+ for order in 0..len {
+ let child = tree.get_child_id(node_id, order);
+ let child_style = tree.get_block_child_style(child);
+ if child_style.box_generation_mode() == BoxGenerationMode::None {
+ drop(child_style);
+ tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
+ tree.perform_child_layout(
+ child,
+ Size::NONE,
+ Size::NONE,
+ Size::MAX_CONTENT,
+ SizingMode::InherentSize,
+ Line::FALSE,
+ );
+ }
+ }
+
+ output
+}
+
+/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
+#[inline]
+fn generate_item_list(
+ tree: &impl LayoutBlockContainer,
+ node: NodeId,
+ node_inner_size: Size<Option<f32>>,
+) -> Vec<BlockItem> {
+ tree.child_ids(node)
+ .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
+ .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
+ .enumerate()
+ .map(|(order, (child_node_id, child_style))| {
+ let aspect_ratio = child_style.aspect_ratio();
+ let padding =
+ child_style.padding().resolve_or_zero(node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let border =
+ child_style.border().resolve_or_zero(node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let pb_sum = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
+
+ let position = child_style.position();
+ let overflow = child_style.overflow();
+
+ #[cfg(feature = "float_layout")]
+ let float = child_style.float();
+ #[cfg(feature = "float_layout")]
+ let is_not_floated = float == Float::None;
+
+ #[cfg(not(feature = "float_layout"))]
+ let is_not_floated = true;
+
+ let is_block = child_style.is_block();
+ let is_table = child_style.is_table();
+ let is_compressible_replaced = child_style.is_compressible_replaced();
+ let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
+ let contain = child_style.contain();
+
+ let is_in_same_bfc: bool = is_block
+ && !is_table
+ && !position.is_out_of_flow()
+ && is_not_floated
+ && !is_scroll_container
+ && !contain.establishes_independent_formatting_context()
+ && child_style.align_content().keyword == AlignContentKeyword::Normal;
+
+ BlockItem {
+ node_id: child_node_id,
+ order: order as u32,
+ is_table,
+ is_compressible_replaced,
+ is_in_same_bfc,
+ #[cfg(feature = "float_layout")]
+ float,
+ #[cfg(feature = "float_layout")]
+ clear: child_style.clear(),
+ size_style: child_style.size(),
+ size: child_style
+ .size()
+ .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ min_size: child_style
+ .min_size()
+ .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ max_size: child_style
+ .max_size()
+ .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ overflow,
+ contain,
+ scrollbar_width: child_style.scrollbar_width(),
+ position,
+ direction: child_style.direction(),
+ align_self: child_style.align_self(),
+ justify_self: child_style.justify_self(),
+ inset: child_style.inset(),
+ margin: child_style.margin(),
+ padding,
+ border,
+ padding_border_sum: pb_sum,
+
+ // Fields to be computed later (for now we initialise with dummy values)
+ computed_size: Size::zero(),
+ static_position: Point::zero(),
+ can_be_collapsed_through: false,
+ final_layout: None,
+ oof_candidates: OofCandidates::new(),
+ }
+ })
+ .collect()
+}
+
+/// Resolve the `stretch` sizing keyword for an item's height style. In the block axis the
+/// intrinsic sizing keywords (`min-content`, `max-content`, `fit-content`, `fit-content(...)`)
+/// are all equal to the content size, which is what an auto height already resolves to, so
+/// only `stretch` requires explicit resolution.
+///
+/// Each of the item's block-axis margins is subtracted from the stretch size unless it is
+/// flagged in `margins_treated_as_zero`: when stretching a block-level box, a margin that
+/// could collapse through the corresponding edge of the containing block (which has neither
+/// border nor padding on that side and does not establish a new BFC) is treated as zero.
+/// <https://github.com/w3c/csswg-drafts/issues/11044#issuecomment-2599101601>
+/// <https://github.com/w3c/csswg-drafts/issues/13260>
+#[inline]
+fn resolve_stretch_height(
+ height_style: Dimension,
+ container_inner_height: Option<f32>,
+ item_margin: Rect<f32>,
+ margins_treated_as_zero: Line<bool>,
+) -> Option<f32> {
+ if !height_style.is_stretch() {
+ return None;
+ }
+ let mut height = container_inner_height?;
+ if !margins_treated_as_zero.start {
+ height -= item_margin.top;
+ }
+ if !margins_treated_as_zero.end {
+ height -= item_margin.bottom;
+ }
+ Some(height)
+}
+
+/// Compute the content-based width in the case that the width of the container is not known
+#[inline]
+fn determine_content_based_container_width(
+ tree: &mut impl LayoutPartialTree,
+ items: &[BlockItem],
+ available_width: AvailableSpace,
+) -> f32 {
+ let available_space = Size { width: available_width, height: AvailableSpace::MinContent };
+
+ let mut max_child_width = 0.0;
+ #[cfg(feature = "float_layout")]
+ let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
+ for item in items.iter().filter(|item| !item.position.is_out_of_flow()) {
+ let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);
+
+ let item_x_margin_sum = item
+ .margin
+ .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
+ .horizontal_axis_sum();
+ let width = known_dimensions.width.unwrap_or_else(|| {
+ let item_available_width =
+ match resolve_sizing_keyword(item.size_style.width, None, None, |val, basis| tree.calc(val, basis)) {
+ Some(SizingKeywordResolution::Measure(available_width)) => available_width,
+ Some(SizingKeywordResolution::Exact(width)) => AvailableSpace::Definite(width),
+ None => available_space.width.maybe_sub(item_x_margin_sum),
+ };
+ tree.measure_child_size(
+ item.node_id,
+ known_dimensions,
+ Size::NONE,
+ Size { width: item_available_width, height: available_space.height },
+ SizingMode::InherentSize,
+ crate::AbsoluteAxis::Horizontal,
+ // Must match the value passed when laying the item out (see `Cache`)
+ if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
+ )
+ });
+
+ let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;
+
+ #[cfg(feature = "float_layout")]
+ if let Some(direction) = item.float.float_direction() {
+ float_contribution.add_float(width, direction, item.clear);
+ continue;
+ }
+
+ max_child_width = f32_max(max_child_width, width);
+ }
+
+ #[cfg(feature = "float_layout")]
+ {
+ max_child_width = max_child_width.max(float_contribution.result());
+ }
+
+ max_child_width
+}
+
+/// Compute each child's final size and position
+#[inline]
+#[allow(clippy::too_many_arguments)]
+fn perform_final_layout_on_in_flow_children(
+ tree: &mut impl LayoutBlockContainer,
+ run_mode: RunMode,
+ items: &mut [BlockItem],
+ container_outer_width: f32,
+ container_percentage_resolution_height: Option<f32>,
+ content_box_inset: Rect<f32>,
+ resolved_content_box_inset: Rect<f32>,
+ resolved_border: Rect<f32>,
+ text_align: TextAlign,
+ justify_items: AlignItems,
+ direction: Direction,
+ own_margins_collapse_with_children: Line<bool>,
+ children_margins_adjoin_own_edges: Line<bool>,
+ #[cfg(feature = "content_size")] is_scroll_container: bool,
+ block_ctx: &mut BlockContext<'_>,
+) -> (Rect<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet, Option<f32>) {
+ // Resolve container_inner_width for sizing child nodes using initial content_box_inset
+ let container_inner_width = (container_outer_width - resolved_content_box_inset.horizontal_axis_sum()).max(0.0);
+ let container_percentage_resolution_height =
+ container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
+ let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
+ // Vertical available space in block flow is indefinite, NOT a min-content
+ // constraint: MaxContent is taffy's representation of "indefinite".
+ // Passing MinContent here made every descendant grid believe it was being
+ // sized under a min-content constraint, in which the maximize-tracks step
+ // has zero free space — so auto rows containing only scroll-container
+ // items (overflow != visible, automatic minimum size = 0) collapsed to
+ // zero height. Browsers size such rows to the item's content.
+ let available_space =
+ Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };
+
+ // TODO: handle nested blocks with different widths
+ #[cfg(feature = "float_layout")]
+ if block_ctx.is_bfc_root() {
+ block_ctx.set_width(container_outer_width);
+ block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
+ }
+
+ // If this block's top margin does not collapse with its children's then the position of its
+ // top margin strut is resolved relative to it, and floats adjoining ancestor struts do not
+ // adjoin this block's strut.
+ #[cfg(feature = "float_layout")]
+ if !own_margins_collapse_with_children.start {
+ block_ctx.commit_strut();
+ }
+
+ #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
+ let mut inflow_overflow_rect = Rect::ZERO;
+ let mut committed_y_offset = resolved_content_box_inset.top;
+ let mut y_offset_for_absolute = resolved_content_box_inset.top;
+ let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
+ let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
+ let mut is_collapsing_with_first_margin_set = true;
+ let mut first_baseline: Option<f32> = None;
+ // Whether the active margin set contains the margins of a self-collapsing element with
+ // clearance. Such margins collapse with the margins of following siblings but the resulting
+ // margin does not collapse with the bottom margin of the parent block.
+ let mut active_margin_set_has_clearance = false;
+
+ #[cfg(feature = "float_layout")]
+ let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
+ #[cfg(not(feature = "float_layout"))]
+ let has_active_floats = false;
+
+ for item in items.iter_mut() {
+ if item.position.is_out_of_flow() {
+ let x = match direction {
+ Direction::Ltr => resolved_content_box_inset.left,
+ Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
+ };
+ item.static_position = Point { x, y: y_offset_for_absolute }
+ } else {
+ let item_margin = item
+ .margin
+ .map(|margin| margin.resolve_to_option(container_inner_width, |val, basis| tree.calc(val, basis)));
+ let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
+ let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();
+
+ let scrollbar_size = Size {
+ width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
+ height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
+ };
+
+ // Handle floated boxes
+ #[cfg(feature = "float_layout")]
+ if let Some(float_direction) = item.float.float_direction() {
+ has_active_floats = true;
+
+ // A float with `width: auto` is shrink-to-fit (fit-content) sized: the available
+ // space clamped between its min-content and max-content sizes.
+ let available_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
+ let (item_known_width, item_available_width) = match resolve_sizing_keyword(
+ item.size_style.width,
+ Some(available_width),
+ Some(container_inner_width),
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Measure(available)) => (None, available),
+ Some(SizingKeywordResolution::Exact(width)) => (Some(width), AvailableSpace::Definite(width)),
+ None => (None, AvailableSpace::Definite(available_width)),
+ };
+ let item_known_height = resolve_stretch_height(
+ item.size_style.height,
+ container_percentage_resolution_height,
+ item_non_auto_margin,
+ // The margins of a float never collapse
+ Line::FALSE,
+ );
+ let mut item_layout = tree.perform_child_layout(
+ item.node_id,
+ Size { width: item_known_width, height: item_known_height },
+ parent_size,
+ Size { width: item_available_width, height: AvailableSpace::MaxContent },
+ SizingMode::InherentSize,
+ // A float establishes a new block formatting context: its margins do not
+ // collapse with the margins of its children
+ Line::FALSE,
+ );
+ item.oof_candidates = item_layout.oof_candidates.take();
+ let margin_box = item_layout.size + item_non_auto_margin.sum_axes();
+
+ // Floats that occur between collapsing margins are positioned as if they had an otherwise
+ // empty anonymous block parent taking part in the flow, so the pending collapsible margins
+ // contribute to the float's minimum y position (unless those margins collapse with the
+ // container's own top margin, in which case they are applied outside the container).
+ //
+ // In the latter case the position of the float is not fully resolved: margins contributed
+ // by later siblings can still collapse into the strut and move the container (and float).
+ // Such floats force clearance on cleared elements whose margins adjoin the same strut.
+ let adjoins_unresolved_strut =
+ is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start;
+ let y_offset_for_float = if adjoins_unresolved_strut {
+ committed_y_offset
+ } else {
+ committed_y_offset + active_collapsible_margin_set.resolve()
+ };
+
+ let mut location = block_ctx.place_floated_box(
+ margin_box,
+ y_offset_for_float,
+ float_direction,
+ item.clear,
+ adjoins_unresolved_strut,
+ );
+
+ // Ensure that content that appears after a float does not get positioned before/above the float
+ //
+ // FIXME: this isn't quite right, because a second float at the same location
+ // shouldn't cause content to push down to it's level
+ // committed_y_offset = committed_y_offset.max(location.y);
+ // y_offset_for_absolute = y_offset_for_absolute.max(location.y);
+
+ // Convert the margin-box location returned by float placement into a border-box location
+ // for the output Layout
+ location.y += item_non_auto_margin.top;
+ location.x += item_non_auto_margin.left;
+
+ // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
+ // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);
+
+ // Deferred to the post-loop pass in `compute_inner` (like in-flow items) so that
+ // `align-content` can shift `location.y` before the layout is committed.
+ item.final_layout = Some(Layout {
+ order: item.order,
+ size: item_layout.size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: item_layout.scrollable_overflow_rect,
+ scrollbar_size,
+ location,
+ padding: item.padding,
+ border: item.border,
+ margin: item_non_auto_margin,
+ });
+
+ #[cfg(feature = "content_size")]
+ {
+ // TODO: Should the overflow of floated boxes count as "inflow_overflow_rect"
+ // or should it be counted separately?
+ let contribution_location = if direction.is_rtl() {
+ Point {
+ x: container_outer_width - (location.x + item_layout.size.width) - resolved_border.right,
+ y: location.y - resolved_border.top,
+ }
+ } else {
+ Point { x: location.x - resolved_border.left, y: location.y - resolved_border.top }
+ };
+ inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
+ contribution_location,
+ item_layout.size,
+ item_layout.scrollable_overflow_rect,
+ item.overflow,
+ item.contain,
+ is_scroll_container,
+ ));
+ }
+
+ continue;
+ }
+
+ // Handle non-floated boxes
+
+ let mut y_margin_offset: f32 = 0.0;
+ #[cfg(feature = "float_layout")]
+ let mut item_avoids_floats = false;
+ #[cfg(feature = "float_layout")]
+ let mut item_pushed_below_float = false;
+
+ let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
+ let stretch_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
+ let position = Point { x: 0.0, y: 0.0 };
+ let width = 0.0;
+
+ (stretch_width, position, width)
+ } else {
+ 'block: {
+ // Set y_margin_offset (different bfc child)
+ if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
+ y_margin_offset =
+ active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
+ };
+ let min_y = committed_y_offset + y_margin_offset;
+
+ // In addition to the running flag, check the float context directly:
+ // floats placed by the subtree of a preceding in-flow sibling (in the same
+ // BFC) are not reflected in the flag
+ #[cfg(feature = "float_layout")]
+ if has_active_floats || block_ctx.has_active_floats(min_y) {
+ let x_margins = [item_non_auto_margin.left, item_non_auto_margin.right];
+ // An auto width resolves to at least the negation of the margin sum
+ // (so that the margin box width is non-negative, per CSS2 §10.3.3)
+ let min_auto_width = -item_non_auto_x_margin_sum;
+
+ // Find the highest slot (at or below `min_y`) with enough horizontal space
+ // for the item's border box, which must not overlap any float
+ let mut slot_segment = None;
+ let slot = loop {
+ let slot = block_ctx.find_bfc_slot(min_y, x_margins, direction, item.clear, slot_segment);
+ let Some(segment_id) = slot.segment_id else { break slot };
+ let width = item
+ .size
+ .width
+ .unwrap_or(slot.stretch_width.max(min_auto_width).max(0.0))
+ .maybe_clamp(item.min_size.width, item.max_size.width);
+ if width <= slot.border_width + FIT_TOLERANCE {
+ break slot;
+ }
+ slot_segment = Some(segment_id);
+ };
+
+ // If the item had to move down to avoid floats then it "separates from the
+ // float": similarly to clearance, its top margin no longer collapses with
+ // the parent's margins.
+ if slot.y > min_y {
+ item_pushed_below_float = true;
+ }
+
+ has_active_floats = slot.segment_id.is_some();
+ item_avoids_floats = true;
+ let stretch_width = slot.stretch_width.max(min_auto_width).max(0.0);
+ break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.border_width);
+ }
+
+ if !has_active_floats {
+ let stretch_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
+ break 'block (
+ stretch_width,
+ Point { x: resolved_content_box_inset.left, y: min_y },
+ container_inner_width,
+ );
+ }
+
+ unreachable!("One of the above cases will always be hit");
+ }
+ };
+
+ // `justify-self` on an in-flow block-level box (css-align-3 §6.1.1). `None` takes the
+ // container's `justify-items`, and `normal` lays the box out according to the default
+ // block layout rules. `stretch` does too: the default rules already stretch an
+ // auto-width box, so it only differs from `normal` for tables and replaced boxes, which
+ // would otherwise resolve their own width.
+ let justify_self =
+ item.justify_self.unwrap_or(justify_items).resolve_self_relative(item.direction, direction, true);
+ let is_stretch = justify_self.keyword == AlignItemsKeyword::Stretch;
+ // The (resolved) `justify-self` if it is neither `normal` nor `stretch`
+ let non_stretch_justify_self = match justify_self.keyword {
+ AlignItemsKeyword::Normal | AlignItemsKeyword::Stretch => None,
+ _ => Some(justify_self),
+ };
+
+ // Unless stretched, tables and compressible replaced elements resolve their own width
+ // <https://www.w3.org/TR/CSS22/visudet.html#block-replaced-width>
+ let known_dimensions = if (item.is_table || item.is_compressible_replaced) && !is_stretch {
+ Size::NONE
+ } else {
+ // The automatic width of a block-level box whose `justify-self` is neither `normal` nor `stretch`
+ // is equivalent to `fit-content` rather than `stretch`
+ let width_style = if non_stretch_justify_self.is_some() && item.size_style.width.is_auto() {
+ Dimension::fit_content()
+ } else {
+ item.size_style.width
+ };
+
+ // Items with a sizing keyword width (min-content, max-content, fit-content,
+ // fit-content(...), stretch) resolve their width either directly or by measuring
+ // the item under the corresponding available space constraint
+ let keyword_width = resolve_sizing_keyword(
+ width_style,
+ Some(stretch_width),
+ Some(container_inner_width),
+ |val, basis| tree.calc(val, basis),
+ )
+ .map(|resolution| match resolution {
+ SizingKeywordResolution::Exact(width) => width,
+ SizingKeywordResolution::Measure(item_available_width) => tree.measure_child_size(
+ item.node_id,
+ Size::NONE,
+ parent_size,
+ Size { width: item_available_width, height: AvailableSpace::MaxContent },
+ SizingMode::InherentSize,
+ crate::AbsoluteAxis::Horizontal,
+ // Must match the value passed when laying the item out (see `Cache`)
+ if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
+ ),
+ });
+
+ let keyword_height = resolve_stretch_height(
+ item.size_style.height,
+ container_percentage_resolution_height,
+ item_non_auto_margin,
+ children_margins_adjoin_own_edges,
+ );
+
+ item.size
+ .map_width(|width| {
+ Some(
+ width
+ .or(keyword_width)
+ .unwrap_or(stretch_width)
+ .maybe_clamp(item.min_size.width, item.max_size.width),
+ )
+ })
+ .map_height(|height| height.or(keyword_height))
+ .maybe_clamp(item.min_size, item.max_size)
+ };
+
+ //
+
+ let inputs = LayoutInput {
+ run_mode,
+ sizing_mode: SizingMode::InherentSize,
+ axis: RequestedAxis::Both,
+ known_dimensions,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size,
+ available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
+ vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
+ };
+
+ #[cfg(feature = "float_layout")]
+ let clear_threshold = block_ctx.cleared_threshold(item.clear);
+ #[cfg(feature = "float_layout")]
+ let clear_pos = clear_threshold.unwrap_or(f32::NEG_INFINITY);
+ #[cfg(not(feature = "float_layout"))]
+ let clear_pos = f32::NEG_INFINITY;
+
+ // The height consumed by floats within a same-BFC child, relative to the child's
+ // border-top. Added to the parent's contribution once the child's position is known.
+ #[cfg(feature = "float_layout")]
+ let mut child_float_contribution = f32::NEG_INFINITY;
+
+ let mut item_layout = if item.is_in_same_bfc {
+ // Replaced elements may not have a known width (they are sized by their
+ // measure function rather than stretch-sized)
+ let width = known_dimensions.width.unwrap_or(stretch_width).max(item.padding_border_sum.width);
+
+ // TODO: account for auto margins
+ let inset_left = item_non_auto_margin.left + content_box_inset.left;
+ let inset_right = container_outer_width - width - inset_left;
+ let insets = [inset_left, inset_right];
+
+ // Compute child layout. The child's position is estimated from its top margin collapsed with
+ // the preceding margins (the child's own collapsed-through margins are not yet known).
+ let estimated_y = committed_y_offset
+ + active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
+ let mut child_block_ctx = block_ctx.sub_context(estimated_y.max(clear_pos), insets);
+ let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));
+
+ // Extract float contribution from child block context
+ #[cfg(feature = "float_layout")]
+ {
+ child_float_contribution = child_block_ctx.floated_content_height_contribution();
+ let child_top_adjoining_floats = child_block_ctx.top_adjoining_floats();
+ // Floats placed while the position of the child's top margin strut was unresolved
+ // also adjoin this block's current strut
+ block_ctx.merge_adjoining_floats(child_top_adjoining_floats);
+ }
+
+ output
+ } else {
+ tree.compute_child_layout(item.node_id, inputs)
+ };
+ item.oof_candidates = item_layout.oof_candidates.take();
+ let final_size = item_layout.size;
+
+ let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
+ let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));
+
+ // Expand auto margins to fill available space
+ // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
+ // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
+ let free_x_space = f32_max(0.0, stretch_width - final_size.width);
+ let x_axis_auto_margin_size = {
+ let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
+ if auto_margin_count > 0 {
+ free_x_space / auto_margin_count as f32
+ } else {
+ 0.0
+ }
+ };
+ let resolved_margin = Rect {
+ left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
+ right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
+ top: item_margin.top.unwrap_or(0.0),
+ bottom: item_margin.bottom.unwrap_or(0.0),
+ };
+
+ // Resolve item inset
+ let inset_percentage_basis =
+ Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
+ let inset = item
+ .inset
+ .zip_size(inset_percentage_basis, |p, s| p.maybe_resolve(s, |val, basis| tree.calc(val, basis)));
+ let inset_offset = if item.position == Position::Relative {
+ Point {
+ x: if direction.is_rtl() {
+ inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
+ } else {
+ inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
+ },
+ y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
+ }
+ } else {
+ Point::ZERO
+ };
+
+ // Set y_margin_offset (same bfc child)
+ if item.is_in_same_bfc
+ && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
+ {
+ y_margin_offset = active_collapsible_margin_set.collapse_with_set(top_margin_set).resolve()
+ };
+
+ // Compute clearance (CSS2.2 9.5.2). Clearance is introduced if the hypothetical position of the
+ // item's top border edge (the position it would have with normal margin collapsing) is not past
+ // the bottom of the relevant floats. When clearance is introduced the item's border edge is
+ // placed at `max(float bottom, hypothetical position)`.
+ #[cfg(feature = "float_layout")]
+ let mut has_clearance = false;
+ #[cfg(not(feature = "float_layout"))]
+ let has_clearance = false;
+ #[cfg(feature = "float_layout")]
+ if item.is_in_same_bfc {
+ if let Some(threshold) = clear_threshold {
+ // The hypothetical position always includes the item's collapsed top margin set, even
+ // when those margins collapse with the container's own top margin (and are thus applied
+ // outside the container): in that case they still move the container (and hence the item)
+ // relative to the floats.
+ let hypothetical_y =
+ committed_y_offset + active_collapsible_margin_set.collapse_with_set(top_margin_set).resolve();
+ // Clearance is forced (regardless of the hypothetical position) if a relevant float is
+ // adjoining the margin-collapse strut that the item's top margin would collapse into:
+ // if the margins were allowed to collapse they would pull the float down with the item,
+ // so clearance is inserted to separate the two, placing the item just below the float.
+ let forced_clearance = block_ctx.has_adjoining_float(item.clear);
+ if forced_clearance || hypothetical_y < threshold {
+ has_clearance = true;
+ // Clearance stops the item's top margin collapsing with preceding margins. If those
+ // preceding margins collapse with the container's own top margin they are applied
+ // outside the container (moving it down), so the item's cleared position within the
+ // container must be reduced by that amount to keep its absolute position correct.
+ let escaped_margin =
+ if is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start {
+ active_collapsible_margin_set.resolve()
+ } else {
+ 0.0
+ };
+ y_margin_offset = threshold - committed_y_offset - escaped_margin;
+ }
+ }
+ }
+
+ item.computed_size = item_layout.size;
+ item.can_be_collapsed_through = item_layout.margins_can_collapse_through && !has_clearance;
+ item.static_position = if item.is_in_same_bfc {
+ let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
+ Point {
+ x: match direction {
+ Direction::Ltr => resolved_content_box_inset.left,
+ Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
+ },
+ y: uncleared_y.max(clear_pos),
+ }
+ } else {
+ // TODO: handle inset and margins
+ Point {
+ x: match direction {
+ Direction::Ltr => float_avoiding_position.x,
+ Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
+ },
+ y: float_avoiding_position.y,
+ }
+ };
+ let mut location = if item.is_in_same_bfc {
+ Point {
+ x: match direction {
+ Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
+ Direction::Rtl => {
+ container_outer_width
+ - resolved_content_box_inset.right
+ - final_size.width
+ - resolved_margin.right
+ + inset_offset.x
+ }
+ },
+ y: committed_y_offset + y_margin_offset + inset_offset.y,
+ }
+ } else {
+ // When the item avoids floats, its non-auto margins are already accounted for in the
+ // slot's border-box position/width (margins may overlap floats), so only the auto
+ // portion of the resolved margin is added here.
+ #[cfg(feature = "float_layout")]
+ let (extra_margin_left, extra_margin_right) = if item_avoids_floats {
+ (
+ resolved_margin.left - item_non_auto_margin.left,
+ resolved_margin.right - item_non_auto_margin.right,
+ )
+ } else {
+ (resolved_margin.left, resolved_margin.right)
+ };
+ #[cfg(not(feature = "float_layout"))]
+ let (extra_margin_left, extra_margin_right) = (resolved_margin.left, resolved_margin.right);
+
+ // TODO: handle inset and margins
+ Point {
+ x: match direction {
+ Direction::Ltr => float_avoiding_position.x + extra_margin_left + inset_offset.x,
+ Direction::Rtl => {
+ float_avoiding_position.x + float_avoiding_width - final_size.width - extra_margin_right
+ + inset_offset.x
+ }
+ },
+ y: float_avoiding_position.y + inset_offset.y,
+ }
+ };
+
+ // Floats within the child are positioned relative to the child's border-top, so the
+ // child's (margin-collapsed) position, rather than its relative offset, is added.
+ #[cfg(feature = "float_layout")]
+ if item.is_in_same_bfc {
+ block_ctx.add_child_floated_content_height_contribution(
+ location.y - inset_offset.y + child_float_contribution,
+ );
+ }
+
+ // Apply alignment. `justify-self` aligns the item's margin box within its alignment
+ // container and takes precedence over legacy `text-align`, but auto margins (which have
+ // already absorbed the free space) take precedence over `justify-self`.
+ let has_auto_x_margin = item_margin.left.is_none() || item_margin.right.is_none();
+ let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
+ if let (Some(justify_self), false) = (non_stretch_justify_self, has_auto_x_margin) {
+ // The alignment container is the containing block, except that a BFC-establishing
+ // box placed next to a float aligns within the space left over by the float (in
+ // which case the slot is already inset by the item's margins).
+ #[cfg(feature = "float_layout")]
+ let (container_start, free_x_space) = if item_avoids_floats {
+ (float_avoiding_position.x - resolved_margin.left, float_avoiding_width - item_layout.size.width)
+ } else {
+ (resolved_content_box_inset.left, container_inner_width - item_outer_width)
+ };
+ #[cfg(not(feature = "float_layout"))]
+ let (container_start, free_x_space) =
+ (resolved_content_box_inset.left, container_inner_width - item_outer_width);
+
+ let keyword = if matches!(justify_self.safety, AlignmentSafety::Safe) && free_x_space < 0.0 {
+ AlignItemsKeyword::Start
+ } else {
+ justify_self.keyword
+ };
+ let align_to_end = match keyword {
+ AlignItemsKeyword::Center => None,
+ AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd | AlignItemsKeyword::SelfEnd => Some(true),
+ _ => Some(false),
+ };
+ let offset = match align_to_end {
+ None => free_x_space / 2.0,
+ Some(end) if end != direction.is_rtl() => free_x_space,
+ Some(_) => 0.0,
+ };
+ location.x = container_start + resolved_margin.left + inset_offset.x + offset;
+ } else if non_stretch_justify_self.is_none() && item_outer_width < container_inner_width {
+ let free_x_space = container_inner_width - item_outer_width;
+ match (text_align, direction) {
+ (TextAlign::Auto, _) => {
+ // Do nothing
+ }
+ (TextAlign::LegacyLeft, Direction::Ltr) => {
+ // Do nothing. Left aligned by default.
+ }
+ (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
+ (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
+ (TextAlign::LegacyRight, Direction::Rtl) => {
+ // Do nothing. Right aligned by default.
+ }
+ (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
+ (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
+ }
+ }
+
+ // A block container's first baseline is the first baseline of its first in-flow child
+ // that has one.
+ //
+ // Scroll containers' baselines are determined from their content as if scrolled to the
+ // initial position, but are additionally clamped to their border box. A scroll container
+ // with no baseline synthesizes one from its border-box bottom edge.
+ // See https://github.com/w3c/csswg-drafts/issues/7660
+ if first_baseline.is_none() {
+ let child_baseline = if item.overflow.y.is_scroll_container() {
+ Some(
+ item_layout
+ .baselines
+ .first
+ .unwrap_or(item_layout.size.height)
+ .min(item_layout.size.height)
+ .max(0.0),
+ )
+ } else {
+ item_layout.baselines.first
+ };
+ first_baseline = child_baseline.map(|baseline| location.y + baseline);
+ }
+
+ // Used auto margins include float-avoidance offsets, unlike the alignment margins above.
+ #[cfg(feature = "float_layout")]
+ let resolved_margin = {
+ let mut margin = resolved_margin;
+ if item_avoids_floats {
+ if item_margin.left.is_none() {
+ margin.left += float_avoiding_position.x - resolved_content_box_inset.left;
+ }
+ if item_margin.right.is_none() {
+ margin.right += container_outer_width
+ - resolved_content_box_inset.right
+ - float_avoiding_position.x
+ - float_avoiding_width;
+ }
+ }
+ margin
+ };
+
+ // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
+ // `align-content` can shift `location.y` before the layout is committed to the tree.
+ item.final_layout = Some(Layout {
+ order: item.order,
+ size: item_layout.size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: item_layout.scrollable_overflow_rect,
+ scrollbar_size,
+ location,
+ padding: item.padding,
+ border: item.border,
+ margin: resolved_margin,
+ });
+
+ #[cfg(feature = "content_size")]
+ {
+ let contribution_location = if direction.is_rtl() {
+ Point {
+ x: container_outer_width - (location.x + final_size.width) - resolved_border.right,
+ y: location.y - resolved_border.top,
+ }
+ } else {
+ Point { x: location.x - resolved_border.left, y: location.y - resolved_border.top }
+ };
+ inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
+ contribution_location,
+ final_size,
+ item_layout.scrollable_overflow_rect,
+ item.overflow,
+ item.contain,
+ is_scroll_container,
+ ));
+ }
+
+ // Update first_child_top_margin_set
+ //
+ // The top margin of an item with clearance does not collapse with the container's top margin,
+ // so clearance terminates collapsing without contributing the item's own margins.
+ #[cfg(feature = "float_layout")]
+ if is_collapsing_with_first_margin_set && item_pushed_below_float {
+ // The item's top margin "separated from the float" and must not
+ // propagate to the parent
+ is_collapsing_with_first_margin_set = false;
+ }
+ if is_collapsing_with_first_margin_set && has_clearance {
+ is_collapsing_with_first_margin_set = false;
+ } else if is_collapsing_with_first_margin_set {
+ if item.can_be_collapsed_through {
+ first_child_top_margin_set = first_child_top_margin_set
+ .collapse_with_set(top_margin_set)
+ .collapse_with_set(bottom_margin_set);
+ } else {
+ first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
+ is_collapsing_with_first_margin_set = false;
+ }
+ }
+
+ // Update active_collapsible_margin_set
+ if item.can_be_collapsed_through {
+ active_collapsible_margin_set = active_collapsible_margin_set
+ .collapse_with_set(top_margin_set)
+ .collapse_with_set(bottom_margin_set);
+ y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
+ } else {
+ committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
+ // A self-collapsing item with clearance is not collapsed through (its margins do not collapse
+ // with margins of preceding siblings), but its top and bottom margins still collapse with each
+ // other and with the margins of following siblings.
+ if has_clearance && item_layout.margins_can_collapse_through {
+ // The element's border edge stays at the cleared position, but its collapsed margin
+ // extends below it: the border edge sits `top margin` inside the collapsed margin, so
+ // following content is offset by `collapsed margin - top margin` from the border edge.
+ committed_y_offset -= top_margin_set.resolve();
+ active_collapsible_margin_set = top_margin_set.collapse_with_set(bottom_margin_set);
+ active_margin_set_has_clearance = true;
+ } else {
+ active_collapsible_margin_set = bottom_margin_set;
+ active_margin_set_has_clearance = false;
+ }
+ y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
+ // Committing in-flow content resolves the position of the current margin-collapse strut,
+ // so floats placed before this point no longer force clearance
+ #[cfg(feature = "float_layout")]
+ block_ctx.commit_strut();
+ }
+ }
+ }
+
+ // The margins of a self-collapsing element with clearance do not collapse with the bottom
+ // margin of the parent block: they extend the parent's content height instead of escaping it
+ let last_child_bottom_margin_set =
+ if active_margin_set_has_clearance { CollapsibleMarginSet::ZERO } else { active_collapsible_margin_set };
+ let bottom_y_margin_offset = if active_margin_set_has_clearance {
+ active_collapsible_margin_set.resolve()
+ } else if own_margins_collapse_with_children.end {
+ 0.0
+ } else {
+ last_child_bottom_margin_set.resolve()
+ };
+
+ committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
+ let content_height = f32_max(0.0, committed_y_offset);
+ (inflow_overflow_rect, content_height, first_child_top_margin_set, last_child_bottom_margin_set, first_baseline)
+}
diff --git a/vendor/taffy/src/compute/common/alignment.rs b/vendor/taffy/src/compute/common/alignment.rs
new file mode 100644
index 00000000..fac558f6
--- /dev/null
+++ b/vendor/taffy/src/compute/common/alignment.rs
@@ -0,0 +1,129 @@
+//! Generic CSS alignment code that is shared between both the Flexbox and CSS Grid algorithms.
+use crate::style::{AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignmentSafety};
+
+/// Resolve the `safe`/`unsafe` overflow-position fallback for a self-level alignment value
+/// (used by `align-self` / `justify-self`-style sites and by absolutely-positioned items in
+/// flex/grid). If the alignment subject overflows its alignment container and the requested
+/// alignment is `safe`, fall back to logical `Start` per CSS Box Alignment
+/// <https://www.w3.org/TR/css-align-3/#overflow-values>. Otherwise drop the safety modifier
+/// and return the bare keyword.
+#[inline]
+pub(crate) fn resolve_self_alignment_safety(alignment: AlignItems, overflows: bool) -> AlignItemsKeyword {
+ if matches!(alignment.safety, AlignmentSafety::Safe) && overflows {
+ AlignItemsKeyword::Start
+ } else {
+ alignment.keyword
+ }
+}
+
+/// Resolve any spec-defined fallbacks for the given [`AlignContent`] value, returning the
+/// bare position keyword the alignment math should use.
+///
+/// In addition to the spec at <https://www.w3.org/TR/css-align-3/> this implementation follows
+/// the resolution of <https://github.com/w3c/csswg-drafts/issues/10154>.
+///
+/// `normal` behaves differently in each layout mode, so callers must resolve
+/// [`AlignContentKeyword::Normal`] to the keyword it behaves as before calling this function
+/// (if it is not resolved then it is treated as `stretch`).
+pub(crate) fn apply_alignment_fallback(
+ free_space: f32,
+ num_items: usize,
+ alignment_mode: AlignContent,
+) -> AlignContentKeyword {
+ debug_assert!(
+ alignment_mode.keyword != AlignContentKeyword::Normal,
+ "normal must be resolved before computing content alignment"
+ );
+ let mut keyword = match alignment_mode.keyword {
+ AlignContentKeyword::Normal => AlignContentKeyword::Stretch,
+ keyword => keyword,
+ };
+ let mut is_safe = matches!(alignment_mode.safety, AlignmentSafety::Safe);
+
+ // 1. If there is only a single item being aligned or the items overflow the container, the
+ // distributed alignment keywords (`stretch`, `space-*`) fall back to a positional keyword
+ // and gain implicit `safe` semantics so step 2 can flip them to `Start` on overflow.
+ // https://www.w3.org/TR/css-align-3/#distribution-values
+ if num_items <= 1 || free_space <= 0.0 {
+ (keyword, is_safe) = match keyword {
+ AlignContentKeyword::Stretch | AlignContentKeyword::SpaceBetween => (AlignContentKeyword::FlexStart, true),
+ AlignContentKeyword::SpaceAround | AlignContentKeyword::SpaceEvenly => (AlignContentKeyword::Center, true),
+ other => (other, is_safe),
+ };
+ }
+
+ // 2. Safe alignment falls back to `Start` whenever the alignment subject would overflow the
+ // alignment container.
+ if free_space <= 0.0 && is_safe {
+ keyword = AlignContentKeyword::Start;
+ }
+
+ keyword
+}
+
+/// Generic alignment function that is used:
+/// - For both align-content and justify-content alignment
+/// - For both the Flexbox and CSS Grid algorithms
+///
+/// CSS Grid does not apply gaps as part of alignment, so the gap parameter should
+/// always be set to zero for CSS Grid.
+pub(crate) fn compute_alignment_offset(
+ free_space: f32,
+ num_items: usize,
+ gap: f32,
+ alignment_mode: AlignContentKeyword,
+ layout_is_flex_reversed: bool,
+ is_first: bool,
+) -> f32 {
+ if is_first {
+ match alignment_mode {
+ AlignContentKeyword::Start => 0.0,
+ AlignContentKeyword::FlexStart => {
+ if layout_is_flex_reversed {
+ free_space
+ } else {
+ 0.0
+ }
+ }
+ AlignContentKeyword::End => free_space,
+ AlignContentKeyword::FlexEnd => {
+ if layout_is_flex_reversed {
+ 0.0
+ } else {
+ free_space
+ }
+ }
+ AlignContentKeyword::Center => free_space / 2.0,
+ AlignContentKeyword::Normal | AlignContentKeyword::Stretch => 0.0,
+ AlignContentKeyword::SpaceBetween => 0.0,
+ AlignContentKeyword::SpaceAround => {
+ if free_space >= 0.0 {
+ (free_space / num_items as f32) / 2.0
+ } else {
+ free_space / 2.0
+ }
+ }
+ AlignContentKeyword::SpaceEvenly => {
+ if free_space >= 0.0 {
+ free_space / (num_items + 1) as f32
+ } else {
+ free_space / 2.0
+ }
+ }
+ }
+ } else {
+ let free_space = free_space.max(0.0);
+ gap + match alignment_mode {
+ AlignContentKeyword::Start
+ | AlignContentKeyword::FlexStart
+ | AlignContentKeyword::End
+ | AlignContentKeyword::FlexEnd
+ | AlignContentKeyword::Center
+ | AlignContentKeyword::Normal
+ | AlignContentKeyword::Stretch => 0.0,
+ AlignContentKeyword::SpaceBetween => free_space / (num_items - 1) as f32,
+ AlignContentKeyword::SpaceAround => free_space / num_items as f32,
+ AlignContentKeyword::SpaceEvenly => free_space / (num_items + 1) as f32,
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/common/mod.rs b/vendor/taffy/src/compute/common/mod.rs
new file mode 100644
index 00000000..f7807e92
--- /dev/null
+++ b/vendor/taffy/src/compute/common/mod.rs
@@ -0,0 +1,6 @@
+//! Generic code that is shared between multiple layout algorithms
+pub(crate) mod alignment;
+pub(crate) mod sizing_keyword;
+
+#[cfg(feature = "content_size")]
+pub(crate) mod scrollable_overflow;
diff --git a/vendor/taffy/src/compute/common/scrollable_overflow.rs b/vendor/taffy/src/compute/common/scrollable_overflow.rs
new file mode 100644
index 00000000..08937627
--- /dev/null
+++ b/vendor/taffy/src/compute/common/scrollable_overflow.rs
@@ -0,0 +1,62 @@
+//! Generic CSS scrollable overflow code that is shared between all CSS algorithms.
+use crate::geometry::{Point, Rect, Size};
+use crate::style::{Contain, Overflow};
+use crate::util::sys::{f32_max, f32_min};
+
+#[inline(always)]
+/// Determine the rectangle that a given node contributes to its parent's scrollable overflow
+/// rectangle.
+///
+/// `location` is the position of the node's border box measured from the parent's scroll origin
+/// (logical start edge): callers pass coordinates that are mirrored for RTL. The node's own
+/// `scrollable_overflow_rect` propagates to the parent only where the node's overflow allows it
+/// to escape: a scroll container (`Hidden`/`Scroll` in either axis) clips both axes and
+/// contributes only its border box, while for non-scroll-containers `Clip` clips just its own
+/// axis and `Visible` propagates.
+///
+/// Boxes positioned wholly in the unreachable scrollable overflow region (entirely before the
+/// scroll origin in either axis) must be clipped by a scroll container and are excluded from its
+/// scrollable overflow region (<https://www.w3.org/TR/css-overflow-3/#scrollable>). This
+/// exclusion only applies when the parent is a scroll container: boxes with `overflow: visible`
+/// have no unreachable region of their own, so all of their content contributes.
+///
+/// A box whose containment contains its scrollable overflow (layout or paint containment)
+/// contributes only its border box, regardless of its overflow style.
+pub(crate) fn compute_scrollable_overflow_contribution(
+ location: Point<f32>,
+ size: Size<f32>,
+ scrollable_overflow_rect: Rect<f32>,
+ overflow: Point<Overflow>,
+ contain: Contain,
+ parent_is_scroll_container: bool,
+) -> Rect<f32> {
+ let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
+ let overflow_is_contained = contain.contains_scrollable_overflow();
+ let propagates = Point {
+ x: !is_scroll_container && !overflow_is_contained && overflow.x == Overflow::Visible,
+ y: !is_scroll_container && !overflow_is_contained && overflow.y == Overflow::Visible,
+ };
+ let end_extent = Size {
+ width: if propagates.x { f32_max(size.width, scrollable_overflow_rect.right) } else { size.width },
+ height: if propagates.y { f32_max(size.height, scrollable_overflow_rect.bottom) } else { size.height },
+ };
+ if end_extent.width <= 0.0 || end_extent.height <= 0.0 {
+ return Rect::ZERO;
+ }
+ let start_extent = Point {
+ x: if propagates.x { f32_min(0.0, scrollable_overflow_rect.left) } else { 0.0 },
+ y: if propagates.y { f32_min(0.0, scrollable_overflow_rect.top) } else { 0.0 },
+ };
+ let contribution = Rect {
+ left: location.x + start_extent.x,
+ right: location.x + end_extent.width,
+ top: location.y + start_extent.y,
+ bottom: location.y + end_extent.height,
+ };
+ let is_wholly_unreachable = contribution.right <= 0.0 || contribution.bottom <= 0.0;
+ if parent_is_scroll_container && is_wholly_unreachable {
+ Rect::ZERO
+ } else {
+ contribution
+ }
+}
diff --git a/vendor/taffy/src/compute/common/sizing_keyword.rs b/vendor/taffy/src/compute/common/sizing_keyword.rs
new file mode 100644
index 00000000..86f630aa
--- /dev/null
+++ b/vendor/taffy/src/compute/common/sizing_keyword.rs
@@ -0,0 +1,162 @@
+//! Shared resolution logic for sizing keywords (`min-content`, `max-content`, `fit-content`,
+//! `fit-content(...)`, and `stretch`) on the `width`/`height` style properties
+use crate::geometry::{AbsoluteAxis, Line, Rect, Size};
+use crate::style::AvailableSpace;
+use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId, SizingMode};
+use crate::util::sys::f32_max;
+use crate::{CompactLength, Dimension};
+
+/// How a sizing keyword resolves to a used size
+pub(crate) enum SizingKeywordResolution {
+ /// The size is the result of measuring the item under the given available space constraint
+ Measure(AvailableSpace),
+ /// The size resolves to an exact value without measuring the item
+ Exact(f32),
+}
+
+/// Resolve an item's size style in one axis if it is a sizing keyword (`min-content`,
+/// `max-content`, `fit-content`, `fit-content(...)`, or `stretch`).
+///
+/// - `stretch_size` is the size the item would take if stretched to fill the available space
+/// (available space minus margins). Used by `fit-content` and `stretch`.
+/// - `percent_resolution_basis` is the size that percentages resolve against in this axis.
+/// Used by `fit-content(<percentage>)`.
+///
+/// Returns `None` if the size style is not a sizing keyword, or if it cannot
+/// be resolved in the current context (in which case it behaves as `auto`).
+#[inline]
+pub(crate) fn resolve_sizing_keyword(
+ style: Dimension,
+ stretch_size: Option<f32>,
+ percent_resolution_basis: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+) -> Option<SizingKeywordResolution> {
+ #[cfg(not(feature = "calc"))]
+ let _ = &calc_resolver;
+ match style.tag() {
+ CompactLength::MIN_CONTENT_TAG => Some(SizingKeywordResolution::Measure(AvailableSpace::MinContent)),
+ CompactLength::MAX_CONTENT_TAG => Some(SizingKeywordResolution::Measure(AvailableSpace::MaxContent)),
+ CompactLength::FIT_CONTENT_PX_TAG => {
+ Some(SizingKeywordResolution::Measure(AvailableSpace::Definite(style.value())))
+ }
+ CompactLength::FIT_CONTENT_PERCENT_TAG => percent_resolution_basis
+ .map(|basis| SizingKeywordResolution::Measure(AvailableSpace::Definite(basis * style.value()))),
+ CompactLength::FIT_CONTENT_KEYWORD_TAG => {
+ stretch_size.map(|size| SizingKeywordResolution::Measure(AvailableSpace::Definite(size)))
+ }
+ #[cfg(feature = "calc")]
+ _ if style.is_fit_content_calc() => percent_resolution_basis.map(|basis| {
+ SizingKeywordResolution::Measure(AvailableSpace::Definite(calc_resolver(style.calc_value(), basis)))
+ }),
+ CompactLength::STRETCH_TAG => stretch_size.map(SizingKeywordResolution::Exact),
+ _ => None,
+ }
+}
+
+/// Resolve the sizing keywords (`min-content`, `max-content`, `fit-content`, `fit-content(...)`,
+/// and `stretch`) on the size styles of an absolutely positioned item, filling in the
+/// corresponding `known_dimensions` axes.
+///
+/// - `area_size` is the size of the item's containing block (which insets and percentages
+/// resolve against).
+/// - The stretch size in each axis is the containing block minus the item's insets and margins
+/// in that axis.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn resolve_absolute_sizing_keywords(
+ tree: &mut impl LayoutPartialTree,
+ node: NodeId,
+ known_dimensions: &mut Size<Option<f32>>,
+ size_style: Size<Dimension>,
+ area_size: Size<f32>,
+ inset: Rect<Option<f32>>,
+ margin: Rect<Option<f32>>,
+ sizing_mode: SizingMode,
+) {
+ let stretch_size = Size {
+ width: f32_max(
+ area_size.width
+ - inset.left.unwrap_or(0.0)
+ - inset.right.unwrap_or(0.0)
+ - margin.left.unwrap_or(0.0)
+ - margin.right.unwrap_or(0.0),
+ 0.0,
+ ),
+ height: f32_max(
+ area_size.height
+ - inset.top.unwrap_or(0.0)
+ - inset.bottom.unwrap_or(0.0)
+ - margin.top.unwrap_or(0.0)
+ - margin.bottom.unwrap_or(0.0),
+ 0.0,
+ ),
+ };
+
+ let keyword_width = if known_dimensions.width.is_none() {
+ resolve_sizing_keyword(size_style.width, Some(stretch_size.width), Some(area_size.width), |val, basis| {
+ tree.calc(val, basis)
+ })
+ } else {
+ None
+ };
+ let keyword_height = if known_dimensions.height.is_none() {
+ resolve_sizing_keyword(size_style.height, Some(stretch_size.height), Some(area_size.height), |val, basis| {
+ tree.calc(val, basis)
+ })
+ } else {
+ None
+ };
+
+ match (keyword_width, keyword_height) {
+ // If both axes need to be measured then resolve them with a single measure call
+ (
+ Some(SizingKeywordResolution::Measure(available_width)),
+ Some(SizingKeywordResolution::Measure(available_height)),
+ ) => {
+ let measured_size = tree.measure_child_size_both(
+ node,
+ Size::NONE,
+ area_size.map(Some),
+ Size { width: available_width, height: available_height },
+ sizing_mode,
+ Line::FALSE,
+ );
+ *known_dimensions = measured_size.map(Some);
+ }
+ (keyword_width, keyword_height) => {
+ if let Some(resolution) = keyword_width {
+ known_dimensions.width = Some(match resolution {
+ SizingKeywordResolution::Exact(width) => width,
+ SizingKeywordResolution::Measure(available_width) => tree.measure_child_size(
+ node,
+ *known_dimensions,
+ area_size.map(Some),
+ Size { width: available_width, height: AvailableSpace::Definite(stretch_size.height) },
+ sizing_mode,
+ AbsoluteAxis::Horizontal,
+ Line::FALSE,
+ ),
+ });
+ }
+ if let Some(resolution) = keyword_height {
+ known_dimensions.height = Some(match resolution {
+ SizingKeywordResolution::Exact(height) => height,
+ SizingKeywordResolution::Measure(available_height) => tree.measure_child_size(
+ node,
+ *known_dimensions,
+ area_size.map(Some),
+ Size {
+ width: known_dimensions
+ .width
+ .map(AvailableSpace::Definite)
+ .unwrap_or(AvailableSpace::Definite(stretch_size.width)),
+ height: available_height,
+ },
+ sizing_mode,
+ AbsoluteAxis::Vertical,
+ Line::FALSE,
+ ),
+ });
+ }
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/flexbox.rs b/vendor/taffy/src/compute/flexbox.rs
new file mode 100644
index 00000000..f9a9b870
--- /dev/null
+++ b/vendor/taffy/src/compute/flexbox.rs
@@ -0,0 +1,3467 @@
+//! Computes the [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) layout algorithm on [`TaffyTree`](crate::TaffyTree) according to the [spec](https://www.w3.org/TR/css-flexbox-1/)
+use crate::compute::common::alignment::{compute_alignment_offset, resolve_self_alignment_safety};
+use crate::geometry::{Line, Point, Rect, Size};
+use crate::style::{
+ AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AvailableSpace, Contain,
+ JustifyContent, LengthPercentageAuto, Overflow, Position,
+};
+use crate::style::{CoreStyle, FlexDirection, FlexboxContainerStyle, FlexboxItemStyle};
+use crate::style_helpers::{TaffyMaxContent, TaffyMinContent};
+use crate::tree::{
+ AxisStaticAlign, AxisStaticEdge, AxisStaticPosition, LayoutFlexboxContainer, LayoutPartialTreeExt, NodeId,
+ OofPositioningArea,
+};
+use crate::tree::{Baselines, Layout, LayoutInput, LayoutOutput, OofCandidate, OofCandidates, RunMode, SizingMode};
+use crate::util::debug::debug_log;
+use crate::util::sys::{f32_max, f32_min, new_vec_with_capacity, Vec};
+use crate::util::MaybeMath;
+use crate::util::{MaybeResolve, ResolveOrZero};
+use crate::{BoxGenerationMode, BoxSizing, Dimension, Direction, RequestedAxis};
+
+use super::common::alignment::apply_alignment_fallback;
+#[cfg(feature = "content_size")]
+use super::common::scrollable_overflow::compute_scrollable_overflow_contribution;
+use super::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
+
+/// The intermediate results of a flexbox calculation for a single item
+struct FlexItem {
+ /// The identifier for the associated node
+ node: NodeId,
+
+ /// The order of the node relative to it's siblings
+ order: u32,
+
+ /// The base size of this item
+ size: Size<Option<f32>>,
+ /// The raw size style of this item. Used to detect and resolve sizing
+ /// keywords (`min-content`, `max-content`, `fit-content`, `fit-content(...)`, and `stretch`)
+ size_style: Size<Dimension>,
+ /// The minimum allowable size of this item
+ min_size: Size<Option<f32>>,
+ /// The maximum allowable size of this item
+ max_size: Size<Option<f32>>,
+ /// The aspect ratio of this item
+ aspect_ratio: Option<f32>,
+ /// The cross-alignment of this item
+ align_self: AlignSelf,
+
+ /// The overflow style of the item
+ overflow: Point<Overflow>,
+ /// The contain style of the item
+ contain: Contain,
+ /// The width of the scrollbars (if it has any)
+ scrollbar_width: f32,
+ /// The flex shrink style of the item
+ flex_shrink: f32,
+ /// The flex grow style of the item
+ flex_grow: f32,
+ /// Whether the item's used flex basis is definite (rather than derived from the item's content)
+ flex_basis_is_definite: bool,
+
+ /// The minimum size of the item. This differs from min_size above because it also
+ /// takes into account content based automatic minimum sizes
+ resolved_minimum_main_size: f32,
+
+ /// The `position: relative` offset of this item, resolved to (width, height) in the
+ /// container's coordinate space (zero for non-relative items)
+ relative_inset: Size<f32>,
+ /// The margin of this item
+ margin: Rect<f32>,
+ /// Whether each margin is an auto margin or not
+ margin_is_auto: Rect<bool>,
+ /// The padding of this item
+ padding: Rect<f32>,
+ /// The border of this item
+ border: Rect<f32>,
+
+ /// The default size of this item
+ flex_basis: f32,
+ /// The default size of this item, minus padding and border
+ inner_flex_basis: f32,
+ /// The amount by which this item has deviated from its target size
+ violation: f32,
+ /// Is the size of this item locked
+ frozen: bool,
+
+ /// Either the max- or min- content flex fraction
+ /// See https://www.w3.org/TR/css-flexbox-1/#intrinsic-main-sizes
+ content_flex_fraction: f32,
+
+ /// The proposed inner size of this item
+ hypothetical_inner_size: Size<f32>,
+ /// The proposed outer size of this item
+ hypothetical_outer_size: Size<f32>,
+ /// The size that this item wants to be
+ target_size: Size<f32>,
+ /// The size that this item wants to be, plus any padding and border
+ outer_target_size: Size<f32>,
+
+ /// The position of the bottom edge of this item
+ baseline: f32,
+
+ /// A temporary value for the main offset
+ ///
+ /// Offset is the relative position from the item's natural flow position based on
+ /// relative position values, alignment, and justification. Does not include margin/padding/border.
+ offset_main: f32,
+ /// A temporary value for the cross offset
+ ///
+ /// Offset is the relative position from the item's natural flow position based on
+ /// relative position values, alignment, and justification. Does not include margin/padding/border.
+ offset_cross: f32,
+
+ /// Out-of-flow candidates bubbled out of this item's subtree. Anchors are relative to the
+ /// container's border box (translated when the item's final layout is computed).
+ oof_candidates: OofCandidates,
+}
+
+impl FlexItem {
+ /// Returns true if the item is a <https://www.w3.org/TR/css-overflow-3/#scroll-container>
+ fn is_scroll_container(&self) -> bool {
+ self.overflow.x.is_scroll_container() | self.overflow.y.is_scroll_container()
+ }
+
+ /// Returns true if the item participates in baseline alignment: it has `align-self: baseline`
+ /// and neither of its cross-axis margins are `auto`.
+ /// See <https://www.w3.org/TR/css-flexbox-1/#baseline-participation>
+ fn participates_in_baseline_alignment(&self, dir: FlexDirection) -> bool {
+ self.align_self == AlignSelf::BASELINE
+ && !self.margin_is_auto.cross_start(dir)
+ && !self.margin_is_auto.cross_end(dir)
+ }
+}
+
+/// A line of [`FlexItem`] used for intermediate computation
+struct FlexLine<'a> {
+ /// The slice of items to iterate over during computation of this line
+ items: &'a mut [FlexItem],
+ /// The dimensions of the cross-axis
+ cross_size: f32,
+ /// The relative offset of the cross-axis
+ offset_cross: f32,
+}
+
+/// Values that can be cached during the flexbox algorithm
+struct AlgoConstants {
+ /// The direction of the current segment being laid out
+ dir: FlexDirection,
+ /// The layout direction of the current segment being laid out
+ layout_direction: Direction,
+ /// Is this segment a row
+ is_row: bool,
+ /// Is this segment a column
+ is_column: bool,
+ /// Is wrapping enabled (in either direction)
+ is_wrap: bool,
+ /// Is the wrap direction inverted
+ is_wrap_reverse: bool,
+ /// Are items balanced across lines (`flex-wrap: balance`)?
+ #[cfg(feature = "flexbox_balance")]
+ is_balance: bool,
+ /// The requested minimum number of lines (`flex-line-count`). `Some` for every
+ /// multi-line container, `None` for `nowrap`.
+ #[cfg(feature = "flexbox_balance")]
+ line_count: Option<u16>,
+
+ /// The item's min_size style
+ min_size: Size<Option<f32>>,
+ /// The item's max_size style
+ max_size: Size<Option<f32>>,
+ /// The border of this section
+ border: Rect<f32>,
+ /// The space between the content box and the border box.
+ /// This consists of padding + border + scrollbar_gutter.
+ content_box_inset: Rect<f32>,
+ /// The size reserved for scrollbar gutters in each axis
+ scrollbar_gutter: Point<f32>,
+ /// Whether the node being laid out is a scroll container
+ #[cfg(feature = "content_size")]
+ is_scroll_container: bool,
+ /// The gap of this section
+ gap: Size<f32>,
+ /// The align_items property of this node
+ align_items: AlignItems,
+ /// The align_content property of this node
+ align_content: AlignContent,
+ /// The justify_content property of this node
+ justify_content: JustifyContent,
+
+ /// The border-box size of the node being laid out (if known)
+ node_outer_size: Size<Option<f32>>,
+ /// The content-box size of the node being laid out (if known)
+ node_inner_size: Size<Option<f32>>,
+ /// Whether the known main size of the node (if any) is definite. This is `false` when a parent
+ /// imposes a main size on this node that is derived from the node's own content, in which case
+ /// it is indefinite for the purposes of resolving percentage sizes of items and collecting items
+ /// into flex lines. See <https://www.w3.org/TR/css-flexbox-1/#definite-sizes>.
+ known_main_size_is_definite: bool,
+ /// Whether the node has a known main size which is definite (as of the start of layout,
+ /// before the main size is determined from the node's contents)
+ has_definite_main_size: bool,
+ /// Whether the node has a known cross size which is definite
+ has_definite_cross_size: bool,
+ /// Whether the cross-axis space that non-stretched items are fit-content sized into is
+ /// definite (either the node's cross size is definite, or the cross-axis available space is).
+ /// A size resolved by fit-content sizing against definite available space is itself definite
+ /// (see <https://www.w3.org/TR/css-sizing-3/#definite>).
+ cross_axis_available_space_is_definite: bool,
+
+ /// The size of the virtual container containing the flex items.
+ container_size: Size<f32>,
+ /// The size of the internal container
+ inner_container_size: Size<f32>,
+}
+
+impl AlgoConstants {
+ /// When a multi-line container requests a minimum number of lines (`flex-line-count`),
+ /// definite cross-axis available space for measuring items is divided between the requested
+ /// number of lines (after subtracting the cross-axis gaps between them).
+ /// See <https://github.com/w3c/csswg-drafts/issues/13414>
+ #[inline]
+ fn divided_cross_space(&self, cross_available_space: f32) -> f32 {
+ #[cfg(feature = "flexbox_balance")]
+ if let Some(line_count) = self.line_count {
+ if line_count > 1 {
+ let line_count = line_count as f32;
+ return (cross_available_space - (line_count - 1.0) * self.gap.cross(self.dir)) / line_count;
+ }
+ }
+ cross_available_space
+ }
+}
+
+/// Computes the layout of a box according to the flexbox algorithm
+pub fn compute_flexbox_layout(
+ tree: &mut impl LayoutFlexboxContainer,
+ node: NodeId,
+ inputs: LayoutInput,
+) -> LayoutOutput {
+ let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
+ let style = tree.get_flexbox_container_style(node);
+
+ // Pull these out earlier to avoid borrowing issues
+ let contain = style.contain();
+ let aspect_ratio = style.aspect_ratio();
+ let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_sum = padding.sum_axes() + border.sum_axes();
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
+
+ let min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
+ style
+ .size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .maybe_clamp(min_size, max_size)
+ } else {
+ Size::NONE
+ };
+
+ // If both min and max in a given axis are set and max <= min then this determines the size in that axis
+ let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
+ (Some(min), Some(max)) if max <= min => Some(min),
+ _ => None,
+ });
+
+ // The size of the container should be floored by the padding and border
+ let styled_based_known_dimensions =
+ known_dimensions.or(min_max_definite_size.or(clamped_style_size).maybe_max(padding_border_sum));
+
+ // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
+ // is ComputeSize (and thus the container's size is all that we're interested in)
+ if run_mode == RunMode::ComputeSize {
+ if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
+ return LayoutOutput::from_outer_size(Size { width, height });
+ }
+
+ // We can also short-circuit if the width is known and only the width has been requested.
+ if inputs.axis == RequestedAxis::Horizontal {
+ if let Some(width) = styled_based_known_dimensions.width {
+ return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
+ }
+ }
+ }
+
+ // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
+ // is ComputeSize (and thus the container's size is all that we're interested in)
+ if run_mode == RunMode::ComputeSize {
+ if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
+ return LayoutOutput::from_outer_size(Size { width, height });
+ }
+ }
+
+ debug_log!("FLEX:", dbg:style.flex_direction());
+ drop(style);
+
+ // Normalize the definiteness flags: they only apply to dimensions which were passed in as known
+ // by the parent. Dimensions resolved from the node's own style are always definite.
+ let known_dimensions_are_definite = inputs
+ .known_dimensions_are_definite
+ .zip_map(known_dimensions, |is_definite, known_dimension| is_definite || known_dimension.is_none());
+
+ let mut output = compute_preliminary(
+ tree,
+ node,
+ LayoutInput { known_dimensions: styled_based_known_dimensions, known_dimensions_are_definite, ..inputs },
+ );
+
+ // Layout containment suppresses the box's baseline for baseline-alignment purposes
+ if contain.suppresses_baseline() {
+ output.baselines = Baselines::NONE;
+ }
+
+ output
+}
+
+/// Compute a preliminary size for an item
+fn compute_preliminary(tree: &mut impl LayoutFlexboxContainer, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
+ let LayoutInput { known_dimensions, parent_size, available_space, run_mode, .. } = inputs;
+
+ // Define some general constants we will need for the remainder of the algorithm.
+ let mut constants = compute_constants(
+ tree,
+ tree.get_flexbox_container_style(node),
+ known_dimensions,
+ inputs.known_dimensions_are_definite,
+ parent_size,
+ available_space,
+ );
+
+ // 9. Flex Layout Algorithm
+
+ // 9.1. Initial Setup
+
+ // 1. Generate anonymous flex items as described in §4 Flex Items.
+ debug_log!("generate_anonymous_flex_items");
+ let mut flex_items = generate_anonymous_flex_items(tree, node, &constants);
+
+ // 9.2. Line Length Determination
+
+ // 2. Determine the available main and cross space for the flex items
+ debug_log!("determine_available_space");
+ let available_space = determine_available_space(known_dimensions, available_space, &constants);
+
+ // 3. Determine the flex base size and hypothetical main size of each item.
+ debug_log!("determine_flex_base_size");
+ determine_flex_base_size(tree, &constants, available_space, &mut flex_items);
+
+ #[cfg(feature = "debug")]
+ for item in flex_items.iter() {
+ debug_log!("item.flex_basis", item.flex_basis);
+ debug_log!("item.inner_flex_basis", item.inner_flex_basis);
+ debug_log!("item.hypothetical_outer_size", dbg:item.hypothetical_outer_size);
+ debug_log!("item.hypothetical_inner_size", dbg:item.hypothetical_inner_size);
+ debug_log!("item.resolved_minimum_main_size", dbg:item.resolved_minimum_main_size);
+ }
+
+ // 4. Determine the main size of the flex container
+ // This has already been done as part of compute_constants. The inner size is exposed as constants.node_inner_size.
+
+ // 9.3. Main Size Determination
+
+ // 5. Collect flex items into flex lines.
+ debug_log!("collect_flex_lines");
+ #[cfg(feature = "flexbox_balance")]
+ let mut flex_lines = if constants.is_balance {
+ collect_balanced_flex_lines(&constants, available_space, &mut flex_items)
+ } else {
+ collect_flex_lines(&constants, available_space, &mut flex_items)
+ };
+ #[cfg(not(feature = "flexbox_balance"))]
+ let mut flex_lines = collect_flex_lines(&constants, available_space, &mut flex_items);
+
+ // If container size is undefined, determine the container's main size
+ // and then re-resolve gaps based on newly determined size
+ debug_log!("determine_container_main_size");
+ if let Some(inner_main_size) = constants.node_inner_size.main(constants.dir) {
+ let outer_main_size = inner_main_size + constants.content_box_inset.main_axis_sum(constants.dir);
+ constants.inner_container_size.set_main(constants.dir, inner_main_size);
+ constants.container_size.set_main(constants.dir, outer_main_size);
+ } else {
+ // Sets constants.container_size and constants.outer_container_size
+ determine_container_main_size(tree, available_space, &mut flex_lines, &mut constants);
+ constants.node_inner_size.set_main(constants.dir, Some(constants.inner_container_size.main(constants.dir)));
+ constants.node_outer_size.set_main(constants.dir, Some(constants.container_size.main(constants.dir)));
+
+ debug_log!("constants.node_outer_size", dbg:constants.node_outer_size);
+ debug_log!("constants.node_inner_size", dbg:constants.node_inner_size);
+
+ // Re-resolve percentage gaps
+ let style = tree.get_flexbox_container_style(node);
+ let inner_container_size = constants.inner_container_size.main(constants.dir);
+ let new_gap = style
+ .gap()
+ .main(constants.dir)
+ .maybe_resolve(inner_container_size, |val, basis| tree.calc(val, basis))
+ .unwrap_or(0.0);
+ constants.gap.set_main(constants.dir, new_gap);
+ }
+
+ // If only the container's main size has been requested then we are done, as nothing below changes it. This
+ // avoids measuring the cross size of every item.
+ if run_mode == RunMode::ComputeSize {
+ let main_axis_is_requested_axis = match inputs.axis {
+ RequestedAxis::Horizontal => constants.dir.is_row(),
+ RequestedAxis::Vertical => constants.dir.is_column(),
+ RequestedAxis::Both => false,
+ };
+ if main_axis_is_requested_axis {
+ let size = Size::ZERO.with_main(constants.dir, constants.container_size.main(constants.dir));
+ return LayoutOutput::from_outer_size(size);
+ }
+ }
+
+ // 6. Resolve the flexible lengths of all the flex items to find their used main size.
+ debug_log!("resolve_flexible_lengths");
+ for line in &mut flex_lines {
+ resolve_flexible_lengths(line, &constants);
+ }
+
+ // 9.4. Cross Size Determination
+
+ // 7. Determine the hypothetical cross size of each item.
+ debug_log!("determine_hypothetical_cross_size");
+ for line in &mut flex_lines {
+ determine_hypothetical_cross_size(tree, line, &constants, available_space);
+ }
+
+ // Calculate child baselines. This function is internally smart and only computes child baselines
+ // if they are necessary.
+ debug_log!("calculate_children_base_lines");
+ calculate_children_base_lines(tree, known_dimensions, available_space, &mut flex_lines, &constants);
+
+ // 8. Calculate the cross size of each flex line.
+ debug_log!("calculate_cross_size");
+ calculate_cross_size(&mut flex_lines, known_dimensions, &constants);
+
+ // 9. Handle 'align-content: stretch'.
+ debug_log!("handle_align_content_stretch");
+ handle_align_content_stretch(&mut flex_lines, known_dimensions, &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.
+ debug_log!("determine_used_cross_size");
+ determine_used_cross_size(tree, &mut flex_lines, &constants);
+
+ // 9.5. Main-Axis Alignment
+
+ // 12. Distribute any remaining free space.
+ debug_log!("distribute_remaining_free_space");
+ distribute_remaining_free_space(&mut flex_lines, &constants);
+
+ // 9.6. Cross-Axis Alignment
+
+ // 13. Resolve cross-axis auto margins (also includes 14).
+ debug_log!("resolve_cross_axis_auto_margins");
+ resolve_cross_axis_auto_margins(&mut flex_lines, &constants);
+
+ // 15. Determine the flex container’s used cross size.
+ debug_log!("determine_container_cross_size");
+ let total_line_cross_size = determine_container_cross_size(&flex_lines, known_dimensions, &mut constants);
+
+ // We have the container size.
+ // If our caller does not care about performing layout we are done now.
+ if run_mode == RunMode::ComputeSize {
+ return LayoutOutput::from_outer_size(constants.container_size);
+ }
+
+ // 16. Align all flex lines per align-content.
+ debug_log!("align_flex_lines_per_align_content");
+ align_flex_lines_per_align_content(&mut flex_lines, &constants, total_line_cross_size);
+
+ // Do a final layout pass and gather the resulting layouts
+ debug_log!("final_layout_pass");
+ let inflow_overflow_rect = final_layout_pass(tree, &mut flex_lines, &constants);
+
+ // Collect out-of-flow candidates in document order (direct out-of-flow children interleaved
+ // with candidates bubbled from in-flow children's subtrees). These are laid out by the
+ // out-of-flow positioning pass (`compute_oof_layout`), which runs after this algorithm.
+ let mut candidates = OofCandidates::new();
+ collect_oof_candidates(tree, node, &constants, &mut flex_lines, &mut candidates);
+
+ let absolute_position_inset = constants.border
+ + Rect {
+ left: if constants.layout_direction.is_rtl() { constants.scrollbar_gutter.x } else { 0.0 },
+ right: if constants.layout_direction.is_rtl() { 0.0 } else { constants.scrollbar_gutter.x },
+ top: 0.0,
+ bottom: constants.scrollbar_gutter.y,
+ };
+ let absolute_position_area = constants.container_size - absolute_position_inset.sum_axes();
+ let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
+
+ debug_log!("hidden_layout");
+ let len = tree.child_count(node);
+ for order in 0..len {
+ let child = tree.get_child_id(node, order);
+ if tree.get_flexbox_child_style(child).box_generation_mode() == BoxGenerationMode::None {
+ tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
+ tree.perform_child_layout(
+ child,
+ Size::NONE,
+ Size::NONE,
+ Size::MAX_CONTENT,
+ SizingMode::ContentSize,
+ Line::FALSE,
+ );
+ }
+ }
+
+ // 8.5. Flex Container Baselines: calculate the flex container's first baseline
+ // See https://www.w3.org/TR/css-flexbox-1/#flex-baselines
+ // The baselines are generated from the startmost flex line, where "startmost" refers to the
+ // line's visual position: for wrap-reverse containers the cross axis is flipped, so the
+ // startmost line is the last line in flex-line order rather than the first.
+ let first_line = if constants.is_wrap_reverse { flex_lines.last() } else { flex_lines.first() };
+ let first_vertical_baseline = first_line.and_then(|line| {
+ if constants.is_column {
+ // For column containers the baseline is generated from the startmost item in the line,
+ // which for reverse-direction containers is the last item in flex order.
+ let item = if constants.dir.is_reverse() { line.items.last() } else { line.items.first() };
+ item.map(|child| child.baseline)
+ } else {
+ line.items
+ .iter()
+ .find(|item| item.participates_in_baseline_alignment(constants.dir))
+ .or_else(|| line.items.iter().next())
+ .map(|child| child.baseline)
+ }
+ });
+
+ let mut output = LayoutOutput::from_sizes_and_baselines(
+ constants.container_size,
+ inflow_overflow_rect,
+ Baselines::from_first(first_vertical_baseline),
+ );
+ output.oof_candidates = candidates;
+ output.oof_positioning_area =
+ Some(OofPositioningArea { size: absolute_position_area, offset: absolute_position_offset });
+ output
+}
+
+/// Resolve the `normal` alignment keyword, which behaves as `stretch` for flex items.
+/// <https://www.w3.org/TR/css-align-3/#align-flex>
+#[inline(always)]
+fn resolve_normal_alignment(alignment: AlignItems) -> AlignItems {
+ match alignment.keyword {
+ AlignItemsKeyword::Normal => AlignItems::STRETCH,
+ _ => alignment,
+ }
+}
+
+/// Compute constants that can be reused during the flexbox algorithm.
+#[inline]
+fn compute_constants(
+ tree: &impl LayoutFlexboxContainer,
+ style: impl FlexboxContainerStyle,
+ known_dimensions: Size<Option<f32>>,
+ known_dimensions_are_definite: Size<bool>,
+ parent_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+) -> AlgoConstants {
+ let dir = style.flex_direction();
+ let is_row = dir.is_row();
+ let is_column = dir.is_column();
+ let flex_wrap = style.flex_wrap();
+ let is_wrap = flex_wrap.is_multi_line();
+ let is_wrap_reverse = flex_wrap.is_reverse();
+ #[cfg(feature = "flexbox_balance")]
+ let is_balance = flex_wrap.is_balance();
+ #[cfg(feature = "flexbox_balance")]
+ let line_count = if is_wrap { Some(style.flex_line_count().max(1)) } else { None };
+
+ let aspect_ratio = style.aspect_ratio();
+ let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_sum = padding.sum_axes() + border.sum_axes();
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
+
+ // `normal` behaves as `stretch` for flex items. This is resolved once here so that
+ // items with an `align_self` of `None`, which defer to this value, are also resolved.
+ let align_items = resolve_normal_alignment(style.align_items());
+ // `normal` behaves as `stretch` for flex containers. In the main axis `stretch` behaves as
+ // `flex-start`, so a `normal` justify-content is resolved straight to `flex-start`.
+ // <https://www.w3.org/TR/css-align-3/#distribution-flex>
+ let align_content = match style.align_content() {
+ AlignContent { keyword: AlignContentKeyword::Normal, .. } => AlignContent::STRETCH,
+ align_content => align_content,
+ };
+ let justify_content = match style.justify_content() {
+ JustifyContent { keyword: AlignContentKeyword::Normal, .. } => JustifyContent::FLEX_START,
+ justify_content => justify_content,
+ };
+ let layout_direction = style.direction();
+
+ // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
+ // However, the axis are switched (transposed) because a node that scrolls vertically needs
+ // *horizontal* space to be reserved for a scrollbar
+ let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
+ Overflow::Scroll => style.scrollbar_width(),
+ _ => 0.0,
+ });
+ #[cfg(feature = "content_size")]
+ let is_scroll_container = {
+ let overflow = style.overflow();
+ overflow.x.is_scroll_container() || overflow.y.is_scroll_container()
+ };
+ let mut content_box_inset = padding + border;
+ content_box_inset.bottom += scrollbar_gutter.y;
+
+ match layout_direction {
+ Direction::Ltr => content_box_inset.right += scrollbar_gutter.x,
+ Direction::Rtl => content_box_inset.left += scrollbar_gutter.x,
+ };
+
+ let node_outer_size = known_dimensions;
+ let node_inner_size = node_outer_size.maybe_sub(content_box_inset.sum_axes());
+ let known_main_size_is_definite = known_dimensions_are_definite.main(dir);
+ let has_definite_main_size = known_main_size_is_definite && known_dimensions.main(dir).is_some();
+ let has_definite_cross_size = known_dimensions_are_definite.cross(dir) && known_dimensions.cross(dir).is_some();
+ let cross_axis_available_space_is_definite =
+ has_definite_cross_size || matches!(available_space.cross(dir), AvailableSpace::Definite(_));
+ let gap = style.gap().resolve_or_zero(node_inner_size.or(Size::zero()), |val, basis| tree.calc(val, basis));
+
+ let container_size = Size::zero();
+ let inner_container_size = Size::zero();
+
+ AlgoConstants {
+ dir,
+ layout_direction,
+ is_row,
+ is_column,
+ is_wrap,
+ is_wrap_reverse,
+ #[cfg(feature = "flexbox_balance")]
+ is_balance,
+ #[cfg(feature = "flexbox_balance")]
+ line_count,
+ min_size: style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ max_size: style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ border,
+ gap,
+ content_box_inset,
+ scrollbar_gutter,
+ #[cfg(feature = "content_size")]
+ is_scroll_container,
+ align_items,
+ align_content,
+ justify_content,
+ node_outer_size,
+ node_inner_size,
+ known_main_size_is_definite,
+ has_definite_main_size,
+ has_definite_cross_size,
+ cross_axis_available_space_is_definite,
+ container_size,
+ inner_container_size,
+ }
+}
+
+/// Resolve a `position: relative` item's inset to a single offset in the container's flex axes,
+/// accounting for flex direction and writing direction.
+fn resolve_relative_inset(inset: Rect<Option<f32>>, constants: &AlgoConstants) -> Size<f32> {
+ let direction = constants.dir;
+ let is_rtl_row = direction.is_row() && constants.layout_direction.is_rtl();
+ let is_rtl_column = direction.is_column() && constants.layout_direction.is_rtl();
+ let main = if is_rtl_row {
+ inset.main_end(direction).or(inset.main_start(direction).map(|pos| -pos)).unwrap_or(0.0)
+ } else {
+ inset.main_start(direction).or(inset.main_end(direction).map(|pos| -pos)).unwrap_or(0.0)
+ };
+ let cross = if is_rtl_column {
+ inset.cross_end(direction).map(|pos| -pos).or(inset.cross_start(direction)).unwrap_or(0.0)
+ } else {
+ inset.cross_start(direction).or(inset.cross_end(direction).map(|pos| -pos)).unwrap_or(0.0)
+ };
+ let mut out = Size::ZERO;
+ out.set_main(direction, main);
+ out.set_cross(direction, cross);
+ out
+}
+
+/// 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(
+ tree: &impl LayoutFlexboxContainer,
+ node: NodeId,
+ constants: &AlgoConstants,
+) -> Vec<FlexItem> {
+ // Percentage sizes of items resolve against the container's inner size, but only if that size
+ // is definite. A known main size which is derived from the container's own content is treated
+ // as indefinite here.
+ let percent_resolution_size = if constants.known_main_size_is_definite {
+ constants.node_inner_size
+ } else {
+ constants.node_inner_size.with_main(constants.dir, None)
+ };
+
+ tree.child_ids(node)
+ .enumerate()
+ .map(|(index, child)| (index, child, tree.get_flexbox_child_style(child)))
+ .filter(|(_, _, style)| !style.position().is_out_of_flow())
+ .filter(|(_, _, style)| style.box_generation_mode() != BoxGenerationMode::None)
+ .map(|(index, child, child_style)| {
+ let aspect_ratio = child_style.aspect_ratio();
+ let padding = child_style
+ .padding()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let border = child_style
+ .border()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let pb_sum = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
+ FlexItem {
+ node: child,
+ order: index as u32,
+ size: child_style
+ .size()
+ .maybe_resolve(percent_resolution_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment),
+ size_style: child_style.size(),
+ min_size: child_style
+ .min_size()
+ .maybe_resolve(percent_resolution_size, |val, basis| tree.calc(val, basis))
+ .maybe_add(box_sizing_adjustment),
+ max_size: child_style
+ .max_size()
+ .maybe_resolve(percent_resolution_size, |val, basis| tree.calc(val, basis))
+ .maybe_add(box_sizing_adjustment),
+ aspect_ratio,
+
+ relative_inset: if child_style.position() == Position::Relative {
+ let inset = child_style.inset().zip_size(constants.node_inner_size, |p, s| {
+ p.maybe_resolve(s, |val, basis| tree.calc(val, basis))
+ });
+ resolve_relative_inset(inset, constants)
+ } else {
+ Size::ZERO
+ },
+ margin: child_style
+ .margin()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
+ margin_is_auto: child_style.margin().map(LengthPercentageAuto::is_auto),
+ padding: child_style
+ .padding()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
+ border: child_style
+ .border()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
+ align_self: resolve_normal_alignment(child_style.align_self().unwrap_or(constants.align_items))
+ .resolve_self_relative(child_style.direction(), constants.layout_direction, constants.is_column),
+ overflow: child_style.overflow(),
+ contain: child_style.contain(),
+ scrollbar_width: child_style.scrollbar_width(),
+ flex_grow: child_style.flex_grow(),
+ flex_shrink: child_style.flex_shrink(),
+ flex_basis_is_definite: false,
+ flex_basis: 0.0,
+ inner_flex_basis: 0.0,
+ violation: 0.0,
+ frozen: false,
+
+ resolved_minimum_main_size: 0.0,
+ hypothetical_inner_size: Size::zero(),
+ hypothetical_outer_size: Size::zero(),
+ target_size: Size::zero(),
+ outer_target_size: Size::zero(),
+ content_flex_fraction: 0.0,
+
+ baseline: 0.0,
+
+ offset_main: 0.0,
+ offset_cross: 0.0,
+
+ oof_candidates: OofCandidates::NONE,
+ }
+ })
+ .collect()
+}
+
+/// 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**.
+///
+/// Note: the flex container's margins have already been subtracted from `outer_available_space` by its parent.
+#[inline]
+#[must_use]
+fn determine_available_space(
+ known_dimensions: Size<Option<f32>>,
+ outer_available_space: Size<AvailableSpace>,
+ constants: &AlgoConstants,
+) -> Size<AvailableSpace> {
+ // Note: min/max/preferred size styles have already been applied to known_dimensions in the `compute` function above
+ let width = match known_dimensions.width {
+ Some(node_width) => {
+ AvailableSpace::Definite((node_width - constants.content_box_inset.horizontal_axis_sum()).max(0.0))
+ }
+ None => outer_available_space.width.maybe_sub(constants.content_box_inset.horizontal_axis_sum()).maybe_max(0.0),
+ };
+
+ let height = match known_dimensions.height {
+ Some(node_height) => {
+ AvailableSpace::Definite((node_height - constants.content_box_inset.vertical_axis_sum()).max(0.0))
+ }
+ None => outer_available_space.height.maybe_sub(constants.content_box_inset.vertical_axis_sum()).maybe_max(0.0),
+ };
+
+ Size { width, height }
+}
+
+/// 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(
+ tree: &mut impl LayoutFlexboxContainer,
+ constants: &AlgoConstants,
+ available_space: Size<AvailableSpace>,
+ flex_items: &mut [FlexItem],
+) {
+ let dir = constants.dir;
+
+ for child in flex_items.iter_mut() {
+ let child_style = tree.get_flexbox_child_style(child.node);
+
+ // Parent size for child sizing
+ let cross_axis_parent_size = constants.node_inner_size.cross(dir);
+ let child_parent_size = Size::from_cross(dir, cross_axis_parent_size);
+
+ // Available space for child sizing (excluding the child's margins)
+ // Min/max sizes transferred through the aspect ratio are taken into account here
+ // https://github.com/w3c/csswg-drafts/issues/10997
+ let transferred_min_size = child.min_size.maybe_apply_aspect_ratio(child.aspect_ratio);
+ let transferred_max_size = child.max_size.maybe_apply_aspect_ratio(child.aspect_ratio);
+ let child_min_cross = transferred_min_size.cross(dir);
+ let child_max_cross = transferred_max_size.cross(dir);
+
+ // Clamp available space by min- and max- size
+ let cross_axis_available_space: AvailableSpace = match available_space.cross(dir) {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(
+ (constants.divided_cross_space(cross_axis_parent_size.unwrap_or(val))
+ - child.margin.cross_axis_sum(dir))
+ .max(0.0)
+ .maybe_clamp(child_min_cross, child_max_cross),
+ ),
+ AvailableSpace::MinContent => match child_min_cross {
+ Some(min) => AvailableSpace::Definite(min),
+ None => AvailableSpace::MinContent,
+ },
+ AvailableSpace::MaxContent => match child_max_cross {
+ Some(max) => AvailableSpace::Definite(max),
+ None => AvailableSpace::MaxContent,
+ },
+ };
+
+ // Known dimensions for child sizing
+ let mut child_cross_size_is_definite = child.size.cross(dir).is_some();
+ let child_known_dimensions = {
+ let mut ckd = child.size.with_main(dir, None);
+ // Clamp the definite cross size by the cross min/max sizes so that sizes
+ // transferred through an intrinsic aspect ratio (e.g. for replaced elements)
+ // are based on the used cross size.
+ ckd.set_cross(
+ dir,
+ ckd.cross(dir).maybe_clamp(transferred_min_size.cross(dir), transferred_max_size.cross(dir)),
+ );
+ if child.align_self == AlignSelf::STRETCH
+ && !child.margin_is_auto.cross_start(constants.dir)
+ && !child.margin_is_auto.cross_end(constants.dir)
+ && ckd.cross(dir).is_none()
+ {
+ ckd.set_cross(dir, cross_axis_available_space.into_option());
+ // The cross size of a stretched item is definite if the container has a definite
+ // cross size (https://www.w3.org/TR/css-flexbox-1/#definite-sizes)
+ child_cross_size_is_definite =
+ !constants.is_wrap && constants.has_definite_cross_size && cross_axis_parent_size.is_some();
+ }
+ ckd
+ };
+
+ // Percentage padding and border resolve against the container's inline size (its width),
+ // whichever axis is the main axis
+ let container_width = constants.node_inner_size.width;
+ let box_sizing_adjustment = if child_style.box_sizing() == BoxSizing::ContentBox {
+ let padding = child_style.padding().resolve_or_zero(container_width, |val, basis| tree.calc(val, basis));
+ let border = child_style.border().resolve_or_zero(container_width, |val, basis| tree.calc(val, basis));
+ (padding + border).sum_axes()
+ } else {
+ Size::ZERO
+ }
+ .main(dir);
+ // Percentage flex basis values resolve against the container's inner main size, but only
+ // if that size is definite. A known main size which is derived from the container's own
+ // content is treated as indefinite here.
+ let percent_resolution_main_size =
+ if constants.known_main_size_is_definite { constants.node_inner_size.main(dir) } else { None };
+ let flex_basis_style = child_style.flex_basis();
+ let flex_basis = flex_basis_style
+ .maybe_resolve(percent_resolution_main_size, |val, basis| tree.calc(val, basis))
+ .maybe_add(box_sizing_adjustment);
+
+ drop(child_style);
+
+ child.flex_basis = 'flex_basis: {
+ // 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.
+
+ let main_size = child.size.main(dir);
+ let main_stretch_size =
+ percent_resolution_main_size.maybe_sub(child.margin.main_axis_sum(dir)).maybe_max(0.0);
+
+ // A flex basis that is a sizing keyword (min-content, max-content, fit-content,
+ // fit-content(...), stretch) is used in place of the main size property: `stretch`
+ // resolves to an exact (definite) size while the other keywords determine the
+ // available space constraint the item is measured under. A keyword that cannot be
+ // resolved in the current context behaves as `content`.
+ let keyword_main_available_space = if flex_basis_style.is_content() {
+ // A flex basis of `content` indicates an automatic size based on the item's
+ // content: the item is measured (ignoring its main size property) under the
+ // default constraint below
+ None
+ } else if flex_basis_style.is_sizing_keyword() {
+ match resolve_sizing_keyword(
+ flex_basis_style,
+ main_stretch_size,
+ percent_resolution_main_size,
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Exact(size)) => {
+ child.flex_basis_is_definite = true;
+ break 'flex_basis size;
+ }
+ Some(SizingKeywordResolution::Measure(available)) => Some(available),
+ None => None,
+ }
+ } else {
+ if let Some(flex_basis) = flex_basis.or(main_size.filter(|_| flex_basis_style.is_auto())) {
+ child.flex_basis_is_definite = true;
+ break 'flex_basis flex_basis;
+ };
+
+ // A main size that is a sizing keyword either resolves to an exact size or
+ // determines the available space constraint the item is measured under
+ if flex_basis_style.is_auto() {
+ match resolve_sizing_keyword(
+ child.size_style.main(dir),
+ main_stretch_size,
+ percent_resolution_main_size,
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Exact(size)) => {
+ child.flex_basis_is_definite = true;
+ break 'flex_basis size;
+ }
+ Some(SizingKeywordResolution::Measure(available)) => Some(available),
+ None => None,
+ }
+ } else {
+ None
+ }
+ };
+
+ // 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.
+
+ // This is covered by the implementation of E below, which passes the available_space constraint
+ // through to the child size computation. It may need a separate implementation if/when D is implemented.
+
+ // D. Otherwise, if the used flex basis is content or depends on its
+ // available space, the available main size is infinite, and the flex item’s
+ // inline axis is parallel to the main axis, lay the item out using the rules
+ // for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
+ // is the item’s max-content main size.
+
+ // TODO if/when vertical writing modes are supported
+
+ // If the item has an aspect ratio and a definite cross size then the flex base size
+ // is calculated by transferring that cross size through the aspect ratio (case B
+ // above), and is therefore definite.
+ if child_cross_size_is_definite {
+ if let (Some(ratio), Some(cross)) = (child.aspect_ratio, child_known_dimensions.cross(dir)) {
+ child.flex_basis_is_definite = true;
+ break 'flex_basis if dir.is_row() { cross * ratio } else { cross / ratio };
+ }
+ }
+
+ // 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.
+
+ let child_available_space = Size::MAX_CONTENT
+ .with_main(
+ dir,
+ keyword_main_available_space.unwrap_or(
+ // Map AvailableSpace::Definite to AvailableSpace::MaxContent
+ if available_space.main(dir) == AvailableSpace::MinContent {
+ AvailableSpace::MinContent
+ } else {
+ AvailableSpace::MaxContent
+ },
+ ),
+ )
+ .with_cross(dir, cross_axis_available_space);
+
+ debug_log!("COMPUTE CHILD BASE SIZE:");
+ break 'flex_basis tree.measure_child_size(
+ child.node,
+ child_known_dimensions,
+ child_parent_size,
+ child_available_space,
+ SizingMode::ContentSize,
+ dir.main_axis(),
+ Line::FALSE,
+ );
+ };
+
+ // Floor flex-basis by the padding_border_sum (floors inner_flex_basis at zero)
+ // This seems to be in violation of the spec which explicitly states that the content box should not be floored at zero
+ // (like it usually is) when calculating the flex-basis. But including this matches both Chrome and Firefox's behaviour.
+ //
+ // TODO: resolve spec violation
+ // Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
+ // Spec: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
+ let padding_border_sum = child.padding.main_axis_sum(constants.dir) + child.border.main_axis_sum(constants.dir);
+ child.flex_basis = child.flex_basis.max(padding_border_sum);
+
+ // 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).
+
+ child.inner_flex_basis =
+ child.flex_basis - child.padding.main_axis_sum(constants.dir) - child.border.main_axis_sum(constants.dir);
+
+ let padding_border_axes_sums = (child.padding + child.border).sum_axes().map(Some);
+
+ // Note that it is important that the `parent_size` parameter in the main axis is not set for this
+ // function call as it used for resolving percentages, and percentage size in an axis should not contribute
+ // to a min-content contribution in that same axis. However the `parent_size` and `available_space` *should*
+ // be set to their usual values in the cross axis so that wrapping content can wrap correctly.
+ //
+ // See https://drafts.csswg.org/css-sizing-3/#min-percentage-contribution
+ let style_min_main_size =
+ child.min_size.or(child.overflow.map(Overflow::maybe_into_automatic_min_size).into()).main(dir);
+
+ child.resolved_minimum_main_size = style_min_main_size.unwrap_or_else(|| {
+ let min_content_main_size = {
+ let child_available_space = Size::MIN_CONTENT.with_cross(dir, cross_axis_available_space);
+
+ debug_log!("COMPUTE CHILD MIN SIZE:");
+ tree.measure_child_size(
+ child.node,
+ child_known_dimensions,
+ child_parent_size,
+ child_available_space,
+ SizingMode::ContentSize,
+ dir.main_axis(),
+ Line::FALSE,
+ )
+ };
+
+ // 4.5. Automatic Minimum Size of Flex Items
+ // https://www.w3.org/TR/css-flexbox-1/#min-size-auto
+ let clamped_min_content_size =
+ min_content_main_size.maybe_min(child.size.main(dir)).maybe_min(transferred_max_size.main(dir));
+ clamped_min_content_size.maybe_max(padding_border_axes_sums.main(dir))
+ });
+
+ // Sizes transferred through the aspect ratio clamp the hypothetical main size,
+ // but do not participate in resolving flexible lengths or clamping the final size.
+ // https://github.com/w3c/csswg-drafts/issues/10997
+ let hypothetical_inner_min_main = child
+ .resolved_minimum_main_size
+ .maybe_max(transferred_min_size.main(constants.dir))
+ .maybe_max(padding_border_axes_sums.main(constants.dir));
+ let hypothetical_inner_size =
+ child.flex_basis.maybe_clamp(Some(hypothetical_inner_min_main), transferred_max_size.main(constants.dir));
+ let hypothetical_outer_size = hypothetical_inner_size + child.margin.main_axis_sum(constants.dir);
+
+ child.hypothetical_inner_size.set_main(constants.dir, hypothetical_inner_size);
+ child.hypothetical_outer_size.set_main(constants.dir, hypothetical_outer_size);
+ }
+}
+
+/// raea: how far a line's items may overflow its container and still fit on the line: Chrome's layout unit, 1/64 px.
+/// Chrome lays out in whole 1/64 px units, so items whose sizes and gaps add up to the container's width stay on one
+/// line; in f32 the sum can come out a few ulps over it (3 × 183.6 + 2 × 54 against 658.8), which wrapped the last
+/// item onto a line of its own (raea #252)
+const LINE_FIT_TOLERANCE: f32 = 1.0 / 64.0;
+
+/// 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>(
+ constants: &AlgoConstants,
+ available_space: Size<AvailableSpace>,
+ flex_items: &'a mut Vec<FlexItem>,
+) -> Vec<FlexLine<'a>> {
+ // Wrapping into multiple lines requires a definite main size. If the container's known main size
+ // is derived from its own content (and is thus indefinite) then all items are collected into a
+ // single flex line, matching how the container was sized under a min/max-content constraint.
+ if !constants.is_wrap || !constants.known_main_size_is_definite {
+ let mut lines = new_vec_with_capacity(1);
+ lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
+ lines
+ } else {
+ let main_axis_available_space = match constants.max_size.main(constants.dir) {
+ Some(max_size) => AvailableSpace::Definite({
+ let available = available_space.main(constants.dir).into_option().unwrap_or(max_size);
+ // If the container's main size is not definite then it is at most the max main size,
+ // so the max size (and not the available space) is the limit that items wrap against.
+ let available = if constants.has_definite_main_size { available } else { available.min(max_size) };
+ available.maybe_max(constants.min_size.main(constants.dir))
+ }),
+ // A column container's automatic main size is content-based, so definite available space
+ // handed down by an ancestor does not constrain where its lines wrap. Automatic widths
+ // resolve against available space, so rows do wrap against it.
+ None if !constants.dir.is_row()
+ && !constants.has_definite_main_size
+ && available_space.main(constants.dir).is_definite() =>
+ {
+ AvailableSpace::MaxContent
+ }
+ None => available_space.main(constants.dir),
+ };
+
+ match main_axis_available_space {
+ // If we're sizing under a max-content constraint then the flex items will never wrap
+ // (at least for now - future extensions to the CSS spec may add provisions for forced wrap points)
+ AvailableSpace::MaxContent => {
+ let mut lines = new_vec_with_capacity(1);
+ lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
+ lines
+ }
+ // If flex-wrap is Wrap and we're sizing under a min-content constraint, then we take every possible wrapping opportunity
+ // and place each item in it's own line
+ AvailableSpace::MinContent => {
+ let mut lines = new_vec_with_capacity(flex_items.len());
+ let mut items = &mut flex_items[..];
+ while !items.is_empty() {
+ let (line_items, rest) = items.split_at_mut(1);
+ lines.push(FlexLine { items: line_items, cross_size: 0.0, offset_cross: 0.0 });
+ items = rest;
+ }
+ lines
+ }
+ AvailableSpace::Definite(main_axis_available_space) => {
+ let mut lines = new_vec_with_capacity(1);
+ let mut flex_items = &mut flex_items[..];
+ let main_axis_gap = constants.gap.main(constants.dir);
+
+ while !flex_items.is_empty() {
+ // Find index of the first item in the next line
+ // (or the last item if all remaining items are in the current line)
+ let mut line_length = 0.0;
+ let index = flex_items
+ .iter()
+ .enumerate()
+ .find(|&(idx, child)| {
+ // Gaps only occur between items (not before the first one or after the last one)
+ // So first item in the line does not contribute a gap to the line length
+ let gap_contribution = if idx == 0 { 0.0 } else { main_axis_gap };
+ line_length += child.hypothetical_outer_size.main(constants.dir) + gap_contribution;
+ line_length > main_axis_available_space + LINE_FIT_TOLERANCE && idx != 0
+ })
+ .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;
+ }
+ lines
+ }
+ }
+ }
+}
+
+/// Collect flex items into balanced flex lines (`flex-wrap: balance`), such that the largest
+/// line is as small as possible.
+///
+/// See <https://drafts.csswg.org/css-flexbox-2/#balance-values>
+#[cfg(feature = "flexbox_balance")]
+fn collect_balanced_flex_lines<'a>(
+ constants: &AlgoConstants,
+ available_space: Size<AvailableSpace>,
+ flex_items: &'a mut [FlexItem],
+) -> Vec<FlexLine<'a>> {
+ if flex_items.is_empty() {
+ return new_vec_with_capacity(0);
+ }
+
+ // If the container's known main size is derived from its own content (and is thus indefinite)
+ // then items are balanced without a size limit, matching how the container was sized under a
+ // min/max-content constraint.
+ let main_axis_available_space = if constants.known_main_size_is_definite {
+ match constants.max_size.main(constants.dir) {
+ Some(max_size) => AvailableSpace::Definite({
+ let available = available_space.main(constants.dir).into_option().unwrap_or(max_size);
+ // If the container's main size is not definite then it is at most the max main size,
+ // so the max size (and not the available space) is the limit that items wrap against.
+ let available = if constants.has_definite_main_size { available } else { available.min(max_size) };
+ available.maybe_max(constants.min_size.main(constants.dir))
+ }),
+ // A column container's automatic main size is content-based, so definite available space
+ // handed down by an ancestor does not constrain where its lines wrap. Automatic widths
+ // resolve against available space, so rows do wrap against it.
+ None if !constants.dir.is_row()
+ && !constants.has_definite_main_size
+ && available_space.main(constants.dir).is_definite() =>
+ {
+ AvailableSpace::MaxContent
+ }
+ None => available_space.main(constants.dir),
+ }
+ } else {
+ AvailableSpace::MaxContent
+ };
+
+ // If we're sizing under a min-content constraint then we take every possible wrapping
+ // opportunity and place each item in its own line, the same as greedy wrapping (the
+ // min-content main size of a multi-line container is the size of its largest item)
+ if main_axis_available_space == AvailableSpace::MinContent {
+ let mut lines = new_vec_with_capacity(flex_items.len());
+ let mut items = &mut flex_items[..];
+ while !items.is_empty() {
+ let (line_items, rest) = items.split_at_mut(1);
+ lines.push(FlexLine { items: line_items, cross_size: 0.0, offset_cross: 0.0 });
+ items = rest;
+ }
+ return lines;
+ }
+
+ // raea: with the same tolerance as greedy wrapping's (LINE_FIT_TOLERANCE, raea #252)
+ let line_break_size = main_axis_available_space.into_option().unwrap_or(f32::INFINITY) + LINE_FIT_TOLERANCE;
+ let min_line_count = constants.line_count.unwrap_or(1) as usize;
+ let item_counts = balance::balanced_line_item_counts(
+ flex_items.iter().map(|item| item.hypothetical_outer_size.main(constants.dir)),
+ line_break_size,
+ constants.gap.main(constants.dir),
+ min_line_count,
+ );
+
+ let mut lines = new_vec_with_capacity(item_counts.len());
+ let mut items = &mut flex_items[..];
+ for count in item_counts {
+ let (line_items, rest) = items.split_at_mut(count);
+ lines.push(FlexLine { items: line_items, cross_size: 0.0, offset_cross: 0.0 });
+ items = rest;
+ }
+ debug_assert!(items.is_empty());
+ lines
+}
+
+/// Compute whether each of an item's known dimensions should be treated as definite when performing
+/// layout on the item. An item's post-flexing main size is only treated as definite if the container
+/// has a definite main size or the item's used flex basis is definite.
+/// See <https://www.w3.org/TR/css-flexbox-1/#definite-sizes>
+#[inline]
+fn item_known_dimension_definiteness(constants: &AlgoConstants, item: &FlexItem) -> Size<bool> {
+ let dir = constants.dir;
+ let main_is_definite = constants.has_definite_main_size || item.flex_basis_is_definite;
+
+ // An item's cross size is definite if it is stretched (it stretches to the flex line, whose
+ // size is known by the time the item's final layout is performed), or if its cross size style
+ // resolved to a definite size. Additionally, a non-stretched item's cross *width* is fit-content
+ // sized, and a size resolved by fit-content sizing against definite available space is itself
+ // definite (<https://www.w3.org/TR/css-sizing-3/#definite>). The same does not apply to cross
+ // heights, which are content-based and therefore indefinite when not stretched.
+
+ let has_cross_auto_margins = item.margin_is_auto.cross_start(dir) || item.margin_is_auto.cross_end(dir);
+ let cross_size = item.size_style.cross(dir);
+ let is_stretched = !has_cross_auto_margins
+ && (cross_size.is_stretch() || (item.align_self == AlignSelf::STRETCH && cross_size.is_auto()));
+ let cross_is_definite = is_stretched
+ || item.size.cross(dir).is_some()
+ || (!dir.is_row() && constants.cross_axis_available_space_is_definite);
+
+ Size { width: true, height: true }.with_main(dir, main_is_definite).with_cross(dir, cross_is_definite)
+}
+
+/// Determine the container's main size (if not already known)
+fn determine_container_main_size(
+ tree: &mut impl LayoutFlexboxContainer,
+ available_space: Size<AvailableSpace>,
+ lines: &mut [FlexLine<'_>],
+ constants: &mut AlgoConstants,
+) {
+ let dir = constants.dir;
+ let main_content_box_inset = constants.content_box_inset.main_axis_sum(constants.dir);
+
+ let outer_main_size: f32 = constants.node_outer_size.main(constants.dir).unwrap_or_else(|| {
+ match available_space.main(dir) {
+ AvailableSpace::Definite(main_axis_available_space) => {
+ let main_axis_gap = constants.gap.main(constants.dir);
+ let item_main_length = |child: &FlexItem| {
+ let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
+ (child.flex_basis.maybe_max(child.min_size.main(constants.dir))
+ + child.margin.main_axis_sum(constants.dir))
+ .max(padding_border_sum)
+ };
+ let longest_line_length: f32 = lines
+ .iter()
+ .map(|line| {
+ let line_main_axis_gap = sum_axis_gaps(main_axis_gap, line.items.len());
+ let total_target_size = line.items.iter().map(item_main_length).sum::<f32>();
+ total_target_size + line_main_axis_gap
+ })
+ .max_by(|a, b| a.total_cmp(b))
+ .unwrap_or(0.0);
+ let size = longest_line_length + main_content_box_inset;
+
+ // A balanced container can produce multiple lines that all fit within the
+ // available space (via `flex-line-count`), in which case fit-content sizing
+ // uses its max-content size: the longest line when items are balanced across
+ // the minimum line count without a size limit.
+ #[cfg(feature = "flexbox_balance")]
+ if constants.is_balance {
+ let min_line_count = constants.line_count.unwrap_or(1);
+ let item_count = lines.iter().map(|line| line.items.len()).sum::<usize>();
+ if item_count == 0 {
+ return size;
+ }
+ let mut item_lengths: Vec<f32> = new_vec_with_capacity(item_count);
+ for line in lines.iter() {
+ for child in line.items.iter() {
+ item_lengths.push(item_main_length(child));
+ }
+ }
+ let item_counts = balance::balanced_line_item_counts(
+ item_lengths.iter().copied(),
+ f32::INFINITY,
+ main_axis_gap,
+ min_line_count.max(1) as usize,
+ );
+ let mut widest_line_length: f32 = 0.0;
+ let mut index = 0;
+ for count in item_counts {
+ let line_length: f32 = item_lengths[index..index + count].iter().sum::<f32>()
+ + sum_axis_gaps(main_axis_gap, count);
+ widest_line_length = widest_line_length.max(line_length);
+ index += count;
+ }
+ let max_content_size = widest_line_length + main_content_box_inset;
+ return f32_max(size, f32_min(max_content_size, main_axis_available_space));
+ }
+
+ if lines.len() > 1 {
+ f32_max(size, main_axis_available_space)
+ } else {
+ size
+ }
+ }
+ AvailableSpace::MinContent if constants.is_wrap => {
+ let longest_line_length: f32 = lines
+ .iter()
+ .map(|line| {
+ let line_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
+ let total_target_size = line
+ .items
+ .iter()
+ .map(|child| {
+ let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
+ (child.flex_basis.maybe_max(child.min_size.main(constants.dir))
+ + child.margin.main_axis_sum(constants.dir))
+ .max(padding_border_sum)
+ })
+ .sum::<f32>();
+ total_target_size + line_main_axis_gap
+ })
+ .max_by(|a, b| a.total_cmp(b))
+ .unwrap_or(0.0);
+ longest_line_length + main_content_box_inset
+ }
+ AvailableSpace::MinContent | AvailableSpace::MaxContent => {
+ // Define a base main_size variable. This is mutated once for iteration over the outer
+ // loop over the flex lines as:
+ // "The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line."
+ let mut main_size = 0.0;
+
+ for line in lines.iter_mut() {
+ for item in line.items.iter_mut() {
+ let style_min = item.min_size.main(constants.dir);
+ let style_preferred = item.size.main(constants.dir);
+ let style_max = item.max_size.main(constants.dir);
+
+ // The spec seems a bit unclear on this point (my initial reading was that the `.maybe_max(style_preferred)` should
+ // not be included here), however for row containers this matches both Chrome and Firefox as of 9th March 2023.
+ // For column containers the flex base size alone is the clamping basis (as the spec says): a column item's
+ // `height` must not inflate the container's max-content size beyond the item's flex-basis.
+ //
+ // Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
+ // Spec modification: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
+ // Issue: https://github.com/w3c/csswg-drafts/issues/1435
+ // Gentest: padding_border_overrides_size_flex_basis_0.html
+ // Gentest: blockflex_min_content_ignores_own_height_as_percentage_basis.html
+ let clamping_basis = if constants.is_row {
+ Some(item.flex_basis).maybe_max(style_preferred)
+ } else {
+ Some(item.flex_basis)
+ };
+ let flex_basis_min = clamping_basis.filter(|_| item.flex_shrink == 0.0);
+ let flex_basis_max = clamping_basis.filter(|_| item.flex_grow == 0.0);
+
+ let min_main_size = style_min
+ .maybe_max(flex_basis_min)
+ .or(flex_basis_min)
+ .unwrap_or(item.resolved_minimum_main_size)
+ .max(item.resolved_minimum_main_size);
+ let max_main_size =
+ style_max.maybe_min(flex_basis_max).or(flex_basis_max).unwrap_or(f32::INFINITY);
+
+ let content_contribution = match (min_main_size, style_preferred, max_main_size) {
+ // If the clamping values are such that max <= min, then we can avoid the expensive step of computing the content size
+ // as we know that the clamping values will override it anyway
+ (min, Some(pref), max) if max <= min || max <= pref => {
+ pref.min(max).max(min) + item.margin.main_axis_sum(constants.dir)
+ }
+ (min, _, max) if max <= min => min + item.margin.main_axis_sum(constants.dir),
+
+ // Else compute the min- or -max content size and apply the full formula for computing the
+ // min- or max- content contribution
+ _ if item.is_scroll_container() => {
+ item.flex_basis + item.margin.main_axis_sum(constants.dir)
+ }
+
+ // If the item has a definite preferred main size then that is its content
+ // contribution (an inherent-size measure of the item would return it), floored
+ // by the item's main-axis padding+border, so measuring the item can be skipped.
+ // Min/max clamping is applied in the same way as for measured contributions.
+ (_, Some(pref), _) => {
+ let item_pb_main = item.padding.main_axis_sum(constants.dir)
+ + item.border.main_axis_sum(constants.dir);
+ let inner_main_size = pref.max(item_pb_main);
+ if constants.is_row {
+ (inner_main_size + item.margin.main_axis_sum(constants.dir))
+ .maybe_clamp(style_min, style_max)
+ } else {
+ (inner_main_size.max(item.flex_basis) + item.margin.main_axis_sum(constants.dir))
+ .maybe_clamp(style_min, style_max)
+ }
+ }
+
+ _ => {
+ // Parent size for child sizing
+ let cross_axis_parent_size = constants.node_inner_size.cross(dir);
+
+ // Available space for child sizing (excluding the child's margins)
+ let child_min_cross = item.min_size.cross(dir);
+ let child_max_cross = item.max_size.cross(dir);
+ let cross_axis_available_space: AvailableSpace = available_space
+ .cross(dir)
+ .map_definite_value(|val| {
+ (constants.divided_cross_space(cross_axis_parent_size.unwrap_or(val))
+ - item.margin.cross_axis_sum(dir))
+ .max(0.0)
+ })
+ .maybe_clamp(child_min_cross, child_max_cross);
+
+ let child_available_space = available_space.with_cross(dir, cross_axis_available_space);
+
+ // Known dimensions for child sizing
+ let child_known_dimensions = {
+ let mut ckd = item.size.with_main(dir, None);
+ // Clamp the definite cross size by the cross min/max sizes, as
+ // `determine_flex_base_size` does: an item measured wider than its
+ // max-width wraps onto fewer lines and under-reports its height.
+ let transferred_min_size =
+ item.min_size.maybe_apply_aspect_ratio(item.aspect_ratio);
+ let transferred_max_size =
+ item.max_size.maybe_apply_aspect_ratio(item.aspect_ratio);
+ ckd.set_cross(
+ dir,
+ ckd.cross(dir).maybe_clamp(
+ transferred_min_size.cross(dir),
+ transferred_max_size.cross(dir),
+ ),
+ );
+ if item.align_self == AlignSelf::STRETCH && ckd.cross(dir).is_none() {
+ ckd.set_cross(dir, cross_axis_available_space.into_option());
+ }
+ ckd
+ };
+
+ // Either the min- or max- content size depending on which constraint we are sizing under.
+ // TODO: Optimise by using already computed values where available
+ debug_log!("COMPUTE CHILD BASE SIZE (for intrinsic main size):");
+ let measured_main_size = tree.measure_child_size(
+ item.node,
+ child_known_dimensions,
+ constants.node_inner_size,
+ child_available_space,
+ SizingMode::ContentSize,
+ dir.main_axis(),
+ Line::FALSE,
+ );
+
+ // A known cross size is transferred through the item's aspect-ratio
+ // and floors the measured content size
+ let transferred_main_size = item
+ .aspect_ratio
+ .zip(child_known_dimensions.cross(dir))
+ .map(|(ratio, cross)| if constants.is_row { cross * ratio } else { cross / ratio });
+
+ let inner_main_size = measured_main_size.maybe_max(transferred_main_size);
+
+ // This is somewhat bizarre in that it's asymmetrical depending whether the flex container is a column or a row.
+ //
+ // I *think* this might relate to https://drafts.csswg.org/css-flexbox-1/#algo-main-container:
+ //
+ // "The automatic block size of a block-level flex container is its max-content size."
+ //
+ // Which could suggest that flex-basis defining a vertical size does not shrink because it is in the block axis, and the automatic size
+ // in the block axis is a MAX content size. Whereas a flex-basis defining a horizontal size does shrink because the automatic size in
+ // inline axis is MIN content size (although I don't have a reference for that).
+ //
+ // Ultimately, this was not found by reading the spec, but by trial and error fixing tests to align with Webkit/Firefox output.
+ // (see the `flex_basis_unconstraint_row` and `flex_basis_uncontraint_column` generated tests which demonstrate this)
+ if constants.is_row {
+ (inner_main_size + item.margin.main_axis_sum(constants.dir))
+ .maybe_clamp(style_min, style_max)
+ } else {
+ (inner_main_size.max(item.flex_basis) + item.margin.main_axis_sum(constants.dir))
+ .maybe_clamp(style_min, style_max)
+ }
+ }
+ };
+ item.content_flex_fraction = {
+ let diff = content_contribution - item.flex_basis;
+ if diff > 0.0 {
+ diff / f32_max(1.0, item.flex_grow)
+ } else if diff < 0.0 {
+ let scaled_shrink_factor = f32_max(1.0, item.flex_shrink) * item.inner_flex_basis;
+ diff / scaled_shrink_factor
+ } else {
+ // We are assuming that diff is 0.0 here and that we haven't accidentally introduced a NaN
+ 0.0
+ }
+ };
+ }
+
+ // TODO Spec says to scale everything by the line's max flex fraction. But neither Chrome nor firefox implement this
+ // so we don't either. But if we did want to, we'd need this computation here (and to use it below):
+ //
+ // Within each line, find the largest max-content flex fraction among all the flex items.
+ // let line_flex_fraction = line
+ // .items
+ // .iter()
+ // .map(|item| item.content_flex_fraction)
+ // .max_by(|a, b| a.total_cmp(b))
+ // .unwrap_or(0.0); // Unwrap case never gets hit because there is always at least one item a line
+
+ // Add each item’s flex base size to the product of:
+ // - its flex grow factor (or scaled flex shrink factor,if the chosen max-content flex fraction was negative)
+ // - the chosen max-content flex fraction
+ // then clamp that result by the max main size floored by the min main size.
+ //
+ // The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line.
+ let item_main_size_sum = line
+ .items
+ .iter_mut()
+ .map(|item| {
+ let flex_fraction = item.content_flex_fraction;
+ // let flex_fraction = line_flex_fraction;
+
+ let flex_contribution = if item.content_flex_fraction > 0.0 {
+ f32_max(1.0, item.flex_grow) * flex_fraction
+ } else if item.content_flex_fraction < 0.0 {
+ let scaled_shrink_factor = f32_max(1.0, item.flex_shrink) * item.inner_flex_basis;
+ if scaled_shrink_factor == 0.0 {
+ 0.0
+ } else {
+ scaled_shrink_factor * flex_fraction
+ }
+ } else {
+ 0.0
+ };
+ let size = item.flex_basis + flex_contribution;
+ item.outer_target_size.set_main(constants.dir, size);
+ item.target_size.set_main(constants.dir, size);
+ size
+ })
+ .sum::<f32>();
+
+ let gap_sum = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
+ main_size = f32_max(main_size, item_main_size_sum + gap_sum)
+ }
+
+ main_size + main_content_box_inset
+ }
+ }
+ });
+
+ let outer_main_size = outer_main_size
+ .maybe_clamp(constants.min_size.main(constants.dir), constants.max_size.main(constants.dir))
+ .max(main_content_box_inset - constants.scrollbar_gutter.main(constants.dir));
+
+ // let outer_main_size = inner_main_size + constants.padding_border.main_axis_sum(constants.dir);
+ let inner_main_size = f32_max(outer_main_size - main_content_box_inset, 0.0);
+ constants.container_size.set_main(constants.dir, outer_main_size);
+ constants.inner_container_size.set_main(constants.dir, inner_main_size);
+ constants.node_inner_size.set_main(constants.dir, Some(inner_main_size));
+}
+
+/// Resolve the flexible lengths of the items within a flex line.
+/// Sets the `main` component of each item's `target_size` and `outer_target_size`
+///
+/// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
+#[inline]
+fn resolve_flexible_lengths(line: &mut FlexLine, constants: &AlgoConstants) {
+ let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
+
+ // 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 total_hypothetical_outer_main_size =
+ line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum::<f32>();
+ let used_flex_factor: f32 = total_main_axis_gap + total_hypothetical_outer_main_size;
+ let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
+ let shrinking = used_flex_factor > constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
+ let exactly_sized = !growing & !shrinking;
+
+ // 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() {
+ let inner_target_size = child.hypothetical_inner_size.main(constants.dir);
+ child.target_size.set_main(constants.dir, inner_target_size);
+
+ if exactly_sized
+ || (child.flex_grow == 0.0 && child.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;
+ let outer_target_size = inner_target_size + child.margin.main_axis_sum(constants.dir);
+ child.outer_target_size.set_main(constants.dir, outer_target_size);
+ }
+ }
+
+ if exactly_sized {
+ return;
+ }
+
+ // 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.
+
+ let used_space: f32 = total_main_axis_gap
+ + line
+ .items
+ .iter()
+ .map(|child| {
+ if child.frozen {
+ child.outer_target_size.main(constants.dir)
+ } else {
+ child.flex_basis + child.margin.main_axis_sum(constants.dir)
+ }
+ })
+ .sum::<f32>();
+
+ let initial_free_space = constants.node_inner_size.main(constants.dir).maybe_sub(used_space).unwrap_or(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 = total_main_axis_gap
+ + line
+ .items
+ .iter()
+ .map(|child| {
+ if child.frozen {
+ child.outer_target_size.main(constants.dir)
+ } else {
+ child.flex_basis + child.margin.main_axis_sum(constants.dir)
+ }
+ })
+ .sum::<f32>();
+
+ let mut unfrozen: 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| {
+ (flex_grow + item.flex_grow, flex_shrink + item.flex_shrink)
+ });
+
+ let free_space = if growing && sum_flex_grow < 1.0 {
+ (initial_free_space * sum_flex_grow - total_main_axis_gap)
+ .maybe_min(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
+ } else if shrinking && sum_flex_shrink < 1.0 {
+ (initial_free_space * sum_flex_shrink - total_main_axis_gap)
+ .maybe_max(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
+ } else {
+ (constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
+ .unwrap_or(used_flex_factor - used_space)
+ };
+
+ // 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 * (child.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 * child.flex_shrink).sum();
+
+ if sum_scaled_shrink_factor > 0.0 {
+ for child in &mut unfrozen {
+ let scaled_shrink_factor = child.inner_flex_basis * child.flex_shrink;
+ child.target_size.set_main(
+ 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 {
+ let resolved_min_main: Option<f32> = child.resolved_minimum_main_size.into();
+ let max_main = child.max_size.main(constants.dir);
+ let clamped = child.target_size.main(constants.dir).maybe_clamp(resolved_min_main, max_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_axis_sum(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,
+ }
+ }
+
+ // f. Return to the start of this loop.
+ }
+}
+
+/// 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(
+ tree: &mut impl LayoutFlexboxContainer,
+ line: &mut FlexLine,
+ constants: &AlgoConstants,
+ available_space: Size<AvailableSpace>,
+) {
+ for child in line.items.iter_mut() {
+ let padding_border_sum = (child.padding + child.border).cross_axis_sum(constants.dir);
+
+ // The available space passed to the child excludes the child's margins
+ let child_available_main =
+ (constants.container_size.main(constants.dir) - child.margin.main_axis_sum(constants.dir)).max(0.0).into();
+
+ // Sizes transferred through the aspect ratio clamp the hypothetical cross size
+ // https://github.com/w3c/csswg-drafts/issues/10997
+ let transferred_min_cross = child.min_size.maybe_apply_aspect_ratio(child.aspect_ratio).cross(constants.dir);
+ let transferred_max_cross = child.max_size.maybe_apply_aspect_ratio(child.aspect_ratio).cross(constants.dir);
+
+ let child_cross = child
+ .size
+ .cross(constants.dir)
+ .maybe_clamp(transferred_min_cross, transferred_max_cross)
+ .maybe_max(padding_border_sum);
+
+ let child_available_cross = available_space
+ .cross(constants.dir)
+ .map_definite_value(|val| {
+ (constants.divided_cross_space(val) - child.margin.cross_axis_sum(constants.dir)).max(0.0)
+ })
+ .maybe_clamp(transferred_min_cross, transferred_max_cross)
+ .maybe_max(padding_border_sum);
+
+ // A cross size that is a sizing keyword (min-content, max-content, fit-content,
+ // fit-content(...)) determines the available space constraint the item is measured under.
+ // The `stretch` keyword is not resolved here: it stretches to the flex line, which is
+ // handled in `determine_used_cross_size`
+ let cross_stretch_size = constants
+ .node_inner_size
+ .cross(constants.dir)
+ .map(|val| constants.divided_cross_space(val))
+ .maybe_sub(child.margin.cross_axis_sum(constants.dir))
+ .maybe_max(0.0);
+ let child_available_cross = match resolve_sizing_keyword(
+ child.size_style.cross(constants.dir),
+ cross_stretch_size,
+ constants.node_inner_size.cross(constants.dir),
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Measure(available)) => available,
+ _ => child_available_cross,
+ };
+
+ let child_inner_cross = child_cross.unwrap_or_else(|| {
+ tree.compute_child_layout(
+ child.node,
+ LayoutInput {
+ run_mode: RunMode::ComputeSize,
+ sizing_mode: SizingMode::ContentSize,
+ axis: constants.dir.cross_axis().into(),
+ known_dimensions: 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() },
+ },
+ known_dimensions_are_definite: item_known_dimension_definiteness(constants, child),
+ parent_size: constants.node_inner_size,
+ available_space: Size {
+ width: if constants.is_row { child_available_main } else { child_available_cross },
+ height: if constants.is_row { child_available_cross } else { child_available_main },
+ },
+ vertical_margins_are_collapsible: Line::FALSE,
+ },
+ )
+ .size
+ .get_abs(constants.dir.cross_axis())
+ .maybe_clamp(transferred_min_cross, transferred_max_cross)
+ .max(padding_border_sum)
+ });
+ let child_outer_cross = child_inner_cross + child.margin.cross_axis_sum(constants.dir);
+
+ child.hypothetical_inner_size.set_cross(constants.dir, child_inner_cross);
+ child.hypothetical_outer_size.set_cross(constants.dir, child_outer_cross);
+ }
+}
+
+/// Calculate the base lines of the children.
+#[inline]
+fn calculate_children_base_lines(
+ tree: &mut impl LayoutFlexboxContainer,
+ node_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+ flex_lines: &mut [FlexLine],
+ constants: &AlgoConstants,
+) {
+ // Only compute baselines for flex rows because we only support baseline alignment in the cross axis
+ // where that axis is also the inline axis
+ // TODO: this may need revisiting if/when we support vertical writing modes
+ if !constants.is_row {
+ return;
+ }
+
+ for line in flex_lines {
+ // If a flex line has one or zero items participating in baseline alignment then baseline alignment is a no-op so we skip
+ let line_baseline_child_count =
+ line.items.iter().filter(|child| child.participates_in_baseline_alignment(constants.dir)).count();
+ if line_baseline_child_count <= 1 {
+ continue;
+ }
+
+ for child in line.items.iter_mut() {
+ // Only calculate baselines for children participating in baseline alignment
+ if !child.participates_in_baseline_alignment(constants.dir) {
+ continue;
+ }
+
+ let measured_size_and_baselines = tree.compute_child_layout(
+ child.node,
+ LayoutInput {
+ run_mode: RunMode::PerformLayout,
+ sizing_mode: SizingMode::ContentSize,
+ axis: RequestedAxis::Both,
+ known_dimensions: Size {
+ width: if constants.is_row {
+ child.target_size.width.into()
+ } else {
+ child.hypothetical_inner_size.width.into()
+ },
+ height: if constants.is_row {
+ child.hypothetical_inner_size.height.into()
+ } else {
+ child.target_size.height.into()
+ },
+ },
+ known_dimensions_are_definite: item_known_dimension_definiteness(constants, child),
+ parent_size: constants.node_inner_size,
+ // The available space passed to the child excludes the child's margins
+ available_space: Size {
+ width: if constants.is_row {
+ constants.container_size.width.into()
+ } else {
+ available_space.width.maybe_set(node_size.width)
+ },
+ height: if constants.is_row {
+ available_space.height.maybe_set(node_size.height)
+ } else {
+ constants.container_size.height.into()
+ },
+ }
+ .maybe_sub(child.margin.sum_axes())
+ .maybe_max(Size::ZERO),
+ vertical_margins_are_collapsible: Line::FALSE,
+ },
+ );
+
+ let baseline = measured_size_and_baselines.baselines.first;
+ let height = measured_size_and_baselines.size.height;
+
+ // Scroll containers' baselines are determined from their content as if scrolled to the
+ // initial position, but are additionally clamped to their border box.
+ // See https://github.com/w3c/csswg-drafts/issues/7660
+ let baseline = if child.overflow.y.is_scroll_container() {
+ baseline.unwrap_or(height).min(height).max(0.0)
+ } else {
+ baseline.unwrap_or(height)
+ };
+
+ child.baseline = baseline + child.margin.top;
+ }
+ }
+}
+
+/// 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).
+#[inline]
+fn calculate_cross_size(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
+ // 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.
+ if !constants.is_wrap && node_size.cross(constants.dir).is_some() {
+ let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
+ let cross_min_size = constants.min_size.cross(constants.dir);
+ let cross_max_size = constants.max_size.cross(constants.dir);
+ flex_lines[0].cross_size = node_size
+ .cross(constants.dir)
+ .maybe_clamp(cross_min_size, cross_max_size)
+ .maybe_sub(cross_axis_padding_border)
+ .maybe_max(0.0)
+ .unwrap_or(0.0);
+ } else {
+ // 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.
+ for line in flex_lines.iter_mut() {
+ let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
+ line.cross_size = line
+ .items
+ .iter()
+ .map(|child| {
+ if child.participates_in_baseline_alignment(constants.dir) {
+ max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
+ } else {
+ child.hypothetical_outer_size.cross(constants.dir)
+ }
+ })
+ .fold(0.0, |acc, x| acc.max(x));
+ }
+
+ // 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 !constants.is_wrap {
+ let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
+ let cross_min_size = constants.min_size.cross(constants.dir);
+ let cross_max_size = constants.max_size.cross(constants.dir);
+ flex_lines[0].cross_size = flex_lines[0].cross_size.maybe_clamp(
+ cross_min_size.maybe_sub(cross_axis_padding_border),
+ cross_max_size.maybe_sub(cross_axis_padding_border),
+ );
+ }
+ }
+}
+
+/// 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(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
+ if constants.align_content == AlignContent::STRETCH {
+ let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
+ let cross_min_size = constants.min_size.cross(constants.dir);
+ let cross_max_size = constants.max_size.cross(constants.dir);
+ let container_min_inner_cross = node_size
+ .cross(constants.dir)
+ .or(cross_min_size)
+ .maybe_clamp(cross_min_size, cross_max_size)
+ .maybe_sub(cross_axis_padding_border)
+ .maybe_max(0.0)
+ .unwrap_or(0.0);
+
+ let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
+ let lines_total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>() + total_cross_axis_gap;
+
+ if lines_total_cross < container_min_inner_cross {
+ let remaining = container_min_inner_cross - lines_total_cross;
+ let addition = remaining / flex_lines.len() as f32;
+ flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
+ }
+ }
+}
+
+/// 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(
+ tree: &impl LayoutFlexboxContainer,
+ flex_lines: &mut [FlexLine],
+ constants: &AlgoConstants,
+) {
+ for line in flex_lines {
+ let line_cross_size = line.cross_size;
+
+ for child in line.items.iter_mut() {
+ let child_style = tree.get_flexbox_child_style(child.node);
+ // A cross size of `stretch` stretches to the flex line like align-self: stretch
+ // (but regardless of the alignment style)
+ let cross_is_stretch = child.size_style.cross(constants.dir).is_stretch();
+ child.target_size.set_cross(
+ constants.dir,
+ if !child.margin_is_auto.cross_start(constants.dir)
+ && !child.margin_is_auto.cross_end(constants.dir)
+ && (cross_is_stretch
+ || (child.align_self == AlignSelf::STRETCH
+ && child_style.size().cross(constants.dir).is_auto()))
+ {
+ // For some reason this particular usage of max_width is an exception to the rule that max_width's transfer
+ // using the aspect_ratio (if set). Both Chrome and Firefox agree on this. And reading the spec, it seems like
+ // a reasonable interpretation. Although it seems to me that the spec *should* apply aspect_ratio here.
+ // Percentage padding and border resolve against the container's inline size
+ // (its width) on all four sides, not against its height for the top/bottom sides
+ let padding = child_style
+ .padding()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let border = child_style
+ .border()
+ .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
+ let pb_sum = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
+
+ let max_size_ignoring_aspect_ratio = child_style
+ .max_size()
+ .maybe_resolve(constants.node_inner_size, |val, basis| tree.calc(val, basis))
+ .maybe_add(box_sizing_adjustment);
+
+ (line_cross_size - child.margin.cross_axis_sum(constants.dir)).max(0.0).maybe_clamp(
+ child.min_size.cross(constants.dir),
+ max_size_ignoring_aspect_ratio.cross(constants.dir),
+ )
+ } else {
+ child.hypothetical_inner_size.cross(constants.dir)
+ },
+ );
+
+ child.outer_target_size.set_cross(
+ constants.dir,
+ child.target_size.cross(constants.dir) + child.margin.cross_axis_sum(constants.dir),
+ );
+ }
+ }
+}
+
+/// 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(flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
+ for line in flex_lines {
+ let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
+ let used_space: f32 = total_main_axis_gap
+ + line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum::<f32>();
+ let mut free_space = constants.inner_container_size.main(constants.dir) - used_space;
+ let mut num_auto_margins = 0;
+
+ for child in line.items.iter_mut() {
+ if child.margin_is_auto.main_start(constants.dir) {
+ num_auto_margins += 1;
+ }
+ if child.margin_is_auto.main_end(constants.dir) {
+ num_auto_margins += 1;
+ }
+ }
+
+ if free_space > 0.0 && num_auto_margins > 0 {
+ let margin = free_space / num_auto_margins as f32;
+
+ for child in line.items.iter_mut() {
+ if child.margin_is_auto.main_start(constants.dir) {
+ if constants.is_row {
+ child.margin.left = margin;
+ } else {
+ child.margin.top = margin;
+ }
+ }
+ if child.margin_is_auto.main_end(constants.dir) {
+ if constants.is_row {
+ child.margin.right = margin;
+ } else {
+ child.margin.bottom = margin;
+ }
+ }
+ }
+
+ // The auto margins have absorbed all of the free space, leaving none for `justify-content`
+ free_space = 0.0;
+ }
+
+ let num_items = line.items.len();
+ let layout_reverse = constants.dir.is_reverse();
+ let gap = constants.gap.main(constants.dir);
+ let justify_content_mode = apply_alignment_fallback(free_space, num_items, constants.justify_content);
+
+ let justify_item = |(i, child): (usize, &mut FlexItem)| {
+ child.offset_main =
+ compute_alignment_offset(free_space, num_items, gap, justify_content_mode, layout_reverse, i == 0);
+ };
+
+ if layout_reverse {
+ line.items.iter_mut().rev().enumerate().for_each(justify_item);
+ } else {
+ line.items.iter_mut().enumerate().for_each(justify_item);
+ }
+ }
+}
+
+/// 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(flex_lines: &mut [FlexLine], 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));
+ let max_baseline_to_bottom_distance: f32 = line
+ .items
+ .iter_mut()
+ .filter(|child| child.participates_in_baseline_alignment(constants.dir))
+ .map(|child| child.outer_target_size.cross(constants.dir) - 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(constants.dir);
+
+ if child.margin_is_auto.cross_start(constants.dir) && child.margin_is_auto.cross_end(constants.dir) {
+ if constants.is_row {
+ child.margin.top = free_space / 2.0;
+ child.margin.bottom = free_space / 2.0;
+ } else {
+ child.margin.left = free_space / 2.0;
+ child.margin.right = free_space / 2.0;
+ }
+ } else if child.margin_is_auto.cross_start(constants.dir) {
+ if constants.is_row {
+ child.margin.top = free_space;
+ } else {
+ child.margin.left = free_space;
+ }
+ } else if child.margin_is_auto.cross_end(constants.dir) {
+ if constants.is_row {
+ child.margin.bottom = free_space;
+ } else {
+ child.margin.right = free_space;
+ }
+ } else {
+ // 14. Align all flex items along the cross-axis.
+ child.offset_cross = align_flex_items_along_cross_axis(
+ child,
+ free_space,
+ max_baseline,
+ max_baseline_to_bottom_distance,
+ constants,
+ );
+ }
+ }
+ }
+}
+
+/// 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(
+ child: &FlexItem,
+ free_space: f32,
+ max_baseline: f32,
+ max_baseline_to_bottom_distance: f32,
+ constants: &AlgoConstants,
+) -> f32 {
+ let cross_axis_should_reverse = constants.is_column && matches!(constants.layout_direction, Direction::Rtl);
+
+ // If align-self uses a "safe" overflow-position keyword and the item would overflow its
+ // line cross size, fall back to logical Start to avoid data loss. See CSS Box Alignment 3
+ // §4.3 <https://www.w3.org/TR/css-align-3/#overflow-values>. Otherwise, drop the safety
+ // field so the match below operates on a bare keyword and stays exhaustive.
+ let align_keyword = if child.align_self.is_safe() && free_space < 0.0 {
+ AlignItemsKeyword::Start
+ } else {
+ child.align_self.keyword
+ };
+
+ match align_keyword {
+ AlignItemsKeyword::Start => {
+ if cross_axis_should_reverse {
+ free_space
+ } else {
+ 0.0
+ }
+ }
+ AlignItemsKeyword::FlexStart => {
+ if constants.is_wrap_reverse ^ cross_axis_should_reverse {
+ free_space
+ } else {
+ 0.0
+ }
+ }
+ AlignItemsKeyword::End => {
+ if cross_axis_should_reverse {
+ 0.0
+ } else {
+ free_space
+ }
+ }
+ AlignItemsKeyword::FlexEnd => {
+ if constants.is_wrap_reverse ^ cross_axis_should_reverse {
+ 0.0
+ } else {
+ free_space
+ }
+ }
+ AlignItemsKeyword::Center => free_space / 2.0,
+ AlignItemsKeyword::Baseline => {
+ if constants.is_row {
+ if constants.is_wrap_reverse {
+ // In a wrap-reverse container the cross axis is flipped, so the baseline-aligned
+ // group of items is aligned to the cross-start edge, which is the bottom of the line.
+ let line_cross_size = free_space + child.outer_target_size.cross(constants.dir);
+ line_cross_size - max_baseline_to_bottom_distance - child.baseline
+ } else {
+ max_baseline - child.baseline
+ }
+ } else {
+ // Until we support vertical writing modes, baseline alignment only makes sense if
+ // the constants.direction is row, so we treat it as flex-start alignment in columns.
+ let baseline_column_should_reverse = cross_axis_should_reverse && !constants.is_wrap;
+ if constants.is_wrap_reverse ^ baseline_column_should_reverse {
+ free_space
+ } else {
+ 0.0
+ }
+ }
+ }
+ AlignItemsKeyword::Stretch => {
+ if constants.is_wrap_reverse ^ cross_axis_should_reverse {
+ free_space
+ } else {
+ 0.0
+ }
+ }
+ // Normal is resolved to Stretch, and SelfStart/SelfEnd are resolved to Start/End
+ // against the item's own direction when flex items are generated.
+ AlignItemsKeyword::Normal | AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd => unreachable!(),
+ }
+}
+
+/// 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]
+#[must_use]
+fn determine_container_cross_size(
+ flex_lines: &[FlexLine],
+ node_size: Size<Option<f32>>,
+ constants: &mut AlgoConstants,
+) -> f32 {
+ let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
+ let total_line_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>();
+
+ let padding_border_sum = constants.content_box_inset.cross_axis_sum(constants.dir);
+ let cross_scrollbar_gutter = constants.scrollbar_gutter.cross(constants.dir);
+ let min_cross_size = constants.min_size.cross(constants.dir);
+ let max_cross_size = constants.max_size.cross(constants.dir);
+ let outer_container_size = node_size
+ .cross(constants.dir)
+ .unwrap_or(total_line_cross_size + total_cross_axis_gap + padding_border_sum)
+ .maybe_clamp(min_cross_size, max_cross_size)
+ .max(padding_border_sum - cross_scrollbar_gutter);
+ let inner_container_size = f32_max(outer_container_size - padding_border_sum, 0.0);
+
+ constants.container_size.set_cross(constants.dir, outer_container_size);
+ constants.inner_container_size.set_cross(constants.dir, inner_container_size);
+
+ total_line_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(flex_lines: &mut [FlexLine], constants: &AlgoConstants, total_cross_size: f32) {
+ let num_lines = flex_lines.len();
+ let gap = constants.gap.cross(constants.dir);
+ let total_cross_axis_gap = sum_axis_gaps(gap, num_lines);
+ let free_space = constants.inner_container_size.cross(constants.dir) - total_cross_size - total_cross_axis_gap;
+
+ let align_content_mode = apply_alignment_fallback(free_space, num_lines, constants.align_content);
+
+ let align_line = |(i, line): (usize, &mut FlexLine)| {
+ line.offset_cross =
+ compute_alignment_offset(free_space, num_lines, gap, align_content_mode, constants.is_wrap_reverse, i == 0);
+ };
+
+ 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);
+ }
+}
+
+/// Calculates the layout for a flex-item
+#[allow(clippy::too_many_arguments)]
+fn calculate_flex_item(
+ tree: &mut impl LayoutFlexboxContainer,
+ item: &mut FlexItem,
+ total_offset_main: &mut f32,
+ total_offset_cross: f32,
+ line_offset_cross: f32,
+ #[cfg(feature = "content_size")] total_overflow_rect: &mut Rect<f32>,
+ #[cfg(feature = "content_size")] border: Rect<f32>,
+ constants: &AlgoConstants,
+) {
+ let container_size = constants.container_size;
+ let node_inner_size = constants.node_inner_size;
+ let direction = constants.dir;
+ let layout_direction = constants.layout_direction;
+ let item_known_dimension_definiteness = item_known_dimension_definiteness(constants, item);
+ let mut layout_output = tree.compute_child_layout(
+ item.node,
+ LayoutInput {
+ run_mode: RunMode::PerformLayout,
+ sizing_mode: SizingMode::ContentSize,
+ axis: RequestedAxis::Both,
+ known_dimensions: item.target_size.map(|s| s.into()),
+ known_dimensions_are_definite: item_known_dimension_definiteness,
+ parent_size: node_inner_size,
+ // The available space passed to the child excludes the child's margins
+ available_space: (container_size - item.margin.sum_axes()).map(|s| s.max(0.0).into()),
+ vertical_margins_are_collapsible: Line::FALSE,
+ },
+ );
+ let LayoutOutput {
+ size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect,
+ ..
+ } = layout_output;
+
+ let is_rtl_row = direction.is_row() && layout_direction.is_rtl();
+ let is_rtl_column = direction.is_column() && layout_direction.is_rtl();
+ let main_relative_inset = item.relative_inset.main(direction);
+ let cross_relative_inset = item.relative_inset.cross(direction);
+ let effective_line_offset_cross = if is_rtl_column { 0.0 } else { line_offset_cross };
+
+ let offset_main = if is_rtl_row {
+ *total_offset_main - item.offset_main - item.margin.main_end(direction) - main_relative_inset - size.width
+ } else {
+ *total_offset_main + item.offset_main + item.margin.main_start(direction) + main_relative_inset
+ };
+
+ let offset_cross = total_offset_cross
+ + item.offset_cross
+ + effective_line_offset_cross
+ + item.margin.cross_start(direction)
+ + cross_relative_inset;
+
+ if direction.is_row() {
+ let baseline_offset_cross =
+ total_offset_cross + item.offset_cross + effective_line_offset_cross + item.margin.cross_start(direction);
+ // Scroll containers' baselines are determined from their content as if scrolled to the initial
+ // position, but are additionally clamped to their border box.
+ // See https://github.com/w3c/csswg-drafts/issues/7660
+ let inner_baseline = {
+ let baseline = layout_output.baselines.first.unwrap_or(size.height);
+ if item.overflow.y.is_scroll_container() {
+ baseline.min(size.height).max(0.0)
+ } else {
+ baseline
+ }
+ };
+ item.baseline = baseline_offset_cross + inner_baseline;
+ } else {
+ let baseline_offset_main = *total_offset_main + item.offset_main + item.margin.main_start(direction);
+ let inner_baseline = layout_output.baselines.first.unwrap_or(size.height);
+ item.baseline = baseline_offset_main + inner_baseline;
+ }
+
+ let location = if direction.is_row() {
+ Point { x: offset_main, y: offset_cross }
+ } else {
+ Point { x: offset_cross, y: offset_main }
+ };
+ let scrollbar_size = Size {
+ width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
+ height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
+ };
+
+ tree.set_unrounded_layout(
+ item.node,
+ &Layout {
+ order: item.order,
+ size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect,
+ scrollbar_size,
+ location,
+ padding: item.padding,
+ border: item.border,
+ margin: item.margin,
+ },
+ );
+
+ // Keep out-of-flow candidates from the item's subtree, translating anchors from
+ // item-relative to container-relative coordinates
+ item.oof_candidates = layout_output.oof_candidates.take();
+ if !item.oof_candidates.is_empty() {
+ item.oof_candidates.translate(location);
+ }
+
+ if is_rtl_row {
+ *total_offset_main -= item.offset_main + item.margin.main_axis_sum(direction) + size.main(direction);
+ } else {
+ *total_offset_main += item.offset_main + item.margin.main_axis_sum(direction) + size.main(direction);
+ }
+
+ #[cfg(feature = "content_size")]
+ {
+ let contribution_location = if layout_direction.is_rtl() {
+ Point { x: container_size.width - (location.x + size.width) - border.right, y: location.y - border.top }
+ } else {
+ Point { x: location.x - border.left, y: location.y - border.top }
+ };
+ *total_overflow_rect = total_overflow_rect.union(compute_scrollable_overflow_contribution(
+ contribution_location,
+ size,
+ scrollable_overflow_rect,
+ item.overflow,
+ item.contain,
+ constants.is_scroll_container,
+ ));
+ }
+}
+
+/// Calculates the layout line
+#[allow(clippy::too_many_arguments)]
+fn calculate_layout_line(
+ tree: &mut impl LayoutFlexboxContainer,
+ line: &mut FlexLine,
+ total_offset_cross: &mut f32,
+ #[cfg(feature = "content_size")] overflow_rect: &mut Rect<f32>,
+ #[cfg(feature = "content_size")] border: Rect<f32>,
+ constants: &AlgoConstants,
+) {
+ let container_size = constants.container_size;
+ let padding_border = constants.content_box_inset;
+ let direction = constants.dir;
+ let layout_direction = constants.layout_direction;
+ let mut total_offset_main = if layout_direction.is_rtl() && direction.is_row() {
+ container_size.width - padding_border.main_end(direction)
+ } else {
+ padding_border.main_start(direction)
+ };
+ let line_offset_cross = line.offset_cross;
+
+ let is_rtl_column = layout_direction.is_rtl() && direction.is_column();
+ if is_rtl_column {
+ *total_offset_cross -= line_offset_cross + line.cross_size;
+ }
+
+ if direction.is_reverse() {
+ for item in line.items.iter_mut().rev() {
+ calculate_flex_item(
+ tree,
+ item,
+ &mut total_offset_main,
+ *total_offset_cross,
+ line_offset_cross,
+ #[cfg(feature = "content_size")]
+ overflow_rect,
+ #[cfg(feature = "content_size")]
+ border,
+ constants,
+ );
+ }
+ } else {
+ for item in line.items.iter_mut() {
+ calculate_flex_item(
+ tree,
+ item,
+ &mut total_offset_main,
+ *total_offset_cross,
+ line_offset_cross,
+ #[cfg(feature = "content_size")]
+ overflow_rect,
+ #[cfg(feature = "content_size")]
+ border,
+ constants,
+ );
+ }
+ }
+
+ if !is_rtl_column {
+ *total_offset_cross += line_offset_cross + line.cross_size;
+ }
+}
+
+/// Do a final layout pass and collect the resulting layouts.
+#[inline]
+fn final_layout_pass(
+ tree: &mut impl LayoutFlexboxContainer,
+ flex_lines: &mut [FlexLine],
+ constants: &AlgoConstants,
+) -> Rect<f32> {
+ let mut total_offset_cross = if constants.is_column && constants.layout_direction.is_rtl() {
+ constants.container_size.width - constants.content_box_inset.cross_end(constants.dir)
+ } else {
+ constants.content_box_inset.cross_start(constants.dir)
+ };
+
+ #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
+ let mut overflow_rect = Rect::ZERO;
+
+ if constants.is_wrap_reverse {
+ for line in flex_lines.iter_mut().rev() {
+ calculate_layout_line(
+ tree,
+ line,
+ &mut total_offset_cross,
+ #[cfg(feature = "content_size")]
+ &mut overflow_rect,
+ #[cfg(feature = "content_size")]
+ constants.border,
+ constants,
+ );
+ }
+ } else {
+ for line in flex_lines.iter_mut() {
+ calculate_layout_line(
+ tree,
+ line,
+ &mut total_offset_cross,
+ #[cfg(feature = "content_size")]
+ &mut overflow_rect,
+ #[cfg(feature = "content_size")]
+ constants.border,
+ constants,
+ );
+ }
+ }
+
+ // A scroll container's own padding at the end of the content is part of its scrollable
+ // overflow region, so it is included in the overflow rect. Boxes that are not scroll
+ // containers do not extend their overflow region by their own padding.
+ #[cfg(feature = "content_size")]
+ if constants.is_scroll_container {
+ overflow_rect.right += if constants.layout_direction.is_rtl() {
+ constants.content_box_inset.left - constants.border.left - constants.scrollbar_gutter.x
+ } else {
+ constants.content_box_inset.right - constants.border.right - constants.scrollbar_gutter.x
+ };
+ overflow_rect.bottom +=
+ constants.content_box_inset.bottom - constants.border.bottom - constants.scrollbar_gutter.y;
+ }
+
+ overflow_rect
+}
+
+/// Collect out-of-flow candidates in document order: direct out-of-flow children (computing their
+/// static positions per the flexbox alignment rules) interleaved with the candidates bubbled out
+/// of each in-flow item's subtree. Final sizing and positioning happens in the shared
+/// out-of-flow positioning pass at the containing block.
+#[inline]
+fn collect_oof_candidates(
+ tree: &mut impl LayoutFlexboxContainer,
+ node: NodeId,
+ constants: &AlgoConstants,
+ flex_lines: &mut [FlexLine],
+ candidates: &mut OofCandidates,
+) {
+ // Lines are contiguous slices of the items in document order (reversal is applied to
+ // positions, not storage), so walking the lines yields items sorted by `order`
+ let mut items = flex_lines
+ .iter_mut()
+ .flat_map(|line| line.items.iter_mut())
+ .filter(|item| !item.oof_candidates.is_empty())
+ .peekable();
+
+ let dir = constants.dir;
+ let container_size = constants.container_size;
+ let content_box_inset = constants.content_box_inset;
+
+ let main_axis_is_horizontal = constants.is_row;
+ let cross_axis_is_horizontal = !constants.is_row;
+ let main_is_rtl = main_axis_is_horizontal && constants.layout_direction.is_rtl();
+ let cross_is_rtl = cross_axis_is_horizontal && constants.layout_direction.is_rtl();
+ let main_axis_flex_start_reversed = dir.is_reverse() ^ main_is_rtl;
+ let cross_axis_flex_start_reversed = constants.is_wrap_reverse ^ cross_is_rtl;
+
+ // The static-position area in each axis is the container's content box
+ let main_area = Line {
+ start: content_box_inset.main_start(dir),
+ end: container_size.main(dir) - content_box_inset.main_end(dir),
+ };
+ let cross_area = Line {
+ start: content_box_inset.cross_start(dir),
+ end: container_size.cross(dir) - content_box_inset.cross_end(dir),
+ };
+
+ for order in 0..tree.child_count(node) {
+ let child = tree.get_child_id(node, order);
+ let child_style = tree.get_flexbox_child_style(child);
+ let position = child_style.position();
+
+ if child_style.box_generation_mode() == BoxGenerationMode::None {
+ continue;
+ }
+ // In-flow item: merge the candidates bubbled out of its subtree
+ if !position.is_out_of_flow() {
+ drop(child_style);
+ if let Some(item) = items.next_if(|item| item.order == order as u32) {
+ candidates.append(&mut item.oof_candidates);
+ }
+ continue;
+ }
+
+ let align_self = resolve_normal_alignment(child_style.align_self().unwrap_or(constants.align_items))
+ .resolve_self_relative(child_style.direction(), constants.layout_direction, constants.is_column);
+ drop(child_style);
+
+ // Main-axis static position (justify-content).
+ //
+ // Stretch is an invalid value for justify_content in the flexbox algorithm, so we
+ // treat it as if it wasn't set (and thus we default to FlexStart behaviour).
+ // Normal has already been resolved to FlexStart.
+ //
+ // The `safe` overflow-position keyword is intentionally NOT applied here, even when
+ // the abs-positioned item would overflow the main axis: Chrome does not apply safe
+ // fallback to `justify-content` on absolutely-positioned flex items (only the
+ // cross-axis `align-self` does so). Matching the layout authority over a strict
+ // spec read keeps gentest fixtures green; reconsider if Chromium changes behavior.
+ //
+ // `start`/`end` are writing-mode relative (they flip for RTL but not for
+ // reversed flex-directions), whereas `flex-start`/`flex-end` and the
+ // distributed keywords' fallbacks are flex-relative.
+ let main_keyword = constants.justify_content.keyword();
+ let main_start_position = match main_keyword {
+ AlignContentKeyword::Start => !main_is_rtl,
+ AlignContentKeyword::End => main_is_rtl,
+ _ => true,
+ };
+ let main_edge = match (main_keyword, main_axis_flex_start_reversed) {
+ (AlignContentKeyword::SpaceBetween, false)
+ | (AlignContentKeyword::Normal | AlignContentKeyword::Stretch, false)
+ | (AlignContentKeyword::FlexStart, false)
+ | (AlignContentKeyword::FlexEnd, true) => AxisStaticEdge::Start,
+ (AlignContentKeyword::Start | AlignContentKeyword::End, _) => {
+ if main_start_position {
+ AxisStaticEdge::Start
+ } else {
+ AxisStaticEdge::End
+ }
+ }
+ (AlignContentKeyword::FlexEnd, false)
+ | (AlignContentKeyword::FlexStart, true)
+ | (AlignContentKeyword::Normal | AlignContentKeyword::Stretch, true)
+ | (AlignContentKeyword::SpaceBetween, true) => AxisStaticEdge::End,
+ (AlignContentKeyword::SpaceEvenly, _)
+ | (AlignContentKeyword::SpaceAround, _)
+ | (AlignContentKeyword::Center, _) => AxisStaticEdge::Center,
+ };
+
+ // Cross-axis static position (align-self).
+ //
+ // `start`/`end` (and `baseline`, whose static-position fallback is `start`) are
+ // writing-mode relative: they flip for RTL but not for `wrap-reverse`.
+ // `flex-start`/`flex-end` and the `stretch` fallback are flex-relative.
+ let cross_edge_for = |keyword: AlignItemsKeyword| {
+ let start_position = match keyword {
+ AlignItemsKeyword::Start | AlignItemsKeyword::Baseline => !cross_is_rtl,
+ AlignItemsKeyword::End => cross_is_rtl,
+ _ => true,
+ };
+ match (keyword, cross_axis_flex_start_reversed) {
+ // Stretch alignment does not apply to absolutely positioned items
+ // See "Example 3" at https://www.w3.org/TR/css-flexbox-1/#abspos-items
+ // Note: Stretch should be FlexStart not Start when we support both
+ (AlignItemsKeyword::Start | AlignItemsKeyword::End | AlignItemsKeyword::Baseline, _) => {
+ if start_position {
+ AxisStaticEdge::Start
+ } else {
+ AxisStaticEdge::End
+ }
+ }
+ (AlignItemsKeyword::Stretch | AlignItemsKeyword::FlexStart, false)
+ | (AlignItemsKeyword::FlexEnd, true) => AxisStaticEdge::Start,
+ (AlignItemsKeyword::Stretch | AlignItemsKeyword::FlexStart, true)
+ | (AlignItemsKeyword::FlexEnd, false) => AxisStaticEdge::End,
+ (AlignItemsKeyword::Center, _) => AxisStaticEdge::Center,
+ // Normal is resolved to Stretch, and SelfStart/SelfEnd are resolved to Start/End
+ // against the item's own direction where `align_self` is read above.
+ (AlignItemsKeyword::Normal | AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd, _) => {
+ unreachable!()
+ }
+ }
+ };
+
+ let cross = AxisStaticPosition {
+ area: cross_area,
+ align: AxisStaticAlign {
+ keyword: cross_edge_for(align_self.keyword),
+ safety: align_self.safety,
+ fallback: cross_edge_for(resolve_self_alignment_safety(align_self, true)),
+ },
+ };
+ let main = AxisStaticPosition { area: main_area, align: AxisStaticAlign::from_keyword(main_edge) };
+
+ let static_position = if constants.is_row { Point { x: main, y: cross } } else { Point { x: cross, y: main } };
+ candidates.push(OofCandidate { node: child, order: order as u32, position, static_position });
+ }
+}
+
+/// Computes the total space taken up by gaps in an axis given:
+/// - The size of each gap
+/// - The number of items (children or flex-lines) between which there are gaps
+#[inline(always)]
+fn sum_axis_gaps(gap: f32, num_items: usize) -> f32 {
+ // Gaps only exist between items, so...
+ if num_items <= 1 {
+ // ...if there are less than 2 items then there are no gaps
+ 0.0
+ } else {
+ // ...otherwise there are (num_items - 1) gaps
+ gap * (num_items - 1) as f32
+ }
+}
+
+/// Balanced line breaking for `flex-wrap: balance`.
+///
+/// Implements the balancing algorithm from the CSS Flexbox Level 2 draft
+/// (<https://drafts.csswg.org/css-flexbox-2/#balancing>). Items are divided into exactly
+/// `line_count` contiguous sequences (lines), where `line_count` is the number of lines that
+/// greedy line breaking would produce (with item sizes floored at zero), raised to the minimum
+/// flex line count (`flex-line-count`, clamped to the number of items), such that:
+///
+/// - every line holds at least one item;
+/// - no line's size exceeds the container's inner main size, unless the line holds a single
+/// (overflowing) item;
+/// - a zero-sized item is assigned to the end of the preceding line rather than the beginning
+/// of a line, unless no valid division can glue it there: because extending the preceding
+/// line through the item would make it exceed the container's inner main size (which covers
+/// a preceding single overflowing item), or because gluing leaves the remaining lines
+/// without a valid division of the remaining items;
+/// - calling the difference between a line's size and the container's inner main size the
+/// line's *error*, the sum of the squared errors of all lines is minimized;
+/// - ties are broken by assigning the most items to the first line, then the most items to the
+/// second line, and so on.
+///
+/// Because every division has the same line count, total item size, and total gap size,
+/// minimizing the sum of squared errors is equivalent to minimizing the sum of squared *line
+/// sizes*, which is what is actually computed: it needs no target size, so an indefinite
+/// (infinite) container size needs no special handling — no line overflows, and the
+/// minimization equalizes the line sizes. All arithmetic uses `f64`: finite `f32` sizes
+/// convert exactly, and the squares and sums involved are far from `f64`'s limits, so
+/// equally-balanced divisions compare equal and are resolved by the tie-break rather than by
+/// rounding noise.
+///
+/// The minimization is a dynamic program over (line count, first item of suffix) accelerated
+/// with the divide-and-conquer optimization, running in `O(line_count * item_count *
+/// log(item_count))` time; the naive `O(line_count * item_count²)` dynamic program is kept as
+/// a test oracle.
+#[cfg(feature = "flexbox_balance")]
+mod balance {
+ use crate::util::sys::{new_vec_with_capacity, Vec};
+
+ /// Score assigned to divisions that violate the line size constraint
+ const INFEASIBLE: f64 = f64::INFINITY;
+
+ /// Convert an item size in pixels to an `f64`, flooring negative sizes at zero. (An
+ /// infinite size is clamped to the largest finite `f32` so that sums stay meaningful.)
+ fn to_size(value: f32) -> f64 {
+ (value as f64).clamp(0.0, f32::MAX as f64)
+ }
+
+ /// Line sizing shared by the scoring and readback phases
+ struct LineSizes {
+ /// Per item, the prefix sum of the item sizes through it (each item also contributes
+ /// one trailing gap, so the size of the line holding items `start..=end` is
+ /// `sums[end].0 - sums[start - 1].0 - gap_between_items`), paired with whether the
+ /// item's (floored) size is zero
+ sums: Vec<(f64, bool)>,
+ /// The size of the gap between adjacent items on a line
+ gap_between_items: f64,
+ /// The container's inner main size, which lines may not exceed (unless they hold a
+ /// single item)
+ limit: f64,
+ }
+
+ impl LineSizes {
+ /// The total number of items
+ fn item_count(&self) -> usize {
+ self.sums.len()
+ }
+
+ /// Whether the item at `index` has a (floored) size of zero
+ fn is_zero_item(&self, index: usize) -> bool {
+ self.sums[index].1
+ }
+
+ /// The size of the line holding items `start..=end`
+ fn line_size(&self, start: usize, end: usize) -> f64 {
+ let start_sum = if start == 0 { 0.0 } else { self.sums[start - 1].0 };
+ self.sums[end].0 - start_sum - self.gap_between_items
+ }
+
+ /// The squared size of the line holding items `start..=end`, or [`INFEASIBLE`] for a
+ /// line of more than one item exceeding the limit
+ fn line_cost(&self, start: usize, end: usize) -> f64 {
+ let size = self.line_size(start, end);
+ if end > start && size > self.limit {
+ return INFEASIBLE;
+ }
+ size * size
+ }
+
+ /// For every suffix of the items, the number of lines that greedy line breaking
+ /// produces for it: each line collects consecutive items until the next item no longer
+ /// fits, and if even the first item of a line doesn't fit, that line takes just the one
+ /// (overflowing) item. (The entry for the empty suffix is zero.)
+ ///
+ /// This is also the *fewest* lines each suffix can validly be divided into, and a
+ /// suffix can validly be divided into any number of lines from that count up to its
+ /// item count: dividing at greedy line ends never violates the zero-sized-item rule
+ /// (a line that can hold no more of the following items can never glue them), and
+ /// from any in-range line count the same holds with line ends capped to leave one
+ /// item per remaining line.
+ fn suffix_greedy_line_counts(&self) -> Vec<u32> {
+ let item_count = self.item_count();
+ let mut counts: Vec<u32> = new_vec_with_capacity(item_count + 1);
+ counts.extend(core::iter::repeat(0).take(item_count + 1));
+ // The (exclusive) end of the greedy first line of the suffix, which only moves
+ // down as the suffix grows leftwards since lines starting earlier are larger
+ let mut line_end = item_count;
+ for start in (0..item_count).rev() {
+ while line_end > start + 1 && self.line_size(start, line_end - 1) > self.limit {
+ line_end -= 1;
+ }
+ counts[start] = 1 + counts[line_end];
+ }
+ counts
+ }
+
+ /// For every `start`, the largest `end` such that the line holding items `start..=end`
+ /// does not exceed the limit (or `start` itself if even that one item overflows)
+ fn fit_ends(&self) -> Vec<u32> {
+ let item_count = self.item_count();
+ let mut fit_ends: Vec<u32> = new_vec_with_capacity(item_count);
+ // Lines starting later are smaller, so the fit end only moves up
+ let mut fit_end = 0;
+ for start in 0..item_count {
+ if fit_end < start {
+ fit_end = start;
+ }
+ while fit_end + 1 < item_count && self.line_size(start, fit_end + 1) <= self.limit {
+ fit_end += 1;
+ }
+ fit_ends.push(fit_end as u32);
+ }
+ fit_ends
+ }
+ }
+
+ /// One row of the balancing dynamic program: divisions of item suffixes into exactly
+ /// `lines` lines
+ struct Row<'a> {
+ /// The line sizing for the items being divided
+ sizes: &'a LineSizes,
+ /// See [`LineSizes::fit_ends`]
+ fit_ends: &'a [u32],
+ /// The previous row: `prev[start]` is the minimum score of any valid division of items
+ /// `start..` into exactly `lines - 1` lines ([`INFEASIBLE`] if there is none)
+ prev: &'a [f64],
+ /// The line ends that precede a non-zero item, in ascending order and capped to
+ /// `max_end`. Line ends preceding a *zero* item are constrained by the
+ /// zero-sized-item rule and handled separately: for a first line starting at `start`,
+ /// the only end preceding a zero item that can be part of a valid division is
+ /// `min(fit_ends[start], max_end)` — the line extended as far as the limit and the
+ /// remaining lines' one-item-each budget allow. Ending earlier is forbidden by the
+ /// rule (the zero item could be glued: the extended line fits and, per
+ /// [`LineSizes::suffix_greedy_line_counts`], what remains after even the longest glued
+ /// line divides validly into the remaining lines whenever what remains after the
+ /// shorter line does, which it must for the division to be feasible at all), and
+ /// ending later exceeds the limit on a line of more than one item.
+ nonzero_ends: &'a [u32],
+ /// The largest possible end of the first line: the remaining `lines - 1` lines need
+ /// one item each
+ max_end: usize,
+ }
+
+ /// Compute `cur[start]` and `opts[start]` for `start` in `start_lo..=start_hi`, where
+ /// `cur[start]` is the minimum over valid ends `end` of
+ /// `row.sizes.line_cost(start, end) + row.prev[end + 1]` and `opts[start]` is the largest
+ /// `end` achieving that minimum. Ends preceding a non-zero item are minimized over
+ /// `row.nonzero_ends[col_lo..col_hi]`; the (at most one) end preceding a zero item allowed
+ /// by the zero-sized-item rule is merged in afterwards.
+ ///
+ /// Uses the divide-and-conquer dynamic programming optimization: over the ends preceding
+ /// non-zero items, the cost function satisfies the concave quadrangle inequality (it is
+ /// the square of a quantity that increases in `end` and decreases in `start`, plus a term
+ /// depending on `end` alone, with infeasibility monotone in line length), so the largest
+ /// minimizing end is non-decreasing in `start`. Solving the middle `start` therefore
+ /// splits the end range in two, and each recursion level scans each candidate end a
+ /// bounded number of times. (The ends constrained by the zero-sized-item rule are *not*
+ /// monotone this way, which is why they are excluded from the scan and merged in
+ /// separately.)
+ fn fill_row(
+ row: &Row,
+ cur: &mut [f64],
+ opts: &mut [u32],
+ start_lo: usize,
+ start_hi: usize,
+ col_lo: usize,
+ col_hi: usize,
+ ) {
+ if start_lo > start_hi {
+ return;
+ }
+ let start = start_lo + (start_hi - start_lo) / 2;
+
+ // Minimize over the in-range ends preceding a non-zero item, starting from `start`
+ // (the line must hold at least one item)
+ let first_col = col_lo + row.nonzero_ends[col_lo..col_hi].partition_point(|&end| (end as usize) < start);
+ let mut min_cost = INFEASIBLE;
+ let mut min_col = None;
+ for col in first_col..col_hi {
+ let end = row.nonzero_ends[col] as usize;
+ let line_cost = row.sizes.line_cost(start, end);
+ if line_cost == INFEASIBLE {
+ // Every longer line also exceeds the limit
+ break;
+ }
+ let cost = line_cost + row.prev[end + 1];
+ // `<=` keeps the *largest* minimizing end, assigning the most items to the
+ // earliest lines as the tie-break requires
+ if cost <= min_cost {
+ min_cost = cost;
+ min_col = Some(col);
+ }
+ }
+
+ // Merge the single end preceding a zero item that the zero-sized-item rule allows
+ let mut min_end = min_col.map(|col| row.nonzero_ends[col] as usize);
+ let zero_end = (row.fit_ends[start] as usize).min(row.max_end);
+ if row.sizes.is_zero_item(zero_end + 1) {
+ let cost = row.sizes.line_cost(start, zero_end) + row.prev[zero_end + 1];
+ if cost < min_cost || (cost == min_cost && min_end.map_or(true, |end| end < zero_end)) {
+ min_cost = cost;
+ min_end = Some(zero_end);
+ }
+ }
+
+ // Infeasible states are excluded from the range by the caller, and every feasible
+ // state has a valid transition (see [`LineSizes::suffix_greedy_line_counts`])
+ debug_assert!(min_cost.is_finite());
+ cur[start] = min_cost;
+ opts[start] = min_end.unwrap_or(start) as u32;
+
+ // The zero-rule end is excluded from the narrowing: only the non-zero ends' minima
+ // are monotone
+ if start > start_lo {
+ let col_hi = min_col.map_or(col_hi, |col| col + 1);
+ fill_row(row, cur, opts, start_lo, start - 1, col_lo, col_hi);
+ }
+ if start < start_hi {
+ let col_lo = min_col.unwrap_or(first_col);
+ fill_row(row, cur, opts, start + 1, start_hi, col_lo, col_hi);
+ }
+ }
+
+ /// Determine the number of items on each line that balances items across lines, such that
+ /// the largest line is as small as possible, with a minimum of `min_line_count` lines
+ /// (or one line per item if there are fewer items).
+ ///
+ /// `item_sizes` must be non-empty. The returned line item counts are all non-zero and sum to
+ /// the number of items.
+ ///
+ /// Runs in `O(line_count * item_count * log(item_count))` time using
+ /// `O(line_count * item_count)` transient memory.
+ pub(super) fn balanced_line_item_counts(
+ item_sizes: impl ExactSizeIterator<Item = f32>,
+ line_limit: f32,
+ gap_between_items: f32,
+ min_line_count: usize,
+ ) -> Vec<usize> {
+ let item_count = item_sizes.len();
+ debug_assert!(item_count > 0);
+ let gap_between_items = to_size(gap_between_items);
+ let limit = line_limit as f64;
+
+ let mut sums: Vec<(f64, bool)> = new_vec_with_capacity(item_count);
+ let mut sum = 0.0;
+ for size in item_sizes {
+ let size = to_size(size);
+ sum += size + gap_between_items;
+ sums.push((sum, size == 0.0));
+ }
+ let sizes = LineSizes { sums, gap_between_items, limit };
+
+ // `suffix_greedy[start]` is the number of lines greedy line breaking produces for items
+ // `start..`, which is also the *fewest* lines the suffix can validly be divided into
+ let suffix_greedy = sizes.suffix_greedy_line_counts();
+ let line_count = (suffix_greedy[0] as usize).max(min_line_count.clamp(1, item_count));
+
+ let mut item_counts: Vec<usize> = new_vec_with_capacity(line_count);
+ if line_count == item_count {
+ // One item per line is the only division (this covers `flex-line-count` of at least
+ // the item count as well as every item overflowing a line of its own)
+ item_counts.extend(core::iter::repeat(1).take(item_count));
+ return item_counts;
+ }
+
+ let fit_ends = sizes.fit_ends();
+ let mut nonzero_ends: Vec<u32> = new_vec_with_capacity(item_count - 1);
+ for end in 0..item_count - 1 {
+ if !sizes.is_zero_item(end + 1) {
+ nonzero_ends.push(end as u32);
+ }
+ }
+
+ // `prev[start]` is the minimum total score of any valid division of items `start..`
+ // into exactly `lines - 1` lines ([`INFEASIBLE`] if there is none), and `cur` is the
+ // row being computed for `lines` lines: a division into `lines` lines is a first line
+ // `start..=end` plus a division of `end + 1..` into `lines - 1` lines.
+ // `opts[(lines - 2) * item_count + start]` records the largest `end` achieving
+ // `cur[start]`, from which the chosen division is read back.
+ let mut prev: Vec<f64> = new_vec_with_capacity(item_count);
+ for start in 0..item_count {
+ prev.push(sizes.line_cost(start, item_count - 1));
+ }
+ let mut cur: Vec<f64> = new_vec_with_capacity(item_count);
+ cur.extend(core::iter::repeat(INFEASIBLE).take(item_count));
+ let mut opts: Vec<u32> = new_vec_with_capacity((line_count - 1) * item_count);
+ opts.extend(core::iter::repeat(0).take((line_count - 1) * item_count));
+ for lines in 2..=line_count {
+ // The remaining `lines - 1` lines need one item each, bounding this line's end
+ let max_end = item_count - lines;
+ // Starts whose suffix doesn't fit in `lines` lines even with greedy breaking are
+ // infeasible; they form a prefix (a longer suffix never needs fewer lines), and
+ // excluding them keeps every state `fill_row` solves feasible
+ let mut first_start = 0;
+ while first_start < max_end && suffix_greedy[first_start] as usize > lines {
+ cur[first_start] = INFEASIBLE;
+ first_start += 1;
+ }
+ let col_hi = nonzero_ends.partition_point(|&end| (end as usize) <= max_end);
+ let row = Row { sizes: &sizes, fit_ends: &fit_ends, prev: &prev, nonzero_ends: &nonzero_ends, max_end };
+ let opts_row = &mut opts[(lines - 2) * item_count..(lines - 1) * item_count];
+ fill_row(&row, &mut cur, opts_row, first_start, max_end, 0, col_hi);
+ core::mem::swap(&mut prev, &mut cur);
+ }
+
+ // Read the division back out front to back
+ debug_assert!(prev[0].is_finite());
+ let mut start = 0;
+ for lines in (2..=line_count).rev() {
+ let end = opts[(lines - 2) * item_count + start] as usize;
+ item_counts.push(end - start + 1);
+ start = end + 1;
+ }
+ item_counts.push(item_count - start);
+ item_counts
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ /// The number of lines that greedy line breaking produces: each line collects
+ /// consecutive items until the next item no longer fits, and if even the first item of
+ /// a line doesn't fit, that line takes just the one (overflowing) item
+ fn greedy_line_count(sizes: &LineSizes) -> usize {
+ let item_count = sizes.item_count();
+ let mut line_count = 1;
+ let mut index = 0;
+ while index < item_count {
+ let mut next = index;
+ while next < item_count && sizes.line_size(index, next) <= sizes.limit {
+ next += 1;
+ }
+ if next == index {
+ next = index + 1;
+ }
+ index = next;
+ if index < item_count {
+ line_count += 1;
+ }
+ }
+ line_count
+ }
+
+ /// The zero-sized-item rule, brute force: a line `start..=end` (of a division of
+ /// `start..` into `lines` lines) may only end before a zero-sized item if no division
+ /// that extends the line through the item exists — every extension either exceeds the
+ /// limit or leaves the remaining items without a valid division into the remaining
+ /// lines. (`min_errors` rows below `lines` must already be computed.)
+ fn zero_boundary_valid(sizes: &LineSizes, min_errors: &[f64], lines: usize, start: usize, end: usize) -> bool {
+ let item_count = sizes.item_count();
+ if !sizes.is_zero_item(end + 1) {
+ return true;
+ }
+ for glued_end in end + 1..=item_count - lines {
+ if sizes.line_size(start, glued_end) > sizes.limit {
+ break;
+ }
+ if min_errors[(lines - 2) * item_count + glued_end + 1].is_finite() {
+ return false;
+ }
+ }
+ true
+ }
+
+ /// The naive `O(line_count * item_count²)` dynamic program from the spec, used as a
+ /// test oracle for the divide-and-conquer optimized implementation
+ fn naive_line_item_counts(
+ item_sizes: &[f32],
+ line_limit: f32,
+ gap_between_items: f32,
+ min_line_count: usize,
+ ) -> Vec<usize> {
+ let item_count = item_sizes.len();
+ let gap_between_items = to_size(gap_between_items);
+ let limit = line_limit as f64;
+
+ let mut sums: Vec<(f64, bool)> = new_vec_with_capacity(item_count);
+ let mut sum = 0.0;
+ for size in item_sizes {
+ let size = to_size(*size);
+ sum += size + gap_between_items;
+ sums.push((sum, size == 0.0));
+ }
+ let sizes = LineSizes { sums, gap_between_items, limit };
+
+ let line_count = greedy_line_count(&sizes).max(min_line_count.clamp(1, item_count));
+
+ // `min_errors[(lines - 1) * item_count + start]` is the minimum total score of any
+ // valid division of items `start..` into exactly `lines` lines
+ let mut min_errors: Vec<f64> = new_vec_with_capacity(line_count * item_count);
+ for start in 0..item_count {
+ min_errors.push(sizes.line_cost(start, item_count - 1));
+ }
+ for lines in 2..=line_count {
+ let row = (lines - 1) * item_count;
+ for start in 0..item_count {
+ let mut min_error = INFEASIBLE;
+ let mut end = start;
+ while end + lines <= item_count {
+ let line_cost = sizes.line_cost(start, end);
+ if line_cost == INFEASIBLE {
+ break;
+ }
+ if zero_boundary_valid(&sizes, &min_errors, lines, start, end) {
+ let error = line_cost + min_errors[row - item_count + end + 1];
+ if error < min_error {
+ min_error = error;
+ }
+ }
+ end += 1;
+ }
+ min_errors.push(min_error);
+ }
+ }
+
+ // For each line, the *largest* end whose error plus the minimum remaining error
+ // adds up to the (feasible) minimum is chosen
+ assert!(min_errors[(line_count - 1) * item_count].is_finite());
+ let mut item_counts: Vec<usize> = new_vec_with_capacity(line_count);
+ let mut start = 0;
+ for lines_after in (0..line_count).rev() {
+ let target = min_errors[lines_after * item_count + start];
+ let mut end = item_count - 1 - lines_after;
+ loop {
+ if sizes.line_cost(start, end) != INFEASIBLE
+ && (lines_after == 0 || zero_boundary_valid(&sizes, &min_errors, lines_after + 1, start, end))
+ {
+ let remaining_error =
+ if lines_after == 0 { 0.0 } else { min_errors[(lines_after - 1) * item_count + end + 1] };
+ if sizes.line_cost(start, end) + remaining_error == target {
+ break;
+ }
+ }
+ assert!(end > start);
+ end -= 1;
+ }
+ item_counts.push(end - start + 1);
+ start = end + 1;
+ }
+ assert_eq!(start, item_count);
+ item_counts
+ }
+
+ #[test]
+ fn zero_sized_item_rule() {
+ // The zero item joins the first line even though the gap it brings makes the score
+ // worse: [70, 0] / [20] has line sizes 80 / 20 (score 6800), while [70] / [0, 20]
+ // would have line sizes 70 / 30 (score 5800)
+ let counts = balanced_line_item_counts([70.0, 0.0, 20.0].iter().copied(), 100.0, 10.0, 1);
+ assert_eq!(counts, [2, 1]);
+ // The zero item is not glued to a single overflowing item's line
+ let counts = balanced_line_item_counts([150.0, 0.0, 30.0].iter().copied(), 100.0, 0.0, 1);
+ assert_eq!(counts, [1, 2]);
+ // Zero items are glued as far as the requested line count allows
+ let counts = balanced_line_item_counts([70.0, 0.0, 0.0].iter().copied(), 100.0, 0.0, 2);
+ assert_eq!(counts, [2, 1]);
+ }
+
+ #[test]
+ fn matches_naive_dp() {
+ // A simple xorshift PRNG so the test is deterministic and dependency-free
+ let mut state: u64 = 0x243F6A8885A308D3;
+ let mut rand = move |bound: u32| -> u32 {
+ state ^= state << 13;
+ state ^= state >> 7;
+ state ^= state << 17;
+ ((state >> 32) as u32) % bound
+ };
+
+ for case in 0..5000 {
+ // Mostly small item counts (quantized sizes maximize ties, exercising the
+ // tie-break rules), with some larger ones exercising the recursion
+ let item_count = if case % 20 == 0 { (rand(60) + 1) as usize } else { (rand(15) + 1) as usize };
+ let mut item_sizes: Vec<f32> = new_vec_with_capacity(item_count);
+ for _ in 0..item_count {
+ let size = match rand(8) {
+ // Frequent zero items exercise the zero-sized-item rule
+ 0 | 1 => 0.0,
+ 2 => -10.0,
+ _ => rand(8) as f32 * 25.0,
+ };
+ item_sizes.push(size);
+ }
+ let line_limit = match rand(5) {
+ 0 => f32::INFINITY,
+ _ => rand(10) as f32 * 30.0,
+ };
+ let gap_between_items = rand(4) as f32 * 5.0;
+ let min_line_count = rand(item_count as u32 + 2) as usize;
+
+ let expected = naive_line_item_counts(&item_sizes, line_limit, gap_between_items, min_line_count);
+ let actual = balanced_line_item_counts(
+ item_sizes.iter().copied(),
+ line_limit,
+ gap_between_items,
+ min_line_count,
+ );
+ assert_eq!(
+ actual, expected,
+ "case {case}: item_sizes={item_sizes:?} line_limit={line_limit} \
+ gap_between_items={gap_between_items} min_line_count={min_line_count}"
+ );
+ }
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/float.rs b/vendor/taffy/src/compute/float.rs
new file mode 100644
index 00000000..5a5fdf51
--- /dev/null
+++ b/vendor/taffy/src/compute/float.rs
@@ -0,0 +1,797 @@
+//! Computes the position of floats in a block formatting context
+//!
+//! Here are the precise rules that govern the behavior of floats:
+//!
+//! 1. The left outer edge of a left-floating box may not be to the left of the left edge of its containing block. An analogous rule
+//! holds for right-floating elements.
+//! 2. If the current box is left-floating, and there are any left-floating boxes generated by elements earlier in the source document,
+//! then for each such earlier box, either the left outer edge of the current box must be to the right of the right outer edge of the earlier box,
+//! or its top must be lower than the bottom of the earlier box. Analogous rules hold for right-floating boxes.
+//! 3. The right outer edge of a left-floating box may not be to the right of the left outer edge of any right-floating box that is next to it.
+//! Analogous rules hold for right-floating elements.
+//! 4. A floating box's outer top may not be higher than the top of its containing block. When the float occurs between two collapsing margins,
+//! the float is positioned as if it had an otherwise empty anonymous block parent taking part in the flow. The position of such a parent is defined
+//! by the rules in the section on margin collapsing.
+//! 5. The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
+//! 6. The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by
+//! an element earlier in the source document.
+//! 7. A left-floating box that has another left-floating box to its left may not have its right outer edge to the right of its containing block's
+//! right edge. (Loosely: a left float may not stick out at the right edge, unless it is already as far to the left as possible.) An analogous rule
+//! holds for right-floating elements.
+//! 8. A floating box must be placed as high as possible.
+//! 9. A left-floating box must be put as far to the left as possible, a right-floating box as far to the right as possible. A higher position is
+//! preferred over one that is further to the left/right.
+//!
+//! But in CSS 2.2, if, within the block formatting context, there is an in-flow negative vertical margin such that the float's position is above the position it would be at were all such negative margins set to zero, the position of the float is undefined.
+//!
+//! <https://www.w3.org/TR/CSS22/visuren.html#floats>
+
+use core::ops::Range;
+
+use crate::{debug::debug_log, sys::Vec, AvailableSpace, Clear, Direction, FloatDirection, Point, Size};
+
+/// Tolerance used when checking whether a box fits in a horizontal space, to absorb `f32`
+/// rounding errors (e.g. percentage widths and margins that sum to exactly 100% may otherwise
+/// exceed the container width and spuriously wrap)
+pub(crate) const FIT_TOLERANCE: f32 = 0.001;
+
+/// An empty "slot" that avoids floats that is suitable for non-floated content
+/// to be laid out into
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ContentSlot {
+ /// The id of the segment that the slot starts in
+ pub segment_id: Option<usize>,
+ /// The x position of the start of the slot
+ pub x: f32,
+ /// The y position of the start of the slot
+ pub y: f32,
+ /// The width of the slot
+ pub width: f32,
+ /// The height of the slot
+ pub height: f32,
+}
+
+/// An empty "slot" that avoids floats that is suitable for a box that establishes
+/// an independent formatting context (and therefore must not overlap floats) to be
+/// laid out into. Unlike [`ContentSlot`], this accounts for the box's own margins,
+/// which are resolved against the containing block's edges (not float edges) and
+/// may therefore overlap floats.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct BfcSlot {
+ /// The id of the segment that the slot starts in
+ pub segment_id: Option<usize>,
+ /// The x position of the start of the slot (border box edge)
+ pub x: f32,
+ /// The y position of the start of the slot
+ pub y: f32,
+ /// The space available for the box's border box: the space between float edges
+ /// and the margin-inset containing block edges. The box fits in the slot if its
+ /// border box width does not exceed this.
+ pub border_width: f32,
+ /// The width that an auto width resolves to (before applying min/max constraints and
+ /// the negative-margin lower bound). This differs from `border_width` in that the
+ /// trailing margin is subtracted (except for any part of it that overlaps a float).
+ pub stretch_width: f32,
+}
+
+/// A floated box
+#[derive(Debug, Clone, Default)]
+pub struct PlacedFloatedBox {
+ /// A user defined ID for the box
+ // id: u64,
+ /// The width of the box
+ pub width: f32,
+ /// The height of the box
+ pub height: f32,
+ /// Horizontal distance from the edge of the container that the box is floated towards
+ /// (distance from the left for left floats, from the right for right floats)
+ pub x_inset: f32,
+ /// Vertical distance from top edge of the container
+ pub y: f32,
+}
+
+/// A non-overlapping horizontal segment of the Block Formatting Context container
+#[derive(Debug, Clone)]
+struct Segment {
+ /// The vertical start and end points of the segment
+ y: Range<f32>,
+ /// Left inset in slot 0. Right inset in slot 1.
+ insets: [f32; 2],
+ /// Whether a float actually occupies the left (slot 0) / right (slot 1) inset.
+ /// The insets of a segment created for a float are seeded with the float's containing
+ /// block insets on both sides, so a non-zero inset alone does not imply a float.
+ has_float: [bool; 2],
+}
+
+impl Segment {
+ /// Whether the segment can fit the passed floated box (in the horizontal axis)
+ ///
+ /// See [`float_fits_horizontally`] for the details of the fit rules.
+ fn fits_float_width(
+ &self,
+ floated_box: Size<f32>,
+ direction: FloatDirection,
+ bfc_width: f32,
+ cb_insets: [f32; 2],
+ ) -> bool {
+ float_fits_horizontally(floated_box.width, direction, bfc_width, self.insets, cb_insets)
+ }
+}
+
+/// Whether a floated box of the given width fits horizontally given the float insets
+/// (`float_insets`) and containing block insets (`cb_insets`) that apply to it.
+///
+/// A float is normally placed at the further-in of the float edge and the containing block
+/// edge on the side it is floated towards (its "lead" side). From that position it must:
+///
+/// - not overlap any float on the opposite ("trail") side (CSS2 §9.5.1 rule 3), and
+/// - not extend past the containing block's trail edge if there is a float on its lead
+/// side (CSS2 §9.5.1 rule 7: a float may only stick out of its containing block if it
+/// is already as far towards its float direction as possible).
+///
+/// Note that a float which is not constrained by other floats *may* overflow its
+/// containing block's trail edge (rules 1 and 7).
+fn float_fits_horizontally(
+ width: f32,
+ direction: FloatDirection,
+ bfc_width: f32,
+ float_insets: [f32; 2],
+ cb_insets: [f32; 2],
+) -> bool {
+ let lead = direction as usize;
+ let trail = 1 - lead;
+ let x_inset = float_insets[lead].max(cb_insets[lead]);
+ let fits_opposite_floats =
+ float_insets[trail] == 0.0 || x_inset + width <= bfc_width - float_insets[trail] + FIT_TOLERANCE;
+ let fits_containing_block =
+ float_insets[lead] == 0.0 || x_inset + width <= bfc_width - cb_insets[trail] + FIT_TOLERANCE;
+ fits_opposite_floats && fits_containing_block
+}
+
+/// Helper type for placing a single floated box
+///
+/// Given a pinned starting y position, this type helps determine if there is any x position
+/// such that there is sufficient horizontal space for the box accross it's entire height.
+#[derive(Debug, Clone)]
+struct FloatFitter {
+ /// The overall width of the Block Formatting Context
+ bfc_width: f32,
+ /// The total height of the set of segments currently being considered
+ slot_height: f64,
+ /// The union of the float insets of the set of segments currently being considered
+ float_insets: [f32; 2],
+ /// The insets of the box's containing block from the edges of the Block Formatting Context
+ cb_insets: [f32; 2],
+}
+
+impl FloatFitter {
+ /// Create a new `FloatFitter`
+ fn new(bfc_width: f32, slot_height: f32, cb_insets: [f32; 2]) -> Self {
+ Self { bfc_width, slot_height: slot_height as f64, float_insets: [0.0, 0.0], cb_insets }
+ }
+
+ // Horizontal fitting
+
+ /// Union the insets of another segment. This is a "max" of the insets on each side.
+ fn union_insets(&mut self, insets: [f32; 2]) {
+ self.float_insets[0] = self.float_insets[0].max(insets[0]);
+ self.float_insets[1] = self.float_insets[1].max(insets[1]);
+ }
+
+ /// The inset from the edge of the BFC (on the side the box is floated towards) that the
+ /// box would be placed at given the currently accounted for insets
+ fn placed_inset(&self, direction: FloatDirection) -> f32 {
+ let lead = direction as usize;
+ self.float_insets[lead].max(self.cb_insets[lead])
+ }
+
+ /// Given the currently accounted for insets, check whether there is an x position
+ /// such that the box fits horizontally.
+ ///
+ /// See [`float_fits_horizontally`] for the details of the fit rules.
+ fn fits_horiontally(&self, width: f32, direction: FloatDirection) -> bool {
+ float_fits_horizontally(width, direction, self.bfc_width, self.float_insets, self.cb_insets)
+ }
+
+ // Vertical fitting
+
+ /// Add the height of another segment.
+ fn add_height(&mut self, height: f32) {
+ self.slot_height += height as f64;
+ }
+
+ /// Given the currently accounted for height, check whether the box fits vertically
+ fn fits_vertically(&mut self, height: f32) -> bool {
+ self.slot_height >= height as f64
+ }
+}
+
+/// A context for placing floated boxes
+#[derive(Debug, Clone)]
+pub struct FloatContext {
+ /// The available space constraint that applies to the root Block Formatting Context
+ /// for which this `FloatContext` manages floats.
+ available_width: f32,
+ /// Whether the float context contains any floats
+ has_floats: bool,
+ /// A list of left-floated boxes within the context
+ left_floats: Vec<PlacedFloatedBox>,
+ /// A list of right-floated boxes within the context
+ right_floats: Vec<PlacedFloatedBox>,
+ /// A list of non-overlapping horizontal "segments" within the context.
+ /// Each segment has the same available width for it's entire height.
+ segments: Vec<Segment>,
+ /// A closed-open range indicating which segment the last placed float
+ /// was placed(on each side).
+ last_placed_floats: [Range<usize>; 2],
+ /// The bottom (y + height) of the lowest float placed on each side, including
+ /// zero-sized floats (which occupy no segment). Left in slot 0, right in slot 1.
+ clear_bottoms: [Option<f32>; 2],
+ /// The topmost y position allowed for a new float (CSS2 float rule 5), including
+ /// the tops of zero-sized floats (which occupy no segment)
+ float_ceiling: Option<f32>,
+ // Left hwm in slot 0. Right hwm in slot 1.
+ // high_water_marks: [usize; 2],
+ // left_float_high_water_mark: usize,
+ // right_float_high_water_mark: usize,
+}
+
+impl Default for FloatContext {
+ fn default() -> Self {
+ Self {
+ available_width: 0.0,
+ has_floats: false,
+ left_floats: Vec::new(),
+ right_floats: Vec::new(),
+ segments: Vec::new(),
+ last_placed_floats: [0..0, 0..0], // high_water_marks: [0, 0],
+ clear_bottoms: [None, None],
+ float_ceiling: None,
+ }
+ }
+}
+
+impl FloatContext {
+ /// Create a new empty `FloatContext`
+ pub fn new() -> Self {
+ Default::default()
+ }
+
+ /// Whether the float context contains any floats
+ #[inline(always)]
+ pub fn has_floats(&self) -> bool {
+ self.has_floats
+ }
+
+ /// Whether the float context contains any floats that extend to or below min_y
+ #[inline(always)]
+ pub fn has_active_floats(&self, min_y: f32) -> bool {
+ self.has_floats && self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0) > min_y
+ }
+
+ /// Set the width of the `FloatContext`
+ pub fn set_width(&mut self, available_width: f32) {
+ self.available_width = available_width;
+ }
+
+ /// Returns a slice of placed left floats
+ pub fn left_floats(&self) -> &[PlacedFloatedBox] {
+ &self.left_floats
+ }
+
+ /// Returns a slice of placed right floats
+ pub fn right_floats(&self) -> &[PlacedFloatedBox] {
+ &self.right_floats
+ }
+
+ /// Divide a segment into two segments so that a new float can be placed and have it's
+ /// vertical start and end at exact segment boundaries
+ fn subdivide_segment(&mut self, idx: usize, divide_at_y: f32) {
+ let old_segment = &mut self.segments[idx];
+ let new_segment =
+ Segment { insets: old_segment.insets, has_float: old_segment.has_float, y: divide_at_y..old_segment.y.end };
+ if !old_segment.y.contains(&divide_at_y) || old_segment.y.start == divide_at_y {
+ debug_log!("old_segment", dbg:&mut *old_segment);
+ debug_log!("divide_at_y", dbg:divide_at_y);
+ assert!(old_segment.y.contains(&divide_at_y) && old_segment.y.start != divide_at_y);
+ }
+ old_segment.y.end = divide_at_y;
+
+ self.segments.splice((idx + 1)..(idx + 1), core::iter::once(new_segment));
+ }
+
+ /// Update the last placed float start and end values
+ fn update_last_placed_float(&mut self, direction: FloatDirection, placement: Range<usize>) {
+ let slot = direction as usize;
+ self.last_placed_floats[slot].start = self.last_placed_floats[slot].start.max(placement.start);
+ self.last_placed_floats[slot].end = self.last_placed_floats[slot].end.max(placement.end);
+ }
+
+ /// Position a floated box with the context, returning the (x, y) coordinates
+ pub fn place_floated_box(
+ &mut self,
+ floated_box: Size<f32>,
+ min_y: f32,
+ containing_block_insets: [f32; 2],
+ direction: FloatDirection,
+ clear: Clear,
+ ) -> Point<f32> {
+ self.has_floats = true;
+
+ let placed_floated_box =
+ self.place_floated_box_inner(floated_box, min_y, containing_block_insets, direction, clear);
+
+ let slot = direction as usize;
+ let bottom = placed_floated_box.y + placed_floated_box.height;
+ self.clear_bottoms[slot] = Some(self.clear_bottoms[slot].map_or(bottom, |b| b.max(bottom)));
+ let y = placed_floated_box.y;
+ self.float_ceiling = Some(self.float_ceiling.map_or(y, |ceiling| ceiling.max(y)));
+
+ let x_inset = placed_floated_box.x_inset;
+ let y = placed_floated_box.y;
+ match direction {
+ FloatDirection::Left => {
+ self.left_floats.push(placed_floated_box);
+ Point { x: x_inset, y }
+ }
+ FloatDirection::Right => {
+ self.right_floats.push(placed_floated_box);
+ Point { x: self.available_width - x_inset - floated_box.width, y }
+ }
+ }
+ }
+
+ /// Inner implementation of float placement, split into a separate function so that it can early-return
+ fn place_floated_box_inner(
+ &mut self,
+ floated_box: Size<f32>,
+ min_y: f32,
+ containing_block_insets: [f32; 2],
+ direction: FloatDirection,
+ clear: Clear,
+ ) -> PlacedFloatedBox {
+ let slot = direction as usize;
+
+ // Floats (including zero-sized floats) that occupy no segment still constrain the
+ // position of later boxes: rule 5 (a float may not be higher than the top of any
+ // earlier float) and `clear` (which clears past the bottom of floats on the
+ // relevant side, regardless of their width)
+ let min_y = min_y
+ .max(self.float_ceiling.unwrap_or(f32::NEG_INFINITY))
+ .max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
+
+ // Ensure that float:
+ // - Starts at or after the last placed float in either direction (CSS2 float rule 5:
+ // "The outer top of a floating box may not be higher than the outer top of any block
+ // or floated box generated by an element earlier in the source document")
+ // - Respects "clear"
+ let float_start = self.last_placed_floats[0].start.max(self.last_placed_floats[1].start);
+ let hwm = match clear {
+ Clear::Left => {
+ let left_end = self.last_placed_floats[0].end;
+ float_start.max(left_end + 1)
+ }
+ Clear::Right => {
+ let right_end = self.last_placed_floats[1].end;
+ float_start.max(right_end + 1)
+ }
+ Clear::Both => {
+ let left_end = self.last_placed_floats[0].end;
+ let right_end = self.last_placed_floats[1].end;
+ left_end.max(right_end) + 1
+ }
+ Clear::None => float_start,
+ };
+
+ // Ensure that float is placed in a segment at or below "min_y"
+ // (ensuring that it is placed at or below min_y within it's segment happens below)
+ let start_idx = self
+ .segments
+ .get(hwm..)
+ .and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
+
+ let mut start_idx = start_idx.unwrap_or(self.segments.len());
+ let mut start_y = min_y;
+ let mut end_idx = start_idx;
+ // let mut end_y = min_y;
+
+ // Loop over remaining segments, trying to place the float in a position
+ // that has space to accomodate it.
+ let (start, mut end, placed_inset) = 'outer: loop {
+ // Start segment does not exist:
+ //
+ // This means no existing segment can accomodate the float so we must create a new
+ // segment below all existing segments. A new segment will always have space for
+ // the float, so we can exit the loop at this point.
+ let Some(start_segment) = self.segments.get(start_idx) else {
+ break (None, None, containing_block_insets[slot]);
+ };
+
+ // Candidate start segment doesn't have (horizontal) space for the float:
+ // => retry with the next segment
+ if !start_segment.fits_float_width(floated_box, direction, self.available_width, containing_block_insets) {
+ start_idx += 1;
+ end_idx = end_idx.max(start_idx);
+ continue;
+ }
+
+ start_y = start_y.max(start_segment.y.start);
+ let available_height = start_segment.y.end - start_y;
+ let mut fitter = FloatFitter::new(self.available_width, available_height, containing_block_insets);
+ fitter.union_insets(start_segment.insets);
+
+ // Pinning the start segment, loop over segments starting with the start segment
+ // to find the end segment:
+ // - The selected segment range must have enough height to contain the float
+ // - All of the segments in the range must have enough horizontal width to contain the float
+ // TODO: must ensure that width is in the correct place.
+ loop {
+ // End segment does not exist:
+ //
+ // This means no existing segment can accomodate the float so we must create a new
+ // segment below all existing segments
+ let Some(end_segment) = self.segments.get(end_idx) else {
+ let inset = fitter.placed_inset(direction);
+ break 'outer (Some(start_idx), None, inset);
+ };
+
+ // Check horizontal fit
+ //
+ // If it does not fit horizontally then it will never fit in this position, so
+ // continue the outer loop to find and check a new position
+ fitter.union_insets(end_segment.insets);
+ if !fitter.fits_horiontally(floated_box.width, direction) {
+ start_idx += 1;
+ end_idx = end_idx.max(start_idx);
+ continue 'outer;
+ }
+
+ // Check vertical fit
+ //
+ // If it does not (yet) fit vertically then continue the inner loop to add another
+ // segment to the range of segments we are placing the float in
+ if end_idx != start_idx {
+ fitter.add_height(end_segment.y.end - end_segment.y.start);
+ }
+ if !fitter.fits_vertically(floated_box.height) {
+ end_idx += 1;
+ continue;
+ }
+
+ let inset = fitter.placed_inset(direction);
+ break 'outer (Some(start_idx), Some(end_idx), inset);
+ }
+ };
+
+ // Short-circuit for zero-height boxes. Zero-width boxes are still recorded in segments:
+ // their edge acts as an obstacle that boxes establishing an independent formatting
+ // context may not be placed to the outside of (e.g. via a negative margin).
+ if floated_box.height == 0.0 {
+ // TODO: need to update last_placed_float?
+
+ return PlacedFloatedBox {
+ width: floated_box.width,
+ height: floated_box.height,
+ y: start_y,
+ x_inset: placed_inset,
+ };
+ }
+
+ // Handle case where floated box is placed after all existing segments
+ if start.is_none() {
+ let last_y_end = self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0);
+ if start_y > last_y_end {
+ self.segments.push(Segment { y: last_y_end..start_y, insets: [0.0, 0.0], has_float: [false; 2] });
+ }
+
+ let start_y = last_y_end.max(start_y);
+
+ let mut insets = containing_block_insets;
+ insets[slot] += floated_box.width;
+ let mut has_float = [false; 2];
+ has_float[slot] = true;
+ self.segments.push(Segment { y: start_y..(start_y + floated_box.height), insets, has_float });
+
+ // Update last_placed_float
+ let start_idx = self.segments.len() - 1;
+ let end_idx = start_idx + 1;
+ self.update_last_placed_float(direction, start_idx..end_idx);
+
+ return PlacedFloatedBox {
+ width: floated_box.width,
+ height: floated_box.height,
+ y: start_y,
+ x_inset: containing_block_insets[slot],
+ };
+ }
+
+ // Else unwrap the index of the segment that the start of the floating box is placed in
+ let mut start_idx = start.unwrap();
+
+ // If the floated box doesn't start at the exact same y-offset as the segment it starts in, then
+ // subdivide that segment into two segments at the y-offset that the floated box starts at, and increment
+ // `start_idx` so that the floating box is placed in the second of the two segments.
+ if start_y != self.segments[start_idx].y.start {
+ self.subdivide_segment(start_idx, start_y);
+ start_idx += 1;
+ if let Some(end_idx) = end.as_mut() {
+ *end_idx += 1;
+ }
+ }
+
+ let end_idx = match end {
+ None => {
+ let last_y_end = self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0);
+ if min_y > last_y_end {
+ self.segments.push(Segment { y: last_y_end..min_y, insets: [0.0, 0.0], has_float: [false; 2] });
+ }
+ self.segments.len() - 1
+ }
+ Some(mut end_idx) => {
+ let end_y = start_y + floated_box.height;
+
+ // Due to floating point imprecision, `end_y` may coincide with (or fall before)
+ // the start of the end segment even though the sum of the candidate segment
+ // heights was computed as sufficient. In that case the float effectively ends at
+ // the boundary of the previous segment, so walk back to the segment that actually
+ // contains `end_y`.
+ while end_idx > start_idx && end_y <= self.segments[end_idx].y.start {
+ end_idx -= 1;
+ }
+
+ // Only subdivide if `end_y` falls strictly within the segment. If it lands on
+ // (or, due to floating point imprecision, beyond) a segment boundary then no
+ // subdivision is needed.
+ if self.segments[end_idx].y.start < end_y && end_y < self.segments[end_idx].y.end {
+ self.subdivide_segment(end_idx, end_y);
+ }
+
+ end_idx
+ }
+ };
+
+ // Update inset for the range of segments that the float is placed in
+ let placed_inset_plus_width = placed_inset + floated_box.width;
+ for segment in &mut self.segments[start_idx..=end_idx] {
+ segment.insets[slot] = placed_inset_plus_width;
+ segment.has_float[slot] = true;
+ }
+
+ // Update last_placed_float
+ self.update_last_placed_float(direction, start_idx..(end_idx + 1));
+
+ PlacedFloatedBox { width: floated_box.width, height: floated_box.height, y: start_y, x_inset: placed_inset }
+ }
+
+ /// Get the end segment of the last float on side(s) specified by the clear parameter (if any)
+ ///
+ /// Returns `None` if no float has been placed on the relevant side(s)
+ fn cleared_segment(&self, clear: Clear) -> Option<usize> {
+ let left_end = self.last_placed_floats[0].end;
+ let right_end = self.last_placed_floats[1].end;
+ match clear {
+ Clear::Left if left_end > 0 => Some(left_end),
+ Clear::Right if right_end > 0 => Some(right_end),
+ Clear::Both if left_end > 0 || right_end > 0 => Some(left_end.max(right_end)),
+ _ => None,
+ }
+ }
+
+ /// Get the bottom of lowest relevant float for the specific clear property
+ pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
+ match clear {
+ Clear::Left => self.clear_bottoms[0],
+ Clear::Right => self.clear_bottoms[1],
+ Clear::Both => match self.clear_bottoms {
+ [Some(l), Some(r)] => Some(l.max(r)),
+ [l, r] => l.or(r),
+ },
+ Clear::None => None,
+ }
+ }
+
+ /// Search for a space suitable for laying out non-floated content into
+ pub fn find_content_slot(
+ &self,
+ min_y: f32,
+ containing_block_insets: [f32; 2],
+ clear: Clear,
+ after: Option<usize>,
+ ) -> ContentSlot {
+ if !self.has_active_floats(min_y) {
+ return ContentSlot {
+ segment_id: None,
+ x: containing_block_insets[0],
+ y: min_y,
+ width: self.available_width - containing_block_insets[0] - containing_block_insets[1],
+ height: f32::INFINITY,
+ };
+ }
+
+ // Clearance clears past the bottom of floats on the relevant side, including
+ // zero-sized floats which occupy no segment
+ let min_y = min_y.max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
+
+ // The min starting segment index
+ let at_least = after.map(|idx| idx + 1).unwrap_or(0);
+ let hwm = at_least.max(self.cleared_segment(clear).map(|idx| idx + 1).unwrap_or(0));
+
+ let start_idx = self
+ .segments
+ .get(hwm..)
+ .and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
+ let start_idx = start_idx.unwrap_or(self.segments.len());
+ let segment = self.segments.get(start_idx);
+ match segment {
+ Some(segment) => {
+ let inset_left = segment.insets[0].max(containing_block_insets[0]);
+ let inset_right = segment.insets[1].max(containing_block_insets[1]);
+ ContentSlot {
+ segment_id: Some(start_idx),
+ x: inset_left,
+ y: segment.y.start.max(min_y),
+ width: self.available_width - inset_left - inset_right,
+ height: f32::INFINITY,
+ }
+ }
+ None => ContentSlot {
+ segment_id: None,
+ x: containing_block_insets[0],
+ y: min_y,
+ width: self.available_width - containing_block_insets[0] - containing_block_insets[1],
+ height: f32::INFINITY,
+ },
+ }
+ }
+
+ /// Search for a space suitable for laying out a box that establishes an independent
+ /// formatting context (whose border box must not overlap floats).
+ ///
+ /// The box's margins are resolved against the containing block's content edges. When there
+ /// are floats beside the box:
+ ///
+ /// - The leading margin (in flow direction) positions the border box's leading edge, but
+ /// may be partially or fully "absorbed" by a float on the leading side (the border edge
+ /// is the further-in of the float edge and the margin-inset containing block edge), and
+ /// a negative leading margin does not move the border edge past the float edge. When no
+ /// float intrudes on the leading side the margin applies as usual, and a negative margin
+ /// may move the border edge outside the containing block.
+ /// - The trailing margin is subtracted from the width an auto width resolves to (except
+ /// for any part of it that overlaps a float on the trailing side). When a float intrudes
+ /// on the trailing side, the trailing margin does not affect whether a box of a given
+ /// width fits in the slot: the trailing margin may overflow the containing block edge.
+ /// When no float intrudes on the trailing side the margin applies as usual, and a
+ /// negative margin lets the border box extend outside the containing block.
+ ///
+ /// When there are no floats beside the box, its (possibly negative) margins apply as usual.
+ pub fn find_bfc_slot(
+ &self,
+ min_y: f32,
+ containing_block_insets: [f32; 2],
+ margins: [f32; 2],
+ direction: Direction,
+ clear: Clear,
+ after: Option<usize>,
+ ) -> BfcSlot {
+ let margin_insets = [containing_block_insets[0] + margins[0], containing_block_insets[1] + margins[1]];
+ let no_float_width = self.available_width - margin_insets[0] - margin_insets[1];
+ let no_float_slot = BfcSlot {
+ segment_id: None,
+ x: margin_insets[0],
+ y: min_y,
+ border_width: no_float_width,
+ stretch_width: no_float_width,
+ };
+
+ if !self.has_active_floats(min_y) {
+ return no_float_slot;
+ }
+
+ // Clearance clears past the bottom of floats on the relevant side, including
+ // zero-sized floats which occupy no segment
+ let min_y = min_y.max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
+
+ // The min starting segment index
+ let at_least = after.map(|idx| idx + 1).unwrap_or(0);
+ let hwm = at_least.max(self.cleared_segment(clear).map(|idx| idx + 1).unwrap_or(0));
+
+ let start_idx = self
+ .segments
+ .get(hwm..)
+ .and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
+ let start_idx = start_idx.unwrap_or(self.segments.len());
+ match self.segments.get(start_idx) {
+ Some(segment) => {
+ let lead = match direction {
+ Direction::Ltr => 0,
+ Direction::Rtl => 1,
+ };
+ let trail = 1 - lead;
+ let has_lead_float = segment.has_float[lead];
+ let has_trail_float = segment.has_float[trail];
+ let mut fit_insets = [0.0; 2];
+ let mut stretch_insets = [0.0; 2];
+ fit_insets[lead] =
+ if has_lead_float { segment.insets[lead].max(margin_insets[lead]) } else { margin_insets[lead] };
+ stretch_insets[lead] = fit_insets[lead];
+ fit_insets[trail] = if has_trail_float {
+ segment.insets[trail].max(containing_block_insets[trail])
+ } else {
+ // A positive trailing margin may overflow the containing block edge (it does
+ // not affect fit), but a negative one widens the space for the border box
+ margin_insets[trail].min(containing_block_insets[trail])
+ };
+ stretch_insets[trail] = if has_trail_float {
+ segment.insets[trail].max(margin_insets[trail])
+ } else {
+ margin_insets[trail]
+ };
+ BfcSlot {
+ segment_id: Some(start_idx),
+ x: fit_insets[0],
+ y: segment.y.start.max(min_y),
+ border_width: self.available_width - fit_insets[0] - fit_insets[1],
+ stretch_width: self.available_width - stretch_insets[0] - stretch_insets[1],
+ }
+ }
+ // Below all floats
+ None => BfcSlot {
+ y: self.segments.last().map(|segment| segment.y.end).unwrap_or(min_y).max(min_y),
+ ..no_float_slot
+ },
+ }
+ }
+}
+
+/// Context for computing the intrinsic width contribution of a set of floats
+pub struct FloatIntrinsicWidthCalculator {
+ /// The available width of the container
+ available_width: AvailableSpace,
+ /// The running sums of the widths of adjacent uncleared floats on each side (left, right)
+ side_sums: [f32; 2],
+ /// The running total intrinsic width contribution
+ contribution: f32,
+ /// The widest single float (the floats' min-content contribution)
+ widest: f32,
+}
+
+impl FloatIntrinsicWidthCalculator {
+ /// Create a new `FloatIntrinsicWidthCalculator`
+ pub fn new(available_width: AvailableSpace) -> Self {
+ Self { available_width, side_sums: [0.0; 2], contribution: 0.0, widest: 0.0 }
+ }
+
+ /// Add a float to the computation
+ pub fn add_float(&mut self, width: f32, direction: FloatDirection, clear: Clear) {
+ match self.available_width {
+ // Definite available width means the container is being fit-content sized
+ // (e.g. it is itself a float being shrink-to-fit sized). The floats' max-content
+ // contribution (widths summed) is clamped by the available width in `result`.
+ AvailableSpace::Definite(_) | AvailableSpace::MaxContent => {
+ // A float that clears a side is placed below the floats on that side, so its
+ // width does not accumulate with theirs.
+ if matches!(clear, Clear::Left | Clear::Both) {
+ self.side_sums[0] = 0.0;
+ }
+ if matches!(clear, Clear::Right | Clear::Both) {
+ self.side_sums[1] = 0.0;
+ }
+ self.side_sums[direction as usize] += width;
+ self.contribution = self.contribution.max(self.side_sums[0] + self.side_sums[1]);
+ }
+ AvailableSpace::MinContent => self.contribution = self.contribution.max(width),
+ };
+ self.widest = self.widest.max(width);
+ }
+
+ /// Get the computed float contribution to intrinsic width
+ pub fn result(&self) -> f32 {
+ match self.available_width {
+ // Fit-content sizing: clamp the max-content contribution between the available
+ // width and the min-content contribution (floats narrow by wrapping onto new
+ // bands, but never below the widest single float).
+ AvailableSpace::Definite(available_width) => self.contribution.min(available_width).max(self.widest),
+ _ => self.contribution,
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/alignment.rs b/vendor/taffy/src/compute/grid/alignment.rs
new file mode 100644
index 00000000..5906a43c
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/alignment.rs
@@ -0,0 +1,536 @@
+//! Alignment of tracks and final positioning of items
+use super::types::GridTrack;
+use crate::compute::common::alignment::{
+ apply_alignment_fallback, compute_alignment_offset, resolve_self_alignment_safety,
+};
+use crate::geometry::{InBothAbsAxis, Line, Point, Rect, Size};
+use crate::style::{
+ AlignContent, AlignItems, AlignItemsKeyword, AlignSelf, AvailableSpace, CoreStyle, GridItemStyle, Overflow,
+ Position,
+};
+use crate::tree::{Layout, LayoutPartialTreeExt, NodeId, OofCandidates, SizingMode};
+use crate::util::sys::f32_max;
+use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
+
+#[cfg(feature = "content_size")]
+use crate::compute::common::scrollable_overflow::compute_scrollable_overflow_contribution;
+use crate::compute::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
+use crate::{AbsoluteAxis, BoxSizing, Direction, LayoutGridContainer};
+
+/// Align the grid tracks within the grid according to the align-content (rows) or
+/// justify-content (columns) property. This only does anything if the size of the
+/// grid is not equal to the size of the grid container in the axis being aligned.
+pub(super) fn align_tracks(
+ grid_container_content_box_size: f32,
+ padding: Line<f32>,
+ border: Line<f32>,
+ tracks: &mut [GridTrack],
+ track_alignment_style: AlignContent,
+ axis_is_reversed: bool,
+) {
+ let used_size: f32 = tracks.iter().map(|track| track.base_size).sum();
+ let free_space = grid_container_content_box_size - used_size;
+ let origin = padding.start + border.start;
+
+ // Count the number of non-collapsed tracks (not counting gutters)
+ let num_tracks = tracks.iter().skip(1).step_by(2).filter(|track| !track.is_collapsed).count();
+
+ // Grid layout treats gaps as full tracks rather than applying them at alignment so we
+ // simply pass zero here. Grid layout is never reversed.
+ let gap = 0.0;
+ let layout_is_reversed = false;
+ let track_alignment = apply_alignment_fallback(free_space, num_tracks, track_alignment_style);
+ let track_alignment = if axis_is_reversed { track_alignment.reversed() } else { track_alignment };
+
+ // If every track is collapsed then no track receives the alignment offset below, but the
+ // grid's lines should still be aligned within the container (e.g. at the inline-start edge
+ // for RTL), so apply the offset to the origin instead.
+ let empty_grid_offset = if num_tracks == 0 {
+ compute_alignment_offset(free_space, num_tracks, gap, track_alignment, layout_is_reversed, true)
+ } else {
+ 0.0
+ };
+
+ // Compute offsets. Tracks are stored in logical order; when the axis is reversed (RTL)
+ // physical offsets are assigned right-to-left by iterating the tracks in reverse.
+ let mut total_offset = origin + empty_grid_offset;
+ let mut seen_non_collapsed_track = false;
+ let mut position_track = |i: usize, track: &mut GridTrack| {
+ // Odd tracks are gutters (but slices are zero-indexed, so odd tracks have even indices)
+ let is_gutter = i % 2 == 0;
+ let is_non_collapsed_track = !is_gutter && !track.is_collapsed;
+
+ // Alignment offsets should be applied only to non-collapsed tracks.
+ let is_first = is_non_collapsed_track && !seen_non_collapsed_track;
+
+ let offset = if is_non_collapsed_track {
+ compute_alignment_offset(free_space, num_tracks, gap, track_alignment, layout_is_reversed, is_first)
+ } else {
+ 0.0
+ };
+
+ track.offset = total_offset + offset;
+ total_offset = total_offset + offset + track.base_size;
+ if is_non_collapsed_track {
+ seen_non_collapsed_track = true;
+ }
+ };
+ if axis_is_reversed {
+ tracks.iter_mut().rev().enumerate().for_each(|(i, track)| position_track(i, track));
+ } else {
+ tracks.iter_mut().enumerate().for_each(|(i, track)| position_track(i, track));
+ }
+}
+
+/// Align and size a grid item into it's final position
+#[allow(clippy::too_many_arguments)]
+pub(super) fn align_and_position_item(
+ tree: &mut impl LayoutGridContainer,
+ node: NodeId,
+ order: u32,
+ grid_area: Rect<f32>,
+ // Percentage basis for the item's styles. Grid passes the grid area size; grid lanes (css-grid-3) items
+ // have the container's content box as their containing block in the stacking axis.
+ containing_block_size: Size<f32>,
+ container_alignment_styles: InBothAbsAxis<AlignItems>,
+ baseline_shim: f32,
+ direction: Direction,
+ container_border_box_width: f32,
+ container_border: Rect<f32>,
+ #[cfg(feature = "content_size")] container_is_scroll_container: bool,
+ bubbled_candidates: &mut OofCandidates,
+) -> (Rect<f32>, f32, f32) {
+ let grid_area_size = Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top };
+
+ let style = tree.get_grid_child_style(node);
+
+ let overflow = style.overflow();
+ #[cfg(feature = "content_size")]
+ let contain = style.contain();
+ let scrollbar_width = style.scrollbar_width();
+ let aspect_ratio = style.aspect_ratio();
+ let is_replaced = style.is_replaced();
+ // Fall back to the container's justify-items/align-items if unset (`None`), and then resolve
+ // writing-mode-relative self-start/self-end keywords against the item's own direction.
+ // The horizontal axis is the inline axis (Taffy only supports horizontal-tb); the vertical
+ // (block) axis resolves them to plain start/end.
+ let item_direction = style.direction();
+ let justify_self = style.justify_self().unwrap_or(container_alignment_styles.horizontal).resolve_self_relative(
+ item_direction,
+ direction,
+ true,
+ );
+ let align_self = style.align_self().unwrap_or(container_alignment_styles.vertical).resolve_self_relative(
+ item_direction,
+ direction,
+ false,
+ );
+
+ let position = style.position();
+ let inset_horizontal = style
+ .inset()
+ .horizontal_components()
+ .map(|size| size.resolve_to_option(containing_block_size.width, |val, basis| tree.calc(val, basis)));
+ let inset_vertical = style
+ .inset()
+ .vertical_components()
+ .map(|size| size.resolve_to_option(containing_block_size.height, |val, basis| tree.calc(val, basis)));
+ let padding = style
+ .padding()
+ .map(|p| p.resolve_or_zero(Some(containing_block_size.width), |val, basis| tree.calc(val, basis)));
+ let border = style
+ .border()
+ .map(|p| p.resolve_or_zero(Some(containing_block_size.width), |val, basis| tree.calc(val, basis)));
+ let padding_border_size = (padding + border).sum_axes();
+
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+
+ let size_style = style.size();
+ let inherent_size = size_style
+ .maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let min_size = style
+ .min_size()
+ .maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
+ .maybe_add(box_sizing_adjustment)
+ .or(padding_border_size.map(Some))
+ .maybe_max(padding_border_size)
+ .maybe_apply_aspect_ratio(aspect_ratio);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+
+ // Resolve `normal` alignment (the default if alignment is set on neither the parent or the node itself)
+ // Note: if the child has a preferred aspect ratio but neither width or height are set, then the width is stretched
+ // and the then height is calculated from the width according the aspect ratio
+ // Replaced elements are not stretched: they are sized as for `start`.
+ // See: https://www.w3.org/TR/css-grid-1/#grid-item-sizing
+ let alignment_styles = InBothAbsAxis {
+ horizontal: match justify_self.keyword {
+ AlignItemsKeyword::Normal => {
+ if inherent_size.width.is_some() || size_style.width.is_sizing_keyword() || is_replaced {
+ AlignSelf::START
+ } else {
+ AlignSelf::STRETCH
+ }
+ }
+ _ => justify_self,
+ },
+ vertical: match align_self.keyword {
+ AlignItemsKeyword::Normal => {
+ if inherent_size.height.is_some()
+ || size_style.height.is_sizing_keyword()
+ || aspect_ratio.is_some()
+ || is_replaced
+ {
+ AlignSelf::START
+ } else {
+ AlignSelf::STRETCH
+ }
+ }
+ _ => align_self,
+ },
+ };
+
+ // Note: This is not a bug. It is part of the CSS spec that both horizontal and vertical margins
+ // resolve against the WIDTH of the grid area.
+ let margin = style
+ .margin()
+ .map(|margin| margin.resolve_to_option(containing_block_size.width, |val, basis| tree.calc(val, basis)));
+
+ drop(style);
+
+ let grid_area_minus_item_margins_size = Size {
+ width: grid_area_size.width.maybe_sub(margin.left).maybe_sub(margin.right).max(0.0),
+ height: (grid_area_size.height.maybe_sub(margin.top).maybe_sub(margin.bottom) - baseline_shim).max(0.0),
+ };
+
+ // A size that is a sizing keyword (min-content, max-content, fit-content,
+ // fit-content(...), stretch) either resolves to an exact size or is resolved
+ // by measuring the item under the corresponding available space constraint
+ let keyword_width = inherent_size.width.is_none().then(|| {
+ resolve_sizing_keyword(
+ size_style.width,
+ Some(grid_area_minus_item_margins_size.width),
+ Some(containing_block_size.width),
+ |val, basis| tree.calc(val, basis),
+ )
+ });
+ let keyword_height = inherent_size.height.is_none().then(|| {
+ resolve_sizing_keyword(
+ size_style.height,
+ Some(grid_area_minus_item_margins_size.height),
+ Some(containing_block_size.height),
+ |val, basis| tree.calc(val, basis),
+ )
+ });
+
+ // If both axes need to be measured then resolve them with a single measure call
+ let keyword_measured_size: Size<Option<f32>> = match (&keyword_width, &keyword_height) {
+ (
+ Some(Some(SizingKeywordResolution::Measure(available_width))),
+ Some(Some(SizingKeywordResolution::Measure(available_height))),
+ ) if !position.is_out_of_flow() => tree
+ .measure_child_size_both(
+ node,
+ Size::NONE,
+ containing_block_size.map(Option::Some),
+ Size { width: *available_width, height: *available_height },
+ SizingMode::InherentSize,
+ Line::FALSE,
+ )
+ .map(Option::Some),
+ _ => Size::NONE,
+ };
+
+ // If node is absolutely positioned and width is not set explicitly, then deduce it
+ // from left, right and container_content_box if both are set.
+ let width = inherent_size.width.or_else(|| {
+ // Apply width derived from both the left and right properties of an absolutely
+ // positioned element being set
+ if position.is_out_of_flow() {
+ if let (Some(left), Some(right)) = (inset_horizontal.start, inset_horizontal.end) {
+ return Some(f32_max(grid_area_minus_item_margins_size.width - left - right, 0.0));
+ }
+ }
+
+ if let Some(Some(resolution)) = keyword_width {
+ return Some(match resolution {
+ SizingKeywordResolution::Exact(width) => width,
+ SizingKeywordResolution::Measure(available_width) => keyword_measured_size.width.unwrap_or_else(|| {
+ tree.measure_child_size(
+ node,
+ Size::NONE,
+ containing_block_size.map(Option::Some),
+ Size {
+ width: available_width,
+ height: AvailableSpace::Definite(grid_area_minus_item_margins_size.height),
+ },
+ SizingMode::InherentSize,
+ AbsoluteAxis::Horizontal,
+ Line::FALSE,
+ )
+ }),
+ });
+ }
+
+ // Apply width based on stretch alignment if:
+ // - Alignment style is "stretch"
+ // - The node is not absolutely positioned
+ // - The node does not have auto margins in this axis.
+ if margin.left.is_some()
+ && margin.right.is_some()
+ && alignment_styles.horizontal == AlignSelf::STRETCH
+ && !position.is_out_of_flow()
+ {
+ return Some(grid_area_minus_item_margins_size.width);
+ }
+
+ None
+ });
+
+ // Reapply aspect ratio after stretch and absolute position width adjustments
+ let Size { width, height } = Size { width, height: inherent_size.height }.maybe_apply_aspect_ratio(aspect_ratio);
+
+ let height = height.or_else(|| {
+ if position.is_out_of_flow() {
+ if let (Some(top), Some(bottom)) = (inset_vertical.start, inset_vertical.end) {
+ return Some(f32_max(grid_area_minus_item_margins_size.height - top - bottom, 0.0));
+ }
+ }
+
+ if let Some(Some(resolution)) = keyword_height {
+ return Some(match resolution {
+ SizingKeywordResolution::Exact(height) => height,
+ SizingKeywordResolution::Measure(available_height) => {
+ keyword_measured_size.height.unwrap_or_else(|| {
+ tree.measure_child_size(
+ node,
+ Size { width, height: None },
+ containing_block_size.map(Option::Some),
+ Size {
+ width: width
+ .map(AvailableSpace::Definite)
+ .unwrap_or(AvailableSpace::Definite(grid_area_minus_item_margins_size.width)),
+ height: available_height,
+ },
+ SizingMode::InherentSize,
+ AbsoluteAxis::Vertical,
+ Line::FALSE,
+ )
+ })
+ }
+ });
+ }
+
+ // Apply height based on stretch alignment if:
+ // - Alignment style is "stretch"
+ // - The node is not absolutely positioned
+ // - The node does not have auto margins in this axis.
+ if margin.top.is_some()
+ && margin.bottom.is_some()
+ && alignment_styles.vertical == AlignSelf::STRETCH
+ && !position.is_out_of_flow()
+ {
+ return Some(grid_area_minus_item_margins_size.height);
+ }
+
+ None
+ });
+ // Reapply aspect ratio after stretch and absolute position height adjustments
+ let Size { width, height } = Size { width, height }.maybe_apply_aspect_ratio(aspect_ratio);
+
+ // Clamp size by min and max width/height
+ let Size { width, height } = Size { width, height }.maybe_clamp(min_size, max_size);
+
+ // Layout node
+ let size = if position.is_out_of_flow() && (width.is_none() || height.is_none()) {
+ tree.measure_child_size_both(
+ node,
+ Size { width, height },
+ containing_block_size.map(Option::Some),
+ grid_area_minus_item_margins_size.map(AvailableSpace::Definite),
+ SizingMode::InherentSize,
+ Line::FALSE,
+ )
+ .map(Some)
+ } else {
+ Size { width, height }
+ };
+
+ let mut layout_output = tree.perform_child_layout(
+ node,
+ size,
+ containing_block_size.map(Option::Some),
+ grid_area_minus_item_margins_size.map(AvailableSpace::Definite),
+ SizingMode::InherentSize,
+ Line::FALSE,
+ );
+
+ // Resolve final size
+ let Size { width, height } = size.unwrap_or(layout_output.size).maybe_clamp(min_size, max_size);
+
+ let (x, x_margin) = align_item_within_area(
+ Line { start: grid_area.left, end: grid_area.right },
+ alignment_styles.horizontal,
+ width,
+ position,
+ inset_horizontal,
+ margin.horizontal_components(),
+ 0.0,
+ direction,
+ );
+ let (y, y_margin) = align_item_within_area(
+ Line { start: grid_area.top, end: grid_area.bottom },
+ alignment_styles.vertical,
+ height,
+ position,
+ inset_vertical,
+ margin.vertical_components(),
+ baseline_shim,
+ Direction::Ltr,
+ );
+
+ let scrollbar_size = Size {
+ width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
+ height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
+ };
+
+ let resolved_margin = Rect { left: x_margin.start, right: x_margin.end, top: y_margin.start, bottom: y_margin.end };
+
+ // Bubble out-of-flow candidates from the item's subtree, translating anchors from
+ // item-relative to container-relative coordinates
+ let mut item_candidates = layout_output.oof_candidates.take();
+ if !item_candidates.is_empty() {
+ item_candidates.translate(Point { x, y });
+ bubbled_candidates.append(&mut item_candidates);
+ }
+
+ tree.set_unrounded_layout(
+ node,
+ &Layout {
+ order,
+ location: Point { x, y },
+ size: Size { width, height },
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: layout_output.scrollable_overflow_rect,
+ scrollbar_size,
+ padding,
+ border,
+ margin: resolved_margin,
+ },
+ );
+
+ #[cfg(feature = "content_size")]
+ let contribution = {
+ // Contributions to the container's scrollable overflow rect are measured from the
+ // container's padding-box origin (mirrored for RTL), matching the scrollable overflow region.
+ let contribution_location = if direction.is_rtl() {
+ Point { x: container_border_box_width - (x + width) - container_border.right, y: y - container_border.top }
+ } else {
+ Point { x: x - container_border.left, y: y - container_border.top }
+ };
+ compute_scrollable_overflow_contribution(
+ contribution_location,
+ Size { width, height },
+ layout_output.scrollable_overflow_rect,
+ overflow,
+ contain,
+ container_is_scroll_container,
+ )
+ };
+ #[cfg(not(feature = "content_size"))]
+ let contribution = Rect::ZERO;
+
+ (contribution, y, height)
+}
+
+/// Align and size a grid item along a single axis
+#[allow(clippy::too_many_arguments)]
+pub(super) fn align_item_within_area(
+ grid_area: Line<f32>,
+ alignment_style: AlignSelf,
+ resolved_size: f32,
+ position: Position,
+ inset: Line<Option<f32>>,
+ margin: Line<Option<f32>>,
+ baseline_shim: f32,
+ direction: Direction,
+) -> (f32, Line<f32>) {
+ // Calculate grid area dimension in the axis
+ let non_auto_margin = Line { start: margin.start.unwrap_or(0.0) + baseline_shim, end: margin.end.unwrap_or(0.0) };
+ let grid_area_size = f32_max(grid_area.end - grid_area.start, 0.0);
+ let free_space = f32_max(grid_area_size - resolved_size - non_auto_margin.sum(), 0.0);
+
+ // Expand auto margins to fill available space
+ let auto_margin_count = margin.start.is_none() as u8 + margin.end.is_none() as u8;
+ let auto_margin_size = if auto_margin_count > 0 { free_space / auto_margin_count as f32 } else { 0.0 };
+ let resolved_margin = Line {
+ start: margin.start.unwrap_or(auto_margin_size) + baseline_shim,
+ end: margin.end.unwrap_or(auto_margin_size),
+ };
+
+ let overflows = resolved_size + non_auto_margin.sum() > grid_area_size;
+ let alignment_keyword = resolve_self_alignment_safety(alignment_style, overflows);
+
+ // Compute offset in the axis
+ let alignment_based_offset = match alignment_keyword {
+ // TODO: Add support for baseline alignment. For now we treat it as "start".
+ AlignItemsKeyword::Start
+ | AlignItemsKeyword::FlexStart
+ | AlignItemsKeyword::Baseline
+ | AlignItemsKeyword::Stretch => {
+ if direction.is_rtl() {
+ grid_area_size - resolved_size - resolved_margin.end
+ } else {
+ resolved_margin.start
+ }
+ }
+ AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd => {
+ if direction.is_rtl() {
+ resolved_margin.start
+ } else {
+ grid_area_size - resolved_size - resolved_margin.end
+ }
+ }
+ AlignItemsKeyword::Center => {
+ (grid_area_size - resolved_size + resolved_margin.start - resolved_margin.end) / 2.0
+ }
+ // Normal is resolved, and SelfStart/SelfEnd are resolved to Start/End against
+ // the item's own direction, in `align_and_position_item`.
+ AlignItemsKeyword::Normal | AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd => unreachable!(),
+ };
+
+ let offset_within_area = if position.is_out_of_flow() {
+ match (inset.start, inset.end) {
+ (Some(start), Some(end)) => {
+ if direction.is_rtl() {
+ grid_area_size - end - resolved_size - non_auto_margin.end
+ } else {
+ start + non_auto_margin.start
+ }
+ }
+ (Some(start), None) => start + non_auto_margin.start,
+ (None, Some(end)) => grid_area_size - end - resolved_size - non_auto_margin.end,
+ (None, None) => alignment_based_offset,
+ }
+ } else {
+ alignment_based_offset
+ };
+
+ let mut start = grid_area.start + offset_within_area;
+ if position == Position::Relative {
+ let relative_inset = if direction.is_rtl() {
+ inset.end.map(|pos| -pos).or(inset.start)
+ } else {
+ inset.start.or(inset.end.map(|pos| -pos))
+ };
+ start += relative_inset.unwrap_or(0.0);
+ }
+
+ (start, resolved_margin)
+}
diff --git a/vendor/taffy/src/compute/grid/explicit_grid.rs b/vendor/taffy/src/compute/grid/explicit_grid.rs
new file mode 100644
index 00000000..44de4b45
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/explicit_grid.rs
@@ -0,0 +1,833 @@
+//! Helper functions for initialising GridTrack's from styles
+//! This mainly consists of evaluating GridAutoTracks
+use super::types::{GridTrack, GridTrackKind, TrackCounts};
+use crate::geometry::AbsoluteAxis;
+use crate::style::{LengthPercentage, RepetitionCount, TrackSizingFunction};
+use crate::style_helpers::TaffyAuto;
+use crate::util::sys::{ceil, floor, Vec};
+use crate::util::MaybeMath;
+use crate::util::ResolveOrZero;
+use core::cmp::min;
+
+use super::MAX_GRID_TRACKS;
+use crate::{GenericGridTemplateComponent, GenericRepetition, GridContainerStyle};
+
+/// The auto-repeat fit strategy to use
+pub(crate) enum AutoRepeatStrategy {
+ /// If the grid container has a definite size or max size in the relevant axis:
+ /// - then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow the content
+ /// box of its grid container.
+ MaxRepetitionsThatDoNotOverflow,
+ /// Otherwise, if the grid container has a definite min size in the relevant axis:
+ /// - then the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement
+ MinRepetitionsThatDoOverflow,
+}
+
+/// Compute the number of rows and columns in the explicit grid
+pub(crate) fn compute_explicit_grid_size_in_axis(
+ style: &impl GridContainerStyle,
+ auto_fit_container_size: Option<f32>,
+ auto_fit_strategy: AutoRepeatStrategy,
+ resolve_calc_value: impl Fn(*const (), f32) -> f32,
+ axis: AbsoluteAxis,
+) -> (u16, u16) {
+ let template = match axis {
+ AbsoluteAxis::Horizontal => style.grid_template_columns(),
+ AbsoluteAxis::Vertical => style.grid_template_rows(),
+ };
+ let Some(template) = template else {
+ return (0, 0);
+ };
+
+ // If template contains no tracks, then there are trivially zero explicit tracks
+ let track_count = template.len();
+ if track_count == 0 {
+ return (0, 0);
+ }
+
+ // If there are any repetitions that contains no tracks, then the whole definition should be considered invalid
+ // and we default to no explicit tracks
+ let template_has_repetitions_with_zero_tracks = template.clone().any(|track_def| match track_def {
+ GenericGridTemplateComponent::Single(_) => false,
+ GenericGridTemplateComponent::Repeat(repeat) => repeat.track_count() == 0,
+ });
+ if template_has_repetitions_with_zero_tracks {
+ return (0, 0);
+ }
+
+ // Compute that number of track generated by single track definition and repetitions with a fixed repetition count
+ // (clamping to the maximum track limit to prevent arithmetic overflow)
+ let non_auto_repeating_track_count = template
+ .clone()
+ .fold(0u32, |track_count, track_def| {
+ let additional_tracks = match track_def {
+ GenericGridTemplateComponent::Single(_) => 1u32,
+ GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
+ RepetitionCount::Count(count) => count as u32 * repeat.track_count() as u32,
+ RepetitionCount::AutoFit | RepetitionCount::AutoFill => 0,
+ },
+ };
+ track_count.saturating_add(additional_tracks)
+ })
+ .min(MAX_GRID_TRACKS as u32) as u16;
+
+ let auto_repetition_count: u16 = template.clone().filter(|track_def| track_def.is_auto_repetition()).count() as u16;
+ let all_track_defs_have_fixed_component = template.clone().all(|track_def| match track_def {
+ GenericGridTemplateComponent::Single(sizing_function) => sizing_function.has_fixed_component(),
+ GenericGridTemplateComponent::Repeat(repeat) => {
+ repeat.tracks().all(|sizing_function| sizing_function.has_fixed_component())
+ }
+ });
+
+ let template_is_valid =
+ auto_repetition_count == 0 || (auto_repetition_count == 1 && all_track_defs_have_fixed_component);
+
+ // If the template is invalid because it contains multiple auto-repetition definitions or it combines an auto-repetition
+ // definition with non-fixed-size track sizing functions, then disregard it entirely and default to zero explicit tracks
+ if !template_is_valid {
+ return (0, 0);
+ }
+
+ // If there are no repetitions, then the number of explicit tracks is simply equal to the lengths of the track definition
+ // vector (as each item in the Vec represents one track).
+ if auto_repetition_count == 0 {
+ return (0, non_auto_repeating_track_count);
+ }
+
+ let mut auto_repeat_insertion_point = 0u32;
+ let repetition_definition = template
+ .clone()
+ .find_map(|def| match def {
+ GenericGridTemplateComponent::Single(_) => {
+ auto_repeat_insertion_point = auto_repeat_insertion_point.saturating_add(1);
+ None
+ }
+ GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
+ RepetitionCount::Count(count) => {
+ auto_repeat_insertion_point =
+ auto_repeat_insertion_point.saturating_add(count as u32 * repeat.track_count() as u32);
+ None
+ }
+ RepetitionCount::AutoFit | RepetitionCount::AutoFill => Some(repeat),
+ },
+ })
+ .unwrap();
+ let repetition_definition_iter = repetition_definition.tracks();
+ let repetition_track_count = repetition_definition_iter.len().min(u16::MAX as usize) as u16;
+
+ // Determine the number of repetitions
+ let num_repetitions: u32 = match auto_fit_container_size {
+ None => 1,
+ Some(inner_container_size) => {
+ let parent_size = Some(inner_container_size);
+
+ /// ...treating each track as its max track sizing function if that is definite or as its minimum track sizing function
+ /// otherwise, flooring the max track sizing function by the min track sizing function if both are definite
+ fn track_definite_value(
+ sizing_function: TrackSizingFunction,
+ parent_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> f32 {
+ let max_size = sizing_function.max.definite_value(parent_size, &calc_resolver);
+ let min_size = sizing_function.min.definite_value(parent_size, &calc_resolver);
+ max_size.map(|max| max.maybe_max(min_size)).or(min_size).unwrap()
+ }
+
+ let non_repeating_track_used_space: f32 = template
+ .clone()
+ .map(|track_def| match track_def {
+ GenericGridTemplateComponent::Single(sizing_function) => {
+ track_definite_value(sizing_function, parent_size, &resolve_calc_value)
+ }
+ GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
+ RepetitionCount::Count(count) => {
+ let sum = repeat
+ .tracks()
+ .map(|sizing_function| {
+ track_definite_value(sizing_function, parent_size, &resolve_calc_value)
+ })
+ .sum::<f32>();
+ sum * (count as f32)
+ }
+ RepetitionCount::AutoFit | RepetitionCount::AutoFill => 0.0,
+ },
+ })
+ .sum();
+ let gap_size = style.gap().get_abs(axis).resolve_or_zero(Some(inner_container_size), &resolve_calc_value);
+
+ // Compute the amount of space that a single repetition of the repeated track list takes
+ let per_repetition_track_used_space: f32 = repetition_definition_iter
+ .map(|sizing_function| track_definite_value(sizing_function, parent_size, &resolve_calc_value))
+ .sum::<f32>();
+
+ // We special case the first repetition here because the number of gaps in the first repetition
+ // depends on the number of non-repeating tracks in the template
+ let first_repetition_and_non_repeating_tracks_used_space = non_repeating_track_used_space
+ + per_repetition_track_used_space
+ + ((non_auto_repeating_track_count as u32 + repetition_track_count as u32).saturating_sub(1) as f32
+ * gap_size);
+
+ // If a single repetition already overflows the container then we return 1 as the repetition count
+ // (the number of repetitions is floored at 1)
+ if first_repetition_and_non_repeating_tracks_used_space > inner_container_size {
+ 1u32
+ } else {
+ let per_repetition_gap_used_space = (repetition_track_count as f32) * gap_size;
+ let per_repetition_used_space = per_repetition_track_used_space + per_repetition_gap_used_space;
+ let num_repetition_that_fit = (inner_container_size
+ - first_repetition_and_non_repeating_tracks_used_space)
+ / per_repetition_used_space;
+
+ // If the container size is a preferred or maximum size:
+ // Then we return the maximum number of repetitions that fit into the container without overflowing.
+ // If the container size is a minimum size:
+ // - Then we return the minimum number of repetitions required to overflow the size.
+ //
+ // In all cases we add the additional repetition that was already accounted for in the special-case computation above
+ // Note: as-casts from f32 to u32 saturate, so a huge or infinite number of repetitions
+ // (e.g. due to zero-sized tracks) resolves to u32::MAX and is clamped below
+ match auto_fit_strategy {
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow => {
+ (floor(num_repetition_that_fit) as u32).saturating_add(1)
+ }
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow => {
+ (ceil(num_repetition_that_fit) as u32).saturating_add(1)
+ }
+ }
+ }
+ }
+ };
+
+ // Clamp the number of repetitions based on the auto-repeat's insertion point so that tracks
+ // before it are preserved and tracks after it are truncated in source order.
+ // https://www.w3.org/TR/css-grid-1/#overlarge-grids
+ let remaining_tracks = (MAX_GRID_TRACKS as u32).saturating_sub(auto_repeat_insertion_point);
+ let num_repetitions = if remaining_tracks == 0 {
+ 0
+ } else {
+ let max_repetitions = (remaining_tracks + repetition_track_count as u32 - 1) / repetition_track_count as u32;
+ num_repetitions.clamp(1, max_repetitions) as u16
+ };
+
+ let grid_template_track_count = min(
+ non_auto_repeating_track_count as u32 + (repetition_track_count as u32 * num_repetitions as u32),
+ MAX_GRID_TRACKS as u32,
+ ) as u16;
+ (num_repetitions, grid_template_track_count)
+}
+
+/// Resolve the track sizing functions of explicit tracks, automatically created tracks, and gutters
+/// given a set of track counts and all of the relevant styles
+pub(super) fn initialize_grid_tracks(
+ tracks: &mut Vec<GridTrack>,
+ counts: TrackCounts,
+ style: &impl GridContainerStyle,
+ axis: AbsoluteAxis,
+ auto_repetition_count: u16,
+ track_has_items: impl Fn(usize) -> bool,
+) {
+ // Extract styles
+ let track_template;
+ let auto_tracks;
+ let gap;
+ match axis {
+ AbsoluteAxis::Horizontal => {
+ track_template = style.grid_template_columns();
+ auto_tracks = style.grid_auto_columns();
+ gap = style.gap().width;
+ }
+ AbsoluteAxis::Vertical => {
+ track_template = style.grid_template_rows();
+ auto_tracks = style.grid_auto_rows();
+ gap = style.gap().height;
+ }
+ };
+
+ // Clear vector (in case this is a re-layout), reserve space for all tracks ahead of time to reduce allocations,
+ // and push the initial gutter
+ tracks.clear();
+ tracks.reserve((counts.len() * 2) + 1);
+ tracks.push(GridTrack::gutter(gap));
+
+ let auto_track_count = auto_tracks.len();
+
+ // Create negative implicit tracks
+ if counts.negative_implicit > 0 {
+ if auto_track_count == 0 {
+ let iter = core::iter::repeat(TrackSizingFunction::AUTO);
+ create_implicit_tracks(tracks, counts.negative_implicit, iter, gap)
+ } else {
+ let offset = auto_track_count - (counts.negative_implicit as usize % auto_track_count);
+ let iter = auto_tracks.clone().cycle().skip(offset);
+ create_implicit_tracks(tracks, counts.negative_implicit, iter, gap)
+ }
+ }
+
+ let mut current_track_index = (counts.negative_implicit) as usize;
+
+ // The maximum index up to which explicit tracks may be created. The explicit track count is clamped
+ // to MAX_GRID_TRACKS, so track creation from the template must be truncated to match.
+ let explicit_track_limit = (counts.negative_implicit + counts.explicit) as usize;
+
+ // Create explicit tracks
+ // An explicit check against the count (rather than just relying on track_template being empty) is required here
+ // because a count of zero can result from the track_template being invalid, in which case it should be ignored.
+ if counts.explicit > 0 {
+ if let Some(track_template) = track_template {
+ track_template.for_each(|track_sizing_function| {
+ match track_sizing_function {
+ GenericGridTemplateComponent::Single(sizing_function) => {
+ if current_track_index < explicit_track_limit {
+ tracks.push(GridTrack::new(
+ sizing_function.min_sizing_function(),
+ sizing_function.max_sizing_function(),
+ ));
+ tracks.push(GridTrack::gutter(gap));
+ current_track_index += 1;
+ }
+ }
+ GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
+ RepetitionCount::Count(count) => {
+ let repeated_track_count = (repeat.track_count() as usize * count as usize)
+ .min(explicit_track_limit - current_track_index);
+ let track_iter = repeat.tracks();
+ let track_iter = track_iter.cycle().take(repeated_track_count);
+ track_iter.for_each(|sizing_function| {
+ tracks.push(GridTrack::new(
+ sizing_function.min_sizing_function(),
+ sizing_function.max_sizing_function(),
+ ));
+ tracks.push(GridTrack::gutter(gap));
+ current_track_index += 1;
+ });
+ }
+ RepetitionCount::AutoFit | RepetitionCount::AutoFill => {
+ let auto_repeated_track_count = (repeat.track_count() as usize
+ * auto_repetition_count as usize)
+ .min(explicit_track_limit - current_track_index);
+ let iter = repeat.tracks().cycle();
+ for track_def in iter.take(auto_repeated_track_count) {
+ let mut track =
+ GridTrack::new(track_def.min_sizing_function(), track_def.max_sizing_function());
+ let mut gutter = GridTrack::gutter(gap);
+
+ // Auto-fit tracks that don't contain should be collapsed.
+ if repeat.count() == RepetitionCount::AutoFit && !track_has_items(current_track_index) {
+ track.collapse();
+ gutter.collapse();
+ }
+
+ tracks.push(track);
+ tracks.push(gutter);
+
+ current_track_index += 1;
+ }
+
+ // Is this auto-repeat at the very end of the track list?
+ let is_last = current_track_index == counts.len();
+
+ // When collapsing auto-fit tracks (in the loop just above), we collapse the gutter after collapsed
+ // tracks but not the gutter before. This is correct so long as there is another non-collapsed track
+ // somewhere in the track list after the collapsed track.
+ //
+ // However, if the auto-fit repeat is at the very end of the track list, then there will be no such track.
+ // In this case we need to iterate backwards through the track list until we find a non-collapsed track and
+ // collapse the gutter just after that track.
+ //
+ // As all of the other tracks and gutters we find along the way will already be collapsed, we simplify the
+ // implementation to collapsing all tracks and gutters until we find the first non-collapsed track.
+ if repeat.count() == RepetitionCount::AutoFit && is_last {
+ for previous_track in tracks.iter_mut().rev() {
+ if previous_track.kind == GridTrackKind::Track && !previous_track.is_collapsed {
+ break;
+ }
+ previous_track.collapse();
+ }
+ }
+ }
+ },
+ }
+ });
+ }
+ }
+
+ let grid_area_tracks = (counts.negative_implicit + counts.explicit) - current_track_index as u16;
+
+ // Create positive implicit tracks
+ if auto_track_count == 0 {
+ let iter = core::iter::repeat(TrackSizingFunction::AUTO);
+ create_implicit_tracks(tracks, counts.positive_implicit + grid_area_tracks, iter, gap)
+ } else {
+ let iter = auto_tracks.clone().cycle();
+ create_implicit_tracks(tracks, counts.positive_implicit + grid_area_tracks, iter, gap)
+ }
+
+ // Mark first and last grid lines as collapsed
+ tracks.first_mut().unwrap().collapse();
+ tracks.last_mut().unwrap().collapse();
+}
+
+/// Utility function for repeating logic of creating implicit tracks
+fn create_implicit_tracks(
+ tracks: &mut Vec<GridTrack>,
+ count: u16,
+ mut auto_tracks_iter: impl Iterator<Item = TrackSizingFunction>,
+ gap: LengthPercentage,
+) {
+ for _ in 0..count {
+ let track_def = auto_tracks_iter.next().unwrap();
+ tracks.push(GridTrack::new(track_def.min_sizing_function(), track_def.max_sizing_function()));
+ tracks.push(GridTrack::gutter(gap));
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::compute_explicit_grid_size_in_axis;
+ use super::initialize_grid_tracks;
+ use crate::compute::grid::explicit_grid::AutoRepeatStrategy;
+ use crate::compute::grid::types::GridTrackKind;
+ use crate::compute::grid::types::TrackCounts;
+ use crate::compute::grid::util::*;
+ use crate::geometry::AbsoluteAxis;
+ use crate::prelude::*;
+ use crate::sys::DefaultCheapStr;
+
+ #[test]
+ fn explicit_grid_sizing_no_repeats() {
+ let grid_style = (600.0, 600.0, 2, 4).into_grid();
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 2);
+ assert_eq!(row_count, 4);
+ assert_eq!(auto_col_reps, 0);
+ assert_eq!(auto_row_reps, 0);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_exact_fit() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(120.0), height: length(80.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 3);
+ assert_eq!(row_count, 4);
+ assert_eq!(auto_col_reps, 3);
+ assert_eq!(auto_row_reps, 4);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_non_exact_fit() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(140.0), height: length(90.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 3);
+ assert_eq!(row_count, 4);
+ assert_eq!(auto_col_reps, 3);
+ assert_eq!(auto_row_reps, 4);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_min_size_exact_fit() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ min_size: Size { width: length(120.0), height: length(80.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ ..Default::default()
+ };
+ let inner_container_size = Size { width: Some(120.0), height: Some(80.0) };
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 3);
+ assert_eq!(row_count, 4);
+ assert_eq!(auto_col_reps, 3);
+ assert_eq!(auto_row_reps, 4);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_min_size_non_exact_fit() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ min_size: Size { width: length(140.0), height: length(90.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ ..Default::default()
+ };
+ let inner_container_size = Size { width: Some(140.0), height: Some(90.0) };
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 4);
+ assert_eq!(row_count, 5);
+ assert_eq!(auto_col_reps, 4);
+ assert_eq!(auto_row_reps, 5);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_multiple_repeated_tracks() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(140.0), height: length(100.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0), length(20.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0), length(10.0)])],
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 4); // 2 repetitions * 2 repeated tracks = 4 tracks in total
+ assert_eq!(row_count, 6); // 3 repetitions * 2 repeated tracks = 4 tracks in total
+ assert_eq!(auto_col_reps, 2);
+ assert_eq!(auto_row_reps, 3);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_auto_fill_gap() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(140.0), height: length(100.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ gap: length(20.0),
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 2); // 2 tracks + 1 gap
+ assert_eq!(row_count, 3); // 3 tracks + 2 gaps
+ assert_eq!(auto_col_reps, 2);
+ assert_eq!(auto_row_reps, 3);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_no_defined_size() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ grid_template_columns: vec![repeat(AutoFill, vec![length(40.0), percent(0.5), length(20.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ gap: length(20.0),
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 3);
+ assert_eq!(row_count, 1);
+ assert_eq!(auto_col_reps, 1);
+ assert_eq!(auto_row_reps, 1);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_mix_repeated_and_non_repeated() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(140.0), height: length(100.0) },
+ grid_template_columns: vec![length(20.0), repeat(AutoFill, vec![length(40.0)])],
+ grid_template_rows: vec![length(40.0), repeat(AutoFill, vec![length(20.0)])],
+ gap: length(20.0),
+ ..Default::default()
+ };
+ let preferred_size = grid_style.size.map(|s| s.into_option());
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ preferred_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 3); // 3 tracks + 2 gaps
+ assert_eq!(row_count, 2); // 2 tracks + 1 gap
+ assert_eq!(auto_col_reps, 2);
+ assert_eq!(auto_row_reps, 1);
+ }
+
+ #[test]
+ fn explicit_grid_sizing_mix_with_padding() {
+ use RepetitionCount::AutoFill;
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ size: Size { width: length(120.0), height: length(120.0) },
+ padding: Rect { left: length(10.0), right: length(10.0), top: length(20.0), bottom: length(20.0) },
+ grid_template_columns: vec![repeat(AutoFill, vec![length(20.0)])],
+ grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
+ ..Default::default()
+ };
+ let inner_container_size = Size { width: Some(100.0), height: Some(80.0) };
+ let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Horizontal),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ inner_container_size.get_abs(AbsoluteAxis::Vertical),
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Vertical,
+ );
+ assert_eq!(col_count, 5); // 40px horizontal padding
+ assert_eq!(row_count, 4); // 20px vertical padding
+ assert_eq!(auto_col_reps, 5);
+ assert_eq!(auto_row_reps, 4);
+ }
+
+ #[test]
+ fn auto_repeat_clamping_preserves_template_source_order() {
+ use RepetitionCount::{AutoFill, Count};
+
+ let auto_repeat_first: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ grid_template_columns: vec![repeat(AutoFill, vec![length(2.0)]), repeat(Count(10_000), vec![length(37.0)])],
+ ..Default::default()
+ };
+ let (repetitions, track_count) = compute_explicit_grid_size_in_axis(
+ &auto_repeat_first,
+ None,
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ assert_eq!((repetitions, track_count), (1, 10_000));
+ let mut tracks = Vec::new();
+ initialize_grid_tracks(
+ &mut tracks,
+ TrackCounts::from_raw(0, track_count, 0),
+ &auto_repeat_first,
+ AbsoluteAxis::Horizontal,
+ repetitions,
+ |_| false,
+ );
+ assert_eq!(tracks[1].min_track_sizing_function, MinTrackSizingFunction::from_length(2.0));
+ assert_eq!(tracks[3].min_track_sizing_function, MinTrackSizingFunction::from_length(37.0));
+
+ let auto_repeat_last: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ grid_template_columns: vec![repeat(Count(10_000), vec![length(37.0)]), repeat(AutoFill, vec![length(2.0)])],
+ ..Default::default()
+ };
+ let (repetitions, track_count) = compute_explicit_grid_size_in_axis(
+ &auto_repeat_last,
+ None,
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ assert_eq!((repetitions, track_count), (0, 10_000));
+ }
+
+ #[test]
+ fn explicit_track_count_accumulation_saturates() {
+ use RepetitionCount::{AutoFill, Count};
+
+ let repeated_tracks = vec![length(1.0); 32_769];
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ grid_template_columns: vec![
+ repeat(Count(u16::MAX), repeated_tracks.clone()),
+ repeat(Count(u16::MAX), repeated_tracks),
+ repeat(AutoFill, vec![length(1.0)]),
+ ],
+ ..Default::default()
+ };
+ let result = compute_explicit_grid_size_in_axis(
+ &grid_style,
+ None,
+ AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ |_, _| 42.42,
+ AbsoluteAxis::Horizontal,
+ );
+ assert_eq!(result, (0, 10_000));
+ }
+
+ #[test]
+ fn test_initialize_grid_tracks() {
+ let minpx0 = MinTrackSizingFunction::from_length(0.0);
+ let minpx20 = MinTrackSizingFunction::from_length(20.0);
+ let minpx100 = MinTrackSizingFunction::from_length(100.0);
+
+ let maxpx0 = MaxTrackSizingFunction::from_length(0.0);
+ let maxpx20 = MaxTrackSizingFunction::from_length(20.0);
+ let maxpx100 = MaxTrackSizingFunction::from_length(100.0);
+
+ // Setup test
+ let grid_style: Style<DefaultCheapStr> = Style {
+ display: Display::Grid,
+ gap: length(20.0),
+ grid_template_columns: vec![length(100.0), minmax(length(100.0), fr(2.0)), fr(1.0)],
+ grid_auto_columns: vec![auto(), length(100.0)],
+ ..Default::default()
+ };
+ let track_counts = TrackCounts {
+ negative_implicit: 3,
+ explicit: grid_style.grid_template_columns.len() as u16,
+ positive_implicit: 3,
+ };
+
+ // Call function
+ let mut tracks = Vec::new();
+ initialize_grid_tracks(&mut tracks, track_counts, &grid_style, AbsoluteAxis::Horizontal, 0, |_| false);
+
+ // Assertions
+ let expected = vec![
+ // Gutter
+ (GridTrackKind::Gutter, minpx0, maxpx0),
+ // Negative implicit tracks
+ (GridTrackKind::Track, minpx100, maxpx100),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, auto(), auto()),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, minpx100, maxpx100),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ // Explicit tracks
+ (GridTrackKind::Track, minpx100, maxpx100),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, minpx100, MaxTrackSizingFunction::from_fr(2.0)), // Note: separate min-max functions
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, auto(), MaxTrackSizingFunction::from_fr(1.0)), // Note: min sizing function of flex sizing functions is AUTO
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ // Positive implicit tracks
+ (GridTrackKind::Track, auto(), auto()),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, minpx100, maxpx100),
+ (GridTrackKind::Gutter, minpx20, maxpx20),
+ (GridTrackKind::Track, auto(), auto()),
+ (GridTrackKind::Gutter, minpx0, maxpx0),
+ ];
+
+ assert_eq!(tracks.len(), expected.len(), "Number of tracks doesn't match");
+
+ for (idx, (actual, (kind, min, max))) in tracks.into_iter().zip(expected).enumerate() {
+ assert_eq!(actual.kind, kind, "Track {idx} (0-based index)");
+ assert_eq!(actual.min_track_sizing_function, min, "Track {idx} (0-based index)");
+ assert_eq!(actual.max_track_sizing_function, max, "Track {idx} (0-based index)");
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/implicit_grid.rs b/vendor/taffy/src/compute/grid/implicit_grid.rs
new file mode 100644
index 00000000..2b12a72b
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/implicit_grid.rs
@@ -0,0 +1,249 @@
+//! This module is not required for spec compliance, but is used as a performance optimisation
+//! to reduce the number of allocations required when creating a grid.
+use crate::geometry::Line;
+use crate::style::{GenericGridPlacement, OriginZeroGridPlacement};
+use core::cmp::{max, min};
+
+use super::types::TrackCounts;
+use super::{ItemPlacement, OriginZeroLine, MAX_OZ_LINE, MIN_OZ_LINE};
+
+/// Estimate the number of rows and columns in the grid
+/// This is used as a performance optimisation to pre-size vectors and reduce allocations. It also forms a necessary step
+/// in the auto-placement
+/// - The estimates for the explicit and negative implicit track counts are exact.
+/// - However, the estimates for the positive explicit track count is a lower bound as auto-placement can affect this
+/// in ways which are impossible to predict until the auto-placement algorithm is run.
+///
+/// Note that this function internally mixes use of grid track numbers and grid line numbers
+pub(crate) fn compute_grid_size_estimate(
+ explicit_col_count: u16,
+ explicit_row_count: u16,
+ placements: &[ItemPlacement],
+) -> (TrackCounts, TrackCounts) {
+ // Iterate over children, producing an estimate of the min and max grid lines (in origin-zero coordinates where)
+ // along with the span of each item
+ let (col_min, col_max, col_max_span, row_min, row_max, row_max_span) = get_known_child_positions(placements);
+
+ // Compute *track* count estimates for each axis from:
+ // - The explicit track counts
+ // - The origin-zero coordinate min and max grid line variables
+ let negative_implicit_inline_tracks = col_min.implied_negative_implicit_tracks();
+ let explicit_inline_tracks = explicit_col_count;
+ let mut positive_implicit_inline_tracks = col_max.implied_positive_implicit_tracks(explicit_col_count);
+ let negative_implicit_block_tracks = row_min.implied_negative_implicit_tracks();
+ let explicit_block_tracks = explicit_row_count;
+ let mut positive_implicit_block_tracks = row_max.implied_positive_implicit_tracks(explicit_row_count);
+
+ // In each axis, adjust positive track estimate if any items have a span that does not fit within
+ // the total number of tracks in the estimate
+ let tot_inline_tracks = negative_implicit_inline_tracks + explicit_inline_tracks + positive_implicit_inline_tracks;
+ if tot_inline_tracks < col_max_span {
+ positive_implicit_inline_tracks = col_max_span - explicit_inline_tracks - negative_implicit_inline_tracks;
+ }
+
+ let tot_block_tracks = negative_implicit_block_tracks + explicit_block_tracks + positive_implicit_block_tracks;
+ if tot_block_tracks < row_max_span {
+ positive_implicit_block_tracks = row_max_span - explicit_block_tracks - negative_implicit_block_tracks;
+ }
+
+ let column_counts =
+ TrackCounts::from_raw(negative_implicit_inline_tracks, explicit_inline_tracks, positive_implicit_inline_tracks);
+
+ let row_counts =
+ TrackCounts::from_raw(negative_implicit_block_tracks, explicit_block_tracks, positive_implicit_block_tracks);
+
+ (column_counts, row_counts)
+}
+
+/// Iterate over the children's `grid-row`/`grid-column` styles (named lines resolved), producing an estimate of the
+/// min and max grid *lines* along with the span of each item
+///
+/// Min and max grid lines are returned in origin-zero coordinates)
+/// The span is measured in tracks spanned
+fn get_known_child_positions(
+ placements: &[ItemPlacement],
+) -> (OriginZeroLine, OriginZeroLine, u16, OriginZeroLine, OriginZeroLine, u16) {
+ let (mut col_min, mut col_max, mut col_max_span) = (OriginZeroLine(0), OriginZeroLine(0), 0);
+ let (mut row_min, mut row_max, mut row_max_span) = (OriginZeroLine(0), OriginZeroLine(0), 0);
+ placements.iter().for_each(|placement| {
+ // Note: that the children reference the lines in between (and around) the tracks not tracks themselves,
+ // and thus we must subtract 1 to get an accurate estimate of the number of tracks
+ let (child_col_min, child_col_max, child_col_span) = child_min_line_max_line_span(placement.horizontal);
+ let (child_row_min, child_row_max, child_row_span) = child_min_line_max_line_span(placement.vertical);
+
+ col_min = min(col_min, child_col_min);
+ col_max = max(col_max, child_col_max);
+ col_max_span = max(col_max_span, child_col_span);
+ row_min = min(row_min, child_row_min);
+ row_max = max(row_max, child_row_max);
+ row_max_span = max(row_max_span, child_row_span);
+ });
+
+ (col_min, col_max, col_max_span, row_min, row_max, row_max_span)
+}
+
+/// Helper function for `compute_grid_size_estimate`
+/// Produces a conservative estimate of the greatest and smallest grid lines used by a single grid item
+///
+/// Values are returned in origin-zero coordinates
+#[inline]
+fn child_min_line_max_line_span(oz_line: Line<OriginZeroGridPlacement>) -> (OriginZeroLine, OriginZeroLine, u16) {
+ use GenericGridPlacement::*;
+
+ // 8.3.1. Grid Placement Conflict Handling
+ // A. If the placement for a grid item contains two lines, and the start line is further end-ward than the end line, swap the two lines.
+ // B. If the start line is equal to the end line, remove the end line.
+ // C. If the placement contains two spans, remove the one contributed by the end grid-placement property.
+ // D. If the placement contains only a span for a named line, replace it with a span of 1.
+
+ let min = match (oz_line.start, oz_line.end) {
+ // Both tracks specified
+ (Line(track1), Line(track2)) => {
+ // See rules A and B above
+ if track1 == track2 {
+ track1
+ } else {
+ min(track1, track2)
+ }
+ }
+
+ // Start track specified
+ (Line(track), Auto) => track,
+ (Line(track), Span(_)) => track,
+
+ // End track specified
+ // An auto start with a definite end resolves to a span of 1 ending at that line
+ (Auto, Line(track)) => track - 1,
+ (Span(span), Line(track)) => track - span,
+
+ // Only spans or autos
+ // We ignore spans here by returning 0 which never effect the estimate as these are accounted for separately
+ (Auto | Span(_), Auto | Span(_)) => OriginZeroLine(0),
+ };
+
+ let max = match (oz_line.start, oz_line.end) {
+ // Both tracks specified
+ (Line(track1), Line(track2)) => {
+ // See rules A and B above
+ if track1 == track2 {
+ track1 + 1
+ } else {
+ max(track1, track2)
+ }
+ }
+
+ // Start track specified
+ (Line(track), Auto) => track + 1,
+ (Line(track), Span(span)) => track + span,
+
+ // End track specified
+ (Auto, Line(track)) => track,
+ (Span(_), Line(track)) => track,
+
+ // Only spans or autos
+ // We ignore spans here by returning 0 which never effect the estimate as these are accounted for separately
+ (Auto | Span(_), Auto | Span(_)) => OriginZeroLine(0),
+ };
+
+ // Calculate span only for indefinitely placed items as we don't need for other items (whose required space will
+ // be taken into account by min and max)
+ let span = match (oz_line.start, oz_line.end) {
+ (Auto | Span(_), Auto | Span(_)) => oz_line.indefinite_span(),
+ _ => 1,
+ };
+
+ // Clamp the min and max lines into the limited grid so that the estimated implicit track counts
+ // stay within the maximum track limit (https://www.w3.org/TR/css-grid-1/#overlarge-grids).
+ // This matches the clamping of the actual item placements performed during placement.
+ let clamped_min = OriginZeroLine(min.0.max(MIN_OZ_LINE));
+ let clamped_max = OriginZeroLine(max.0.min(MAX_OZ_LINE));
+
+ (clamped_min, clamped_max, span)
+}
+
+#[allow(clippy::bool_assert_comparison)]
+#[cfg(test)]
+mod tests {
+ mod test_child_min_max_line {
+ use super::super::child_min_line_max_line_span;
+ use super::super::OriginZeroLine;
+ use crate::geometry::Line;
+ use crate::style::GridPlacement;
+ use crate::style_helpers::*;
+
+ #[test]
+ fn child_min_max_line_auto() {
+ let (min_col, max_col, span) = child_min_line_max_line_span(
+ Line::<GridPlacement<String>> { start: line(5), end: span(6) }.into_origin_zero_ignoring_named(6),
+ );
+ assert_eq!(min_col, OriginZeroLine(4));
+ assert_eq!(max_col, OriginZeroLine(10));
+ assert_eq!(span, 1);
+ }
+
+ #[test]
+ fn child_min_max_line_negative_track() {
+ let (min_col, max_col, span) = child_min_line_max_line_span(
+ Line::<GridPlacement<String>> { start: line(-5), end: span(3) }.into_origin_zero_ignoring_named(6),
+ );
+ assert_eq!(min_col, OriginZeroLine(2));
+ assert_eq!(max_col, OriginZeroLine(5));
+ assert_eq!(span, 1);
+ }
+ }
+
+ mod test_initial_grid_sizing {
+ use super::super::{compute_grid_size_estimate, TrackCounts};
+ use crate::compute::grid::util::test_helpers::*;
+ use crate::compute::grid::NamedLineResolver;
+ use crate::style_helpers::*;
+ use crate::Style;
+
+ fn estimate(
+ explicit_col_count: u16,
+ explicit_row_count: u16,
+ child_styles: &[Style],
+ ) -> (TrackCounts, TrackCounts) {
+ let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
+ name_resolver.set_explicit_column_count(explicit_col_count);
+ name_resolver.set_explicit_row_count(explicit_row_count);
+ let placements =
+ resolve_named_lines(child_styles.iter(), &name_resolver, explicit_col_count, explicit_row_count);
+ compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements)
+ }
+
+ #[test]
+ fn explicit_grid_sizing_with_children() {
+ let explicit_col_count = 6;
+ let explicit_row_count = 8;
+ let child_styles = [
+ (line(1), span(2), line(2), auto()).into_grid_child(),
+ (line(-4), auto(), line(-2), auto()).into_grid_child(),
+ ];
+ let (inline, block) = estimate(explicit_col_count, explicit_row_count, &child_styles);
+ assert_eq!(inline.negative_implicit, 0);
+ assert_eq!(inline.explicit, explicit_col_count);
+ assert_eq!(inline.positive_implicit, 0);
+ assert_eq!(block.negative_implicit, 0);
+ assert_eq!(block.explicit, explicit_row_count);
+ assert_eq!(block.positive_implicit, 0);
+ }
+
+ #[test]
+ fn negative_implicit_grid_sizing() {
+ let explicit_col_count = 4;
+ let explicit_row_count = 4;
+ let child_styles = [
+ (line(-6), span(2), line(-8), auto()).into_grid_child(),
+ (line(4), auto(), line(3), auto()).into_grid_child(),
+ ];
+ let (inline, block) = estimate(explicit_col_count, explicit_row_count, &child_styles);
+ assert_eq!(inline.negative_implicit, 1);
+ assert_eq!(inline.explicit, explicit_col_count);
+ assert_eq!(inline.positive_implicit, 0);
+ assert_eq!(block.negative_implicit, 3);
+ assert_eq!(block.explicit, explicit_row_count);
+ assert_eq!(block.positive_implicit, 0);
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/mod.rs b/vendor/taffy/src/compute/grid/mod.rs
new file mode 100644
index 00000000..4d188461
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/mod.rs
@@ -0,0 +1,1416 @@
+//! This module is a partial implementation of the CSS Grid Level 1 specification
+//! <https://www.w3.org/TR/css-grid-1>
+use crate::geometry::{AbsoluteAxis, AbstractAxis, InBothAbsAxis};
+use crate::geometry::{Line, Point, Rect, Size};
+use crate::style::{AlignContent, AlignItems, AvailableSpace, Contain, ContainingBlockClaims, Overflow};
+use crate::tree::{
+ AxisStaticPosition, Baselines, Layout, LayoutInput, LayoutOutput, LayoutPartialTreeExt, NodeId, OofCandidate,
+ OofCandidates, OofPositioningArea, RunMode, SizingMode,
+};
+use crate::util::debug::debug_log;
+use crate::util::sys::{f32_max, f32_min, GridTrackVec, Vec};
+use crate::util::MaybeMath;
+use crate::util::{MaybeResolve, ResolveOrZero};
+use crate::{
+ style_helpers::*, BoxGenerationMode, BoxSizing, CoreStyle, Direction, GridContainerStyle, GridItemStyle,
+ LayoutGridContainer, RequestedAxis,
+};
+use alignment::{align_and_position_item, align_tracks};
+use explicit_grid::{compute_explicit_grid_size_in_axis, initialize_grid_tracks, AutoRepeatStrategy};
+use implicit_grid::compute_grid_size_estimate;
+use placement::{place_grid_items, ItemPlacement};
+use track_sizing::{
+ determine_if_item_crosses_flexible_or_intrinsic_tracks, resolve_item_track_indexes, track_sizing_algorithm,
+};
+use types::{CellOccupancyMatrix, GridAreasMap, GridTrack, NamedLineResolver};
+
+use crate::sys::{DefaultCheapStr, String};
+use crate::{CheapCloneStr, GridAreaAxis, GridPlacement};
+use core::ops::Range;
+use types::{GridItem, GridTrackKind, TrackCounts};
+
+pub(crate) use types::{GridCoordinate, GridLine, OriginZeroLine, MAX_GRID_TRACKS, MAX_OZ_LINE, MIN_OZ_LINE};
+
+pub use types::{GridLineNames, GridLineNamesIter};
+
+mod alignment;
+mod explicit_grid;
+mod implicit_grid;
+mod placement;
+mod track_sizing;
+mod types;
+mod util;
+/// The grid container's resolved box, size constraints, alignment styles and available space,
+/// computed once from the container's style and the layout inputs before the grid is laid out
+#[derive(Clone, Copy)]
+struct GridContainerConstants {
+ /// The container's `direction` style
+ direction: Direction,
+ /// The container's `contain` style
+ contain: Contain,
+ /// Which positioning schemes the container is a containing block for
+ containing_block_claims: ContainingBlockClaims,
+ /// The container's resolved padding
+ padding: Rect<f32>,
+ /// The container's resolved border
+ border: Rect<f32>,
+ /// The sum of padding and border in each axis
+ padding_border_size: Size<f32>,
+ /// The container's border-box min size, if definite
+ min_size: Size<Option<f32>>,
+ /// The container's border-box max size, if definite
+ max_size: Size<Option<f32>>,
+ /// The container's border-box preferred size, if definite
+ preferred_size: Size<Option<f32>>,
+ /// The space reserved for scrollbars in each axis
+ scrollbar_gutter: Point<f32>,
+ /// Whether the container's overflow makes it a scroll container
+ #[cfg(feature = "content_size")]
+ is_scroll_container: bool,
+ /// Padding, border and scrollbar gutter combined
+ content_box_inset: Rect<f32>,
+ /// The container's `align-content` style
+ align_content: AlignContent,
+ /// The container's `justify-content` style
+ justify_content: AlignContent,
+ /// The container's `align-items` style
+ align_items: AlignItems,
+ /// The container's `justify-items` style
+ justify_items: AlignItems,
+ /// The space available to size the grid tracks in each axis
+ available_grid_space: Size<AvailableSpace>,
+ /// The container's border-box size, if definite
+ outer_node_size: Size<Option<f32>>,
+ /// The container's content-box min size, if definite
+ inner_min_size: Size<Option<f32>>,
+ /// The container's content-box max size, if definite
+ inner_max_size: Size<Option<f32>>,
+ /// The container's content-box size, if definite
+ inner_node_size: Size<Option<f32>>,
+}
+
+/// Resolve the grid container's style against the layout inputs (step 1 of `compute_grid_layout`)
+fn compute_container_constants<Tree: LayoutGridContainer>(
+ tree: &Tree,
+ style: &Tree::GridContainerStyle<'_>,
+ inputs: LayoutInput,
+) -> GridContainerConstants {
+ let LayoutInput { known_dimensions, parent_size, available_space, .. } = inputs;
+
+ let direction = style.direction();
+ let contain = style.contain();
+ let containing_block_claims = style.is_containing_block();
+
+ // 1. Compute "available grid space"
+ // https://www.w3.org/TR/css-grid-1/#available-grid-space
+ let aspect_ratio = style.aspect_ratio();
+ let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border = padding + border;
+ let padding_border_size = padding_border.sum_axes();
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+
+ let min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let preferred_size = if inputs.sizing_mode == SizingMode::InherentSize {
+ style
+ .size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(style.aspect_ratio())
+ .maybe_add(box_sizing_adjustment)
+ } else {
+ Size::NONE
+ };
+
+ // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
+ // However, the axis are switched (transposed) because a node that scrolls vertically needs
+ // *horizontal* space to be reserved for a scrollbar
+ let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
+ Overflow::Scroll => style.scrollbar_width(),
+ _ => 0.0,
+ });
+ #[cfg(feature = "content_size")]
+ let is_scroll_container = {
+ let overflow = style.overflow();
+ overflow.x.is_scroll_container() || overflow.y.is_scroll_container()
+ };
+ let mut content_box_inset = padding_border;
+ content_box_inset.bottom += scrollbar_gutter.y;
+
+ match direction {
+ Direction::Ltr => content_box_inset.right += scrollbar_gutter.x,
+ Direction::Rtl => content_box_inset.left += scrollbar_gutter.x,
+ };
+
+ // `normal` behaves as `stretch` for grid containers
+ let align_content = style.grid_align_content(AbstractAxis::Block);
+ let justify_content = style.grid_align_content(AbstractAxis::Inline);
+ let align_items = style.align_items();
+ let justify_items = style.justify_items();
+ let constrained_available_space = known_dimensions
+ .or(preferred_size)
+ .map(|size| size.map(AvailableSpace::Definite))
+ .unwrap_or(available_space)
+ .maybe_clamp(min_size, max_size)
+ .maybe_max(padding_border_size);
+
+ let available_grid_space = Size {
+ width: constrained_available_space
+ .width
+ .map_definite_value(|space| space - content_box_inset.horizontal_axis_sum()),
+ height: constrained_available_space
+ .height
+ .map_definite_value(|space| space - content_box_inset.vertical_axis_sum()),
+ };
+
+ let outer_node_size =
+ known_dimensions.or(preferred_size).maybe_clamp(min_size, max_size).maybe_max(padding_border_size);
+
+ // The track sizing algorithm operates on the grid container's content box, so the min/max sizes
+ // (which are border-box sizes) need converting to content-box sizes before being passed to it
+ let inner_min_size = min_size.maybe_sub(content_box_inset.sum_axes());
+ let inner_max_size = max_size.maybe_sub(content_box_inset.sum_axes());
+ let inner_node_size = Size {
+ width: outer_node_size.width.map(|space| space - content_box_inset.horizontal_axis_sum()),
+ height: outer_node_size.height.map(|space| space - content_box_inset.vertical_axis_sum()),
+ };
+
+ GridContainerConstants {
+ direction,
+ contain,
+ containing_block_claims,
+ padding,
+ border,
+ padding_border_size,
+ min_size,
+ max_size,
+ preferred_size,
+ scrollbar_gutter,
+ #[cfg(feature = "content_size")]
+ is_scroll_container,
+ content_box_inset,
+ align_content,
+ justify_content,
+ align_items,
+ justify_items,
+ available_grid_space,
+ outer_node_size,
+ inner_min_size,
+ inner_max_size,
+ inner_node_size,
+ }
+}
+
+/// Grid layout algorithm
+/// This consists of a few phases:
+/// - Resolving the explicit grid
+/// - Placing items (which also resolves the implicit grid)
+/// - Track (row/column) sizing
+/// - Alignment & Final item placement
+pub fn compute_grid_layout<Tree: LayoutGridContainer>(
+ tree: &mut Tree,
+ node: NodeId,
+ inputs: LayoutInput,
+) -> LayoutOutput {
+ let LayoutInput { known_dimensions, run_mode, .. } = inputs;
+
+ let style = tree.get_grid_container_style(node);
+ let constants = compute_container_constants(tree, &style, inputs);
+ let GridContainerConstants {
+ direction,
+ contain,
+ containing_block_claims,
+ padding,
+ border,
+ padding_border_size,
+ min_size,
+ max_size,
+ preferred_size,
+ scrollbar_gutter,
+ #[cfg(feature = "content_size")]
+ is_scroll_container,
+ content_box_inset,
+ align_content,
+ justify_content,
+ align_items,
+ justify_items,
+ available_grid_space,
+ outer_node_size,
+ inner_min_size,
+ inner_max_size,
+ mut inner_node_size,
+ } = constants;
+
+ // Note: we avoid accessing the grid rows/columns methods more than once as this can
+ // cause an expensive-ish computation
+ let grid_template_columns = style.grid_template_columns();
+ let grid_template_rows = style.grid_template_rows();
+ let grid_auto_columns = style.grid_auto_columns();
+ let grid_auto_rows = style.grid_auto_rows();
+
+ debug_log!("parent_size", dbg:inputs.parent_size);
+ debug_log!("outer_node_size", dbg:outer_node_size);
+ debug_log!("inner_node_size", dbg:inner_node_size);
+
+ // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
+ // is ComputeSize (and thus the container's size is all that we're interested in)
+ if run_mode == RunMode::ComputeSize {
+ if let Size { width: Some(width), height: Some(height) } = outer_node_size {
+ return LayoutOutput::from_outer_size(Size { width, height });
+ }
+
+ // We can also short-circuit if the width is known and only the width has been requested.
+ if inputs.axis == RequestedAxis::Horizontal {
+ if let Some(width) = outer_node_size.width {
+ return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
+ }
+ }
+ }
+
+ // 2. Resolve the explicit grid
+
+ // This is very similar to the inner_node_size except if the inner_node_size is not definite but the node
+ // has a min- or max- size style then that will be used in it's place.
+ let auto_fit_container_size = outer_node_size
+ .or(max_size)
+ .or(min_size)
+ .maybe_clamp(min_size, max_size)
+ .maybe_max(padding_border_size)
+ .maybe_sub(content_box_inset.sum_axes());
+
+ // If the grid container has a definite size or max size in the relevant axis:
+ // - then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow the content
+ // box of its grid container.
+ // Otherwise, if the grid container has a definite min size in the relevant axis:
+ // - then the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement
+ // Otherwise, the specified track list repeats only once.
+ let auto_repeat_fit_strategy = outer_node_size.or(max_size).map(|val| match val {
+ Some(_) => AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
+ None => AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
+ });
+
+ // Compute the number of rows and columns in the explicit grid *template*
+ // (explicit tracks from grid_areas are computed separately below)
+ let (col_auto_repetition_count, grid_template_col_count) = compute_explicit_grid_size_in_axis(
+ &style,
+ auto_fit_container_size.width,
+ auto_repeat_fit_strategy.width,
+ |val, basis| tree.calc(val, basis),
+ AbsoluteAxis::Horizontal,
+ );
+ let (row_auto_repetition_count, grid_template_row_count) = compute_explicit_grid_size_in_axis(
+ &style,
+ auto_fit_container_size.height,
+ auto_repeat_fit_strategy.height,
+ |val, basis| tree.calc(val, basis),
+ AbsoluteAxis::Vertical,
+ );
+
+ // type CustomIdent<'a> = <<Tree as LayoutPartialTree>::CoreContainerStyle<'_> as CoreStyle>::CustomIdent;
+ let mut name_resolver = NamedLineResolver::new(&style, col_auto_repetition_count, row_auto_repetition_count);
+
+ // Clamp the explicit grid to MAX_GRID_TRACKS tracks in each axis
+ // https://www.w3.org/TR/css-grid-1/#overlarge-grids
+ let explicit_col_count = grid_template_col_count.max(name_resolver.area_column_count()).min(MAX_GRID_TRACKS);
+ let explicit_row_count = grid_template_row_count.max(name_resolver.area_row_count()).min(MAX_GRID_TRACKS);
+
+ name_resolver.set_explicit_column_count(explicit_col_count);
+ name_resolver.set_explicit_row_count(explicit_row_count);
+
+ // Build the per-line names of the explicit grid from the name resolver's collected pairs
+ let mut detailed_column_line_names = name_resolver.detailed_line_names(AbsoluteAxis::Horizontal);
+ let mut detailed_row_line_names = name_resolver.detailed_line_names(AbsoluteAxis::Vertical);
+
+ // 3. Create the grid items (in document order) and resolve the named lines in their `grid-row`/`grid-column` styles
+ // Absolutely positioned children do not take part in grid placement and do not create implicit tracks,
+ // so they are excluded here. Each child's style is read and its named lines resolved exactly once; the
+ // results drive both the grid size estimate and item placement below.
+ let child_count = tree.child_count(node);
+ let mut items: Vec<GridItem> = Vec::with_capacity(child_count);
+ let mut placements: Vec<ItemPlacement> = Vec::with_capacity(child_count);
+ for (index, child_node) in tree.child_ids(node).enumerate() {
+ let child_style = tree.get_grid_child_style(child_node);
+ if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position().is_out_of_flow() {
+ continue;
+ }
+ placements.push(InBothAbsAxis {
+ horizontal: name_resolver
+ .resolve_column_names(&child_style.grid_column())
+ .into_origin_zero(explicit_col_count),
+ vertical: name_resolver.resolve_row_names(&child_style.grid_row()).into_origin_zero(explicit_row_count),
+ });
+ items.push(GridItem::new_with_style_and_order(
+ child_node,
+ child_style,
+ align_items,
+ justify_items,
+ index as u16,
+ ));
+ }
+
+ // 4. Implicit Grid: Estimate Track Counts
+ // Estimate the number of rows and columns in the implicit grid (= the entire grid)
+ // This is necessary as part of placement. Doing it early here is a perf optimisation to reduce allocations.
+ let (est_col_counts, est_row_counts) =
+ compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements);
+
+ // 5. Grid Item Placement
+ // Match items (children) to a definite grid position (row start/end and column start/end position)
+ let mut cell_occupancy_matrix = CellOccupancyMatrix::with_track_counts(est_col_counts, est_row_counts);
+ // `items` is in document order from here on (placement only fills in each item's grid area). The track
+ // sizing and baseline passes sort references to the items rather than the items themselves.
+ place_grid_items(&mut cell_occupancy_matrix, &mut items, &placements, style.grid_auto_flow());
+
+ // Extract track counts from previous step (auto-placement can expand the number of tracks)
+ let final_col_counts = *cell_occupancy_matrix.track_counts(AbsoluteAxis::Horizontal);
+ let final_row_counts = *cell_occupancy_matrix.track_counts(AbsoluteAxis::Vertical);
+
+ // 5. Initialize Tracks
+ // Initialize (explicit and implicit) grid tracks (and gutters)
+ // This resolves the min and max track sizing functions for all tracks and gutters
+ let mut columns = GridTrackVec::new();
+ let mut rows = GridTrackVec::new();
+ initialize_grid_tracks(
+ &mut columns,
+ final_col_counts,
+ &style,
+ AbsoluteAxis::Horizontal,
+ col_auto_repetition_count,
+ |column_index| cell_occupancy_matrix.column_is_occupied(column_index),
+ );
+ initialize_grid_tracks(
+ &mut rows,
+ final_row_counts,
+ &style,
+ AbsoluteAxis::Vertical,
+ row_auto_repetition_count,
+ |row_index| cell_occupancy_matrix.row_is_occupied(row_index),
+ );
+
+ drop(grid_template_rows);
+ drop(grid_template_columns);
+ drop(grid_auto_rows);
+ drop(grid_auto_columns);
+ drop(style);
+
+ // 6. Track Sizing
+
+ // Convert grid placements in origin-zero coordinates to indexes into the GridTrack (rows and columns) vectors
+ // This computation is relatively trivial, but it requires the final number of negative (implicit) tracks in
+ // each axis, and doing it up-front here means we don't have to keep repeating that calculation
+ resolve_item_track_indexes(&mut items, final_col_counts, final_row_counts);
+ // For each item, and in each axis, determine whether the item crosses any flexible (fr) tracks
+ // Record this as a boolean (per-axis) on each item for later use in the track-sizing algorithm
+ determine_if_item_crosses_flexible_or_intrinsic_tracks(&mut items, &columns, &rows);
+
+ // Determine if the grid has any baseline aligned items
+ let has_baseline_aligned_item = items.iter().any(|item| item.participates_in_baseline_alignment());
+
+ // Run track sizing algorithm for Inline axis
+ track_sizing_algorithm(
+ tree,
+ AbstractAxis::Inline,
+ inner_min_size.get(AbstractAxis::Inline),
+ inner_max_size.get(AbstractAxis::Inline),
+ justify_content,
+ align_content,
+ available_grid_space,
+ inner_node_size,
+ &mut columns,
+ &mut rows,
+ &mut items,
+ |track: &GridTrack, parent_size: Option<f32>, tree: &Tree| {
+ track.max_track_sizing_function.definite_value(parent_size, |val, basis| tree.calc(val, basis))
+ },
+ has_baseline_aligned_item,
+ );
+ let initial_column_sum = columns.iter().map(|track| track.base_size).sum::<f32>();
+ inner_node_size.width = inner_node_size.width.or_else(|| initial_column_sum.into());
+
+ // If only the container's width has been requested then we can skip sizing the rows entirely (which avoids
+ // measuring the height of every item), as column sizing is not re-run when only computing the container's size.
+ // Note: the short-circuit above has already handled the case where the container's width is known.
+ if run_mode == RunMode::ComputeSize && inputs.axis == RequestedAxis::Horizontal {
+ let width = (initial_column_sum + content_box_inset.horizontal_axis_sum())
+ .maybe_clamp(min_size.width, max_size.width)
+ .max(padding_border_size.width);
+ return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
+ }
+
+ items.iter_mut().for_each(|item| item.grid_area_size_cache = None);
+
+ // Run track sizing algorithm for Block axis
+ track_sizing_algorithm(
+ tree,
+ AbstractAxis::Block,
+ inner_min_size.get(AbstractAxis::Block),
+ inner_max_size.get(AbstractAxis::Block),
+ align_content,
+ justify_content,
+ available_grid_space,
+ inner_node_size,
+ &mut rows,
+ &mut columns,
+ &mut items,
+ |track: &GridTrack, _, _| Some(track.base_size),
+ false, // TODO: Support baseline alignment in the vertical axis
+ );
+ let initial_row_sum = rows.iter().map(|track| track.base_size).sum::<f32>();
+
+ debug_log!("initial_column_sum", dbg:initial_column_sum);
+ debug_log!(dbg: columns.iter().map(|track| track.base_size).collect::<Vec<_>>());
+ debug_log!("initial_row_sum", dbg:initial_row_sum);
+ debug_log!(dbg: rows.iter().map(|track| track.base_size).collect::<Vec<_>>());
+
+ // 6. Compute container size
+ let resolved_style_size = known_dimensions.or(preferred_size);
+ let mut container_border_box = Size {
+ width: resolved_style_size
+ .get(AbstractAxis::Inline)
+ .unwrap_or_else(|| initial_column_sum + content_box_inset.horizontal_axis_sum())
+ .maybe_clamp(min_size.width, max_size.width)
+ .max(padding_border_size.width),
+ height: resolved_style_size
+ .get(AbstractAxis::Block)
+ .unwrap_or_else(|| initial_row_sum + content_box_inset.vertical_axis_sum())
+ .maybe_clamp(min_size.height, max_size.height)
+ .max(padding_border_size.height),
+ };
+ let mut container_content_box = Size {
+ width: f32_max(0.0, container_border_box.width - content_box_inset.horizontal_axis_sum()),
+ height: f32_max(0.0, container_border_box.height - content_box_inset.vertical_axis_sum()),
+ };
+
+ // If only the container's size has been requested
+ if run_mode == RunMode::ComputeSize {
+ return LayoutOutput::from_outer_size(container_border_box);
+ }
+
+ // The container's size is now determined, so percentages resolve against its content box when re-running track sizing.
+ // This may be a no-op if the container's size was known upfront (in which case it already equals `inner_node_size`).
+ inner_node_size = container_content_box.map(Some);
+
+ // Column sizing must be re-run (once) if:
+ // - The grid container's width was initially indefinite and there are any columns with percentage track sizing functions
+ // - Any grid item crossing an intrinsically sized track's min content contribution width has changed
+ // TODO: Only rerun sizing for tracks that actually require it rather than for all tracks if any need it.
+ let mut rerun_column_sizing;
+ let mut intrinsic_column_contribution_changed = false;
+
+ let has_percentage_column = columns.iter().any(|track| track.uses_percentage());
+ let has_percentage_row = rows.iter().any(|track| track.uses_percentage());
+ let parent_width_indefinite = outer_node_size.width.is_none();
+ rerun_column_sizing = parent_width_indefinite && has_percentage_column;
+
+ if !rerun_column_sizing {
+ // Note: every item must be visited (no short-circuiting) as the closure updates each item's caches
+ intrinsic_column_contribution_changed =
+ items.iter_mut().filter(|item| item.crosses_intrinsic_column).fold(false, |any_changed, item| {
+ let grid_area_size = item.grid_area_size(
+ AbstractAxis::Inline,
+ &columns,
+ &rows,
+ inner_node_size,
+ |track: &GridTrack, _| Some(track.base_size),
+ &|val, basis| tree.calc(val, basis),
+ );
+ let available_space = grid_area_size.with(AbstractAxis::Inline, None);
+ let new_min_content_contribution =
+ item.min_content_contribution(AbstractAxis::Inline, tree, grid_area_size, available_space);
+
+ let has_changed = Some(new_min_content_contribution) != item.min_content_contribution_cache.width;
+
+ item.grid_area_size_cache = Some(grid_area_size);
+ item.min_content_contribution_cache.width = Some(new_min_content_contribution);
+ item.max_content_contribution_cache.width = None;
+ item.minimum_contribution_cache.width = None;
+
+ any_changed | has_changed
+ });
+ rerun_column_sizing = intrinsic_column_contribution_changed;
+ } else {
+ // Clear intrinsic width caches
+ items.iter_mut().for_each(|item| {
+ item.grid_area_size_cache = None;
+ item.min_content_contribution_cache.width = None;
+ item.max_content_contribution_cache.width = None;
+ item.minimum_contribution_cache.width = None;
+ });
+ }
+
+ // Row sizing must be re-run (once) if:
+ // - The grid container's height was initially indefinite and there are any rows with percentage track sizing functions
+ // - Column sizing was re-run and any grid item crossing an intrinsically sized track's min content contribution height has changed
+ // TODO: Only rerun sizing for tracks that actually require it rather than for all tracks if any need it.
+ let parent_height_indefinite = outer_node_size.height.is_none();
+ let mut rerun_row_sizing = parent_height_indefinite && has_percentage_row;
+ let mut intrinsic_row_contribution_changed = false;
+
+ if rerun_row_sizing {
+ // Clear intrinsic height caches
+ items.iter_mut().for_each(|item| {
+ item.grid_area_size_cache = None;
+ item.min_content_contribution_cache.height = None;
+ item.max_content_contribution_cache.height = None;
+ item.minimum_contribution_cache.height = None;
+ });
+ }
+
+ if rerun_column_sizing {
+ // Re-run track sizing algorithm for Inline axis
+ track_sizing_algorithm(
+ tree,
+ AbstractAxis::Inline,
+ inner_min_size.get(AbstractAxis::Inline),
+ inner_max_size.get(AbstractAxis::Inline),
+ justify_content,
+ align_content,
+ available_grid_space,
+ inner_node_size,
+ &mut columns,
+ &mut rows,
+ &mut items,
+ |track: &GridTrack, _, _| Some(track.base_size),
+ has_baseline_aligned_item,
+ );
+
+ // The column widths may have changed, so the items' intrinsic height contributions need to be recomputed
+ // (unless row sizing is being re-run anyway, in which case the caches have already been cleared).
+ if !rerun_row_sizing {
+ // Note: every item must be visited (no short-circuiting) as the closure updates each item's caches
+ intrinsic_row_contribution_changed =
+ items.iter_mut().filter(|item| item.crosses_intrinsic_row).fold(false, |any_changed, item| {
+ let grid_area_size = item.grid_area_size(
+ AbstractAxis::Block,
+ &rows,
+ &columns,
+ inner_node_size,
+ |track: &GridTrack, _| Some(track.base_size),
+ &|val, basis| tree.calc(val, basis),
+ );
+ let available_space = grid_area_size.with(AbstractAxis::Block, None);
+ let new_min_content_contribution =
+ item.min_content_contribution(AbstractAxis::Block, tree, grid_area_size, available_space);
+
+ let has_changed = Some(new_min_content_contribution) != item.min_content_contribution_cache.height;
+
+ item.grid_area_size_cache = Some(grid_area_size);
+ item.min_content_contribution_cache.height = Some(new_min_content_contribution);
+ item.max_content_contribution_cache.height = None;
+ item.minimum_contribution_cache.height = None;
+
+ any_changed | has_changed
+ });
+ rerun_row_sizing = intrinsic_row_contribution_changed;
+ }
+ }
+
+ if rerun_row_sizing {
+ // Re-run track sizing algorithm for Block axis
+ track_sizing_algorithm(
+ tree,
+ AbstractAxis::Block,
+ inner_min_size.get(AbstractAxis::Block),
+ inner_max_size.get(AbstractAxis::Block),
+ align_content,
+ justify_content,
+ available_grid_space,
+ inner_node_size,
+ &mut rows,
+ &mut columns,
+ &mut items,
+ |track: &GridTrack, _, _| Some(track.base_size),
+ false, // TODO: Support baseline alignment in the vertical axis
+ );
+ }
+
+ if (intrinsic_column_contribution_changed && !has_percentage_column)
+ || (intrinsic_row_contribution_changed && !has_percentage_row)
+ {
+ let final_column_sum = columns.iter().map(|track| track.base_size).sum::<f32>();
+ let final_row_sum = rows.iter().map(|track| track.base_size).sum::<f32>();
+
+ if intrinsic_column_contribution_changed && !has_percentage_column {
+ container_border_box.width = resolved_style_size
+ .get(AbstractAxis::Inline)
+ .unwrap_or_else(|| final_column_sum + content_box_inset.horizontal_axis_sum())
+ .maybe_clamp(min_size.width, max_size.width)
+ .max(padding_border_size.width);
+ container_content_box.width =
+ f32_max(0.0, container_border_box.width - content_box_inset.horizontal_axis_sum());
+ }
+
+ if intrinsic_row_contribution_changed && !has_percentage_row {
+ container_border_box.height = resolved_style_size
+ .get(AbstractAxis::Block)
+ .unwrap_or_else(|| final_row_sum + content_box_inset.vertical_axis_sum())
+ .maybe_clamp(min_size.height, max_size.height)
+ .max(padding_border_size.height);
+ container_content_box.height =
+ f32_max(0.0, container_border_box.height - content_box_inset.vertical_axis_sum());
+ }
+ }
+
+ // If only the container's size has been requested
+ if run_mode == RunMode::ComputeSize {
+ return LayoutOutput::from_outer_size(container_border_box);
+ }
+
+ // 8. Track Alignment
+
+ // Align columns
+ let inline_size_without_scrollbar = f32_max(container_border_box.width - padding_border_size.width, 0.0);
+ let inline_scrollbar_gutter_for_alignment = f32_min(scrollbar_gutter.x, inline_size_without_scrollbar);
+ align_tracks(
+ container_content_box.get(AbstractAxis::Inline),
+ Line {
+ start: padding.left + if direction.is_rtl() { inline_scrollbar_gutter_for_alignment } else { 0.0 },
+ end: padding.right + if direction.is_rtl() { 0.0 } else { inline_scrollbar_gutter_for_alignment },
+ },
+ Line { start: border.left, end: border.right },
+ &mut columns,
+ justify_content,
+ direction.is_rtl(),
+ );
+ // Align rows
+ align_tracks(
+ container_content_box.get(AbstractAxis::Block),
+ Line { start: padding.top, end: padding.bottom },
+ Line { start: border.top, end: border.bottom },
+ &mut rows,
+ align_content,
+ false,
+ );
+
+ // 9. Size, Align, and Position Grid Items
+
+ #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
+ let mut item_overflow_rect = Rect::ZERO;
+
+ // Out-of-flow candidates in document order: direct out-of-flow children of the grid
+ // interleaved with candidates bubbled from in-flow children's subtrees. These are laid out
+ // by the out-of-flow positioning pass (`compute_oof_layout`), which runs after this algorithm.
+ let mut oof_candidates = OofCandidates::new();
+
+ let container_alignment_styles = InBothAbsAxis { horizontal: justify_items, vertical: align_items };
+
+ // Position in-flow children (stored in items vector)
+ for (index, item) in items.iter_mut().enumerate() {
+ // Tracks are stored in logical order. In RTL the physical offsets are assigned
+ // right-to-left, so an item's physical left edge is derived from its logical end
+ // line and its physical right edge from its logical start line.
+ let grid_area = Rect {
+ top: rows[item.row_indexes.start as usize + 1].offset,
+ bottom: rows[item.row_indexes.end as usize].offset,
+ left: if direction.is_rtl() {
+ columns[item.column_indexes.end as usize - 1].offset
+ } else {
+ columns[item.column_indexes.start as usize + 1].offset
+ },
+ right: if direction.is_rtl() {
+ columns[item.column_indexes.start as usize].offset
+ } else {
+ columns[item.column_indexes.end as usize].offset
+ },
+ };
+ #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
+ let (overflow_contribution, y_position, height) = align_and_position_item(
+ tree,
+ item.node,
+ index as u32,
+ grid_area,
+ Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top },
+ container_alignment_styles,
+ item.baseline_shim,
+ direction,
+ container_border_box.width,
+ border,
+ #[cfg(feature = "content_size")]
+ is_scroll_container,
+ &mut item.oof_candidates,
+ );
+ item.y_position = y_position;
+ item.height = height;
+
+ #[cfg(feature = "content_size")]
+ {
+ item_overflow_rect = item_overflow_rect.union(overflow_contribution);
+ }
+ }
+
+ // Position hidden and absolutely positioned children, merging in the candidates bubbled out
+ // of in-flow children's subtrees (`items` is sorted by `source_order`, i.e. child index)
+ let mut order = items.len() as u32;
+ let mut in_flow_items = items.iter_mut().peekable();
+ (0..tree.child_count(node)).for_each(|index| {
+ if let Some(item) = in_flow_items.next_if(|item| item.source_order as usize == index) {
+ oof_candidates.append(&mut item.oof_candidates);
+ return;
+ }
+
+ let child = tree.get_child_id(node, index);
+ let child_style = tree.get_grid_child_style(child);
+
+ // Position hidden child
+ if child_style.box_generation_mode() == BoxGenerationMode::None {
+ drop(child_style);
+ tree.set_unrounded_layout(child, &Layout::with_order(order));
+ tree.perform_child_layout(
+ child,
+ Size::NONE,
+ Size::NONE,
+ Size::MAX_CONTENT,
+ SizingMode::InherentSize,
+ Line::FALSE,
+ );
+ order += 1;
+ return;
+ }
+
+ // Emit out-of-flow children as candidates for the out-of-flow positioning pass
+ // (`compute_oof_layout`), which lays out those for which this grid is the containing
+ // block after this algorithm has run (resolving their grid areas from the detailed grid
+ // info recorded below).
+ if child_style.position().is_out_of_flow() {
+ let position = child_style.position();
+ let item_direction = child_style.direction();
+ let justify_self = child_style.justify_self().unwrap_or(justify_items).resolve_self_relative(
+ item_direction,
+ direction,
+ true,
+ );
+ let align_self =
+ child_style.align_self().unwrap_or(align_items).resolve_self_relative(item_direction, direction, false);
+
+ // The static-position rectangle: the grid area determined by the grid-placement
+ // properties when this grid is the child's containing block, and otherwise the
+ // grid's content box, as if the child were the sole grid item in a grid area
+ // coinciding with the grid's content edges (grid placement does not apply when the
+ // grid is not the containing block).
+ // https://www.w3.org/TR/css-grid-1/#static-position
+ let area = if containing_block_claims.for_position(position) {
+ resolve_static_position_grid_area(
+ &child_style,
+ &name_resolver,
+ final_row_counts,
+ final_col_counts,
+ &rows,
+ &columns,
+ direction,
+ border,
+ scrollbar_gutter,
+ container_border_box,
+ )
+ } else {
+ Rect {
+ left: border.left + padding.left + if direction.is_rtl() { scrollbar_gutter.x } else { 0.0 },
+ right: container_border_box.width
+ - border.right
+ - padding.right
+ - if direction.is_rtl() { 0.0 } else { scrollbar_gutter.x },
+ top: border.top + padding.top,
+ bottom: container_border_box.height - border.bottom - padding.bottom - scrollbar_gutter.y,
+ }
+ };
+ drop(child_style);
+
+ oof_candidates.push(OofCandidate {
+ node: child,
+ order,
+ position,
+ static_position: Point {
+ x: AxisStaticPosition::from_alignment(
+ justify_self,
+ Line { start: area.left, end: area.right },
+ direction.is_rtl(),
+ ),
+ y: AxisStaticPosition::from_alignment(
+ align_self,
+ Line { start: area.top, end: area.bottom },
+ false,
+ ),
+ },
+ });
+
+ order += 1;
+ }
+ });
+
+ let absolute_position_inset = border
+ + Rect {
+ left: if direction.is_rtl() { scrollbar_gutter.x } else { 0.0 },
+ right: if direction.is_rtl() { 0.0 } else { scrollbar_gutter.x },
+ top: 0.0,
+ bottom: scrollbar_gutter.y,
+ };
+ let absolute_position_area = container_border_box - absolute_position_inset.sum_axes();
+ let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
+ // Store the detailed grid info before the out-of-flow positioning pass so that the pass can
+ // resolve the grid areas of out-of-flow boxes whose containing block is this grid
+ let areas =
+ name_resolver.populate_detailed_line_resolvers(&mut detailed_row_line_names, &mut detailed_column_line_names);
+ tree.set_detailed_grid_info(
+ node,
+ DetailedGridInfo {
+ rows: DetailedGridTracksInfo::from_grid_tracks_and_track_count(
+ final_row_counts,
+ rows,
+ detailed_row_line_names,
+ ),
+ columns: DetailedGridTracksInfo::from_grid_tracks_and_track_count(
+ final_col_counts,
+ columns,
+ detailed_column_line_names,
+ ),
+ items: items.iter().map(DetailedGridItemsInfo::from_grid_item).collect(),
+ areas,
+ },
+ );
+
+ let oof_positioning_area =
+ Some(OofPositioningArea { size: absolute_position_area, offset: absolute_position_offset });
+
+ // If there are no in-flow items then return the container size and the overflow (no baseline)
+ if items.is_empty() {
+ #[cfg(feature = "content_size")]
+ let mut output = {
+ let mut overflow_rect = item_overflow_rect;
+ if is_scroll_container {
+ overflow_rect.right += if direction.is_rtl() { padding.left } else { padding.right };
+ overflow_rect.bottom += padding.bottom;
+ }
+ LayoutOutput::from_sizes(container_border_box, overflow_rect)
+ };
+ #[cfg(not(feature = "content_size"))]
+ let mut output = LayoutOutput::from_outer_size(container_border_box);
+ output.oof_candidates = oof_candidates;
+ output.oof_positioning_area = oof_positioning_area;
+ return output;
+ }
+
+ // Determine the grid container baseline(s) (currently we only compute the first baseline)
+ // Layout containment suppresses the box's baseline for baseline-alignment purposes
+ let grid_container_baseline: Option<f32> = if contain.suppresses_baseline() {
+ None
+ } else {
+ // Get the row index of the first row containing items
+ let first_row = items.iter().map(|item| item.row_indexes.start).min().unwrap();
+
+ // Check if any items in *this row* participate in baseline alignment
+ // (items with an auto block-axis margin do not participate: https://www.w3.org/TR/css-align-3/#baseline-align-self)
+ let mut first_row_items = items.iter().filter(|item| item.row_indexes.start == first_row);
+ let first_item = first_row_items.next().unwrap();
+ let item = if first_item.participates_in_baseline_alignment() {
+ first_item
+ } else {
+ first_row_items.find(|item| item.participates_in_baseline_alignment()).unwrap_or(first_item)
+ };
+
+ Some(item.y_position + item.baseline.unwrap_or(item.height))
+ };
+
+ // A scroll container's own padding at the end of the content is part of its scrollable
+ // overflow region, so it is included in the in-flow overflow rect. Boxes that are not
+ // scroll containers do not extend their overflow region by their own padding.
+ #[cfg(feature = "content_size")]
+ let scrollable_overflow_rect = {
+ let mut overflow_rect = item_overflow_rect;
+ if is_scroll_container {
+ overflow_rect.right += if direction.is_rtl() { padding.left } else { padding.right };
+ overflow_rect.bottom += padding.bottom;
+ }
+ overflow_rect
+ };
+ #[cfg(not(feature = "content_size"))]
+ let scrollable_overflow_rect = item_overflow_rect;
+
+ let mut output = LayoutOutput::from_sizes_and_baselines(
+ container_border_box,
+ scrollable_overflow_rect,
+ Baselines::from_first(grid_container_baseline),
+ );
+ output.oof_candidates = oof_candidates;
+ output.oof_positioning_area = oof_positioning_area;
+ output
+}
+
+/// Resolve the static-position rectangle (the grid area determined by the grid-placement
+/// properties) for an out-of-flow child of a positioned grid container.
+///
+/// Content alignment (align-content/justify-content) may distribute free space before, between,
+/// or after tracks. Grid lines used by absolutely positioned items resolve to the edges of the
+/// tracks adjacent to the line rather than to the raw gutter offset:
+/// - As a start edge, a line resolves to the start of the track that follows it
+/// - As an end edge, a line resolves to the end of the track that precedes it
+#[allow(clippy::too_many_arguments)]
+fn resolve_static_position_grid_area<S: CheapCloneStr>(
+ child_style: &impl GridItemStyle<CustomIdent = S>,
+ name_resolver: &NamedLineResolver<S>,
+ final_row_counts: TrackCounts,
+ final_col_counts: TrackCounts,
+ rows: &[GridTrack],
+ columns: &[GridTrack],
+ direction: Direction,
+ border: Rect<f32>,
+ scrollbar_gutter: Point<f32>,
+ container_border_box: Size<f32>,
+) -> Rect<f32> {
+ // Convert grid-col-{start/end} into Option's of indexes into the columns vector
+ // The Option is None if the style property is Auto and an unresolvable Span
+ let maybe_col_indexes = name_resolver
+ .resolve_column_names(&child_style.grid_column())
+ .into_origin_zero(final_col_counts.explicit)
+ .resolve_absolutely_positioned_grid_tracks()
+ .map(|maybe_grid_line| {
+ maybe_grid_line.and_then(|line: OriginZeroLine| line.try_into_track_vec_index(final_col_counts))
+ });
+ // Convert grid-row-{start/end} into Option's of indexes into the row vector
+ // The Option is None if the style property is Auto and an unresolvable Span
+ let maybe_row_indexes = name_resolver
+ .resolve_row_names(&child_style.grid_row())
+ .into_origin_zero(final_row_counts.explicit)
+ .resolve_absolutely_positioned_grid_tracks()
+ .map(|maybe_grid_line| {
+ maybe_grid_line.and_then(|line: OriginZeroLine| line.try_into_track_vec_index(final_row_counts))
+ });
+
+ /// Resolve a grid line (by track vector index) used as a start edge to a position
+ fn line_as_start_edge(tracks: &[GridTrack], index: usize) -> f32 {
+ tracks.get(index + 1).unwrap_or(&tracks[index]).offset
+ }
+ /// Resolve a grid line (by track vector index) used as an end edge to a position
+ fn line_as_end_edge(tracks: &[GridTrack], index: usize) -> f32 {
+ if index == 0 {
+ tracks.get(1).unwrap_or(&tracks[0]).offset
+ } else {
+ tracks[index].offset
+ }
+ }
+ // In RTL, tracks remain in logical order but physical offsets are assigned
+ // right-to-left: a line used as an inline-start edge resolves to the physical
+ // *right* edge of the track that follows it (its gutter's offset), and a line
+ // used as an inline-end edge resolves to the physical *left* edge (offset) of
+ // the track that precedes it.
+ /// Resolve a grid line used as an inline-start edge to a physical right x-position (RTL)
+ fn rtl_line_as_start_edge(tracks: &[GridTrack], index: usize) -> f32 {
+ if tracks.len() > index + 1 {
+ // The gutter's offset is the physical right edge of the track that follows the line
+ tracks[index].offset
+ } else if index == 0 {
+ tracks[0].offset
+ } else {
+ // No track follows the line: resolve to the line itself, which is the physical
+ // left edge of the track that precedes it (the trailing gutter is assigned its
+ // offset before any alignment offset is applied, so it cannot be used here)
+ tracks[index - 1].offset
+ }
+ }
+ /// Resolve a grid line used as an inline-end edge to a physical left x-position (RTL)
+ fn rtl_line_as_end_edge(tracks: &[GridTrack], index: usize) -> f32 {
+ if index == 0 {
+ tracks[0].offset
+ } else {
+ tracks[index - 1].offset
+ }
+ }
+
+ // In RTL the item's physical left edge derives from its logical end line and its
+ // physical right edge from its logical start line.
+ let (grid_area_left, grid_area_right) = if direction.is_rtl() {
+ (
+ maybe_col_indexes
+ .end
+ .map(|index| rtl_line_as_end_edge(columns, index))
+ .unwrap_or(border.left + scrollbar_gutter.x),
+ maybe_col_indexes
+ .start
+ .map(|index| rtl_line_as_start_edge(columns, index))
+ .unwrap_or(container_border_box.width - border.right),
+ )
+ } else {
+ (
+ maybe_col_indexes.start.map(|index| line_as_start_edge(columns, index)).unwrap_or(border.left),
+ maybe_col_indexes
+ .end
+ .map(|index| line_as_end_edge(columns, index))
+ .unwrap_or(container_border_box.width - border.right - scrollbar_gutter.x),
+ )
+ };
+
+ Rect {
+ top: maybe_row_indexes.start.map(|index| line_as_start_edge(rows, index)).unwrap_or(border.top),
+ bottom: maybe_row_indexes
+ .end
+ .map(|index| line_as_end_edge(rows, index))
+ .unwrap_or(container_border_box.height - border.bottom - scrollbar_gutter.y),
+ left: grid_area_left,
+ right: grid_area_right,
+ }
+}
+
+/// Information from the computation of grid
+#[derive(Debug, Clone, PartialEq)]
+pub struct DetailedGridInfo<S: CheapCloneStr = DefaultCheapStr> {
+ /// <https://drafts.csswg.org/css-grid-1/#grid-row>
+ pub rows: DetailedGridTracksInfo<S>,
+ /// <https://drafts.csswg.org/css-grid-1/#grid-column>
+ pub columns: DetailedGridTracksInfo<S>,
+ /// <https://drafts.csswg.org/css-grid-1/#grid-items>
+ pub items: Vec<DetailedGridItemsInfo>,
+ /// Grid area edge lookup used to resolve the grid placements of absolutely positioned children
+ areas: GridAreasMap<S>,
+}
+
+impl<S: CheapCloneStr> DetailedGridTracksInfo<S> {
+ /// Resolve an absolute placement in this axis to physical start and end coordinates
+ fn resolve_absolute_grid_axis(
+ &self,
+ placement: Line<GridPlacement<S>>,
+ areas: &GridAreasMap<S>,
+ axis: GridAreaAxis,
+ padding_start: f32,
+ padding_end: f32,
+ is_reversed: bool,
+ ) -> Line<f32> {
+ let track_counts = TrackCounts {
+ negative_implicit: self.negative_implicit_tracks,
+ explicit: self.explicit_tracks,
+ positive_implicit: self.positive_implicit_tracks,
+ };
+ let min_line = -(track_counts.negative_implicit as i16);
+ let max_line = (track_counts.explicit + track_counts.positive_implicit) as i16;
+ // Resolve the placement to a pair of (sorted) lines first, and only then treat lines
+ // that fall outside the grid as `auto`. A placement whose lines end up swapped (e.g.
+ // `grid-column: 3 / 1`, or a non-existent named line which resolves past the end of the
+ // explicit grid) is normalized before the out-of-grid check, so e.g. `foo / 3` on a
+ // 2-column grid resolves to the area between line 3 and the end padding edge.
+ let placement = self
+ .line_names
+ .resolve_line_names(&placement, areas, axis, self.explicit_tracks)
+ .into_origin_zero(self.explicit_tracks)
+ .resolve_absolutely_positioned_grid_tracks()
+ .map(|line| line.filter(|line| line.0 >= min_line && line.0 <= max_line))
+ .map(|line| line.and_then(|line| line.try_into_track_vec_index(track_counts).map(|index| index / 2)));
+ let start_position = placement
+ .start
+ .and_then(|line| {
+ (line < self.positions.len())
+ .then(|| self.absolute_track_edge(line, true, is_reversed))
+ .or_else(|| self.positions.last().map(|track| if is_reversed { track.start } else { track.end }))
+ .or(self.empty_axis_line)
+ })
+ .unwrap_or(if is_reversed { padding_end } else { padding_start });
+ let end_position = placement
+ .end
+ .and_then(|line| {
+ line.checked_sub(1)
+ .filter(|&line| line < self.positions.len())
+ .map(|line| self.absolute_track_edge(line, false, is_reversed))
+ .or_else(|| self.positions.first().map(|track| if is_reversed { track.end } else { track.start }))
+ .or(self.empty_axis_line)
+ })
+ .unwrap_or(if is_reversed { padding_start } else { padding_end });
+
+ // An area whose lines all fall within a collapsed run is zero-sized and anchored at its
+ // logical start edge (as in Chrome; Gecko anchors it before the shared gutter instead).
+ if is_reversed {
+ Line { start: f32_min(start_position, end_position), end: start_position }
+ } else {
+ Line { start: start_position, end: f32_max(start_position, end_position) }
+ }
+ }
+
+ /// Resolve a track edge, excluding gutters that overlap across a collapsed track run.
+ fn absolute_track_edge(&self, index: usize, is_start: bool, is_reversed: bool) -> f32 {
+ let range_index = self.collapsed_tracks.partition_point(|range| range.end <= index);
+ let range = self.collapsed_tracks.get(range_index).filter(|range| range.contains(&index));
+ let track = range
+ .and_then(|range| {
+ let adjacent = if is_start { Some(range.end) } else { range.start.checked_sub(1) };
+ adjacent.and_then(|index| self.positions.get(index))
+ })
+ .unwrap_or(&self.positions[index]);
+ // Collapsed gutters overlap: a start edge follows the shared gutter, while an end
+ // edge precedes it.
+ if is_start != is_reversed {
+ track.start
+ } else {
+ track.end
+ }
+ }
+}
+
+impl<S: CheapCloneStr> DetailedGridInfo<S> {
+ /// Write the used row track sizes and line names to the passed writer in the resolved value
+ /// format of the `grid-template-rows` property
+ /// (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn write_grid_template_rows(&self, out: &mut impl core::fmt::Write, zoom: f32) -> core::fmt::Result {
+ self.rows.write_track_list(out, zoom)
+ }
+
+ /// Write the used column track sizes and line names to the passed writer in the resolved value
+ /// format of the `grid-template-columns` property
+ /// (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn write_grid_template_columns(&self, out: &mut impl core::fmt::Write, zoom: f32) -> core::fmt::Result {
+ self.columns.write_track_list(out, zoom)
+ }
+
+ /// Serialize the used row track sizes and line names in the resolved value format of the
+ /// `grid-template-rows` property (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn grid_template_rows(&self, zoom: f32) -> String {
+ self.rows.to_track_list_string(zoom)
+ }
+
+ /// Serialize the used column track sizes and line names in the resolved value format of the
+ /// `grid-template-columns` property (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn grid_template_columns(&self, zoom: f32) -> String {
+ self.columns.to_track_list_string(zoom)
+ }
+
+ /// Resolve the physical grid area for an absolutely positioned box from its grid placement.
+ /// The padding box and returned area use coordinates relative to the grid container's border box.
+ pub fn resolve_absolute_grid_area(
+ &self,
+ grid_row: Line<GridPlacement<S>>,
+ grid_column: Line<GridPlacement<S>>,
+ direction: Direction,
+ padding_box: Rect<f32>,
+ ) -> Rect<f32> {
+ let columns = self.columns.resolve_absolute_grid_axis(
+ grid_column,
+ &self.areas,
+ GridAreaAxis::Column,
+ padding_box.left,
+ padding_box.right,
+ direction.is_rtl(),
+ );
+ let rows = self.rows.resolve_absolute_grid_axis(
+ grid_row,
+ &self.areas,
+ GridAreaAxis::Row,
+ padding_box.top,
+ padding_box.bottom,
+ false,
+ );
+ Rect { left: columns.start, right: columns.end, top: rows.start, bottom: rows.end }
+ }
+
+ /// Compute the location and size of the grid area occupied by the item at `item_index` (an
+ /// index into [`DetailedGridInfo::items`]), relative to the grid container's border box.
+ ///
+ /// The edges resolve to the edges of the tracks bounding the item's grid area (a start line
+ /// resolves to the start of the track that follows it and an end line to the end of the track
+ /// that precedes it), so the area excludes any gutter or content-alignment spacing around it.
+ ///
+ /// Returns `None` if `item_index` is out of bounds.
+ pub fn item_grid_area(&self, item_index: usize) -> Option<(Point<f32>, Size<f32>)> {
+ let item = self.items.get(item_index)?;
+ let start_col = self.columns.positions[item.column_start as usize - 1];
+ let end_col = self.columns.positions[item.column_end as usize - 2];
+ let left = f32_min(start_col.start, end_col.start);
+ let right = f32_max(start_col.end, end_col.end);
+ let top = self.rows.positions[item.row_start as usize - 1].start;
+ let bottom = self.rows.positions[item.row_end as usize - 2].end;
+ Some((Point { x: left, y: top }, Size { width: right - left, height: bottom - top }))
+ }
+}
+
+/// Information from the computation of grids tracks
+#[derive(Debug, Clone, PartialEq)]
+pub struct DetailedGridTracksInfo<S: CheapCloneStr = DefaultCheapStr> {
+ /// Number of leading implicit grid tracks
+ pub negative_implicit_tracks: u16,
+ /// Number of explicit grid tracks
+ pub explicit_tracks: u16,
+ /// Number of trailing implicit grid tracks
+ pub positive_implicit_tracks: u16,
+
+ /// The start and end position of each track relative to the grid container's border box.
+ /// These positions account for the container's border and padding, the `gap` property,
+ /// content alignment (`align-content`/`justify-content`), and collapsed tracks.
+ pub positions: Vec<Line<f32>>,
+
+ /// Sorted, disjoint ranges of collapsed `auto-fit` tracks (indices into `positions`), whose
+ /// adjacent gutters overlap when resolving absolute grid-area edges. Empty (and never
+ /// allocated) unless a track collapsed.
+ pub collapsed_tracks: Vec<Range<usize>>,
+
+ /// The position of the axis' single grid line relative to the grid container's border box
+ /// when the axis has no tracks (an empty grid still contains one grid line in each axis,
+ /// positioned by content alignment). `None` when the axis has tracks.
+ pub empty_axis_line: Option<f32>,
+
+ /// The names of each *explicit* grid line. Stored line `i` (0-indexed) bounds the start of
+ /// explicit track `i`; use [`DetailedGridTracksInfo::names_for_line`] or
+ /// [`DetailedGridTracksInfo::iter_line_names`] for indices relative to the full grid
+ /// (including implicit tracks). Empty if the grid has no named lines.
+ pub line_names: GridLineNames<S>,
+}
+
+impl<S: CheapCloneStr> DetailedGridTracksInfo<S> {
+ /// Get the start and end position of each track relative to the grid container's border box,
+ /// along with the index ranges of any runs of collapsed `auto-fit` tracks
+ fn positions_from_grid_track_layout(grid_tracks: &[GridTrack]) -> (Vec<Line<f32>>, Vec<Range<usize>>) {
+ let mut positions = Vec::with_capacity(grid_tracks.len() / 2);
+ let mut collapsed_tracks: Vec<Range<usize>> = Vec::new();
+ for track in grid_tracks.iter().filter(|track| track.kind == GridTrackKind::Track) {
+ if track.is_collapsed {
+ let index = positions.len();
+ match collapsed_tracks.last_mut() {
+ Some(range) if range.end == index => range.end += 1,
+ _ => collapsed_tracks.push(index..index + 1),
+ }
+ }
+ positions.push(Line { start: track.offset, end: track.offset + track.base_size });
+ }
+ (positions, collapsed_tracks)
+ }
+
+ /// Construct DetailedGridTracksInfo from TrackCounts and GridTracks
+ fn from_grid_tracks_and_track_count(
+ track_count: TrackCounts,
+ grid_tracks: Vec<GridTrack>,
+ line_names: GridLineNames<S>,
+ ) -> Self {
+ let (positions, collapsed_tracks) = DetailedGridTracksInfo::<S>::positions_from_grid_track_layout(&grid_tracks);
+ // An axis with no tracks consists of a single gutter whose offset is where the axis'
+ // single grid line was positioned by content alignment
+ let empty_axis_line = if positions.is_empty() { grid_tracks.first().map(|track| track.offset) } else { None };
+ DetailedGridTracksInfo {
+ negative_implicit_tracks: track_count.negative_implicit,
+ explicit_tracks: track_count.explicit,
+ positive_implicit_tracks: track_count.positive_implicit,
+ positions,
+ collapsed_tracks,
+ empty_axis_line,
+ line_names,
+ }
+ }
+
+ /// The names of the grid line with the passed 0-indexed line index, where line `i` bounds
+ /// the start of track `i` of the full grid (including implicit tracks).
+ /// Returns an empty slice if the line has no names or the index is out of range.
+ pub fn names_for_line(&self, line_index: usize) -> &[S] {
+ match line_index.checked_sub(self.negative_implicit_tracks as usize) {
+ Some(stored_index) => self.line_names.line(stored_index),
+ None => &[],
+ }
+ }
+
+ /// Iterate over the name group (`&[S]`) of each grid line of the full grid (including
+ /// implicit tracks) in line order, yielding empty groups for unnamed (implicit) lines.
+ /// Yields nothing if the grid has no named lines.
+ pub fn iter_line_names(&self) -> GridLineNamesIter<'_, S> {
+ if self.line_names.is_empty() {
+ return self.line_names.iter();
+ }
+ let total_line_count = self.positions.len() + 1;
+ let leading_empty = self.negative_implicit_tracks as usize;
+ let trailing_empty = total_line_count.saturating_sub(leading_empty + self.line_names.line_count());
+ self.line_names.iter_padded(leading_empty, trailing_empty)
+ }
+
+ /// Write the used track sizes and line names of this axis to the passed writer in the
+ /// resolved value format of the `grid-template-rows`/`grid-template-columns` properties
+ /// (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn write_track_list(&self, out: &mut impl core::fmt::Write, zoom: f32) -> core::fmt::Result {
+ /// Write a bracketed line name group (e.g. `[foo bar]`)
+ fn write_line_names<S: CheapCloneStr>(out: &mut impl core::fmt::Write, names: &[S]) -> core::fmt::Result {
+ out.write_char('[')?;
+ for (i, name) in names.iter().enumerate() {
+ if i != 0 {
+ out.write_char(' ')?;
+ }
+ out.write_str(name.as_ref())?;
+ }
+ out.write_char(']')
+ }
+
+ if self.positions.is_empty() {
+ return out.write_str("none");
+ }
+
+ let mut needs_space = false;
+ for (track_index, position) in self.positions.iter().enumerate() {
+ let names = self.names_for_line(track_index);
+ if !names.is_empty() {
+ if needs_space {
+ out.write_char(' ')?;
+ }
+ write_line_names(out, names)?;
+ needs_space = true;
+ }
+ if needs_space {
+ out.write_char(' ')?;
+ }
+ write!(out, "{}px", (position.end - position.start) / zoom)?;
+ needs_space = true;
+ }
+ let trailing_names = self.names_for_line(self.positions.len());
+ if !trailing_names.is_empty() {
+ out.write_char(' ')?;
+ write_line_names(out, trailing_names)?;
+ }
+ Ok(())
+ }
+
+ /// Serialize the used track sizes and line names of this axis in the resolved value format of
+ /// the `grid-template-rows`/`grid-template-columns` properties
+ /// (see <https://www.w3.org/TR/css-grid-1/#resolved-track-list>)
+ /// Track sizes are divided by `zoom` (the container's effective CSS `zoom`, or `1.0`) to give unzoomed px.
+ pub fn to_track_list_string(&self, zoom: f32) -> String {
+ let mut out = String::new();
+ self.write_track_list(&mut out, zoom).expect("writing to a String cannot fail");
+ out
+ }
+}
+
+/// Grid area information from the placement algorithm
+///
+/// The values is 1-indexed grid line numbers bounding the area.
+/// This matches the Chrome and Firefox's format as of 2nd Jan 2024.
+#[derive(Debug, Clone, PartialEq)]
+pub struct DetailedGridItemsInfo {
+ /// row-start with 1-indexed grid line numbers
+ pub row_start: u16,
+ /// row-end with 1-indexed grid line numbers
+ pub row_end: u16,
+ /// column-start with 1-indexed grid line numbers
+ pub column_start: u16,
+ /// column-end with 1-indexed grid line numbers
+ pub column_end: u16,
+}
+
+/// Grid area information from the placement algorithm
+impl DetailedGridItemsInfo {
+ /// Construct from GridItems
+ #[inline(always)]
+ fn from_grid_item(grid_item: &GridItem) -> Self {
+ /// Conversion from the indexes of Vec<GridTrack> into 1-indexed grid line numbers. See [`GridItem::row_indexes`] or [`GridItem::column_indexes`]
+ #[inline(always)]
+ fn to_one_indexed_grid_line(grid_track_index: u16) -> u16 {
+ grid_track_index / 2 + 1
+ }
+
+ DetailedGridItemsInfo {
+ row_start: to_one_indexed_grid_line(grid_item.row_indexes.start),
+ row_end: to_one_indexed_grid_line(grid_item.row_indexes.end),
+ column_start: to_one_indexed_grid_line(grid_item.column_indexes.start),
+ column_end: to_one_indexed_grid_line(grid_item.column_indexes.end),
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/placement.rs b/vendor/taffy/src/compute/grid/placement.rs
new file mode 100644
index 00000000..7759a2a4
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/placement.rs
@@ -0,0 +1,638 @@
+//! Implements placing items in the grid and resolving the implicit grid.
+//! <https://www.w3.org/TR/css-grid-1/#placement>
+use super::types::{CellOccupancyMatrix, CellOccupancyState, GridItem};
+use super::{OriginZeroLine, MAX_OZ_LINE, MIN_OZ_LINE};
+use crate::geometry::Line;
+use crate::geometry::{AbsoluteAxis, InBothAbsAxis};
+use crate::style::{GridAutoFlow, OriginZeroGridPlacement};
+
+#[inline]
+/// Advances the cursor by one track.
+fn advance_position(position: OriginZeroLine) -> OriginZeroLine {
+ OriginZeroLine(position.0.saturating_add(1))
+}
+
+#[inline]
+/// Resolves an indefinite span starting at `position`.
+fn resolve_indefinite_grid_span(position: OriginZeroLine, span: u16) -> Line<OriginZeroLine> {
+ let position = position.0 as i32;
+ let span = span as i32;
+ let line = |value: i32| OriginZeroLine(value.clamp(i16::MIN as i32, i16::MAX as i32) as i16);
+ Line { start: line(position), end: line(position + span) }
+}
+
+/// A grid item's `grid-row`/`grid-column` styles with named lines resolved, in origin-zero coordinates
+pub(super) type ItemPlacement = InBothAbsAxis<Line<OriginZeroGridPlacement>>;
+
+/// 8.5. Grid Item Placement Algorithm
+/// Place items into the grid, generating new rows/column into the implicit grid as required
+///
+/// `items` and `placements` are parallel slices in document order: `placements[i]` holds the `grid-row`/`grid-column`
+/// styles of `items[i]`, with named lines already resolved. The placement passes run over these (small) values rather
+/// than re-reading the children's styles.
+///
+/// [Specification](https://www.w3.org/TR/css-grid-2/#auto-placement-algo)
+pub(super) fn place_grid_items(
+ cell_occupancy_matrix: &mut CellOccupancyMatrix,
+ items: &mut [GridItem],
+ placements: &[ItemPlacement],
+ grid_auto_flow: GridAutoFlow,
+) {
+ debug_assert_eq!(items.len(), placements.len());
+ let primary_axis = grid_auto_flow.primary_axis();
+ let secondary_axis = primary_axis.other_axis();
+
+ // 1. Place children with definite positions
+ for (item, &placement) in items.iter_mut().zip(placements.iter()) {
+ if !(placement.horizontal.is_definite() && placement.vertical.is_definite()) {
+ continue;
+ }
+ #[cfg(test)]
+ println!("Definite Item {}\n==============", item.source_order);
+
+ let (row_span, col_span) = place_definite_grid_item(placement, primary_axis);
+ record_grid_placement(
+ cell_occupancy_matrix,
+ item,
+ primary_axis,
+ row_span,
+ col_span,
+ CellOccupancyState::DefinitelyPlaced,
+ );
+ }
+
+ // 2. Place remaining children with definite secondary axis positions
+ for (item, &placement) in items.iter_mut().zip(placements.iter()) {
+ if !(placement.get(secondary_axis).is_definite() && !placement.get(primary_axis).is_definite()) {
+ continue;
+ }
+ #[cfg(test)]
+ println!("Definite Secondary Item {}\n==============", item.source_order);
+
+ let (primary_span, secondary_span) =
+ place_definite_secondary_axis_item(&*cell_occupancy_matrix, placement, grid_auto_flow);
+
+ record_grid_placement(
+ cell_occupancy_matrix,
+ item,
+ primary_axis,
+ primary_span,
+ secondary_span,
+ CellOccupancyState::AutoPlaced,
+ );
+ }
+
+ // 3. Determine the number of columns in the implicit grid
+ // By the time we get to this point in the execution, this is actually already accounted for:
+ //
+ // 3.1 Start with the columns from the explicit grid
+ // => Handled by grid size estimate which is used to pre-size the GridOccupancyMatrix
+ //
+ // 3.2 Among all the items with a definite column position (explicitly positioned items, items positioned in the previous step,
+ // and items not yet positioned but with a definite column) add columns to the beginning and end of the implicit grid as necessary
+ // to accommodate those items.
+ // => Handled by expand_to_fit_range which expands the GridOccupancyMatrix as necessary
+ // -> Called by mark_area_as
+ // -> Called by record_grid_placement
+ //
+ // 3.3 If the largest column span among all the items without a definite column position is larger than the width of
+ // the implicit grid, add columns to the end of the implicit grid to accommodate that column span.
+ // => Handled by grid size estimate which is used to pre-size the GridOccupancyMatrix
+
+ // 4. Position the remaining grid items
+ // (which either have definite position only in the secondary axis or indefinite positions in both axis)
+ let primary_axis = grid_auto_flow.primary_axis();
+ let secondary_axis = primary_axis.other_axis();
+ let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
+ let secondary_axis_grid_start_line = cell_occupancy_matrix.track_counts(secondary_axis).implicit_start_line();
+ let grid_start_position = (primary_axis_grid_start_line, secondary_axis_grid_start_line);
+ let mut grid_position = grid_start_position;
+ for (item, &placement) in items.iter_mut().zip(placements.iter()) {
+ if placement.get(secondary_axis).is_definite() {
+ continue;
+ }
+ #[cfg(test)]
+ println!("\nAuto Item {}\n==============", item.source_order);
+
+ // Compute placement
+ let (primary_span, secondary_span) =
+ place_indefinitely_positioned_item(&*cell_occupancy_matrix, placement, grid_auto_flow, grid_position);
+
+ // Record item
+ record_grid_placement(
+ cell_occupancy_matrix,
+ item,
+ primary_axis,
+ primary_span,
+ secondary_span,
+ CellOccupancyState::AutoPlaced,
+ );
+
+ // If using the "dense" placement algorithm then reset the grid position back to grid_start_position ready for the next item
+ // Otherwise set it to the position of the current item so that the next item it placed after it.
+ grid_position = match grid_auto_flow.is_dense() {
+ true => grid_start_position,
+ false => (primary_span.end, secondary_span.start),
+ };
+ }
+}
+
+/// 8.5. Grid Item Placement Algorithm
+/// Place a single definitely placed item into the grid
+fn place_definite_grid_item(
+ placement: ItemPlacement,
+ primary_axis: AbsoluteAxis,
+) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
+ // Resolve spans to tracks
+ let primary_span = placement.get(primary_axis).resolve_definite_grid_lines();
+ let secondary_span = placement.get(primary_axis.other_axis()).resolve_definite_grid_lines();
+
+ (primary_span, secondary_span)
+}
+
+/// 8.5. Grid Item Placement Algorithm
+/// Step 2. Place remaining children with definite secondary axis positions
+fn place_definite_secondary_axis_item(
+ cell_occupancy_matrix: &CellOccupancyMatrix,
+ placement: ItemPlacement,
+ auto_flow: GridAutoFlow,
+) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
+ let primary_axis = auto_flow.primary_axis();
+ let secondary_axis = primary_axis.other_axis();
+ let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
+
+ let secondary_axis_placement = placement.get(secondary_axis).resolve_definite_grid_lines();
+ let starting_position = match auto_flow.is_dense() {
+ true => primary_axis_grid_start_line,
+ false => cell_occupancy_matrix
+ .auto_placement_cursor(primary_axis, secondary_axis_placement.start)
+ .unwrap_or(primary_axis_grid_start_line),
+ };
+ let primary_axis_span = placement.get(primary_axis).indefinite_span();
+
+ let mut position: OriginZeroLine = starting_position;
+ loop {
+ let primary_axis_placement = resolve_indefinite_grid_span(position, primary_axis_span);
+
+ let collision = cell_occupancy_matrix.line_area_collision_jump(
+ primary_axis,
+ primary_axis_placement,
+ secondary_axis_placement,
+ );
+
+ match collision {
+ None => return (primary_axis_placement, secondary_axis_placement),
+ Some(next_position) => position = next_position,
+ }
+ }
+}
+
+/// 8.5. Grid Item Placement Algorithm
+/// Step 4. Position the remaining grid items.
+fn place_indefinitely_positioned_item(
+ cell_occupancy_matrix: &CellOccupancyMatrix,
+ placement: ItemPlacement,
+ auto_flow: GridAutoFlow,
+ grid_position: (OriginZeroLine, OriginZeroLine),
+) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
+ let primary_axis = auto_flow.primary_axis();
+ let secondary_axis = primary_axis.other_axis();
+
+ let primary_placement_style = placement.get(primary_axis);
+ let secondary_placement_style = placement.get(secondary_axis);
+
+ let secondary_span = secondary_placement_style.indefinite_span();
+ let has_definite_primary_axis_position = primary_placement_style.is_definite();
+ let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
+ let primary_axis_grid_end_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_end_line();
+ let secondary_axis_grid_start_line = cell_occupancy_matrix.track_counts(secondary_axis).implicit_start_line();
+
+ let (mut primary_idx, mut secondary_idx) = grid_position;
+
+ if has_definite_primary_axis_position {
+ let primary_span = primary_placement_style.resolve_definite_grid_lines();
+
+ // Compute secondary axis starting position for search
+ secondary_idx = match auto_flow.is_dense() {
+ // If auto-flow is dense then we always search from the first track
+ true => secondary_axis_grid_start_line,
+ false => {
+ if primary_span.start < primary_idx {
+ advance_position(secondary_idx)
+ } else {
+ secondary_idx
+ }
+ }
+ };
+
+ // Item has fixed primary axis position: so we simply increment the secondary axis position
+ // until we find a space that the item fits in
+ loop {
+ let secondary_span = resolve_indefinite_grid_span(secondary_idx, secondary_span);
+
+ // If area is occupied, jump the index past the collision and try again
+ let collision =
+ cell_occupancy_matrix.line_area_collision_jump(secondary_axis, secondary_span, primary_span);
+ if let Some(next_position) = collision {
+ secondary_idx = next_position;
+ continue;
+ }
+
+ // Once we find a free space, return that position
+ return (primary_span, secondary_span);
+ }
+ } else {
+ let primary_span = primary_placement_style.indefinite_span();
+
+ // Whether the item spans every track in the primary axis. Such an item can only be
+ // placed at the primary axis grid start, in a stripe of entirely unoccupied tracks.
+ let spans_all_primary_tracks = primary_span as usize >= cell_occupancy_matrix.track_counts(primary_axis).len();
+
+ // Item does not have any fixed axis, so we search along the primary axis until we hit the end of the already
+ // existent tracks, and then we reset the primary axis back to zero and increment the secondary axis index.
+ // We continue in this vein until we find a space that the item fits in.
+ loop {
+ let primary_span = resolve_indefinite_grid_span(primary_idx, primary_span);
+ let secondary_span = resolve_indefinite_grid_span(secondary_idx, secondary_span);
+
+ // If the primary index is out of bounds, then increment the secondary index and reset the primary
+ // index back to the start of the grid
+ let primary_out_of_bounds = primary_span.end > primary_axis_grid_end_line;
+ if primary_out_of_bounds {
+ // If the span is out of bounds even at the search start position then it can never fit,
+ // as searching only ever moves the span further away from the start of the grid. Bail out
+ // and let `record_grid_placement` clamp the placement into the limited grid
+ if primary_idx == primary_axis_grid_start_line {
+ return (primary_span, secondary_span);
+ }
+ secondary_idx = advance_position(secondary_idx);
+ primary_idx = primary_axis_grid_start_line;
+ continue;
+ }
+
+ // If the item spans every primary axis track, it fits if and only if all of the
+ // secondary axis tracks it spans are entirely unoccupied. Jump the secondary index
+ // past any non-empty tracks in the spanned stripe.
+ if spans_all_primary_tracks {
+ match cell_occupancy_matrix.occupied_track_jump(secondary_axis, secondary_span) {
+ Some(next_position) => {
+ secondary_idx = next_position;
+ primary_idx = primary_axis_grid_start_line;
+ continue;
+ }
+ None => return (primary_span, secondary_span),
+ }
+ }
+
+ // If area is occupied, jump the primary index past the collision and try again
+ let collision = cell_occupancy_matrix.line_area_collision_jump(primary_axis, primary_span, secondary_span);
+ if let Some(next_position) = collision {
+ primary_idx = next_position;
+ continue;
+ }
+
+ // Once we find a free space that's in bounds, return that position
+ return (primary_span, secondary_span);
+ }
+ }
+}
+
+/// Clamp a placement into the limited grid, preserving a span of at least 1 track.
+/// Items placed outside of the limited grid are clamped into it.
+///
+/// See: <https://www.w3.org/TR/css-grid-1/#overlarge-grids>
+fn clamp_span_to_limited_grid(span: Line<OriginZeroLine>) -> Line<OriginZeroLine> {
+ let start = span.start.0.clamp(MIN_OZ_LINE, MAX_OZ_LINE - 1);
+ let end = span.end.0.clamp(start + 1, MAX_OZ_LINE);
+ Line { start: OriginZeroLine(start), end: OriginZeroLine(end) }
+}
+
+/// Record the grid item's placement in both the CellOccupancyMatrix and the item itself
+/// once a definite placement has been determined
+fn record_grid_placement(
+ cell_occupancy_matrix: &mut CellOccupancyMatrix,
+ item: &mut GridItem,
+ primary_axis: AbsoluteAxis,
+ primary_span: Line<OriginZeroLine>,
+ secondary_span: Line<OriginZeroLine>,
+ placement_type: CellOccupancyState,
+) {
+ #[cfg(test)]
+ println!("BEFORE placement:");
+ #[cfg(test)]
+ println!("{cell_occupancy_matrix:?}");
+
+ // Clamp placements into the limited grid to prevent arithmetic overflow when growing the
+ // implicit grid (https://www.w3.org/TR/css-grid-1/#overlarge-grids)
+ let primary_span = clamp_span_to_limited_grid(primary_span);
+ let secondary_span = clamp_span_to_limited_grid(secondary_span);
+
+ // Mark area of grid as occupied
+ cell_occupancy_matrix.mark_area_as(primary_axis, primary_span, secondary_span, placement_type);
+
+ // Record placement on the item
+ let (col_span, row_span) = match primary_axis {
+ AbsoluteAxis::Horizontal => (primary_span, secondary_span),
+ AbsoluteAxis::Vertical => (secondary_span, primary_span),
+ };
+ item.column = col_span;
+ item.row = row_span;
+
+ #[cfg(test)]
+ println!("AFTER placement:");
+ #[cfg(test)]
+ println!("{cell_occupancy_matrix:?}");
+ #[cfg(test)]
+ println!("\n");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ mod test_placement_algorithm {
+ use crate::compute::grid::implicit_grid::compute_grid_size_estimate;
+ use crate::compute::grid::types::TrackCounts;
+ use crate::compute::grid::util::test_helpers::{grid_items, resolve_named_lines};
+ use crate::compute::grid::util::*;
+ use crate::compute::grid::CellOccupancyMatrix;
+ use crate::compute::grid::NamedLineResolver;
+ use crate::compute::grid::OriginZeroLine;
+ use crate::prelude::*;
+ use crate::style::GridAutoFlow;
+
+ use super::super::place_grid_items;
+
+ type ExpectedPlacement = (i16, i16, i16, i16);
+
+ fn placement_test_runner(
+ explicit_col_count: u16,
+ explicit_row_count: u16,
+ children: Vec<(usize, Style, ExpectedPlacement)>,
+ expected_col_counts: TrackCounts,
+ expected_row_counts: TrackCounts,
+ flow: GridAutoFlow,
+ ) {
+ // Setup test
+ let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
+ name_resolver.set_explicit_column_count(explicit_col_count);
+ name_resolver.set_explicit_row_count(explicit_row_count);
+ let mut items = grid_items(children.iter().map(|(index, style, _)| (*index, style)));
+ let placements = resolve_named_lines(
+ children.iter().map(|(_, style, _)| style),
+ &name_resolver,
+ explicit_col_count,
+ explicit_row_count,
+ );
+ let estimated_sizes = compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements);
+ let mut cell_occupancy_matrix =
+ CellOccupancyMatrix::with_track_counts(estimated_sizes.0, estimated_sizes.1);
+
+ // Run placement algorithm
+ place_grid_items(&mut cell_occupancy_matrix, &mut items, &placements, flow);
+
+ // Assert that each item has been placed in the right location (items are in the same order as children)
+ assert_eq!(items.len(), children.len());
+ for (idx, ((id, _style, expected_placement), item)) in children.iter().zip(items.iter()).enumerate() {
+ assert_eq!(item.node, NodeId::from(*id));
+ let actual_placement = (item.column.start, item.column.end, item.row.start, item.row.end);
+ assert_eq!(actual_placement, (*expected_placement).into_oz(), "Item {idx} (0-indexed)");
+ }
+
+ // Assert that the correct number of implicit rows have been generated
+ let actual_row_counts = *cell_occupancy_matrix.track_counts(crate::compute::grid::AbsoluteAxis::Vertical);
+ assert_eq!(actual_row_counts, expected_row_counts, "row track counts");
+ let actual_col_counts = *cell_occupancy_matrix.track_counts(crate::compute::grid::AbsoluteAxis::Horizontal);
+ assert_eq!(actual_col_counts, expected_col_counts, "column track counts");
+ }
+
+ #[test]
+ fn test_only_fixed_placement() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // node, style (grid coords), expected_placement (oz coords)
+ (1, (line(1), auto(), line(1), auto()).into_grid_child(), (0, 1, 0, 1)),
+ (2, (line(-4), auto(), line(-3), auto()).into_grid_child(), (-1, 0, 0, 1)),
+ (3, (line(-3), auto(), line(-4), auto()).into_grid_child(), (0, 1, -1, 0)),
+ (4, (line(3), span(2), line(5), auto()).into_grid_child(), (2, 4, 4, 5)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
+ let expected_rows = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 3 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_placement_spanning_origin() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // node, style (grid coords), expected_placement (oz coords)
+ (1, (line(-1), line(-1), line(-1), line(-1)).into_grid_child(), (2, 3, 2, 3)),
+ (2, (line(-1), span(2), line(-1), span(2)).into_grid_child(), (2, 4, 2, 4)),
+ (3, (line(-4), line(-4), line(-4), line(-4)).into_grid_child(), (-1, 0, -1, 0)),
+ (4, (line(-4), span(2), line(-4), span(2)).into_grid_child(), (-1, 1, -1, 1)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
+ let expected_rows = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_only_auto_placement_row_flow() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ let auto_child = (auto(), auto(), auto(), auto()).into_grid_child();
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, auto_child.clone(), (0, 1, 0, 1)),
+ (2, auto_child.clone(), (1, 2, 0, 1)),
+ (3, auto_child.clone(), (0, 1, 1, 2)),
+ (4, auto_child.clone(), (1, 2, 1, 2)),
+ (5, auto_child.clone(), (0, 1, 2, 3)),
+ (6, auto_child.clone(), (1, 2, 2, 3)),
+ (7, auto_child.clone(), (0, 1, 3, 4)),
+ (8, auto_child.clone(), (1, 2, 3, 4)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_only_auto_placement_column_flow() {
+ let flow = GridAutoFlow::Column;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ let auto_child = (auto(), auto(), auto(), auto()).into_grid_child();
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, auto_child.clone(), (0, 1, 0, 1)),
+ (2, auto_child.clone(), (0, 1, 1, 2)),
+ (3, auto_child.clone(), (1, 2, 0, 1)),
+ (4, auto_child.clone(), (1, 2, 1, 2)),
+ (5, auto_child.clone(), (2, 3, 0, 1)),
+ (6, auto_child.clone(), (2, 3, 1, 2)),
+ (7, auto_child.clone(), (3, 4, 0, 1)),
+ (8, auto_child.clone(), (3, 4, 1, 2)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_oversized_item() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, (span(5), auto(), auto(), auto()).into_grid_child(), (0, 5, 0, 1)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 3 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_fixed_in_secondary_axis() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, (span(2), auto(), line(1), auto()).into_grid_child(), (0, 2, 0, 1)),
+ (2, (auto(), auto(), line(2), auto()).into_grid_child(), (0, 1, 1, 2)),
+ (3, (auto(), auto(), line(1), auto()).into_grid_child(), (2, 3, 0, 1)),
+ (4, (auto(), auto(), line(4), auto()).into_grid_child(), (0, 1, 3, 4)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 1 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_definite_in_secondary_axis_with_fully_definite_negative() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (2, (auto(), auto(), line(2), auto()).into_grid_child(), (0, 1, 1, 2)),
+ (1, (line(-4), auto(), line(2), auto()).into_grid_child(), (-1, 0, 1, 2)),
+ (3, (auto(), auto(), line(1), auto()).into_grid_child(), (-1, 0, 0, 1)),
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 0 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_dense_packing_algorithm() {
+ let flow = GridAutoFlow::RowDense;
+ let explicit_col_count = 4;
+ let explicit_row_count = 4;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, (line(2), auto(), line(1), auto()).into_grid_child(), (1, 2, 0, 1)), // Definitely positioned in column 2
+ (2, (span(2), auto(), auto(), auto()).into_grid_child(), (2, 4, 0, 1)), // Spans 2 columns, so positioned after item 1
+ (3, (auto(), auto(), auto(), auto()).into_grid_child(), (0, 1, 0, 1)), // Spans 1 column, so should be positioned before item 1
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_sparse_packing_algorithm() {
+ let flow = GridAutoFlow::Row;
+ let explicit_col_count = 4;
+ let explicit_row_count = 4;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, (auto(), span(3), auto(), auto()).into_grid_child(), (0, 3, 0, 1)), // Width 3
+ (2, (auto(), span(3), auto(), auto()).into_grid_child(), (0, 3, 1, 2)), // Width 3 (wraps to next row)
+ (3, (auto(), span(1), auto(), auto()).into_grid_child(), (3, 4, 1, 2)), // Width 1 (uses second row as we're already on it)
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_auto_placement_in_negative_tracks() {
+ let flow = GridAutoFlow::RowDense;
+ let explicit_col_count = 2;
+ let explicit_row_count = 2;
+ let children = {
+ vec![
+ // output order, node, style (grid coords), expected_placement (oz coords)
+ (1, (line(-5), auto(), line(1), auto()).into_grid_child(), (-2, -1, 0, 1)), // Row 1. Definitely positioned in column -2
+ (2, (auto(), auto(), line(2), auto()).into_grid_child(), (-2, -1, 1, 2)), // Row 2. Auto positioned in column -2
+ (3, (auto(), auto(), auto(), auto()).into_grid_child(), (-1, 0, 0, 1)), // Row 1. Auto positioned in column -1
+ ]
+ };
+ let expected_cols = TrackCounts { negative_implicit: 2, explicit: 2, positive_implicit: 0 };
+ let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
+ placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
+ }
+
+ #[test]
+ fn test_overlarge_placement_is_clamped() {
+ let explicit_col_count = 9_000;
+ let explicit_row_count = 0;
+ let style = (line(-19_005), auto(), auto(), auto()).into_grid_child();
+ let children = [(0usize, style)];
+ let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
+ name_resolver.set_explicit_column_count(explicit_col_count);
+ name_resolver.set_explicit_row_count(explicit_row_count);
+ let mut items = grid_items(children.iter().map(|(index, style)| (*index, style)));
+ let placements = resolve_named_lines(
+ children.iter().map(|(_, style)| style),
+ &name_resolver,
+ explicit_col_count,
+ explicit_row_count,
+ );
+ let estimated_sizes = compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements);
+ let mut cell_occupancy_matrix =
+ CellOccupancyMatrix::with_track_counts(estimated_sizes.0, estimated_sizes.1);
+ place_grid_items(&mut cell_occupancy_matrix, &mut items, &placements, GridAutoFlow::Row);
+ assert_eq!(items[0].column, Line { start: OriginZeroLine(-10_000), end: OriginZeroLine(-9_999) });
+ }
+ }
+
+ #[test]
+ fn auto_placement_cursor_saturates_at_integer_bounds() {
+ assert_eq!(advance_position(OriginZeroLine(i16::MAX)), OriginZeroLine(i16::MAX));
+ }
+
+ #[test]
+ fn indefinite_spans_saturate_at_integer_bounds() {
+ assert_eq!(
+ resolve_indefinite_grid_span(OriginZeroLine(i16::MAX), 1),
+ Line { start: OriginZeroLine(i16::MAX), end: OriginZeroLine(i16::MAX) }
+ );
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/track_sizing.rs b/vendor/taffy/src/compute/grid/track_sizing.rs
new file mode 100644
index 00000000..a450531d
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/track_sizing.rs
@@ -0,0 +1,1507 @@
+//! Implements the track sizing algorithm
+//! <https://www.w3.org/TR/css-grid-1/#layout-algorithm>
+use super::types::{GridItem, GridTrack, TrackCounts};
+use crate::geometry::{AbstractAxis, Line, Size};
+use crate::style::{AlignContent, AlignContentKeyword, AvailableSpace};
+use crate::style_helpers::TaffyMinContent;
+use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, SizingMode};
+use crate::util::sys::{f32_max, f32_min, Vec};
+use crate::util::{FrontBackVecBuilder, MaybeMath, ResolveOrZero};
+use crate::CompactLength;
+
+/// Takes an axis, and a list of grid items sorted firstly by whether they cross a flex track
+/// in the specified axis (items that don't cross a flex track first) and then by the number
+/// of tracks they cross in specified axis (ascending order).
+///
+/// The list holds references so that the `GridItem`s themselves stay in document order and
+/// only the (pointer-sized) references are sorted.
+struct ItemBatcher {
+ /// The axis in which the ItemBatcher is operating. Used when querying properties from items.
+ axis: AbstractAxis,
+ /// The starting index of the current batch
+ index_offset: usize,
+ /// The span of the items in the current batch
+ current_span: u16,
+ /// Whether the current batch of items cross a flexible track
+ current_is_flex: bool,
+}
+
+impl ItemBatcher {
+ /// Create a new ItemBatcher for the specified axis
+ #[inline(always)]
+ fn new(axis: AbstractAxis) -> Self {
+ ItemBatcher { index_offset: 0, axis, current_span: 1, current_is_flex: false }
+ }
+
+ /// This is basically a manual version of Iterator::next which passes `items`
+ /// in as a parameter on each iteration to work around borrow checker rules
+ #[inline]
+ fn next<'items, 'a>(
+ &mut self,
+ items: &'items mut [&'a mut GridItem],
+ ) -> Option<(&'items mut [&'a mut GridItem], bool)> {
+ if self.current_is_flex || self.index_offset >= items.len() {
+ return None;
+ }
+
+ let item = &items[self.index_offset];
+ self.current_span = item.span(self.axis);
+ self.current_is_flex = item.crosses_flexible_track(self.axis);
+
+ let next_index_offset = if self.current_is_flex {
+ items.len()
+ } else {
+ items
+ .iter()
+ .position(|item: &&mut GridItem| {
+ item.crosses_flexible_track(self.axis) || item.span(self.axis) > self.current_span
+ })
+ .unwrap_or(items.len())
+ };
+
+ let batch_range = self.index_offset..next_index_offset;
+ self.index_offset = next_index_offset;
+
+ let batch = &mut items[batch_range];
+ Some((batch, self.current_is_flex))
+ }
+}
+
+/// This struct captures a bunch of variables which are used to compute the intrinsic sizes of children so that those variables
+/// don't have to be passed around all over the place below. It then has methods that implement the intrinsic sizing computations
+struct IntrinsicSizeMeasurer<'tree, 'oat, Tree, EstimateFunction>
+where
+ Tree: LayoutPartialTree,
+ EstimateFunction: Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
+{
+ /// The layout tree
+ tree: &'tree mut Tree,
+ /// The tracks in the opposite axis to the one we are currently sizing
+ other_axis_tracks: &'oat [GridTrack],
+ /// A function that computes an estimate of an other-axis track's size which is passed to
+ /// the child size measurement functions
+ get_track_size_estimate: EstimateFunction,
+ /// The axis we are currently sizing
+ axis: AbstractAxis,
+ /// The available grid space
+ inner_node_size: Size<Option<f32>>,
+}
+
+impl<Tree, EstimateFunction> IntrinsicSizeMeasurer<'_, '_, Tree, EstimateFunction>
+where
+ Tree: LayoutPartialTree,
+ EstimateFunction: Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
+{
+ /// Compute the available_space to be passed to the child sizing functions
+ /// These are estimates based on either the max track sizing function or the provisional base size in the opposite
+ /// axis to the one currently being sized.
+ /// https://www.w3.org/TR/css-grid-1/#algo-overview
+ #[inline(always)]
+ fn grid_area_size(&self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> Size<Option<f32>> {
+ item.grid_area_size_cached(
+ self.axis,
+ axis_tracks,
+ self.other_axis_tracks,
+ self.inner_node_size,
+ |track, basis| (self.get_track_size_estimate)(track, basis, self.tree),
+ &|val, basis| self.tree.calc(val, basis),
+ )
+ }
+
+ /// Compute the item's resolved margins for size contributions. Horizontal percentage margins always resolve
+ /// to zero if the container size is indefinite as otherwise this would introduce a cyclic dependency.
+ #[inline(always)]
+ fn margins_axis_sums_with_baseline_shims(&self, item: &GridItem, percentage_basis: Option<f32>) -> Size<f32> {
+ item.margins_axis_sums_with_baseline_shims(percentage_basis, self.tree)
+ }
+
+ /// Simple pass-through function to `LayoutPartialTreeExt::calc`
+ #[inline(always)]
+ fn calc(&self, val: *const (), basis: f32) -> f32 {
+ self.tree.calc(val, basis)
+ }
+
+ /// Retrieve the item's min content contribution from the cache or compute it using the provided parameters
+ #[inline(always)]
+ fn min_content_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
+ let grid_area_size = self.grid_area_size(item, axis_tracks);
+ let available_space = grid_area_size.with(self.axis, None);
+ let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
+ let contribution = item.min_content_contribution_cached(self.axis, self.tree, grid_area_size, available_space);
+ contribution + margin_axis_sums.get(self.axis)
+ }
+
+ /// Retrieve the item's max content contribution from the cache or compute it using the provided parameters
+ #[inline(always)]
+ fn max_content_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
+ let grid_area_size = self.grid_area_size(item, axis_tracks);
+ let available_space = grid_area_size.with(self.axis, None);
+ let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
+ let contribution = item.max_content_contribution_cached(self.axis, self.tree, grid_area_size, available_space);
+ contribution + margin_axis_sums.get(self.axis)
+ }
+
+ /// The minimum contribution of an item is the smallest outer size it can have.
+ /// Specifically:
+ /// - If the item’s computed preferred size behaves as auto or depends on the size of its containing block in the relevant axis:
+ /// Its minimum contribution is the outer size that would result from assuming the item’s used minimum size as its preferred size;
+ /// - Else the item’s minimum contribution is its min-content contribution.
+ ///
+ /// Because the minimum contribution often depends on the size of the item’s content, it is considered a type of intrinsic size contribution.
+ #[inline(always)]
+ fn minimum_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
+ let grid_area_size = self.grid_area_size(item, axis_tracks);
+ let available_space = grid_area_size.with(self.axis, None);
+ let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
+ let contribution =
+ item.minimum_contribution_cached(self.tree, self.axis, axis_tracks, grid_area_size, self.inner_node_size);
+ contribution + margin_axis_sums.get(self.axis)
+ }
+}
+
+/// When applying the track sizing algorithm and estimating the size in the other axis for content sizing items
+/// we should take into account align-content/justify-content if both the grid container and all items in the
+/// other axis have definite sizes. This function computes such a per-gutter additional size adjustment.
+#[inline(always)]
+pub(super) fn compute_alignment_gutter_adjustment(
+ alignment: AlignContent,
+ axis_inner_node_size: Option<f32>,
+ get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
+ tracks: &[GridTrack],
+) -> f32 {
+ if tracks.len() <= 1 {
+ return 0.0;
+ }
+
+ // As items never cross the outermost gutters in a grid, we can simplify our calculations by
+ // treating Start and End the same. The safety modifier doesn't influence gutter weight;
+ // overflow fallback is handled when offsets are computed.
+ let outer_gutter_weight = match alignment.keyword() {
+ AlignContentKeyword::Start
+ | AlignContentKeyword::FlexStart
+ | AlignContentKeyword::End
+ | AlignContentKeyword::FlexEnd
+ | AlignContentKeyword::Center => 1,
+ // Normal is resolved to Stretch in `compute_grid_layout`
+ AlignContentKeyword::Normal | AlignContentKeyword::Stretch => 0,
+ AlignContentKeyword::SpaceBetween => 0,
+ AlignContentKeyword::SpaceAround => 1,
+ AlignContentKeyword::SpaceEvenly => 1,
+ };
+
+ let inner_gutter_weight = match alignment.keyword() {
+ AlignContentKeyword::FlexStart
+ | AlignContentKeyword::Start
+ | AlignContentKeyword::FlexEnd
+ | AlignContentKeyword::End
+ | AlignContentKeyword::Center
+ | AlignContentKeyword::Normal
+ | AlignContentKeyword::Stretch => 0,
+ AlignContentKeyword::SpaceBetween => 1,
+ AlignContentKeyword::SpaceAround => 2,
+ AlignContentKeyword::SpaceEvenly => 1,
+ };
+
+ if inner_gutter_weight == 0 {
+ return 0.0;
+ }
+
+ if let Some(axis_inner_node_size) = axis_inner_node_size {
+ let free_space = tracks
+ .iter()
+ .map(|track| get_track_size_estimate(track, Some(axis_inner_node_size)))
+ .sum::<Option<f32>>()
+ .map(|track_size_sum| f32_max(0.0, axis_inner_node_size - track_size_sum))
+ .unwrap_or(0.0);
+
+ let weighted_track_count =
+ (((tracks.len() - 3) / 2) * inner_gutter_weight as usize) + (2 * outer_gutter_weight as usize);
+
+ return (free_space / weighted_track_count as f32) * inner_gutter_weight as f32;
+ }
+
+ 0.0
+}
+
+/// Convert origin-zero coordinates track placement in grid track vector indexes
+#[inline(always)]
+pub(super) fn resolve_item_track_indexes(items: &mut [GridItem], column_counts: TrackCounts, row_counts: TrackCounts) {
+ for item in items {
+ item.column_indexes = item.column.map(|line| line.into_track_vec_index(column_counts) as u16);
+ item.row_indexes = item.row.map(|line| line.into_track_vec_index(row_counts) as u16);
+ }
+}
+
+/// Determine (in each axis) whether the item crosses any flexible tracks
+#[inline(always)]
+pub(super) fn determine_if_item_crosses_flexible_or_intrinsic_tracks(
+ items: &mut Vec<GridItem>,
+ columns: &[GridTrack],
+ rows: &[GridTrack],
+) {
+ for item in items {
+ item.crosses_flexible_column =
+ item.track_range_excluding_lines(AbstractAxis::Inline).any(|i| columns[i].is_flexible());
+ item.crosses_intrinsic_column =
+ item.track_range_excluding_lines(AbstractAxis::Inline).any(|i| columns[i].has_intrinsic_sizing_function());
+ item.crosses_flexible_row =
+ item.track_range_excluding_lines(AbstractAxis::Block).any(|i| rows[i].is_flexible());
+ item.crosses_intrinsic_row =
+ item.track_range_excluding_lines(AbstractAxis::Block).any(|i| rows[i].has_intrinsic_sizing_function());
+ }
+}
+
+/// Track sizing algorithm
+/// Note: Gutters are treated as empty fixed-size tracks for the purpose of the track sizing algorithm.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn track_sizing_algorithm<Tree: LayoutPartialTree>(
+ tree: &mut Tree,
+ axis: AbstractAxis,
+ axis_min_size: Option<f32>,
+ axis_max_size: Option<f32>,
+ axis_alignment: AlignContent,
+ other_axis_alignment: AlignContent,
+ available_grid_space: Size<AvailableSpace>,
+ inner_node_size: Size<Option<f32>>,
+ axis_tracks: &mut [GridTrack],
+ other_axis_tracks: &mut [GridTrack],
+ items: &mut [GridItem],
+ get_track_size_estimate: fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
+ has_baseline_aligned_item: bool,
+) {
+ // 11.4 Initialise Track sizes
+ // Initialize each track’s base size and growth limit.
+ let percentage_basis = inner_node_size.get(axis).or(axis_min_size);
+ initialize_track_sizes(tree, axis_tracks, percentage_basis);
+
+ // Resolve fit-content() limits against the container's inner size (these are fixed for the rest of this pass)
+ let axis_inner_node_size = inner_node_size.get(axis);
+ for track in axis_tracks.iter_mut() {
+ track.resolve_fit_content_limit(axis_inner_node_size, |val, basis| tree.calc(val, basis));
+ }
+
+ // 11.5.1 Shim item baselines
+ if has_baseline_aligned_item {
+ resolve_item_baselines(tree, axis, items, inner_node_size);
+ }
+
+ // If all tracks have a fixed min track sizing function and base_size = growth_limit,
+ // then the track sizes are already final and we can skip the rest of this function.
+ // Note that tracks with an intrinsic min track sizing function can still grow beyond
+ // a fixed growth limit (e.g. minmax(auto, 0px)), so they cannot be skipped.
+ if axis_tracks.iter().all(|track| {
+ track.base_size == track.growth_limit
+ && track
+ .min_track_sizing_function
+ .definite_value(percentage_basis, |val, basis| tree.calc(val, basis))
+ .is_some()
+ }) {
+ return;
+ }
+
+ // Pre-computations for 11.5 Resolve Intrinsic Track Sizes
+
+ // Compute an additional amount to add to each spanned gutter when computing item's estimated size in the
+ // in the opposite axis based on the alignment, container size, and estimated track sizes in that axis
+ let gutter_alignment_adjustment = compute_alignment_gutter_adjustment(
+ other_axis_alignment,
+ inner_node_size.get(axis.other()),
+ |track, basis| get_track_size_estimate(track, basis, tree),
+ other_axis_tracks,
+ );
+ if other_axis_tracks.len() > 3 {
+ let len = other_axis_tracks.len();
+ let inner_gutter_tracks = other_axis_tracks[2..len].iter_mut().step_by(2);
+ for track in inner_gutter_tracks {
+ track.content_alignment_adjustment = gutter_alignment_adjustment;
+ }
+ }
+
+ // 11.5 Resolve Intrinsic Track Sizes
+ resolve_intrinsic_track_sizes(
+ tree,
+ axis,
+ axis_tracks,
+ other_axis_tracks,
+ items,
+ available_grid_space.get(axis),
+ inner_node_size,
+ get_track_size_estimate,
+ );
+
+ // 11.6. Maximise Tracks
+ // Distributes free space (if any) to tracks with FINITE growth limits, up to their limits.
+ maximise_tracks(axis_tracks, available_grid_space.get(axis));
+
+ // For the purpose of the final two expansion steps ("Expand Flexible Tracks" and "Stretch auto Tracks"), we only want to expand
+ // into space generated by the grid container's size (as defined by either it's preferred size style or by it's parent node through
+ // something like stretch alignment), not just any available space. To do this we map definite available space to AvailableSpace::MaxContent
+ // in the case that inner_node_size is None. A min-content constraint in the block axis is also mapped to AvailableSpace::MaxContent,
+ // as the min-content block size of a grid container is its max-content block size.
+ let axis_available_space_for_expansion = if let Some(available_space) = inner_node_size.get(axis) {
+ AvailableSpace::Definite(available_space)
+ } else {
+ match available_grid_space.get(axis) {
+ AvailableSpace::MinContent if axis == AbstractAxis::Inline => AvailableSpace::MinContent,
+ _ => AvailableSpace::MaxContent,
+ }
+ };
+
+ // 11.7. Expand Flexible Tracks
+ // This step sizes flexible tracks using the largest value it can assign to an fr without exceeding the available space.
+ expand_flexible_tracks(
+ tree,
+ axis,
+ axis_tracks,
+ other_axis_tracks,
+ items,
+ axis_min_size,
+ axis_max_size,
+ axis_available_space_for_expansion,
+ inner_node_size,
+ get_track_size_estimate,
+ );
+
+ // 11.8. Stretch auto Tracks
+ // This step expands tracks that have an auto max track sizing function by dividing any remaining positive, definite free space equally amongst them.
+ if axis_alignment == AlignContent::STRETCH {
+ stretch_auto_tracks(axis_tracks, axis_min_size, axis_available_space_for_expansion);
+ }
+}
+
+/// Whether it is a minimum or maximum size's space being distributed
+/// This controls behaviour of the space distribution algorithm when distributing beyond limits
+/// See "distributing space beyond limits" at https://www.w3.org/TR/css-grid-1/#extra-space
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+enum IntrinsicContributionType {
+ /// It's a minimum size's space being distributed
+ Minimum,
+ /// It's a maximum size's space being distributed
+ Maximum,
+}
+
+/// Add any planned base size increases to the base size after a round of distributing space to base sizes
+/// Reset the planed base size increase to zero ready for the next round.
+#[inline(always)]
+fn flush_planned_base_size_increases(tracks: &mut [GridTrack]) {
+ for track in tracks {
+ track.base_size += track.base_size_planned_increase;
+ track.base_size_planned_increase = 0.0;
+ }
+}
+
+/// Add any planned growth limit increases to the growth limit after a round of distributing space to growth limits
+/// Reset the planed growth limit increase to zero ready for the next round.
+#[inline(always)]
+fn flush_planned_growth_limit_increases(tracks: &mut [GridTrack], set_infinitely_growable: bool) {
+ for track in tracks {
+ if track.growth_limit_planned_increase > 0.0 {
+ track.growth_limit = if track.growth_limit == f32::INFINITY {
+ track.base_size + track.growth_limit_planned_increase
+ } else {
+ track.growth_limit + track.growth_limit_planned_increase
+ };
+ track.infinitely_growable = set_infinitely_growable;
+ } else {
+ track.infinitely_growable = false;
+ }
+ track.growth_limit_planned_increase = 0.0
+ }
+}
+
+/// 11.4 Initialise Track sizes
+/// Initialize each track’s base size and growth limit.
+#[inline(always)]
+fn initialize_track_sizes(
+ tree: &impl LayoutPartialTree,
+ axis_tracks: &mut [GridTrack],
+ axis_inner_node_size: Option<f32>,
+) {
+ for track in axis_tracks.iter_mut() {
+ // For each track, if the track’s min track sizing function is:
+ // - A fixed sizing function
+ // Resolve to an absolute length and use that size as the track’s initial base size.
+ // Note: Indefinite lengths cannot occur, as they’re treated as auto.
+ // - An intrinsic sizing function
+ // Use an initial base size of zero.
+ track.base_size = track
+ .min_track_sizing_function
+ .definite_value(axis_inner_node_size, |val, basis| tree.calc(val, basis))
+ .unwrap_or(0.0);
+
+ // For each track, if the track’s max track sizing function is:
+ // - A fixed sizing function
+ // Resolve to an absolute length and use that size as the track’s initial growth limit.
+ // - An intrinsic sizing function
+ // Use an initial growth limit of infinity.
+ // - A flexible sizing function
+ // Use an initial growth limit of infinity.
+ track.growth_limit = track
+ .max_track_sizing_function
+ .definite_value(axis_inner_node_size, |val, basis| tree.calc(val, basis))
+ .unwrap_or(f32::INFINITY);
+
+ // In all cases, if the growth limit is less than the base size, increase the growth limit to match the base size.
+ if track.growth_limit < track.base_size {
+ track.growth_limit = track.base_size;
+ }
+ }
+}
+
+/// 11.5.1 Shim baseline-aligned items so their intrinsic size contributions reflect their baseline alignment.
+fn resolve_item_baselines(
+ tree: &mut impl LayoutPartialTree,
+ axis: AbstractAxis,
+ items: &mut [GridItem],
+ inner_node_size: Size<Option<f32>>,
+) {
+ // Sort items by track in the other axis (row) start position so that we can iterate items in groups which
+ // are in the same track in the other axis (row)
+ let other_axis = axis.other();
+ let mut items: Vec<&mut GridItem> = items.iter_mut().collect();
+ items.sort_by_key(|item| item.placement(other_axis).start);
+
+ // Iterate over grid rows
+ let mut remaining_items = &mut items[0..];
+ while !remaining_items.is_empty() {
+ // Get the row index of the current row
+ let current_row = remaining_items[0].placement(other_axis).start;
+
+ // Find the item index of the first item that is in a different row (or None if we've reached the end of the list)
+ let next_row_first_item =
+ remaining_items.iter().position(|item| item.placement(other_axis).start != current_row);
+
+ // Use this index to split the `remaining_items` slice in two slices:
+ // - A `row_items` slice containing the items (that start) in the current row
+ // - A new `remaining_items` consisting of the remainder of the `remaining_items` slice
+ // that hasn't been split off into `row_items
+ let row_items = if let Some(index) = next_row_first_item {
+ let (row_items, tail) = remaining_items.split_at_mut(index);
+ remaining_items = tail;
+ row_items
+ } else {
+ let row_items = remaining_items;
+ remaining_items = &mut [];
+ row_items
+ };
+
+ // Count how many items in *this row* are baseline aligned
+ // If a row has one or zero items participating in baseline alignment then baseline alignment is a no-op
+ // for those items and we skip further computations for that row
+ let row_baseline_item_count = row_items.iter().filter(|item| item.participates_in_baseline_alignment()).count();
+ if row_baseline_item_count <= 1 {
+ continue;
+ }
+
+ // Compute the baselines of all items in the row participating in baseline alignment
+ for item in row_items.iter_mut() {
+ if !item.participates_in_baseline_alignment() {
+ continue;
+ }
+
+ let measured_size_and_baselines = tree.perform_child_layout(
+ item.node,
+ Size::NONE,
+ inner_node_size,
+ Size::MIN_CONTENT,
+ SizingMode::InherentSize,
+ Line::FALSE,
+ );
+
+ let baseline = measured_size_and_baselines.baselines.first;
+ let height = measured_size_and_baselines.size.height;
+
+ // Scroll containers' baselines are determined from their content as if scrolled to the
+ // initial position, but are additionally clamped to their border box.
+ // See https://github.com/w3c/csswg-drafts/issues/7660
+ let baseline = if item.overflow.y.is_scroll_container() {
+ baseline.unwrap_or(height).min(height).max(0.0)
+ } else {
+ baseline.unwrap_or(height)
+ };
+
+ item.baseline = Some(
+ baseline + item.margin.top.resolve_or_zero(inner_node_size.width, |val, basis| tree.calc(val, basis)),
+ );
+ }
+
+ // Compute the max baseline of all items in the row participating in baseline alignment
+ let row_max_baseline = row_items
+ .iter()
+ .filter(|item| item.participates_in_baseline_alignment())
+ .map(|item| item.baseline.unwrap_or(0.0))
+ .max_by(|a, b| a.total_cmp(b))
+ .unwrap();
+
+ // Compute the baseline shim for each item in the row participating in baseline alignment
+ for item in row_items.iter_mut() {
+ if item.participates_in_baseline_alignment() {
+ item.baseline_shim = row_max_baseline - item.baseline.unwrap_or(0.0);
+ item.known_dimensions_cache = None;
+ }
+ }
+ }
+}
+
+/// 11.5 Resolve Intrinsic Track Sizes
+#[allow(clippy::too_many_arguments)]
+fn resolve_intrinsic_track_sizes<Tree: LayoutPartialTree>(
+ tree: &mut Tree,
+ axis: AbstractAxis,
+ axis_tracks: &mut [GridTrack],
+ other_axis_tracks: &[GridTrack],
+ items: &mut [GridItem],
+ axis_available_grid_space: AvailableSpace,
+ inner_node_size: Size<Option<f32>>,
+ get_track_size_estimate: impl Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
+) {
+ // Step 1. Shim baseline-aligned items so their intrinsic size contributions reflect their baseline alignment.
+
+ // Already done at this point. See resolve_item_baselines function.
+
+ // Step 2.
+
+ // The track sizing algorithm requires us to iterate through the items in ascending order of the number of
+ // tracks they span (first items that span 1 track, then items that span 2 tracks, etc).
+ // To avoid having to do multiple iterations of the items, we pre-sort them into this order.
+ //
+ // Items that cross a flexible track are all processed together in a single batch (regardless of their span), so
+ // they only need to be moved to the end of the list. And the order in which items within a batch are processed
+ // does not affect the result, so the remaining items only need to be sorted if any of them span more than one track.
+ let mut partitioned_items: FrontBackVecBuilder<&mut GridItem> = FrontBackVecBuilder::with_capacity(items.len());
+ let mut needs_sort = false;
+ for item in items.iter_mut() {
+ if item.crosses_flexible_track(axis) {
+ partitioned_items.push_back(item);
+ } else {
+ needs_sort |= item.span(axis) > 1;
+ partitioned_items.push_front(item);
+ }
+ }
+ let (mut items, non_flex_item_count) = partitioned_items.into_vec();
+ if needs_sort {
+ items[..non_flex_item_count].sort_by_key(|item| item.span(axis));
+ }
+ let items = items.as_mut_slice();
+
+ // Step 2, Step 3 and Step 4
+ // 2 & 3. Iterate over items that don't cross a flex track. Items should have already been sorted in ascending order
+ // of the number of tracks they span. Step 2 is the 1 track case and has an optimised implementation
+ // 4. Next, repeat the previous step instead considering (together, rather than grouped by span size) all items
+ // that do span a track with a flexible sizing function while
+
+ // Compute item's intrinsic (content-based) sizes
+ // Note: For items with a specified minimum size of auto (the initial value), the minimum contribution is usually equivalent
+ // to the min-content contribution—but can differ in some cases, see §6.6 Automatic Minimum Size of Grid Items.
+ // Also, minimum contribution <= min-content contribution <= max-content contribution.
+
+ let axis_inner_node_size = inner_node_size.get(axis);
+ let mut item_sizer =
+ IntrinsicSizeMeasurer { tree, other_axis_tracks, axis, inner_node_size, get_track_size_estimate };
+
+ let mut batched_item_iterator = ItemBatcher::new(axis);
+ while let Some((batch, is_flex)) = batched_item_iterator.next(items) {
+ // 2. Size tracks to fit non-spanning items: For each track with an intrinsic track sizing function and not a flexible sizing function,
+ // consider the items in it with a span of 1:
+ let batch_span = batch[0].placement(axis).span();
+ if !is_flex && batch_span == 1 {
+ for item in batch.iter_mut() {
+ let track_index = item.placement_indexes(axis).start + 1;
+ let track = &axis_tracks[track_index as usize];
+
+ // Handle base sizes
+ let new_base_size = match track.min_track_sizing_function.0.tag() {
+ CompactLength::MIN_CONTENT_TAG => {
+ f32_max(track.base_size, item_sizer.min_content_contribution(item, axis_tracks))
+ }
+ CompactLength::MAX_CONTENT_TAG => {
+ f32_max(track.base_size, item_sizer.max_content_contribution(item, axis_tracks))
+ }
+ // If the container size is indefinite and has not yet been resolved then percentage sized
+ // tracks are treated as auto
+ _ if track.min_track_sizing_function.behaves_as_auto(axis_inner_node_size) => {
+ let space = match axis_available_grid_space {
+ // QUIRK: The spec says that:
+ //
+ // If the grid container is being sized under a min- or max-content constraint, use the items’ limited
+ // min-content contributions in place of their minimum contributions here.
+ //
+ // However, in practice browsers only seem to apply this rule if the item is not a scroll container
+ // (note that overflow:hidden counts as a scroll container), giving the automatic minimum size of scroll
+ // containers (zero) precedence over the min-content contributions.
+ AvailableSpace::MinContent | AvailableSpace::MaxContent
+ if !item.overflow.get(axis).is_scroll_container() =>
+ {
+ let axis_minimum_size = item_sizer.minimum_contribution(item, axis_tracks);
+ let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
+ let limit = track
+ .max_track_sizing_function
+ .definite_limit(axis_inner_node_size, |val, basis| item_sizer.calc(val, basis));
+ axis_min_content_size.maybe_min(limit).max(axis_minimum_size)
+ }
+ _ => item_sizer.minimum_contribution(item, axis_tracks),
+ };
+ f32_max(track.base_size, space)
+ }
+ // Do nothing as it's not an intrinsic track sizing function
+ _ => track.base_size,
+ };
+ axis_tracks[track_index as usize].base_size = new_base_size;
+
+ // Handle growth limits
+ //
+ // Computing an item's contributions calls into the child, so they are only computed if they are used.
+ // The min-content contribution is computed for every item in an intrinsic track (even where only the
+ // max-content contribution determines the growth limit), as the check for whether track sizing needs
+ // to be re-run compares each such item's min-content contribution against the one cached here.
+ let track = &axis_tracks[track_index as usize];
+ let max_track_sizing_function = track.max_track_sizing_function;
+ let fit_content_limit = track.fit_content_limit();
+ let min_content_contribution = if track.has_intrinsic_sizing_function() {
+ Some(item_sizer.min_content_contribution(item, axis_tracks))
+ } else {
+ None
+ };
+ let planned_increase = if max_track_sizing_function.is_fit_content() {
+ // Always increase the growth limit to at least the size of the *fit-content limited*
+ // max-content contribution
+ let max_content_contribution =
+ f32_min(item_sizer.max_content_contribution(item, axis_tracks), fit_content_limit);
+
+ // If item is not a scroll container, then increase the growth limit to at least the
+ // size of the min-content contribution
+ match min_content_contribution {
+ Some(min_content_contribution) if !item.overflow.get(axis).is_scroll_container() => {
+ Some(f32_max(min_content_contribution, max_content_contribution))
+ }
+ _ => Some(max_content_contribution),
+ }
+ } else if max_track_sizing_function.is_max_content_alike()
+ || max_track_sizing_function.uses_percentage() && axis_inner_node_size.is_none()
+ {
+ // If the container size is indefinite and has not yet been resolved then percentage sized
+ // tracks should be treated as auto (this matches Chrome's behaviour and seems sensible)
+ Some(item_sizer.max_content_contribution(item, axis_tracks))
+ } else if max_track_sizing_function.is_intrinsic() {
+ min_content_contribution
+ } else {
+ None
+ };
+ if let Some(planned_increase) = planned_increase {
+ let track = &mut axis_tracks[track_index as usize];
+ track.growth_limit_planned_increase =
+ f32_max(track.growth_limit_planned_increase, planned_increase);
+ }
+ }
+
+ for track in axis_tracks.iter_mut() {
+ if track.growth_limit_planned_increase > 0.0 {
+ track.growth_limit = if track.growth_limit == f32::INFINITY {
+ track.growth_limit_planned_increase
+ } else {
+ f32_max(track.growth_limit, track.growth_limit_planned_increase)
+ };
+ }
+ track.infinitely_growable = false;
+ track.growth_limit_planned_increase = 0.0;
+ if track.growth_limit < track.base_size {
+ track.growth_limit = track.base_size;
+ }
+ }
+
+ continue;
+ }
+
+ // 1. For intrinsic minimums:
+ // First increase the base size of tracks with an intrinsic min track sizing function
+ for item in batch.iter_mut().filter(|item| item.crosses_intrinsic_track(axis)) {
+ // ...by distributing extra space as needed to accommodate these items’ minimum contributions.
+ //
+ // QUIRK: The spec says that:
+ //
+ // If the grid container is being sized under a min- or max-content constraint, use the items’ limited min-content contributions
+ // in place of their minimum contributions here.
+ //
+ // However, in practice browsers only seem to apply this rule if the item is not a scroll container (note that overflow:hidden counts as
+ // a scroll container), giving the automatic minimum size of scroll containers (zero) precedence over the min-content contributions.
+ let space = match axis_available_grid_space {
+ AvailableSpace::MinContent | AvailableSpace::MaxContent
+ if !item.overflow.get(axis).is_scroll_container() =>
+ {
+ let axis_minimum_size = item_sizer.minimum_contribution(item, axis_tracks);
+ let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
+ let limit = item.spanned_track_limit(axis, axis_tracks, axis_inner_node_size, &|val, basis| {
+ item_sizer.calc(val, basis)
+ });
+ let limited_min_content = axis_min_content_size.maybe_min(limit).max(axis_minimum_size);
+
+ // For items crossing flexible tracks, browsers hand the content-derived contribution to
+ // the flexible tracks only in proportion to the crossed flex factor sum, clamped at one
+ // (CSS Grid 2, 12.5: "if the sum is less than one, distribute that proportion of
+ // space"). The proportion applies to the space left after covering the spanned
+ // inflexible tracks, and the item's minimum contribution acts as a floor on the result:
+ // a definite size still spreads over `0fr` tracks in full. This is what lets a `0fr`
+ // track holding a `min-height: 0` item collapse to zero, which the
+ // `grid-template-rows: 0fr` to `1fr` collapse animation pattern relies on.
+ if is_flex {
+ let spanned_tracks = &axis_tracks[item.track_range_excluding_lines(axis)];
+ let inflexible_sizes: f32 = spanned_tracks
+ .iter()
+ .filter(|track| !track.is_flexible())
+ .map(|track| track.base_size)
+ .sum();
+ let scale = f32_min(crossed_flex_factor_sum(spanned_tracks), 1.0);
+ let excess = f32_max(limited_min_content - inflexible_sizes, 0.0);
+ f32_max(axis_minimum_size, inflexible_sizes + excess * scale)
+ } else {
+ limited_min_content
+ }
+ }
+ _ => item_sizer.minimum_contribution(item, axis_tracks),
+ };
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ let has_intrinsic_min_track_sizing_function = |track: &GridTrack| {
+ track
+ .min_track_sizing_function
+ .definite_value(axis_inner_node_size, |val, basis| item_sizer.calc(val, basis))
+ .is_none()
+ };
+ if item.overflow.get(axis).is_scroll_container() {
+ let fit_content_limit = move |track: &GridTrack| track.fit_content_limited_growth_limit();
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_intrinsic_min_track_sizing_function,
+ fit_content_limit,
+ IntrinsicContributionType::Minimum,
+ );
+ } else {
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_intrinsic_min_track_sizing_function,
+ |track| track.growth_limit,
+ IntrinsicContributionType::Minimum,
+ );
+ }
+ }
+ }
+ flush_planned_base_size_increases(axis_tracks);
+
+ // 2. For content-based minimums:
+ // Next continue to increase the base size of tracks with a min track sizing function of min-content or max-content
+ // by distributing extra space as needed to account for these items' min-content contributions.
+ let has_min_or_max_content_min_track_sizing_function =
+ move |track: &GridTrack| track.min_track_sizing_function.is_min_or_max_content();
+ for item in batch.iter_mut() {
+ if !item.spans_track_matching(axis, axis_tracks, has_min_or_max_content_min_track_sizing_function) {
+ continue;
+ }
+ let space = item_sizer.min_content_contribution(item, axis_tracks);
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ if item.overflow.get(axis).is_scroll_container() {
+ let fit_content_limit = move |track: &GridTrack| track.fit_content_limited_growth_limit();
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_min_or_max_content_min_track_sizing_function,
+ fit_content_limit,
+ IntrinsicContributionType::Minimum,
+ );
+ } else {
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_min_or_max_content_min_track_sizing_function,
+ |track| track.growth_limit,
+ IntrinsicContributionType::Minimum,
+ );
+ }
+ }
+ }
+ flush_planned_base_size_increases(axis_tracks);
+
+ // 3. For max-content minimums:
+
+ // If the grid container is being sized under a max-content constraint, continue to increase the base size of tracks with
+ // a min track sizing function of auto or max-content by distributing extra space as needed to account for these items'
+ // limited max-content contributions.
+
+ // Define fit_content_limited_growth_limit function. This is passed to the distribute_space_up_to_limits
+ // helper function, and is used to compute the limit to distribute up to for each track.
+ // Wrapping the method on GridTrack is necessary in order to resolve percentage fit-content arguments.
+ if axis_available_grid_space == AvailableSpace::MaxContent {
+ /// Whether a track:
+ /// - has an Auto MIN track sizing function
+ /// - Does not have a MinContent MAX track sizing function
+ ///
+ /// The latter condition was added in order to match Chrome. But I believe it is due to the provision
+ /// under minmax here https://www.w3.org/TR/css-grid-1/#track-sizes which states that:
+ ///
+ /// "If the max is less than the min, then the max will be floored by the min (essentially yielding minmax(min, min))"
+ #[inline(always)]
+ fn has_auto_min_track_sizing_function(track: &GridTrack) -> bool {
+ track.min_track_sizing_function.is_auto() && !track.max_track_sizing_function.is_min_content()
+ }
+
+ /// Whether a track has a MaxContent min track sizing function
+ #[inline(always)]
+ fn has_max_content_min_track_sizing_function(track: &GridTrack) -> bool {
+ track.min_track_sizing_function.is_max_content()
+ }
+
+ for item in batch.iter_mut() {
+ if !item.spans_track_matching(axis, axis_tracks, |track| {
+ has_auto_min_track_sizing_function(track) || has_max_content_min_track_sizing_function(track)
+ }) {
+ continue;
+ }
+ let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
+ let limit = item.spanned_track_limit(axis, axis_tracks, axis_inner_node_size, &|val, basis| {
+ item_sizer.calc(val, basis)
+ });
+ let mut space = axis_max_content_size.maybe_min(limit);
+
+ // As for the intrinsic minimums above: scale the space beyond the spanned inflexible
+ // tracks by the crossed flex factor sum, clamped at one. Anchoring at the inflexible
+ // track sizes rather than the current base sizes keeps this pass from compounding with
+ // the scaling already applied to the min-content contribution.
+ if is_flex {
+ let spanned_tracks = &axis_tracks[item.track_range_excluding_lines(axis)];
+ let inflexible_sizes: f32 =
+ spanned_tracks.iter().filter(|track| !track.is_flexible()).map(|track| track.base_size).sum();
+ let scale = f32_min(crossed_flex_factor_sum(spanned_tracks), 1.0);
+ space = inflexible_sizes + f32_max(space - inflexible_sizes, 0.0) * scale;
+ }
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ // If any of the tracks spanned by the item have a MaxContent min track sizing function then
+ // distribute space only to those tracks. Otherwise distribute space to tracks with an Auto min
+ // track sizing function.
+ //
+ // Note: this prioritisation of MaxContent over Auto is not mentioned in the spec (which suggests that
+ // we ought to distribute space evenly between MaxContent and Auto tracks). But it is implemented like
+ // this in both Chrome and Firefox (and it does have a certain logic to it), so we implement it too for
+ // compatibility.
+ //
+ // See: https://www.w3.org/TR/css-grid-1/#track-size-max-content-min
+ if tracks.iter().any(has_max_content_min_track_sizing_function) {
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_max_content_min_track_sizing_function,
+ |_| f32::INFINITY,
+ IntrinsicContributionType::Maximum,
+ );
+ } else {
+ let fit_content_limited_growth_limit =
+ move |track: &GridTrack| track.fit_content_limited_growth_limit();
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_auto_min_track_sizing_function,
+ fit_content_limited_growth_limit,
+ IntrinsicContributionType::Maximum,
+ );
+ }
+ }
+ }
+ flush_planned_base_size_increases(axis_tracks);
+ }
+
+ // In all cases, continue to increase the base size of tracks with a min track sizing function of max-content by distributing
+ // extra space as needed to account for these items' max-content contributions.
+ let has_max_content_min_track_sizing_function =
+ move |track: &GridTrack| track.min_track_sizing_function.is_max_content();
+ for item in batch.iter_mut() {
+ if !item.spans_track_matching(axis, axis_tracks, has_max_content_min_track_sizing_function) {
+ continue;
+ }
+ let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
+ let space = axis_max_content_size;
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ distribute_item_space_to_base_size(
+ is_flex,
+ space,
+ tracks,
+ has_max_content_min_track_sizing_function,
+ |track| track.growth_limit,
+ IntrinsicContributionType::Maximum,
+ );
+ }
+ }
+ flush_planned_base_size_increases(axis_tracks);
+
+ // 4. If at this point any track’s growth limit is now less than its base size, increase its growth limit to match its base size.
+ for track in axis_tracks.iter_mut() {
+ if track.growth_limit < track.base_size {
+ track.growth_limit = track.base_size;
+ }
+ }
+
+ // If a track is a flexible track, then it has flexible max track sizing function
+ // It cannot also have an intrinsic max track sizing function, so these steps do not apply.
+ if !is_flex {
+ // 5. For intrinsic maximums: Next increase the growth limit of tracks with an intrinsic max track sizing function by
+ // distributing extra space as needed to account for these items' min-content contributions.
+ let has_intrinsic_max_track_sizing_function =
+ move |track: &GridTrack| !track.max_track_sizing_function.has_definite_value(axis_inner_node_size);
+ for item in batch.iter_mut() {
+ if !item.spans_track_matching(axis, axis_tracks, has_intrinsic_max_track_sizing_function) {
+ continue;
+ }
+ let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
+ let space = axis_min_content_size;
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ distribute_item_space_to_growth_limit(space, tracks, has_intrinsic_max_track_sizing_function);
+ }
+ }
+ // Mark any tracks whose growth limit changed from infinite to finite in this step as infinitely growable for the next step.
+ flush_planned_growth_limit_increases(axis_tracks, true);
+
+ // 6. For max-content maximums: Lastly continue to increase the growth limit of tracks with a max track sizing function of max-content
+ // by distributing extra space as needed to account for these items' max-content contributions. However, limit the growth of any
+ // fit-content() tracks by their fit-content() argument.
+ let has_max_content_max_track_sizing_function = |track: &GridTrack| {
+ track.max_track_sizing_function.is_max_content_alike()
+ || (track.max_track_sizing_function.uses_percentage() && axis_inner_node_size.is_none())
+ };
+ for item in batch.iter_mut() {
+ if !item.spans_track_matching(axis, axis_tracks, has_max_content_max_track_sizing_function) {
+ continue;
+ }
+ let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
+ let space = axis_max_content_size;
+ let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
+ if space > 0.0 {
+ distribute_item_space_to_growth_limit(space, tracks, has_max_content_max_track_sizing_function);
+ }
+ }
+ // Mark any tracks whose growth limit changed from infinite to finite in this step as infinitely growable for the next step.
+ flush_planned_growth_limit_increases(axis_tracks, false);
+ }
+ }
+
+ // Step 5. If any track still has an infinite growth limit (because, for example, it had no items placed
+ // in it or it is a flexible track), set its growth limit to its base size.
+ // NOTE: this step is super-important to ensure that the "Maximise Tracks" step doesn't affect flexible tracks
+ axis_tracks
+ .iter_mut()
+ .filter(|track| track.growth_limit == f32::INFINITY)
+ .for_each(|track| track.growth_limit = track.base_size);
+}
+
+/// The sum of the flex factors of the flexible tracks in an item's spanned track range
+#[inline(always)]
+fn crossed_flex_factor_sum(tracks: &[GridTrack]) -> f32 {
+ tracks.iter().filter(|track| track.is_flexible()).map(|track| track.flex_factor()).sum()
+}
+
+/// 11.5.1. Distributing Extra Space Across Spanned Tracks
+/// https://www.w3.org/TR/css-grid-1/#extra-space
+#[inline(always)]
+fn distribute_item_space_to_base_size(
+ is_flex: bool,
+ space: f32,
+ tracks: &mut [GridTrack],
+ track_is_affected: impl Fn(&GridTrack) -> bool,
+ track_limit: impl Fn(&GridTrack) -> f32,
+ intrinsic_contribution_type: IntrinsicContributionType,
+) {
+ if is_flex {
+ let filter = |track: &GridTrack| track.is_flexible() && track_is_affected(track);
+
+ // If the sum of the flex factors of the affected tracks is greater than zero, distribute
+ // space according to the ratios of the tracks' flex factors. Otherwise distribute space equally.
+ //
+ // Note: the spec says to compute the sum over all flexible tracks spanned by the item, and to
+ // blend flex-factor-proportional and equal distribution when the sum is below one. But Chrome
+ // computes the sum over only the affected tracks and uses pure flex-factor ratios whenever
+ // that sum is non-zero, so we do the same for compatibility.
+ let flex_factor_sum: f32 = tracks.iter().filter(|track| filter(track)).map(|track| track.flex_factor()).sum();
+ if flex_factor_sum > 0.0 {
+ distribute_item_space_to_base_size_inner(
+ space,
+ tracks,
+ filter,
+ |track| track.flex_factor(),
+ track_limit,
+ intrinsic_contribution_type,
+ )
+ } else {
+ distribute_item_space_to_base_size_inner(
+ space,
+ tracks,
+ filter,
+ |_| 1.0,
+ track_limit,
+ intrinsic_contribution_type,
+ )
+ }
+ } else {
+ distribute_item_space_to_base_size_inner(
+ space,
+ tracks,
+ track_is_affected,
+ |_| 1.0,
+ track_limit,
+ intrinsic_contribution_type,
+ )
+ }
+
+ /// Inner function that doesn't account for differences due to distributing to flex items
+ /// This difference is handled by the closure passed in above
+ fn distribute_item_space_to_base_size_inner(
+ space: f32,
+ tracks: &mut [GridTrack],
+ track_is_affected: impl Fn(&GridTrack) -> bool,
+ track_distribution_proportion: impl Fn(&GridTrack) -> f32,
+ track_limit: impl Fn(&GridTrack) -> f32,
+ intrinsic_contribution_type: IntrinsicContributionType,
+ ) {
+ // Skip this distribution if there is either
+ // - no space to distribute
+ // - no affected tracks to distribute space to
+ if space == 0.0 || !tracks.iter().any(&track_is_affected) {
+ return;
+ }
+
+ // Define get_base_size function. This is passed to the distribute_space_up_to_limits helper function
+ // to indicate that it is the base size that is being distributed to.
+ let get_base_size = |track: &GridTrack| track.base_size;
+
+ // 1. Find the space to distribute
+ let track_sizes: f32 = tracks.iter().map(|track| track.base_size).sum();
+ let extra_space: f32 = f32_max(0.0, space - track_sizes);
+
+ // 2. Distribute space up to limits:
+ // Note: there are two exit conditions to this loop:
+ // - We run out of space to distribute (extra_space falls below THRESHOLD)
+ // - We run out of growable tracks to distribute to
+
+ /// Define a small constant to avoid infinite loops due to rounding errors. Rather than stopping distributing
+ /// extra space when it gets to exactly zero, we will stop when it falls below this amount
+ const THRESHOLD: f32 = 0.000001;
+
+ let extra_space = distribute_space_up_to_limits(
+ extra_space,
+ tracks,
+ &track_is_affected,
+ &track_distribution_proportion,
+ get_base_size,
+ &track_limit,
+ );
+
+ // 3. Distribute remaining span beyond limits (if any)
+ if extra_space > THRESHOLD {
+ // When accommodating minimum contributions or accommodating min-content contributions:
+ // - any affected track that happens to also have an intrinsic max track sizing function;
+ // When accommodating max-content contributions:
+ // - any affected track that happens to also have a max-content max track sizing function
+ let mut filter = match intrinsic_contribution_type {
+ IntrinsicContributionType::Minimum => {
+ (|track: &GridTrack| track.max_track_sizing_function.is_intrinsic()) as fn(&GridTrack) -> bool
+ }
+ IntrinsicContributionType::Maximum => {
+ (|track: &GridTrack| track.max_track_sizing_function.is_max_or_fit_content())
+ as fn(&GridTrack) -> bool
+ }
+ };
+
+ // If there are no such tracks (matching filter above), then use all affected tracks.
+ let number_of_tracks =
+ tracks.iter().filter(|track| track_is_affected(track)).filter(|track| filter(track)).count();
+ if number_of_tracks == 0 {
+ filter = (|_| true) as fn(&GridTrack) -> bool;
+ }
+
+ // When distributing beyond limits, growth limits are ignored, but the argument
+ // to any fit-content() max track sizing function still caps growth.
+ distribute_space_up_to_limits(
+ extra_space,
+ tracks,
+ |track| track_is_affected(track) && filter(track),
+ &track_distribution_proportion,
+ get_base_size,
+ |track| track.fit_content_limit(),
+ );
+ }
+
+ // 4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned increase
+ // set the track’s planned increase to that value.
+ for track in tracks.iter_mut() {
+ if track.item_incurred_increase > track.base_size_planned_increase {
+ track.base_size_planned_increase = track.item_incurred_increase;
+ }
+
+ // Reset the item_incurresed increase ready for the next space distribution
+ track.item_incurred_increase = 0.0;
+ }
+ }
+}
+
+/// 11.5.1. Distributing Extra Space Across Spanned Tracks
+/// This is simplified (and faster) version of the algorithm for growth limits
+/// https://www.w3.org/TR/css-grid-1/#extra-space
+fn distribute_item_space_to_growth_limit(
+ space: f32,
+ tracks: &mut [GridTrack],
+ track_is_affected: impl Fn(&GridTrack) -> bool,
+) {
+ // Skip this distribution if there is either
+ // - no space to distribute
+ // - no affected tracks to distribute space to
+ if space == 0.0 || tracks.iter().filter(|track| track_is_affected(track)).count() == 0 {
+ return;
+ }
+
+ // 1. Find the space to distribute
+ let track_sizes: f32 = tracks
+ .iter()
+ .map(|track| if track.growth_limit == f32::INFINITY { track.base_size } else { track.growth_limit })
+ .sum();
+ let extra_space: f32 = f32_max(0.0, space - track_sizes);
+
+ // 2. Distribute space up to limits:
+ // For growth limits the limit is the growth limit itself unless the track is marked infinitely growable (or its
+ // growth limit is still infinite), in which case it is the track's fit-content() argument if it has one, or
+ // infinity if it does not. As the affected size of a track that isn't growable is its growth limit, those
+ // tracks won't receive any space in this step.
+ let growth_limit_or_base_size =
+ |track: &GridTrack| if track.growth_limit == f32::INFINITY { track.base_size } else { track.growth_limit };
+ let extra_space = distribute_space_up_to_limits(
+ extra_space,
+ tracks,
+ |track| track_is_affected(track) && (track.infinitely_growable || track.growth_limit == f32::INFINITY),
+ |_| 1.0,
+ growth_limit_or_base_size,
+ move |track| track.fit_content_limit(),
+ );
+
+ // 3. Distribute space beyond limits
+ // If space remains after all tracks are frozen, unfreeze and continue to distribute space to the item-incurred increase
+ // ...when handling any intrinsic growth limit: all affected tracks.
+ if extra_space > 0.0 {
+ distribute_space_up_to_limits(
+ extra_space,
+ tracks,
+ track_is_affected,
+ |_| 1.0,
+ growth_limit_or_base_size,
+ move |track| track.fit_content_limit(),
+ );
+ }
+
+ // 4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned increase
+ // set the track’s planned increase to that value.
+ for track in tracks.iter_mut() {
+ if track.item_incurred_increase > track.growth_limit_planned_increase {
+ track.growth_limit_planned_increase = track.item_incurred_increase;
+ }
+
+ // Reset the item_incurresed increase ready for the next space distribution
+ track.item_incurred_increase = 0.0;
+ }
+}
+
+/// 11.6 Maximise Tracks
+/// Distributes free space (if any) to tracks with FINITE growth limits, up to their limits.
+#[inline(always)]
+fn maximise_tracks(axis_tracks: &mut [GridTrack], axis_available_grid_space: AvailableSpace) {
+ let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
+ let free_space = axis_available_grid_space.compute_free_space(used_space);
+ if free_space == f32::INFINITY {
+ axis_tracks.iter_mut().for_each(|track| track.base_size = track.growth_limit);
+ } else if free_space > 0.0 {
+ distribute_space_up_to_limits(
+ free_space,
+ axis_tracks,
+ |_| true,
+ |_| 1.0,
+ |track| track.base_size,
+ move |track: &GridTrack| track.fit_content_limited_growth_limit(),
+ );
+ for track in axis_tracks.iter_mut() {
+ track.base_size += track.item_incurred_increase;
+ track.item_incurred_increase = 0.0;
+ }
+ }
+}
+
+/// 11.7. Expand Flexible Tracks
+/// This step sizes flexible tracks using the largest value it can assign to an fr without exceeding the available space.
+#[allow(clippy::too_many_arguments)]
+#[inline(always)]
+fn expand_flexible_tracks<Tree: LayoutPartialTree>(
+ tree: &mut Tree,
+ axis: AbstractAxis,
+ axis_tracks: &mut [GridTrack],
+ other_axis_tracks: &[GridTrack],
+ items: &mut [GridItem],
+ axis_min_size: Option<f32>,
+ axis_max_size: Option<f32>,
+ axis_available_space_for_expansion: AvailableSpace,
+ inner_node_size: Size<Option<f32>>,
+ get_track_size_estimate: impl Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
+) {
+ let mut item_sizer =
+ IntrinsicSizeMeasurer { tree, other_axis_tracks, axis, inner_node_size, get_track_size_estimate };
+
+ // First, find the grid’s used flex fraction:
+ let flex_fraction = match axis_available_space_for_expansion {
+ // If the free space is zero:
+ // The used flex fraction is zero.
+ // Otherwise, if the free space is a definite length:
+ // The used flex fraction is the result of finding the size of an fr using all of the grid tracks and
+ // a space to fill of the available grid space.
+ AvailableSpace::Definite(available_space) => {
+ let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
+ let free_space = available_space - used_space;
+ if free_space <= 0.0 {
+ 0.0
+ } else {
+ find_size_of_fr(axis_tracks, available_space)
+ }
+ }
+ // If ... sizing the grid container under a min-content constraint the used flex fraction is zero.
+ AvailableSpace::MinContent => 0.0,
+ // Otherwise, if the free space is an indefinite length:
+ AvailableSpace::MaxContent => {
+ // The used flex fraction is the maximum of:
+ let flex_fraction = f32_max(
+ // For each flexible track, if the flexible track’s flex factor is greater than one,
+ // the result of dividing the track’s base size by its flex factor; otherwise, the track’s base size.
+ axis_tracks
+ .iter()
+ .filter(|track| track.max_track_sizing_function.is_fr())
+ .map(|track| {
+ let flex_factor = track.flex_factor();
+ if flex_factor > 1.0 {
+ track.base_size / flex_factor
+ } else {
+ track.base_size
+ }
+ })
+ .max_by(|a, b| a.total_cmp(b))
+ .unwrap_or(0.0),
+ // For each grid item that crosses a flexible track, the result of finding the size of an fr using all the grid tracks
+ // that the item crosses and a space to fill of the item’s max-content contribution.
+ items
+ .iter_mut()
+ .filter(|item| item.crosses_flexible_track(axis))
+ .map(|item| {
+ let max_content_contribution = item_sizer.max_content_contribution(item, axis_tracks);
+ let tracks = &axis_tracks[item.track_range_excluding_lines(axis)];
+ find_size_of_fr(tracks, max_content_contribution)
+ })
+ .max_by(|a, b| a.total_cmp(b))
+ .unwrap_or(0.0),
+ );
+
+ // If using this flex fraction would cause the grid to be smaller than the grid container’s min-width/height (or larger than the
+ // grid container’s max-width/height), then redo this step, treating the free space as definite and the available grid space as equal
+ // to the grid container’s inner size when it’s sized to its min-width/height (max-width/height).
+ // (Note: min_size takes precedence over max_size)
+ let hypothetical_grid_size: f32 = axis_tracks
+ .iter()
+ .map(|track| {
+ if track.max_track_sizing_function.is_fr() {
+ let track_flex_factor = track.max_track_sizing_function.0.value();
+ f32_max(track.base_size, track_flex_factor * flex_fraction)
+ } else {
+ track.base_size
+ }
+ })
+ .sum();
+ let axis_min_size = axis_min_size.unwrap_or(0.0);
+ let axis_max_size = axis_max_size.unwrap_or(f32::INFINITY);
+ if hypothetical_grid_size < axis_min_size {
+ find_size_of_fr(axis_tracks, axis_min_size)
+ } else if hypothetical_grid_size > axis_max_size {
+ find_size_of_fr(axis_tracks, axis_max_size)
+ } else {
+ flex_fraction
+ }
+ }
+ };
+
+ // For each flexible track, if the product of the used flex fraction and the track’s flex factor is greater
+ // than the track’s base size, set its base size to that product.
+ for track in axis_tracks.iter_mut().filter(|track| track.max_track_sizing_function.is_fr()) {
+ let track_flex_factor = track.max_track_sizing_function.0.value();
+ track.base_size = f32_max(track.base_size, track_flex_factor * flex_fraction);
+ }
+}
+
+/// 11.7.1. Find the Size of an fr
+/// This algorithm finds the largest size that an fr unit can be without exceeding the target size.
+/// It must be called with a set of grid tracks and some quantity of space to fill.
+#[inline(always)]
+fn find_size_of_fr(tracks: &[GridTrack], space_to_fill: f32) -> f32 {
+ // Handle the trivial case where there is no space to fill
+ // Do not remove as otherwise the loop below will loop infinitely
+ if space_to_fill == 0.0 {
+ return 0.0;
+ }
+
+ // If the product of the hypothetical fr size (computed below) and any flexible track’s flex factor
+ // is less than the track’s base size, then we must restart this algorithm treating all such tracks as inflexible.
+ // We therefore wrap the entire algorithm in a loop, with an hypothetical_fr_size of INFINITY such that the above
+ // condition can never be true for the first iteration.
+ let mut hypothetical_fr_size = f32::INFINITY;
+ let mut previous_iter_hypothetical_fr_size;
+ // Every restart of the algorithm treats at least one more flexible track as inflexible, so a valid
+ // hypothetical fr size is always found within `tracks.len() + 1` iterations. Non-finite values (which
+ // can arise from non-finite style inputs) break that invariant as comparisons against `NaN` are always
+ // false, so we bound the iteration count to guarantee termination.
+ let max_iterations = tracks.len() + 1;
+ for _ in 0..max_iterations {
+ // Let leftover space be the space to fill minus the base sizes of the non-flexible grid tracks.
+ // Let flex factor sum be the sum of the flex factors of the flexible tracks. If this value is less than 1, set it to 1 instead.
+ // We compute both of these in a single loop to avoid iterating over the data twice
+ let mut used_space = 0.0;
+ let mut naive_flex_factor_sum = 0.0;
+ for track in tracks.iter() {
+ // Tracks for which flex_factor * hypothetical_fr_size < track.base_size are treated as inflexible
+ if track.max_track_sizing_function.is_fr()
+ && track.max_track_sizing_function.0.value() * hypothetical_fr_size >= track.base_size
+ {
+ naive_flex_factor_sum += track.max_track_sizing_function.0.value();
+ } else {
+ used_space += track.base_size;
+ };
+ }
+ let leftover_space = space_to_fill - used_space;
+ let flex_factor = f32_max(naive_flex_factor_sum, 1.0);
+
+ // Let the hypothetical fr size be the leftover space divided by the flex factor sum.
+ previous_iter_hypothetical_fr_size = hypothetical_fr_size;
+ hypothetical_fr_size = leftover_space / flex_factor;
+
+ // If the product of the hypothetical fr size and a flexible track’s flex factor is less than the track’s base size,
+ // restart this algorithm treating all such tracks as inflexible.
+ // We keep track of the hypothetical_fr_size
+ let hypothetical_fr_size_is_valid = tracks.iter().all(|track| {
+ if track.max_track_sizing_function.is_fr() {
+ let flex_factor = track.max_track_sizing_function.0.value();
+ flex_factor * hypothetical_fr_size >= track.base_size
+ || flex_factor * previous_iter_hypothetical_fr_size < track.base_size
+ } else {
+ true
+ }
+ });
+ if hypothetical_fr_size_is_valid {
+ break;
+ }
+ }
+
+ // Return the hypothetical fr size.
+ hypothetical_fr_size
+}
+
+/// 11.8. Stretch auto Tracks
+/// This step expands tracks that have an auto max track sizing function by dividing any remaining positive, definite free space equally amongst them.
+#[inline(always)]
+fn stretch_auto_tracks(
+ axis_tracks: &mut [GridTrack],
+ axis_min_size: Option<f32>,
+ axis_available_space_for_expansion: AvailableSpace,
+) {
+ let num_auto_tracks = axis_tracks.iter().filter(|track| track.max_track_sizing_function.is_auto()).count();
+ if num_auto_tracks > 0 {
+ let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
+
+ // If the free space is indefinite, but the grid container has a definite min-width/height
+ // use that size to calculate the free space for this step instead.
+ let free_space = if axis_available_space_for_expansion.is_definite() {
+ axis_available_space_for_expansion.compute_free_space(used_space)
+ } else {
+ match axis_min_size {
+ Some(size) => size - used_space,
+ None => 0.0,
+ }
+ };
+ if free_space > 0.0 {
+ let extra_space_per_auto_track = free_space / num_auto_tracks as f32;
+ axis_tracks
+ .iter_mut()
+ .filter(|track| track.max_track_sizing_function.is_auto())
+ .for_each(|track| track.base_size += extra_space_per_auto_track);
+ }
+ }
+}
+
+/// Helper function for distributing space to tracks evenly
+/// Used by both distribute_item_space_to_base_size and maximise_tracks steps
+#[inline(always)]
+fn distribute_space_up_to_limits(
+ space_to_distribute: f32,
+ tracks: &mut [GridTrack],
+ track_is_affected: impl Fn(&GridTrack) -> bool,
+ track_distribution_proportion: impl Fn(&GridTrack) -> f32,
+ track_affected_property: impl Fn(&GridTrack) -> f32,
+ track_limit: impl Fn(&GridTrack) -> f32,
+) -> f32 {
+ /// Define a small constant to avoid infinite loops due to rounding errors. Rather than stopping distributing
+ /// extra space when it gets to exactly zero, we will stop when it falls below this amount
+ const THRESHOLD: f32 = 0.01;
+
+ // Each iteration freezes at least one track at its limit, so the loop always completes within
+ // `tracks.len() + 1` iterations. Non-finite values (which can arise from non-finite style inputs) can
+ // prevent any space from being distributed, so we bound the iteration count to guarantee termination.
+ let max_iterations = tracks.len() + 1;
+
+ let mut space_to_distribute = space_to_distribute;
+ for _ in 0..max_iterations {
+ if space_to_distribute <= THRESHOLD {
+ break;
+ }
+ let track_distribution_proportion_sum: f32 = tracks
+ .iter()
+ .filter(|track| track_affected_property(track) + track.item_incurred_increase < track_limit(track))
+ .filter(|track| track_is_affected(track))
+ .map(&track_distribution_proportion)
+ .sum();
+
+ if track_distribution_proportion_sum == 0.0 {
+ break;
+ }
+
+ // Compute item-incurred increase for this iteration
+ let min_increase_limit = tracks
+ .iter()
+ .filter(|track| track_affected_property(track) + track.item_incurred_increase < track_limit(track))
+ .filter(|track| track_is_affected(track))
+ .map(|track| {
+ (track_limit(track) - track_affected_property(track) - track.item_incurred_increase)
+ / track_distribution_proportion(track)
+ })
+ .min_by(|a, b| a.total_cmp(b))
+ .unwrap(); // We will never pass an empty track list to this function
+ let iteration_item_incurred_increase =
+ f32_min(min_increase_limit, space_to_distribute / track_distribution_proportion_sum);
+
+ for track in tracks.iter_mut().filter(|track| track_is_affected(track)) {
+ let increase = iteration_item_incurred_increase * track_distribution_proportion(track);
+ if increase > 0.0
+ && track_affected_property(track) + track.item_incurred_increase + increase
+ <= track_limit(track) + THRESHOLD
+ {
+ track.item_incurred_increase += increase;
+ space_to_distribute -= increase;
+ }
+ }
+ }
+
+ space_to_distribute
+}
diff --git a/vendor/taffy/src/compute/grid/types/cell_occupancy.rs b/vendor/taffy/src/compute/grid/types/cell_occupancy.rs
new file mode 100644
index 00000000..b6739de1
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/cell_occupancy.rs
@@ -0,0 +1,608 @@
+//! Contains CellOccupancyMatrix used to track occupied cells during grid placement
+use super::TrackCounts;
+use crate::compute::grid::OriginZeroLine;
+use crate::geometry::AbsoluteAxis;
+use crate::geometry::Line;
+use crate::util::sys::{new_vec_with_capacity, Vec};
+use core::cmp::{max, min};
+use core::fmt::Debug;
+use core::ops::Range;
+use smallvec::SmallVec;
+
+/// The occupancy state of a single grid cell
+#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
+pub(crate) enum CellOccupancyState {
+ #[default]
+ /// Indicates that a grid cell is unoccupied
+ Unoccupied,
+ /// Indicates that a grid cell is occupied by a definitely placed item
+ DefinitelyPlaced,
+ /// Indicates that a grid cell is occupied by an item that was placed by the auto placement algorithm
+ AutoPlaced,
+}
+
+/// A run of occupied cells within a single track. The range is in OriginZero line coordinates
+/// along the track (so for a row track, the range spans column lines and vice versa).
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct OccupiedInterval {
+ /// The range of cells covered by this interval (start line..end line in OriginZero coordinates)
+ range: Range<i16>,
+ /// The occupancy state of every cell within this interval
+ state: CellOccupancyState,
+}
+
+impl OccupiedInterval {
+ /// Whether this interval overlaps the given range
+ fn overlaps(&self, range: &Range<i16>) -> bool {
+ self.range.start < range.end && self.range.end > range.start
+ }
+}
+
+/// The occupied cells of a single track, stored as a sorted list of disjoint intervals in
+/// OriginZero line coordinates. Gaps between intervals are unoccupied. Touching intervals
+/// with the same state are merged.
+#[derive(Debug, Clone, Default)]
+struct TrackIntervals {
+ /// The sorted, disjoint list of occupied intervals within the track
+ intervals: SmallVec<[OccupiedInterval; 2]>,
+ /// The furthest end line of an auto-placed item starting in this secondary-axis track
+ auto_placement_cursor: Option<OriginZeroLine>,
+}
+
+impl TrackIntervals {
+ /// Whether the track contains any occupied cells
+ fn is_empty(&self) -> bool {
+ self.intervals.is_empty()
+ }
+
+ /// The occupancy state of the cell whose start line is at `coordinate`
+ fn state_at(&self, coordinate: i16) -> CellOccupancyState {
+ self.intervals
+ .iter()
+ .find(|interval| interval.range.start <= coordinate && coordinate < interval.range.end)
+ .map(|interval| interval.state)
+ .unwrap_or(CellOccupancyState::Unoccupied)
+ }
+
+ /// Set the cells covered by `range` to `state`, overwriting the state of any already-occupied
+ /// cells within the range (matching the overwrite semantics of a dense matrix of cells)
+ fn paint(&mut self, range: Range<i16>, state: CellOccupancyState) {
+ if range.start >= range.end {
+ return;
+ }
+
+ // Fast path: the painted range lies entirely after all existing intervals
+ // (the common case, as placement queries and inserts mostly advance forwards)
+ match self.intervals.last_mut() {
+ None => {
+ self.intervals.push(OccupiedInterval { range, state });
+ return;
+ }
+ Some(last) if last.range.end <= range.start => {
+ if last.state == state && last.range.end == range.start {
+ last.range.end = range.end;
+ } else {
+ self.intervals.push(OccupiedInterval { range, state });
+ }
+ return;
+ }
+ _ => {}
+ }
+
+ let mut result: SmallVec<[OccupiedInterval; 2]> = SmallVec::new();
+
+ // Intervals (or partial intervals) entirely before the painted range
+ for interval in &self.intervals {
+ if interval.range.end <= range.start {
+ result.push(interval.clone());
+ } else if interval.range.start < range.start {
+ result.push(OccupiedInterval { range: interval.range.start..range.start, state: interval.state });
+ }
+ }
+
+ // The painted range, merged with the preceding interval if it touches and has the same state
+ match result.last_mut() {
+ Some(last) if last.state == state && last.range.end == range.start => last.range.end = range.end,
+ _ => result.push(OccupiedInterval { range: range.clone(), state }),
+ }
+
+ // Intervals (or partial intervals) entirely after the painted range
+ for interval in &self.intervals {
+ let trimmed = if interval.range.start >= range.end {
+ interval.clone()
+ } else if interval.range.end > range.end {
+ OccupiedInterval { range: range.end..interval.range.end, state: interval.state }
+ } else {
+ continue;
+ };
+ match result.last_mut() {
+ Some(last) if last.state == trimmed.state && last.range.end == trimmed.range.start => {
+ last.range.end = trimmed.range.end
+ }
+ _ => result.push(trimmed),
+ }
+ }
+
+ self.intervals = result;
+ }
+
+ /// Find the extent of the occupied interval which an auto-placement search along the track
+ /// would collide with last: the end of the last overlapping interval. Returns the extremal
+ /// occupied cell of that interval (which may lie outside `range`: every search position
+ /// before the returned extent also collides with the interval), or `None` if the range is
+ /// entirely unoccupied.
+ fn collision_extent(&self, range: &Range<i16>) -> Option<i16> {
+ let interval = self
+ .intervals
+ .iter()
+ .rev()
+ .take_while(|interval| interval.range.end > range.start)
+ .find(|interval| interval.overlaps(range))?;
+ Some(interval.range.end - 1)
+ }
+}
+
+/// A dynamically sized matrix (2d grid) which tracks the occupancy of each grid cell during auto-placement.
+/// It also keeps tabs on how many tracks there are and which tracks are implicit and which are explicit.
+///
+/// Occupancy is stored sparsely as per-track interval lists (in both orientations), so memory usage
+/// is proportional to the number of placed items rather than the total number of grid cells.
+pub(crate) struct CellOccupancyMatrix {
+ /// The counts of implicit and explicit columns
+ columns: TrackCounts,
+ /// The counts of implicit and explicit rows
+ rows: TrackCounts,
+ /// For each row track: the occupied intervals within that row (in column coordinates)
+ row_intervals: Vec<TrackIntervals>,
+ /// For each column track: the occupied intervals within that column (in row coordinates)
+ column_intervals: Vec<TrackIntervals>,
+}
+
+/// Debug impl that represents the matrix in a compact 2d text format
+impl Debug for CellOccupancyMatrix {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ writeln!(
+ f,
+ "Rows: neg_implicit={} explicit={} pos_implicit={}",
+ self.rows.negative_implicit, self.rows.explicit, self.rows.positive_implicit
+ )?;
+ writeln!(
+ f,
+ "Cols: neg_implicit={} explicit={} pos_implicit={}",
+ self.columns.negative_implicit, self.columns.explicit, self.columns.positive_implicit
+ )?;
+ if self.rows.len() > 100 || self.columns.len() > 100 {
+ writeln!(f, "State: (not printed: more than 100 tracks)")?;
+ return Ok(());
+ }
+ writeln!(f, "State:")?;
+
+ for row in &self.row_intervals {
+ for column_index in 0..self.columns.len() {
+ let coordinate = self.columns.track_to_prev_oz_line(column_index as u16);
+ let letter = match row.state_at(coordinate.0) {
+ CellOccupancyState::Unoccupied => '_',
+ CellOccupancyState::DefinitelyPlaced => 'D',
+ CellOccupancyState::AutoPlaced => 'A',
+ };
+ write!(f, "{letter}")?;
+ }
+ writeln!(f)?;
+ }
+
+ Ok(())
+ }
+}
+
+impl CellOccupancyMatrix {
+ /// Create a CellOccupancyMatrix given a set of provisional track counts. The grid can expand as needed to fit more tracks,
+ /// the provisional track counts represent a best effort attempt to avoid the extra allocations this requires.
+ pub fn with_track_counts(columns: TrackCounts, rows: TrackCounts) -> Self {
+ let mut row_intervals = new_vec_with_capacity(rows.len());
+ row_intervals.resize(rows.len(), TrackIntervals::default());
+ let mut column_intervals = new_vec_with_capacity(columns.len());
+ column_intervals.resize(columns.len(), TrackIntervals::default());
+ Self { rows, columns, row_intervals, column_intervals }
+ }
+
+ /// The per-track interval lists for tracks in the specified axis. Each row track's intervals
+ /// are in column coordinates and vice versa.
+ fn track_lists(&self, track_axis: AbsoluteAxis) -> &[TrackIntervals] {
+ match track_axis {
+ AbsoluteAxis::Horizontal => &self.column_intervals,
+ AbsoluteAxis::Vertical => &self.row_intervals,
+ }
+ }
+
+ /// Expands the grid (potentially in all 4 directions) in order to ensure that the specified
+ /// spans (in OriginZero coordinates) fit within the tracked tracks
+ fn expand_to_fit_range(&mut self, row_span: Line<OriginZeroLine>, col_span: Line<OriginZeroLine>) {
+ // Calculate number of rows and columns missing to accommodate ranges (if any)
+ let req_negative_rows = max(-(self.rows.negative_implicit as i16) - row_span.start.0, 0);
+ let req_positive_rows = max(row_span.end.0 - self.rows.implicit_end_line().0, 0);
+ let req_negative_cols = max(-(self.columns.negative_implicit as i16) - col_span.start.0, 0);
+ let req_positive_cols = max(col_span.end.0 - self.columns.implicit_end_line().0, 0);
+
+ // Add empty tracks to the front and/or back of the per-track interval lists.
+ // Interval contents are stored in OriginZero coordinates, so they do not need to shift.
+ if req_negative_rows > 0 {
+ self.row_intervals
+ .splice(0..0, core::iter::repeat_with(TrackIntervals::default).take(req_negative_rows as usize));
+ }
+ if req_positive_rows > 0 {
+ let new_len = self.row_intervals.len() + req_positive_rows as usize;
+ self.row_intervals.resize(new_len, TrackIntervals::default());
+ }
+ if req_negative_cols > 0 {
+ self.column_intervals
+ .splice(0..0, core::iter::repeat_with(TrackIntervals::default).take(req_negative_cols as usize));
+ }
+ if req_positive_cols > 0 {
+ let new_len = self.column_intervals.len() + req_positive_cols as usize;
+ self.column_intervals.resize(new_len, TrackIntervals::default());
+ }
+
+ self.rows.negative_implicit += req_negative_rows as u16;
+ self.rows.positive_implicit += req_positive_rows as u16;
+ self.columns.negative_implicit += req_negative_cols as u16;
+ self.columns.positive_implicit += req_positive_cols as u16;
+ }
+
+ /// Mark an area of the matrix as occupied, expanding the allocated space as necessary to accommodate the passed area.
+ pub fn mark_area_as(
+ &mut self,
+ primary_axis: AbsoluteAxis,
+ primary_span: Line<OriginZeroLine>,
+ secondary_span: Line<OriginZeroLine>,
+ value: CellOccupancyState,
+ ) {
+ let (row_span, column_span) = match primary_axis {
+ AbsoluteAxis::Horizontal => (secondary_span, primary_span),
+ AbsoluteAxis::Vertical => (primary_span, secondary_span),
+ };
+
+ self.expand_to_fit_range(row_span, column_span);
+
+ if value == CellOccupancyState::AutoPlaced
+ && primary_span.start < primary_span.end
+ && secondary_span.start < secondary_span.end
+ {
+ self.advance_auto_placement_cursor(primary_axis, secondary_span.start, primary_span.end);
+ }
+
+ let row_range = self.rows.oz_line_range_to_track_range(row_span);
+ let col_range = self.columns.oz_line_range_to_track_range(column_span);
+ for row_index in row_range {
+ self.row_intervals[row_index as usize].paint(column_span.start.0..column_span.end.0, value);
+ }
+ for column_index in col_range {
+ self.column_intervals[column_index as usize].paint(row_span.start.0..row_span.end.0, value);
+ }
+ }
+
+ /// Determines whether a grid area specified by the bounding grid lines in OriginZero coordinates
+ /// is entirely unnocupied. Returns true if all grid cells within the grid area are unnocupied, else false.
+ #[cfg(test)]
+ pub fn line_area_is_unoccupied(
+ &self,
+ primary_axis: AbsoluteAxis,
+ primary_span: Line<OriginZeroLine>,
+ secondary_span: Line<OriginZeroLine>,
+ ) -> bool {
+ self.line_area_collision_jump(primary_axis, primary_span, secondary_span).is_none()
+ }
+
+ /// Checks the specified area for occupied cells (`primary_span` and `secondary_span` are
+ /// bounding grid lines in OriginZero coordinates). Returns `None` if the area is entirely
+ /// unoccupied. Otherwise returns the next search position (in OriginZero coordinates, along
+ /// `primary_axis`) that is not guaranteed to collide with the occupied cells found in the
+ /// area. This allows the auto-placement search cursor to jump past collisions rather than
+ /// advancing one track at a time.
+ pub fn line_area_collision_jump(
+ &self,
+ primary_axis: AbsoluteAxis,
+ primary_span: Line<OriginZeroLine>,
+ secondary_span: Line<OriginZeroLine>,
+ ) -> Option<OriginZeroLine> {
+ let track_lists = self.track_lists(primary_axis.other_axis());
+ let secondary_counts = self.track_counts(primary_axis.other_axis());
+ let secondary_range = secondary_counts.oz_line_range_to_track_range(secondary_span);
+
+ // Out of bounds cells are considered unoccupied, so clamp the secondary range to the
+ // tracks which actually exist
+ let secondary_start = max(secondary_range.start, 0);
+ let secondary_end = min(secondary_range.end, track_lists.len() as i16);
+
+ let primary_range = primary_span.start.0..primary_span.end.0;
+
+ let mut extent: Option<i16> = None;
+ for secondary_index in secondary_start..secondary_end {
+ let Some(cell) = track_lists[secondary_index as usize].collision_extent(&primary_range) else {
+ continue;
+ };
+ extent = Some(match extent {
+ None => cell,
+ Some(best) => max(best, cell),
+ });
+ }
+
+ extent.map(|cell| OriginZeroLine(cell + 1))
+ }
+
+ /// Given a span of tracks in `axis` (in OriginZero coordinates), returns the next search
+ /// position past all non-empty tracks within the span, or `None` if all tracks within the
+ /// span are entirely unoccupied. Used to place items which span every track in the other
+ /// axis (such items can only fit in a stripe of entirely unoccupied tracks).
+ pub fn occupied_track_jump(&self, axis: AbsoluteAxis, span: Line<OriginZeroLine>) -> Option<OriginZeroLine> {
+ let counts = self.track_counts(axis);
+ let track_lists = self.track_lists(axis);
+ let range = counts.oz_line_range_to_track_range(span);
+ let start = max(range.start, 0);
+ let end = min(range.end, track_lists.len() as i16);
+ let found = (start..end).rev().find(|&index| !track_lists[index as usize].is_empty());
+ found.map(|track_index| {
+ let line = counts.track_to_prev_oz_line(track_index as u16);
+ line + 1
+ })
+ }
+
+ /// Determines whether the specified row contains any items
+ pub fn row_is_occupied(&self, row_index: usize) -> bool {
+ self.track_lists(AbsoluteAxis::Vertical).get(row_index).is_some_and(|track| !track.is_empty())
+ }
+
+ /// Determines whether the specified column contains any items
+ pub fn column_is_occupied(&self, column_index: usize) -> bool {
+ self.track_lists(AbsoluteAxis::Horizontal).get(column_index).is_some_and(|track| !track.is_empty())
+ }
+
+ /// Returns the track counts of this CellOccunpancyMatrix in the relevant axis
+ pub fn track_counts(&self, track_type: AbsoluteAxis) -> &TrackCounts {
+ match track_type {
+ AbsoluteAxis::Horizontal => &self.columns,
+ AbsoluteAxis::Vertical => &self.rows,
+ }
+ }
+
+ /// The sparse placement cursor for items starting in the given secondary-axis track.
+ pub fn auto_placement_cursor(&self, track_type: AbsoluteAxis, start_at: OriginZeroLine) -> Option<OriginZeroLine> {
+ let track_counts = self.track_counts(track_type.other_axis());
+ let track_computed_index = track_counts.oz_line_to_next_track(start_at);
+ let track_lists = self.track_lists(track_type.other_axis());
+ if track_computed_index < 0 || track_computed_index >= track_lists.len() as i16 {
+ // Index out of bounds: no tracks to search
+ return None;
+ }
+ track_lists[track_computed_index as usize].auto_placement_cursor
+ }
+
+ /// Advances the sparse placement cursor to at least `primary_end`.
+ /// The secondary-axis track must already exist in the matrix.
+ fn advance_auto_placement_cursor(
+ &mut self,
+ primary_axis: AbsoluteAxis,
+ secondary_start: OriginZeroLine,
+ primary_end: OriginZeroLine,
+ ) {
+ let track_index = self.track_counts(primary_axis.other_axis()).oz_line_to_next_track(secondary_start) as usize;
+ let tracks = match primary_axis {
+ AbsoluteAxis::Horizontal => &mut self.row_intervals,
+ AbsoluteAxis::Vertical => &mut self.column_intervals,
+ };
+ let cursor = &mut tracks[track_index].auto_placement_cursor;
+ *cursor = max(*cursor, Some(primary_end));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn interval(range: Range<i16>, state: CellOccupancyState) -> OccupiedInterval {
+ OccupiedInterval { range, state }
+ }
+
+ mod track_intervals {
+ use super::*;
+ use CellOccupancyState::{AutoPlaced, DefinitelyPlaced};
+
+ #[test]
+ fn paint_merges_touching_same_state_intervals() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..2, AutoPlaced);
+ track.paint(4..6, AutoPlaced);
+ track.paint(2..4, AutoPlaced);
+ assert_eq!(track.intervals.as_slice(), &[interval(0..6, AutoPlaced)]);
+ }
+
+ #[test]
+ fn paint_does_not_merge_different_states() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..2, AutoPlaced);
+ track.paint(2..4, DefinitelyPlaced);
+ assert_eq!(track.intervals.as_slice(), &[interval(0..2, AutoPlaced), interval(2..4, DefinitelyPlaced)]);
+ }
+
+ #[test]
+ fn paint_overwrites_overlapped_cells() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..6, AutoPlaced);
+ track.paint(2..4, DefinitelyPlaced);
+ assert_eq!(
+ track.intervals.as_slice(),
+ &[interval(0..2, AutoPlaced), interval(2..4, DefinitelyPlaced), interval(4..6, AutoPlaced)]
+ );
+
+ // Painting over everything replaces all intervals
+ track.paint(-1..7, AutoPlaced);
+ assert_eq!(track.intervals.as_slice(), &[interval(-1..7, AutoPlaced)]);
+ }
+
+ #[test]
+ fn paint_overwrites_multiple_intervals() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..2, AutoPlaced);
+ track.paint(3..5, DefinitelyPlaced);
+ track.paint(6..8, AutoPlaced);
+ track.paint(1..7, DefinitelyPlaced);
+ assert_eq!(
+ track.intervals.as_slice(),
+ &[interval(0..1, AutoPlaced), interval(1..7, DefinitelyPlaced), interval(7..8, AutoPlaced)]
+ );
+ }
+
+ #[test]
+ fn collision_extent_finds_extremal_occupied_cell() {
+ let mut track = TrackIntervals::default();
+ track.paint(2..4, AutoPlaced);
+ track.paint(6..8, DefinitelyPlaced);
+ // The last cell of the last overlapping interval
+ assert_eq!(track.collision_extent(&(0..10)), Some(7));
+ assert_eq!(track.collision_extent(&(0..7)), Some(7));
+ assert_eq!(track.collision_extent(&(0..6)), Some(3));
+ assert_eq!(track.collision_extent(&(4..6)), None);
+ }
+
+ #[test]
+ fn state_at_distinguishes_occupied_intervals_and_gaps() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..2, DefinitelyPlaced);
+ track.paint(2..4, AutoPlaced);
+ track.paint(6..8, AutoPlaced);
+ track.paint(8..9, DefinitelyPlaced);
+ assert_eq!(track.state_at(0), DefinitelyPlaced);
+ assert_eq!(track.state_at(3), AutoPlaced);
+ assert_eq!(track.state_at(5), CellOccupancyState::Unoccupied);
+ assert_eq!(track.state_at(7), AutoPlaced);
+ assert_eq!(track.state_at(8), DefinitelyPlaced);
+ }
+
+ #[test]
+ fn definitely_placed_overwrite_hides_auto_placed_cells() {
+ let mut track = TrackIntervals::default();
+ track.paint(0..4, CellOccupancyState::AutoPlaced);
+ track.paint(2..4, CellOccupancyState::DefinitelyPlaced);
+ assert_eq!(track.state_at(1), CellOccupancyState::AutoPlaced);
+ assert_eq!(track.state_at(2), CellOccupancyState::DefinitelyPlaced);
+ assert_eq!(track.state_at(3), CellOccupancyState::DefinitelyPlaced);
+ }
+ }
+
+ mod cell_occupancy_matrix {
+ use super::*;
+ use crate::geometry::AbsoluteAxis::{Horizontal, Vertical};
+ use CellOccupancyState::AutoPlaced;
+
+ fn line(start: i16, end: i16) -> Line<OriginZeroLine> {
+ Line { start: OriginZeroLine(start), end: OriginZeroLine(end) }
+ }
+
+ #[test]
+ fn negative_expansion_preserves_occupancy() {
+ let mut matrix =
+ CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 2, 0), TrackCounts::from_raw(0, 2, 0));
+ matrix.mark_area_as(Horizontal, line(0, 1), line(0, 1), AutoPlaced);
+ // Expand by marking an area in negative tracks
+ matrix.mark_area_as(Horizontal, line(-2, -1), line(-1, 0), AutoPlaced);
+
+ assert_eq!(*matrix.track_counts(Horizontal), TrackCounts::from_raw(2, 2, 0));
+ assert_eq!(*matrix.track_counts(Vertical), TrackCounts::from_raw(1, 2, 0));
+
+ // Original cell still occupied at the same OriginZero coordinates
+ assert!(!matrix.line_area_is_unoccupied(Horizontal, line(0, 1), line(0, 1)));
+ assert!(!matrix.line_area_is_unoccupied(Horizontal, line(-2, -1), line(-1, 0)));
+ assert!(matrix.line_area_is_unoccupied(Horizontal, line(-1, 0), line(0, 1)));
+
+ // Matrix-index based queries account for the shifted origin
+ assert!(matrix.column_is_occupied(0)); // OriginZero column -2
+ assert!(!matrix.column_is_occupied(1)); // OriginZero column -1
+ assert!(matrix.column_is_occupied(2)); // OriginZero column 0
+ assert!(matrix.row_is_occupied(0)); // OriginZero row -1
+ assert!(matrix.row_is_occupied(1)); // OriginZero row 0
+ assert!(!matrix.row_is_occupied(2)); // OriginZero row 1
+ }
+
+ #[test]
+ fn auto_placed_item_only_advances_cursor_in_first_secondary_track() {
+ for axis in [Horizontal, Vertical] {
+ let mut matrix = CellOccupancyMatrix::with_track_counts(
+ TrackCounts::from_raw(0, 4, 0),
+ TrackCounts::from_raw(0, 4, 0),
+ );
+ matrix.mark_area_as(axis, line(1, 3), line(1, 4), AutoPlaced);
+
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(1)), Some(OriginZeroLine(3)));
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(2)), None);
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(3)), None);
+
+ assert!(!matrix.line_area_is_unoccupied(axis, line(1, 3), line(2, 4)));
+ }
+ }
+
+ #[test]
+ fn cursors_survive_interval_merging_and_grid_expansion() {
+ for axis in [Horizontal, Vertical] {
+ let mut matrix = CellOccupancyMatrix::with_track_counts(
+ TrackCounts::from_raw(0, 4, 0),
+ TrackCounts::from_raw(0, 4, 0),
+ );
+ matrix.mark_area_as(axis, line(2, 4), line(1, 2), AutoPlaced);
+ matrix.mark_area_as(axis, line(4, 8), line(0, 2), AutoPlaced);
+ matrix.mark_area_as(axis, line(8, 10), line(1, 2), CellOccupancyState::DefinitelyPlaced);
+ matrix.mark_area_as(axis, line(-3, -1), line(-2, -1), AutoPlaced);
+ matrix.mark_area_as(axis, line(12, 14), line(7, 8), AutoPlaced);
+ matrix.mark_area_as(axis, line(0, 1), line(1, 2), AutoPlaced);
+
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(1)), Some(OriginZeroLine(4)));
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(0)), Some(OriginZeroLine(8)));
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(-2)), Some(OriginZeroLine(-1)));
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(7)), Some(OriginZeroLine(14)));
+ for track in [-3, -1, 2, 8] {
+ assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(track)), None);
+ }
+ }
+ }
+
+ #[test]
+ fn alternating_spans_merge_occupancy_and_skip_the_occupied_prefix() {
+ for axis in [Horizontal, Vertical] {
+ let mut matrix = CellOccupancyMatrix::with_track_counts(
+ TrackCounts::from_raw(0, 0, 0),
+ TrackCounts::from_raw(0, 0, 0),
+ );
+ for i in 0..128 {
+ matrix.mark_area_as(axis, line(i, i + 1), line(i % 2, 2), AutoPlaced);
+ }
+
+ let track = &matrix.track_lists(axis.other_axis())[1];
+ assert_eq!(track.intervals.as_slice(), &[interval(0..128, AutoPlaced)]);
+ assert!(!track.intervals.spilled());
+ assert_eq!(matrix.line_area_collision_jump(axis, line(0, 1), line(1, 2)), Some(OriginZeroLine(128)));
+ }
+ }
+
+ #[test]
+ fn collision_jump_returns_next_search_position() {
+ let mut matrix =
+ CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 4, 0), TrackCounts::from_raw(0, 4, 0));
+ matrix.mark_area_as(Horizontal, line(1, 3), line(0, 1), AutoPlaced);
+
+ // Jump past the end of the last colliding interval
+ assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 2), line(0, 1)), Some(OriginZeroLine(3)));
+ assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 4), line(0, 1)), Some(OriginZeroLine(3)));
+ // No collision in a different row
+ assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 4), line(1, 2)), None);
+ }
+
+ #[test]
+ fn occupied_track_jump_skips_non_empty_tracks() {
+ let mut matrix =
+ CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 4, 0), TrackCounts::from_raw(0, 4, 0));
+ matrix.mark_area_as(Horizontal, line(0, 1), line(1, 2), AutoPlaced);
+
+ // Vertical (row) tracks: row 1 is occupied
+ assert_eq!(matrix.occupied_track_jump(Vertical, line(0, 4)), Some(OriginZeroLine(2)));
+ assert_eq!(matrix.occupied_track_jump(Vertical, line(2, 4)), None);
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/types/coordinates.rs b/vendor/taffy/src/compute/grid/types/coordinates.rs
new file mode 100644
index 00000000..c252892a
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/coordinates.rs
@@ -0,0 +1,184 @@
+//! Taffy uses two coordinate systems to refer to grid lines (the gaps/gutters between rows/columns):
+use super::super::types::TrackCounts;
+use crate::geometry::Line;
+use core::cmp::{max, Ordering};
+use core::ops::{Add, AddAssign, Sub};
+
+/// The maximum number of tracks in each direction from the start of the explicit grid (line 0 in
+/// OriginZero coordinates), and the maximum span of a single grid item. This limits the grid to
+/// `2 * MAX_GRID_TRACKS` total tracks in each axis (including explicit tracks, which count against
+/// the positive limit). Grids larger than this limit are clamped.
+///
+/// See: <https://www.w3.org/TR/css-grid-1/#overlarge-grids>
+pub(crate) const MAX_GRID_TRACKS: u16 = 10_000;
+
+/// The lowest valid grid line in OriginZero coordinates
+pub(crate) const MIN_OZ_LINE: i16 = -(MAX_GRID_TRACKS as i16);
+
+/// The highest valid grid line in OriginZero coordinates
+pub(crate) const MAX_OZ_LINE: i16 = MAX_GRID_TRACKS as i16;
+
+/// Represents a grid line position in "CSS Grid Line" coordinates
+///
+/// "CSS Grid Line" coordinates are those used in grid-row/grid-column in the CSS grid spec:
+/// - The line at left hand (or top) edge of the explicit grid is line 1
+/// (and counts up from there)
+/// - The line at the right hand (or bottom) edge of the explicit grid is -1
+/// (and counts down from there)
+/// - 0 is not a valid index
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[repr(transparent)]
+pub struct GridLine(i16);
+
+impl From<i16> for GridLine {
+ fn from(value: i16) -> Self {
+ Self(value)
+ }
+}
+
+impl GridLine {
+ /// Returns the underlying i16
+ pub fn as_i16(self) -> i16 {
+ self.0
+ }
+
+ /// Convert into OriginZero coordinates using the specified explicit track count.
+ ///
+ /// The result is clamped into the limited grid `[-MAX_GRID_TRACKS, MAX_GRID_TRACKS]`
+ pub(crate) fn into_origin_zero_line(self, explicit_track_count: u16) -> OriginZeroLine {
+ let explicit_line_count = explicit_track_count as i32 + 1;
+ let oz_line = match self.0.cmp(&0) {
+ Ordering::Greater => self.0 as i32 - 1,
+ Ordering::Less => self.0 as i32 + explicit_line_count,
+ Ordering::Equal => panic!("Grid line of zero is invalid"),
+ };
+ OriginZeroLine::clamped(oz_line)
+ }
+}
+
+/// Represents a grid line position in "OriginZero" coordinates
+///
+/// "OriginZero" coordinates are a normalized form:
+/// - The line at left hand (or top) edge of the explicit grid is line 0
+/// - The next line to the right (or down) is 1, and so on
+/// - The next line to the left (or up) is -1, and so on
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+#[repr(transparent)]
+pub struct OriginZeroLine(pub i16);
+
+// Add and Sub with Self
+impl Add<OriginZeroLine> for OriginZeroLine {
+ type Output = Self;
+ fn add(self, rhs: OriginZeroLine) -> Self::Output {
+ OriginZeroLine(self.0 + rhs.0)
+ }
+}
+impl Sub<OriginZeroLine> for OriginZeroLine {
+ type Output = Self;
+ fn sub(self, rhs: OriginZeroLine) -> Self::Output {
+ OriginZeroLine(self.0 - rhs.0)
+ }
+}
+
+// Add and Sub with u16
+impl Add<u16> for OriginZeroLine {
+ type Output = Self;
+ fn add(self, rhs: u16) -> Self::Output {
+ OriginZeroLine(self.0 + rhs as i16)
+ }
+}
+impl AddAssign<u16> for OriginZeroLine {
+ fn add_assign(&mut self, rhs: u16) {
+ self.0 += rhs as i16;
+ }
+}
+impl Sub<u16> for OriginZeroLine {
+ type Output = Self;
+ fn sub(self, rhs: u16) -> Self::Output {
+ OriginZeroLine(self.0 - rhs as i16)
+ }
+}
+
+impl OriginZeroLine {
+ /// Create an `OriginZeroLine`, clamping the line into the limited grid `[-MAX_GRID_TRACKS, MAX_GRID_TRACKS]`
+ pub(crate) fn clamped(line: i32) -> Self {
+ OriginZeroLine(line.clamp(MIN_OZ_LINE as i32, MAX_OZ_LINE as i32) as i16)
+ }
+
+ /// Convert into "CSS Grid Line" coordinates using the specified explicit track count.
+ ///
+ /// The inverse of [`GridLine::into_origin_zero_line`]
+ pub(crate) fn into_grid_line(self, explicit_track_count: u16) -> GridLine {
+ let explicit_line_count = explicit_track_count + 1;
+ if self.0 >= 0 {
+ GridLine(self.0 + 1)
+ } else {
+ GridLine(self.0 - explicit_line_count as i16)
+ }
+ }
+
+ /// Converts a grid line in OriginZero coordinates into the index of that same grid line in the GridTrackVec.
+ pub(crate) fn into_track_vec_index(self, track_counts: TrackCounts) -> usize {
+ self.try_into_track_vec_index(track_counts).unwrap_or_else(|| {
+ if self.0 > 0 {
+ panic!("OriginZero grid line cannot be more than the number of positive grid lines");
+ } else {
+ panic!("OriginZero grid line cannot be less than the number of negative grid lines");
+ }
+ })
+ }
+
+ /// Converts a grid line in OriginZero coordinates into the index of that same grid line in the GridTrackVec.
+ ///
+ /// This fallible version is used for the placement of absolutely positioned grid items:
+ ///
+ /// If a grid-placement property refers to a non-existent line either by explicitly specifying such a line or by
+ /// spanning outside of the existing implicit grid, it is instead treated as specifying auto (instead of creating
+ /// new implicit grid lines).
+ ///
+ /// The infallible version above if used when placing regular in-flow grid items.
+ pub(crate) fn try_into_track_vec_index(self, track_counts: TrackCounts) -> Option<usize> {
+ // OriginZero grid line cannot be less than the number of negative grid lines
+ if self.0 < -(track_counts.negative_implicit as i16) {
+ return None;
+ };
+ // OriginZero grid line cannot be more than the number of positive grid lines
+ if self.0 > (track_counts.explicit + track_counts.positive_implicit) as i16 {
+ return None;
+ };
+
+ Some(2 * ((self.0 + track_counts.negative_implicit as i16) as usize))
+ }
+
+ /// The minimum number of negative implicit track there must be if a grid item starts at this line.
+ pub(crate) fn implied_negative_implicit_tracks(self) -> u16 {
+ if self.0 < 0 {
+ self.0.unsigned_abs()
+ } else {
+ 0
+ }
+ }
+
+ /// The minimum number of positive implicit track there must be if a grid item end at this line.
+ pub(crate) fn implied_positive_implicit_tracks(self, explicit_track_count: u16) -> u16 {
+ if self.0 > explicit_track_count as i16 {
+ self.0 as u16 - explicit_track_count
+ } else {
+ 0
+ }
+ }
+}
+
+impl Line<OriginZeroLine> {
+ /// The number of tracks between the start and end lines
+ #[inline(always)]
+ pub(crate) fn span(self) -> u16 {
+ max(self.end.0 - self.start.0, 0) as u16
+ }
+}
+
+/// A trait for the different coordinates used to define grid lines.
+pub trait GridCoordinate: Copy {}
+impl GridCoordinate for GridLine {}
+impl GridCoordinate for OriginZeroLine {}
diff --git a/vendor/taffy/src/compute/grid/types/grid_item.rs b/vendor/taffy/src/compute/grid/types/grid_item.rs
new file mode 100644
index 00000000..e72c8873
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/grid_item.rs
@@ -0,0 +1,817 @@
+//! Contains GridItem used to represent a single grid item during layout
+use super::GridTrack;
+use crate::compute::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
+use crate::compute::grid::OriginZeroLine;
+use crate::geometry::AbstractAxis;
+use crate::geometry::{Line, Point, Rect, Size};
+use crate::style::{AlignItems, AlignSelf, AvailableSpace, Dimension, LengthPercentageAuto, Overflow};
+use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId, OofCandidates, SizingMode};
+use crate::util::sys::f32_max;
+use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
+use crate::{AlignItemsKeyword, BoxSizing, GridItemStyle, LengthPercentage};
+use core::ops::Range;
+
+/// The known_dimensions computed for a grid item for a given grid area size
+#[derive(Debug, Clone, Copy)]
+pub(in super::super) struct KnownDimensionsCacheEntry {
+ /// The grid area size that `known_dimensions` was computed for
+ grid_area_size: Size<Option<f32>>,
+ /// The cached known_dimensions
+ known_dimensions: Size<Option<f32>>,
+}
+
+/// Represents a single grid item
+#[derive(Debug)]
+pub(in super::super) struct GridItem {
+ /// The id of the node that this item represents
+ pub node: NodeId,
+
+ /// The index of the item in the children array
+ pub source_order: u16,
+
+ /// The item's definite row-start and row-end, as resolved by the placement algorithm
+ /// (in origin-zero coordinates). Set by the placement algorithm.
+ pub row: Line<OriginZeroLine>,
+ /// The items definite column-start and column-end, as resolved by the placement algorithm
+ /// (in origin-zero coordinates). Set by the placement algorithm.
+ pub column: Line<OriginZeroLine>,
+
+ /// Is it a compressible replaced element?
+ /// https://drafts.csswg.org/css-sizing-3/#min-content-zero
+ pub is_compressible_replaced: bool,
+ /// Whether the item is a replaced element. Such items are not stretched by `normal` alignment.
+ pub is_replaced: bool,
+ /// The item's overflow style
+ pub overflow: Point<Overflow>,
+ /// The item's box_sizing style
+ pub box_sizing: BoxSizing,
+ /// The item's size style
+ pub size: Size<Dimension>,
+ /// The item's min_size style
+ pub min_size: Size<LengthPercentageAuto>,
+ /// The item's max_size style
+ pub max_size: Size<LengthPercentageAuto>,
+ /// The item's aspect_ratio style
+ pub aspect_ratio: Option<f32>,
+ /// The item's padding style
+ pub padding: Rect<LengthPercentage>,
+ /// The item's border style
+ pub border: Rect<LengthPercentage>,
+ /// The item's margin style
+ pub margin: Rect<LengthPercentageAuto>,
+ /// The item's align_self property, or the parent's align_items property if it is `None`
+ pub align_self: AlignSelf,
+ /// The item's justify_self property, or the parent's justify_items property if it is `None`
+ pub justify_self: AlignSelf,
+ /// The items first baseline (horizontal)
+ pub baseline: Option<f32>,
+ /// Shim for baseline alignment that acts like an extra top margin
+ /// TODO: Support last baseline and vertical text baselines
+ pub baseline_shim: f32,
+
+ /// The item's definite row-start and row-end (same as `row` field, except in a different coordinate system)
+ /// (as indexes into the Vec<GridTrack> stored in a grid's AbstractAxisTracks)
+ pub row_indexes: Line<u16>,
+ /// The items definite column-start and column-end (same as `column` field, except in a different coordinate system)
+ /// (as indexes into the Vec<GridTrack> stored in a grid's AbstractAxisTracks)
+ pub column_indexes: Line<u16>,
+
+ /// Whether the item crosses a flexible row
+ pub crosses_flexible_row: bool,
+ /// Whether the item crosses a flexible column
+ pub crosses_flexible_column: bool,
+ /// Whether the item crosses a intrinsic row
+ pub crosses_intrinsic_row: bool,
+ /// Whether the item crosses a intrinsic column
+ pub crosses_intrinsic_column: bool,
+
+ // Caches for intrinsic size computation. These caches are only valid for a single run of the track-sizing algorithm.
+ /// Cache for the known_dimensions input to intrinsic sizing computation
+ pub grid_area_size_cache: Option<Size<Option<f32>>>,
+ /// Cache for the known_dimensions passed to the child when computing its intrinsic contributions, stored along with
+ /// the grid area size it was computed for. Must be cleared whenever `baseline_shim` changes.
+ pub known_dimensions_cache: Option<KnownDimensionsCacheEntry>,
+ /// Cache for the min-content size
+ pub min_content_contribution_cache: Size<Option<f32>>,
+ /// Cache for the minimum contribution
+ pub minimum_contribution_cache: Size<Option<f32>>,
+ /// Cache for the max-content size
+ pub max_content_contribution_cache: Size<Option<f32>>,
+
+ /// Final y position. Used to compute baseline alignment for the container.
+ pub y_position: f32,
+ /// Final height. Used to compute baseline alignment for the container.
+ pub height: f32,
+
+ /// Out-of-flow candidates bubbled out of this item's subtree (anchors relative to the
+ /// container's border box)
+ pub oof_candidates: OofCandidates,
+}
+
+impl GridItem {
+ /// Create a new item from its style. Its placement (`row`/`column`) is filled in by the placement algorithm.
+ pub fn new_with_style_and_order<S: GridItemStyle>(
+ node: NodeId,
+ style: S,
+ parent_align_items: AlignItems,
+ parent_justify_items: AlignItems,
+ source_order: u16,
+ ) -> Self {
+ const UNPLACED: Line<OriginZeroLine> = Line { start: OriginZeroLine(0), end: OriginZeroLine(0) };
+ GridItem {
+ node,
+ source_order,
+ row: UNPLACED,
+ column: UNPLACED,
+ is_compressible_replaced: style.is_compressible_replaced(),
+ is_replaced: style.is_replaced(),
+ overflow: style.overflow(),
+ box_sizing: style.box_sizing(),
+ size: style.size(),
+ min_size: style.min_size(),
+ max_size: style.max_size(),
+ aspect_ratio: style.aspect_ratio(),
+ padding: style.padding(),
+ border: style.border(),
+ margin: style.margin(),
+ align_self: style.align_self().unwrap_or(parent_align_items),
+ justify_self: style.justify_self().unwrap_or(parent_justify_items),
+ baseline: None,
+ baseline_shim: 0.0,
+ row_indexes: Line { start: 0, end: 0 }, // Properly initialised later
+ column_indexes: Line { start: 0, end: 0 }, // Properly initialised later
+ crosses_flexible_row: false, // Properly initialised later
+ crosses_flexible_column: false, // Properly initialised later
+ crosses_intrinsic_row: false, // Properly initialised later
+ crosses_intrinsic_column: false, // Properly initialised later
+ grid_area_size_cache: None,
+ min_content_contribution_cache: Size::NONE,
+ max_content_contribution_cache: Size::NONE,
+ known_dimensions_cache: None,
+ minimum_contribution_cache: Size::NONE,
+ y_position: 0.0,
+ height: 0.0,
+ oof_candidates: OofCandidates::NONE,
+ }
+ }
+
+ /// Whether the item has an auto margin in the block axis
+ #[inline(always)]
+ pub fn has_auto_block_margin(&self) -> bool {
+ self.margin.top.is_auto() || self.margin.bottom.is_auto()
+ }
+
+ /// Whether the item's block size depends on the size of its row(s), creating a cyclic
+ /// dependency with baseline alignment (which affects row sizing). Per
+ /// <https://www.w3.org/TR/css-grid-1/#row-align> such items do not participate in baseline
+ /// alignment and are aligned using their fallback alignment instead.
+ #[inline(always)]
+ pub fn has_cyclic_block_size_dependency(&self) -> bool {
+ self.size.height.0.uses_percentage() && (self.crosses_intrinsic_row || self.crosses_flexible_row)
+ }
+
+ /// Returns true if the item participates in baseline alignment: it has `align-self: baseline`
+ /// and neither of its block-axis margins are `auto`.
+ /// See <https://www.w3.org/TR/css-align-3/#baseline-align-self>
+ #[inline(always)]
+ pub fn participates_in_baseline_alignment(&self) -> bool {
+ self.align_self.keyword == AlignItemsKeyword::Baseline
+ && !self.has_auto_block_margin()
+ && !self.has_cyclic_block_size_dependency()
+ }
+
+ /// This item's placement in the specified axis in OriginZero coordinates
+ pub fn placement(&self, axis: AbstractAxis) -> Line<OriginZeroLine> {
+ match axis {
+ AbstractAxis::Block => self.row,
+ AbstractAxis::Inline => self.column,
+ }
+ }
+
+ /// This item's placement in the specified axis as GridTrackVec indices
+ pub fn placement_indexes(&self, axis: AbstractAxis) -> Line<u16> {
+ match axis {
+ AbstractAxis::Block => self.row_indexes,
+ AbstractAxis::Inline => self.column_indexes,
+ }
+ }
+
+ /// Returns a range which can be used as an index into the GridTrackVec in the specified axis
+ /// which will produce a sub-slice of covering all the tracks and lines that this item spans
+ /// excluding the lines that bound it.
+ pub fn track_range_excluding_lines(&self, axis: AbstractAxis) -> Range<usize> {
+ let indexes = self.placement_indexes(axis);
+ (indexes.start as usize + 1)..(indexes.end as usize)
+ }
+
+ /// Whether any track spanned by this item in the specified axis satisfies `predicate`
+ pub fn spans_track_matching(
+ &self,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ predicate: impl Fn(&GridTrack) -> bool,
+ ) -> bool {
+ axis_tracks[self.track_range_excluding_lines(axis)].iter().any(predicate)
+ }
+
+ /// Returns the number of tracks that this item spans in the specified axis
+ pub fn span(&self, axis: AbstractAxis) -> u16 {
+ match axis {
+ AbstractAxis::Block => self.row.span(),
+ AbstractAxis::Inline => self.column.span(),
+ }
+ }
+
+ /// Returns the pre-computed value indicating whether the grid item crosses a flexible track in
+ /// the specified axis
+ pub fn crosses_flexible_track(&self, axis: AbstractAxis) -> bool {
+ match axis {
+ AbstractAxis::Inline => self.crosses_flexible_column,
+ AbstractAxis::Block => self.crosses_flexible_row,
+ }
+ }
+
+ /// Returns the pre-computed value indicating whether the grid item crosses an intrinsic track in
+ /// the specified axis
+ pub fn crosses_intrinsic_track(&self, axis: AbstractAxis) -> bool {
+ match axis {
+ AbstractAxis::Inline => self.crosses_intrinsic_column,
+ AbstractAxis::Block => self.crosses_intrinsic_row,
+ }
+ }
+
+ /// For an item spanning multiple tracks, the upper limit used to calculate its limited min-/max-content contribution is the
+ /// sum of the fixed max track sizing functions of any tracks it spans, and is applied if it only spans such tracks.
+ pub fn spanned_track_limit(
+ &mut self,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ axis_parent_size: Option<f32>,
+ resolve_calc_value: &dyn Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ let spanned_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
+ let tracks_all_fixed = spanned_tracks.iter().all(|track| {
+ track.max_track_sizing_function.definite_limit(axis_parent_size, resolve_calc_value).is_some()
+ });
+ if tracks_all_fixed {
+ let limit: f32 = spanned_tracks
+ .iter()
+ .map(|track| {
+ track.max_track_sizing_function.definite_limit(axis_parent_size, resolve_calc_value).unwrap()
+ })
+ .sum();
+ Some(limit)
+ } else {
+ None
+ }
+ }
+
+ /// Similar to the spanned_track_limit, but excludes FitContent arguments from the limit.
+ /// Used to clamp the automatic minimum contributions of an item
+ pub fn spanned_fixed_track_limit(
+ &mut self,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ axis_parent_size: Option<f32>,
+ resolve_calc_value: &dyn Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ let spanned_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
+ let tracks_all_fixed = spanned_tracks.iter().all(|track| {
+ track.max_track_sizing_function.definite_value(axis_parent_size, resolve_calc_value).is_some()
+ });
+ if tracks_all_fixed {
+ let limit: f32 = spanned_tracks
+ .iter()
+ .map(|track| {
+ track.max_track_sizing_function.definite_value(axis_parent_size, resolve_calc_value).unwrap()
+ })
+ .sum();
+ Some(limit)
+ } else {
+ None
+ }
+ }
+
+ /// Retrieve the known_dimensions for the given grid area size from the cache or compute them.
+ /// The min-content and max-content contributions of an item are both computed from the same known_dimensions.
+ #[inline(always)]
+ fn known_dimensions_cached(
+ &mut self,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ ) -> Size<Option<f32>> {
+ if let Some(entry) = self.known_dimensions_cache {
+ if entry.grid_area_size == grid_area_size {
+ return entry.known_dimensions;
+ }
+ }
+ let known_dimensions = self.known_dimensions(tree, grid_area_size);
+ self.known_dimensions_cache = Some(KnownDimensionsCacheEntry { grid_area_size, known_dimensions });
+ known_dimensions
+ }
+
+ /// Whether the given self-alignment stretches the item: `stretch`, or `normal` unless the item is replaced
+ #[inline(always)]
+ fn is_stretch_aligned(&self, alignment: AlignSelf) -> bool {
+ match alignment.keyword {
+ AlignItemsKeyword::Stretch => true,
+ AlignItemsKeyword::Normal => !self.is_replaced,
+ _ => false,
+ }
+ }
+
+ /// Compute the known_dimensions to be passed to the child sizing functions
+ /// The key thing that is being done here is applying stretch alignment, which is necessary to
+ /// allow percentage sizes further down the tree to resolve properly in some cases
+ fn known_dimensions(
+ &self,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ ) -> Size<Option<f32>> {
+ let margins = self.margins_axis_sums_with_baseline_shims(grid_area_size.width, tree);
+
+ let aspect_ratio = self.aspect_ratio;
+ // CSS resolves percentage padding and border against the inline size of the containing
+ // block. For a grid item under intrinsic measurement, that inline-size basis is the grid
+ // area's width when it is definite.
+ // Spec:
+ // https://www.w3.org/TR/css-grid-1/#item-margins
+ // https://www.w3.org/TR/CSS22/box.html#padding-properties
+ let padding = self.padding.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
+ let border = self.border.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_size = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if self.box_sizing == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+ let inherent_size = self
+ .size
+ .maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let min_size = self
+ .min_size
+ .maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ // The size of the item is floored by its padding and border
+ .or(padding_border_size.map(Some))
+ .maybe_max(padding_border_size);
+ let max_size = self
+ .max_size
+ .maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+
+ let grid_area_minus_item_margins_size = grid_area_size.maybe_sub(margins).maybe_max(Size::ZERO);
+
+ // If node is absolutely positioned and width is not set explicitly, then deduce it
+ // from left, right and container_content_box if both are set.
+ let width = inherent_size.width.or_else(|| {
+ // A width that is a sizing keyword is not auto, so it does not stretch. The stretch
+ // keyword resolves to an exact width; the others resolve during content measurement.
+ if self.size.width.is_sizing_keyword() {
+ return match resolve_sizing_keyword(
+ self.size.width,
+ grid_area_minus_item_margins_size.width,
+ grid_area_size.width,
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Exact(width)) => Some(width),
+ _ => None,
+ };
+ }
+
+ // Apply width based on stretch alignment if:
+ // - Alignment style is "stretch" or "normal". Note that "normal" is treated as "stretch"
+ // here regardless of whether the item has a preferred size or aspect ratio in this axis,
+ // which differs from the rule used when the item is finally aligned (see `align_and_position_item`).
+ // Replaced elements are not stretched by "normal".
+ // - The node is not absolutely positioned
+ // - The node does not have auto margins in this axis.
+ if !self.margin.left.is_auto() && !self.margin.right.is_auto() && self.is_stretch_aligned(self.justify_self)
+ {
+ return grid_area_minus_item_margins_size.width;
+ }
+
+ None
+ });
+ // Reapply aspect ratio after stretch and absolute position width adjustments
+ let Size { width, height } =
+ Size { width, height: inherent_size.height }.maybe_apply_aspect_ratio(aspect_ratio);
+
+ let height = height.or_else(|| {
+ // A height that is a sizing keyword is not auto, so it does not stretch. The stretch
+ // keyword resolves to an exact height; the others resolve during content measurement.
+ if self.size.height.is_sizing_keyword() {
+ return match resolve_sizing_keyword(
+ self.size.height,
+ grid_area_minus_item_margins_size.height,
+ grid_area_size.height,
+ |val, basis| tree.calc(val, basis),
+ ) {
+ Some(SizingKeywordResolution::Exact(height)) => Some(height),
+ _ => None,
+ };
+ }
+
+ // Apply height based on stretch alignment if:
+ // - Alignment style is "stretch" or "normal" (see the note on width above)
+ // - The node is not absolutely positioned
+ // - The node does not have auto margins in this axis.
+ if !self.margin.top.is_auto() && !self.margin.bottom.is_auto() && self.is_stretch_aligned(self.align_self) {
+ return grid_area_minus_item_margins_size.height;
+ }
+
+ None
+ });
+ // Reapply aspect ratio after stretch and absolute position height adjustments
+ let Size { width, height } = Size { width, height }.maybe_apply_aspect_ratio(aspect_ratio);
+
+ // Clamp size by min and max width/height
+ let Size { width, height } = Size { width, height }.maybe_clamp(min_size, max_size);
+
+ Size { width, height }
+ }
+
+ /// Returns the grid area's size in the specified axis when every spanned track has a definite fixed size.
+ ///
+ /// During intrinsic sizing, percentages on grid items resolve against the size of the grid area,
+ /// not the grid container. If the spanned tracks in an axis are not all definite yet, the grid
+ /// area is still indefinite in that axis and percentage-dependent values must stay unresolved here.
+ ///
+ /// Spec:
+ /// https://www.w3.org/TR/css-grid-1/#grid-item-sizing
+ /// https://www.w3.org/TR/css-grid-1/#algo-overview
+ ///
+ /// Compute the available_space to be passed to the child sizing functions
+ /// These are estimates based on either the max track sizing function or the provisional base size in the opposite
+ /// axis to the one currently being sized.
+ /// https://www.w3.org/TR/css-grid-1/#algo-overview
+ pub fn grid_area_size(
+ &self,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ other_axis_tracks: &[GridTrack],
+ available_space: Size<Option<f32>>,
+ get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
+ resolve_calc_value: &impl Fn(*const (), f32) -> f32,
+ ) -> Size<Option<f32>> {
+ let mut size = Size::NONE;
+ size.set(
+ axis,
+ axis_tracks[self.track_range_excluding_lines(axis)]
+ .iter()
+ .map(|track| {
+ let min_size = track
+ .min_track_sizing_function
+ .definite_value(available_space.get(axis), resolve_calc_value)?;
+ let max_size = track
+ .max_track_sizing_function
+ .definite_value(available_space.get(axis), resolve_calc_value)?;
+
+ if min_size == max_size {
+ Some(track.base_size)
+ } else {
+ None
+ }
+ })
+ .sum::<Option<f32>>(),
+ );
+
+ size.set(
+ axis.other(),
+ other_axis_tracks[self.track_range_excluding_lines(axis.other())]
+ .iter()
+ .map(|track| {
+ get_track_size_estimate(track, available_space.get(axis.other()))
+ .map(|size| size + track.content_alignment_adjustment)
+ })
+ .sum::<Option<f32>>(),
+ );
+
+ size
+ }
+
+ /// Retrieve the available_space from the cache or compute them using the passed parameters
+ pub fn grid_area_size_cached(
+ &mut self,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ other_axis_tracks: &[GridTrack],
+ available_space: Size<Option<f32>>,
+ get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
+ resolve_calc_value: &impl Fn(*const (), f32) -> f32,
+ ) -> Size<Option<f32>> {
+ self.grid_area_size_cache.unwrap_or_else(|| {
+ let grid_area_size = self.grid_area_size(
+ axis,
+ axis_tracks,
+ other_axis_tracks,
+ available_space,
+ get_track_size_estimate,
+ resolve_calc_value,
+ );
+ self.grid_area_size_cache = Some(grid_area_size);
+ grid_area_size
+ })
+ }
+
+ /// Compute the item's resolved margins for size contributions. Horizontal percentage margins always resolve
+ /// to zero if the container size is indefinite as otherwise this would introduce a cyclic dependency.
+ #[inline(always)]
+ pub fn margins_axis_sums_with_baseline_shims(
+ &self,
+ inner_node_width: Option<f32>,
+ tree: &impl LayoutPartialTree,
+ ) -> Size<f32> {
+ Rect {
+ left: self.margin.left.resolve_or_zero(Some(0.0), |val, basis| tree.calc(val, basis)),
+ right: self.margin.right.resolve_or_zero(Some(0.0), |val, basis| tree.calc(val, basis)),
+ top: self.margin.top.resolve_or_zero(inner_node_width, |val, basis| tree.calc(val, basis))
+ + self.baseline_shim,
+ bottom: self.margin.bottom.resolve_or_zero(inner_node_width, |val, basis| tree.calc(val, basis)),
+ }
+ .sum_axes()
+ }
+
+ /// Compute the item's min content contribution from the provided parameters
+ pub fn min_content_contribution(
+ &mut self,
+ axis: AbstractAxis,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<Option<f32>>,
+ ) -> f32 {
+ let known_dimensions = self.known_dimensions_cached(tree, grid_area_size);
+ // If the item's size in the axis being measured is already known then that size is its contribution,
+ // and we can avoid calling into the child entirely.
+ if let Some(size) = known_dimensions.get(axis) {
+ return size;
+ }
+ // The child sees the grid area as its containing block during intrinsic measurement, so
+ // percentage box properties resolve against the grid area when that size is definite.
+ // Spec:
+ // https://www.w3.org/TR/css-grid-1/#grid-item-sizing
+ // https://www.w3.org/TR/css-grid-1/#algo-overview
+ tree.measure_child_size(
+ self.node,
+ known_dimensions,
+ grid_area_size,
+ self.keyword_adjusted_available_space(
+ grid_area_size,
+ self.available_space_minus_margins(grid_area_size, available_space, tree).map(|opt| match opt {
+ Some(size) => AvailableSpace::Definite(size),
+ None => AvailableSpace::MinContent,
+ }),
+ tree,
+ ),
+ SizingMode::InherentSize,
+ axis.as_abs_naive(),
+ Line::FALSE,
+ )
+ }
+
+ /// Retrieve the item's min content contribution from the cache or compute it using the provided parameters
+ #[inline(always)]
+ pub fn min_content_contribution_cached(
+ &mut self,
+ axis: AbstractAxis,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<Option<f32>>,
+ ) -> f32 {
+ self.min_content_contribution_cache.get(axis).unwrap_or_else(|| {
+ let size = self.min_content_contribution(axis, tree, grid_area_size, available_space);
+ self.min_content_contribution_cache.set(axis, Some(size));
+ size
+ })
+ }
+
+ /// Compute the item's max content contribution from the provided parameters
+ pub fn max_content_contribution(
+ &mut self,
+ axis: AbstractAxis,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<Option<f32>>,
+ ) -> f32 {
+ let known_dimensions = self.known_dimensions_cached(tree, grid_area_size);
+ // If the item's size in the axis being measured is already known then that size is its contribution,
+ // and we can avoid calling into the child entirely.
+ if let Some(size) = known_dimensions.get(axis) {
+ return size;
+ }
+ // See the min-content path above. Max-content measurement uses the same containing-block
+ // basis so percentage-dependent item geometry is measured from the grid area rather than
+ // from the container.
+ tree.measure_child_size(
+ self.node,
+ known_dimensions,
+ grid_area_size,
+ self.keyword_adjusted_available_space(
+ grid_area_size,
+ self.available_space_minus_margins(grid_area_size, available_space, tree).map(|opt| match opt {
+ Some(size) => AvailableSpace::Definite(size),
+ None => AvailableSpace::MaxContent,
+ }),
+ tree,
+ ),
+ SizingMode::InherentSize,
+ axis.as_abs_naive(),
+ Line::FALSE,
+ )
+ }
+
+ /// Subtract the item's margins (and baseline shim) from the definite axes of the space available
+ /// to the item's margin box, giving the available space that is passed to the item.
+ /// As when the item is laid out into its final position, margins resolve against the width
+ /// of the grid area and `auto` margins are treated as zero.
+ #[inline(always)]
+ fn available_space_minus_margins(
+ &self,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<Option<f32>>,
+ tree: &impl LayoutPartialTree,
+ ) -> Size<Option<f32>> {
+ if available_space.width.is_none() && available_space.height.is_none() {
+ return available_space;
+ }
+ let margin = self.margin.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
+ Size {
+ width: available_space.width.map(|width| f32_max(width - margin.horizontal_axis_sum(), 0.0)),
+ height: available_space
+ .height
+ .map(|height| f32_max(height - margin.vertical_axis_sum() - self.baseline_shim, 0.0)),
+ }
+ }
+
+ /// Override the available space in each axis whose size style is a sizing keyword that
+ /// measures the item under a specific available space constraint
+ /// (min-content, max-content, fit-content, fit-content(...))
+ fn keyword_adjusted_available_space(
+ &self,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+ tree: &impl LayoutPartialTree,
+ ) -> Size<AvailableSpace> {
+ if !self.size.width.is_sizing_keyword() && !self.size.height.is_sizing_keyword() {
+ return available_space;
+ }
+ let margins = self.margins_axis_sums_with_baseline_shims(grid_area_size.width, tree);
+ let mut adjusted = available_space;
+ for axis in [AbstractAxis::Inline, AbstractAxis::Block] {
+ let size_style = self.size.get(axis);
+ if !size_style.is_sizing_keyword() {
+ continue;
+ }
+ let stretch_size = grid_area_size.get(axis).maybe_sub(margins.get(axis)).maybe_max(0.0);
+ if let Some(SizingKeywordResolution::Measure(available)) =
+ resolve_sizing_keyword(size_style, stretch_size, grid_area_size.get(axis), |val, basis| {
+ tree.calc(val, basis)
+ })
+ {
+ adjusted.set(axis, available);
+ }
+ }
+ adjusted
+ }
+
+ /// Retrieve the item's max content contribution from the cache or compute it using the provided parameters
+ #[inline(always)]
+ pub fn max_content_contribution_cached(
+ &mut self,
+ axis: AbstractAxis,
+ tree: &mut impl LayoutPartialTree,
+ grid_area_size: Size<Option<f32>>,
+ available_space: Size<Option<f32>>,
+ ) -> f32 {
+ self.max_content_contribution_cache.get(axis).unwrap_or_else(|| {
+ let size = self.max_content_contribution(axis, tree, grid_area_size, available_space);
+ self.max_content_contribution_cache.set(axis, Some(size));
+ size
+ })
+ }
+
+ /// The minimum contribution of an item is the smallest outer size it can have.
+ /// Specifically:
+ /// - If the item’s computed preferred size behaves as auto or depends on the size of its containing block in the relevant axis:
+ /// Its minimum contribution is the outer size that would result from assuming the item’s used minimum size as its preferred size;
+ /// - Else the item’s minimum contribution is its min-content contribution.
+ ///
+ /// Because the minimum contribution often depends on the size of the item’s content, it is considered a type of intrinsic size contribution.
+ /// See: https://www.w3.org/TR/css-grid-1/#min-size-auto
+ pub fn minimum_contribution(
+ &mut self,
+ tree: &mut impl LayoutPartialTree,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ grid_area_size: Size<Option<f32>>,
+ inner_node_size: Size<Option<f32>>,
+ ) -> f32 {
+ let padding = self.padding.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
+ let border = self.border.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_size = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if self.box_sizing == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+ self.size
+ .maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(self.aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .get(axis)
+ .map(|size| {
+ // A definite preferred size is clamped by the minimum and maximum sizes. For a compressible replaced
+ // element, an indefinite percentage maximum size is resolved against zero.
+ let min_size = self.min_size.get(axis);
+ let max_size = self.max_size.get(axis);
+ if min_size.is_auto() && max_size.is_auto() {
+ return size;
+ }
+ let basis = grid_area_size.get(axis);
+ let max_size_basis = if self.is_compressible_replaced { basis.or(Some(0.0)) } else { basis };
+ let adjustment = box_sizing_adjustment.get(axis);
+ let min_size = min_size.maybe_resolve(basis, |val, basis| tree.calc(val, basis));
+ let max_size = max_size.maybe_resolve(max_size_basis, |val, basis| tree.calc(val, basis));
+ size.maybe_clamp(min_size.maybe_add(adjustment), max_size.maybe_add(adjustment))
+ })
+ .or_else(|| {
+ // A preferred size that is a sizing keyword other than `stretch` does not behave as auto,
+ // so the minimum contribution is the min-content contribution.
+ let size = self.size.get(axis);
+ (size.is_sizing_keyword() && !size.is_stretch())
+ .then(|| self.min_content_contribution_cached(axis, tree, grid_area_size, grid_area_size))
+ })
+ .or_else(|| {
+ self.min_size
+ .maybe_resolve(grid_area_size.map(|size| size.unwrap_or(0.0)), |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(self.aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .get(axis)
+ })
+ .or_else(|| self.overflow.get(axis).maybe_into_automatic_min_size())
+ .unwrap_or_else(|| {
+ // Automatic minimum size. See https://www.w3.org/TR/css-grid-1/#min-size-auto
+
+ // To provide a more reasonable default minimum size for grid items, the used value of its automatic minimum size
+ // in a given axis is the content-based minimum size if all of the following are true:
+ let item_axis_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
+
+ // it is not a scroll container (handled above)
+
+ // it spans at least one track in that axis whose min track sizing function is auto
+ let spans_auto_min_track = item_axis_tracks
+ .iter()
+ .any(|track| track.min_track_sizing_function.behaves_as_auto(inner_node_size.get(axis)));
+
+ // if it spans more than one track in that axis, none of those tracks are flexible
+ let only_span_one_track = item_axis_tracks.len() == 1;
+ let use_content_based_minimum = spans_auto_min_track
+ && (only_span_one_track
+ || !item_axis_tracks.iter().any(|track| track.max_track_sizing_function.is_fr()));
+
+ // Otherwise, the automatic minimum size is zero, as usual.
+ if use_content_based_minimum {
+ let mut minimum_contribution =
+ self.min_content_contribution_cached(axis, tree, grid_area_size, grid_area_size);
+
+ // If the item is a compressible replaced element, and has a definite preferred size or maximum size in the
+ // relevant axis, the size suggestion is capped by those sizes; for this purpose, any indefinite percentages
+ // in these sizes are resolved against zero (and considered definite).
+ if self.is_compressible_replaced {
+ let size = self.size.get(axis).maybe_resolve(Some(0.0), |val, basis| tree.calc(val, basis));
+ let max_size =
+ self.max_size.get(axis).maybe_resolve(Some(0.0), |val, basis| tree.calc(val, basis));
+ minimum_contribution = minimum_contribution.maybe_min(size).maybe_min(max_size);
+ }
+
+ // The content-based minimum size is additionally clamped by the sum of any fixed max track sizing
+ // functions of the tracks the item spans. Note that this clamp does not apply to explicitly specified
+ // preferred or minimum sizes, and that the argument to fit-content() does not clamp the content-based
+ // minimum size in the same way as a fixed max track sizing function. The clamp is a stretch fit into
+ // the limit, so it does not shrink the item below its padding + border.
+ let limit =
+ self.spanned_fixed_track_limit(axis, axis_tracks, inner_node_size.get(axis), &|val, basis| {
+ tree.resolve_calc_value(val, basis)
+ });
+ minimum_contribution.maybe_min(limit.map(|limit| f32_max(limit, padding_border_size.get(axis))))
+ } else {
+ 0.0
+ }
+ })
+ }
+
+ /// Retrieve the item's minimum contribution from the cache or compute it using the provided parameters
+ #[inline(always)]
+ pub fn minimum_contribution_cached(
+ &mut self,
+ tree: &mut impl LayoutPartialTree,
+ axis: AbstractAxis,
+ axis_tracks: &[GridTrack],
+ grid_area_size: Size<Option<f32>>,
+ inner_node_size: Size<Option<f32>>,
+ ) -> f32 {
+ self.minimum_contribution_cache.get(axis).unwrap_or_else(|| {
+ let size = self.minimum_contribution(tree, axis, axis_tracks, grid_area_size, inner_node_size);
+ self.minimum_contribution_cache.set(axis, Some(size));
+ size
+ })
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/types/grid_track.rs b/vendor/taffy/src/compute/grid/types/grid_track.rs
new file mode 100644
index 00000000..4c0e0fa3
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/grid_track.rs
@@ -0,0 +1,169 @@
+//! Contains GridTrack used to represent a single grid track (row/column) during layout
+use crate::{
+ prelude::TaffyZero,
+ style::{LengthPercentage, MaxTrackSizingFunction, MinTrackSizingFunction},
+ util::sys::f32_min,
+};
+
+/// Whether a GridTrack represents an actual track or a gutter.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(in super::super) enum GridTrackKind {
+ /// Track is an actual track
+ Track,
+ /// Track is a gutter (aka grid line) (aka gap)
+ Gutter, // { name: Option<u16> },
+}
+
+/// Internal sizing information for a single grid track (row/column)
+/// Gutters between tracks are sized similarly to actual tracks, so they
+/// are also represented by this struct
+#[derive(Debug, Clone)]
+pub(in super::super) struct GridTrack {
+ #[allow(dead_code)] // Used in tests + may be useful in future
+ /// Whether the track is a full track, a gutter, or a placeholder that has not yet been initialised
+ pub kind: GridTrackKind,
+
+ /// Whether the track is a collapsed track/gutter. Collapsed tracks are effectively treated as if
+ /// they don't exist for the purposes of grid sizing. Gutters between collapsed tracks are also collapsed.
+ pub is_collapsed: bool,
+
+ /// The minimum track sizing function of the track
+ pub min_track_sizing_function: MinTrackSizingFunction,
+
+ /// The maximum track sizing function of the track
+ pub max_track_sizing_function: MaxTrackSizingFunction,
+
+ /// The distance of the start of the track from the start of the grid container
+ pub offset: f32,
+
+ /// The size (width/height as applicable) of the track
+ pub base_size: f32,
+
+ /// A temporary scratch value when sizing tracks
+ /// Note: can be infinity
+ pub growth_limit: f32,
+
+ /// A temporary scratch value when sizing tracks. Is used as an additional amount to add to the
+ /// estimate for the available space in the opposite axis when content sizing items
+ pub content_alignment_adjustment: f32,
+
+ /// A temporary scratch value when "distributing space" to avoid clobbering planned increase variable
+ pub item_incurred_increase: f32,
+ /// A temporary scratch value when "distributing space" to avoid clobbering the main variable
+ pub base_size_planned_increase: f32,
+ /// A temporary scratch value when "distributing space" to avoid clobbering the main variable
+ pub growth_limit_planned_increase: f32,
+ /// A temporary scratch value when "distributing space"
+ /// See: https://www.w3.org/TR/css3-grid-layout/#infinitely-growable
+ pub infinitely_growable: bool,
+
+ /// The resolved `fit-content()` limit of the max track sizing function (infinity if it is not `fit-content()`
+ /// or the limit cannot be resolved). Resolved once per track sizing pass by `resolve_fit_content_limit`.
+ pub fit_content_limit: f32,
+}
+
+impl GridTrack {
+ /// GridTrack constructor with all configuration parameters for the other constructors exposed
+ const fn new_with_kind(
+ kind: GridTrackKind,
+ min_track_sizing_function: MinTrackSizingFunction,
+ max_track_sizing_function: MaxTrackSizingFunction,
+ ) -> GridTrack {
+ GridTrack {
+ kind,
+ is_collapsed: false,
+ min_track_sizing_function,
+ max_track_sizing_function,
+ offset: 0.0,
+ base_size: 0.0,
+ growth_limit: 0.0,
+ content_alignment_adjustment: 0.0,
+ item_incurred_increase: 0.0,
+ base_size_planned_increase: 0.0,
+ growth_limit_planned_increase: 0.0,
+ infinitely_growable: false,
+ fit_content_limit: f32::INFINITY,
+ }
+ }
+
+ /// Create new GridTrack representing an actual track (not a gutter)
+ pub const fn new(
+ min_track_sizing_function: MinTrackSizingFunction,
+ max_track_sizing_function: MaxTrackSizingFunction,
+ ) -> GridTrack {
+ Self::new_with_kind(GridTrackKind::Track, min_track_sizing_function, max_track_sizing_function)
+ }
+
+ /// Create a new GridTrack representing a gutter
+ pub fn gutter(size: LengthPercentage) -> GridTrack {
+ Self::new_with_kind(
+ GridTrackKind::Gutter,
+ MinTrackSizingFunction::from(size),
+ MaxTrackSizingFunction::from(size),
+ )
+ }
+
+ /// Mark a GridTrack as collapsed. Also sets both of the track's sizing functions
+ /// to fixed zero-sized sizing functions.
+ pub fn collapse(&mut self) {
+ self.is_collapsed = true;
+ self.min_track_sizing_function = MinTrackSizingFunction::ZERO;
+ self.max_track_sizing_function = MaxTrackSizingFunction::ZERO;
+ self.fit_content_limit = f32::INFINITY;
+ }
+
+ #[inline(always)]
+ /// Returns true if the track is flexible (has a Flex MaxTrackSizingFunction), else false.
+ pub fn is_flexible(&self) -> bool {
+ self.max_track_sizing_function.is_fr()
+ }
+
+ #[inline(always)]
+ /// Returns true if the track is flexible (has a Flex MaxTrackSizingFunction), else false.
+ pub fn uses_percentage(&self) -> bool {
+ self.min_track_sizing_function.uses_percentage() || self.max_track_sizing_function.uses_percentage()
+ }
+
+ #[inline(always)]
+ /// Returns true if the track has an intrinsic min and or max sizing function
+ pub fn has_intrinsic_sizing_function(&self) -> bool {
+ self.min_track_sizing_function.is_intrinsic() || self.max_track_sizing_function.is_intrinsic()
+ }
+
+ /// Cache the `fit-content()` limit of the max track sizing function (if any), resolved against the
+ /// container's inner size in this axis. Percentage and calc() limits resolve to infinity if that size is
+ /// indefinite, as do tracks which are not `fit-content()`.
+ #[inline]
+ pub fn resolve_fit_content_limit(
+ &mut self,
+ axis_inner_node_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) {
+ self.fit_content_limit = self
+ .max_track_sizing_function
+ .fit_content_limit(axis_inner_node_size, calc_resolver)
+ .unwrap_or(f32::INFINITY);
+ }
+
+ #[inline(always)]
+ /// Returns the resolved `fit-content()` limit of the track (infinity if the track is not `fit-content()`)
+ pub fn fit_content_limit(&self) -> f32 {
+ self.fit_content_limit
+ }
+
+ #[inline]
+ /// Returns the track's growth limit, capped by its `fit-content()` limit (if any)
+ pub fn fit_content_limited_growth_limit(&self) -> f32 {
+ f32_min(self.growth_limit, self.fit_content_limit)
+ }
+
+ #[inline]
+ /// Returns the track's flex factor if it is a flex track, else 0.
+ pub fn flex_factor(&self) -> f32 {
+ if self.max_track_sizing_function.is_fr() {
+ self.max_track_sizing_function.0.value()
+ } else {
+ 0.0
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/types/grid_track_counts.rs b/vendor/taffy/src/compute/grid/types/grid_track_counts.rs
new file mode 100644
index 00000000..079533de
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/grid_track_counts.rs
@@ -0,0 +1,102 @@
+//! Contains TrackCounts used to keep track of the number of tracks in the explicit and implicit grids.
+//! Also contains coordinate conversion functions which depend on those counts
+//!
+//! Taffy uses two coordinate systems to refer to grid lines (the gaps/gutters between rows/columns):
+//!
+//! "CSS Grid Line" coordinates are those used in grid-row/grid-column in the CSS grid spec:
+//! - 0 is not a valid index
+//! - The line at left hand (or top) edge of the explicit grid is line 1
+//! (and counts up from there)
+//! - The line at the right hand (or bottom) edge of the explicit grid in -1
+//! (and counts down from there)
+//!
+//! "OriginZero" coordinates are a normalized form:
+//! - The line at left hand (or top) edge of the explicit grid is line 0
+//! - The next line to the right (or down) is 1, and so on
+//! - The next line to the left (or up) is -1, and so on
+//!
+//! Taffy also uses two coordinate systems to refer to grid tracks (rows/columns):
+//!
+//! Both of these systems represent the entire implicit grid, not just the explicit grid.
+//!
+//! "CellOccupancyMatrix track indices":
+//! - These are indexes into the CellOccupancyMatrix
+//! - The CellOccupancyMatrix stores only tracks
+//! - 0 is the leftmost track of the implicit grid, and indexes count up there
+//!
+//! "GridTrackVec track indices":
+//! - The GridTrackVecs store both lines and tracks, so:
+//! - even indices (0, 2, 4, etc) represent lines
+//! - odd indices (1, 3, 5, etc) represent tracks
+//! - These is always an odd number of
+//! - Index 1 is the leftmost track of the implicit grid. Index 3 is the second leftmost track, etc.
+//! - Index 0 is the leftmost grid line. Index 2 is the second leftmost line, etc.
+//!
+use crate::{compute::grid::OriginZeroLine, geometry::Line};
+use core::ops::Range;
+
+/// Stores the number of tracks in a given dimension.
+/// Stores separately the number of tracks in the implicit and explicit grids
+#[derive(Clone, Copy, Debug, PartialEq, Default)]
+pub(crate) struct TrackCounts {
+ /// The number of track in the implicit grid before the explicit grid
+ pub negative_implicit: u16,
+ /// The number of tracks in the explicit grid
+ pub explicit: u16,
+ /// The number of tracks in the implicit grid after the explicit grid
+ pub positive_implicit: u16,
+}
+
+impl TrackCounts {
+ /// Create a TrackCounts instance from raw track count numbers
+ pub const fn from_raw(negative_implicit: u16, explicit: u16, positive_implicit: u16) -> Self {
+ Self { negative_implicit, explicit, positive_implicit }
+ }
+
+ /// Count the total number of tracks in the axis
+ pub const fn len(&self) -> usize {
+ (self.negative_implicit + self.explicit + self.positive_implicit) as usize
+ }
+
+ /// The OriginZeroLine representing the start of the implicit grid
+ pub const fn implicit_start_line(&self) -> OriginZeroLine {
+ OriginZeroLine(-(self.negative_implicit as i16))
+ }
+
+ /// The OriginZeroLine representing the end of the implicit grid
+ pub const fn implicit_end_line(&self) -> OriginZeroLine {
+ OriginZeroLine((self.explicit + self.positive_implicit) as i16)
+ }
+}
+
+/// Conversion functions between OriginZero coordinates and CellOccupancyMatrix track indexes
+#[allow(dead_code)]
+impl TrackCounts {
+ /// Converts a grid line in OriginZero coordinates into the track immediately
+ /// following that grid line as an index into the CellOccupancyMatrix.
+ pub const fn oz_line_to_next_track(&self, index: OriginZeroLine) -> i16 {
+ index.0 + (self.negative_implicit as i16)
+ }
+
+ /// Converts start and end grid lines in OriginZero coordinates into a range of tracks
+ /// as indexes into the CellOccupancyMatrix
+ pub const fn oz_line_range_to_track_range(&self, input: Line<OriginZeroLine>) -> Range<i16> {
+ let start = self.oz_line_to_next_track(input.start);
+ let end = self.oz_line_to_next_track(input.end); // Don't subtract 1 as output range is exclusive
+ start..end
+ }
+
+ /// Converts a track as an index into the CellOccupancyMatrix into the grid line immediately
+ /// preceding that track in OriginZero coordinates.
+ pub const fn track_to_prev_oz_line(&self, index: u16) -> OriginZeroLine {
+ OriginZeroLine((index as i16) - (self.negative_implicit as i16))
+ }
+
+ /// Converts a range of tracks as indexes into the CellOccupancyMatrix into
+ /// start and end grid lines in OriginZero coordinates
+ pub const fn track_range_to_oz_line_range(&self, input: Range<i16>) -> Line<OriginZeroLine> {
+ let start = self.track_to_prev_oz_line(input.start as u16);
+ let end = self.track_to_prev_oz_line(input.end as u16); // Don't add 1 as input range is exclusive
+ Line { start, end }
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/types/mod.rs b/vendor/taffy/src/compute/grid/types/mod.rs
new file mode 100644
index 00000000..d73feaf5
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/mod.rs
@@ -0,0 +1,19 @@
+//! Structs and enums that are used within the grid module
+mod cell_occupancy;
+mod coordinates;
+mod grid_item;
+mod grid_track;
+mod grid_track_counts;
+mod named;
+
+// Publish only locally in the grid module
+pub(super) use cell_occupancy::{CellOccupancyMatrix, CellOccupancyState};
+pub(crate) use coordinates::{GridCoordinate, GridLine, OriginZeroLine, MAX_GRID_TRACKS, MAX_OZ_LINE, MIN_OZ_LINE};
+pub(super) use grid_item::GridItem;
+pub(super) use grid_track::GridTrack;
+pub(super) use grid_track_counts::TrackCounts;
+pub(super) use named::{GridAreasMap, NamedLineResolver};
+pub use named::{GridLineNames, GridLineNamesIter};
+
+#[allow(unused_imports)]
+pub(super) use grid_track::GridTrackKind;
diff --git a/vendor/taffy/src/compute/grid/types/named.rs b/vendor/taffy/src/compute/grid/types/named.rs
new file mode 100644
index 00000000..70838fe7
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/types/named.rs
@@ -0,0 +1,998 @@
+//! Code for resolving name grid lines and areas
+
+use crate::{
+ CheapCloneStr, GenericGridTemplateComponent, GenericRepetition as _, GridAreaAxis, GridAreaEnd, GridContainerStyle,
+ GridPlacement, Line, NonNamedGridPlacement, RepetitionCount,
+};
+use core::{borrow::Borrow, cmp::Ordering, fmt::Debug};
+
+use super::{GridLine, OriginZeroLine, MAX_GRID_TRACKS};
+use crate::geometry::AbsoluteAxis;
+use crate::sys::DefaultCheapStr;
+use crate::sys::{Map, Vec};
+use smallvec::{smallvec, SmallVec};
+
+/// Wrap an `AsRef<str>` type with a type which implements Hash by first
+/// deferring to the underlying `&str`'s implementation of Hash.
+#[derive(Debug, Clone)]
+pub(crate) struct StrHasher<T: CheapCloneStr>(pub T);
+impl<T: CheapCloneStr> PartialOrd for StrHasher<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+impl<T: CheapCloneStr> Ord for StrHasher<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.0.as_ref().cmp(other.0.as_ref())
+ }
+}
+impl<T: CheapCloneStr> PartialEq for StrHasher<T> {
+ fn eq(&self, other: &Self) -> bool {
+ other.0.as_ref() == self.0.as_ref()
+ }
+}
+impl<T: CheapCloneStr> Eq for StrHasher<T> {}
+#[cfg(feature = "std")]
+impl<T: CheapCloneStr> std::hash::Hash for StrHasher<T> {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.0.as_ref().hash(state)
+ }
+}
+impl<T: CheapCloneStr> Borrow<str> for StrHasher<T> {
+ fn borrow(&self) -> &str {
+ self.0.as_ref()
+ }
+}
+
+/// The one-indexed line positions of a single grid line name. Inline capacity of 4 keeps the
+/// type the same size as `Vec<u32>` (24 bytes) while avoiding a heap allocation for names
+/// mapping to at most 4 lines (the common case)
+pub(crate) type LinePositions = SmallVec<[u32; 4]>;
+
+/// Map from a grid line name to its one-indexed line positions
+type NamedGridLinesMap<S> = Map<StrHasher<S>, LinePositions>;
+
+/// The one-indexed positions of the first line that starts and the first line that ends a named grid area in
+/// each axis, i.e. the first line named `<area-name>-start`/`<area-name>-end` (explicitly or by
+/// `grid-template-areas`). A value of 0 means that there is no such line.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) struct AreaLines {
+ /// The first line that starts the area in the row axis
+ row_start: u32,
+ /// The first line that ends the area in the row axis
+ row_end: u32,
+ /// The first line that starts the area in the column axis
+ column_start: u32,
+ /// The first line that ends the area in the column axis
+ column_end: u32,
+}
+
+impl AreaLines {
+ /// The line for the passed edge of the area (if there is one)
+ fn line(&self, axis: GridAreaAxis, end: GridAreaEnd) -> Option<&u32> {
+ let line = match (axis, end) {
+ (GridAreaAxis::Row, GridAreaEnd::Start) => &self.row_start,
+ (GridAreaAxis::Row, GridAreaEnd::End) => &self.row_end,
+ (GridAreaAxis::Column, GridAreaEnd::Start) => &self.column_start,
+ (GridAreaAxis::Column, GridAreaEnd::End) => &self.column_end,
+ };
+ Some(line).filter(|line| **line != 0)
+ }
+
+ /// The line for the passed edge of the area (0 if there is none)
+ fn line_mut(&mut self, axis: GridAreaAxis, end: GridAreaEnd) -> &mut u32 {
+ match (axis, end) {
+ (GridAreaAxis::Row, GridAreaEnd::Start) => &mut self.row_start,
+ (GridAreaAxis::Row, GridAreaEnd::End) => &mut self.row_end,
+ (GridAreaAxis::Column, GridAreaEnd::Start) => &mut self.column_start,
+ (GridAreaAxis::Column, GridAreaEnd::End) => &mut self.column_end,
+ }
+ }
+}
+
+/// Map from the name of a grid area to the lines of its edges.
+///
+/// This is how the `<area-name>-start` and `<area-name>-end` line names that `grid-template-areas` implicitly
+/// generates are represented: storing them as line names would require allocating a string for each of them.
+pub(crate) type GridAreasMap<S> = Map<StrHasher<S>, AreaLines>;
+
+/// Split a line name of the form `<area-name>-start` or `<area-name>-end` into the area name and the edge
+fn split_area_edge_name(name: &str) -> Option<(&str, GridAreaEnd)> {
+ if let Some(area_name) = name.strip_suffix("-start") {
+ Some((area_name, GridAreaEnd::Start))
+ } else if let Some(area_name) = name.strip_suffix("-end") {
+ Some((area_name, GridAreaEnd::End))
+ } else {
+ None
+ }
+}
+
+/// Resolver for named placements in one grid axis
+struct NamedLineResolverAxis<'a, S: CheapCloneStr> {
+ /// Named lines and their one-indexed positions
+ lines: &'a NamedGridLinesMap<S>,
+ /// The edges of named grid areas (in both axes)
+ areas: &'a GridAreasMap<S>,
+ /// The axis being resolved
+ axis: GridAreaAxis,
+ /// Number of explicit tracks in this axis
+ explicit_track_count: u16,
+}
+
+/// Resolver that takes grid lines names and area names as input and can then be used to
+/// resolve line names of grid placement properties into line numbers.
+pub(crate) struct NamedLineResolver<S: CheapCloneStr> {
+ /// Map of row line names to line numbers. Each line name may correspond to multiple lines
+ /// so we store a `SmallVec`
+ row_lines: NamedGridLinesMap<S>,
+ /// Map of column line names to line numbers. Each line name may correspond to multiple lines
+ /// so we store a `SmallVec`
+ column_lines: NamedGridLinesMap<S>,
+ /// Map of area names to the lines of the area's edges
+ areas: GridAreasMap<S>,
+ /// Number of columns implied by grid area definitions
+ area_column_count: u16,
+ /// Number of rows implied by grid area definitions
+ area_row_count: u16,
+ /// The number of explicit columns in the grid. This is an *input* to the `NamedLineResolver` and is
+ /// used when computing the fallback line when a non-existent named line is specified.
+ explicit_column_count: u16,
+ /// The number of explicit rows in the grid. This is an *input* to the `NamedLineResolver` and is
+ /// used when computing the fallback line when a non-existent named line is specified.
+ explicit_row_count: u16,
+ /// The (1-indexed line number, name) pairs of every column line named in the track template,
+ /// in source order (excludes the implicit names generated by `grid-template-areas`)
+ column_line_name_pairs: Vec<(u32, S)>,
+ /// The (1-indexed line number, name) pairs of every row line named in the track template,
+ /// in source order (excludes the implicit names generated by `grid-template-areas`)
+ row_line_name_pairs: Vec<(u32, S)>,
+}
+
+/// Utility function to create or update an entry in a line name map
+///
+/// `areas` must already contain the edges of the areas defined by `grid-template-areas`
+fn upsert_line_name_map<S: CheapCloneStr>(
+ map: &mut NamedGridLinesMap<S>,
+ areas: &mut GridAreasMap<S>,
+ axis: GridAreaAxis,
+ key: S,
+ value: u32,
+) {
+ // A line named `foo-start` or `foo-end` is also an edge of the (implicitly) named area `foo`. Record it as such
+ // if it is the first such line. If `foo` is also an area defined by `grid-template-areas`, then the line which
+ // that area generated also has this name.
+ let mut area_line = 0;
+ if let Some((area_name, end)) = split_area_edge_name(key.as_ref()) {
+ // The key is only created if the area is not already in the map
+ if !areas.contains_key(area_name) {
+ areas.insert(StrHasher(S::from(area_name)), AreaLines::default());
+ }
+ let edge = areas.get_mut(area_name).unwrap().line_mut(axis, end);
+ area_line = *edge;
+ *edge = if *edge == 0 { value } else { (*edge).min(value) };
+ }
+
+ map.entry(StrHasher(key)).and_modify(|lines| lines.push(value)).or_insert_with(|| {
+ // Until this entry is created, the only line that can have been recorded for this edge is the area's own
+ if area_line == 0 {
+ smallvec![value]
+ } else {
+ smallvec![area_line, value]
+ }
+ });
+}
+
+impl<S: CheapCloneStr> NamedLineResolverAxis<'_, S> {
+ /// The line for the passed edge of the named grid area in this axis (if there is one)
+ fn area_line(&self, area_name: &str, end: GridAreaEnd) -> Option<&u32> {
+ self.areas.get(area_name)?.line(self.axis, end)
+ }
+
+ /// Resolve named lines and spans into numeric placements
+ fn resolve_line_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
+ let start_holder;
+ let start_line_resolved = if let GridPlacement::NamedLine(name, idx) = &line.start {
+ start_holder = GridPlacement::Line(self.find_named_line(name, *idx, GridAreaEnd::Start));
+ &start_holder
+ } else {
+ &line.start
+ };
+
+ let end_holder;
+ let end_line_resolved = if let GridPlacement::NamedLine(name, idx) = &line.end {
+ end_holder = GridPlacement::Line(self.find_named_line(name, *idx, GridAreaEnd::End));
+ &end_holder
+ } else {
+ &line.end
+ };
+
+ // If both the *-start and *-end values of its grid-placement properties specify a line, its grid span is implicit.
+ // If it has an explicit span value, its grid span is explicit.
+ // Otherwise, its grid span is automatic:
+ // - if it is subgridded in that axis, its grid span is determined from its <line-name-list>;
+ // - otherwise its grid span is 1.
+ //
+ // <https://drafts.csswg.org/css-grid-2/#grid-span>
+ match (&start_line_resolved, &end_line_resolved) {
+ (GridPlacement::Line(start_line), GridPlacement::NamedSpan(name, idx)) if start_line.as_i16() != 0 => {
+ let after_start_line = start_line.into_origin_zero_line(self.explicit_track_count) + 1;
+ let end_line =
+ self.nth_line_forwards(self.lines_named(name.as_ref()), after_start_line, (*idx).max(1) as i32);
+ Line {
+ start: NonNamedGridPlacement::Line(*start_line),
+ end: NonNamedGridPlacement::Line(end_line.into_grid_line(self.explicit_track_count)),
+ }
+ }
+ (GridPlacement::NamedSpan(name, idx), GridPlacement::Line(end_line)) if end_line.as_i16() != 0 => {
+ let before_end_line = end_line.into_origin_zero_line(self.explicit_track_count) - 1;
+ let start_line =
+ self.nth_line_backwards(self.lines_named(name.as_ref()), before_end_line, (*idx).max(1) as i32);
+ Line {
+ start: NonNamedGridPlacement::Line(start_line.into_grid_line(self.explicit_track_count)),
+ end: NonNamedGridPlacement::Line(*end_line),
+ }
+ }
+ (start, end) => Line {
+ start: match start {
+ GridPlacement::Auto => NonNamedGridPlacement::Auto,
+ GridPlacement::Line(grid_line) => NonNamedGridPlacement::Line(*grid_line),
+ GridPlacement::Span(span) => NonNamedGridPlacement::Span(*span),
+ GridPlacement::NamedSpan(_, _) => NonNamedGridPlacement::Span(1),
+ _ => unreachable!(),
+ },
+ end: match end {
+ GridPlacement::Auto => NonNamedGridPlacement::Auto,
+ GridPlacement::Line(grid_line) => NonNamedGridPlacement::Line(*grid_line),
+ GridPlacement::Span(span) => NonNamedGridPlacement::Span(*span),
+ GridPlacement::NamedSpan(_, _) => NonNamedGridPlacement::Span(1),
+ _ => unreachable!(),
+ },
+ },
+ }
+ }
+
+ /// Resolve the grid line for a named grid line (`<custom-ident>` or `<integer> <custom-ident>`).
+ /// An index of 0 is used to represent "no index specified".
+ ///
+ /// <https://drafts.csswg.org/css-grid-2/#line-placement>
+ fn find_named_line(&self, name: &S, idx: i16, end: GridAreaEnd) -> GridLine {
+ let name = name.as_ref();
+
+ // A `<custom-ident>` on its own first attempts to match the edge of a named grid area:
+ // the first line named `<custom-ident>-start` (or `<custom-ident>-end` for an end line).
+ // Otherwise it is treated as if the integer 1 had been specified along with it.
+ if idx == 0 {
+ if let Some(first_line) = self.area_line(name, end) {
+ return OriginZeroLine::clamped(oz_line(*first_line)).into_grid_line(self.explicit_track_count);
+ }
+ }
+
+ let lines = self.lines_named(name);
+ let line = if idx >= 0 {
+ self.nth_line_forwards(lines, OriginZeroLine(0), (idx as i32).max(1))
+ } else {
+ self.nth_line_backwards(lines, self.last_explicit_line(), -(idx as i32))
+ };
+ line.into_grid_line(self.explicit_track_count)
+ }
+
+ /// The sorted line numbers of the lines with the passed name
+ ///
+ /// A line generated by a grid area is included in the lines of its name if any line has been explicitly
+ /// given the same name. Otherwise it is found from the area's edges.
+ fn lines_named(&self, name: &str) -> &[u32] {
+ match self.lines.get(name) {
+ Some(lines) => lines.as_slice(),
+ None => split_area_edge_name(name)
+ .and_then(|(area_name, area_end)| self.area_line(area_name, area_end))
+ .map(core::slice::from_ref)
+ .unwrap_or(&[]),
+ }
+ }
+
+ /// The line at the end edge of the explicit grid
+ fn last_explicit_line(&self) -> OriginZeroLine {
+ OriginZeroLine(self.explicit_track_count as i16)
+ }
+
+ /// Find the `n`th line in `lines` (searching forwards) that is not before `first_line`.
+ ///
+ /// If there are not enough such lines, then all implicit lines after the explicit grid are
+ /// assumed to be in `lines` for the purpose of counting
+ ///
+ /// <https://drafts.csswg.org/css-grid-2/#grid-placement-int>
+ fn nth_line_forwards(&self, lines: &[u32], first_line: OriginZeroLine, n: i32) -> OriginZeroLine {
+ let first_line = first_line.0.max(0) as i32;
+ let lines = &lines[lines.partition_point(|line| oz_line(*line) < first_line)..];
+ let line = match lines.get(n as usize - 1) {
+ Some(line) => oz_line(*line),
+ None => first_line.max(self.last_explicit_line().0 as i32 + 1) + (n - lines.len() as i32) - 1,
+ };
+ OriginZeroLine::clamped(line)
+ }
+
+ /// Find the `n`th line in `lines` (searching backwards) that is not after `last_line`.
+ ///
+ /// If there are not enough such lines, then all implicit lines before the explicit grid are
+ /// assumed to be in `lines` for the purpose of counting
+ ///
+ /// <https://drafts.csswg.org/css-grid-2/#grid-placement-int>
+ fn nth_line_backwards(&self, lines: &[u32], last_line: OriginZeroLine, n: i32) -> OriginZeroLine {
+ let last_line = last_line.0.min(self.last_explicit_line().0) as i32;
+ let lines = &lines[..lines.partition_point(|line| oz_line(*line) <= last_line)];
+ let line = match lines.len().checked_sub(n as usize) {
+ Some(index) => oz_line(lines[index]),
+ None => last_line.min(-1) - (n - lines.len() as i32) + 1,
+ };
+ OriginZeroLine::clamped(line)
+ }
+}
+
+/// The named line maps store lines as 1-based "CSS Grid Line" numbers (which are always within the
+/// explicit grid). Convert one to OriginZero coordinates.
+fn oz_line(line: u32) -> i32 {
+ line as i32 - 1
+}
+
+impl<S: CheapCloneStr> NamedLineResolver<S> {
+ /// Create and initialise a new `NamedLineResolver`
+ pub(crate) fn new(
+ style: &impl GridContainerStyle<CustomIdent = S>,
+ column_auto_repetitions: u16,
+ row_auto_repetitions: u16,
+ ) -> Self {
+ let mut column_lines: NamedGridLinesMap<S> = Map::new();
+ let mut row_lines: NamedGridLinesMap<S> = Map::new();
+ let mut areas: GridAreasMap<S> = Map::new();
+
+ let mut column_line_name_pairs: Vec<(u32, S)> = Vec::new();
+ let mut row_line_name_pairs: Vec<(u32, S)> = Vec::new();
+
+ // The size of the area template may be larger than the extents of the named areas
+ // due to unnamed (`.`) cells, so it is taken from the style rather than being derived
+ // from the areas themselves.
+ let area_column_count = style.grid_template_area_column_count();
+ let area_row_count = style.grid_template_area_row_count();
+ if let Some(area_iter) = style.grid_template_areas() {
+ for area in area_iter.into_iter() {
+ let lines = AreaLines {
+ row_start: area.row_start as u32,
+ row_end: area.row_end as u32,
+ column_start: area.column_start as u32,
+ column_end: area.column_end as u32,
+ };
+ areas.insert(StrHasher(area.name.clone()), lines);
+ }
+ }
+
+ let mut current_line = 0;
+ if let Some(mut column_tracks) = style.grid_template_columns() {
+ if let Some(column_line_names_iter) = style.grid_template_column_names() {
+ for line_names in column_line_names_iter {
+ current_line += 1;
+ for line_name in line_names.into_iter() {
+ column_line_name_pairs.push((current_line, line_name.clone()));
+ upsert_line_name_map(
+ &mut column_lines,
+ &mut areas,
+ GridAreaAxis::Column,
+ line_name.clone(),
+ current_line,
+ );
+ }
+
+ if let Some(GenericGridTemplateComponent::Repeat(repeat)) = column_tracks.next() {
+ let repeat_count = match repeat.count() {
+ RepetitionCount::Count(count) => count,
+ RepetitionCount::AutoFill | RepetitionCount::AutoFit => column_auto_repetitions,
+ };
+
+ // Line name sets are positional: set `i` names the `i`th line of each
+ // repetition, and the final line name set of each repetition collapses
+ // with the first line name set of the following one. An empty list means
+ // the repetition's lines are unnamed; any other length must be exactly
+ // `track_count + 1` (one set per line, including both edge lines).
+ let line_name_set_count = repeat.lines_names().len() as u32;
+ let lines_per_repetition = repeat.track_count() as u32;
+ assert!(
+ line_name_set_count == 0 || line_name_set_count == lines_per_repetition + 1,
+ "grid template repetition must have no line name sets or exactly track count + 1 of them ({} tracks but {} line name sets)",
+ lines_per_repetition,
+ line_name_set_count,
+ );
+
+ for _ in 0..repeat_count {
+ for (line, line_name_set) in (current_line..).zip(repeat.lines_names()) {
+ for line_name in line_name_set {
+ column_line_name_pairs.push((line, line_name.clone()));
+ upsert_line_name_map(
+ &mut column_lines,
+ &mut areas,
+ GridAreaAxis::Column,
+ line_name.clone(),
+ line,
+ );
+ }
+ }
+ current_line += lines_per_repetition;
+
+ // Names for lines beyond the maximum track limit are never resolvable:
+ // stop generating them (the explicit grid is clamped to MAX_GRID_TRACKS)
+ if current_line > MAX_GRID_TRACKS as u32 {
+ break;
+ }
+ }
+ // Last line name set collapses with following line name set
+ if repeat_count > 0 {
+ current_line = current_line.saturating_sub(1);
+ }
+ }
+ }
+ }
+ }
+
+ let mut current_line = 0;
+ if let Some(mut row_tracks) = style.grid_template_rows() {
+ if let Some(row_line_names_iter) = style.grid_template_row_names() {
+ for line_names in row_line_names_iter {
+ current_line += 1;
+ for line_name in line_names.into_iter() {
+ row_line_name_pairs.push((current_line, line_name.clone()));
+ upsert_line_name_map(
+ &mut row_lines,
+ &mut areas,
+ GridAreaAxis::Row,
+ line_name.clone(),
+ current_line,
+ );
+ }
+
+ if let Some(GenericGridTemplateComponent::Repeat(repeat)) = row_tracks.next() {
+ let repeat_count = match repeat.count() {
+ RepetitionCount::Count(count) => count,
+ RepetitionCount::AutoFill | RepetitionCount::AutoFit => row_auto_repetitions,
+ };
+
+ // Line name sets are positional: set `i` names the `i`th line of each
+ // repetition, and the final line name set of each repetition collapses
+ // with the first line name set of the following one. An empty list means
+ // the repetition's lines are unnamed; any other length must be exactly
+ // `track_count + 1` (one set per line, including both edge lines).
+ let line_name_set_count = repeat.lines_names().len() as u32;
+ let lines_per_repetition = repeat.track_count() as u32;
+ assert!(
+ line_name_set_count == 0 || line_name_set_count == lines_per_repetition + 1,
+ "grid template repetition must have no line name sets or exactly track count + 1 of them ({} tracks but {} line name sets)",
+ lines_per_repetition,
+ line_name_set_count,
+ );
+
+ for _ in 0..repeat_count {
+ for (line, line_name_set) in (current_line..).zip(repeat.lines_names()) {
+ for line_name in line_name_set {
+ row_line_name_pairs.push((line, line_name.clone()));
+ upsert_line_name_map(
+ &mut row_lines,
+ &mut areas,
+ GridAreaAxis::Row,
+ line_name.clone(),
+ line,
+ );
+ }
+ }
+ current_line += lines_per_repetition;
+
+ // Names for lines beyond the maximum track limit are never resolvable:
+ // stop generating them (the explicit grid is clamped to MAX_GRID_TRACKS)
+ if current_line > MAX_GRID_TRACKS as u32 {
+ break;
+ }
+ }
+ // Last line name set collapses with following line name set
+ if repeat_count > 0 {
+ current_line = current_line.saturating_sub(1);
+ }
+ }
+ }
+ }
+ }
+ // Sort and dedup lines for each column name
+ for lines in column_lines.values_mut() {
+ lines.sort_unstable();
+ lines.dedup();
+ }
+ // Sort and dedup lines for each row name
+ for lines in row_lines.values_mut() {
+ lines.sort_unstable();
+ lines.dedup();
+ }
+
+ Self {
+ area_column_count,
+ area_row_count,
+ explicit_column_count: 0, // Overwritten later
+ explicit_row_count: 0, // Overwritten later
+ row_lines,
+ column_lines,
+ areas,
+ column_line_name_pairs,
+ row_line_name_pairs,
+ }
+ }
+
+ /// Build the per-line name groups of the explicit grid in the passed axis as a
+ /// [`GridLineNames`], with `repeat()`s expanded. Only names given explicitly in the track
+ /// template are included; the implicit `<name>-start`/`<name>-end` names generated by
+ /// `grid-template-areas` are omitted (matching the resolved value of
+ /// `grid-template-rows`/`grid-template-columns` in browsers) but remain resolvable for
+ /// placement via [`GridLineNames::resolve_line_names`].
+ ///
+ /// Line indices are relative to the explicit grid (line 0 = start of the first explicit track).
+ pub(crate) fn detailed_line_names(&self, axis: AbsoluteAxis) -> GridLineNames<S> {
+ let (pairs, explicit_track_count) = match axis {
+ AbsoluteAxis::Horizontal => (&self.column_line_name_pairs, self.explicit_column_count),
+ AbsoluteAxis::Vertical => (&self.row_line_name_pairs, self.explicit_row_count),
+ };
+
+ if pairs.is_empty() {
+ return GridLineNames::default();
+ }
+
+ // Stable sort by line number preserves the source order of names within each line
+ let mut sorted_pairs: Vec<&(u32, S)> = pairs.iter().collect();
+ sorted_pairs.sort_by_key(|(line, _)| *line);
+
+ let line_count = explicit_track_count as usize + 1;
+ let mut line_names = GridLineNames::with_capacity(sorted_pairs.len(), line_count + 1);
+ let mut pair_iter = sorted_pairs.into_iter().peekable();
+ for line in 1..=(line_count as u32) {
+ line_names.start_line();
+ while let Some(&&(pair_line, ref name)) = pair_iter.peek() {
+ if pair_line != line {
+ break;
+ }
+ pair_iter.next();
+ if !line_names.current_line_contains(name.as_ref()) {
+ line_names.push_name(name.clone());
+ }
+ }
+ }
+ line_names
+ }
+
+ /// Resolve named lines for both the `start` and `end` of a row-axis grid placement
+ #[inline(always)]
+ pub(crate) fn resolve_row_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
+ self.resolve_line_names(line, GridAreaAxis::Row)
+ }
+
+ /// Resolve named lines for both the `start` and `end` of a column-axis grid placement
+ #[inline(always)]
+ pub(crate) fn resolve_column_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
+ self.resolve_line_names(line, GridAreaAxis::Column)
+ }
+
+ /// Resolve named lines for both the `start` and `end` of a grid placement
+ #[inline(always)]
+ pub(crate) fn resolve_line_names(
+ &self,
+ line: &Line<GridPlacement<S>>,
+ axis: GridAreaAxis,
+ ) -> Line<NonNamedGridPlacement> {
+ let (lines, explicit_track_count) = match axis {
+ GridAreaAxis::Row => (&self.row_lines, self.explicit_row_count),
+ GridAreaAxis::Column => (&self.column_lines, self.explicit_column_count),
+ };
+ NamedLineResolverAxis { lines, areas: &self.areas, axis, explicit_track_count }.resolve_line_names(line)
+ }
+
+ /// Move the row and column line-name maps into the detailed grid information, and return the grid area map
+ /// for the same purpose
+ pub(crate) fn populate_detailed_line_resolvers(
+ self,
+ rows: &mut GridLineNames<S>,
+ columns: &mut GridLineNames<S>,
+ ) -> GridAreasMap<S> {
+ rows.resolver = self.row_lines;
+ columns.resolver = self.column_lines;
+ self.areas
+ }
+
+ /// Get the number of columns defined by the grid areas
+ pub(crate) fn area_column_count(&self) -> u16 {
+ self.area_column_count
+ }
+
+ /// Get the number of rows defined by the grid areas
+ pub(crate) fn area_row_count(&self) -> u16 {
+ self.area_row_count
+ }
+
+ /// Set the number of columns in the explicit grid
+ pub(crate) fn set_explicit_column_count(&mut self, count: u16) {
+ self.explicit_column_count = count;
+ }
+
+ /// Set the number of rows in the explicit grid
+ pub(crate) fn set_explicit_row_count(&mut self, count: u16) {
+ self.explicit_row_count = count;
+ }
+}
+
+impl<S: CheapCloneStr> Debug for NamedLineResolver<S> {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ writeln!(f, "Grid Areas (row-start / column-start / row-end / column-end):")?;
+ for (name, area) in self.areas.iter() {
+ let AreaLines { row_start, column_start, row_end, column_end } = area;
+ writeln!(f, "{}: {row_start} / {column_start} / {row_end} / {column_end}", name.0.as_ref())?;
+ }
+
+ writeln!(f, "Grid Rows:")?;
+ for (name, lines) in self.row_lines.iter() {
+ write!(f, "{}: ", name.0.as_ref())?;
+ for line in lines {
+ write!(f, "{line} ")?;
+ }
+ writeln!(f)?;
+ }
+
+ writeln!(f, "Grid Columns:")?;
+ for (name, lines) in self.column_lines.iter() {
+ write!(f, "{}: ", name.0.as_ref())?;
+ for line in lines {
+ write!(f, "{line} ")?;
+ }
+ writeln!(f)?;
+ }
+
+ Ok(())
+ }
+}
+
+/// The names of each explicit grid line in a single axis, stored in CSR (compressed sparse
+/// row) format: a single flat `Vec` of names plus a `Vec` of offsets into it (one more offset
+/// than there are lines). The names of line `i` (0-indexed) are `names[offsets[i]..offsets[i + 1]]`.
+///
+/// Line indices here are relative to the explicit grid;
+/// [`DetailedGridTracksInfo`](crate::DetailedGridTracksInfo) provides accessors with indices
+/// relative to the full grid (including implicit tracks).
+///
+/// Iterate over per-line name groups with [`GridLineNames::iter`], or access a single line's
+/// names with [`GridLineNames::line`]. A grid with no named lines is represented by two empty
+/// `Vec`s (see [`GridLineNames::is_empty`]).
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct GridLineNames<S: CheapCloneStr = DefaultCheapStr> {
+ /// The names of every grid line in the axis, concatenated in line order
+ names: Vec<S>,
+ /// Offsets into `names`: line `i`'s names are `names[offsets[i]..offsets[i + 1]]`.
+ /// Either empty (no named lines) or of length `line count + 1`.
+ offsets: Vec<u32>,
+ /// Named line lookup used to resolve arbitrary grid placements
+ resolver: NamedGridLinesMap<S>,
+}
+
+impl<S: CheapCloneStr> GridLineNames<S> {
+ /// Create an empty `GridLineNames` with pre-allocated capacity
+ pub(crate) fn with_capacity(name_capacity: usize, offset_capacity: usize) -> Self {
+ let mut offsets = Vec::with_capacity(offset_capacity);
+ offsets.push(0);
+ Self { names: Vec::with_capacity(name_capacity), offsets, resolver: Map::new() }
+ }
+
+ /// Start a new (initially empty) line
+ pub(crate) fn start_line(&mut self) {
+ self.offsets.push(self.names.len() as u32);
+ }
+
+ /// Append a name to the current (last) line
+ pub(crate) fn push_name(&mut self, name: S) {
+ self.names.push(name);
+ *self.offsets.last_mut().unwrap() = self.names.len() as u32;
+ }
+
+ /// Whether the current (last) line already contains the passed name
+ pub(crate) fn current_line_contains(&self, name: &str) -> bool {
+ self.line(self.line_count().wrapping_sub(1)).iter().any(|n| n.as_ref() == name)
+ }
+
+ /// Resolve named lines and spans using the retained line-name map and the passed grid area map
+ pub(crate) fn resolve_line_names(
+ &self,
+ line: &Line<GridPlacement<S>>,
+ areas: &GridAreasMap<S>,
+ axis: GridAreaAxis,
+ explicit_track_count: u16,
+ ) -> Line<NonNamedGridPlacement> {
+ NamedLineResolverAxis { lines: &self.resolver, areas, axis, explicit_track_count }.resolve_line_names(line)
+ }
+
+ /// Whether the axis has any named lines at all
+ pub fn is_empty(&self) -> bool {
+ self.names.is_empty()
+ }
+
+ /// The number of grid lines represented (zero if the grid has no named lines)
+ pub fn line_count(&self) -> usize {
+ self.offsets.len().saturating_sub(1)
+ }
+
+ /// The names of the line with the passed 0-indexed line index.
+ /// Returns an empty slice if the line has no names or the index is out of range.
+ pub fn line(&self, line_index: usize) -> &[S] {
+ match (self.offsets.get(line_index), self.offsets.get(line_index + 1)) {
+ (Some(&start), Some(&end)) => &self.names[start as usize..end as usize],
+ _ => &[],
+ }
+ }
+
+ /// Iterate over the name group (`&[S]`) of each grid line in line order
+ pub fn iter(&self) -> GridLineNamesIter<'_, S> {
+ self.iter_padded(0, 0)
+ }
+
+ /// Iterate over the name group (`&[S]`) of each grid line in line order, additionally
+ /// yielding `leading_empty` empty groups before the stored lines and `trailing_empty`
+ /// empty groups after them (representing unnamed implicit grid lines)
+ pub(crate) fn iter_padded(&self, leading_empty: usize, trailing_empty: usize) -> GridLineNamesIter<'_, S> {
+ GridLineNamesIter { names: &self.names, offsets: self.offsets.windows(2), leading_empty, trailing_empty }
+ }
+}
+
+impl<'a, S: CheapCloneStr> IntoIterator for &'a GridLineNames<S> {
+ type Item = &'a [S];
+ type IntoIter = GridLineNamesIter<'a, S>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+/// Iterator over the per-line name groups of a [`GridLineNames`]. Yields one `&[S]` per grid
+/// line (which is empty for unnamed lines)
+#[derive(Debug, Clone)]
+pub struct GridLineNamesIter<'a, S: CheapCloneStr> {
+ /// The flat name storage being iterated over
+ names: &'a [S],
+ /// Iterator over adjacent pairs of offsets into `names`
+ offsets: core::slice::Windows<'a, u32>,
+ /// Number of (unnamed, implicit) lines remaining before the stored lines
+ leading_empty: usize,
+ /// Number of (unnamed, implicit) lines remaining after the stored lines
+ trailing_empty: usize,
+}
+
+impl<'a, S: CheapCloneStr> Iterator for GridLineNamesIter<'a, S> {
+ type Item = &'a [S];
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.leading_empty > 0 {
+ self.leading_empty -= 1;
+ return Some(&[]);
+ }
+ if let Some(window) = self.offsets.next() {
+ return Some(&self.names[window[0] as usize..window[1] as usize]);
+ }
+ if self.trailing_empty > 0 {
+ self.trailing_empty -= 1;
+ return Some(&[]);
+ }
+ None
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let len = self.leading_empty + self.offsets.len() + self.trailing_empty;
+ (len, Some(len))
+ }
+}
+
+impl<S: CheapCloneStr> ExactSizeIterator for GridLineNamesIter<'_, S> {}
+
+#[cfg(test)]
+mod tests {
+ use super::super::{MAX_OZ_LINE, MIN_OZ_LINE};
+ use super::*;
+ use crate::style::GenericGridPlacement;
+ use crate::sys::DefaultCheapStr;
+ use crate::GridTemplateAreas;
+ use crate::Style;
+ use crate::{GridTemplateArea, NonNamedGridPlacement};
+
+ fn resolver(explicit_track_count: u16) -> NamedLineResolver<DefaultCheapStr> {
+ let mut resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
+ resolver.set_explicit_column_count(explicit_track_count);
+ resolver
+ }
+
+ fn resolved_start_line(
+ resolver: &NamedLineResolver<DefaultCheapStr>,
+ placement: GridPlacement<DefaultCheapStr>,
+ ) -> i16 {
+ let resolved = resolver.resolve_column_names(&Line { start: placement, end: GridPlacement::Auto });
+ match resolved.start {
+ GenericGridPlacement::Line(line) => line.as_i16(),
+ _ => panic!("expected a resolved line"),
+ }
+ }
+
+ #[test]
+ fn extreme_missing_named_line_indices_do_not_overflow() {
+ // Lines are clamped to the limits of the grid, in the same way as `GridLine::into_origin_zero_line`
+ let resolver = resolver(10_000);
+ assert_eq!(
+ resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("missing"), i16::MAX)),
+ OriginZeroLine(MAX_OZ_LINE).into_grid_line(10_000).as_i16()
+ );
+ assert_eq!(
+ resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("missing"), i16::MIN)),
+ OriginZeroLine(MIN_OZ_LINE).into_grid_line(10_000).as_i16()
+ );
+ }
+
+ #[test]
+ fn large_named_span_does_not_wrap_negative() {
+ let resolver = resolver(10_000);
+ let resolved = resolver.resolve_column_names(&Line {
+ start: GridPlacement::Line(GridLine::from(1)),
+ end: GridPlacement::NamedSpan(DefaultCheapStr::from("missing"), u16::MAX),
+ });
+ match resolved.end {
+ GenericGridPlacement::Line(line) => assert_eq!(line, OriginZeroLine(MAX_OZ_LINE).into_grid_line(10_000)),
+ _ => panic!("expected a resolved line"),
+ }
+ }
+
+ #[test]
+ fn area_lines_saturate_when_converted_to_grid_lines() {
+ let style = Style {
+ grid_template_areas: Some(GridTemplateAreas {
+ areas: vec![GridTemplateArea {
+ name: DefaultCheapStr::from("area"),
+ row_start: 1,
+ row_end: 2,
+ column_start: u16::MAX,
+ column_end: u16::MAX,
+ }],
+ row_count: 1,
+ column_count: u16::MAX,
+ }),
+ ..Style::DEFAULT
+ };
+ let resolver = NamedLineResolver::new(&style, 0, 0);
+ assert_eq!(
+ resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("area-start"), 1)),
+ OriginZeroLine(MAX_OZ_LINE).into_grid_line(0).as_i16()
+ );
+ assert_eq!(
+ resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("area"), 0)),
+ OriginZeroLine(MAX_OZ_LINE).into_grid_line(0).as_i16()
+ );
+ }
+
+ /// A resolver for a grid with 4 explicit columns, the passed names for each of the 5 column lines, and a
+ /// single grid area named "area" which spans columns 2 and 3 (lines 2 to 4)
+ fn area_resolver(column_line_names: [&[&str]; 5]) -> NamedLineResolver<DefaultCheapStr> {
+ let style = Style {
+ grid_template_column_names: column_line_names
+ .iter()
+ .map(|names| names.iter().map(|name| DefaultCheapStr::from(*name)).collect())
+ .collect(),
+ grid_template_areas: Some(GridTemplateAreas {
+ areas: vec![GridTemplateArea {
+ name: DefaultCheapStr::from("area"),
+ row_start: 1,
+ row_end: 2,
+ column_start: 2,
+ column_end: 4,
+ }],
+ row_count: 1,
+ column_count: 4,
+ }),
+ ..Style::DEFAULT
+ };
+ let mut resolver = NamedLineResolver::new(&style, 0, 0);
+ resolver.set_explicit_column_count(4);
+ resolver.set_explicit_row_count(1);
+ resolver
+ }
+
+ fn named_line(name: &str, index: i16) -> GridPlacement<DefaultCheapStr> {
+ GridPlacement::NamedLine(DefaultCheapStr::from(name), index)
+ }
+
+ fn resolved_end_line(
+ resolver: &NamedLineResolver<DefaultCheapStr>,
+ placement: GridPlacement<DefaultCheapStr>,
+ ) -> i16 {
+ let resolved = resolver.resolve_column_names(&Line { start: GridPlacement::Auto, end: placement });
+ match resolved.end {
+ GenericGridPlacement::Line(line) => line.as_i16(),
+ _ => panic!("expected a resolved line"),
+ }
+ }
+
+ #[test]
+ fn bare_ident_resolves_to_area_edge() {
+ let resolver = area_resolver([&[], &[], &[], &[], &[]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
+ assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
+
+ let rows = resolver.resolve_row_names(&Line { start: named_line("area", 0), end: named_line("area", 0) });
+ assert_eq!(rows.start, NonNamedGridPlacement::Line(GridLine::from(1)));
+ assert_eq!(rows.end, NonNamedGridPlacement::Line(GridLine::from(2)));
+ }
+
+ #[test]
+ fn bare_ident_resolves_to_edge_of_implicitly_named_area() {
+ let resolver = area_resolver([&[], &["foo-start"], &["foo-start"], &["foo-end"], &["foo-end"]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("foo", 0)), 2);
+ assert_eq!(resolved_end_line(&resolver, named_line("foo", 0)), 4);
+ }
+
+ #[test]
+ fn area_edges_are_lines_named_with_start_and_end_suffixes() {
+ let resolver = area_resolver([&[], &[], &[], &[], &[]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 0)), 2);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 1)), 4);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", -1)), 4);
+ // There is only one such line, so the second is the first implicit line after the grid
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 6);
+ }
+
+ #[test]
+ fn area_edges_are_merged_with_explicitly_named_lines() {
+ // The area's start edge is line 2 and its end edge is line 4
+ let resolver = area_resolver([&["area-start"], &[], &["area-start"], &["area-end"], &["area-end"]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 1);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 2);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 3)), 3);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", -1)), 3);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 4)), 6);
+ // The area's end edge has the same line number as an explicitly named line
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 1)), 4);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 5);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 3)), 6);
+ // A bare ident matches the first line of the edge
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 1);
+ assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
+
+ let span = resolver.resolve_column_names(&Line {
+ start: GridPlacement::Line(GridLine::from(1)),
+ end: GridPlacement::NamedSpan(DefaultCheapStr::from("area-start"), 2),
+ });
+ assert_eq!(span.end, NonNamedGridPlacement::Line(GridLine::from(3)));
+ }
+
+ #[test]
+ fn area_edges_are_only_matched_by_bare_idents() {
+ let resolver = area_resolver([&[], &[], &[], &[], &[]]);
+ // There are no lines named "area", so these resolve to implicit lines after the grid
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 1)), 6);
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 2)), 7);
+
+ let span = resolver.resolve_column_names(&Line {
+ start: GridPlacement::Line(GridLine::from(1)),
+ end: GridPlacement::NamedSpan(DefaultCheapStr::from("area"), 0),
+ });
+ assert_eq!(span.end, NonNamedGridPlacement::Line(GridLine::from(6)));
+ }
+
+ #[test]
+ fn area_edge_is_the_first_line_with_the_edge_name() {
+ // Explicit lines named after the area's edges which come after the area's generated lines (lines 2 and
+ // 4) don't replace them
+ let resolver = area_resolver([&[], &[], &["area-start"], &[], &["area-end"]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
+ assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 3);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 5);
+
+ // An explicit line with the same number as the generated line is the same line
+ let resolver = area_resolver([&[], &["area-start"], &[], &["area-end"], &[]]);
+ assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
+ assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 6);
+ assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 6);
+ }
+}
diff --git a/vendor/taffy/src/compute/grid/util/mod.rs b/vendor/taffy/src/compute/grid/util/mod.rs
new file mode 100644
index 00000000..ea6a8ed2
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/util/mod.rs
@@ -0,0 +1,6 @@
+//! Utility functions used within the grid module
+
+#[cfg(test)]
+pub(super) mod test_helpers;
+#[cfg(test)]
+pub(super) use test_helpers::{CreateChildTestNode, CreateExpectedPlacement, CreateParentTestNode};
diff --git a/vendor/taffy/src/compute/grid/util/test_helpers.rs b/vendor/taffy/src/compute/grid/util/test_helpers.rs
new file mode 100644
index 00000000..d1ad9479
--- /dev/null
+++ b/vendor/taffy/src/compute/grid/util/test_helpers.rs
@@ -0,0 +1,78 @@
+//! Helpers for use in unit tests within the grid module
+use super::super::types::{GridItem, NamedLineResolver};
+use super::super::{ItemPlacement, OriginZeroLine};
+use crate::geometry::InBothAbsAxis;
+use crate::prelude::*;
+use crate::style::{Dimension, GridPlacement, Style};
+use crate::util::sys::Vec;
+
+/// Create a `GridItem` (with start alignment) for each `(index, style)` pair, as `compute_grid_layout` does
+/// for the in-flow children of a grid container
+pub(crate) fn grid_items<'a>(children: impl Iterator<Item = (usize, &'a Style)>) -> Vec<GridItem> {
+ children
+ .map(|(index, style)| {
+ GridItem::new_with_style_and_order(
+ NodeId::from(index),
+ style,
+ AlignSelf::START,
+ AlignSelf::START,
+ index as u16,
+ )
+ })
+ .collect()
+}
+
+/// Resolve the named lines in the `grid-row`/`grid-column` styles of the given child styles (and convert them to
+/// origin-zero coordinates), as `compute_grid_layout` does before estimating the grid size and placing items
+pub(crate) fn resolve_named_lines<'a>(
+ child_styles: impl Iterator<Item = &'a Style>,
+ name_resolver: &NamedLineResolver<String>,
+ explicit_col_count: u16,
+ explicit_row_count: u16,
+) -> Vec<ItemPlacement> {
+ child_styles
+ .map(|style| InBothAbsAxis {
+ horizontal: name_resolver.resolve_column_names(&style.grid_column).into_origin_zero(explicit_col_count),
+ vertical: name_resolver.resolve_row_names(&style.grid_row).into_origin_zero(explicit_row_count),
+ })
+ .collect()
+}
+
+pub(crate) trait CreateParentTestNode {
+ fn into_grid(self) -> Style;
+}
+impl CreateParentTestNode for (f32, f32, i32, i32) {
+ fn into_grid(self) -> Style {
+ Style {
+ display: Display::Grid,
+ size: Size { width: Dimension::from_length(self.0), height: Dimension::from_length(self.1) },
+ grid_template_columns: vec![fr(1f32); self.2 as usize],
+ grid_template_rows: vec![fr(1f32); self.3 as usize],
+ ..Default::default()
+ }
+ }
+}
+pub(crate) trait CreateChildTestNode {
+ fn into_grid_child(self) -> Style;
+}
+impl CreateChildTestNode
+ for (GridPlacement<String>, GridPlacement<String>, GridPlacement<String>, GridPlacement<String>)
+{
+ fn into_grid_child(self) -> Style<String> {
+ Style {
+ display: Display::Grid,
+ grid_column: Line { start: self.0, end: self.1 },
+ grid_row: Line { start: self.2, end: self.3 },
+ ..Default::default()
+ }
+ }
+}
+
+pub(crate) trait CreateExpectedPlacement {
+ fn into_oz(self) -> (OriginZeroLine, OriginZeroLine, OriginZeroLine, OriginZeroLine);
+}
+impl CreateExpectedPlacement for (i16, i16, i16, i16) {
+ fn into_oz(self) -> (OriginZeroLine, OriginZeroLine, OriginZeroLine, OriginZeroLine) {
+ (OriginZeroLine(self.0), OriginZeroLine(self.1), OriginZeroLine(self.2), OriginZeroLine(self.3))
+ }
+}
diff --git a/vendor/taffy/src/compute/leaf.rs b/vendor/taffy/src/compute/leaf.rs
new file mode 100644
index 00000000..415b41d0
--- /dev/null
+++ b/vendor/taffy/src/compute/leaf.rs
@@ -0,0 +1,188 @@
+//! Computes size using styles and measure functions
+
+#[cfg(feature = "content_size")]
+use crate::geometry::Rect;
+use crate::geometry::Size;
+use crate::style::{AvailableSpace, Overflow};
+use crate::tree::{Baselines, CollapsibleMarginSet, RunMode};
+use crate::tree::{LayoutInput, LayoutOutput, SizingMode};
+use crate::util::debug::debug_log;
+use crate::util::sys::f32_max;
+use crate::util::MaybeMath;
+use crate::util::{MaybeResolve, ResolveOrZero};
+use crate::{BoxSizing, CoreStyle};
+use core::unreachable;
+
+/// Compute the size of a leaf node (node with no children)
+///
+/// A definite `inputs.available_space` is treated as the space available to the node's border box:
+/// the caller is expected to have already subtracted the node's margins from it.
+pub fn compute_leaf_layout<MeasureFunction>(
+ inputs: LayoutInput,
+ style: &impl CoreStyle,
+ resolve_calc_value: impl Fn(*const (), f32) -> f32,
+ measure_function: MeasureFunction,
+) -> LayoutOutput
+where
+ MeasureFunction: FnOnce(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>,
+{
+ let LayoutInput { known_dimensions, parent_size, available_space, sizing_mode, run_mode, .. } = inputs;
+
+ // Note: both horizontal and vertical percentage padding/borders are resolved against the container's inline size (i.e. width).
+ // This is not a bug, but is how CSS is specified (see: https://developer.mozilla.org/en-US/docs/Web/CSS/padding#values)
+ let padding = style.padding().resolve_or_zero(parent_size.width, &resolve_calc_value);
+ let border = style.border().resolve_or_zero(parent_size.width, &resolve_calc_value);
+ let padding_border = padding + border;
+ let pb_sum = padding_border.sum_axes();
+ let box_sizing_adjustment = if style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
+
+ // Resolve node's preferred/min/max sizes (width/heights) against the available space (percentages resolve to pixel values)
+ // For ContentSize mode, we pretend that the node has no size styles as these should be ignored.
+ let (node_size, node_min_size, node_max_size, aspect_ratio) = match sizing_mode {
+ SizingMode::ContentSize => {
+ let node_size = known_dimensions;
+ let node_min_size = Size::NONE;
+ let node_max_size = Size::NONE;
+ (node_size, node_min_size, node_max_size, None)
+ }
+ SizingMode::InherentSize => {
+ let aspect_ratio = style.aspect_ratio();
+ let style_size = style
+ .size()
+ .maybe_resolve(parent_size, &resolve_calc_value)
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let style_min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, &resolve_calc_value)
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let style_max_size =
+ style.max_size().maybe_resolve(parent_size, &resolve_calc_value).maybe_add(box_sizing_adjustment);
+
+ let node_size = known_dimensions.or(style_size);
+ (node_size, style_min_size, style_max_size, aspect_ratio)
+ }
+ };
+
+ // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
+ // However, the axis are switched (transposed) because a node that scrolls vertically needs
+ // *horizontal* space to be reserved for a scrollbar
+ let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
+ Overflow::Scroll => style.scrollbar_width(),
+ _ => 0.0,
+ });
+ // TODO: make side configurable based on the `direction` property
+ let mut content_box_inset = padding_border;
+ content_box_inset.right += scrollbar_gutter.x;
+ content_box_inset.bottom += scrollbar_gutter.y;
+
+ let has_styles_preventing_being_collapsed_through = !style.is_block()
+ || style.overflow().x.is_scroll_container()
+ || style.overflow().y.is_scroll_container()
+ || style.position().is_out_of_flow()
+ || style.contain().establishes_independent_formatting_context()
+ || padding.top > 0.0
+ || padding.bottom > 0.0
+ || border.top > 0.0
+ || border.bottom > 0.0
+ || matches!(node_size.height, Some(h) if h > 0.0)
+ || matches!(node_min_size.height, Some(h) if h > 0.0);
+
+ debug_log!("LEAF");
+ debug_log!("node_size", dbg:node_size);
+ debug_log!("min_size ", dbg:node_min_size);
+ debug_log!("max_size ", dbg:node_max_size);
+
+ // Return early if both width and height are known
+ if run_mode == RunMode::ComputeSize && has_styles_preventing_being_collapsed_through {
+ if let Size { width: Some(width), height: Some(height) } = node_size {
+ let size = Size { width, height }
+ .maybe_clamp(node_min_size, node_max_size)
+ .maybe_max(padding_border.sum_axes().map(Some));
+ return LayoutOutput {
+ size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: Rect::ZERO,
+ baselines: Baselines::NONE,
+ top_margin: CollapsibleMarginSet::ZERO,
+ bottom_margin: CollapsibleMarginSet::ZERO,
+ margins_can_collapse_through: false,
+ oof_candidates: crate::tree::OofCandidates::NONE,
+ oof_positioning_area: None,
+ };
+ };
+ }
+
+ // Compute available space
+ let available_space = Size {
+ width: known_dimensions
+ .width
+ .map(AvailableSpace::from)
+ .unwrap_or(available_space.width)
+ .maybe_set(known_dimensions.width)
+ .maybe_set(node_size.width)
+ .map_definite_value(|size| {
+ size.maybe_clamp(node_min_size.width, node_max_size.width) - content_box_inset.horizontal_axis_sum()
+ }),
+ height: known_dimensions
+ .height
+ .map(AvailableSpace::from)
+ .unwrap_or(available_space.height)
+ .maybe_set(known_dimensions.height)
+ .maybe_set(node_size.height)
+ .map_definite_value(|size| {
+ size.maybe_clamp(node_min_size.height, node_max_size.height) - content_box_inset.vertical_axis_sum()
+ }),
+ };
+
+ // Measure node
+ let measured_size = measure_function(
+ match run_mode {
+ RunMode::ComputeSize => known_dimensions,
+ RunMode::PerformLayout => Size::NONE,
+ RunMode::PerformHiddenLayout => unreachable!(),
+ },
+ available_space,
+ );
+ let clamped_size = known_dimensions
+ .or(node_size)
+ .unwrap_or(measured_size + content_box_inset.sum_axes())
+ .maybe_clamp(node_min_size, node_max_size);
+ let size = Size {
+ width: clamped_size.width,
+ height: f32_max(clamped_size.height, aspect_ratio.map(|ratio| clamped_size.width / ratio).unwrap_or(0.0)),
+ };
+ let size = size.maybe_max(padding_border.sum_axes().map(Some));
+
+ // A scroll container's own padding at the end of the content is part of its scrollable
+ // overflow region, so it is included in the overflow rect. Boxes that are not scroll
+ // containers do not extend their overflow region by their own padding.
+ #[cfg(feature = "content_size")]
+ let scrollable_overflow_rect = {
+ let is_scroll_container = style.overflow().x.is_scroll_container() || style.overflow().y.is_scroll_container();
+ let is_rtl = style.direction().is_rtl();
+ let start_padding = if is_rtl { padding.right } else { padding.left };
+ let end_padding = if is_rtl { padding.left } else { padding.right };
+ Rect {
+ left: 0.0,
+ right: start_padding + measured_size.width + if is_scroll_container { end_padding } else { 0.0 },
+ top: 0.0,
+ bottom: padding.top + measured_size.height + if is_scroll_container { padding.bottom } else { 0.0 },
+ }
+ };
+
+ LayoutOutput {
+ size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect,
+ baselines: Baselines::NONE,
+ top_margin: CollapsibleMarginSet::ZERO,
+ bottom_margin: CollapsibleMarginSet::ZERO,
+ margins_can_collapse_through: !has_styles_preventing_being_collapsed_through
+ && size.height == 0.0
+ && measured_size.height == 0.0,
+ oof_candidates: crate::tree::OofCandidates::NONE,
+ oof_positioning_area: None,
+ }
+}
diff --git a/vendor/taffy/src/compute/mod.rs b/vendor/taffy/src/compute/mod.rs
new file mode 100644
index 00000000..1e4af954
--- /dev/null
+++ b/vendor/taffy/src/compute/mod.rs
@@ -0,0 +1,516 @@
+//! Low-level access to the layout algorithms themselves. For a higher-level API, see the [`TaffyTree`](crate::TaffyTree) struct.
+//!
+//! ### Layout functions
+//!
+//! The layout functions all take an [`&mut impl LayoutPartialTree`](crate::LayoutPartialTree) parameter, which represents a single container node and it's direct children.
+//!
+//! | Function | Purpose |
+//! | --- | --- |
+//! | [`compute_flexbox_layout`] | Layout a Flexbox container and it's direct children |
+//! | [`compute_grid_layout`] | Layout a CSS Grid container and it's direct children |
+//! | [`compute_block_layout`] | Layout a Block container and it's direct children |
+//! | [`compute_leaf_layout`] | Applies common properties like padding/border/aspect-ratio to a node before deferring to a passed closure to determine it's size. Can be applied to nodes like text or image nodes. |
+//! | [`compute_root_layout`] | Layout the root node of a tree (regardless of it's layout mode). This function is typically called once to begin a layout run. | |
+//! | [`compute_hidden_layout`] | Mark a node as hidden during layout (like `Display::None`) |
+//! | [`compute_cached_layout`] | Attempts to find a cached layout for the specified node and layout inputs. Uses the provided closure to compute the layout (and then stores the result in the cache) if no cached layout is found. |
+//!
+//! ### Other functions
+//!
+//! | Function | Requires | Purpose |
+//! | --- | --- | --- |
+//! | [`round_layout`] | [`RoundTree`] | Round a tree of float-valued layouts to integer pixels |
+//! | [`print_tree`](crate::print_tree) | [`PrintTree`](crate::PrintTree) | Print a debug representation of a node tree and it's computed layout |
+//!
+pub(crate) mod common;
+pub(crate) mod leaf;
+pub(crate) mod oof;
+
+#[cfg(feature = "block_layout")]
+pub(crate) mod block;
+
+#[cfg(feature = "float_layout")]
+pub(crate) mod float;
+
+#[cfg(feature = "flexbox")]
+pub(crate) mod flexbox;
+
+#[cfg(feature = "grid")]
+pub(crate) mod grid;
+
+pub use leaf::compute_leaf_layout;
+pub use oof::{compute_oof_layout, compute_oof_layout_for_area, resolve_static_offset, OofLayoutResult};
+
+#[cfg(feature = "block_layout")]
+pub use self::block::{compute_block_align_content_offset, compute_block_layout, BlockContext, BlockFormattingContext};
+
+#[cfg(feature = "flexbox")]
+pub use self::flexbox::compute_flexbox_layout;
+
+#[cfg(feature = "grid")]
+pub use self::grid::compute_grid_layout;
+
+#[cfg(feature = "float_layout")]
+pub use self::float::{BfcSlot, ContentSlot, FloatContext, FloatIntrinsicWidthCalculator};
+
+use crate::geometry::{Line, Point, Size};
+use crate::style::{AvailableSpace, ContainingBlockClaims, CoreStyle, Overflow, Position};
+use crate::tree::{
+ AxisStaticAlign, AxisStaticEdge, AxisStaticPosition, Layout, LayoutInput, LayoutOutput, LayoutPartialTree,
+ LayoutPartialTreeExt, NodeId, OofCandidate, OofCandidates, RequestedAxis, RoundTree, RunMode, SizingMode,
+};
+use crate::util::debug::{debug_log, debug_log_node, debug_pop_node, debug_push_node};
+use crate::util::sys::{round, Vec};
+use crate::util::ResolveOrZero;
+use crate::{CacheTree, MaybeMath, MaybeResolve};
+
+/// Compute layout for the root node in the tree
+///
+/// The root's containing block is the initial containing block (ICB), which has the dimensions of the
+/// viewport (`available_space`) and is anchored at the canvas origin. The root's `position` and `inset`
+/// styles are resolved against it:
+///
+/// - A `position: absolute`/`fixed` root is laid out by the out-of-flow positioning routine used for
+/// every other out-of-flow box (insets, shrink-to-fit sizing, auto margins, ...), with its static
+/// position at the ICB origin. This requires a definite `available_space` in both axes: otherwise there
+/// is no ICB to resolve against and the root is laid out as if it were in flow.
+/// - A `position: relative` root is laid out in flow and then offset by its insets.
+pub fn compute_root_layout(
+ tree: &mut (impl crate::tree::LayoutContainingBlock + CacheTree),
+ root: NodeId,
+ available_space: Size<AvailableSpace>,
+) {
+ let style = tree.get_core_container_style(root);
+ let position = style.position();
+ let direction = style.direction();
+ drop(style);
+
+ let icb_size = available_space.into_options();
+ let oof_root_area = match (position.is_out_of_flow(), icb_size.width, icb_size.height) {
+ (true, Some(width), Some(height)) => Some(Size { width, height }),
+ _ => None,
+ };
+
+ // When the root's layout is served from the cache its layout algorithm does not run, so the
+ // hoisted children it recorded on a previous run (including those added by the root
+ // positioning pass below) are still in place and must not be re-added.
+ let mut root_is_cached = false;
+
+ let (layout, candidates) = if let Some(area_size) = oof_root_area {
+ // The static position of the root places its margin box at the origin of the ICB
+ let (start, end) = if direction.is_rtl() { (area_size.width, area_size.width) } else { (0.0, 0.0) };
+ let candidate = OofCandidate {
+ node: root,
+ order: 0,
+ position,
+ static_position: Point {
+ x: AxisStaticPosition {
+ area: Line { start, end },
+ align: AxisStaticAlign::from_keyword(if direction.is_rtl() {
+ AxisStaticEdge::End
+ } else {
+ AxisStaticEdge::Start
+ }),
+ },
+ y: AxisStaticPosition::from_edge(0.0, AxisStaticEdge::Start),
+ },
+ };
+ let oof::OofBoxLayout { layout, surfaced, .. } = oof::layout_oof_box(
+ tree,
+ candidate,
+ area_size,
+ Point::ZERO,
+ direction,
+ // The initial containing block is not a scroll container
+ Point { x: Overflow::Visible, y: Overflow::Visible },
+ #[cfg(feature = "grid")]
+ None,
+ |tree, inputs| root_is_cached = tree.cache_get(root, inputs).is_some(),
+ );
+ (layout, surfaced)
+ } else {
+ compute_in_flow_root_layout(tree, root, available_space, &mut root_is_cached)
+ };
+
+ // Final positioning pass for out-of-flow boxes with no nearer containing block: the initial
+ // containing block is the containing block for `position: fixed` boxes and for
+ // `position: absolute` boxes with no positioned ancestor.
+ if !candidates.is_empty() {
+ let overflow = tree.get_core_container_style(root).overflow();
+
+ // The initial containing block has the dimensions of the viewport (the available space) and is
+ // anchored at the canvas origin. In an axis where the available space is indefinite, fall back
+ // to the root's padding box.
+ let area_inset = layout.border
+ + crate::geometry::Rect {
+ left: 0.0,
+ right: layout.scrollbar_size.width,
+ top: 0.0,
+ bottom: layout.scrollbar_size.height,
+ };
+ let root_padding_box_size =
+ layout.size - Size { width: area_inset.horizontal_axis_sum(), height: area_inset.vertical_axis_sum() };
+ let (area_width, area_x) = match icb_size.width {
+ Some(width) => ((width - layout.scrollbar_size.width).max(0.0), -layout.location.x),
+ None => (root_padding_box_size.width, area_inset.left),
+ };
+ let (area_height, area_y) = match icb_size.height {
+ Some(height) => ((height - layout.scrollbar_size.height).max(0.0), -layout.location.y),
+ None => (root_padding_box_size.height, area_inset.top),
+ };
+ let area_size = Size { width: area_width, height: area_height };
+ let area_offset = Point { x: area_x, y: area_y };
+
+ let mut hoisted: Vec<NodeId> = Vec::new();
+ let mut unclaimed = OofCandidates::new();
+ oof::perform_oof_layout(
+ tree,
+ root,
+ candidates.as_slice(),
+ area_size,
+ area_offset,
+ direction,
+ // The root is the initial containing block and claims all remaining candidates
+ ContainingBlockClaims::ALL,
+ overflow,
+ &mut hoisted,
+ &mut unclaimed,
+ );
+ debug_assert!(unclaimed.is_empty(), "the root positioning pass must claim all remaining candidates");
+ if !root_is_cached {
+ tree.add_hoisted_children(root, &hoisted);
+ }
+ }
+}
+
+/// Lay out an in-flow (or `position: relative`) root node against the available space, store its layout
+/// and return it along with the out-of-flow candidates bubbled up from its subtree.
+#[inline(always)]
+fn compute_in_flow_root_layout(
+ tree: &mut (impl crate::tree::LayoutContainingBlock + CacheTree),
+ root: NodeId,
+ available_space: Size<AvailableSpace>,
+ root_is_cached: &mut bool,
+) -> (Layout, OofCandidates) {
+ let mut known_dimensions = Size::NONE;
+
+ // The available space passed to the root excludes the root's margins
+ let root_available_space = {
+ let style = tree.get_core_container_style(root);
+ let margin =
+ style.margin().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
+ available_space.maybe_sub(margin.sum_axes()).maybe_max(Size::ZERO)
+ };
+
+ #[cfg(feature = "block_layout")]
+ {
+ use crate::BoxSizing;
+
+ let parent_size = available_space.into_options();
+ let style = tree.get_core_container_style(root);
+
+ if style.is_block() {
+ // Pull these out earlier to avoid borrowing issues
+ let aspect_ratio = style.aspect_ratio();
+ let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
+ let padding_border_size = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
+
+ let min_size = style
+ .min_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let max_size = style
+ .max_size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let clamped_style_size = style
+ .size()
+ .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .maybe_clamp(min_size, max_size);
+
+ // If both min and max in a given axis are set and max <= min then this determines the size in that axis
+ let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
+ (Some(min), Some(max)) if max <= min => Some(min),
+ _ => None,
+ });
+
+ // Block nodes automatically stretch fit their width to fit available space if available space is definite
+ let available_space_based_size = Size { width: root_available_space.width.into_option(), height: None };
+
+ let styled_based_known_dimensions = known_dimensions
+ .or(min_max_definite_size)
+ .or(clamped_style_size)
+ .or(available_space_based_size)
+ .maybe_max(padding_border_size);
+
+ known_dimensions = styled_based_known_dimensions;
+ }
+ }
+
+ let inputs = LayoutInput {
+ known_dimensions,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size: available_space.into_options(),
+ available_space: root_available_space,
+ sizing_mode: SizingMode::InherentSize,
+ axis: RequestedAxis::Both,
+ run_mode: RunMode::PerformLayout,
+ vertical_margins_are_collapsible: Line::FALSE,
+ };
+ *root_is_cached = tree.cache_get(root, &inputs).is_some();
+
+ // Recursively compute node layout
+ let mut output = tree.compute_child_layout(root, inputs);
+ let style = tree.get_core_container_style(root);
+ let padding =
+ style.padding().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
+ let border =
+ style.border().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
+ let margin =
+ style.margin().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
+ let scrollbar_size = Size {
+ width: if style.overflow().y == Overflow::Scroll { style.scrollbar_width() } else { 0.0 },
+ height: if style.overflow().x == Overflow::Scroll { style.scrollbar_width() } else { 0.0 },
+ };
+ let is_rtl = style.direction().is_rtl();
+
+ // The root's margin box is placed at the origin of the initial containing block
+ let mut location = Point {
+ x: match (is_rtl, available_space.width.into_option()) {
+ (true, Some(available_width)) => available_width - output.size.width - margin.right,
+ _ => margin.left,
+ },
+ y: margin.top,
+ };
+
+ // A relatively positioned root is offset by its insets (resolved against the initial containing block)
+ if style.position() == Position::Relative {
+ let icb_size = available_space.into_options();
+ let inset = style.inset();
+ let left = inset.left.maybe_resolve(icb_size.width, |val, basis| tree.calc(val, basis));
+ let right = inset.right.maybe_resolve(icb_size.width, |val, basis| tree.calc(val, basis));
+ let top = inset.top.maybe_resolve(icb_size.height, |val, basis| tree.calc(val, basis));
+ let bottom = inset.bottom.maybe_resolve(icb_size.height, |val, basis| tree.calc(val, basis));
+ location.x += if is_rtl {
+ right.map(|right| -right).or(left).unwrap_or(0.0)
+ } else {
+ left.or(right.map(|right| -right)).unwrap_or(0.0)
+ };
+ location.y += top.or(bottom.map(|bottom| -bottom)).unwrap_or(0.0);
+ }
+ drop(style);
+
+ let layout = Layout {
+ order: 0,
+ location,
+ size: output.size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: output.scrollable_overflow_rect,
+ scrollbar_size,
+ padding,
+ border,
+ // TODO: support auto margins for root node?
+ margin,
+ };
+ tree.set_unrounded_layout(root, &layout);
+
+ (layout, output.oof_candidates.take())
+}
+
+/// Attempts to find a cached layout for the specified node and layout inputs.
+///
+/// Uses the provided closure to compute the layout (and then stores the result in the cache) if no cached layout is found.
+#[inline(always)]
+pub fn compute_cached_layout<Tree: CacheTree + ?Sized, ComputeFunction>(
+ tree: &mut Tree,
+ node: NodeId,
+ inputs: LayoutInput,
+ compute_uncached: ComputeFunction,
+) -> LayoutOutput
+where
+ ComputeFunction: FnOnce(&mut Tree, NodeId, LayoutInput) -> LayoutOutput,
+{
+ debug_push_node!(node);
+
+ // First we check if we have a cached result for the given input
+ let cache_entry = tree.cache_get(node, &inputs);
+ if let Some(cached_size_and_baselines) = cache_entry {
+ debug_log_node!(inputs);
+ debug_log!("RESULT (CACHED)", dbg:cached_size_and_baselines.size);
+ debug_pop_node!();
+ return cached_size_and_baselines;
+ }
+
+ debug_log_node!(inputs);
+
+ let computed_size_and_baselines = compute_uncached(tree, node, inputs);
+
+ // Cache result
+ tree.cache_store(node, &inputs, computed_size_and_baselines.clone());
+
+ debug_log!("RESULT", dbg:computed_size_and_baselines.size);
+ debug_pop_node!();
+
+ computed_size_and_baselines
+}
+
+/// Rounds the calculated layout to exact pixel values
+///
+/// In order to ensure that no gaps in the layout are introduced we:
+/// - Always round based on the cumulative x/y coordinates (relative to the viewport) rather than
+/// parent-relative coordinates
+/// - Compute width/height by first rounding the top/bottom/left/right and then computing the difference
+/// rather than rounding the width/height directly
+///
+/// See <https://github.com/facebook/yoga/commit/aa5b296ac78f7a22e1aeaf4891243c6bb76488e2> for more context
+///
+/// In order to prevent innacuracies caused by rounding already-rounded values, we read from `unrounded_layout`
+/// and write to `final_layout`.
+pub fn round_layout(tree: &mut impl RoundTree, node_id: NodeId) {
+ return round_layout_inner(tree, node_id, 0.0, 0.0);
+
+ /// Recursive function to apply rounding to all descendents
+ fn round_layout_inner(tree: &mut impl RoundTree, node_id: NodeId, cumulative_x: f32, cumulative_y: f32) {
+ let unrounded_layout = tree.get_unrounded_layout(node_id);
+ let mut layout = unrounded_layout;
+
+ let parent_x = cumulative_x;
+ let parent_y = cumulative_y;
+ let cumulative_x = cumulative_x + unrounded_layout.location.x;
+ let cumulative_y = cumulative_y + unrounded_layout.location.y;
+
+ layout.location.x = round(cumulative_x) - round(parent_x);
+ layout.location.y = round(cumulative_y) - round(parent_y);
+ layout.size.width = round(cumulative_x + unrounded_layout.size.width) - round(cumulative_x);
+ layout.size.height = round(cumulative_y + unrounded_layout.size.height) - round(cumulative_y);
+ layout.scrollbar_size.width = round(unrounded_layout.scrollbar_size.width);
+ layout.scrollbar_size.height = round(unrounded_layout.scrollbar_size.height);
+ layout.border.left = round(cumulative_x + unrounded_layout.border.left) - round(cumulative_x);
+ layout.border.right = round(cumulative_x + unrounded_layout.size.width)
+ - round(cumulative_x + unrounded_layout.size.width - unrounded_layout.border.right);
+ layout.border.top = round(cumulative_y + unrounded_layout.border.top) - round(cumulative_y);
+ layout.border.bottom = round(cumulative_y + unrounded_layout.size.height)
+ - round(cumulative_y + unrounded_layout.size.height - unrounded_layout.border.bottom);
+ layout.padding.left = round(cumulative_x + unrounded_layout.padding.left) - round(cumulative_x);
+ layout.padding.right = round(cumulative_x + unrounded_layout.size.width)
+ - round(cumulative_x + unrounded_layout.size.width - unrounded_layout.padding.right);
+ layout.padding.top = round(cumulative_y + unrounded_layout.padding.top) - round(cumulative_y);
+ layout.padding.bottom = round(cumulative_y + unrounded_layout.size.height)
+ - round(cumulative_y + unrounded_layout.size.height - unrounded_layout.padding.bottom);
+
+ #[cfg(feature = "content_size")]
+ round_scrollable_overflow_rect(
+ &mut layout,
+ unrounded_layout.scrollable_overflow_rect,
+ cumulative_x,
+ cumulative_y,
+ );
+
+ tree.set_final_layout(node_id, &layout);
+
+ // Recurse into in-flow children. Out-of-flow (absolute/fixed) children are skipped here:
+ // they are instead visited via their containing block's hoisted child list below, which
+ // ensures each node is visited exactly once and that its cumulative offset is accumulated
+ // relative to its containing block (which its `location` is relative to).
+ let child_count = tree.child_count(node_id);
+ for index in 0..child_count {
+ let child = tree.get_child_id(node_id, index);
+ if !tree.is_out_of_flow(child) {
+ round_layout_inner(tree, child, cumulative_x, cumulative_y);
+ }
+ }
+
+ // Recurse into out-of-flow boxes for which this node is the containing block
+ let hoisted_count = tree.hoisted_child_count(node_id);
+ for index in 0..hoisted_count {
+ let child = tree.get_hoisted_child_id(node_id, index);
+ round_layout_inner(tree, child, cumulative_x, cumulative_y);
+ }
+ }
+
+ #[cfg(feature = "content_size")]
+ #[inline(always)]
+ /// Round the scrollable overflow rect.
+ /// This is split into a separate function to make it easier to feature flag.
+ fn round_scrollable_overflow_rect(
+ layout: &mut Layout,
+ unrounded_rect: crate::geometry::Rect<f32>,
+ cumulative_x: f32,
+ cumulative_y: f32,
+ ) {
+ layout.scrollable_overflow_rect.left = round(cumulative_x + unrounded_rect.left) - round(cumulative_x);
+ layout.scrollable_overflow_rect.right = round(cumulative_x + unrounded_rect.right) - round(cumulative_x);
+ layout.scrollable_overflow_rect.top = round(cumulative_y + unrounded_rect.top) - round(cumulative_y);
+ layout.scrollable_overflow_rect.bottom = round(cumulative_y + unrounded_rect.bottom) - round(cumulative_y);
+ }
+}
+
+/// Creates a layout for this node and its children, recursively.
+/// Each hidden node has zero size and is placed at the origin
+pub fn compute_hidden_layout(tree: &mut (impl LayoutPartialTree + CacheTree), node: NodeId) -> LayoutOutput {
+ // Clear cache and set zeroed-out layout for the node
+ tree.cache_clear(node);
+ tree.set_unrounded_layout(node, &Layout::with_order(0));
+
+ // Perform hidden layout on all children
+ for index in 0..tree.child_count(node) {
+ let child_id = tree.get_child_id(node, index);
+ tree.compute_child_layout(child_id, LayoutInput::HIDDEN);
+ }
+
+ LayoutOutput::HIDDEN
+}
+
+/// A module for unified re-exports of detailed layout info structs, used by low level API
+pub mod detailed_info {
+ #[cfg(feature = "grid")]
+ pub use super::grid::{
+ DetailedGridInfo, DetailedGridItemsInfo, DetailedGridTracksInfo, GridLineNames, GridLineNamesIter,
+ };
+}
+
+#[cfg(test)]
+mod tests {
+ use super::compute_hidden_layout;
+ use crate::geometry::{Point, Size};
+ use crate::style::{Display, Style};
+ use crate::TaffyTree;
+
+ #[test]
+ fn hidden_layout_should_hide_recursively() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let style: Style = Style { display: Display::Flex, size: Size::from_lengths(50.0, 50.0), ..Default::default() };
+
+ let grandchild_00 = taffy.new_leaf(style.clone()).unwrap();
+ let grandchild_01 = taffy.new_leaf(style.clone()).unwrap();
+ let child_00 = taffy.new_with_children(style.clone(), &[grandchild_00, grandchild_01]).unwrap();
+
+ let grandchild_02 = taffy.new_leaf(style.clone()).unwrap();
+ let child_01 = taffy.new_with_children(style.clone(), &[grandchild_02]).unwrap();
+
+ let root = taffy
+ .new_with_children(
+ Style { display: Display::None, size: Size::from_lengths(50.0, 50.0), ..Default::default() },
+ &[child_00, child_01],
+ )
+ .unwrap();
+
+ compute_hidden_layout(&mut taffy.as_layout_tree(), root);
+
+ // Whatever size and display-mode the nodes had previously,
+ // all layouts should resolve to ZERO due to the root's DISPLAY::NONE
+
+ for node in [root, child_00, child_01, grandchild_00, grandchild_01, grandchild_02] {
+ let layout = taffy.layout(node).unwrap();
+ assert_eq!(layout.size, Size::zero());
+ assert_eq!(layout.location, Point::zero());
+ }
+ }
+}
diff --git a/vendor/taffy/src/compute/oof.rs b/vendor/taffy/src/compute/oof.rs
new file mode 100644
index 00000000..9a76e171
--- /dev/null
+++ b/vendor/taffy/src/compute/oof.rs
@@ -0,0 +1,912 @@
+//! Shared positioning pass for out-of-flow (`position: absolute` / `position: fixed`) boxes.
+//!
+//! Layout algorithms do not lay out their out-of-flow children directly (unless they are the
+//! child's containing block). Instead they emit [`OofCandidate`] records which bubble up the tree
+//! via [`LayoutOutput::oof_candidates`](crate::LayoutOutput) until they reach the box's containing
+//! block, which lays the box out using the routine in this module.
+use crate::geometry::{Line, Point, Rect, Size};
+use crate::style::{
+ AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace, ContainingBlockClaims, CoreStyle, OofItemStyle,
+ Overflow,
+};
+#[cfg(feature = "grid")]
+use crate::tree::DetailedLayoutInfo;
+use crate::tree::{
+ AxisStaticPosition, Layout, LayoutContainingBlock, LayoutInput, LayoutOutput, LayoutPartialTreeExt, NodeId,
+ OofCandidate, OofCandidates, OofPositioningArea, RequestedAxis, RunMode, SizingMode,
+};
+use crate::util::sys::{f32_max, Vec};
+use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
+use crate::{AxisStaticEdge, BoxSizing, Direction};
+
+#[cfg(feature = "content_size")]
+use super::common::scrollable_overflow::compute_scrollable_overflow_contribution;
+use super::common::sizing_keyword::resolve_absolute_sizing_keywords;
+
+/// Resolve the final static offset of an out-of-flow box from its static position, given the
+/// box's final size and resolved margins.
+///
+/// In each axis the box's margin box is aligned within the static-position area according to the
+/// recorded alignment keyword. When the alignment is `safe` and the margin box overflows the
+/// area, the fallback keyword is used instead (the `safe` overflow-position keyword from CSS
+/// Box Alignment). The returned offset locates the box's border box and is relative to whatever
+/// the static-position areas are relative to (the containing block's border box once a candidate
+/// has bubbled to its containing block).
+pub fn resolve_static_offset(
+ static_position: Point<AxisStaticPosition>,
+ final_size: Size<f32>,
+ resolved_margin: Rect<f32>,
+) -> Point<f32> {
+ Point {
+ x: resolve_static_offset_axis(
+ static_position.x,
+ final_size.width,
+ Line { start: resolved_margin.left, end: resolved_margin.right },
+ ),
+ y: resolve_static_offset_axis(
+ static_position.y,
+ final_size.height,
+ Line { start: resolved_margin.top, end: resolved_margin.bottom },
+ ),
+ }
+}
+
+/// Single-axis version of [`resolve_static_offset`]
+fn resolve_static_offset_axis(sp: AxisStaticPosition, size: f32, margin: Line<f32>) -> f32 {
+ let margin_box_size = size + margin.start + margin.end;
+ let overflows = matches!(sp.align.safety, AlignmentSafety::Safe) && margin_box_size > sp.area.end - sp.area.start;
+ let keyword = if overflows { sp.align.fallback } else { sp.align.keyword };
+ align_in_line(sp.area, margin_box_size, keyword) + margin.start
+}
+
+/// Position a box of `size` within `container` so that it is aligned to the given physical edge
+fn align_in_line(container: Line<f32>, size: f32, edge: AxisStaticEdge) -> f32 {
+ match edge {
+ AxisStaticEdge::Start => container.start,
+ AxisStaticEdge::End => container.end - size,
+ AxisStaticEdge::Center => (container.start + container.end - size) / 2.0,
+ }
+}
+
+/// The self-alignment of an out-of-flow box in one axis, resolved relative to the writing mode
+/// of its containing block (`Start` is the logical start edge of the containing block).
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+enum OofAlignment {
+ /// `normal` (or `auto`): stretch-fit sizing for non-replaced, non-table boxes; start alignment
+ Normal,
+ /// `stretch`: stretch-fit sizing; start alignment
+ Stretch,
+ /// Aligned to the logical start edge
+ Start,
+ /// Centered
+ Center,
+ /// Aligned to the logical end edge
+ End,
+}
+
+impl OofAlignment {
+ /// Convert an `align-self`/`justify-self` value for an out-of-flow box into a logical
+ /// alignment relative to the containing block's writing mode.
+ ///
+ /// `alignment` must already have had `self-start`/`self-end` resolved against the containing
+ /// block's direction (see [`AlignSelf::resolve_self_relative`]).
+ fn from_resolved(alignment: AlignSelf) -> Self {
+ debug_assert!(
+ !matches!(alignment.keyword, AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd),
+ "self-start/self-end must be resolved before computing out-of-flow alignment"
+ );
+ match alignment.keyword {
+ AlignItemsKeyword::Normal => Self::Normal,
+ AlignItemsKeyword::Stretch => Self::Stretch,
+ AlignItemsKeyword::Center => Self::Center,
+ AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd | AlignItemsKeyword::SelfEnd => Self::End,
+ // The fallback alignment of `baseline` is `start`
+ AlignItemsKeyword::Start
+ | AlignItemsKeyword::FlexStart
+ | AlignItemsKeyword::SelfStart
+ | AlignItemsKeyword::Baseline => Self::Start,
+ }
+ }
+
+ /// The physical edge of the containing block the box's margin box is aligned to once its
+ /// size has been determined. `Normal` and `Stretch` behave as `Start`.
+ fn physical_edge(self, reversed: bool) -> AxisStaticEdge {
+ match (self, reversed) {
+ (Self::Center, _) => AxisStaticEdge::Center,
+ (Self::End, false) | (Self::Normal | Self::Stretch | Self::Start, true) => AxisStaticEdge::End,
+ (Self::End, true) | (Self::Normal | Self::Stretch | Self::Start, false) => AxisStaticEdge::Start,
+ }
+ }
+}
+
+/// The inputs to the absolute positioning layout model
+/// (<https://www.w3.org/TR/css-position-3/#abspos-layout>) in a single axis. All coordinates
+/// are physical (left-to-right / top-to-bottom) and relative to the start of the containing
+/// block's inset-resolution area.
+#[derive(Copy, Clone, Debug)]
+struct OofAxis {
+ /// The size of the containing block in this axis
+ cb_size: f32,
+ /// The box's resolved inset properties (`None` = `auto`)
+ inset: Line<Option<f32>>,
+ /// The box's resolved margins (`None` = `auto`)
+ margin: Line<Option<f32>>,
+ /// The box's static position (relative to the containing block's inset-resolution area)
+ static_position: AxisStaticPosition,
+ /// The box's self-alignment in this axis
+ alignment: OofAlignment,
+ /// The overflow-position modifier of the box's self-alignment in this axis
+ safety: AlignmentSafety,
+ /// Whether this is the inline axis of the containing block
+ is_inline: bool,
+ /// Whether the logical start edge of the containing block is the physical end edge of this
+ /// axis (the inline axis of an RTL containing block)
+ reversed: bool,
+ /// Whether the containing block is a scroll container which scrolls in this axis
+ is_scroll_axis: bool,
+}
+
+impl OofAxis {
+ /// The physical edge corresponding to the logical start edge of the containing block
+ fn start_edge(&self) -> AxisStaticEdge {
+ if self.reversed {
+ AxisStaticEdge::End
+ } else {
+ AxisStaticEdge::Start
+ }
+ }
+
+ /// The physical edge corresponding to the logical end edge of the containing block
+ fn end_edge(&self) -> AxisStaticEdge {
+ if self.reversed {
+ AxisStaticEdge::Start
+ } else {
+ AxisStaticEdge::End
+ }
+ }
+
+ /// The inset-modified containing block (IMCB) in this axis
+ /// <https://www.w3.org/TR/css-position-3/#resolving-insets>
+ fn inset_modified_containing_block(&self) -> Line<f32> {
+ let (mut imcb, weaker_edge) = match (self.inset.start, self.inset.end) {
+ (Some(start), Some(end)) => (Line { start, end: self.cb_size - end }, self.end_edge()),
+ // A lone auto inset resolves to zero, and is the weaker inset
+ (Some(start), None) => (Line { start, end: self.cb_size }, AxisStaticEdge::End),
+ (None, Some(end)) => (Line { start: 0.0, end: self.cb_size - end }, AxisStaticEdge::Start),
+ // Both insets are auto: resolve them from the static position rectangle and the
+ // alignment within it
+ (None, None) => {
+ let sp = self.static_position;
+ let imcb = match sp.align.keyword {
+ AxisStaticEdge::Start => Line { start: sp.area.start, end: self.cb_size },
+ AxisStaticEdge::End => Line { start: 0.0, end: sp.area.end },
+ AxisStaticEdge::Center => {
+ // Center the IMCB on the static position rectangle's center, bounded by
+ // the nearer edge of the containing block
+ let center = (sp.area.start + sp.area.end) / 2.0;
+ let start_distance = center;
+ let end_distance = self.cb_size - center;
+ if start_distance.abs() <= end_distance.abs() {
+ Line { start: 0.0, end: 2.0 * start_distance }
+ } else {
+ Line { start: self.cb_size - 2.0 * end_distance, end: self.cb_size }
+ }
+ }
+ };
+ (imcb, self.end_edge())
+ }
+ };
+
+ // Overconstrained insets: the weaker inset is reduced to bring the IMCB size up to zero
+ // <https://www.w3.org/TR/css-position-3/#resolving-insets>
+ if imcb.end < imcb.start {
+ match weaker_edge {
+ AxisStaticEdge::Start => imcb.start = imcb.end,
+ _ => imcb.end = imcb.start,
+ }
+ }
+ imcb
+ }
+
+ /// The size of the IMCB in this axis: the space available to the box's margin box
+ fn inset_modified_containing_block_size(&self) -> f32 {
+ let imcb = self.inset_modified_containing_block();
+ imcb.end - imcb.start
+ }
+
+ /// The stretch-fit size of the box's border box: the IMCB minus the non-auto margins (auto
+ /// margins are treated as zero) <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
+ fn stretch_fit_size(&self) -> f32 {
+ let non_auto_margin_sum = self.margin.start.unwrap_or(0.0) + self.margin.end.unwrap_or(0.0);
+ f32_max(self.inset_modified_containing_block_size() - non_auto_margin_sum, 0.0)
+ }
+
+ /// Whether an `auto` size in this axis is the stretch-fit size (rather than fit-content)
+ /// <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
+ fn is_stretch_sized(&self, is_replaced: bool, is_table: bool) -> bool {
+ let no_auto_inset = self.inset.start.is_some() && self.inset.end.is_some();
+ no_auto_inset
+ && match self.alignment {
+ OofAlignment::Stretch => true,
+ OofAlignment::Normal => !is_replaced && !is_table,
+ _ => false,
+ }
+ }
+
+ /// Resolve the box's auto margins given its final size
+ /// <https://www.w3.org/TR/css-position-3/#abspos-margins>
+ fn resolve_margins(&self, size: f32) -> Line<f32> {
+ let both_insets = self.inset.start.is_some() && self.inset.end.is_some();
+ let imcb = self.inset_modified_containing_block();
+ let free_space = imcb.end - imcb.start - size;
+ match (self.margin.start, self.margin.end) {
+ (Some(start), Some(end)) => Line { start, end },
+ // If either inset is auto then auto margins resolve to zero
+ _ if !both_insets => Line { start: self.margin.start.unwrap_or(0.0), end: self.margin.end.unwrap_or(0.0) },
+ (Some(start), None) => Line { start, end: free_space - start },
+ (None, Some(end)) => Line { start: free_space - end, end },
+ (None, None) => {
+ // In the inline axis, negative free space is absorbed entirely by the end margin
+ if free_space < 0.0 && self.is_inline {
+ if self.reversed {
+ Line { start: free_space, end: 0.0 }
+ } else {
+ Line { start: 0.0, end: free_space }
+ }
+ } else {
+ Line { start: free_space / 2.0, end: free_space / 2.0 }
+ }
+ }
+ }
+ }
+
+ /// Compute the physical start of the box's border box given its final size and margins
+ /// <https://www.w3.org/TR/css-position-3/#abspos-alignment>
+ fn position(&self, size: f32, margin: Line<f32>) -> f32 {
+ let imcb = self.inset_modified_containing_block();
+ match (self.inset.start, self.inset.end) {
+ // Both insets are auto: static alignment, with safe overflow relative to the IMCB
+ (None, None) => {
+ let sp = self.static_position;
+ let margin_box_size = size + margin.start + margin.end;
+ let offset = if sp.align.safety == AlignmentSafety::Safe && margin_box_size > imcb.end - imcb.start {
+ align_in_line(imcb, margin_box_size, self.start_edge())
+ } else {
+ align_in_line(sp.area, margin_box_size, sp.align.keyword)
+ };
+ offset + margin.start
+ }
+ // One auto inset: the margin box is aligned to the edge of the stronger inset
+ (Some(_), None) => imcb.start + margin.start,
+ (None, Some(_)) => imcb.end - size - margin.end,
+ (Some(_), Some(_)) => {
+ // Auto margins have already absorbed all of the free space
+ if self.margin.start.is_none() || self.margin.end.is_none() {
+ return imcb.start + margin.start;
+ }
+
+ let margin_box_size = size + margin.start + margin.end;
+ let imcb_size = imcb.end - imcb.start;
+ let edge = self.alignment.physical_edge(self.reversed);
+ let margin_box_start = match self.safety {
+ AlignmentSafety::Unsafe => align_in_line(imcb, margin_box_size, edge),
+ AlignmentSafety::Safe => {
+ let edge = if margin_box_size > imcb_size { self.start_edge() } else { edge };
+ align_in_line(imcb, margin_box_size, edge)
+ }
+ // Default overflow alignment for absolutely positioned boxes:
+ // <https://www.w3.org/TR/css-align-3/#auto-safety-position>
+ AlignmentSafety::Default => {
+ if margin_box_size <= imcb_size || self.alignment == OofAlignment::Normal {
+ // 1. Fits within the IMCB: align as specified
+ align_in_line(imcb, margin_box_size, edge)
+ } else {
+ // The overflow limit rect is the bounding rect of the IMCB and the
+ // containing block, extended to infinity in the scrollable direction
+ // of a scroll container
+ let mut limit = Line { start: imcb.start.min(0.0), end: f32_max(imcb.end, self.cb_size) };
+ if self.is_scroll_axis {
+ if self.reversed {
+ limit.start = f32::NEG_INFINITY;
+ } else {
+ limit.end = f32::INFINITY;
+ }
+ }
+ if margin_box_size <= limit.end - limit.start {
+ // 2. Fits within the overflow limit rect: cover the IMCB and align
+ // as specified as far as possible without overflowing the limit
+ let start = align_in_line(imcb, margin_box_size, edge);
+ f32_max(start.min(limit.end - margin_box_size), limit.start)
+ } else {
+ // 3. Start-align within the overflow limit rect
+ align_in_line(limit, margin_box_size, self.start_edge())
+ }
+ }
+ }
+ };
+ margin_box_start + margin.start
+ }
+ }
+ }
+}
+
+/// Run the out-of-flow positioning pass for `node_id` after its layout algorithm has produced
+/// `output`: lay out the out-of-flow candidates in `output.oof_candidates` for which the node is
+/// the containing block, record them as the node's hoisted children, and replace
+/// `output.oof_candidates` with the unclaimed remainder (which bubble further up the tree).
+/// The scrollable overflow contributed by the claimed boxes is merged into
+/// `output.scrollable_overflow_rect`.
+///
+/// This should be called once per `RunMode::PerformLayout` container layout, after the layout
+/// algorithm (block/flexbox/grid) has run, and *inside* any layout caching wrapper (such as
+/// [`compute_cached_layout`](crate::compute_cached_layout)) so that cache hits do not re-run the
+/// pass. It is a no-op when `output.oof_positioning_area` is `None` (leaf and size-only outputs).
+///
+/// Which candidates the node claims is determined by the node's style via
+/// [`CoreStyle::is_containing_block`]. `position: fixed` boxes unclaimed by every ancestor are
+/// claimed by the final root positioning pass in [`compute_root_layout`](crate::compute_root_layout).
+pub fn compute_oof_layout(tree: &mut impl LayoutContainingBlock, node_id: NodeId, output: &mut LayoutOutput) {
+ let Some(area) = output.oof_positioning_area else { return };
+
+ let style = tree.get_core_container_style(node_id);
+ let direction = style.direction();
+ let claims = style.is_containing_block();
+ drop(style);
+
+ let candidates = output.oof_candidates.take();
+ let result = compute_oof_layout_for_area(tree, node_id, candidates.as_slice(), area, direction, claims);
+ // Always record the hoisted child list (even when empty) so that lists recorded by previous
+ // layout runs do not persist
+ tree.clear_hoisted_children(node_id);
+ tree.add_hoisted_children(node_id, &result.hoisted);
+ output.oof_candidates = result.unclaimed;
+ #[cfg(feature = "content_size")]
+ {
+ output.scrollable_overflow_rect = output.scrollable_overflow_rect.union(result.scrollable_overflow_rect);
+ }
+}
+
+/// The result of laying out out-of-flow candidates against an explicit positioning area.
+pub struct OofLayoutResult {
+ /// Candidates claimed and laid out by this pass, in document order.
+ pub hoisted: Vec<NodeId>,
+ /// Candidates not claimed by this pass, which must continue bubbling.
+ pub unclaimed: OofCandidates,
+ /// Scrollable overflow contributed by the claimed candidates, relative to the positioning
+ /// area's origin.
+ pub scrollable_overflow_rect: Rect<f32>,
+}
+
+/// Lay out out-of-flow candidates against an explicit positioning area.
+///
+/// Unlike [`compute_oof_layout`], this function does not update the geometry owner's hoisted
+/// children or merge overflow into a [`LayoutOutput`]. This is useful when the CSS containing
+/// block does not have its own layout node and another node owns the resulting geometry.
+///
+/// `geometry_owner` supplies the layout tree operations, detailed layout information, and
+/// scroll-container state used by the positioning pass. `direction` and `claims` describe the
+/// actual CSS containing block.
+pub fn compute_oof_layout_for_area(
+ tree: &mut impl LayoutContainingBlock,
+ geometry_owner: NodeId,
+ candidates: &[OofCandidate],
+ area: OofPositioningArea,
+ direction: Direction,
+ claims: ContainingBlockClaims,
+) -> OofLayoutResult {
+ let overflow = tree.get_core_container_style(geometry_owner).overflow();
+
+ let mut hoisted = Vec::new();
+ let mut unclaimed = OofCandidates::new();
+ let scrollable_overflow_rect = perform_oof_layout(
+ tree,
+ geometry_owner,
+ candidates,
+ area.size,
+ area.offset,
+ direction,
+ claims,
+ overflow,
+ &mut hoisted,
+ &mut unclaimed,
+ );
+
+ OofLayoutResult { hoisted, unclaimed, scrollable_overflow_rect }
+}
+
+/// The result of laying out a single out-of-flow box with [`layout_oof_box`].
+pub(crate) struct OofBoxLayout {
+ /// The box's final layout (its `location` is relative to the containing block's border box)
+ pub layout: Layout,
+ /// Out-of-flow candidates surfaced from within the box's subtree, with anchors relative to
+ /// the box's own border box
+ pub surfaced: OofCandidates,
+ /// The box's `overflow` style
+ #[cfg(feature = "content_size")]
+ pub overflow: Point<Overflow>,
+ /// The box's `contain` style
+ #[cfg(feature = "content_size")]
+ pub contain: crate::style::Contain,
+}
+
+/// Size and position a single out-of-flow box against its containing block, and store its layout.
+///
+/// - `area_size`/`area_offset` describe the inset-resolution area of the containing block
+/// (border box minus borders and scrollbar gutters), relative to the containing block's border box.
+/// - `container_overflow` is the `overflow` style of the containing block, which determines
+/// whether overflowing boxes may be aligned into its scrollable overflow area.
+/// - `grid_owner` is the node whose detailed layout info is consulted for grid placement: if it is
+/// a grid container, the box is positioned relative to the grid area determined by its
+/// grid-placement properties rather than the passed area.
+/// - `before_layout` is called with the inputs of the final layout pass just before it runs, which
+/// allows the caller to inspect the layout cache for the box.
+#[inline(always)]
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn layout_oof_box<Tree: LayoutContainingBlock>(
+ tree: &mut Tree,
+ candidate: OofCandidate,
+ area_size: Size<f32>,
+ area_offset: Point<f32>,
+ direction: Direction,
+ container_overflow: Point<Overflow>,
+ #[cfg(feature = "grid")] grid_owner: Option<NodeId>,
+ before_layout: impl FnOnce(&mut Tree, &LayoutInput),
+) -> OofBoxLayout {
+ let child_style = tree.get_oof_item_style(candidate.node);
+
+ // If the current node is a grid container then the box is positioned relative to the
+ // grid area determined by its grid-placement properties (which falls back to the passed
+ // area for `auto` placement)
+ #[cfg(feature = "grid")]
+ let (area_size, area_offset) = match grid_owner.map(|owner| tree.get_detailed_layout_info(owner)) {
+ Some(DetailedLayoutInfo::Grid(grid_info)) => {
+ let area_rect = Rect {
+ left: area_offset.x,
+ right: area_offset.x + area_size.width,
+ top: area_offset.y,
+ bottom: area_offset.y + area_size.height,
+ };
+ let grid_area = grid_info.resolve_absolute_grid_area(
+ child_style.grid_row(),
+ child_style.grid_column(),
+ direction,
+ area_rect,
+ );
+ (
+ Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top },
+ Point { x: grid_area.left, y: grid_area.top },
+ )
+ }
+ _ => (area_size, area_offset),
+ };
+ let area_width = area_size.width;
+ let area_height = area_size.height;
+
+ let aspect_ratio = child_style.aspect_ratio();
+ let margin =
+ child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
+ let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
+ let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
+ let padding_border_sum = (padding + border).sum_axes();
+ let box_sizing_adjustment =
+ if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
+
+ // Resolve inset
+ let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
+ let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
+ let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
+ let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
+
+ // Compute known dimensions from min/max/inherent size styles
+ let size_style = child_style.size();
+ let style_size = size_style
+ .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let mut min_size = child_style
+ .min_size()
+ .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment)
+ .or(padding_border_sum.map(Some))
+ .maybe_max(padding_border_sum);
+ let max_size = child_style
+ .max_size()
+ .maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
+ .maybe_apply_aspect_ratio(aspect_ratio)
+ .maybe_add(box_sizing_adjustment);
+ let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
+
+ let is_replaced = child_style.is_replaced();
+ let is_table = child_style.is_table();
+ let item_direction = child_style.direction();
+ // Taffy only supports the `horizontal-tb` writing mode, so only the inline axis can be reversed.
+ // `auto` (`None`) behaves as `normal` for absolutely positioned boxes: it does not defer to the
+ // `*-items` properties of the containing block.
+ let justify_self =
+ child_style.justify_self().unwrap_or(AlignSelf::NORMAL).resolve_self_relative(item_direction, direction, true);
+ let align_self =
+ child_style.align_self().unwrap_or(AlignSelf::NORMAL).resolve_self_relative(item_direction, direction, false);
+ let overflow = child_style.overflow();
+ let scrollbar_width = child_style.scrollbar_width();
+ #[cfg(feature = "content_size")]
+ let contain = child_style.contain();
+
+ drop(child_style);
+
+ // Static positions are relative to the containing block's border box: make them relative to
+ // the inset-resolution area
+ let static_position = Point {
+ x: AxisStaticPosition {
+ area: candidate.static_position.x.area.map(|v| v - area_offset.x),
+ align: candidate.static_position.x.align,
+ },
+ y: AxisStaticPosition {
+ area: candidate.static_position.y.area.map(|v| v - area_offset.y),
+ align: candidate.static_position.y.align,
+ },
+ };
+
+ let horizontal = OofAxis {
+ cb_size: area_width,
+ inset: Line { start: left, end: right },
+ margin: Line { start: margin.left, end: margin.right },
+ static_position: static_position.x,
+ alignment: OofAlignment::from_resolved(justify_self),
+ safety: justify_self.safety,
+ is_inline: true,
+ reversed: direction.is_rtl(),
+ is_scroll_axis: container_overflow.x.is_scroll_container(),
+ };
+ let vertical = OofAxis {
+ cb_size: area_height,
+ inset: Line { start: top, end: bottom },
+ margin: Line { start: margin.top, end: margin.bottom },
+ static_position: static_position.y,
+ alignment: OofAlignment::from_resolved(align_self),
+ safety: align_self.safety,
+ is_inline: false,
+ reversed: false,
+ is_scroll_axis: container_overflow.y.is_scroll_container(),
+ };
+ let stretch_fit_size = Size { width: horizontal.stretch_fit_size(), height: vertical.stretch_fit_size() };
+ // The space available to the box's border box is its stretch-fit size (the IMCB minus its
+ // non-auto margins). The available space for a table never exceeds that of the containing
+ // block (minus the margins) <https://www.w3.org/TR/css-tables-3/#abspos>
+ let mut available_space = stretch_fit_size;
+ if is_table {
+ let non_auto_margin = margin.map(|m| m.unwrap_or(0.0));
+ available_space = available_space.f32_min(Size {
+ width: f32_max(area_width - non_auto_margin.horizontal_axis_sum(), 0.0),
+ height: f32_max(area_height - non_auto_margin.vertical_axis_sum(), 0.0),
+ });
+ }
+ let available_space = available_space.maybe_clamp(min_size, max_size).map(AvailableSpace::Definite);
+
+ // Resolve any sizing keywords (min-content, max-content, fit-content, fit-content(...),
+ // stretch) in the size styles. An explicitly sized axis takes precedence over the
+ // automatic size below.
+ if size_style.width.is_sizing_keyword() || size_style.height.is_sizing_keyword() {
+ resolve_absolute_sizing_keywords(
+ tree,
+ candidate.node,
+ &mut known_dimensions,
+ size_style,
+ area_size,
+ Rect { left, right, top, bottom },
+ margin,
+ SizingMode::ContentSize,
+ );
+ known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
+ }
+
+ // Resolve automatic sizes <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
+ //
+ // An auto size is the stretch-fit size (the IMCB minus margins) if the self-alignment in
+ // that axis is `stretch` (or `normal` for a non-replaced, non-table box) and neither inset is
+ // auto. Otherwise it is the fit-content size, which is measured below. Stretch-fit sizes are
+ // resolved first so that a size in the other axis can be transferred through the aspect ratio.
+ // The block axis is the ratio-dependent axis, so a stretched inline size is transferred
+ // through the aspect ratio rather than also stretching the block size. An explicit
+ // `stretch` in both axes stretches both and ignores the aspect ratio.
+ let stretch_width = known_dimensions.width.is_none() && horizontal.is_stretch_sized(is_replaced, is_table);
+ let stretch_height = known_dimensions.height.is_none() && vertical.is_stretch_sized(is_replaced, is_table);
+ let both_explicit_stretch =
+ horizontal.alignment == OofAlignment::Stretch && vertical.alignment == OofAlignment::Stretch;
+ let stretch_aspect_ratio =
+ if stretch_width && stretch_height && both_explicit_stretch { None } else { aspect_ratio };
+ if stretch_width {
+ if is_table {
+ // A table cannot be stretched smaller than its content: stretch-fit is a minimum
+ min_size.width = Some(f32_max(min_size.width.unwrap_or(0.0), stretch_fit_size.width));
+ } else {
+ known_dimensions.width = Some(stretch_fit_size.width);
+ known_dimensions =
+ known_dimensions.maybe_apply_aspect_ratio(stretch_aspect_ratio).maybe_clamp(min_size, max_size);
+ }
+ }
+ if known_dimensions.height.is_none() && stretch_height {
+ if is_table {
+ min_size.height = Some(f32_max(min_size.height.unwrap_or(0.0), stretch_fit_size.height));
+ } else {
+ known_dimensions.height = Some(stretch_fit_size.height);
+ known_dimensions =
+ known_dimensions.maybe_apply_aspect_ratio(stretch_aspect_ratio).maybe_clamp(min_size, max_size);
+ }
+ }
+
+ let final_size = match (known_dimensions.width, known_dimensions.height) {
+ (Some(width), Some(height)) => Size { width, height },
+ _ => {
+ let measured_size = tree.measure_child_size_both(
+ candidate.node,
+ known_dimensions,
+ area_size.map(Some),
+ available_space,
+ SizingMode::ContentSize,
+ Line::FALSE,
+ );
+ known_dimensions.unwrap_or(measured_size)
+ }
+ }
+ .maybe_clamp(min_size, max_size);
+
+ let layout_input = LayoutInput {
+ known_dimensions: final_size.map(Some),
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size: area_size.map(Some),
+ available_space,
+ sizing_mode: SizingMode::ContentSize,
+ axis: RequestedAxis::Both,
+ run_mode: RunMode::PerformLayout,
+ vertical_margins_are_collapsible: Line::FALSE,
+ };
+ before_layout(tree, &layout_input);
+ let mut layout_output = tree.compute_child_layout(candidate.node, layout_input);
+
+ // Resolve auto margins <https://www.w3.org/TR/css-position-3/#abspos-margins>
+ let horizontal_margin = horizontal.resolve_margins(final_size.width);
+ let vertical_margin = vertical.resolve_margins(final_size.height);
+ let resolved_margin = Rect {
+ left: horizontal_margin.start,
+ right: horizontal_margin.end,
+ top: vertical_margin.start,
+ bottom: vertical_margin.end,
+ };
+
+ // Align the margin box within the IMCB <https://www.w3.org/TR/css-position-3/#abspos-alignment>
+ let location = Point {
+ x: horizontal.position(final_size.width, horizontal_margin) + area_offset.x,
+ y: vertical.position(final_size.height, vertical_margin) + area_offset.y,
+ };
+
+ // Note: axis intentionally switched here as scrollbars take up space in the opposite axis
+ // to the axis in which scrolling is enabled.
+ let scrollbar_size = Size {
+ width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
+ height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
+ };
+
+ let layout = Layout {
+ order: candidate.order,
+ size: final_size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: layout_output.scrollable_overflow_rect,
+ scrollbar_size,
+ location,
+ padding,
+ border,
+ margin: resolved_margin,
+ };
+ tree.set_unrounded_layout(candidate.node, &layout);
+
+ OofBoxLayout {
+ layout,
+ surfaced: layout_output.oof_candidates.take(),
+ #[cfg(feature = "content_size")]
+ overflow,
+ #[cfg(feature = "content_size")]
+ contain,
+ }
+}
+
+/// Perform final layout on the out-of-flow candidates for which the current node is the
+/// containing block, and collect the remainder into `unclaimed` for further bubbling.
+///
+/// - `node_id` is the current node. If its detailed layout info (as returned by
+/// [`LayoutContainingBlock::get_detailed_layout_info`]) indicates that it is a grid container,
+/// each claimed box is positioned relative to the grid area determined by its grid-placement
+/// properties rather than the passed inset-resolution area.
+/// - `candidates` is the merged, document-ordered list of candidates held by the current node
+/// (direct out-of-flow children plus candidates bubbled from in-flow children). Anchors must be
+/// relative to the current node's border box.
+/// - `area_size`/`area_offset` describe the inset-resolution area of the current node
+/// (border box minus borders and scrollbar gutters).
+/// - `claims` describes which out-of-flow positions the current node acts as a containing block
+/// for (see [`CoreStyle::is_containing_block`]). The final root positioning pass claims all.
+/// - `container_overflow` is the `overflow` style of the containing block.
+///
+/// Laying out a claimed box may surface further candidates from within its subtree (e.g. a
+/// `position: fixed` descendant of a `position: absolute` box). These are re-swept: claimed ones
+/// are appended to the work list, unclaimed ones are added to `unclaimed`.
+///
+/// The ids of claimed boxes are appended to `hoisted` in order. Returns the scrollable overflow
+/// contribution of the claimed boxes.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn perform_oof_layout(
+ tree: &mut impl LayoutContainingBlock,
+ node_id: NodeId,
+ candidates: &[OofCandidate],
+ area_size: Size<f32>,
+ area_offset: Point<f32>,
+ direction: Direction,
+ claims: ContainingBlockClaims,
+ container_overflow: Point<Overflow>,
+ hoisted: &mut Vec<NodeId>,
+ unclaimed: &mut OofCandidates,
+) -> Rect<f32> {
+ #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
+ let mut absolute_overflow_rect = Rect::ZERO;
+
+ if candidates.is_empty() {
+ return absolute_overflow_rect;
+ }
+
+ #[cfg(feature = "content_size")]
+ let is_scroll_container = container_overflow.x.is_scroll_container() || container_overflow.y.is_scroll_container();
+
+ // Split the candidate list into an initial work list of claimed candidates and the unclaimed
+ // remainder. Further claimed candidates surfaced while laying out a claimed box are appended
+ // to the work list (Blink-style re-sweep).
+ let mut worklist: Vec<OofCandidate> = Vec::new();
+ for candidate in candidates {
+ if claims.for_position(candidate.position) {
+ worklist.push(*candidate);
+ } else {
+ unclaimed.push(*candidate);
+ }
+ }
+
+ #[cfg(not(feature = "grid"))]
+ let _ = node_id;
+
+ let mut index = 0;
+ while index < worklist.len() {
+ let candidate = worklist[index];
+ index += 1;
+ hoisted.push(candidate.node);
+
+ let OofBoxLayout {
+ layout,
+ surfaced,
+ #[cfg(feature = "content_size")]
+ overflow,
+ #[cfg(feature = "content_size")]
+ contain,
+ } = layout_oof_box(
+ tree,
+ candidate,
+ area_size,
+ area_offset,
+ direction,
+ container_overflow,
+ #[cfg(feature = "grid")]
+ Some(node_id),
+ |_, _| {},
+ );
+ let location = layout.location;
+ let final_size = layout.size;
+
+ // Re-sweep any candidates surfaced from within the box's subtree, translating their
+ // anchors so they are relative to this node's border box
+ let mut surfaced = surfaced;
+ if !surfaced.is_empty() {
+ surfaced.translate(location);
+ for surfaced_candidate in surfaced.iter() {
+ if claims.for_position(surfaced_candidate.position) {
+ worklist.push(*surfaced_candidate);
+ } else {
+ unclaimed.push(*surfaced_candidate);
+ }
+ }
+ }
+
+ #[cfg(feature = "content_size")]
+ {
+ // Location is measured from the scroll origin (the inline-start edge: right side in RTL)
+ let relative_location = if direction.is_rtl() {
+ Point {
+ x: area_size.width - (location.x - area_offset.x) - final_size.width,
+ y: location.y - area_offset.y,
+ }
+ } else {
+ Point { x: location.x - area_offset.x, y: location.y - area_offset.y }
+ };
+ absolute_overflow_rect = absolute_overflow_rect.union(compute_scrollable_overflow_contribution(
+ relative_location,
+ final_size,
+ layout.scrollable_overflow_rect,
+ overflow,
+ contain,
+ is_scroll_container,
+ ));
+ }
+ }
+
+ absolute_overflow_rect
+}
+
+#[cfg(test)]
+mod tests {
+ use super::resolve_static_offset;
+ use crate::geometry::{Line, Point, Rect, Size};
+ use crate::style::AlignmentSafety;
+ use crate::tree::{AxisStaticAlign, AxisStaticEdge, AxisStaticPosition};
+
+ fn sp(
+ area: Line<f32>,
+ keyword: AxisStaticEdge,
+ safety: AlignmentSafety,
+ fallback: AxisStaticEdge,
+ ) -> AxisStaticPosition {
+ AxisStaticPosition { area, align: AxisStaticAlign { keyword, safety, fallback } }
+ }
+
+ fn resolve_x(sp_x: AxisStaticPosition, width: f32, margin: Rect<f32>) -> f32 {
+ let position = Point { x: sp_x, y: AxisStaticPosition::from_edge(0.0, AxisStaticEdge::Start) };
+ resolve_static_offset(position, Size { width, height: 10.0 }, margin).x
+ }
+
+ const AREA: Line<f32> = Line { start: 10.0, end: 110.0 };
+ const NO_MARGIN: Rect<f32> = Rect { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0 };
+ const MARGIN: Rect<f32> = Rect { left: 5.0, right: 15.0, top: 0.0, bottom: 0.0 };
+
+ #[test]
+ fn start_alignment() {
+ let sp_x = sp(AREA, AxisStaticEdge::Start, AlignmentSafety::Unsafe, AxisStaticEdge::Start);
+ assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 10.0);
+ assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 15.0);
+ }
+
+ #[test]
+ fn end_alignment() {
+ let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Unsafe, AxisStaticEdge::End);
+ assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 90.0);
+ assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 75.0);
+ }
+
+ #[test]
+ fn center_alignment() {
+ let sp_x = sp(AREA, AxisStaticEdge::Center, AlignmentSafety::Unsafe, AxisStaticEdge::Center);
+ assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 50.0);
+ // Center offsets by half the margin difference
+ assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 45.0);
+ }
+
+ #[test]
+ fn safe_alignment_falls_back_only_on_overflow() {
+ let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Safe, AxisStaticEdge::Start);
+ // Fits: aligned to the end
+ assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 90.0);
+ // Margin box exactly fills the area: no fallback
+ assert_eq!(resolve_x(sp_x, 100.0, NO_MARGIN), 10.0);
+ // Margin box overflows the area: falls back to start
+ assert_eq!(resolve_x(sp_x, 120.0, NO_MARGIN), 10.0);
+ assert_eq!(resolve_x(sp_x, 90.0, MARGIN), 15.0);
+ }
+
+ #[test]
+ fn unsafe_alignment_never_falls_back() {
+ let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Unsafe, AxisStaticEdge::Start);
+ assert_eq!(resolve_x(sp_x, 120.0, NO_MARGIN), -10.0);
+ }
+
+ #[test]
+ fn degenerate_area() {
+ // A zero-extent area (static positions emitted by block layout) behaves as an anchor point
+ let anchor = AxisStaticPosition::from_edge(40.0, AxisStaticEdge::Start);
+ assert_eq!(resolve_x(anchor, 20.0, NO_MARGIN), 40.0);
+ let anchor_end = AxisStaticPosition::from_edge(40.0, AxisStaticEdge::End);
+ assert_eq!(resolve_x(anchor_end, 20.0, NO_MARGIN), 20.0);
+ }
+}
diff --git a/vendor/taffy/src/geometry.rs b/vendor/taffy/src/geometry.rs
new file mode 100644
index 00000000..c743dfb7
--- /dev/null
+++ b/vendor/taffy/src/geometry.rs
@@ -0,0 +1,773 @@
+//! Geometric primitives useful for layout
+
+use crate::util::sys::f32_max;
+use crate::CompactLength;
+use crate::{style::Dimension, util::sys::f32_min};
+use core::ops::{Add, Sub};
+
+#[cfg(feature = "flexbox")]
+use crate::style::FlexDirection;
+
+/// The simple absolute horizontal and vertical axis
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum AbsoluteAxis {
+ /// The horizontal axis
+ Horizontal,
+ /// The vertical axis
+ Vertical,
+}
+
+impl AbsoluteAxis {
+ /// Returns the other variant of the enum
+ #[inline]
+ pub const fn other_axis(&self) -> Self {
+ match *self {
+ AbsoluteAxis::Horizontal => AbsoluteAxis::Vertical,
+ AbsoluteAxis::Vertical => AbsoluteAxis::Horizontal,
+ }
+ }
+}
+
+impl<T> Size<T> {
+ #[inline(always)]
+ /// Get either the width or height depending on the AbsoluteAxis passed in
+ pub fn get_abs(self, axis: AbsoluteAxis) -> T {
+ match axis {
+ AbsoluteAxis::Horizontal => self.width,
+ AbsoluteAxis::Vertical => self.height,
+ }
+ }
+
+ /// Swap the width and height components
+ #[inline(always)]
+ pub fn transpose(self) -> Size<T> {
+ Size { width: self.height, height: self.width }
+ }
+}
+
+impl<T: Add> Rect<T> {
+ #[inline(always)]
+ /// Get either the width or height depending on the AbsoluteAxis passed in
+ pub fn grid_axis_sum(self, axis: AbsoluteAxis) -> <T as Add>::Output {
+ match axis {
+ AbsoluteAxis::Horizontal => self.left + self.right,
+ AbsoluteAxis::Vertical => self.top + self.bottom,
+ }
+ }
+}
+
+/// The CSS abstract axis
+/// <https://www.w3.org/TR/css-writing-modes-3/#abstract-axes>
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub enum AbstractAxis {
+ /// The axis in the inline dimension, i.e. the horizontal axis in horizontal writing modes and the vertical axis in vertical writing modes.
+ Inline,
+ /// The axis in the block dimension, i.e. the vertical axis in horizontal writing modes and the horizontal axis in vertical writing modes.
+ Block,
+}
+
+impl AbstractAxis {
+ /// Returns the other variant of the enum
+ #[inline]
+ pub const fn other(&self) -> AbstractAxis {
+ match *self {
+ AbstractAxis::Inline => AbstractAxis::Block,
+ AbstractAxis::Block => AbstractAxis::Inline,
+ }
+ }
+
+ /// Convert an `AbstractAxis` into an `AbsoluteAxis` naively assuming that the Inline axis is Horizontal
+ /// This is currently always true, but will change if Taffy ever implements the `writing_mode` property
+ #[inline]
+ pub const fn as_abs_naive(&self) -> AbsoluteAxis {
+ match self {
+ AbstractAxis::Inline => AbsoluteAxis::Horizontal,
+ AbstractAxis::Block => AbsoluteAxis::Vertical,
+ }
+ }
+}
+
+/// Container that holds an item in each absolute axis without specifying
+/// what kind of item it is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct InBothAbsAxis<T> {
+ /// The item in the horizontal axis
+ pub horizontal: T,
+ /// The item in the vertical axis
+ pub vertical: T,
+}
+
+impl<T: Copy> InBothAbsAxis<T> {
+ #[cfg(feature = "grid")]
+ /// Get the contained item based on the AbsoluteAxis passed
+ pub const fn get(&self, axis: AbsoluteAxis) -> T {
+ match axis {
+ AbsoluteAxis::Horizontal => self.horizontal,
+ AbsoluteAxis::Vertical => self.vertical,
+ }
+ }
+}
+
+/// An axis-aligned UI rectangle
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct Rect<T> {
+ /// This can represent either the x-coordinate of the starting edge,
+ /// or the amount of padding on the starting side.
+ ///
+ /// The starting edge is the left edge when working with LTR text,
+ /// and the right edge when working with RTL text.
+ pub left: T,
+ /// This can represent either the x-coordinate of the ending edge,
+ /// or the amount of padding on the ending side.
+ ///
+ /// The ending edge is the right edge when working with LTR text,
+ /// and the left edge when working with RTL text.
+ pub right: T,
+ /// This can represent either the y-coordinate of the top edge,
+ /// or the amount of padding on the top side.
+ pub top: T,
+ /// This can represent either the y-coordinate of the bottom edge,
+ /// or the amount of padding on the bottom side.
+ pub bottom: T,
+}
+
+impl<U, T: Add<U>> Add<Rect<U>> for Rect<T> {
+ type Output = Rect<T::Output>;
+
+ fn add(self, rhs: Rect<U>) -> Self::Output {
+ Rect {
+ left: self.left + rhs.left,
+ right: self.right + rhs.right,
+ top: self.top + rhs.top,
+ bottom: self.bottom + rhs.bottom,
+ }
+ }
+}
+
+impl<T> Rect<T> {
+ /// Swap the horizontal and vertical sides (`left <-> top`, `right <-> bottom`)
+ #[inline(always)]
+ pub fn transpose(self) -> Rect<T> {
+ Rect { left: self.top, right: self.bottom, top: self.left, bottom: self.right }
+ }
+
+ /// Applies the function `f` to all four sides of the rect
+ ///
+ /// When applied to the left and right sides, the width is used
+ /// as the second parameter of `f`.
+ /// When applied to the top or bottom sides, the height is used instead.
+ #[cfg(any(feature = "flexbox", feature = "block_layout"))]
+ #[inline(always)]
+ pub(crate) fn zip_size<R, F, U>(self, size: Size<U>, f: F) -> Rect<R>
+ where
+ F: Fn(T, U) -> R,
+ U: Copy,
+ {
+ Rect {
+ left: f(self.left, size.width),
+ right: f(self.right, size.width),
+ top: f(self.top, size.height),
+ bottom: f(self.bottom, size.height),
+ }
+ }
+
+ /// Applies the function `f` to the left, right, top, and bottom properties
+ ///
+ /// This is used to transform a `Rect<T>` into a `Rect<R>`.
+ #[inline(always)]
+ pub fn map<R, F>(self, f: F) -> Rect<R>
+ where
+ F: Fn(T) -> R,
+ {
+ Rect { left: f(self.left), right: f(self.right), top: f(self.top), bottom: f(self.bottom) }
+ }
+
+ /// Returns a `Line<T>` representing the left and right properties of the Rect
+ pub fn horizontal_components(self) -> Line<T> {
+ Line { start: self.left, end: self.right }
+ }
+
+ /// Returns a `Line<T>` containing the top and bottom properties of the Rect
+ pub fn vertical_components(self) -> Line<T> {
+ Line { start: self.top, end: self.bottom }
+ }
+}
+
+impl<T, U> Rect<T>
+where
+ T: Add<Output = U> + Copy + Clone,
+{
+ /// The sum of [`Rect.start`](Rect) and [`Rect.end`](Rect)
+ ///
+ /// This is typically used when computing total padding.
+ ///
+ /// **NOTE:** this is *not* the width of the rectangle.
+ #[inline(always)]
+ pub fn horizontal_axis_sum(&self) -> U {
+ self.left + self.right
+ }
+
+ /// The sum of [`Rect.top`](Rect) and [`Rect.bottom`](Rect)
+ ///
+ /// This is typically used when computing total padding.
+ ///
+ /// **NOTE:** this is *not* the height of the rectangle.
+ #[inline(always)]
+ pub fn vertical_axis_sum(&self) -> U {
+ self.top + self.bottom
+ }
+
+ /// Both horizontal_axis_sum and vertical_axis_sum as a `Size<T>`
+ ///
+ /// **NOTE:** this is *not* the width/height of the rectangle.
+ #[inline(always)]
+ #[allow(dead_code)] // Fixes spurious clippy warning: this function is used!
+ pub fn sum_axes(&self) -> Size<U> {
+ Size { width: self.horizontal_axis_sum(), height: self.vertical_axis_sum() }
+ }
+
+ /// The sum of the two fields of the [`Rect`] representing the main axis.
+ ///
+ /// This is typically used when computing total padding.
+ ///
+ /// If the [`FlexDirection`] is [`FlexDirection::Row`] or [`FlexDirection::RowReverse`], this is [`Rect::horizontal`].
+ /// Otherwise, this is [`Rect::vertical`].
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn main_axis_sum(&self, direction: FlexDirection) -> U {
+ if direction.is_row() {
+ self.horizontal_axis_sum()
+ } else {
+ self.vertical_axis_sum()
+ }
+ }
+
+ /// The sum of the two fields of the [`Rect`] representing the cross axis.
+ ///
+ /// If the [`FlexDirection`] is [`FlexDirection::Row`] or [`FlexDirection::RowReverse`], this is [`Rect::vertical`].
+ /// Otherwise, this is [`Rect::horizontal`].
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn cross_axis_sum(&self, direction: FlexDirection) -> U {
+ if direction.is_row() {
+ self.vertical_axis_sum()
+ } else {
+ self.horizontal_axis_sum()
+ }
+ }
+}
+
+impl<T> Rect<T>
+where
+ T: Copy + Clone,
+{
+ /// The `start` or `top` value of the [`Rect`], from the perspective of the main layout axis
+ #[cfg(feature = "flexbox")]
+ pub(crate) const fn main_start(&self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.left
+ } else {
+ self.top
+ }
+ }
+
+ /// The `end` or `bottom` value of the [`Rect`], from the perspective of the main layout axis
+ #[cfg(feature = "flexbox")]
+ pub(crate) const fn main_end(&self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.right
+ } else {
+ self.bottom
+ }
+ }
+
+ /// The `start` or `top` value of the [`Rect`], from the perspective of the cross layout axis
+ #[cfg(feature = "flexbox")]
+ pub(crate) const fn cross_start(&self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.top
+ } else {
+ self.left
+ }
+ }
+
+ /// The `end` or `bottom` value of the [`Rect`], from the perspective of the main layout axis
+ #[cfg(feature = "flexbox")]
+ pub(crate) const fn cross_end(&self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.bottom
+ } else {
+ self.right
+ }
+ }
+}
+
+impl Rect<Option<f32>> {
+ /// A [`Rect`] with `None` as all parameters
+ pub const NONE: Rect<Option<f32>> = Self { left: None, right: None, top: None, bottom: None };
+}
+
+impl Rect<f32> {
+ /// Creates a new Rect with `0.0` as all parameters
+ pub const ZERO: Rect<f32> = Self { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0 };
+
+ /// Creates a new Rect
+ #[must_use]
+ pub const fn new(start: f32, end: f32, top: f32, bottom: f32) -> Self {
+ Self { left: start, right: end, top, bottom }
+ }
+
+ /// Returns the smallest rectangle that contains both `self` and `other`, where the fields
+ /// of each `Rect` are interpreted as edge coordinates (`left`/`top` being the minimum
+ /// coordinates and `right`/`bottom` the maximum coordinates of the rectangle)
+ #[must_use]
+ pub fn union(self, other: Self) -> Self {
+ Self {
+ left: self.left.min(other.left),
+ right: self.right.max(other.right),
+ top: self.top.min(other.top),
+ bottom: self.bottom.max(other.bottom),
+ }
+ }
+}
+
+/// An abstract "line". Represents any type that has a start and an end
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[cfg_attr(feature = "serde", serde(default))]
+pub struct Line<T> {
+ /// The start position of a line
+ pub start: T,
+ /// The end position of a line
+ pub end: T,
+}
+
+impl<T> Line<T> {
+ /// Applies the function `f` to both the width and height
+ ///
+ /// This is used to transform a `Line<T>` into a `Line<R>`.
+ pub fn map<R, F>(self, f: F) -> Line<R>
+ where
+ F: Fn(T) -> R,
+ {
+ Line { start: f(self.start), end: f(self.end) }
+ }
+}
+
+impl Line<bool> {
+ /// A `Line<bool>` with both start and end set to `true`
+ pub const TRUE: Self = Line { start: true, end: true };
+ /// A `Line<bool>` with both start and end set to `false`
+ pub const FALSE: Self = Line { start: false, end: false };
+}
+
+impl<T: Add + Copy> Line<T> {
+ /// Adds the start and end values together and returns the result
+ pub fn sum(&self) -> <T as Add>::Output {
+ self.start + self.end
+ }
+}
+
+/// The width and height of a [`Rect`]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct Size<T> {
+ /// The x extent of the rectangle
+ pub width: T,
+ /// The y extent of the rectangle
+ pub height: T,
+}
+
+// Generic Add impl for Size<T> + Size<U> where T + U has an Add impl
+impl<U, T: Add<U>> Add<Size<U>> for Size<T> {
+ type Output = Size<<T as Add<U>>::Output>;
+
+ fn add(self, rhs: Size<U>) -> Self::Output {
+ Size { width: self.width + rhs.width, height: self.height + rhs.height }
+ }
+}
+
+// Generic Sub impl for Size<T> + Size<U> where T + U has an Sub impl
+impl<U, T: Sub<U>> Sub<Size<U>> for Size<T> {
+ type Output = Size<<T as Sub<U>>::Output>;
+
+ fn sub(self, rhs: Size<U>) -> Self::Output {
+ Size { width: self.width - rhs.width, height: self.height - rhs.height }
+ }
+}
+
+// Note: we allow dead_code here as we want to provide a complete API of helpers that is symmetrical in all axes,
+// but sometimes we only currently have a use for the helper in a single axis
+#[allow(dead_code)]
+impl<T> Size<T> {
+ /// Applies the function `f` to both the width and height
+ ///
+ /// This is used to transform a `Size<T>` into a `Size<R>`.
+ pub fn map<R, F>(self, f: F) -> Size<R>
+ where
+ F: Fn(T) -> R,
+ {
+ Size { width: f(self.width), height: f(self.height) }
+ }
+
+ /// Applies the function `f` to the width
+ pub fn map_width<F>(self, f: F) -> Size<T>
+ where
+ F: Fn(T) -> T,
+ {
+ Size { width: f(self.width), height: self.height }
+ }
+
+ /// Applies the function `f` to the height
+ pub fn map_height<F>(self, f: F) -> Size<T>
+ where
+ F: Fn(T) -> T,
+ {
+ Size { width: self.width, height: f(self.height) }
+ }
+
+ /// Applies the function `f` to both the width and height
+ /// of this value and another passed value
+ pub fn zip_map<Other, Ret, Func>(self, other: Size<Other>, f: Func) -> Size<Ret>
+ where
+ Func: Fn(T, Other) -> Ret,
+ {
+ Size { width: f(self.width, other.width), height: f(self.height, other.height) }
+ }
+
+ /// Sets the extent of the main layout axis
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn set_main(&mut self, direction: FlexDirection, value: T) {
+ if direction.is_row() {
+ self.width = value
+ } else {
+ self.height = value
+ }
+ }
+
+ /// Sets the extent of the cross layout axis
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn set_cross(&mut self, direction: FlexDirection, value: T) {
+ if direction.is_row() {
+ self.height = value
+ } else {
+ self.width = value
+ }
+ }
+
+ /// Creates a new value of type Self with the main axis set to value provided
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn with_main(self, direction: FlexDirection, value: T) -> Self {
+ let mut new = self;
+ if direction.is_row() {
+ new.width = value
+ } else {
+ new.height = value
+ }
+ new
+ }
+
+ /// Creates a new value of type Self with the cross axis set to value provided
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn with_cross(self, direction: FlexDirection, value: T) -> Self {
+ let mut new = self;
+ if direction.is_row() {
+ new.height = value
+ } else {
+ new.width = value
+ }
+ new
+ }
+
+ /// Creates a new value of type Self with the main axis modified by the callback provided
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn map_main(self, direction: FlexDirection, mapper: impl FnOnce(T) -> T) -> Self {
+ let mut new = self;
+ if direction.is_row() {
+ new.width = mapper(new.width);
+ } else {
+ new.height = mapper(new.height);
+ }
+ new
+ }
+
+ /// Creates a new value of type Self with the cross axis modified by the callback provided
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn map_cross(self, direction: FlexDirection, mapper: impl FnOnce(T) -> T) -> Self {
+ let mut new = self;
+ if direction.is_row() {
+ new.height = mapper(new.height);
+ } else {
+ new.width = mapper(new.width);
+ }
+ new
+ }
+
+ /// Gets the extent of the main layout axis
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn main(self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.width
+ } else {
+ self.height
+ }
+ }
+
+ /// Gets the extent of the cross layout axis
+ ///
+ /// Whether this is the width or height depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn cross(self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.height
+ } else {
+ self.width
+ }
+ }
+
+ /// Gets the extent of the specified layout axis
+ /// Whether this is the width or height depends on the `GridAxis` provided
+ #[cfg(feature = "grid")]
+ pub(crate) fn get(self, axis: AbstractAxis) -> T {
+ match axis {
+ AbstractAxis::Inline => self.width,
+ AbstractAxis::Block => self.height,
+ }
+ }
+
+ /// Sets the extent of the specified layout axis
+ /// Whether this is the width or height depends on the `GridAxis` provided
+ #[cfg(feature = "grid")]
+ pub(crate) fn set(&mut self, axis: AbstractAxis, value: T) {
+ match axis {
+ AbstractAxis::Inline => self.width = value,
+ AbstractAxis::Block => self.height = value,
+ }
+ }
+
+ /// Sets the extent of the specified layout axis
+ /// Whether this is the width or height depends on the `GridAxis` provided
+ #[cfg(feature = "grid")]
+ pub(crate) fn with(mut self, axis: AbstractAxis, value: T) -> Self {
+ match axis {
+ AbstractAxis::Inline => self.width = value,
+ AbstractAxis::Block => self.height = value,
+ }
+ self
+ }
+}
+
+impl Size<f32> {
+ /// A [`Size`] with zero width and height
+ pub const ZERO: Size<f32> = Self { width: 0.0, height: 0.0 };
+
+ /// Applies f32_max to each component separately
+ #[inline(always)]
+ pub fn f32_max(self, rhs: Size<f32>) -> Size<f32> {
+ Size { width: f32_max(self.width, rhs.width), height: f32_max(self.height, rhs.height) }
+ }
+
+ /// Applies f32_min to each component separately
+ #[inline(always)]
+ pub fn f32_min(self, rhs: Size<f32>) -> Size<f32> {
+ Size { width: f32_min(self.width, rhs.width), height: f32_min(self.height, rhs.height) }
+ }
+
+ /// Return true if both width and height are greater than 0 else false
+ #[inline(always)]
+ pub fn has_non_zero_area(self) -> bool {
+ self.width > 0.0 && self.height > 0.0
+ }
+}
+
+impl Size<Option<f32>> {
+ /// A [`Size`] with `None` width and height
+ pub const NONE: Size<Option<f32>> = Self { width: None, height: None };
+
+ /// A [`Size<Option<f32>>`] with `Some(width)` and `Some(height)` as parameters
+ #[must_use]
+ pub const fn new(width: f32, height: f32) -> Self {
+ Size { width: Some(width), height: Some(height) }
+ }
+
+ /// Creates a new [`Size<Option<f32>>`] with either the width or height set based on the provided `direction`
+ #[cfg(feature = "flexbox")]
+ pub const fn from_cross(direction: FlexDirection, value: Option<f32>) -> Self {
+ let mut new = Self::NONE;
+ if direction.is_row() {
+ new.height = value
+ } else {
+ new.width = value
+ }
+ new
+ }
+
+ /// Applies aspect_ratio (if one is supplied) to the Size:
+ /// - If width is `Some` but height is `None`, then height is computed from width and aspect_ratio
+ /// - If height is `Some` but width is `None`, then width is computed from height and aspect_ratio
+ ///
+ /// If aspect_ratio is `None` then this function simply returns self.
+ pub fn maybe_apply_aspect_ratio(self, aspect_ratio: Option<f32>) -> Size<Option<f32>> {
+ match aspect_ratio {
+ Some(ratio) => match (self.width, self.height) {
+ (Some(width), None) => Size { width: Some(width), height: Some(width / ratio) },
+ (None, Some(height)) => Size { width: Some(height * ratio), height: Some(height) },
+ _ => self,
+ },
+ None => self,
+ }
+ }
+}
+
+impl<T> Size<Option<T>> {
+ /// Performs Option::unwrap_or on each component separately
+ pub fn unwrap_or(self, alt: Size<T>) -> Size<T> {
+ Size { width: self.width.unwrap_or(alt.width), height: self.height.unwrap_or(alt.height) }
+ }
+
+ /// Performs Option::or on each component separately
+ pub fn or(self, alt: Size<Option<T>>) -> Size<Option<T>> {
+ Size { width: self.width.or(alt.width), height: self.height.or(alt.height) }
+ }
+
+ /// Return true if both components are Some, else false.
+ #[inline(always)]
+ pub fn both_axis_defined(&self) -> bool {
+ self.width.is_some() && self.height.is_some()
+ }
+}
+
+impl Size<Dimension> {
+ /// Generates a [`Size<Dimension>`] using length values
+ #[must_use]
+ pub const fn from_lengths(width: f32, height: f32) -> Self {
+ Size { width: Dimension(CompactLength::length(width)), height: Dimension(CompactLength::length(height)) }
+ }
+
+ /// Generates a [`Size<Dimension>`] using percentage values
+ #[must_use]
+ pub const fn from_percent(width: f32, height: f32) -> Self {
+ Size { width: Dimension(CompactLength::percent(width)), height: Dimension(CompactLength::percent(height)) }
+ }
+}
+
+/// A 2-dimensional coordinate.
+///
+/// When used in association with a [`Rect`], represents the top-left corner.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct Point<T> {
+ /// The x-coordinate
+ pub x: T,
+ /// The y-coordinate
+ pub y: T,
+}
+
+impl Point<f32> {
+ /// A [`Point`] with values (0,0), representing the origin
+ pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
+}
+
+impl Point<Option<f32>> {
+ /// A [`Point`] with values (None, None)
+ pub const NONE: Self = Self { x: None, y: None };
+}
+
+// Generic Add impl for Point<T> + Point<U> where T + U has an Add impl
+impl<U, T: Add<U>> Add<Point<U>> for Point<T> {
+ type Output = Point<<T as Add<U>>::Output>;
+
+ fn add(self, rhs: Point<U>) -> Self::Output {
+ Point { x: self.x + rhs.x, y: self.y + rhs.y }
+ }
+}
+
+impl<T> Point<T> {
+ /// Applies the function `f` to both the x and y
+ ///
+ /// This is used to transform a `Point<T>` into a `Point<R>`.
+ pub fn map<R, F>(self, f: F) -> Point<R>
+ where
+ F: Fn(T) -> R,
+ {
+ Point { x: f(self.x), y: f(self.y) }
+ }
+
+ /// Gets the extent of the specified layout axis
+ /// Whether this is the width or height depends on the `GridAxis` provided
+ #[cfg(feature = "grid")]
+ pub fn get(self, axis: AbstractAxis) -> T {
+ match axis {
+ AbstractAxis::Inline => self.x,
+ AbstractAxis::Block => self.y,
+ }
+ }
+
+ /// Swap x and y components
+ pub fn transpose(self) -> Point<T> {
+ Point { x: self.y, y: self.x }
+ }
+
+ /// Sets the extent of the specified layout axis
+ /// Whether this is the width or height depends on the `GridAxis` provided
+ #[cfg(feature = "grid")]
+ pub fn set(&mut self, axis: AbstractAxis, value: T) {
+ match axis {
+ AbstractAxis::Inline => self.x = value,
+ AbstractAxis::Block => self.y = value,
+ }
+ }
+
+ /// Gets the component in the main layout axis
+ ///
+ /// Whether this is the x or y depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn main(self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.x
+ } else {
+ self.y
+ }
+ }
+
+ /// Gets the component in the cross layout axis
+ ///
+ /// Whether this is the x or y depends on the `direction` provided
+ #[cfg(feature = "flexbox")]
+ pub(crate) fn cross(self, direction: FlexDirection) -> T {
+ if direction.is_row() {
+ self.y
+ } else {
+ self.x
+ }
+ }
+}
+
+impl<T> From<Point<T>> for Size<T> {
+ fn from(value: Point<T>) -> Self {
+ Size { width: value.x, height: value.y }
+ }
+}
+
+/// Generic struct which holds a "min" value and a "max" value
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct MinMax<Min, Max> {
+ /// The value representing the minimum
+ pub min: Min,
+ /// The value representing the maximum
+ pub max: Max,
+}
diff --git a/vendor/taffy/src/lib.rs b/vendor/taffy/src/lib.rs
new file mode 100644
index 00000000..c18fa644
--- /dev/null
+++ b/vendor/taffy/src/lib.rs
@@ -0,0 +1,133 @@
+//! # Taffy
+//!
+//! Taffy is a flexible, high-performance library for **UI layout**.
+//! It currently implements the Flexbox, Grid and Block layout algorithms from the CSS specification. Support for other paradigms is planned.
+//! For more information on this and other future development plans see the [roadmap issue](https://github.com/DioxusLabs/taffy/issues/345).
+//!
+//! ## Architecture
+//!
+//! Taffy is based on a tree of "UI nodes" similar to the tree of DOM nodes that one finds in web-based UI. Each node has:
+//! - A [`Style`] struct which holds a set of CSS styles which function as the primary input to the layout computations.
+//! - A [`Layout`] struct containing a position (x/y) and a size (width/height) which function as the output of the layout computations.
+//! - Optionally:
+//! - A `Vec` set of child nodes
+//! - "Context": arbitrary user-defined data (which you can access when using a "measure function" to integrate Taffy with other kinds of layout such as text layout)
+//!
+//! Usage of Taffy consists of constructing a tree of UI nodes (with associated styles, children and context), then calling function(s)
+//! from Taffy to translate those styles, parent-child relationships and measure functions into a size and position in 2d space for each node
+//! in the tree.
+//!
+//! ## High-level API vs. Low-level API
+//!
+//! Taffy has two APIs: a high-level API that is simpler and easier to get started with, and a low-level API that is more flexible gives greater control.
+//! We would generally recommend the high-level API for users using Taffy standalone and the low-level API for users wanting to embed Taffy as part of
+//! a wider layout system or as part of a UI framework that already has it's own node/widget tree representation.
+//!
+//! ### High-level API
+//!
+//! The high-level API consists of the [`TaffyTree`] struct which contains a tree implementation and provides methods that allow you to construct
+//! a tree of UI nodes. Once constructed, you can call the [`compute_layout_with_measure`](crate::TaffyTree::compute_layout_with_measure) method to compute the layout (passing in a "measure function" closure which is used to compute the size of leaf nodes), and then access
+//! the layout of each node using the [`layout`](crate::TaffyTree::layout) method.
+//!
+//! When using the high-level API, Taffy will take care of node storage, caching and dispatching to the correct layout algorithm for a given node for you.
+//! See the [`TaffyTree`] struct for more details on this API.
+//!
+//! Examples which show usage of the high-level API include:
+//!
+//! - [basic](https://github.com/DioxusLabs/taffy/blob/main/examples/basic.rs)
+//! - [flexbox_gap](https://github.com/DioxusLabs/taffy/blob/main/examples/flexbox_gap.rs)
+//! - [grid_holy_grail](https://github.com/DioxusLabs/taffy/blob/main/examples/grid_holy_grail.rs)
+//! - [measure](https://github.com/DioxusLabs/taffy/blob/main/examples/measure.rs)
+//! - [parley](https://github.com/DioxusLabs/taffy/blob/main/examples/parley/src/main.rs)
+//!
+//! In particular, the "measure" example shows how to integrate Taffy layout with other layout modalities such as text or image layout when using the high level API.
+//!
+//! ### Low-level API
+//!
+//! The low-level API consists of a [set of traits](crate::tree::traits) (notably the [`LayoutPartialTree`] trait) which define an interface behind which you must implement your own
+//! tree implementation, and a [set of functions](crate::compute) such as [`compute_flexbox_layout`] and [`compute_grid_layout`] which implement the layout algorithms (for a single node at a time), and are designed to be flexible
+//! and easy to integrate into a wider layout or UI system.
+//!
+//! When using this API, you must handle node storage, caching, and dispatching to the correct layout algorithm for a given node yourself.
+//! See the [`crate::tree::traits`] module for more details on this API.
+//!
+//! Examples which show usage of the low-level API are:
+//!
+//! - [custom_tree_vec](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_vec.rs) which implements a custom Taffy tree using a `Vec` as an arena with NodeId's being index's into the Vec.
+//! - [custom_tree_owned_partial](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_partial.rs) which implements a custom Taffy tree using directly owned children with NodeId's being index's into vec on parent node.
+//! - [custom_tree_owned_unsafe](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_unsafe.rs) which implements a custom Taffy tree using directly owned children with NodeId's being pointers.
+
+// document the feature flags for the crate by extracting the comments from Cargo.toml
+#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
+// annotate items with their required features (gated by docsrs flag as this requires the nightly toolchain)
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![cfg_attr(not(feature = "std"), no_std)]
+#![deny(unsafe_code)]
+#![warn(missing_docs)]
+#![warn(clippy::missing_docs_in_private_items)]
+// Disable "unused_x" warnings when default features aren't enabled.
+#![cfg_attr(not(feature = "default"), allow(dead_code))]
+#![cfg_attr(not(feature = "default"), allow(unused_imports))]
+#![cfg_attr(not(feature = "default"), allow(unused_variables))]
+#![cfg_attr(not(feature = "default"), allow(unused_mut))]
+
+// We always need std for the tests
+// See <https://github.com/la10736/rstest/issues/149#issuecomment-1156402989>
+#[cfg(all(test, not(feature = "std")))]
+#[macro_use]
+extern crate std;
+
+#[cfg(not(feature = "std"))]
+extern crate alloc;
+
+#[cfg_attr(feature = "serde", macro_use)]
+#[cfg(feature = "serde")]
+extern crate serde;
+
+pub mod compute;
+pub mod geometry;
+pub mod prelude;
+pub mod style;
+pub mod style_helpers;
+pub mod tree;
+#[macro_use]
+pub mod util;
+
+mod readme_doctest {
+ #![doc = include_str!("../README.md")]
+}
+
+#[cfg(feature = "flexbox")]
+#[doc(inline)]
+pub use crate::compute::compute_flexbox_layout;
+#[cfg(feature = "grid")]
+#[doc(inline)]
+pub use crate::compute::compute_grid_layout;
+pub use crate::compute::detailed_info::*;
+#[cfg(feature = "block_layout")]
+#[doc(inline)]
+pub use crate::compute::{compute_block_align_content_offset, compute_block_layout};
+#[doc(inline)]
+pub use crate::compute::{
+ compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_oof_layout, compute_oof_layout_for_area,
+ compute_root_layout, resolve_static_offset, round_layout, OofLayoutResult,
+};
+#[doc(inline)]
+pub use crate::style::Style;
+#[doc(inline)]
+pub use crate::tree::traits::*;
+#[cfg(feature = "taffy_tree")]
+#[doc(inline)]
+pub use crate::tree::TaffyTree;
+#[cfg(feature = "std")]
+#[doc(inline)]
+pub use crate::util::print_tree;
+
+#[cfg(feature = "parse")]
+pub use parse::{ParseError, ParseResult};
+
+pub use crate::compute::*;
+pub use crate::geometry::*;
+pub use crate::style::*;
+pub use crate::tree::*;
+pub use crate::util::*;
diff --git a/vendor/taffy/src/prelude.rs b/vendor/taffy/src/prelude.rs
new file mode 100644
index 00000000..cc3381d4
--- /dev/null
+++ b/vendor/taffy/src/prelude.rs
@@ -0,0 +1,31 @@
+//! Commonly used types
+
+pub use crate::{
+ geometry::{Line, Rect, Size},
+ style::{
+ AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
+ BoxSizing, CompactLength, Dimension, Display, JustifyContent, JustifyItems, JustifySelf, LengthPercentage,
+ LengthPercentageAuto, Position, Style,
+ },
+ style_helpers::{
+ auto, fit_content, length, max_content, min_content, percent, zero, FromFr, FromLength, FromPercent, TaffyAuto,
+ TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero,
+ },
+ tree::{Layout, LayoutPartialTree, NodeId, PrintTree, RoundTree, TraversePartialTree, TraverseTree},
+};
+
+#[cfg(feature = "flexbox")]
+pub use crate::style::{FlexDirection, FlexWrap};
+
+#[cfg(feature = "grid")]
+pub use crate::style::{
+ GridAutoFlow, GridPlacement, GridTemplateComponent, MaxTrackSizingFunction, MinTrackSizingFunction,
+ RepetitionCount, TrackSizingFunction,
+};
+#[cfg(feature = "grid")]
+pub use crate::style_helpers::{
+ evenly_sized_tracks, flex, fr, line, minmax, repeat, span, TaffyGridLine, TaffyGridSpan,
+};
+
+#[cfg(feature = "taffy_tree")]
+pub use crate::TaffyTree;
diff --git a/vendor/taffy/src/style/alignment.rs b/vendor/taffy/src/style/alignment.rs
new file mode 100644
index 00000000..a6aa4533
--- /dev/null
+++ b/vendor/taffy/src/style/alignment.rs
@@ -0,0 +1,979 @@
+//! Style types for controlling alignment.
+//!
+//! The public alignment types ([`AlignItems`], [`AlignContent`], and their aliases) are
+//! structs with two orthogonal fields: a *position* keyword
+//! ([`AlignItemsKeyword`] / [`AlignContentKeyword`]) and an *overflow-position*
+//! modifier ([`AlignmentSafety`]). The pre-existing CSS spellings — `Start`, `End`,
+//! `FlexStart`, `FlexEnd`, `Center`, `Stretch`, `SpaceBetween`, …, `SafeStart`,
+//! `SafeEnd`, `SafeFlexStart`, `SafeFlexEnd`, `SafeCenter` — are exposed as associated
+//! constants on the structs, so call sites read identically to the previous enum form.
+
+#[cfg(feature = "parse")]
+use crate::util::parse::{CssParseResult, FromCss, Parser, Token};
+
+use crate::style::Direction;
+
+/// The position-keyword half of [`AlignItems`] (and its aliases `AlignSelf`,
+/// `JustifyItems`, `JustifySelf`).
+///
+/// Compute paths match on this enum directly so every match is exhaustive and
+/// requires no `Safe*` siblings.
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[repr(u8)]
+pub enum AlignItemsKeyword {
+ /// The layout mode's default alignment: usually `Stretch`, but `Start` in some cases.
+ #[default]
+ Normal,
+ /// Items are packed toward the start of the axis.
+ Start,
+ /// Items are packed toward the end of the axis.
+ End,
+ /// Items are packed towards the flex-relative start of the axis.
+ ///
+ /// For flex containers with flex_direction RowReverse or ColumnReverse this is
+ /// equivalent to End. In all other cases it is equivalent to Start.
+ FlexStart,
+ /// Items are packed towards the flex-relative end of the axis.
+ ///
+ /// For flex containers with flex_direction RowReverse or ColumnReverse this is
+ /// equivalent to Start. In all other cases it is equivalent to End.
+ FlexEnd,
+ /// Items are packed toward the start of the axis as determined by the item's own
+ /// writing mode/direction (rather than the container's).
+ ///
+ /// Equivalent to Start when the item's `direction` matches the container's, and
+ /// to End when they differ (in the inline axis).
+ SelfStart,
+ /// Items are packed toward the end of the axis as determined by the item's own
+ /// writing mode/direction (rather than the container's).
+ ///
+ /// Equivalent to End when the item's `direction` matches the container's, and
+ /// to Start when they differ (in the inline axis).
+ SelfEnd,
+ /// Items are packed along the center of the cross axis.
+ Center,
+ /// Items are aligned such as their baselines align.
+ Baseline,
+ /// Stretch to fill the container.
+ Stretch,
+}
+
+/// The position-keyword half of [`AlignContent`] (and its alias `JustifyContent`).
+///
+/// Compute paths match on this enum directly so every match is exhaustive and
+/// requires no `Safe*` siblings.
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[repr(u8)]
+pub enum AlignContentKeyword {
+ /// The layout mode's default alignment: `Stretch` for flex and grid containers, `Start`
+ /// for block containers.
+ #[default]
+ Normal,
+ /// Items are packed toward the start of the axis.
+ Start,
+ /// Items are packed toward the end of the axis.
+ End,
+ /// Items are packed towards the flex-relative start of the axis.
+ FlexStart,
+ /// Items are packed towards the flex-relative end of the axis.
+ FlexEnd,
+ /// Items are centered around the middle of the axis.
+ Center,
+ /// Items are stretched to fill the container.
+ Stretch,
+ /// The first and last items are aligned flush with the edges of the container
+ /// (no gap). The gap between items is distributed evenly.
+ SpaceBetween,
+ /// The gap between the first and last items is exactly THE SAME as the gap
+ /// between items. The gaps are distributed evenly.
+ SpaceEvenly,
+ /// The gap between the first and last items is exactly HALF the gap between
+ /// items. The gaps are distributed evenly in proportion to these ratios.
+ SpaceAround,
+}
+
+impl AlignContentKeyword {
+ /// Returns the reversed keyword for RTL (right-to-left) contexts: `Start`↔`End`,
+ /// `FlexStart`↔`FlexEnd`. `Stretch` maps to `End` to preserve the layout
+ /// algorithms' historical handling. `Normal`, `Center` and the distribution keywords
+ /// (`SpaceBetween`, `SpaceEvenly`, `SpaceAround`) are unaffected because their
+ /// visual placement is direction-symmetric.
+ pub(crate) fn reversed(self) -> Self {
+ match self {
+ Self::Start => Self::End,
+ Self::End => Self::Start,
+ Self::FlexStart => Self::FlexEnd,
+ Self::FlexEnd => Self::FlexStart,
+ Self::Stretch => Self::End,
+ Self::Normal | Self::Center | Self::SpaceBetween | Self::SpaceEvenly | Self::SpaceAround => self,
+ }
+ }
+}
+
+/// The overflow-position modifier per [CSS Box Alignment §4.3][css-align-overflow].
+///
+/// `Safe` falls back to start-edge alignment when the alignment subject would
+/// overflow the alignment container, so the start of the content stays visible.
+/// `Unsafe` keeps the requested alignment even when that causes overflow at the
+/// start edge. `Default` (no overflow-position keyword specified) behaves as
+/// `Unsafe`, except for absolutely positioned boxes whose alignment is instead
+/// adjusted to minimize overflow per [CSS Box Alignment §4.4.1.2][css-align-abspos].
+///
+/// CSS only defines `safe` / `unsafe` against the position values `start`, `end`,
+/// `flex-start`, `flex-end`, `center`. The struct shape does not enforce that
+/// constraint at the type level — the parser rejects invalid combinations, and
+/// the compute pass treats `Safe` paired with a non-position keyword (`Stretch`,
+/// `Baseline`, `Space*`) the same as `Unsafe`.
+///
+/// [css-align-overflow]: https://www.w3.org/TR/css-align-3/#overflow-values
+/// [css-align-abspos]: https://www.w3.org/TR/css-align-3/#auto-safety-position
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[repr(u8)]
+pub enum AlignmentSafety {
+ /// No overflow-position keyword specified. Behaves as `Unsafe`, except for absolutely
+ /// positioned boxes, whose alignment is adjusted to minimize overflow of their
+ /// containing block.
+ #[default]
+ Default,
+ /// Keeps the requested alignment even when the subject overflows the alignment
+ /// container at the start edge.
+ Unsafe,
+ /// Falls back to the start edge when the subject would overflow, to avoid data
+ /// loss.
+ Safe,
+}
+
+/// Used to control how child nodes are aligned.
+/// For Flexbox it controls alignment in the cross axis.
+/// For Grid it controls alignment in the block axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+pub struct AlignItems {
+ /// Position keyword.
+ pub keyword: AlignItemsKeyword,
+ /// Overflow-position modifier (`safe` / `unsafe`).
+ pub safety: AlignmentSafety,
+}
+
+impl AlignItems {
+ /// The layout mode's default alignment. See [`AlignItemsKeyword::Normal`].
+ pub const NORMAL: Self = Self { keyword: AlignItemsKeyword::Normal, safety: AlignmentSafety::Default };
+ /// Items are packed toward the start of the axis.
+ pub const START: Self = Self { keyword: AlignItemsKeyword::Start, safety: AlignmentSafety::Default };
+ /// Items are packed toward the end of the axis.
+ pub const END: Self = Self { keyword: AlignItemsKeyword::End, safety: AlignmentSafety::Default };
+ /// Items are packed towards the flex-relative start of the axis.
+ pub const FLEX_START: Self = Self { keyword: AlignItemsKeyword::FlexStart, safety: AlignmentSafety::Default };
+ /// Items are packed towards the flex-relative end of the axis.
+ pub const FLEX_END: Self = Self { keyword: AlignItemsKeyword::FlexEnd, safety: AlignmentSafety::Default };
+ /// Items are packed toward the start of the axis as determined by the item's own direction.
+ pub const SELF_START: Self = Self { keyword: AlignItemsKeyword::SelfStart, safety: AlignmentSafety::Default };
+ /// Items are packed toward the end of the axis as determined by the item's own direction.
+ pub const SELF_END: Self = Self { keyword: AlignItemsKeyword::SelfEnd, safety: AlignmentSafety::Default };
+ /// Items are packed along the center of the cross axis.
+ pub const CENTER: Self = Self { keyword: AlignItemsKeyword::Center, safety: AlignmentSafety::Default };
+ /// Items are aligned such as their baselines align.
+ pub const BASELINE: Self = Self { keyword: AlignItemsKeyword::Baseline, safety: AlignmentSafety::Default };
+ /// Stretch to fill the container.
+ pub const STRETCH: Self = Self { keyword: AlignItemsKeyword::Stretch, safety: AlignmentSafety::Default };
+ /// Like [`AlignItems::START`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_START: Self = Self { keyword: AlignItemsKeyword::Start, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::END`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_END: Self = Self { keyword: AlignItemsKeyword::End, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::FLEX_START`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_FLEX_START: Self = Self { keyword: AlignItemsKeyword::FlexStart, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::FLEX_END`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_FLEX_END: Self = Self { keyword: AlignItemsKeyword::FlexEnd, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::CENTER`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_CENTER: Self = Self { keyword: AlignItemsKeyword::Center, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::SELF_START`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_SELF_START: Self = Self { keyword: AlignItemsKeyword::SelfStart, safety: AlignmentSafety::Safe };
+ /// Like [`AlignItems::SELF_END`], but falls back to [`AlignItems::START`] when the
+ /// alignment subject overflows the alignment container, to avoid data loss.
+ pub const SAFE_SELF_END: Self = Self { keyword: AlignItemsKeyword::SelfEnd, safety: AlignmentSafety::Safe };
+
+ /// Returns `true` iff this carries the `safe` overflow-position modifier.
+ #[inline]
+ pub const fn is_safe(self) -> bool {
+ matches!(self.safety, AlignmentSafety::Safe)
+ }
+
+ /// Returns this alignment with the given overflow-position modifier.
+ #[inline]
+ pub const fn with_safety(self, safety: AlignmentSafety) -> Self {
+ Self { keyword: self.keyword, safety }
+ }
+
+ /// Returns the underlying position keyword, discarding the safety modifier.
+ #[inline]
+ pub const fn keyword(self) -> AlignItemsKeyword {
+ self.keyword
+ }
+
+ /// Returns true if the keyword is `Stretch` or `Normal` (ignoring any overflow-position
+ /// modifier).
+ #[inline(always)]
+ pub const fn is_stretch_or_normal(self) -> bool {
+ matches!(self.keyword, AlignItemsKeyword::Stretch | AlignItemsKeyword::Normal)
+ }
+
+ /// Resolve the writing-mode-relative `SelfStart`/`SelfEnd` keywords to `Start`/`End`
+ /// based on the item's own `direction` per CSS Box Alignment §5.2
+ /// <https://www.w3.org/TR/css-align-3/#self-alignment>. All other keywords are
+ /// returned unchanged.
+ ///
+ /// The `Start`/`End` keywords used by the compute paths are relative to the
+ /// *container's* writing mode/direction, so in the inline axis `SelfStart` resolves
+ /// to `Start` when the item's direction matches the container's and to `End` when it
+ /// differs. Taffy only supports the `horizontal-tb` writing mode, so in the block
+ /// axis `SelfStart`/`SelfEnd` always resolve to `Start`/`End` respectively.
+ #[inline]
+ pub fn resolve_self_relative(
+ self,
+ item_direction: Direction,
+ container_direction: Direction,
+ axis_is_inline: bool,
+ ) -> Self {
+ let flip = axis_is_inline && item_direction != container_direction;
+ let keyword = match self.keyword {
+ AlignItemsKeyword::SelfStart => {
+ if flip {
+ AlignItemsKeyword::End
+ } else {
+ AlignItemsKeyword::Start
+ }
+ }
+ AlignItemsKeyword::SelfEnd => {
+ if flip {
+ AlignItemsKeyword::Start
+ } else {
+ AlignItemsKeyword::End
+ }
+ }
+ other => other,
+ };
+ Self { keyword, safety: self.safety }
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for AlignItems {
+ fn from_css<'i>(input: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let first = input.expect_ident()?.clone();
+ cssparser::match_ignore_ascii_case! { &*first,
+ "safe" => {
+ let pos = input.expect_ident()?.clone();
+ cssparser::match_ignore_ascii_case! { &*pos,
+ "start" => Ok(Self::SAFE_START),
+ "end" => Ok(Self::SAFE_END),
+ "flex-start" => Ok(Self::SAFE_FLEX_START),
+ "flex-end" => Ok(Self::SAFE_FLEX_END),
+ "self-start" => Ok(Self::SAFE_SELF_START),
+ "self-end" => Ok(Self::SAFE_SELF_END),
+ "center" => Ok(Self::SAFE_CENTER),
+ _ => Err(input.new_unexpected_token_error(Token::Ident(pos))),
+ }
+ },
+ "unsafe" => {
+ let pos = input.expect_ident()?.clone();
+ let keyword = cssparser::match_ignore_ascii_case! { &*pos,
+ "start" => AlignItemsKeyword::Start,
+ "end" => AlignItemsKeyword::End,
+ "flex-start" => AlignItemsKeyword::FlexStart,
+ "flex-end" => AlignItemsKeyword::FlexEnd,
+ "self-start" => AlignItemsKeyword::SelfStart,
+ "self-end" => AlignItemsKeyword::SelfEnd,
+ "center" => AlignItemsKeyword::Center,
+ _ => return Err(input.new_unexpected_token_error(Token::Ident(pos))),
+ };
+ Ok(Self { keyword, safety: AlignmentSafety::Unsafe })
+ },
+ "normal" => Ok(Self::NORMAL),
+ "start" => Ok(Self::START),
+ "end" => Ok(Self::END),
+ "flex-start" => Ok(Self::FLEX_START),
+ "flex-end" => Ok(Self::FLEX_END),
+ "self-start" => Ok(Self::SELF_START),
+ "self-end" => Ok(Self::SELF_END),
+ "center" => Ok(Self::CENTER),
+ "baseline" => Ok(Self::BASELINE),
+ "stretch" => Ok(Self::STRETCH),
+ _ => Err(input.new_unexpected_token_error(Token::Ident(first))),
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::from_str_from_css!(AlignItems);
+
+/// Used to control how child nodes are aligned.
+/// Does not apply to Flexbox, and will be ignored if specified on a flex container.
+/// For Grid it controls alignment in the inline axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
+pub type JustifyItems = AlignItems;
+/// Controls alignment of an individual node.
+///
+/// Overrides the parent Node's `AlignItems` property.
+/// For Flexbox it controls alignment in the cross axis.
+/// For Grid it controls alignment in the block axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
+pub type AlignSelf = AlignItems;
+/// Controls alignment of an individual node.
+///
+/// Overrides the parent Node's `JustifyItems` property.
+/// Does not apply to Flexbox, and will be ignored if specified on a flex child.
+/// For Grid it controls alignment in the inline axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
+pub type JustifySelf = AlignItems;
+
+/// Sets the distribution of space between and around content items.
+/// For Flexbox it controls alignment in the cross axis.
+/// For Grid it controls alignment in the block axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+pub struct AlignContent {
+ /// Position keyword.
+ pub keyword: AlignContentKeyword,
+ /// Overflow-position modifier (`safe` / `unsafe`).
+ pub safety: AlignmentSafety,
+}
+
+impl AlignContent {
+ /// The layout mode's default alignment. See [`AlignContentKeyword::Normal`].
+ pub const NORMAL: Self = Self { keyword: AlignContentKeyword::Normal, safety: AlignmentSafety::Default };
+ /// Items are packed toward the start of the axis.
+ pub const START: Self = Self { keyword: AlignContentKeyword::Start, safety: AlignmentSafety::Default };
+ /// Items are packed toward the end of the axis.
+ pub const END: Self = Self { keyword: AlignContentKeyword::End, safety: AlignmentSafety::Default };
+ /// Items are packed towards the flex-relative start of the axis.
+ pub const FLEX_START: Self = Self { keyword: AlignContentKeyword::FlexStart, safety: AlignmentSafety::Default };
+ /// Items are packed towards the flex-relative end of the axis.
+ pub const FLEX_END: Self = Self { keyword: AlignContentKeyword::FlexEnd, safety: AlignmentSafety::Default };
+ /// Items are centered around the middle of the axis.
+ pub const CENTER: Self = Self { keyword: AlignContentKeyword::Center, safety: AlignmentSafety::Default };
+ /// Items are stretched to fill the container.
+ pub const STRETCH: Self = Self { keyword: AlignContentKeyword::Stretch, safety: AlignmentSafety::Default };
+ /// The first and last items are aligned flush with the edges of the container.
+ pub const SPACE_BETWEEN: Self =
+ Self { keyword: AlignContentKeyword::SpaceBetween, safety: AlignmentSafety::Default };
+ /// The gap between the first and last items equals the gap between items.
+ pub const SPACE_EVENLY: Self = Self { keyword: AlignContentKeyword::SpaceEvenly, safety: AlignmentSafety::Default };
+ /// The gap between the first and last items is half the gap between items.
+ pub const SPACE_AROUND: Self = Self { keyword: AlignContentKeyword::SpaceAround, safety: AlignmentSafety::Default };
+ /// Like [`AlignContent::START`], but falls back to [`AlignContent::START`] when the
+ /// content overflows the alignment container, to avoid data loss.
+ pub const SAFE_START: Self = Self { keyword: AlignContentKeyword::Start, safety: AlignmentSafety::Safe };
+ /// Like [`AlignContent::END`], but falls back to [`AlignContent::START`] when the
+ /// content overflows the alignment container, to avoid data loss.
+ pub const SAFE_END: Self = Self { keyword: AlignContentKeyword::End, safety: AlignmentSafety::Safe };
+ /// Like [`AlignContent::FLEX_START`], but falls back to [`AlignContent::START`] when
+ /// the content overflows the alignment container, to avoid data loss.
+ pub const SAFE_FLEX_START: Self = Self { keyword: AlignContentKeyword::FlexStart, safety: AlignmentSafety::Safe };
+ /// Like [`AlignContent::FLEX_END`], but falls back to [`AlignContent::START`] when the
+ /// content overflows the alignment container, to avoid data loss.
+ pub const SAFE_FLEX_END: Self = Self { keyword: AlignContentKeyword::FlexEnd, safety: AlignmentSafety::Safe };
+ /// Like [`AlignContent::CENTER`], but falls back to [`AlignContent::START`] when the
+ /// content overflows the alignment container, to avoid data loss.
+ pub const SAFE_CENTER: Self = Self { keyword: AlignContentKeyword::Center, safety: AlignmentSafety::Safe };
+
+ /// Returns `true` iff this carries the `safe` overflow-position modifier.
+ #[inline]
+ pub const fn is_safe(self) -> bool {
+ matches!(self.safety, AlignmentSafety::Safe)
+ }
+
+ /// Returns this alignment with the given overflow-position modifier.
+ #[inline]
+ pub const fn with_safety(self, safety: AlignmentSafety) -> Self {
+ Self { keyword: self.keyword, safety }
+ }
+
+ /// Returns the underlying position keyword, discarding the safety modifier.
+ #[inline]
+ pub const fn keyword(self) -> AlignContentKeyword {
+ self.keyword
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for AlignContent {
+ fn from_css<'i>(input: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let first = input.expect_ident()?.clone();
+ cssparser::match_ignore_ascii_case! { &*first,
+ "safe" => {
+ let pos = input.expect_ident()?.clone();
+ cssparser::match_ignore_ascii_case! { &*pos,
+ "start" => Ok(Self::SAFE_START),
+ "end" => Ok(Self::SAFE_END),
+ "flex-start" => Ok(Self::SAFE_FLEX_START),
+ "flex-end" => Ok(Self::SAFE_FLEX_END),
+ "center" => Ok(Self::SAFE_CENTER),
+ _ => Err(input.new_unexpected_token_error(Token::Ident(pos))),
+ }
+ },
+ "unsafe" => {
+ let pos = input.expect_ident()?.clone();
+ let keyword = cssparser::match_ignore_ascii_case! { &*pos,
+ "start" => AlignContentKeyword::Start,
+ "end" => AlignContentKeyword::End,
+ "flex-start" => AlignContentKeyword::FlexStart,
+ "flex-end" => AlignContentKeyword::FlexEnd,
+ "center" => AlignContentKeyword::Center,
+ _ => return Err(input.new_unexpected_token_error(Token::Ident(pos))),
+ };
+ Ok(Self { keyword, safety: AlignmentSafety::Unsafe })
+ },
+ "normal" => Ok(Self::NORMAL),
+ "start" => Ok(Self::START),
+ "end" => Ok(Self::END),
+ "flex-start" => Ok(Self::FLEX_START),
+ "flex-end" => Ok(Self::FLEX_END),
+ "center" => Ok(Self::CENTER),
+ "stretch" => Ok(Self::STRETCH),
+ "space-between" => Ok(Self::SPACE_BETWEEN),
+ "space-evenly" => Ok(Self::SPACE_EVENLY),
+ "space-around" => Ok(Self::SPACE_AROUND),
+ _ => Err(input.new_unexpected_token_error(Token::Ident(first))),
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::from_str_from_css!(AlignContent);
+
+/// Sets the distribution of space between and around content items.
+/// For Flexbox it controls alignment in the main axis.
+/// For Grid it controls alignment in the inline axis.
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
+pub type JustifyContent = AlignContent;
+
+// ---------------------------------------------------------------------------
+// Serde — custom impls preserve the pre-struct wire format (single tag string
+// per public spelling) so consumers reading data serialized before the refactor
+// continue to deserialize correctly.
+// ---------------------------------------------------------------------------
+
+/// Canonical tag-string set accepted by [`AlignItems`] serde deserialization, used in
+/// `unknown_variant` errors. Mirrors the spellings produced by `Serialize`.
+#[cfg(feature = "serde")]
+const ALIGN_ITEMS_NAMES: &[&str] = &[
+ "Normal",
+ "Start",
+ "End",
+ "FlexStart",
+ "FlexEnd",
+ "SelfStart",
+ "SelfEnd",
+ "Center",
+ "Baseline",
+ "Stretch",
+ "SafeStart",
+ "SafeEnd",
+ "SafeFlexStart",
+ "SafeFlexEnd",
+ "SafeSelfStart",
+ "SafeSelfEnd",
+ "SafeCenter",
+ "UnsafeStart",
+ "UnsafeEnd",
+ "UnsafeFlexStart",
+ "UnsafeFlexEnd",
+ "UnsafeSelfStart",
+ "UnsafeSelfEnd",
+ "UnsafeCenter",
+];
+
+#[cfg(feature = "serde")]
+impl serde::Serialize for AlignItems {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ let name = match (self.keyword, self.safety) {
+ (AlignItemsKeyword::Start, AlignmentSafety::Default) => "Start",
+ (AlignItemsKeyword::End, AlignmentSafety::Default) => "End",
+ (AlignItemsKeyword::FlexStart, AlignmentSafety::Default) => "FlexStart",
+ (AlignItemsKeyword::FlexEnd, AlignmentSafety::Default) => "FlexEnd",
+ (AlignItemsKeyword::SelfStart, AlignmentSafety::Default) => "SelfStart",
+ (AlignItemsKeyword::SelfEnd, AlignmentSafety::Default) => "SelfEnd",
+ (AlignItemsKeyword::Center, AlignmentSafety::Default) => "Center",
+ (AlignItemsKeyword::Start, AlignmentSafety::Unsafe) => "UnsafeStart",
+ (AlignItemsKeyword::End, AlignmentSafety::Unsafe) => "UnsafeEnd",
+ (AlignItemsKeyword::FlexStart, AlignmentSafety::Unsafe) => "UnsafeFlexStart",
+ (AlignItemsKeyword::FlexEnd, AlignmentSafety::Unsafe) => "UnsafeFlexEnd",
+ (AlignItemsKeyword::SelfStart, AlignmentSafety::Unsafe) => "UnsafeSelfStart",
+ (AlignItemsKeyword::SelfEnd, AlignmentSafety::Unsafe) => "UnsafeSelfEnd",
+ (AlignItemsKeyword::Center, AlignmentSafety::Unsafe) => "UnsafeCenter",
+ (AlignItemsKeyword::Normal, _) => "Normal",
+ (AlignItemsKeyword::Baseline, _) => "Baseline",
+ (AlignItemsKeyword::Stretch, _) => "Stretch",
+ (AlignItemsKeyword::Start, AlignmentSafety::Safe) => "SafeStart",
+ (AlignItemsKeyword::End, AlignmentSafety::Safe) => "SafeEnd",
+ (AlignItemsKeyword::FlexStart, AlignmentSafety::Safe) => "SafeFlexStart",
+ (AlignItemsKeyword::FlexEnd, AlignmentSafety::Safe) => "SafeFlexEnd",
+ (AlignItemsKeyword::SelfStart, AlignmentSafety::Safe) => "SafeSelfStart",
+ (AlignItemsKeyword::SelfEnd, AlignmentSafety::Safe) => "SafeSelfEnd",
+ (AlignItemsKeyword::Center, AlignmentSafety::Safe) => "SafeCenter",
+ };
+ serializer.serialize_str(name)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for AlignItems {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct AlignItemsVisitor;
+ impl<'de> serde::de::Visitor<'de> for AlignItemsVisitor {
+ type Value = AlignItems;
+ fn expecting(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
+ fmt.write_str("an AlignItems variant tag string")
+ }
+ fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
+ Ok(match v {
+ "Normal" => AlignItems::NORMAL,
+ "Start" => AlignItems::START,
+ "End" => AlignItems::END,
+ "FlexStart" => AlignItems::FLEX_START,
+ "FlexEnd" => AlignItems::FLEX_END,
+ "SelfStart" => AlignItems::SELF_START,
+ "SelfEnd" => AlignItems::SELF_END,
+ "Center" => AlignItems::CENTER,
+ "Baseline" => AlignItems::BASELINE,
+ "Stretch" => AlignItems::STRETCH,
+ "SafeStart" => AlignItems::SAFE_START,
+ "SafeEnd" => AlignItems::SAFE_END,
+ "SafeFlexStart" => AlignItems::SAFE_FLEX_START,
+ "SafeFlexEnd" => AlignItems::SAFE_FLEX_END,
+ "SafeSelfStart" => AlignItems::SAFE_SELF_START,
+ "SafeSelfEnd" => AlignItems::SAFE_SELF_END,
+ "SafeCenter" => AlignItems::SAFE_CENTER,
+ "UnsafeStart" => AlignItems::START.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeEnd" => AlignItems::END.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeFlexStart" => AlignItems::FLEX_START.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeFlexEnd" => AlignItems::FLEX_END.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeSelfStart" => AlignItems::SELF_START.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeSelfEnd" => AlignItems::SELF_END.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeCenter" => AlignItems::CENTER.with_safety(AlignmentSafety::Unsafe),
+ other => return Err(E::unknown_variant(other, ALIGN_ITEMS_NAMES)),
+ })
+ }
+ }
+ deserializer.deserialize_str(AlignItemsVisitor)
+ }
+}
+
+/// Canonical tag-string set accepted by [`AlignContent`] serde deserialization, used in
+/// `unknown_variant` errors. Mirrors the spellings produced by `Serialize`.
+#[cfg(feature = "serde")]
+const ALIGN_CONTENT_NAMES: &[&str] = &[
+ "Normal",
+ "Start",
+ "End",
+ "FlexStart",
+ "FlexEnd",
+ "Center",
+ "Stretch",
+ "SpaceBetween",
+ "SpaceEvenly",
+ "SpaceAround",
+ "SafeStart",
+ "SafeEnd",
+ "SafeFlexStart",
+ "SafeFlexEnd",
+ "SafeCenter",
+ "UnsafeStart",
+ "UnsafeEnd",
+ "UnsafeFlexStart",
+ "UnsafeFlexEnd",
+ "UnsafeCenter",
+];
+
+#[cfg(feature = "serde")]
+impl serde::Serialize for AlignContent {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ let name = match (self.keyword, self.safety) {
+ (AlignContentKeyword::Start, AlignmentSafety::Default) => "Start",
+ (AlignContentKeyword::End, AlignmentSafety::Default) => "End",
+ (AlignContentKeyword::FlexStart, AlignmentSafety::Default) => "FlexStart",
+ (AlignContentKeyword::FlexEnd, AlignmentSafety::Default) => "FlexEnd",
+ (AlignContentKeyword::Center, AlignmentSafety::Default) => "Center",
+ (AlignContentKeyword::Start, AlignmentSafety::Unsafe) => "UnsafeStart",
+ (AlignContentKeyword::End, AlignmentSafety::Unsafe) => "UnsafeEnd",
+ (AlignContentKeyword::FlexStart, AlignmentSafety::Unsafe) => "UnsafeFlexStart",
+ (AlignContentKeyword::FlexEnd, AlignmentSafety::Unsafe) => "UnsafeFlexEnd",
+ (AlignContentKeyword::Center, AlignmentSafety::Unsafe) => "UnsafeCenter",
+ (AlignContentKeyword::Normal, _) => "Normal",
+ (AlignContentKeyword::Stretch, _) => "Stretch",
+ (AlignContentKeyword::SpaceBetween, _) => "SpaceBetween",
+ (AlignContentKeyword::SpaceEvenly, _) => "SpaceEvenly",
+ (AlignContentKeyword::SpaceAround, _) => "SpaceAround",
+ (AlignContentKeyword::Start, AlignmentSafety::Safe) => "SafeStart",
+ (AlignContentKeyword::End, AlignmentSafety::Safe) => "SafeEnd",
+ (AlignContentKeyword::FlexStart, AlignmentSafety::Safe) => "SafeFlexStart",
+ (AlignContentKeyword::FlexEnd, AlignmentSafety::Safe) => "SafeFlexEnd",
+ (AlignContentKeyword::Center, AlignmentSafety::Safe) => "SafeCenter",
+ };
+ serializer.serialize_str(name)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for AlignContent {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct AlignContentVisitor;
+ impl<'de> serde::de::Visitor<'de> for AlignContentVisitor {
+ type Value = AlignContent;
+ fn expecting(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
+ fmt.write_str("an AlignContent variant tag string")
+ }
+ fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
+ Ok(match v {
+ "Normal" => AlignContent::NORMAL,
+ "Start" => AlignContent::START,
+ "End" => AlignContent::END,
+ "FlexStart" => AlignContent::FLEX_START,
+ "FlexEnd" => AlignContent::FLEX_END,
+ "Center" => AlignContent::CENTER,
+ "Stretch" => AlignContent::STRETCH,
+ "SpaceBetween" => AlignContent::SPACE_BETWEEN,
+ "SpaceEvenly" => AlignContent::SPACE_EVENLY,
+ "SpaceAround" => AlignContent::SPACE_AROUND,
+ "SafeStart" => AlignContent::SAFE_START,
+ "SafeEnd" => AlignContent::SAFE_END,
+ "SafeFlexStart" => AlignContent::SAFE_FLEX_START,
+ "SafeFlexEnd" => AlignContent::SAFE_FLEX_END,
+ "SafeCenter" => AlignContent::SAFE_CENTER,
+ "UnsafeStart" => AlignContent::START.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeEnd" => AlignContent::END.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeFlexStart" => AlignContent::FLEX_START.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeFlexEnd" => AlignContent::FLEX_END.with_safety(AlignmentSafety::Unsafe),
+ "UnsafeCenter" => AlignContent::CENTER.with_safety(AlignmentSafety::Unsafe),
+ other => return Err(E::unknown_variant(other, ALIGN_CONTENT_NAMES)),
+ })
+ }
+ }
+ deserializer.deserialize_str(AlignContentVisitor)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use core::mem::size_of;
+
+ // Size budget — struct = 1B keyword + 1B safety, no niche packing.
+ // Pre-refactor each was a single-byte enum; spec §V13 caps regression at +2B.
+ #[test]
+ fn align_types_within_size_budget() {
+ assert!(size_of::<AlignItems>() <= 2, "AlignItems grew to {}", size_of::<AlignItems>());
+ assert!(size_of::<AlignContent>() <= 2, "AlignContent grew to {}", size_of::<AlignContent>());
+ assert!(size_of::<Option<AlignItems>>() <= 3);
+ }
+
+ #[test]
+ fn align_items_is_safe() {
+ assert!(AlignItems::SAFE_START.is_safe());
+ assert!(AlignItems::SAFE_END.is_safe());
+ assert!(AlignItems::SAFE_FLEX_START.is_safe());
+ assert!(AlignItems::SAFE_FLEX_END.is_safe());
+ assert!(AlignItems::SAFE_CENTER.is_safe());
+ assert!(!AlignItems::START.is_safe());
+ assert!(!AlignItems::END.is_safe());
+ assert!(!AlignItems::FLEX_START.is_safe());
+ assert!(!AlignItems::FLEX_END.is_safe());
+ assert!(!AlignItems::CENTER.is_safe());
+ assert!(!AlignItems::BASELINE.is_safe());
+ assert!(!AlignItems::STRETCH.is_safe());
+ assert!(AlignItems::SAFE_SELF_START.is_safe());
+ assert!(AlignItems::SAFE_SELF_END.is_safe());
+ assert!(!AlignItems::SELF_START.is_safe());
+ assert!(!AlignItems::SELF_END.is_safe());
+ assert!(!AlignItems::NORMAL.is_safe());
+ }
+
+ #[test]
+ fn align_items_keyword_strips_safe() {
+ assert_eq!(AlignItems::SAFE_START.keyword(), AlignItemsKeyword::Start);
+ assert_eq!(AlignItems::SAFE_END.keyword(), AlignItemsKeyword::End);
+ assert_eq!(AlignItems::SAFE_FLEX_START.keyword(), AlignItemsKeyword::FlexStart);
+ assert_eq!(AlignItems::SAFE_FLEX_END.keyword(), AlignItemsKeyword::FlexEnd);
+ assert_eq!(AlignItems::SAFE_CENTER.keyword(), AlignItemsKeyword::Center);
+ assert_eq!(AlignItems::SAFE_SELF_START.keyword(), AlignItemsKeyword::SelfStart);
+ assert_eq!(AlignItems::SAFE_SELF_END.keyword(), AlignItemsKeyword::SelfEnd);
+ }
+
+ #[test]
+ fn align_items_keyword_passthrough() {
+ assert_eq!(AlignItems::START.keyword(), AlignItemsKeyword::Start);
+ assert_eq!(AlignItems::STRETCH.keyword(), AlignItemsKeyword::Stretch);
+ assert_eq!(AlignItems::BASELINE.keyword(), AlignItemsKeyword::Baseline);
+ assert_eq!(AlignItems::FLEX_START.keyword(), AlignItemsKeyword::FlexStart);
+ assert_eq!(AlignItems::NORMAL.keyword(), AlignItemsKeyword::Normal);
+ }
+
+ #[test]
+ fn align_items_default_is_normal() {
+ assert_eq!(AlignItems::default(), AlignItems::NORMAL);
+ assert_eq!(AlignItemsKeyword::default(), AlignItemsKeyword::Normal);
+ assert_eq!(AlignmentSafety::default(), AlignmentSafety::Default);
+ }
+
+ #[test]
+ fn resolve_self_relative_inline_axis() {
+ use Direction::{Ltr, Rtl};
+ // Same direction: self-start == start, self-end == end
+ assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Ltr, true), AlignItems::START);
+ assert_eq!(AlignItems::SELF_END.resolve_self_relative(Ltr, Ltr, true), AlignItems::END);
+ assert_eq!(AlignItems::SELF_START.resolve_self_relative(Rtl, Rtl, true), AlignItems::START);
+ assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Rtl, true), AlignItems::END);
+ // Opposite direction: self-start == end, self-end == start
+ assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Rtl, true), AlignItems::END);
+ assert_eq!(AlignItems::SELF_END.resolve_self_relative(Ltr, Rtl, true), AlignItems::START);
+ assert_eq!(AlignItems::SELF_START.resolve_self_relative(Rtl, Ltr, true), AlignItems::END);
+ assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Ltr, true), AlignItems::START);
+ // Safety modifier is preserved
+ assert_eq!(AlignItems::SAFE_SELF_START.resolve_self_relative(Ltr, Rtl, true), AlignItems::SAFE_END);
+ // Other keywords are unchanged
+ assert_eq!(AlignItems::START.resolve_self_relative(Ltr, Rtl, true), AlignItems::START);
+ assert_eq!(AlignItems::FLEX_END.resolve_self_relative(Ltr, Rtl, true), AlignItems::FLEX_END);
+ assert_eq!(AlignItems::NORMAL.resolve_self_relative(Ltr, Rtl, true), AlignItems::NORMAL);
+ }
+
+ #[test]
+ fn resolve_self_relative_block_axis() {
+ use Direction::{Ltr, Rtl};
+ // In the block axis (horizontal-tb only) direction never flips self-start/self-end
+ assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Rtl, false), AlignItems::START);
+ assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Ltr, false), AlignItems::END);
+ }
+
+ #[test]
+ fn align_content_is_safe() {
+ assert!(AlignContent::SAFE_START.is_safe());
+ assert!(AlignContent::SAFE_CENTER.is_safe());
+ assert!(!AlignContent::SPACE_BETWEEN.is_safe());
+ assert!(!AlignContent::STRETCH.is_safe());
+ assert!(!AlignContent::NORMAL.is_safe());
+ }
+
+ #[test]
+ fn align_content_keyword_strips_safe() {
+ assert_eq!(AlignContent::SAFE_START.keyword(), AlignContentKeyword::Start);
+ assert_eq!(AlignContent::SAFE_FLEX_END.keyword(), AlignContentKeyword::FlexEnd);
+ assert_eq!(AlignContent::SAFE_CENTER.keyword(), AlignContentKeyword::Center);
+ assert_eq!(AlignContent::SPACE_BETWEEN.keyword(), AlignContentKeyword::SpaceBetween);
+ assert_eq!(AlignContent::NORMAL.keyword(), AlignContentKeyword::Normal);
+ assert_eq!(JustifyContent::NORMAL, AlignContent::NORMAL);
+ }
+
+ #[test]
+ fn align_content_keyword_reversed_swaps_start_end() {
+ assert_eq!(AlignContentKeyword::Start.reversed(), AlignContentKeyword::End);
+ assert_eq!(AlignContentKeyword::End.reversed(), AlignContentKeyword::Start);
+ assert_eq!(AlignContentKeyword::FlexStart.reversed(), AlignContentKeyword::FlexEnd);
+ assert_eq!(AlignContentKeyword::FlexEnd.reversed(), AlignContentKeyword::FlexStart);
+ // Stretch reverses to End — preserves pre-refactor behaviour.
+ assert_eq!(AlignContentKeyword::Stretch.reversed(), AlignContentKeyword::End);
+ assert_eq!(AlignContentKeyword::Normal.reversed(), AlignContentKeyword::Normal);
+ assert_eq!(AlignContentKeyword::Center.reversed(), AlignContentKeyword::Center);
+ assert_eq!(AlignContentKeyword::SpaceBetween.reversed(), AlignContentKeyword::SpaceBetween);
+ assert_eq!(AlignContentKeyword::SpaceEvenly.reversed(), AlignContentKeyword::SpaceEvenly);
+ assert_eq!(AlignContentKeyword::SpaceAround.reversed(), AlignContentKeyword::SpaceAround);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_plain() {
+ assert_eq!("start".parse::<AlignItems>().unwrap(), AlignItems::START);
+ assert_eq!("end".parse::<AlignItems>().unwrap(), AlignItems::END);
+ assert_eq!("flex-start".parse::<AlignItems>().unwrap(), AlignItems::FLEX_START);
+ assert_eq!("flex-end".parse::<AlignItems>().unwrap(), AlignItems::FLEX_END);
+ assert_eq!("center".parse::<AlignItems>().unwrap(), AlignItems::CENTER);
+ assert_eq!("self-start".parse::<AlignItems>().unwrap(), AlignItems::SELF_START);
+ assert_eq!("self-end".parse::<AlignItems>().unwrap(), AlignItems::SELF_END);
+ assert_eq!("baseline".parse::<AlignItems>().unwrap(), AlignItems::BASELINE);
+ assert_eq!("stretch".parse::<AlignItems>().unwrap(), AlignItems::STRETCH);
+ }
+
+ #[test]
+ fn align_content_default_is_normal() {
+ assert_eq!(AlignContent::default(), AlignContent::NORMAL);
+ assert_eq!(JustifyContent::default(), JustifyContent::NORMAL);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_normal() {
+ assert_eq!("normal".parse::<AlignItems>().unwrap(), AlignItems::NORMAL);
+ assert_eq!("NORMAL".parse::<AlignItems>().unwrap(), AlignItems::NORMAL);
+ assert_eq!(AlignItems::NORMAL.safety, AlignmentSafety::Default);
+ // `auto` is not an `AlignItems` keyword: it is represented by `None` on the `*-self` styles
+ assert!("auto".parse::<AlignSelf>().is_err());
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_safe() {
+ assert_eq!("safe start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_START);
+ assert_eq!("safe end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_END);
+ assert_eq!("safe flex-start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_START);
+ assert_eq!("safe flex-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_END);
+ assert_eq!("safe self-start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_SELF_START);
+ assert_eq!("safe self-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_SELF_END);
+ assert_eq!("safe center".parse::<AlignItems>().unwrap(), AlignItems::SAFE_CENTER);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_safe_case_insensitive() {
+ assert_eq!("SAFE Start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_START);
+ assert_eq!("Safe FLEX-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_END);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_unsafe() {
+ let unsafe_ = |keyword| AlignItems { keyword, safety: AlignmentSafety::Unsafe };
+ assert_eq!("unsafe start".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::Start));
+ assert_eq!("unsafe end".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::End));
+ assert_eq!("unsafe self-start".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::SelfStart));
+ assert_eq!("unsafe self-end".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::SelfEnd));
+ assert_eq!("unsafe center".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::Center));
+ // The bare keyword carries no overflow-position modifier
+ assert_eq!(AlignItems::START.safety, AlignmentSafety::Default);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_items_rejects_invalid_safe_combos() {
+ assert!("safe stretch".parse::<AlignItems>().is_err());
+ assert!("safe baseline".parse::<AlignItems>().is_err());
+ assert!("safe space-between".parse::<AlignItems>().is_err());
+ assert!("safe".parse::<AlignItems>().is_err());
+ assert!("safe garbage".parse::<AlignItems>().is_err());
+ assert!("unsafe stretch".parse::<AlignItems>().is_err());
+ assert!("unsafe baseline".parse::<AlignItems>().is_err());
+ assert!("safe normal".parse::<AlignItems>().is_err());
+ assert!("safe auto".parse::<AlignItems>().is_err());
+ assert!("unsafe normal".parse::<AlignItems>().is_err());
+ assert!("unsafe auto".parse::<AlignItems>().is_err());
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_content_plain() {
+ assert_eq!("normal".parse::<AlignContent>().unwrap(), AlignContent::NORMAL);
+ assert_eq!("Normal".parse::<JustifyContent>().unwrap(), JustifyContent::NORMAL);
+ assert_eq!(AlignContent::NORMAL.safety, AlignmentSafety::Default);
+ assert_eq!("start".parse::<AlignContent>().unwrap(), AlignContent::START);
+ assert_eq!("space-between".parse::<AlignContent>().unwrap(), AlignContent::SPACE_BETWEEN);
+ assert_eq!("space-evenly".parse::<AlignContent>().unwrap(), AlignContent::SPACE_EVENLY);
+ assert_eq!("space-around".parse::<AlignContent>().unwrap(), AlignContent::SPACE_AROUND);
+ assert_eq!("stretch".parse::<AlignContent>().unwrap(), AlignContent::STRETCH);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_content_safe() {
+ assert_eq!("safe start".parse::<AlignContent>().unwrap(), AlignContent::SAFE_START);
+ assert_eq!("safe end".parse::<AlignContent>().unwrap(), AlignContent::SAFE_END);
+ assert_eq!("safe flex-start".parse::<AlignContent>().unwrap(), AlignContent::SAFE_FLEX_START);
+ assert_eq!("safe flex-end".parse::<AlignContent>().unwrap(), AlignContent::SAFE_FLEX_END);
+ assert_eq!("safe center".parse::<AlignContent>().unwrap(), AlignContent::SAFE_CENTER);
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_content_unsafe() {
+ let unsafe_ = |keyword| AlignContent { keyword, safety: AlignmentSafety::Unsafe };
+ assert_eq!("unsafe start".parse::<AlignContent>().unwrap(), unsafe_(AlignContentKeyword::Start));
+ assert_eq!("unsafe flex-end".parse::<AlignContent>().unwrap(), unsafe_(AlignContentKeyword::FlexEnd));
+ }
+
+ #[cfg(feature = "parse")]
+ #[test]
+ fn parse_align_content_rejects_invalid_safe_combos() {
+ assert!("safe stretch".parse::<AlignContent>().is_err());
+ assert!("safe space-between".parse::<AlignContent>().is_err());
+ assert!("safe space-evenly".parse::<AlignContent>().is_err());
+ assert!("safe space-around".parse::<AlignContent>().is_err());
+ assert!("safe".parse::<AlignContent>().is_err());
+ assert!("unsafe stretch".parse::<AlignContent>().is_err());
+ assert!("unsafe space-between".parse::<AlignContent>().is_err());
+ assert!("safe normal".parse::<AlignContent>().is_err());
+ assert!("unsafe normal".parse::<AlignContent>().is_err());
+ assert!("auto".parse::<AlignContent>().is_err());
+ }
+
+ #[cfg(feature = "serde")]
+ #[test]
+ fn serde_align_items_round_trip() {
+ let cases = [
+ (AlignItems::NORMAL, "\"Normal\""),
+ (AlignItems::START, "\"Start\""),
+ (AlignItems::END, "\"End\""),
+ (AlignItems::FLEX_START, "\"FlexStart\""),
+ (AlignItems::FLEX_END, "\"FlexEnd\""),
+ (AlignItems::CENTER, "\"Center\""),
+ (AlignItems::BASELINE, "\"Baseline\""),
+ (AlignItems::STRETCH, "\"Stretch\""),
+ (AlignItems::SAFE_START, "\"SafeStart\""),
+ (AlignItems::SAFE_END, "\"SafeEnd\""),
+ (AlignItems::SAFE_FLEX_START, "\"SafeFlexStart\""),
+ (AlignItems::SAFE_FLEX_END, "\"SafeFlexEnd\""),
+ (AlignItems::SAFE_CENTER, "\"SafeCenter\""),
+ (AlignItems::SELF_START, "\"SelfStart\""),
+ (AlignItems::SELF_END, "\"SelfEnd\""),
+ (AlignItems::SAFE_SELF_START, "\"SafeSelfStart\""),
+ (AlignItems::SAFE_SELF_END, "\"SafeSelfEnd\""),
+ ];
+ for (value, expected) in cases {
+ let serialized = serde_json::to_string(&value).unwrap();
+ assert_eq!(serialized, expected, "serialize {:?}", value);
+ let deserialized: AlignItems = serde_json::from_str(expected).unwrap();
+ assert_eq!(deserialized, value, "round-trip {:?}", value);
+ }
+ assert!(serde_json::from_str::<AlignItems>("\"NotAVariant\"").is_err());
+ }
+
+ #[cfg(feature = "serde")]
+ #[test]
+ fn serde_align_content_round_trip() {
+ let cases = [
+ (AlignContent::NORMAL, "\"Normal\""),
+ (AlignContent::START, "\"Start\""),
+ (AlignContent::END, "\"End\""),
+ (AlignContent::FLEX_START, "\"FlexStart\""),
+ (AlignContent::FLEX_END, "\"FlexEnd\""),
+ (AlignContent::CENTER, "\"Center\""),
+ (AlignContent::STRETCH, "\"Stretch\""),
+ (AlignContent::SPACE_BETWEEN, "\"SpaceBetween\""),
+ (AlignContent::SPACE_EVENLY, "\"SpaceEvenly\""),
+ (AlignContent::SPACE_AROUND, "\"SpaceAround\""),
+ (AlignContent::SAFE_START, "\"SafeStart\""),
+ (AlignContent::SAFE_END, "\"SafeEnd\""),
+ (AlignContent::SAFE_FLEX_START, "\"SafeFlexStart\""),
+ (AlignContent::SAFE_FLEX_END, "\"SafeFlexEnd\""),
+ (AlignContent::SAFE_CENTER, "\"SafeCenter\""),
+ ];
+ for (value, expected) in cases {
+ let serialized = serde_json::to_string(&value).unwrap();
+ assert_eq!(serialized, expected, "serialize {:?}", value);
+ let deserialized: AlignContent = serde_json::from_str(expected).unwrap();
+ assert_eq!(deserialized, value, "round-trip {:?}", value);
+ }
+ assert!(serde_json::from_str::<AlignContent>("\"NotAVariant\"").is_err());
+ }
+}
diff --git a/vendor/taffy/src/style/available_space.rs b/vendor/taffy/src/style/available_space.rs
new file mode 100644
index 00000000..d36dd045
--- /dev/null
+++ b/vendor/taffy/src/style/available_space.rs
@@ -0,0 +1,163 @@
+//! Style type for representing available space as a sizing constraint
+use crate::{
+ prelude::{FromLength, TaffyMaxContent, TaffyMinContent, TaffyZero},
+ sys::abs,
+ Size,
+};
+
+#[cfg(feature = "parse")]
+use crate::util::parse::{from_str_from_css, CssParseResult, FromCss, Parser, Token};
+
+/// The amount of space available to a node in a given axis
+/// <https://www.w3.org/TR/css-sizing-3/#available>
+#[derive(Copy, Clone, Debug, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub enum AvailableSpace {
+ /// The amount of space available is the specified number of pixels
+ Definite(f32),
+ /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
+ MinContent,
+ /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
+ MaxContent,
+}
+impl TaffyZero for AvailableSpace {
+ const ZERO: Self = Self::Definite(0.0);
+}
+impl TaffyMaxContent for AvailableSpace {
+ const MAX_CONTENT: Self = Self::MaxContent;
+}
+impl TaffyMinContent for AvailableSpace {
+ const MIN_CONTENT: Self = Self::MinContent;
+}
+impl FromLength for AvailableSpace {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::Definite(value.into() as f32)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for AvailableSpace {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ match parser.next()?.clone() {
+ Token::Number { value, .. } if value >= 0.0 => Ok(Self::Definite(value)),
+ Token::Dimension { value, .. } if value >= 0.0 => Ok(Self::Definite(value)),
+ Token::Ident(ident) if ident == "max-content" => Ok(Self::MaxContent),
+ Token::Ident(ident) if ident == "min-content" => Ok(Self::MinContent),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(AvailableSpace);
+
+impl AvailableSpace {
+ /// Returns true for definite values, else false
+ pub const fn is_definite(self) -> bool {
+ matches!(self, AvailableSpace::Definite(_))
+ }
+
+ /// Convert to Option
+ /// Definite values become Some(value). Constraints become None.
+ pub const fn into_option(self) -> Option<f32> {
+ match self {
+ AvailableSpace::Definite(value) => Some(value),
+ _ => None,
+ }
+ }
+
+ /// Return the definite value or a default value
+ pub fn unwrap_or(self, default: f32) -> f32 {
+ self.into_option().unwrap_or(default)
+ }
+
+ /// Return the definite value. Panic is the value is not definite.
+ #[track_caller]
+ pub fn unwrap(self) -> f32 {
+ self.into_option().unwrap()
+ }
+
+ /// Return self if definite or a default value
+ pub fn or(self, default: AvailableSpace) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(_) => self,
+ _ => default,
+ }
+ }
+
+ /// Return self if definite or a the result of the default value callback
+ pub fn or_else(self, default_cb: impl FnOnce() -> AvailableSpace) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(_) => self,
+ _ => default_cb(),
+ }
+ }
+
+ /// Return the definite value or the result of the default value callback
+ pub fn unwrap_or_else(self, default_cb: impl FnOnce() -> f32) -> f32 {
+ self.into_option().unwrap_or_else(default_cb)
+ }
+
+ /// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
+ pub fn maybe_set(self, value: Option<f32>) -> AvailableSpace {
+ match value {
+ Some(value) => AvailableSpace::Definite(value),
+ None => self,
+ }
+ }
+
+ /// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
+ pub fn map_definite_value(self, map_function: impl FnOnce(f32) -> f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(value) => AvailableSpace::Definite(map_function(value)),
+ _ => self,
+ }
+ }
+
+ /// Compute free_space given the passed used_space
+ pub fn compute_free_space(&self, used_space: f32) -> f32 {
+ match self {
+ AvailableSpace::MaxContent => f32::INFINITY,
+ AvailableSpace::MinContent => 0.0,
+ AvailableSpace::Definite(available_space) => available_space - used_space,
+ }
+ }
+
+ /// Compare equality with another AvailableSpace, treating definite values
+ /// that are within f32::EPSILON of each other as equal
+ pub fn is_roughly_equal(self, other: AvailableSpace) -> bool {
+ use AvailableSpace::*;
+ match (self, other) {
+ (Definite(a), Definite(b)) => abs(a - b) < f32::EPSILON,
+ (MinContent, MinContent) => true,
+ (MaxContent, MaxContent) => true,
+ _ => false,
+ }
+ }
+}
+
+impl From<f32> for AvailableSpace {
+ fn from(value: f32) -> Self {
+ Self::Definite(value)
+ }
+}
+
+impl From<Option<f32>> for AvailableSpace {
+ fn from(option: Option<f32>) -> Self {
+ match option {
+ Some(value) => Self::Definite(value),
+ None => Self::MaxContent,
+ }
+ }
+}
+
+impl Size<AvailableSpace> {
+ /// Convert `Size<AvailableSpace>` into `Size<Option<f32>>`
+ pub fn into_options(self) -> Size<Option<f32>> {
+ Size { width: self.width.into_option(), height: self.height.into_option() }
+ }
+
+ /// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
+ pub fn maybe_set(self, value: Size<Option<f32>>) -> Size<AvailableSpace> {
+ Size { width: self.width.maybe_set(value.width), height: self.height.maybe_set(value.height) }
+ }
+}
diff --git a/vendor/taffy/src/style/block.rs b/vendor/taffy/src/style/block.rs
new file mode 100644
index 00000000..fb1c7a3b
--- /dev/null
+++ b/vendor/taffy/src/style/block.rs
@@ -0,0 +1,95 @@
+//! Style types for Block layout
+use crate::style::{AlignContent, AlignItems, AlignSelf};
+use crate::{CoreStyle, Style};
+
+/// The set of styles required for a Block layout container
+pub trait BlockContainerStyle: CoreStyle {
+ /// Defines which row in the grid the item should start and end at
+ #[inline(always)]
+ fn text_align(&self) -> TextAlign {
+ Style::<Self::CustomIdent>::DEFAULT.text_align
+ }
+
+ /// How children of this block container are aligned in the block (cross) axis
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ Style::<Self::CustomIdent>::DEFAULT.align_content
+ }
+
+ /// The default inline-axis alignment of this block container's children (`justify-items`).
+ /// Out-of-flow children with `justify-self: auto` are aligned within their static-position
+ /// rectangle according to this value.
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ Style::<Self::CustomIdent>::DEFAULT.justify_items
+ }
+}
+
+/// The set of styles required for a Block layout item (child of a Block container)
+pub trait BlockItemStyle: CoreStyle {
+ /// Whether the item is a table. Table children are handled specially in block layout.
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ false
+ }
+
+ /// How an out-of-flow (absolutely positioned) child is aligned in the block axis of its
+ /// static-position rectangle (`align-self`). `None` corresponds to `normal`/`auto`.
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ None
+ }
+
+ /// How an out-of-flow (absolutely positioned) child is aligned in the inline axis of its
+ /// static-position rectangle (`justify-self`). `None` corresponds to `normal`/`auto`.
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ None
+ }
+
+ /// The `align-content` of the item (if it is itself a block container). A non-`normal`
+ /// value makes the item establish an independent formatting context, so that it is laid
+ /// out next to (rather than underneath) floats and does not collapse margins with its
+ /// parent (<https://www.w3.org/TR/css-align-3/#distribution-block>).
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ AlignContent::NORMAL
+ }
+
+ /// Whether the item is a floated
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn float(&self) -> super::Float {
+ super::Float::None
+ }
+
+ /// Whether the item is a floated
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn clear(&self) -> super::Clear {
+ super::Clear::None
+ }
+}
+
+/// Used by block layout to implement the legacy behaviour of `<center>` and `<div align="left | right | center">`
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum TextAlign {
+ /// No special legacy text align behaviour.
+ #[default]
+ Auto,
+ /// Corresponds to `-webkit-left` or `-moz-left` in browsers
+ LegacyLeft,
+ /// Corresponds to `-webkit-right` or `-moz-right` in browsers
+ LegacyRight,
+ /// Corresponds to `-webkit-center` or `-moz-center` in browsers
+ LegacyCenter,
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(TextAlign,
+ "auto" => Auto,
+ "-webkit-left" => LegacyLeft,
+ "-webkit-right" => LegacyRight,
+ "-webkit-center" => LegacyCenter,
+);
diff --git a/vendor/taffy/src/style/compact_length.rs b/vendor/taffy/src/style/compact_length.rs
new file mode 100644
index 00000000..39234991
--- /dev/null
+++ b/vendor/taffy/src/style/compact_length.rs
@@ -0,0 +1,793 @@
+//! A tagged-pointer abstraction that allows size styles in Taffy to be represented
+//! in just 64 bits. Wrapped by types in the `super::dimension` and `super::grid` modules.
+use super::LengthPercentage;
+use crate::style_helpers::{
+ FromFr, FromLength, FromPercent, TaffyAuto, TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero,
+};
+
+/// Note: these two functions are copied directly from the std (core) library. But by duplicating them
+/// here we can reduce MSRV from 1.84 all the way down to 1.65 while retaining const constructors and
+/// strict pointer provenance
+mod compat {
+ #![allow(unsafe_code)]
+ #![allow(unknown_lints)]
+ #![allow(unnecessary_transmutes)]
+
+ /// Raw transmutation from `f32` to `u32`.
+ pub const fn f32_to_bits(val: f32) -> u32 {
+ // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
+ unsafe { core::mem::transmute(val) }
+ }
+ /// Raw transmutation from `u32` to `f32`.
+ pub const fn f32_from_bits(v: u32) -> f32 {
+ // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
+ unsafe { core::mem::transmute(v) }
+ }
+
+ /// Tag a pointer preserving provenance (requires Rust 1.84)
+ #[inline(always)]
+ #[cfg(all(target_pointer_width = "64", feature = "strict_provenance"))]
+ pub fn tag_ptr(ptr: *const (), tag: usize) -> *const () {
+ ptr.map_addr(|a| a | tag)
+ }
+
+ /// Tag a pointer exposing provenance (works back to Rust 1.0)
+ #[inline(always)]
+ #[cfg(all(target_pointer_width = "64", not(feature = "strict_provenance")))]
+ pub fn tag_ptr(ptr: *const (), tag: usize) -> *const () {
+ (ptr as usize | tag) as *const ()
+ }
+
+ /// Clear the tag bits of a pointer preserving provenance (requires Rust 1.84)
+ #[inline(always)]
+ #[cfg(all(target_pointer_width = "64", feature = "strict_provenance"))]
+ pub fn untag_ptr(ptr: *const (), mask: usize) -> *const () {
+ ptr.map_addr(|a| a & !mask)
+ }
+
+ /// Clear the tag bits of a pointer exposing provenance (works back to Rust 1.0)
+ #[inline(always)]
+ #[cfg(all(target_pointer_width = "64", not(feature = "strict_provenance")))]
+ pub fn untag_ptr(ptr: *const (), mask: usize) -> *const () {
+ (ptr as usize & !mask) as *const ()
+ }
+}
+
+#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
+std::compile_error!("Taffy only supports targets with a pointer width of 32 or 64 bits");
+
+/// CompactLengthInner implementation for 64 bit platforms
+#[cfg(target_pointer_width = "64")]
+mod inner {
+ use super::compat::{f32_from_bits, f32_to_bits, tag_ptr, untag_ptr};
+
+ /// The low byte (8 bits)
+ const TAG_MASK: usize = 0b11111111;
+ /// The low 3 bits
+ const CALC_TAG_MASK: usize = 0b111;
+
+ /// On 64 bit platforms the tag, value and pointer are packed into a single 64 bit pointer
+ ///
+ /// The tagged pointer always has a tag and may contain an f32 value or a pointer
+ /// (or neither) depending on the variant indicated by the tag.
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ pub(super) struct CompactLengthInner {
+ /// The tagged pointer
+ tagged_ptr: *const (),
+ }
+ impl CompactLengthInner {
+ /// Construct a `CompactLengthInner` from a tag and pointer
+ #[inline(always)]
+ pub(super) fn from_ptr(ptr: *const (), tag: usize) -> Self {
+ let tagged_ptr = tag_ptr(ptr, tag);
+ Self { tagged_ptr }
+ }
+
+ /// Construct a `CompactLengthInner` from a tag and numeric value
+ #[inline(always)]
+ pub(super) const fn from_val(val: f32, tag: usize) -> Self {
+ let tagged_ptr = (((f32_to_bits(val) as usize) << 32) | tag) as *const ();
+ Self { tagged_ptr }
+ }
+
+ /// Construct a `CompactLengthInner` from only a tag
+ #[inline(always)]
+ pub(super) const fn from_tag(tag: usize) -> Self {
+ let tagged_ptr = tag as *const ();
+ Self { tagged_ptr }
+ }
+
+ /// Get the calc tag (low 3 bits)
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub(super) fn calc_tag(self) -> usize {
+ (self.tagged_ptr as usize) & CALC_TAG_MASK
+ }
+
+ /// Get the general tag (low 8 bits)
+ #[inline(always)]
+ pub(super) fn tag(self) -> usize {
+ (self.tagged_ptr as usize) & TAG_MASK
+ }
+
+ /// Get the pointer value (with the tag bits cleared)
+ #[inline(always)]
+ pub(super) fn ptr(self) -> *const () {
+ untag_ptr(self.tagged_ptr, CALC_TAG_MASK)
+ }
+
+ /// Get the numeric value
+ #[inline(always)]
+ pub(super) fn value(self) -> f32 {
+ f32_from_bits((self.tagged_ptr as usize >> 32) as u32)
+ }
+
+ /// Get the serialized value.
+ #[inline(always)]
+ #[cfg(feature = "serde")]
+ pub(super) fn serialized(self) -> u64 {
+ (self.tagged_ptr as usize as u64).rotate_left(32)
+ }
+
+ /// Derialized from a value.
+ #[inline(always)]
+ #[cfg(feature = "serde")]
+ pub(super) fn from_serialized(value: u64) -> Self {
+ Self { tagged_ptr: value.rotate_right(32) as usize as *const () }
+ }
+ }
+}
+
+/// CompactLengthInner implementation for 32 bit platforms
+#[cfg(target_pointer_width = "32")]
+mod inner {
+ use super::compat::{f32_from_bits, f32_to_bits};
+
+ /// On 32 bit platforms the tag is stored separately.
+ /// Either an f32 value or a pointer (or neither) are packed into the ptr field
+ /// depending on the variant indicated by the tag
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ pub(super) struct CompactLengthInner {
+ /// The tag indicating what kind of value we are storing
+ tag: usize,
+ /// The pointer of numeric value
+ ptr: *const (),
+ }
+
+ impl CompactLengthInner {
+ /// Construct a `CompactLengthInner` from a tag and pointer
+ #[inline(always)]
+ pub(super) fn from_ptr(ptr: *const (), tag: usize) -> Self {
+ Self { ptr, tag }
+ }
+
+ /// Construct a `CompactLengthInner` from a tag and numeric value
+ #[inline(always)]
+ pub(super) const fn from_val(val: f32, tag: usize) -> Self {
+ Self { ptr: f32_to_bits(val) as usize as *const (), tag }
+ }
+
+ /// Construct a `CompactLengthInner` from only a tag
+ #[inline(always)]
+ pub(super) const fn from_tag(tag: usize) -> Self {
+ Self { ptr: 0 as *const (), tag }
+ }
+
+ /// Get the calc tag (low 3 bits)
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub(super) fn calc_tag(self) -> usize {
+ self.tag
+ }
+
+ /// Get the general tag (low 8 bits)
+ #[inline(always)]
+ pub(super) fn tag(self) -> usize {
+ self.tag
+ }
+
+ /// Get the pointer value
+ #[inline(always)]
+ pub(super) fn ptr(self) -> *const () {
+ self.ptr
+ }
+
+ /// Get the numeric value
+ #[inline(always)]
+ pub(super) fn value(self) -> f32 {
+ f32_from_bits(self.ptr as u32)
+ }
+
+ /// Get the serialized value.
+ #[inline(always)]
+ #[cfg(feature = "serde")]
+ pub(super) fn serialized(self) -> u64 {
+ (self.tag as u64) << 32 | (self.ptr as u64)
+ }
+
+ /// Derialized from a value.
+ #[inline(always)]
+ #[cfg(feature = "serde")]
+ pub(super) fn from_serialized(value: u64) -> Self {
+ Self { tag: (value >> 32) as usize, ptr: (value & 0xFFFFFFFF) as usize as *const () }
+ }
+ }
+}
+
+use inner::CompactLengthInner;
+
+/// A representation of a length as a compact 64-bit tagged pointer
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[repr(transparent)]
+pub struct CompactLength(CompactLengthInner);
+
+/// Tag layout
+///
+/// Tags are 8 bits. The low 3 bits are shared with pointer variants (such as `calc()`), which require
+/// an 8-byte aligned pointer and so always have those bits clear. They are assigned as follows:
+///
+/// - Bit 0 (`NON_POINTER_BIT`): set for every variant that is *not* a pointer. Pointer variants
+/// (`calc()`) have this bit clear, so `is_plain_calc()` is a single bit test.
+/// - Bit 1 (`KEYWORD_BIT`): set for every variant that is *not* a plain length, percentage or calc()
+/// value (i.e. everything that cannot be resolved to a length given only a percentage basis).
+/// - Bit 2 (`PERCENTAGE_BIT`): set for every variant whose resolved value depends on a percentage basis,
+/// including all `calc()` variants. `uses_percentage()` is a single bit test.
+///
+/// Pointer variants are distinguished by bit 1: `calc()` is `0b100` and `fit-content(calc())` is `0b110`.
+/// Any pointer variant's `tag()` includes address bits 3..7, so pointer variants must be tested with low-bit
+/// masks (`is_plain_calc()`, `is_fit_content_calc()`, `has_calc()`) rather than as `match` arms.
+///
+/// Within the keyword class, bit 3 (`SIZING_KEYWORD_BIT`) is set for the CSS sizing keywords
+/// (`min-content`, `max-content`, `fit-content`, `fit-content()`, `stretch`) and clear for `auto`,
+/// `fr` and `content`. The remaining high bits distinguish variants within a class.
+impl CompactLength {
+ /// Bit set for all non-pointer (i.e. not `calc()`) tags
+ pub const NON_POINTER_BIT: usize = 0b0001;
+ /// Bit set for all tags that are not a plain length, percentage or calc() value
+ pub const KEYWORD_BIT: usize = 0b0010;
+ /// Bit set for all tags whose value depends on a percentage basis (including `calc()`)
+ pub const PERCENTAGE_BIT: usize = 0b0100;
+ /// Bit set (in addition to `KEYWORD_BIT`) for all CSS sizing keyword tags
+ pub const SIZING_KEYWORD_BIT: usize = 0b1000;
+
+ /// The tag indicating a calc() value
+ #[cfg(feature = "calc")]
+ pub const CALC_TAG: usize = 0b0000_0100;
+ /// The tag indicating a fit-content() value with a calc() limit
+ #[cfg(feature = "calc")]
+ pub const FIT_CONTENT_CALC_TAG: usize = 0b0000_0110;
+ /// The tag indicating a length value
+ pub const LENGTH_TAG: usize = 0b0000_0001;
+ /// The tag indicating a percentage value
+ pub const PERCENT_TAG: usize = 0b0000_0101;
+ /// The tag indicating an auto value
+ pub const AUTO_TAG: usize = 0b0000_0011;
+ /// The tag indicating an fr value
+ pub const FR_TAG: usize = 0b0001_0011;
+ /// The tag indicating a content keyword value
+ pub const CONTENT_TAG: usize = 0b0010_0011;
+ /// The tag indicating a min-content value
+ pub const MIN_CONTENT_TAG: usize = 0b0000_1011;
+ /// The tag indicating a max-content value
+ pub const MAX_CONTENT_TAG: usize = 0b0001_1011;
+ /// The tag indicating a fit-content value with px limit
+ pub const FIT_CONTENT_PX_TAG: usize = 0b0010_1011;
+ /// The tag indicating a plain fit-content keyword value (no limit)
+ pub const FIT_CONTENT_KEYWORD_TAG: usize = 0b0011_1011;
+ /// The tag indicating a stretch keyword value
+ pub const STRETCH_TAG: usize = 0b0100_1011;
+ /// The tag indicating a fit-content value with percent limit
+ pub const FIT_CONTENT_PERCENT_TAG: usize = 0b0000_1111;
+}
+
+impl CompactLength {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLengthInner::from_val(val, Self::LENGTH_TAG))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLengthInner::from_val(val, Self::PERCENT_TAG))
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ assert_ne!(ptr as u64, 0);
+ assert_eq!(ptr as u64 & 0b111, 0);
+ Self(CompactLengthInner::from_ptr(ptr, Self::CALC_TAG))
+ }
+
+ /// A `fit-content(calc())` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation of the limit and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn fit_content_calc(ptr: *const ()) -> Self {
+ assert_ne!(ptr as u64, 0);
+ assert_eq!(ptr as u64 & 0b111, 0);
+ Self(CompactLengthInner::from_ptr(ptr, Self::FIT_CONTENT_CALC_TAG))
+ }
+
+ /// The dimension should be automatically computed according to algorithm-specific rules
+ /// regarding the default size of boxes.
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ Self(CompactLengthInner::from_tag(Self::AUTO_TAG))
+ }
+
+ /// The dimension as a fraction of the total available grid space (`fr` units in CSS)
+ /// Specified value is the numerator of the fraction. Denominator is the sum of all fraction specified in that grid dimension
+ /// Spec: <https://www.w3.org/TR/css3-grid-layout/#fr-unit>
+ #[inline(always)]
+ pub const fn fr(val: f32) -> Self {
+ Self(CompactLengthInner::from_val(val, Self::FR_TAG))
+ }
+
+ /// The size should be the "min-content" size.
+ /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ Self(CompactLengthInner::from_tag(Self::MIN_CONTENT_TAG))
+ }
+
+ /// The size should be the "max-content" size.
+ /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ Self(CompactLengthInner::from_tag(Self::MAX_CONTENT_TAG))
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where:
+ /// - `min_content` is the [min-content](Self::min_content) size
+ /// - `max_content` is the [max-content](Self::max_content) size
+ /// - `limit` is a LENGTH value passed to this function
+ ///
+ /// The effect of this is that the item takes the size of `limit` clamped
+ /// by the min-content and max-content sizes.
+ #[inline(always)]
+ pub const fn fit_content_px(limit: f32) -> Self {
+ Self(CompactLengthInner::from_val(limit, Self::FIT_CONTENT_PX_TAG))
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where:
+ /// - `min_content` is the [min-content](Self::min_content) size
+ /// - `max_content` is the [max-content](Self::max_content) size
+ /// - `limit` is a PERCENTAGE value passed to this function
+ ///
+ /// The effect of this is that the item takes the size of `limit` clamped
+ /// by the min-content and max-content sizes.
+ #[inline(always)]
+ pub const fn fit_content_percent(limit: f32) -> Self {
+ Self(CompactLengthInner::from_val(limit, Self::FIT_CONTENT_PERCENT_TAG))
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, stretch))`
+ /// where:
+ /// - `min_content` is the [min-content](Self::min_content) size
+ /// - `max_content` is the [max-content](Self::max_content) size
+ /// - `stretch` is the "stretch-fit" size (the size the box would take if it filled the available space)
+ #[inline(always)]
+ pub const fn fit_content_keyword() -> Self {
+ Self(CompactLengthInner::from_tag(Self::FIT_CONTENT_KEYWORD_TAG))
+ }
+
+ /// The size should be the "stretch-fit" size: the size the box would take
+ /// if it filled the available space
+ /// (<https://www.w3.org/TR/css-sizing-4/#stretch-fit-sizing>)
+ #[inline(always)]
+ pub const fn stretch() -> Self {
+ Self(CompactLengthInner::from_tag(Self::STRETCH_TAG))
+ }
+
+ /// The size should be an automatic size based on the box's content
+ /// (<https://www.w3.org/TR/css-flexbox-1/#valdef-flex-basis-content>)
+ ///
+ /// This keyword is only valid for `flex-basis`. In any other context it behaves as [`auto`](Self::auto).
+ #[inline(always)]
+ pub const fn content() -> Self {
+ Self(CompactLengthInner::from_tag(Self::CONTENT_TAG))
+ }
+
+ /// Get the primary tag
+ #[inline(always)]
+ pub fn tag(self) -> usize {
+ self.0.tag()
+ }
+
+ /// Get the numeric value associated with the `CompactLength`
+ /// (e.g. the pixel value for a LENGTH variant)
+ #[inline(always)]
+ pub fn value(self) -> f32 {
+ self.0.value()
+ }
+
+ /// Get the calc pointer of the `CompactLength`
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub fn calc_value(self) -> *const () {
+ self.0.ptr()
+ }
+
+ /// Returns true if the value is a plain calc() value (not a fit-content(calc()) value)
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub fn is_plain_calc(self) -> bool {
+ self.0.calc_tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == 0
+ }
+
+ /// Returns true if the value is a fit-content() value with a calc() limit
+ #[inline(always)]
+ pub fn is_fit_content_calc(self) -> bool {
+ self.tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == Self::KEYWORD_BIT
+ }
+
+ /// Returns true if the value holds a calc() pointer: either a plain calc() value or a
+ /// fit-content() value with a calc() limit. `calc_value()` is valid for exactly these values.
+ #[inline(always)]
+ pub fn has_calc(self) -> bool {
+ self.tag() & Self::NON_POINTER_BIT == 0
+ }
+
+ /// Returns true if the value is 0 px
+ #[inline(always)]
+ pub fn is_zero(self) -> bool {
+ self.0 == Self::ZERO.0
+ }
+
+ /// Returns true if the value is a length or percentage value
+ #[inline(always)]
+ pub fn is_length_or_percentage(self) -> bool {
+ self.tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == Self::NON_POINTER_BIT
+ }
+
+ /// Returns true if the value is auto
+ #[inline(always)]
+ pub fn is_auto(self) -> bool {
+ self.tag() == Self::AUTO_TAG
+ }
+
+ /// Returns true if the value is the content keyword
+ #[inline(always)]
+ pub fn is_content(self) -> bool {
+ self.tag() == Self::CONTENT_TAG
+ }
+
+ /// Returns true if the value is min-content
+ #[inline(always)]
+ pub fn is_min_content(self) -> bool {
+ matches!(self.tag(), Self::MIN_CONTENT_TAG)
+ }
+
+ /// Returns true if the value is max-content
+ #[inline(always)]
+ pub fn is_max_content(self) -> bool {
+ matches!(self.tag(), Self::MAX_CONTENT_TAG)
+ }
+
+ /// Returns true if the value is a fit-content(...) value
+ #[inline(always)]
+ pub fn is_fit_content(self) -> bool {
+ matches!(self.tag(), Self::FIT_CONTENT_PX_TAG | Self::FIT_CONTENT_PERCENT_TAG) || self.is_fit_content_calc()
+ }
+
+ /// Returns true if the value is min-content, max-content, fit-content, fit-content(...), or stretch
+ #[inline(always)]
+ pub fn is_sizing_keyword(self) -> bool {
+ const MASK: usize =
+ CompactLength::NON_POINTER_BIT | CompactLength::KEYWORD_BIT | CompactLength::SIZING_KEYWORD_BIT;
+ self.tag() & MASK == MASK || self.is_fit_content_calc()
+ }
+
+ /// Returns true if the value is max-content or a fit-content(...) value
+ #[inline(always)]
+ pub fn is_max_or_fit_content(self) -> bool {
+ matches!(self.tag(), Self::MAX_CONTENT_TAG | Self::FIT_CONTENT_PX_TAG | Self::FIT_CONTENT_PERCENT_TAG)
+ || self.is_fit_content_calc()
+ }
+
+ /// Returns true if the max track sizing function is `MaxContent`, `FitContent` or `Auto` else false.
+ /// "In all cases, treat auto and fit-content() as max-content, except where specified otherwise for fit-content()."
+ /// See: <https://www.w3.org/TR/css-grid-1/#algo-terms>
+ #[inline(always)]
+ pub fn is_max_content_alike(&self) -> bool {
+ matches!(
+ self.tag(),
+ CompactLength::AUTO_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ ) || self.is_fit_content_calc()
+ }
+
+ /// Returns true if the min track sizing function is `MinContent` or `MaxContent`, else false.
+ #[inline(always)]
+ pub fn is_min_or_max_content(&self) -> bool {
+ matches!(self.tag(), Self::MIN_CONTENT_TAG | Self::MAX_CONTENT_TAG)
+ }
+
+ /// Returns true if the value is auto, min-content, max-content, or fit-content(...)
+ #[inline(always)]
+ pub fn is_intrinsic(self) -> bool {
+ matches!(
+ self.tag(),
+ Self::AUTO_TAG
+ | Self::MIN_CONTENT_TAG
+ | Self::MAX_CONTENT_TAG
+ | Self::FIT_CONTENT_PX_TAG
+ | Self::FIT_CONTENT_PERCENT_TAG
+ ) || self.is_fit_content_calc()
+ }
+
+ /// Returns true if the value is and fr value
+ #[inline(always)]
+ pub fn is_fr(self) -> bool {
+ self.tag() == Self::FR_TAG
+ }
+
+ /// Whether the track sizing functions depends on the size of the parent node
+ #[inline(always)]
+ pub fn uses_percentage(self) -> bool {
+ self.tag() & Self::PERCENTAGE_BIT != 0
+ }
+
+ /// Resolve percentage values against the passed parent_size, returning Some(value)
+ /// Non-percentage values always return None.
+ #[inline(always)]
+ pub fn resolved_percentage_size(
+ self,
+ parent_size: f32,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ match self.tag() {
+ CompactLength::PERCENT_TAG => Some(self.value() * parent_size),
+ #[cfg(feature = "calc")]
+ _ if self.is_plain_calc() => Some(calc_resolver(self.0.ptr(), parent_size)),
+ _ => None,
+ }
+ }
+}
+
+impl TaffyZero for CompactLength {
+ const ZERO: Self = Self::length(0.0);
+}
+impl TaffyAuto for CompactLength {
+ const AUTO: Self = Self::auto();
+}
+impl TaffyMinContent for CompactLength {
+ const MIN_CONTENT: Self = Self::min_content();
+}
+impl TaffyMaxContent for CompactLength {
+ const MAX_CONTENT: Self = Self::max_content();
+}
+impl FromLength for CompactLength {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for CompactLength {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+impl FromFr for CompactLength {
+ fn from_fr<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::fr(value.into() as f32)
+ }
+}
+impl TaffyFitContent for CompactLength {
+ fn fit_content(lp: LengthPercentage) -> Self {
+ let value = lp.0.value();
+ match lp.0.tag() {
+ Self::LENGTH_TAG => Self::fit_content_px(value),
+ Self::PERCENT_TAG => Self::fit_content_percent(value),
+ #[cfg(feature = "calc")]
+ _ if lp.0.is_plain_calc() => Self::fit_content_calc(lp.0.calc_value()),
+ _ => unreachable!(),
+ }
+ }
+}
+
+#[cfg(feature = "serde")]
+impl serde::Serialize for CompactLength {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ #[cfg(feature = "calc")]
+ {
+ if self.has_calc() {
+ Err(serde::ser::Error::custom("Cannot serialize Calc value"))
+ } else {
+ serializer.serialize_u64(self.0.serialized())
+ }
+ }
+
+ #[cfg(not(feature = "calc"))]
+ serializer.serialize_u64(self.0.serialized())
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for CompactLength {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let bits: u64 = u64::deserialize(deserializer)?;
+ let value = Self(CompactLengthInner::from_serialized(bits));
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported.
+ // All of the accepted tags have `NON_POINTER_BIT` set, so a calc() tag can never pass validation.
+ if matches!(
+ value.tag(),
+ CompactLength::LENGTH_TAG
+ | CompactLength::PERCENT_TAG
+ | CompactLength::AUTO_TAG
+ | CompactLength::MIN_CONTENT_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_KEYWORD_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ | CompactLength::STRETCH_TAG
+ | CompactLength::CONTENT_TAG
+ | CompactLength::FR_TAG
+ ) {
+ Ok(value)
+ } else {
+ Err(serde::de::Error::custom("Cannot deserialize Calc value"))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{CompactLength, CompactLengthInner};
+
+ impl CompactLength {
+ fn from_raw_tag(tag: usize) -> Self {
+ Self(CompactLengthInner::from_tag(tag))
+ }
+ }
+
+ const NON_PERCENTAGE_TAGS: &[usize] = &[
+ CompactLength::LENGTH_TAG,
+ CompactLength::AUTO_TAG,
+ CompactLength::FR_TAG,
+ CompactLength::MIN_CONTENT_TAG,
+ CompactLength::MAX_CONTENT_TAG,
+ CompactLength::FIT_CONTENT_PX_TAG,
+ CompactLength::FIT_CONTENT_KEYWORD_TAG,
+ CompactLength::STRETCH_TAG,
+ CompactLength::CONTENT_TAG,
+ ];
+ const PERCENTAGE_TAGS: &[usize] = &[CompactLength::PERCENT_TAG, CompactLength::FIT_CONTENT_PERCENT_TAG];
+
+ #[test]
+ fn tags_are_unique_and_fit_in_a_byte() {
+ let mut all: Vec<usize> = NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS).copied().collect();
+ #[cfg(feature = "calc")]
+ all.push(CompactLength::CALC_TAG);
+ #[cfg(feature = "calc")]
+ all.push(CompactLength::FIT_CONTENT_CALC_TAG);
+ assert!(all.iter().all(|tag| *tag <= 0xFF));
+ all.sort_unstable();
+ all.dedup();
+ assert_eq!(all.len(), NON_PERCENTAGE_TAGS.len() + PERCENTAGE_TAGS.len() + 2 * cfg!(feature = "calc") as usize);
+ }
+
+ #[test]
+ fn non_pointer_tags_have_non_pointer_bit_set() {
+ for tag in NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS) {
+ assert_ne!(tag & CompactLength::NON_POINTER_BIT, 0, "tag {tag:#010b}");
+ }
+ #[cfg(feature = "calc")]
+ assert_eq!(CompactLength::CALC_TAG & CompactLength::NON_POINTER_BIT, 0);
+ }
+
+ #[test]
+ fn keyword_bits_match_predicates() {
+ let all = NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS).map(|tag| CompactLength::from_raw_tag(*tag));
+ for value in all {
+ let tag = value.tag();
+ let is_plain = matches!(tag, CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG);
+ assert_eq!(tag & CompactLength::KEYWORD_BIT == 0, is_plain, "tag {tag:#010b}");
+ assert_eq!(value.is_length_or_percentage(), is_plain, "tag {tag:#010b}");
+ let is_sizing_keyword = matches!(
+ tag,
+ CompactLength::MIN_CONTENT_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_KEYWORD_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ | CompactLength::STRETCH_TAG
+ );
+ assert_eq!(value.is_sizing_keyword(), is_sizing_keyword, "tag {tag:#010b}");
+ }
+ #[cfg(feature = "calc")]
+ {
+ assert_eq!(CompactLength::CALC_TAG & CompactLength::KEYWORD_BIT, 0);
+ assert_ne!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::KEYWORD_BIT, 0);
+ assert_eq!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::NON_POINTER_BIT, 0);
+ assert_ne!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::PERCENTAGE_BIT, 0);
+ }
+ }
+
+ #[test]
+ fn percentage_bit_matches_uses_percentage() {
+ for tag in NON_PERCENTAGE_TAGS {
+ assert_eq!(tag & CompactLength::PERCENTAGE_BIT, 0, "tag {tag:#010b}");
+ }
+ for tag in PERCENTAGE_TAGS {
+ assert_ne!(tag & CompactLength::PERCENTAGE_BIT, 0, "tag {tag:#010b}");
+ }
+ #[cfg(feature = "calc")]
+ assert_ne!(CompactLength::CALC_TAG & CompactLength::PERCENTAGE_BIT, 0);
+
+ assert!(!CompactLength::length(10.0).uses_percentage());
+ assert!(!CompactLength::auto().uses_percentage());
+ assert!(!CompactLength::fr(1.0).uses_percentage());
+ assert!(!CompactLength::min_content().uses_percentage());
+ assert!(!CompactLength::max_content().uses_percentage());
+ assert!(!CompactLength::fit_content_px(10.0).uses_percentage());
+ assert!(!CompactLength::fit_content_keyword().uses_percentage());
+ assert!(!CompactLength::stretch().uses_percentage());
+ assert!(!CompactLength::content().uses_percentage());
+ assert!(CompactLength::percent(0.5).uses_percentage());
+ assert!(CompactLength::fit_content_percent(0.5).uses_percentage());
+ }
+
+ #[test]
+ #[cfg(feature = "calc")]
+ fn fit_content_calc_round_trips_pointer() {
+ let boxed = Box::new(0u64);
+ let ptr = &*boxed as *const u64 as *const ();
+ let value = CompactLength::fit_content_calc(ptr);
+ assert!(value.is_fit_content_calc());
+ assert!(value.has_calc());
+ assert!(!value.is_plain_calc());
+ assert!(value.is_fit_content());
+ assert!(value.is_sizing_keyword());
+ assert!(value.is_intrinsic());
+ assert!(value.is_max_or_fit_content());
+ assert!(value.is_max_content_alike());
+ assert!(value.uses_percentage());
+ assert!(!value.is_length_or_percentage());
+ assert_eq!(value.calc_value(), ptr);
+
+ let calc = CompactLength::calc(ptr);
+ assert!(calc.is_plain_calc());
+ assert!(calc.has_calc());
+ assert!(!calc.is_fit_content_calc());
+ assert!(!calc.is_fit_content());
+ assert!(!calc.is_sizing_keyword());
+ }
+
+ #[test]
+ fn calc_round_trips_pointer() {
+ let boxed = Box::new(42u64);
+ let ptr = &*boxed as *const u64 as *const ();
+ let value = CompactLength::calc(ptr);
+ assert!(value.is_plain_calc());
+ assert!(value.uses_percentage());
+ assert!(!value.is_length_or_percentage());
+ assert!(!value.is_auto());
+ assert!(!value.is_intrinsic());
+ assert_eq!(value.calc_value(), ptr);
+ }
+}
diff --git a/vendor/taffy/src/style/dimension.rs b/vendor/taffy/src/style/dimension.rs
new file mode 100644
index 00000000..7297231d
--- /dev/null
+++ b/vendor/taffy/src/style/dimension.rs
@@ -0,0 +1,762 @@
+//! Style types for representing lengths / sizes
+use super::CompactLength;
+use crate::geometry::Rect;
+use crate::style_helpers::{FromLength, FromPercent, TaffyAuto, TaffyZero};
+#[cfg(feature = "parse")]
+use crate::util::parse::{from_str_from_css, CssParseResult, FromCss, Parser, Token};
+
+/// A unit of linear measurement
+///
+/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct LengthPercentage(pub(crate) CompactLength);
+impl TaffyZero for LengthPercentage {
+ const ZERO: Self = Self(CompactLength::ZERO);
+}
+impl FromLength for LengthPercentage {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for LengthPercentage {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for LengthPercentage {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ match parser.next()?.clone() {
+ Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(LengthPercentage);
+
+impl LengthPercentage {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLength::length(val))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLength::percent(val))
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ Self(CompactLength::calc(ptr))
+ }
+
+ /// Create a LengthPercentage from a raw `CompactLength`.
+ /// # Safety
+ /// CompactLength must represent a valid variant for LengthPercentage
+ #[allow(unsafe_code)]
+ pub const unsafe fn from_raw(val: CompactLength) -> Self {
+ Self(val)
+ }
+
+ /// Get the underlying `CompactLength` representation of the value
+ pub const fn into_raw(self) -> CompactLength {
+ self.0
+ }
+
+ /// Expand the compact representation into an [`ExpandedLengthPercentage`] enum.
+ ///
+ /// This is useful when integrating with other libraries (e.g. for style inspection or
+ /// serialization) as it allows the value to be pattern-matched without having to work
+ /// with the raw [`CompactLength`] tagged-pointer representation directly.
+ pub fn expand(self) -> ExpandedLengthPercentage {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => ExpandedLengthPercentage::Length(self.0.value()),
+ CompactLength::PERCENT_TAG => ExpandedLengthPercentage::Percent(self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => ExpandedLengthPercentage::Calc(self.0.calc_value()),
+ _ => unreachable!("LengthPercentage contains a value with an invalid tag"),
+ }
+ }
+}
+
+/// The expanded, non-compact representation of a [`LengthPercentage`].
+///
+/// Obtained via [`LengthPercentage::expand`]. Can be converted back into a [`LengthPercentage`]
+/// using the [`From`] implementation.
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum ExpandedLengthPercentage {
+ /// An absolute length (see [`LengthPercentage::length`])
+ Length(f32),
+ /// A percentage length (see [`LengthPercentage::percent`])
+ Percent(f32),
+ /// A `calc()` value (see [`LengthPercentage::calc`]). The pointer is an opaque handle to the
+ /// calc representation, exactly as passed to the constructor.
+ #[cfg(feature = "calc")]
+ Calc(*const ()),
+}
+
+impl From<LengthPercentage> for ExpandedLengthPercentage {
+ fn from(value: LengthPercentage) -> Self {
+ value.expand()
+ }
+}
+
+impl From<ExpandedLengthPercentage> for LengthPercentage {
+ fn from(value: ExpandedLengthPercentage) -> Self {
+ match value {
+ ExpandedLengthPercentage::Length(val) => Self::length(val),
+ ExpandedLengthPercentage::Percent(val) => Self::percent(val),
+ #[cfg(feature = "calc")]
+ ExpandedLengthPercentage::Calc(ptr) => Self::calc(ptr),
+ }
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for LengthPercentage {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let inner = CompactLength::deserialize(deserializer)?;
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
+ if matches!(inner.tag(), CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG) {
+ Ok(Self(inner))
+ } else {
+ Err(serde::de::Error::custom("Invalid tag"))
+ }
+ }
+}
+
+/// A unit of linear measurement
+///
+/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct LengthPercentageAuto(pub(crate) CompactLength);
+impl TaffyZero for LengthPercentageAuto {
+ const ZERO: Self = Self(CompactLength::ZERO);
+}
+impl TaffyAuto for LengthPercentageAuto {
+ const AUTO: Self = Self(CompactLength::AUTO);
+}
+impl FromLength for LengthPercentageAuto {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for LengthPercentageAuto {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+impl From<LengthPercentage> for LengthPercentageAuto {
+ fn from(input: LengthPercentage) -> Self {
+ Self(input.0)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for LengthPercentageAuto {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ match parser.next()?.clone() {
+ Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
+ Token::Ident(ident) if ident == "auto" => Ok(Self::auto()),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(LengthPercentageAuto);
+
+impl LengthPercentageAuto {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLength::length(val))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLength::percent(val))
+ }
+
+ /// The dimension should be automatically computed according to algorithm-specific rules
+ /// regarding the default size of boxes.
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ Self(CompactLength::auto())
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ Self(CompactLength::calc(ptr))
+ }
+
+ /// Create a LengthPercentageAuto from a raw `CompactLength`.
+ /// # Safety
+ /// CompactLength must represent a valid variant for LengthPercentageAuto
+ #[allow(unsafe_code)]
+ pub const unsafe fn from_raw(val: CompactLength) -> Self {
+ Self(val)
+ }
+
+ /// Get the underlying `CompactLength` representation of the value
+ pub const fn into_raw(self) -> CompactLength {
+ self.0
+ }
+
+ /// Returns:
+ /// - Some(length) for Length variants
+ /// - Some(resolved) using the provided context for Percent variants
+ /// - None for Auto variants
+ #[inline(always)]
+ pub fn resolve_to_option(self, context: f32, calc_resolver: impl Fn(*const (), f32) -> f32) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => Some(context * self.0.value()),
+ CompactLength::AUTO_TAG => None,
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => Some(calc_resolver(self.0.calc_value(), context)),
+ _ => unreachable!("LengthPercentageAuto values cannot be constructed with other tags"),
+ }
+ }
+
+ /// Returns true if value is LengthPercentageAuto::Auto
+ #[inline(always)]
+ pub fn is_auto(self) -> bool {
+ self.0.is_auto()
+ }
+
+ /// Expand the compact representation into an [`ExpandedLengthPercentageAuto`] enum.
+ ///
+ /// This is useful when integrating with other libraries (e.g. for style inspection or
+ /// serialization) as it allows the value to be pattern-matched without having to work
+ /// with the raw [`CompactLength`] tagged-pointer representation directly.
+ pub fn expand(self) -> ExpandedLengthPercentageAuto {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => ExpandedLengthPercentageAuto::Length(self.0.value()),
+ CompactLength::PERCENT_TAG => ExpandedLengthPercentageAuto::Percent(self.0.value()),
+ CompactLength::AUTO_TAG => ExpandedLengthPercentageAuto::Auto,
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => ExpandedLengthPercentageAuto::Calc(self.0.calc_value()),
+ _ => unreachable!("LengthPercentageAuto contains a value with an invalid tag"),
+ }
+ }
+}
+
+/// The expanded, non-compact representation of a [`LengthPercentageAuto`].
+///
+/// Obtained via [`LengthPercentageAuto::expand`]. Can be converted back into a
+/// [`LengthPercentageAuto`] using the [`From`] implementation.
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum ExpandedLengthPercentageAuto {
+ /// An absolute length (see [`LengthPercentageAuto::length`])
+ Length(f32),
+ /// A percentage length (see [`LengthPercentageAuto::percent`])
+ Percent(f32),
+ /// The automatic keyword (see [`LengthPercentageAuto::auto`])
+ Auto,
+ /// A `calc()` value (see [`LengthPercentageAuto::calc`]). The pointer is an opaque handle to
+ /// the calc representation, exactly as passed to the constructor.
+ #[cfg(feature = "calc")]
+ Calc(*const ()),
+}
+
+impl From<LengthPercentageAuto> for ExpandedLengthPercentageAuto {
+ fn from(value: LengthPercentageAuto) -> Self {
+ value.expand()
+ }
+}
+
+impl From<ExpandedLengthPercentageAuto> for LengthPercentageAuto {
+ fn from(value: ExpandedLengthPercentageAuto) -> Self {
+ match value {
+ ExpandedLengthPercentageAuto::Length(val) => Self::length(val),
+ ExpandedLengthPercentageAuto::Percent(val) => Self::percent(val),
+ ExpandedLengthPercentageAuto::Auto => Self::auto(),
+ #[cfg(feature = "calc")]
+ ExpandedLengthPercentageAuto::Calc(ptr) => Self::calc(ptr),
+ }
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for LengthPercentageAuto {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let inner = CompactLength::deserialize(deserializer)?;
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
+ if matches!(inner.tag(), CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG | CompactLength::AUTO_TAG) {
+ Ok(Self(inner))
+ } else {
+ Err(serde::de::Error::custom("Invalid tag"))
+ }
+ }
+}
+
+/// A unit of linear measurement
+///
+/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct Dimension(pub(crate) CompactLength);
+impl TaffyZero for Dimension {
+ const ZERO: Self = Self(CompactLength::ZERO);
+}
+impl TaffyAuto for Dimension {
+ const AUTO: Self = Self(CompactLength::AUTO);
+}
+impl FromLength for Dimension {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for Dimension {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+impl From<LengthPercentage> for Dimension {
+ fn from(input: LengthPercentage) -> Self {
+ Self(input.0)
+ }
+}
+impl From<LengthPercentageAuto> for Dimension {
+ fn from(input: LengthPercentageAuto) -> Self {
+ Self(input.0)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for Dimension {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let token = parser.next()?.clone();
+ match token {
+ Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
+ Token::Ident(ref ident) => match ident.as_ref() {
+ "auto" => Ok(Self::auto()),
+ "min-content" => Ok(Self::min_content()),
+ "max-content" => Ok(Self::max_content()),
+ "fit-content" => Ok(Self::fit_content()),
+ "stretch" => Ok(Self::stretch()),
+ "content" => Ok(Self::content()),
+ _ => Err(parser.new_unexpected_token_error(token))?,
+ },
+ Token::Function(ref name) if name.as_ref() == "fit-content" => parser.parse_nested_block(|parser| {
+ let token = parser.next()?.clone();
+ match token {
+ Token::Percentage { unit_value, .. } => Ok(Self::fit_content_percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::fit_content_px(value)),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(Dimension);
+
+impl Dimension {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLength::length(val))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLength::percent(val))
+ }
+
+ /// The dimension should be automatically computed according to algorithm-specific rules
+ /// regarding the default size of boxes.
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ Self(CompactLength::auto())
+ }
+
+ /// The size should be the "min-content" size.
+ /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ Self(CompactLength::min_content())
+ }
+
+ /// The size should be the "max-content" size.
+ /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ Self(CompactLength::max_content())
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, stretch))`
+ /// where `stretch` is the size the box would take if it filled the available space
+ #[inline(always)]
+ pub const fn fit_content() -> Self {
+ Self(CompactLength::fit_content_keyword())
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where `limit` is a LENGTH value
+ #[inline(always)]
+ pub const fn fit_content_px(limit: f32) -> Self {
+ Self(CompactLength::fit_content_px(limit))
+ }
+
+ /// The size should be the "stretch-fit" size: the size the box would take
+ /// if it filled the available space
+ /// (<https://www.w3.org/TR/css-sizing-4/#stretch-fit-sizing>)
+ #[inline(always)]
+ pub const fn stretch() -> Self {
+ Self(CompactLength::stretch())
+ }
+
+ /// The size should be an automatic size based on the box's content
+ /// (<https://www.w3.org/TR/css-flexbox-1/#valdef-flex-basis-content>)
+ ///
+ /// This keyword is only valid for `flex-basis`. In any other context it behaves as [`auto`](Self::auto).
+ #[inline(always)]
+ pub const fn content() -> Self {
+ Self(CompactLength::content())
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where `limit` is a PERCENTAGE value
+ #[inline(always)]
+ pub const fn fit_content_percent(limit: f32) -> Self {
+ Self(CompactLength::fit_content_percent(limit))
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ Self(CompactLength::calc(ptr))
+ }
+
+ /// A `fit-content()` value whose limit is a `calc()` value. The value passed here is treated as an opaque
+ /// handle to the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn fit_content_calc(ptr: *const ()) -> Self {
+ Self(CompactLength::fit_content_calc(ptr))
+ }
+
+ /// Returns true if the value is a `fit-content()` value with a `calc()` limit
+ #[inline(always)]
+ pub fn is_fit_content_calc(self) -> bool {
+ self.0.is_fit_content_calc()
+ }
+
+ /// Get the calc() pointer (valid for `calc()` and `fit-content(calc())` values)
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ pub fn calc_value(self) -> *const () {
+ self.0.calc_value()
+ }
+
+ /// Create a LengthPercentageAuto from a raw `CompactLength`.
+ /// # Safety
+ /// CompactLength must represent a valid variant for LengthPercentageAuto
+ #[allow(unsafe_code)]
+ pub const unsafe fn from_raw(val: CompactLength) -> Self {
+ Self(val)
+ }
+
+ /// Get the underlying `CompactLength` representation of the value
+ pub const fn into_raw(self) -> CompactLength {
+ self.0
+ }
+
+ /// Get Length value if value is Length variant
+ #[cfg(feature = "grid")]
+ pub fn into_option(self) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ _ => None,
+ }
+ }
+ /// Returns true if value is Auto
+ #[inline(always)]
+ pub fn is_auto(self) -> bool {
+ self.0.is_auto()
+ }
+
+ /// Returns true if value is min-content, max-content, fit-content, fit-content(...), or stretch
+ #[inline(always)]
+ pub fn is_sizing_keyword(self) -> bool {
+ self.0.is_sizing_keyword()
+ }
+
+ /// Returns true if value is the stretch keyword
+ #[inline(always)]
+ pub fn is_stretch(self) -> bool {
+ self.0.tag() == CompactLength::STRETCH_TAG
+ }
+
+ /// Returns true if value is the content keyword
+ #[inline(always)]
+ pub fn is_content(self) -> bool {
+ self.0.is_content()
+ }
+
+ /// Get the raw `CompactLength` tag
+ pub fn tag(self) -> usize {
+ self.0.tag()
+ }
+
+ /// Get the raw `CompactLength` value for non-calc variants that have a numeric parameter
+ pub fn value(self) -> f32 {
+ self.0.value()
+ }
+
+ /// Expand the compact representation into an [`ExpandedDimension`] enum.
+ ///
+ /// This is useful when integrating with other libraries (e.g. for style inspection or
+ /// serialization) as it allows the value to be pattern-matched without having to work
+ /// with the raw [`CompactLength`] tagged-pointer representation directly.
+ pub fn expand(self) -> ExpandedDimension {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => ExpandedDimension::Length(self.0.value()),
+ CompactLength::PERCENT_TAG => ExpandedDimension::Percent(self.0.value()),
+ CompactLength::AUTO_TAG => ExpandedDimension::Auto,
+ CompactLength::MIN_CONTENT_TAG => ExpandedDimension::MinContent,
+ CompactLength::MAX_CONTENT_TAG => ExpandedDimension::MaxContent,
+ CompactLength::FIT_CONTENT_PX_TAG => ExpandedDimension::FitContentPx(self.0.value()),
+ CompactLength::FIT_CONTENT_PERCENT_TAG => ExpandedDimension::FitContentPercent(self.0.value()),
+ CompactLength::FIT_CONTENT_KEYWORD_TAG => ExpandedDimension::FitContent,
+ #[cfg(feature = "calc")]
+ _ if self.0.is_fit_content_calc() => ExpandedDimension::FitContentCalc(self.0.calc_value()),
+ CompactLength::STRETCH_TAG => ExpandedDimension::Stretch,
+ CompactLength::CONTENT_TAG => ExpandedDimension::Content,
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => ExpandedDimension::Calc(self.0.calc_value()),
+ _ => unreachable!("Dimension contains a value with an invalid tag"),
+ }
+ }
+}
+
+/// The expanded, non-compact representation of a [`Dimension`].
+///
+/// Obtained via [`Dimension::expand`]. Can be converted back into a [`Dimension`] using the
+/// [`From`] implementation.
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum ExpandedDimension {
+ /// An absolute length (see [`Dimension::length`])
+ Length(f32),
+ /// A percentage length (see [`Dimension::percent`])
+ Percent(f32),
+ /// The automatic keyword (see [`Dimension::auto`])
+ Auto,
+ /// The `min-content` keyword (see [`Dimension::min_content`])
+ MinContent,
+ /// The `max-content` keyword (see [`Dimension::max_content`])
+ MaxContent,
+ /// A `fit-content(...)` value with a length limit (see [`Dimension::fit_content_px`])
+ FitContentPx(f32),
+ /// A `fit-content(...)` value with a percentage limit (see [`Dimension::fit_content_percent`])
+ FitContentPercent(f32),
+ /// The size is the fit-content size with a `calc()` limit (an opaque handle to the calc representation)
+ #[cfg(feature = "calc")]
+ FitContentCalc(*const ()),
+ /// The `fit-content` keyword with no limit (see [`Dimension::fit_content`])
+ FitContent,
+ /// The `stretch` keyword (see [`Dimension::stretch`])
+ Stretch,
+ /// The `content` keyword (see [`Dimension::content`])
+ Content,
+ /// A `calc()` value (see [`Dimension::calc`]). The pointer is an opaque handle to the calc
+ /// representation, exactly as passed to the constructor.
+ #[cfg(feature = "calc")]
+ Calc(*const ()),
+}
+
+impl From<Dimension> for ExpandedDimension {
+ fn from(value: Dimension) -> Self {
+ value.expand()
+ }
+}
+
+impl From<ExpandedDimension> for Dimension {
+ fn from(value: ExpandedDimension) -> Self {
+ match value {
+ ExpandedDimension::Length(val) => Self::length(val),
+ ExpandedDimension::Percent(val) => Self::percent(val),
+ ExpandedDimension::Auto => Self::auto(),
+ ExpandedDimension::MinContent => Self::min_content(),
+ ExpandedDimension::MaxContent => Self::max_content(),
+ ExpandedDimension::FitContentPx(val) => Self::fit_content_px(val),
+ ExpandedDimension::FitContentPercent(val) => Self::fit_content_percent(val),
+ ExpandedDimension::FitContent => Self::fit_content(),
+ #[cfg(feature = "calc")]
+ ExpandedDimension::FitContentCalc(ptr) => Self::fit_content_calc(ptr),
+ ExpandedDimension::Stretch => Self::stretch(),
+ ExpandedDimension::Content => Self::content(),
+ #[cfg(feature = "calc")]
+ ExpandedDimension::Calc(ptr) => Self::calc(ptr),
+ }
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for Dimension {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let inner = CompactLength::deserialize(deserializer)?;
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
+ if matches!(
+ inner.tag(),
+ CompactLength::LENGTH_TAG
+ | CompactLength::PERCENT_TAG
+ | CompactLength::AUTO_TAG
+ | CompactLength::MIN_CONTENT_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_KEYWORD_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ | CompactLength::STRETCH_TAG
+ | CompactLength::CONTENT_TAG
+ ) {
+ Ok(Self(inner))
+ } else {
+ Err(serde::de::Error::custom("Invalid tag"))
+ }
+ }
+}
+
+impl Rect<Dimension> {
+ /// Create a new Rect with length values
+ #[must_use]
+ pub const fn from_length(start: f32, end: f32, top: f32, bottom: f32) -> Self {
+ Rect {
+ left: Dimension(CompactLength::length(start)),
+ right: Dimension(CompactLength::length(end)),
+ top: Dimension(CompactLength::length(top)),
+ bottom: Dimension(CompactLength::length(bottom)),
+ }
+ }
+
+ /// Create a new Rect with percentage values
+ #[must_use]
+ pub const fn from_percent(start: f32, end: f32, top: f32, bottom: f32) -> Self {
+ Rect {
+ left: Dimension(CompactLength::percent(start)),
+ right: Dimension(CompactLength::percent(end)),
+ top: Dimension(CompactLength::percent(top)),
+ bottom: Dimension(CompactLength::percent(bottom)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod expand_tests {
+ use super::*;
+
+ /// A helper that produces a valid `calc()` handle for tests: a non-null pointer whose low
+ /// three bits are zero (as required by `CompactLength::calc`).
+ #[cfg(feature = "calc")]
+ fn calc_handle() -> *const () {
+ #[allow(dead_code)]
+ #[repr(align(8))]
+ struct Aligned(u64);
+ static HANDLE: Aligned = Aligned(0);
+ &HANDLE as *const Aligned as *const ()
+ }
+
+ #[test]
+ fn length_percentage_round_trips() {
+ let cases = [LengthPercentage::length(12.0), LengthPercentage::percent(0.5), LengthPercentage::ZERO];
+ for value in cases {
+ assert_eq!(LengthPercentage::from(value.expand()), value);
+ assert_eq!(ExpandedLengthPercentage::from(value), value.expand());
+ }
+ assert_eq!(LengthPercentage::length(3.0).expand(), ExpandedLengthPercentage::Length(3.0));
+ assert_eq!(LengthPercentage::percent(0.25).expand(), ExpandedLengthPercentage::Percent(0.25));
+ }
+
+ #[test]
+ fn length_percentage_auto_round_trips() {
+ let cases =
+ [LengthPercentageAuto::length(12.0), LengthPercentageAuto::percent(0.5), LengthPercentageAuto::auto()];
+ for value in cases {
+ assert_eq!(LengthPercentageAuto::from(value.expand()), value);
+ }
+ assert_eq!(LengthPercentageAuto::auto().expand(), ExpandedLengthPercentageAuto::Auto);
+ }
+
+ #[test]
+ fn dimension_round_trips_all_keywords() {
+ let cases = [
+ Dimension::length(12.0),
+ Dimension::percent(0.5),
+ Dimension::auto(),
+ Dimension::min_content(),
+ Dimension::max_content(),
+ Dimension::fit_content_px(30.0),
+ Dimension::fit_content_percent(0.75),
+ Dimension::fit_content(),
+ Dimension::stretch(),
+ Dimension::content(),
+ ];
+ for value in cases {
+ assert_eq!(Dimension::from(value.expand()), value);
+ }
+ assert_eq!(Dimension::fit_content_px(30.0).expand(), ExpandedDimension::FitContentPx(30.0));
+ assert_eq!(Dimension::content().expand(), ExpandedDimension::Content);
+ }
+
+ #[cfg(feature = "calc")]
+ #[test]
+ fn calc_round_trips() {
+ let handle = calc_handle();
+ assert_eq!(LengthPercentage::calc(handle).expand(), ExpandedLengthPercentage::Calc(handle));
+ assert_eq!(LengthPercentage::from(ExpandedLengthPercentage::Calc(handle)), LengthPercentage::calc(handle));
+ assert_eq!(Dimension::calc(handle).expand(), ExpandedDimension::Calc(handle));
+ assert_eq!(Dimension::fit_content_calc(handle).expand(), ExpandedDimension::FitContentCalc(handle));
+ assert_eq!(Dimension::from(ExpandedDimension::FitContentCalc(handle)), Dimension::fit_content_calc(handle));
+ assert_eq!(LengthPercentageAuto::calc(handle).expand(), ExpandedLengthPercentageAuto::Calc(handle));
+ }
+}
diff --git a/vendor/taffy/src/style/flex.rs b/vendor/taffy/src/style/flex.rs
new file mode 100644
index 00000000..20bc5e97
--- /dev/null
+++ b/vendor/taffy/src/style/flex.rs
@@ -0,0 +1,293 @@
+//! Style types for Flexbox layout
+use super::{AlignContent, AlignItems, AlignSelf, CoreStyle, Dimension, JustifyContent, LengthPercentage, Style};
+use crate::geometry::Size;
+
+/// The set of styles required for a Flexbox container
+pub trait FlexboxContainerStyle: CoreStyle {
+ /// Which direction does the main axis flow in?
+ #[inline(always)]
+ fn flex_direction(&self) -> FlexDirection {
+ Style::<Self::CustomIdent>::DEFAULT.flex_direction
+ }
+ /// Should elements wrap, or stay in a single line?
+ #[inline(always)]
+ fn flex_wrap(&self) -> FlexWrap {
+ Style::<Self::CustomIdent>::DEFAULT.flex_wrap
+ }
+ /// The minimum number of flex lines requested for a multi-line container. When items are
+ /// balanced ([`FlexWrap::Balance`] or [`FlexWrap::BalanceReverse`]) they are balanced into
+ /// at least this many lines. For any multi-line container, definite cross-axis available
+ /// space for measuring items is divided between this many lines.
+ #[cfg(feature = "flexbox_balance")]
+ #[inline(always)]
+ fn flex_line_count(&self) -> u16 {
+ Style::<Self::CustomIdent>::DEFAULT.flex_line_count
+ }
+
+ /// How large should the gaps between items in a grid or flex container be?
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ Style::<Self::CustomIdent>::DEFAULT.gap
+ }
+
+ // Alignment properties
+
+ /// How should content contained within this item be aligned in the cross/block axis
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ Style::<Self::CustomIdent>::DEFAULT.align_content
+ }
+ /// How this node's children aligned in the cross/block axis?
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ Style::<Self::CustomIdent>::DEFAULT.align_items
+ }
+ /// How this node's children should be aligned in the inline axis
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ Style::<Self::CustomIdent>::DEFAULT.justify_content
+ }
+}
+
+/// The set of styles required for a Flexbox item (child of a Flexbox container)
+pub trait FlexboxItemStyle: CoreStyle {
+ /// Sets the initial main axis size of the item
+ #[inline(always)]
+ fn flex_basis(&self) -> Dimension {
+ Style::<Self::CustomIdent>::DEFAULT.flex_basis
+ }
+ /// The relative rate at which this item grows when it is expanding to fill space
+ #[inline(always)]
+ fn flex_grow(&self) -> f32 {
+ Style::<Self::CustomIdent>::DEFAULT.flex_grow
+ }
+ /// The relative rate at which this item shrinks when it is contracting to fit into space
+ #[inline(always)]
+ fn flex_shrink(&self) -> f32 {
+ Style::<Self::CustomIdent>::DEFAULT.flex_shrink
+ }
+
+ /// How this node should be aligned in the cross/block axis
+ /// Falls back to the parents [`AlignItems`] if not set
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ Style::<Self::CustomIdent>::DEFAULT.align_self
+ }
+}
+
+use crate::geometry::AbsoluteAxis;
+
+/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
+///
+/// Defaults to [`FlexWrap::NoWrap`]
+///
+/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum FlexWrap {
+ /// Items will not wrap and stay on a single line
+ #[default]
+ NoWrap,
+ /// Items will wrap according to this item's [`FlexDirection`]
+ Wrap,
+ /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
+ WrapReverse,
+ /// Items will wrap according to this item's [`FlexDirection`], and be balanced across
+ /// lines such that the largest line is as small as possible
+ ///
+ /// [Specification](https://drafts.csswg.org/css-flexbox-2/#balance-values)
+ #[cfg(feature = "flexbox_balance")]
+ Balance,
+ /// Items will wrap in the opposite direction to this item's [`FlexDirection`], and be
+ /// balanced across lines such that the largest line is as small as possible
+ ///
+ /// [Specification](https://drafts.csswg.org/css-flexbox-2/#balance-values)
+ #[cfg(feature = "flexbox_balance")]
+ BalanceReverse,
+}
+
+impl FlexWrap {
+ /// Is this a wrapping mode (any value other than [`FlexWrap::NoWrap`])?
+ #[inline]
+ pub(crate) fn is_multi_line(self) -> bool {
+ self != Self::NoWrap
+ }
+
+ /// Do lines stack in the opposite direction to the cross axis?
+ #[inline]
+ pub(crate) fn is_reverse(self) -> bool {
+ match self {
+ Self::WrapReverse => true,
+ #[cfg(feature = "flexbox_balance")]
+ Self::BalanceReverse => true,
+ _ => false,
+ }
+ }
+
+ /// Are items balanced across lines?
+ #[cfg(feature = "flexbox_balance")]
+ #[inline]
+ pub(crate) fn is_balance(self) -> bool {
+ matches!(self, Self::Balance | Self::BalanceReverse)
+ }
+}
+
+#[cfg(all(feature = "parse", not(feature = "flexbox_balance")))]
+crate::util::parse::impl_parse_for_keyword_enum!(FlexWrap,
+ "nowrap" => NoWrap,
+ "wrap" => Wrap,
+ "wrap-reverse" => WrapReverse,
+);
+
+#[cfg(all(feature = "parse", feature = "flexbox_balance"))]
+impl crate::util::parse::FromCss for FlexWrap {
+ fn from_css<'i>(input: &mut crate::util::parse::Parser<'i, '_>) -> crate::util::parse::CssParseResult<'i, Self> {
+ let mut wrap: Option<Self> = None;
+ let mut balance = false;
+ let mut is_first = true;
+ loop {
+ let ident = if is_first {
+ input.expect_ident()?.clone()
+ } else {
+ match input.try_parse(|input| input.expect_ident().cloned()) {
+ Ok(ident) => ident,
+ Err(_) => break,
+ }
+ };
+ let is_valid = cssparser::match_ignore_ascii_case! { &ident,
+ "nowrap" => {
+ if is_first {
+ return Ok(Self::NoWrap);
+ }
+ false
+ },
+ "wrap" => wrap.replace(Self::Wrap).is_none(),
+ "wrap-reverse" => wrap.replace(Self::WrapReverse).is_none(),
+ "balance" => !core::mem::replace(&mut balance, true),
+ _ => false,
+ };
+ if !is_valid {
+ return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
+ }
+ is_first = false;
+ }
+ Ok(match (wrap, balance) {
+ (Some(Self::WrapReverse), true) => Self::BalanceReverse,
+ (_, true) => Self::Balance,
+ // At least one keyword is always parsed, so `wrap` must be `Some` if `balance` is false
+ (wrap, false) => wrap.unwrap_or(Self::NoWrap),
+ })
+ }
+}
+#[cfg(all(feature = "parse", feature = "flexbox_balance"))]
+crate::util::parse::from_str_from_css!(FlexWrap);
+
+/// The direction of the flexbox layout main axis.
+///
+/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
+/// Adding items will cause them to be positioned adjacent to each other along the main axis.
+/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
+///
+/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
+///
+/// The default behavior is [`FlexDirection::Row`].
+///
+/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum FlexDirection {
+ /// Defines +x as the main axis
+ ///
+ /// Items will be added from left to right in a row.
+ #[default]
+ Row,
+ /// Defines +y as the main axis
+ ///
+ /// Items will be added from top to bottom in a column.
+ Column,
+ /// Defines -x as the main axis
+ ///
+ /// Items will be added from right to left in a row.
+ RowReverse,
+ /// Defines -y as the main axis
+ ///
+ /// Items will be added from bottom to top in a column.
+ ColumnReverse,
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(FlexDirection,
+ "row" => Row,
+ "column" => Column,
+ "row-reverse" => RowReverse,
+ "column-reverse" => ColumnReverse,
+);
+
+impl FlexDirection {
+ #[inline]
+ /// Is the direction [`FlexDirection::Row`] or [`FlexDirection::RowReverse`]?
+ pub(crate) const fn is_row(self) -> bool {
+ matches!(self, Self::Row | Self::RowReverse)
+ }
+
+ #[inline]
+ /// Is the direction [`FlexDirection::Column`] or [`FlexDirection::ColumnReverse`]?
+ pub(crate) const fn is_column(self) -> bool {
+ matches!(self, Self::Column | Self::ColumnReverse)
+ }
+
+ #[inline]
+ /// Is the direction [`FlexDirection::RowReverse`] or [`FlexDirection::ColumnReverse`]?
+ pub(crate) const fn is_reverse(self) -> bool {
+ matches!(self, Self::RowReverse | Self::ColumnReverse)
+ }
+
+ #[inline]
+ /// The `AbsoluteAxis` that corresponds to the main axis
+ pub(crate) const fn main_axis(self) -> AbsoluteAxis {
+ match self {
+ Self::Row | Self::RowReverse => AbsoluteAxis::Horizontal,
+ Self::Column | Self::ColumnReverse => AbsoluteAxis::Vertical,
+ }
+ }
+
+ #[inline]
+ /// The `AbsoluteAxis` that corresponds to the cross axis
+ pub(crate) const fn cross_axis(self) -> AbsoluteAxis {
+ match self {
+ Self::Row | Self::RowReverse => AbsoluteAxis::Vertical,
+ Self::Column | Self::ColumnReverse => AbsoluteAxis::Horizontal,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ mod test_flex_direction {
+ use crate::style::*;
+
+ #[test]
+ fn flex_direction_is_row() {
+ assert!(FlexDirection::Row.is_row());
+ assert!(FlexDirection::RowReverse.is_row());
+ assert!(!FlexDirection::Column.is_row());
+ assert!(!FlexDirection::ColumnReverse.is_row());
+ }
+
+ #[test]
+ fn flex_direction_is_column() {
+ assert!(!FlexDirection::Row.is_column());
+ assert!(!FlexDirection::RowReverse.is_column());
+ assert!(FlexDirection::Column.is_column());
+ assert!(FlexDirection::ColumnReverse.is_column());
+ }
+
+ #[test]
+ fn flex_direction_is_reverse() {
+ assert!(!FlexDirection::Row.is_reverse());
+ assert!(FlexDirection::RowReverse.is_reverse());
+ assert!(!FlexDirection::Column.is_reverse());
+ assert!(FlexDirection::ColumnReverse.is_reverse());
+ }
+ }
+}
diff --git a/vendor/taffy/src/style/float.rs b/vendor/taffy/src/style/float.rs
new file mode 100644
index 00000000..6a8fb51b
--- /dev/null
+++ b/vendor/taffy/src/style/float.rs
@@ -0,0 +1,80 @@
+//! Style types for float layout
+
+/// Floats a box to the left or right.
+/// This property only applies to children of a block layout
+///
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/float>
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Float {
+ /// The box is floated to the left
+ Left,
+ /// The box is floated to the right
+ Right,
+ /// The box is not floated
+ #[default]
+ None,
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Float,
+ "left" => Left,
+ "right" => Right,
+ "none" => None,
+);
+
+/// Whether a box that is definitely floated is floated to the left
+/// of to the right.
+///
+/// This type is only used in the low-level parts of the
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[repr(u8)]
+pub enum FloatDirection {
+ /// The box is floated to the left
+ Left = 0,
+ /// The box is floated to the right
+ Right = 1,
+}
+
+impl Float {
+ /// Whether the box is floated
+ pub fn is_floated(self) -> bool {
+ matches!(self, Self::Left | Self::Right)
+ }
+
+ /// Converts [`Float`] into `Option<FloatDirection>`ca
+ pub fn float_direction(&self) -> Option<FloatDirection> {
+ match self {
+ Float::Left => Some(FloatDirection::Left),
+ Float::Right => Some(FloatDirection::Right),
+ Float::None => None,
+ }
+ }
+}
+
+/// Gives a box "clearance", which moves it below floated boxes which precede
+/// it in the tree.
+///
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/clear>
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Clear {
+ /// The box clears left-floated boxes
+ Left,
+ /// The box clears right-floated boxes
+ Right,
+ /// The box clears boxes floated in either direction
+ Both,
+ /// The box does not clear floated boxes
+ #[default]
+ None,
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Clear,
+ "left" => Left,
+ "right" => Right,
+ "both" => Both,
+ "none" => None,
+);
diff --git a/vendor/taffy/src/style/grid.rs b/vendor/taffy/src/style/grid.rs
new file mode 100644
index 00000000..f6ffa809
--- /dev/null
+++ b/vendor/taffy/src/style/grid.rs
@@ -0,0 +1,1978 @@
+//! Style types for CSS Grid layout
+use super::{
+ AlignContent, AlignContentKeyword, AlignItems, AlignSelf, CheapCloneStr, CompactLength, CoreStyle, Dimension,
+ JustifyContent, LengthPercentage, LengthPercentageAuto, Style,
+};
+use crate::compute::grid::{GridCoordinate, GridLine, OriginZeroLine, MAX_GRID_TRACKS};
+use crate::geometry::{AbsoluteAxis, AbstractAxis, Line, MinMax, Size};
+use crate::style_helpers::*;
+use crate::sys::{DefaultCheapStr, Vec};
+use core::cmp::{max, min};
+use core::fmt::Debug;
+
+#[cfg(feature = "parse")]
+use crate::util::parse::{
+ from_str_from_css, parse_css_str_entirely, CssParseResult, FromCss, ParseError, Parser, Token,
+};
+
+/// Defines the value of the `grid-template-areas` property: the named areas plus the overall
+/// size (in tracks) of the area template.
+///
+/// The template may be larger than the extents of the named areas due to unnamed (`.`) cells,
+/// so the size is stored explicitly.
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct GridTemplateAreas<CustomIdent: CheapCloneStr> {
+ /// The named grid areas
+ pub areas: crate::util::sys::GridTrackVec<GridTemplateArea<CustomIdent>>,
+ /// The number of rows in the area template
+ pub row_count: u16,
+ /// The number of columns in the area template
+ pub column_count: u16,
+}
+
+/// Defines a grid area
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct GridTemplateArea<CustomIdent: CheapCloneStr> {
+ /// The name of the grid area which
+ #[cfg_attr(feature = "serde", serde(deserialize_with = "crate::util::deserialize_from_str"))]
+ pub name: CustomIdent,
+ /// The index of the row at which the grid area starts in grid coordinates.
+ pub row_start: u16,
+ /// The index of the row at which the grid area ends in grid coordinates.
+ pub row_end: u16,
+ /// The index of the column at which the grid area starts in grid coordinates.
+ pub column_start: u16,
+ /// The index of the column at which the grid area end in grid coordinates.
+ pub column_end: u16,
+}
+
+/// Defines a named grid line
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct NamedGridLine<CustomIdent: CheapCloneStr> {
+ /// The name of the grid area which
+ #[cfg_attr(feature = "serde", serde(deserialize_with = "crate::util::deserialize_from_str"))]
+ pub name: CustomIdent,
+ /// The index of the row at which the grid area starts in grid coordinates.
+ pub index: u16,
+}
+
+/// Axis as `Row` or `Column`
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) enum GridAreaAxis {
+ /// The `Row` axis
+ Row,
+ /// The `Column` axis
+ Column,
+}
+
+/// Logical end (`Start` or `End`)
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) enum GridAreaEnd {
+ /// The `Start` end
+ Start,
+ /// The `End` end
+ End,
+}
+
+/// A trait to represent a `repeat()` clause in a `grid-template-*` definition
+pub trait GenericRepetition {
+ /// The type that represents `<custom-ident>`s (for named lines)
+ type CustomIdent: CheapCloneStr;
+ /// The type which represents an iterator over the list of repeated tracks
+ type RepetitionTrackList<'a>: Iterator<Item = TrackSizingFunction> + ExactSizeIterator + Clone
+ where
+ Self: 'a;
+
+ /// A nested iterator of line names (nested because each line may have multiple associated names)
+ type TemplateLineNames<'a>: TemplateLineNames<'a, Self::CustomIdent>
+ where
+ Self: 'a;
+ /// The repetition count (integer, auto-fill, or auto-fit)
+ fn count(&self) -> RepetitionCount;
+ /// Get an iterator over the repeated tracks
+ fn tracks(&self) -> Self::RepetitionTrackList<'_>;
+ /// Returns the number of repeated tracks
+ fn track_count(&self) -> u16 {
+ self.tracks().len().min(u16::MAX as usize) as u16
+ }
+ /// Returns an iterator over the lines names
+ ///
+ /// Line name sets are positional: set `i` names the `i`th line of each repetition. The iterator
+ /// must yield either no line name sets at all (all lines are unnamed) or exactly
+ /// `track_count() + 1` of them (one set per line, including both edge lines).
+ fn lines_names(&self) -> Self::TemplateLineNames<'_>;
+}
+
+/// A nested list of line names. This is effectively a generic representation of `Vec<Vec<String>>` that allows
+/// both the collection and string type to be customised.
+#[rustfmt::skip]
+pub trait TemplateLineNames<'a, S: CheapCloneStr> : Iterator<Item = Self::LineNameSet<'a>> + ExactSizeIterator + Clone where Self: 'a {
+ /// A simple list line names. This is effectively a generic representation of `VecString>` that allows
+ /// both the collection and string type to be customised.
+ type LineNameSet<'b>: Iterator<Item = &'b S> + ExactSizeIterator + Clone where Self: 'b;
+}
+
+impl<'a, S: CheapCloneStr> TemplateLineNames<'a, S>
+ for core::iter::Map<core::slice::Iter<'a, Vec<S>>, fn(&Vec<S>) -> core::slice::Iter<'_, S>>
+{
+ type LineNameSet<'b>
+ = core::slice::Iter<'b, S>
+ where
+ Self: 'b;
+}
+
+#[derive(Copy, Clone)]
+/// A type representing a component in a `grid-template-*` defintion where the type
+/// representing `repeat()`s is generic
+pub enum GenericGridTemplateComponent<S, Repetition>
+where
+ S: CheapCloneStr,
+ Repetition: GenericRepetition<CustomIdent = S>,
+{
+ /// A single track sizing function
+ Single(TrackSizingFunction),
+ /// A `repeat()`
+ Repeat(Repetition),
+}
+
+impl<S, Repetition> GenericGridTemplateComponent<S, Repetition>
+where
+ S: CheapCloneStr,
+ Repetition: GenericRepetition<CustomIdent = S>,
+{
+ /// Whether the track definition is a auto-repeated fragment
+ pub fn is_auto_repetition(&self) -> bool {
+ match self {
+ Self::Single(_) => false,
+ Self::Repeat(repeat) => matches!(repeat.count(), RepetitionCount::AutoFit | RepetitionCount::AutoFill),
+ }
+ }
+}
+
+/// The set of styles required for a CSS Grid container
+pub trait GridContainerStyle: CoreStyle {
+ /// The type for a `repeat()` within a grid_template_rows or grid_template_columns
+ type Repetition<'a>: GenericRepetition<CustomIdent = Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// The type returned by grid_template_rows and grid_template_columns
+ type TemplateTrackList<'a>: Iterator<Item = GenericGridTemplateComponent<Self::CustomIdent, Self::Repetition<'a>>>
+ + ExactSizeIterator
+ + Clone
+ where
+ Self: 'a;
+
+ /// The type returned by grid_auto_rows and grid_auto_columns
+ type AutoTrackList<'a>: Iterator<Item = TrackSizingFunction> + ExactSizeIterator + Clone
+ where
+ Self: 'a;
+
+ /// The type returned by grid_template_row_names and grid_template_column_names
+ //IntoIterator<Item = &'a Self::LineNameSet<'a>>
+ type TemplateLineNames<'a>: TemplateLineNames<'a, Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// The type of custom identifiers used to identify named grid lines and areas
+ type GridTemplateAreas<'a>: IntoIterator<Item = GridTemplateArea<Self::CustomIdent>>
+ where
+ Self: 'a;
+
+ // FIXME: re-add default implemenations for grid_{template,auto}_{rows,columns} once the
+ // associated_type_defaults feature (https://github.com/rust-lang/rust/issues/29661) is stabilised.
+
+ /// Defines the track sizing functions (heights) of the grid rows
+ fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>>;
+ /// Defines the track sizing functions (widths) of the grid columns
+ fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>>;
+ /// Defines the size of implicitly created rows
+ fn grid_auto_rows(&self) -> Self::AutoTrackList<'_>;
+ /// Defined the size of implicitly created columns
+ fn grid_auto_columns(&self) -> Self::AutoTrackList<'_>;
+
+ /// Named grid areas
+ fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>>;
+ /// The number of rows in the `grid-template-areas` template (0 if there is no template).
+ /// May be greater than the extent of the named areas due to unnamed (`.`) cells.
+ fn grid_template_area_row_count(&self) -> u16 {
+ self.grid_template_areas()
+ .map(|areas| areas.into_iter().map(|area| area.row_end.max(1) - 1).max().unwrap_or(0))
+ .unwrap_or(0)
+ }
+ /// The number of columns in the `grid-template-areas` template (0 if there is no template).
+ /// May be greater than the extent of the named areas due to unnamed (`.`) cells.
+ fn grid_template_area_column_count(&self) -> u16 {
+ self.grid_template_areas()
+ .map(|areas| areas.into_iter().map(|area| area.column_end.max(1) - 1).max().unwrap_or(0))
+ .unwrap_or(0)
+ }
+ /// Defines the line names for row lines
+ fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>>;
+ /// Defines the size of implicitly created rows
+ fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>>;
+
+ /// Controls how items get placed into the grid for auto-placed items
+ #[inline(always)]
+ fn grid_auto_flow(&self) -> GridAutoFlow {
+ Style::<Self::CustomIdent>::DEFAULT.grid_auto_flow
+ }
+
+ /// How large should the gaps between items in a grid or flex container be?
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ Style::<Self::CustomIdent>::DEFAULT.gap
+ }
+
+ // Alignment properties
+
+ /// How should content contained within this item be aligned in the cross/block axis
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ Style::<Self::CustomIdent>::DEFAULT.align_content
+ }
+ /// How should contained within this item be aligned in the main/inline axis
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ Style::<Self::CustomIdent>::DEFAULT.justify_content
+ }
+ /// How this node's children aligned in the cross/block axis?
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ Style::<Self::CustomIdent>::DEFAULT.align_items
+ }
+ /// How this node's children should be aligned in the inline axis
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ Style::<Self::CustomIdent>::DEFAULT.justify_items
+ }
+
+ /// Get a grid item's row or column placement depending on the axis passed
+ #[inline(always)]
+ fn grid_template_tracks(&self, axis: AbsoluteAxis) -> Option<Self::TemplateTrackList<'_>> {
+ match axis {
+ AbsoluteAxis::Horizontal => self.grid_template_columns(),
+ AbsoluteAxis::Vertical => self.grid_template_rows(),
+ }
+ }
+
+ /// Get a grid container's align-content or justify-content alignment depending on the axis passed
+ /// (with `normal` resolved to `stretch`)
+ #[inline(always)]
+ fn grid_align_content(&self, axis: AbstractAxis) -> AlignContent {
+ let alignment = match axis {
+ AbstractAxis::Inline => self.justify_content(),
+ AbstractAxis::Block => self.align_content(),
+ };
+ match alignment.keyword {
+ AlignContentKeyword::Normal => AlignContent::STRETCH,
+ _ => alignment,
+ }
+ }
+}
+
+/// The set of styles required for a CSS Grid item (child of a CSS Grid container)
+pub trait GridItemStyle: CoreStyle {
+ /// Defines which row in the grid the item should start and end at
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ Default::default()
+ }
+ /// Defines which column in the grid the item should start and end at
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ Default::default()
+ }
+
+ /// How this node should be aligned in the cross/block axis
+ /// Falls back to the parents [`AlignItems`] if not set
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ Style::<Self::CustomIdent>::DEFAULT.align_self
+ }
+ /// How this node should be aligned in the inline axis
+ /// Falls back to the parents [`super::JustifyItems`] if not set
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ Style::<Self::CustomIdent>::DEFAULT.justify_self
+ }
+
+ /// Get a grid item's row or column placement depending on the axis passed
+ #[inline(always)]
+ fn grid_placement(&self, axis: AbsoluteAxis) -> Line<GridPlacement<Self::CustomIdent>> {
+ match axis {
+ AbsoluteAxis::Horizontal => self.grid_column(),
+ AbsoluteAxis::Vertical => self.grid_row(),
+ }
+ }
+}
+
+/// Controls whether grid items are placed row-wise or column-wise. And whether the sparse or dense packing algorithm is used.
+///
+/// The "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause items to appear out-of-order, when doing so would fill in holes left by larger items.
+///
+/// Defaults to [`GridAutoFlow::Row`]
+///
+/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow)
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum GridAutoFlow {
+ /// Items are placed by filling each row in turn, adding new rows as necessary
+ #[default]
+ Row,
+ /// Items are placed by filling each column in turn, adding new columns as necessary.
+ Column,
+ /// Combines `Row` with the dense packing algorithm.
+ RowDense,
+ /// Combines `Column` with the dense packing algorithm.
+ ColumnDense,
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for GridAutoFlow {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let mut axis: Option<&'static str> = None;
+ let mut dense = false;
+
+ for _ in 0..2 {
+ if let Ok(ident) = parser.try_parse(|parser| parser.expect_ident_cloned()) {
+ match &*ident {
+ "row" => {
+ axis = Some("row");
+ }
+ "column" => {
+ axis = Some("column");
+ }
+ "dense" => dense = true,
+ _ => {
+ return Err(parser.new_unexpected_token_error(Token::Ident(ident)));
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ match (axis, dense) {
+ (Some("row"), false) => Ok(Self::Row),
+ (Some("row") | None, true) => Ok(Self::RowDense),
+ (Some("column"), false) => Ok(Self::Column),
+ (Some("column"), true) => Ok(Self::ColumnDense),
+ (None, false) => {
+ let token = parser.next().cloned()?;
+ Err(parser.new_unexpected_token_error(token))
+ }
+ _ => unreachable!(),
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(GridAutoFlow);
+
+impl GridAutoFlow {
+ /// Whether grid auto placement uses the sparse placement algorithm or the dense placement algorithm
+ /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow#values>
+ pub const fn is_dense(&self) -> bool {
+ match self {
+ Self::Row | Self::Column => false,
+ Self::RowDense | Self::ColumnDense => true,
+ }
+ }
+
+ /// Whether grid auto placement fills areas row-wise or column-wise
+ /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow#values>
+ pub const fn primary_axis(&self) -> AbsoluteAxis {
+ match self {
+ Self::Row | Self::RowDense => AbsoluteAxis::Horizontal,
+ Self::Column | Self::ColumnDense => AbsoluteAxis::Vertical,
+ }
+ }
+}
+
+/// A grid line placement specification which is generic over the coordinate system that it uses to define
+/// grid line positions.
+///
+/// `GenericGridPlacement<GridLine>` is aliased as GridPlacement and is exposed to users of Taffy to define styles.
+/// `GenericGridPlacement<OriginZeroLine>` is aliased as OriginZeroGridPlacement and is used internally for placement computations.
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum GenericGridPlacement<LineType: GridCoordinate> {
+ /// Place item according to the auto-placement algorithm, and the parent's grid_auto_flow property
+ Auto,
+ /// Place item at specified line (column or row) index
+ Line(LineType),
+ /// Item should span specified number of tracks (columns or rows)
+ Span(u16),
+}
+
+/// A grid line placement using the normalized OriginZero coordinates to specify line positions.
+pub(crate) type OriginZeroGridPlacement = GenericGridPlacement<OriginZeroLine>;
+
+/// A grid line placement using CSS grid line coordinates to specify line positions. This uses the same coordinate
+/// system as the public `GridPlacement` type but doesn't support named lines (these are expected to have already
+/// been resolved by the time values of this type are constructed).
+pub(crate) type NonNamedGridPlacement = GenericGridPlacement<GridLine>;
+
+/// A grid line placement specification. Used for grid-[row/column]-[start/end]. Named tracks are not implemented.
+///
+/// Defaults to `GridPlacement::Auto`
+///
+/// [Specification](https://www.w3.org/TR/css3-grid-layout/#typedef-grid-row-start-grid-line)
+#[derive(Clone, PartialEq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum GridPlacement<S: CheapCloneStr = DefaultCheapStr> {
+ /// Place item according to the auto-placement algorithm, and the parent's grid_auto_flow property
+ #[default]
+ Auto,
+ /// Place item at specified line (column or row) index
+ Line(GridLine),
+ /// Place item at specified named line (column or row)
+ NamedLine(S, i16),
+ /// Item should span specified number of tracks (columns or rows)
+ Span(u16),
+ /// Item should span until the nth line named `<name>`.
+ ///
+ /// If there are less than n lines named `<name>` in the specified direction then
+ /// all implicit lines will be counted.
+ NamedSpan(S, u16),
+}
+impl<S: CheapCloneStr> TaffyAuto for GridPlacement<S> {
+ const AUTO: Self = Self::Auto;
+}
+impl<S: CheapCloneStr> TaffyGridLine for GridPlacement<S> {
+ fn from_line_index(index: i16) -> Self {
+ GridPlacement::<S>::Line(GridLine::from(index))
+ }
+}
+impl<S: CheapCloneStr> TaffyGridLine for Line<GridPlacement<S>> {
+ fn from_line_index(index: i16) -> Self {
+ Line { start: GridPlacement::<S>::from_line_index(index), end: GridPlacement::<S>::Auto }
+ }
+}
+impl<S: CheapCloneStr> TaffyGridSpan for GridPlacement<S> {
+ fn from_span(span: u16) -> Self {
+ GridPlacement::<S>::Span(span)
+ }
+}
+impl<S: CheapCloneStr> TaffyGridSpan for Line<GridPlacement<S>> {
+ fn from_span(span: u16) -> Self {
+ Line { start: GridPlacement::<S>::from_span(span), end: GridPlacement::<S>::Auto }
+ }
+}
+
+#[cfg(feature = "parse")]
+/// Saturates an `i32` to the range representable by `i16`.
+fn saturating_i16(value: i32) -> i16 {
+ value.clamp(i16::MIN as i32, i16::MAX as i32) as i16
+}
+
+#[cfg(feature = "parse")]
+/// Saturates an `i32` to the range representable by `u16`.
+fn saturating_u16(value: i32) -> u16 {
+ value.clamp(u16::MIN as i32, u16::MAX as i32) as u16
+}
+
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr> FromCss for GridPlacement<S> {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let mut span = false;
+ let mut number = None;
+ let mut ident = None;
+
+ while !parser.is_exhausted() {
+ let token = parser.next()?.clone();
+ match &token {
+ Token::Ident(s) => match s.as_ref() {
+ "auto" => {
+ if span || number.is_some() || ident.is_some() {
+ return Err(parser.new_unexpected_token_error(token));
+ }
+ parser.expect_exhausted()?;
+ return Ok(Self::Auto);
+ }
+ "span" => {
+ if span {
+ return Err(parser.new_unexpected_token_error(token));
+ }
+ span = true;
+ }
+ other => {
+ if ident.is_some() {
+ return Err(parser.new_unexpected_token_error(token));
+ }
+ ident = Some(S::from(other));
+ }
+ },
+ Token::Number { int_value: Some(value), .. } if *value != 0 => {
+ if number.is_some() {
+ return Err(parser.new_unexpected_token_error(token));
+ }
+ number = Some(*value);
+ }
+ _ => return Err(parser.new_unexpected_token_error(token)),
+ };
+ }
+
+ match (span, number, ident) {
+ (true, None, None) => Ok(Self::Span(0)),
+ (true, Some(number), None) => Ok(Self::Span(saturating_u16(number))),
+ (true, None, Some(ident)) => Ok(Self::NamedSpan(ident, 0)),
+ (true, Some(number), Some(ident)) => Ok(Self::NamedSpan(ident, saturating_u16(number))),
+ (false, Some(number), None) => Ok(Self::Line(GridLine::from(saturating_i16(number)))),
+ (false, Some(number), Some(ident)) => Ok(Self::NamedLine(ident, saturating_i16(number))),
+ (false, None, Some(ident)) => Ok(Self::NamedLine(ident, 0)),
+ (false, None, None) => Err(parser.new_error(cssparser::BasicParseErrorKind::EndOfInput)),
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr> core::str::FromStr for GridPlacement<S> {
+ type Err = ParseError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ parse_css_str_entirely(input)
+ }
+}
+
+impl<S: CheapCloneStr> GridPlacement<S> {
+ /// Apply a mapping function if the [`GridPlacement`] is a `Line`. Otherwise return `self` unmodified.
+ pub fn into_origin_zero_placement_ignoring_named(&self, explicit_track_count: u16) -> OriginZeroGridPlacement {
+ match self {
+ Self::Auto => OriginZeroGridPlacement::Auto,
+ // Spans are clamped between 1 (a zero span is an invalid value which is treated as 1)
+ // and the maximum track limit (https://www.w3.org/TR/css-grid-1/#overlarge-grids)
+ Self::Span(span) => OriginZeroGridPlacement::Span((*span).clamp(1, MAX_GRID_TRACKS)),
+ // Grid line zero is an invalid index, so it gets treated as Auto
+ // See: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start#values
+ Self::Line(line) => match line.as_i16() {
+ 0 => OriginZeroGridPlacement::Auto,
+ _ => OriginZeroGridPlacement::Line(line.into_origin_zero_line(explicit_track_count)),
+ },
+ Self::NamedLine(_, _) => OriginZeroGridPlacement::Auto,
+ Self::NamedSpan(_, _) => OriginZeroGridPlacement::Auto,
+ }
+ }
+}
+
+impl<S: CheapCloneStr> Line<GridPlacement<S>> {
+ /// Apply a mapping function if the [`GridPlacement`] is a `Line`. Otherwise return `self` unmodified.
+ pub fn into_origin_zero_ignoring_named(&self, explicit_track_count: u16) -> Line<OriginZeroGridPlacement> {
+ Line {
+ start: self.start.into_origin_zero_placement_ignoring_named(explicit_track_count),
+ end: self.end.into_origin_zero_placement_ignoring_named(explicit_track_count),
+ }
+ }
+}
+
+impl NonNamedGridPlacement {
+ /// Apply a mapping function if the [`GridPlacement`] is a `Track`. Otherwise return `self` unmodified.
+ pub fn into_origin_zero_placement(
+ &self,
+ explicit_track_count: u16,
+ // resolve_named: impl Fn(&str) -> Option<GridLine>
+ ) -> OriginZeroGridPlacement {
+ match self {
+ Self::Auto => OriginZeroGridPlacement::Auto,
+ // Spans are clamped between 1 (a zero span is an invalid value which is treated as 1)
+ // and the maximum track limit (https://www.w3.org/TR/css-grid-1/#overlarge-grids)
+ Self::Span(span) => OriginZeroGridPlacement::Span((*span).clamp(1, MAX_GRID_TRACKS)),
+ // Grid line zero is an invalid index, so it gets treated as Auto
+ // See: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start#values
+ Self::Line(line) => match line.as_i16() {
+ 0 => OriginZeroGridPlacement::Auto,
+ _ => OriginZeroGridPlacement::Line(line.into_origin_zero_line(explicit_track_count)),
+ },
+ }
+ }
+}
+
+impl<T: GridCoordinate> Line<GenericGridPlacement<T>> {
+ /// Resolves the span for an indefinite placement (a placement that does not consist of two `Track`s).
+ /// Panics if called on a definite placement
+ pub const fn indefinite_span(&self) -> u16 {
+ use GenericGridPlacement as GP;
+ match (self.start, self.end) {
+ (GP::Line(_), GP::Auto) => 1,
+ (GP::Auto, GP::Line(_)) => 1,
+ (GP::Auto, GP::Auto) => 1,
+ (GP::Line(_), GP::Span(span)) => span,
+ (GP::Span(span), GP::Line(_)) => span,
+ (GP::Span(span), GP::Auto) => span,
+ (GP::Auto, GP::Span(span)) => span,
+ (GP::Span(span), GP::Span(_)) => span,
+ (GP::Line(_), GP::Line(_)) => panic!("indefinite_span should only be called on indefinite grid tracks"),
+ }
+ }
+}
+
+impl<S: CheapCloneStr> Line<GridPlacement<S>> {
+ #[inline]
+ /// Whether the track position is definite in this axis (or the item will need auto placement)
+ /// The track position is definite if least one of the start and end positions is a NON-ZERO track index
+ /// (0 is an invalid line in GridLine coordinates, and falls back to "auto" which is indefinite)
+ pub fn is_definite(&self) -> bool {
+ match (&self.start, &self.end) {
+ (GridPlacement::Line(line), _) if line.as_i16() != 0 => true,
+ (_, GridPlacement::Line(line)) if line.as_i16() != 0 => true,
+ (GridPlacement::NamedLine(_, _), _) => true,
+ (_, GridPlacement::NamedLine(_, _)) => true,
+ _ => false,
+ }
+ }
+}
+
+impl Line<NonNamedGridPlacement> {
+ #[inline]
+ /// Whether the track position is definite in this axis (or the item will need auto placement)
+ /// The track position is definite if least one of the start and end positions is a NON-ZERO track index
+ /// (0 is an invalid line in GridLine coordinates, and falls back to "auto" which is indefinite)
+ pub fn is_definite(&self) -> bool {
+ match (&self.start, &self.end) {
+ (GenericGridPlacement::Line(line), _) if line.as_i16() != 0 => true,
+ (_, GenericGridPlacement::Line(line)) if line.as_i16() != 0 => true,
+ _ => false,
+ }
+ }
+
+ /// Apply a mapping function if the [`GridPlacement`] is a `Track`. Otherwise return `self` unmodified.
+ pub fn into_origin_zero(&self, explicit_track_count: u16) -> Line<OriginZeroGridPlacement> {
+ Line {
+ start: self.start.into_origin_zero_placement(explicit_track_count),
+ end: self.end.into_origin_zero_placement(explicit_track_count),
+ }
+ }
+}
+
+impl Line<OriginZeroGridPlacement> {
+ #[inline]
+ /// Whether the track position is definite in this axis (or the item will need auto placement)
+ /// The track position is definite if least one of the start and end positions is a track index
+ pub const fn is_definite(&self) -> bool {
+ matches!((self.start, self.end), (GenericGridPlacement::Line(_), _) | (_, GenericGridPlacement::Line(_)))
+ }
+
+ /// If at least one of the of the start and end positions is a track index then the other end can be resolved
+ /// into a track index purely based on the information contained with the placement specification
+ pub fn resolve_definite_grid_lines(&self) -> Line<OriginZeroLine> {
+ use OriginZeroGridPlacement as GP;
+ match (self.start, self.end) {
+ (GP::Line(line1), GP::Line(line2)) => {
+ if line1 == line2 {
+ Line { start: line1, end: line1 + 1 }
+ } else {
+ Line { start: min(line1, line2), end: max(line1, line2) }
+ }
+ }
+ (GP::Line(line), GP::Span(span)) => Line { start: line, end: line + span },
+ (GP::Line(line), GP::Auto) => Line { start: line, end: line + 1 },
+ (GP::Span(span), GP::Line(line)) => Line { start: line - span, end: line },
+ (GP::Auto, GP::Line(line)) => Line { start: line - 1, end: line },
+ _ => panic!("resolve_definite_grid_tracks should only be called on definite grid tracks"),
+ }
+ }
+
+ /// For absolutely positioned items:
+ /// - Tracks resolve to definite tracks
+ /// - For Spans:
+ /// - If the other position is a Track, they resolve to a definite track relative to the other track
+ /// - Else resolve to None
+ /// - Auto resolves to None
+ ///
+ /// When finally positioning the item, a value of None means that the item's grid area is bounded by the grid
+ /// container's border box on that side.
+ pub fn resolve_absolutely_positioned_grid_tracks(&self) -> Line<Option<OriginZeroLine>> {
+ use OriginZeroGridPlacement as GP;
+ match (self.start, self.end) {
+ (GP::Line(track1), GP::Line(track2)) => {
+ if track1 == track2 {
+ Line { start: Some(track1), end: Some(track1 + 1) }
+ } else {
+ Line { start: Some(min(track1, track2)), end: Some(max(track1, track2)) }
+ }
+ }
+ (GP::Line(track), GP::Span(span)) => Line { start: Some(track), end: Some(track + span) },
+ (GP::Line(track), GP::Auto) => Line { start: Some(track), end: None },
+ (GP::Span(span), GP::Line(track)) => Line { start: Some(track - span), end: Some(track) },
+ (GP::Auto, GP::Line(track)) => Line { start: None, end: Some(track) },
+ _ => Line { start: None, end: None },
+ }
+ }
+
+ /// If neither of the start and end positions is a track index then the other end can be resolved
+ /// into a track index if a definite start position is supplied externally
+ pub fn resolve_indefinite_grid_tracks(&self, start: OriginZeroLine) -> Line<OriginZeroLine> {
+ use OriginZeroGridPlacement as GP;
+ match (self.start, self.end) {
+ (GP::Auto, GP::Auto) => Line { start, end: start + 1 },
+ (GP::Span(span), GP::Auto) => Line { start, end: start + span },
+ (GP::Auto, GP::Span(span)) => Line { start, end: start + span },
+ (GP::Span(span), GP::Span(_)) => Line { start, end: start + span },
+ _ => panic!("resolve_indefinite_grid_tracks should only be called on indefinite grid tracks"),
+ }
+ }
+}
+
+/// Represents the start and end points of a GridItem within a given axis
+impl<S: CheapCloneStr> Default for Line<GridPlacement<S>> {
+ fn default() -> Self {
+ Line { start: GridPlacement::<S>::Auto, end: GridPlacement::<S>::Auto }
+ }
+}
+
+/// Maximum track sizing function
+///
+/// Specifies the maximum size of a grid track. A grid track will automatically size between it's minimum and maximum size based
+/// on the size of it's contents, the amount of available space, and the sizing constraint the grid is being size under.
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct MaxTrackSizingFunction(pub(crate) CompactLength);
+impl TaffyZero for MaxTrackSizingFunction {
+ const ZERO: Self = Self(CompactLength::ZERO);
+}
+impl TaffyAuto for MaxTrackSizingFunction {
+ const AUTO: Self = Self(CompactLength::AUTO);
+}
+impl TaffyMinContent for MaxTrackSizingFunction {
+ const MIN_CONTENT: Self = Self(CompactLength::MIN_CONTENT);
+}
+impl TaffyMaxContent for MaxTrackSizingFunction {
+ const MAX_CONTENT: Self = Self(CompactLength::MAX_CONTENT);
+}
+impl FromLength for MaxTrackSizingFunction {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for MaxTrackSizingFunction {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+impl TaffyFitContent for MaxTrackSizingFunction {
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Self(CompactLength::fit_content(argument))
+ }
+}
+impl FromFr for MaxTrackSizingFunction {
+ fn from_fr<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::fr(value.into() as f32)
+ }
+}
+impl From<LengthPercentage> for MaxTrackSizingFunction {
+ fn from(input: LengthPercentage) -> Self {
+ Self(input.0)
+ }
+}
+impl From<LengthPercentageAuto> for MaxTrackSizingFunction {
+ fn from(input: LengthPercentageAuto) -> Self {
+ Self(input.0)
+ }
+}
+impl From<Dimension> for MaxTrackSizingFunction {
+ fn from(input: Dimension) -> Self {
+ // Dimension supports values that are not valid max track sizing functions.
+ // Map those to `auto`.
+ match input.0.tag() {
+ CompactLength::FIT_CONTENT_KEYWORD_TAG | CompactLength::STRETCH_TAG | CompactLength::CONTENT_TAG => {
+ Self::auto()
+ }
+ _ => Self(input.0),
+ }
+ }
+}
+impl From<MinTrackSizingFunction> for MaxTrackSizingFunction {
+ fn from(input: MinTrackSizingFunction) -> Self {
+ Self(input.0)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for MaxTrackSizingFunction {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let token = parser.next()?.clone();
+ match token {
+ Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
+ Token::Dimension { unit, value, .. } if unit == "fr" && value.is_sign_positive() => Ok(Self::fr(value)),
+ Token::Ident(ref ident) => match ident.as_ref() {
+ "auto" => Ok(Self::auto()),
+ "min-content" => Ok(Self::min_content()),
+ "max-content" => Ok(Self::max_content()),
+ _ => Err(parser.new_unexpected_token_error(token))?,
+ },
+ Token::Function(ref name) if name.as_ref() == "fit-content" => parser.parse_nested_block(|parser| {
+ let token = parser.next()?.clone();
+ match token {
+ Token::Percentage { unit_value, .. } => Ok(Self::fit_content_percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::fit_content_px(value)),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+from_str_from_css!(MaxTrackSizingFunction);
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for MaxTrackSizingFunction {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let inner = CompactLength::deserialize(deserializer)?;
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
+ if matches!(
+ inner.tag(),
+ CompactLength::LENGTH_TAG
+ | CompactLength::PERCENT_TAG
+ | CompactLength::AUTO_TAG
+ | CompactLength::MIN_CONTENT_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ | CompactLength::FR_TAG
+ ) {
+ Ok(Self(inner))
+ } else {
+ Err(serde::de::Error::custom("Invalid tag"))
+ }
+ }
+}
+
+impl MaxTrackSizingFunction {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLength::length(val))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLength::percent(val))
+ }
+
+ /// The dimension should be automatically computed according to algorithm-specific rules
+ /// regarding the default size of boxes.
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ Self(CompactLength::auto())
+ }
+
+ /// The size should be the "min-content" size.
+ /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ Self(CompactLength::min_content())
+ }
+
+ /// The size should be the "max-content" size.
+ /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ Self(CompactLength::max_content())
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where:
+ /// - `min_content` is the [min-content](Self::min_content) size
+ /// - `max_content` is the [max-content](Self::max_content) size
+ /// - `limit` is a LENGTH value passed to this function
+ ///
+ /// The effect of this is that the item takes the size of `limit` clamped
+ /// by the min-content and max-content sizes.
+ #[inline(always)]
+ pub const fn fit_content_px(limit: f32) -> Self {
+ Self(CompactLength::fit_content_px(limit))
+ }
+
+ /// The size should be computed according to the "fit content" formula:
+ /// `max(min_content, min(max_content, limit))`
+ /// where:
+ /// - `min_content` is the [min-content](Self::min_content) size
+ /// - `max_content` is the [max-content](Self::max_content) size
+ /// - `limit` is a PERCENTAGE value passed to this function
+ ///
+ /// The effect of this is that the item takes the size of `limit` clamped
+ /// by the min-content and max-content sizes.
+ #[inline(always)]
+ pub const fn fit_content_percent(limit: f32) -> Self {
+ Self(CompactLength::fit_content_percent(limit))
+ }
+
+ /// The dimension as a fraction of the total available grid space (`fr` units in CSS)
+ /// Specified value is the numerator of the fraction. Denominator is the sum of all fraction specified in that grid dimension
+ /// Spec: <https://www.w3.org/TR/css3-grid-layout/#fr-unit>
+ #[inline(always)]
+ pub const fn fr(val: f32) -> Self {
+ Self(CompactLength::fr(val))
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ Self(CompactLength::calc(ptr))
+ }
+
+ /// A `fit-content()` track sizing function whose limit is a `calc()` value. The value passed here is treated
+ /// as an opaque handle to the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn fit_content_calc(ptr: *const ()) -> Self {
+ Self(CompactLength::fit_content_calc(ptr))
+ }
+
+ /// Create a LengthPercentageAuto from a raw `CompactLength`.
+ /// # Safety
+ /// CompactLength must represent a valid variant for LengthPercentageAuto
+ #[allow(unsafe_code)]
+ pub unsafe fn from_raw(val: CompactLength) -> Self {
+ Self(val)
+ }
+
+ /// Get the underlying `CompactLength` representation of the value
+ pub fn into_raw(self) -> CompactLength {
+ self.0
+ }
+
+ /// Returns true if the max track sizing function is `MinContent`, `MaxContent`, `FitContent` or `Auto`, else false.
+ #[inline(always)]
+ pub fn is_intrinsic(&self) -> bool {
+ self.0.is_intrinsic()
+ }
+
+ /// Returns true if the max track sizing function is `MaxContent`, `FitContent` or `Auto` else false.
+ /// "In all cases, treat auto and fit-content() as max-content, except where specified otherwise for fit-content()."
+ /// See: <https://www.w3.org/TR/css-grid-1/#algo-terms>
+ #[inline(always)]
+ pub fn is_max_content_alike(&self) -> bool {
+ self.0.is_max_content_alike()
+ }
+
+ /// Returns true if the an Fr value, else false.
+ #[inline(always)]
+ pub fn is_fr(&self) -> bool {
+ self.0.is_fr()
+ }
+
+ /// Returns true if the is `Auto`, else false.
+ #[inline(always)]
+ pub fn is_auto(&self) -> bool {
+ self.0.is_auto()
+ }
+
+ /// Returns true if value is MinContent
+ #[inline(always)]
+ pub fn is_min_content(&self) -> bool {
+ self.0.is_min_content()
+ }
+
+ /// Returns true if value is MaxContent
+ #[inline(always)]
+ pub fn is_max_content(&self) -> bool {
+ self.0.is_max_content()
+ }
+
+ /// Returns true if value is FitContent(...)
+ #[inline(always)]
+ pub fn is_fit_content(&self) -> bool {
+ self.0.is_fit_content()
+ }
+
+ /// Returns true if value is MaxContent or FitContent(...)
+ #[inline(always)]
+ pub fn is_max_or_fit_content(&self) -> bool {
+ self.0.is_max_or_fit_content()
+ }
+
+ /// Returns whether the value can be resolved using `Self::definite_value`
+ #[inline(always)]
+ pub fn has_definite_value(self, parent_size: Option<f32>) -> bool {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => true,
+ CompactLength::PERCENT_TAG => parent_size.is_some(),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => parent_size.is_some(),
+ _ => false,
+ }
+ }
+
+ /// Returns fixed point values directly. Attempts to resolve percentage values against
+ /// the passed available_space and returns if this results in a concrete value (which it
+ /// will if the available_space is `Some`). Otherwise returns None.
+ #[inline(always)]
+ pub fn definite_value(
+ self,
+ parent_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
+ _ => None,
+ }
+ }
+
+ /// Resolve the `fit-content()` limit of this track sizing function against the passed `parent_size`.
+ /// Returns `None` if this is not a `fit-content()` function, or if it has a percentage or `calc()`
+ /// argument and `parent_size` is indefinite.
+ #[inline(always)]
+ pub fn fit_content_limit(
+ self,
+ parent_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ #[cfg(not(feature = "calc"))]
+ let _ = &calc_resolver;
+ match self.0.tag() {
+ CompactLength::FIT_CONTENT_PX_TAG => Some(self.0.value()),
+ CompactLength::FIT_CONTENT_PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_fit_content_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
+ _ => None,
+ }
+ }
+
+ /// Resolve the maximum size of the track as defined by either:
+ /// - A fixed track sizing function
+ /// - A percentage track sizing function (with definite available space)
+ /// - A fit-content sizing function with fixed argument
+ /// - A fit-content sizing function with percentage argument (with definite available space)
+ /// All other kinds of track sizing function return None.
+ #[inline(always)]
+ pub fn definite_limit(
+ self,
+ parent_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::FIT_CONTENT_PX_TAG => Some(self.0.value()),
+ CompactLength::FIT_CONTENT_PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_fit_content_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
+ _ => self.definite_value(parent_size, calc_resolver),
+ }
+ }
+
+ /// Resolve percentage values against the passed parent_size, returning Some(value)
+ /// Non-percentage values always return None.
+ #[inline(always)]
+ pub fn resolved_percentage_size(
+ self,
+ parent_size: f32,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ self.0.resolved_percentage_size(parent_size, calc_resolver)
+ }
+
+ /// Whether the track sizing functions depends on the size of the parent node
+ #[inline(always)]
+ pub fn uses_percentage(self) -> bool {
+ self.0.uses_percentage()
+ }
+
+ /// Expand the compact representation into an [`ExpandedMaxTrackSizingFunction`] enum.
+ ///
+ /// This is useful when integrating with other libraries (e.g. for style inspection or
+ /// serialization) as it allows the value to be pattern-matched without having to work
+ /// with the raw [`CompactLength`] tagged-pointer representation directly.
+ pub fn expand(self) -> ExpandedMaxTrackSizingFunction {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => ExpandedMaxTrackSizingFunction::Length(self.0.value()),
+ CompactLength::PERCENT_TAG => ExpandedMaxTrackSizingFunction::Percent(self.0.value()),
+ CompactLength::AUTO_TAG => ExpandedMaxTrackSizingFunction::Auto,
+ CompactLength::MIN_CONTENT_TAG => ExpandedMaxTrackSizingFunction::MinContent,
+ CompactLength::MAX_CONTENT_TAG => ExpandedMaxTrackSizingFunction::MaxContent,
+ CompactLength::FIT_CONTENT_PX_TAG => ExpandedMaxTrackSizingFunction::FitContentPx(self.0.value()),
+ CompactLength::FIT_CONTENT_PERCENT_TAG => ExpandedMaxTrackSizingFunction::FitContentPercent(self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_fit_content_calc() => ExpandedMaxTrackSizingFunction::FitContentCalc(self.0.calc_value()),
+ CompactLength::FR_TAG => ExpandedMaxTrackSizingFunction::Fr(self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => ExpandedMaxTrackSizingFunction::Calc(self.0.calc_value()),
+ _ => unreachable!("MaxTrackSizingFunction contains a value with an invalid tag"),
+ }
+ }
+}
+
+/// The expanded, non-compact representation of a [`MaxTrackSizingFunction`].
+///
+/// Obtained via [`MaxTrackSizingFunction::expand`]. Can be converted back into a
+/// [`MaxTrackSizingFunction`] using the [`From`] implementation.
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum ExpandedMaxTrackSizingFunction {
+ /// An absolute length (see [`MaxTrackSizingFunction::length`])
+ Length(f32),
+ /// A percentage length (see [`MaxTrackSizingFunction::percent`])
+ Percent(f32),
+ /// The automatic keyword (see [`MaxTrackSizingFunction::auto`])
+ Auto,
+ /// The `min-content` keyword (see [`MaxTrackSizingFunction::min_content`])
+ MinContent,
+ /// The `max-content` keyword (see [`MaxTrackSizingFunction::max_content`])
+ MaxContent,
+ /// A `fit-content(...)` value with a length limit (see [`MaxTrackSizingFunction::fit_content_px`])
+ FitContentPx(f32),
+ /// A `fit-content(...)` value with a percentage limit (see [`MaxTrackSizingFunction::fit_content_percent`])
+ FitContentPercent(f32),
+ /// Track maximum size should be content sized under a max-content constraint, but not larger than
+ /// the `calc()` limit (an opaque handle to the calc representation)
+ #[cfg(feature = "calc")]
+ FitContentCalc(*const ()),
+ /// A fraction of the leftover space (see [`MaxTrackSizingFunction::fr`])
+ Fr(f32),
+ /// A `calc()` value (see [`MaxTrackSizingFunction::calc`]). The pointer is an opaque handle to
+ /// the calc representation, exactly as passed to the constructor.
+ #[cfg(feature = "calc")]
+ Calc(*const ()),
+}
+
+impl From<MaxTrackSizingFunction> for ExpandedMaxTrackSizingFunction {
+ fn from(value: MaxTrackSizingFunction) -> Self {
+ value.expand()
+ }
+}
+
+impl From<ExpandedMaxTrackSizingFunction> for MaxTrackSizingFunction {
+ fn from(value: ExpandedMaxTrackSizingFunction) -> Self {
+ match value {
+ ExpandedMaxTrackSizingFunction::Length(val) => Self::length(val),
+ ExpandedMaxTrackSizingFunction::Percent(val) => Self::percent(val),
+ ExpandedMaxTrackSizingFunction::Auto => Self::auto(),
+ ExpandedMaxTrackSizingFunction::MinContent => Self::min_content(),
+ ExpandedMaxTrackSizingFunction::MaxContent => Self::max_content(),
+ ExpandedMaxTrackSizingFunction::FitContentPx(val) => Self::fit_content_px(val),
+ ExpandedMaxTrackSizingFunction::FitContentPercent(val) => Self::fit_content_percent(val),
+ #[cfg(feature = "calc")]
+ ExpandedMaxTrackSizingFunction::FitContentCalc(ptr) => Self::fit_content_calc(ptr),
+ ExpandedMaxTrackSizingFunction::Fr(val) => Self::fr(val),
+ #[cfg(feature = "calc")]
+ ExpandedMaxTrackSizingFunction::Calc(ptr) => Self::calc(ptr),
+ }
+ }
+}
+
+/// Minimum track sizing function
+///
+/// Specifies the minimum size of a grid track. A grid track will automatically size between it's minimum and maximum size based
+/// on the size of it's contents, the amount of available space, and the sizing constraint the grid is being size under.
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
+#[derive(Copy, Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct MinTrackSizingFunction(pub(crate) CompactLength);
+impl TaffyZero for MinTrackSizingFunction {
+ const ZERO: Self = Self(CompactLength::ZERO);
+}
+impl TaffyAuto for MinTrackSizingFunction {
+ const AUTO: Self = Self(CompactLength::AUTO);
+}
+impl TaffyMinContent for MinTrackSizingFunction {
+ const MIN_CONTENT: Self = Self(CompactLength::MIN_CONTENT);
+}
+impl TaffyMaxContent for MinTrackSizingFunction {
+ const MAX_CONTENT: Self = Self(CompactLength::MAX_CONTENT);
+}
+impl FromLength for MinTrackSizingFunction {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::length(value.into() as f32)
+ }
+}
+impl FromPercent for MinTrackSizingFunction {
+ fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::percent(value.into() as f32)
+ }
+}
+impl From<LengthPercentage> for MinTrackSizingFunction {
+ fn from(input: LengthPercentage) -> Self {
+ Self(input.0)
+ }
+}
+impl From<LengthPercentageAuto> for MinTrackSizingFunction {
+ fn from(input: LengthPercentageAuto) -> Self {
+ Self(input.0)
+ }
+}
+impl From<Dimension> for MinTrackSizingFunction {
+ fn from(input: Dimension) -> Self {
+ // Dimension supports values that are not valid min track sizing functions.
+ // Map those to `auto`.
+ match input.0.tag() {
+ CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ | CompactLength::FIT_CONTENT_KEYWORD_TAG
+ | CompactLength::STRETCH_TAG
+ | CompactLength::CONTENT_TAG => Self::auto(),
+ _ if input.0.is_fit_content_calc() => Self::auto(),
+ _ => Self(input.0),
+ }
+ }
+}
+
+impl From<MaxTrackSizingFunction> for MinTrackSizingFunction {
+ fn from(input: MaxTrackSizingFunction) -> Self {
+ if input.is_fr() || input.is_fit_content() {
+ return Self::auto();
+ }
+ Self(input.0)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for MinTrackSizingFunction {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let token = parser.next()?.clone();
+ match token {
+ Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
+ Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
+ Token::Ident(ref ident) => match ident.as_ref() {
+ "auto" => Ok(Self::auto()),
+ "min-content" => Ok(Self::min_content()),
+ "max-content" => Ok(Self::max_content()),
+ _ => Err(parser.new_unexpected_token_error(token))?,
+ },
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+from_str_from_css!(MinTrackSizingFunction);
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for MinTrackSizingFunction {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let inner = CompactLength::deserialize(deserializer)?;
+ // Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
+ if matches!(
+ inner.tag(),
+ CompactLength::LENGTH_TAG
+ | CompactLength::PERCENT_TAG
+ | CompactLength::AUTO_TAG
+ | CompactLength::MIN_CONTENT_TAG
+ | CompactLength::MAX_CONTENT_TAG
+ | CompactLength::FIT_CONTENT_PX_TAG
+ | CompactLength::FIT_CONTENT_PERCENT_TAG
+ ) {
+ Ok(Self(inner))
+ } else {
+ Err(serde::de::Error::custom("Invalid tag"))
+ }
+ }
+}
+
+impl MinTrackSizingFunction {
+ /// An absolute length in some abstract units. Users of Taffy may define what they correspond
+ /// to in their application (pixels, logical pixels, mm, etc) as they see fit.
+ #[inline(always)]
+ pub const fn length(val: f32) -> Self {
+ Self(CompactLength::length(val))
+ }
+
+ /// A percentage length relative to the size of the containing block.
+ ///
+ /// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
+ #[inline(always)]
+ pub const fn percent(val: f32) -> Self {
+ Self(CompactLength::percent(val))
+ }
+
+ /// The dimension should be automatically computed according to algorithm-specific rules
+ /// regarding the default size of boxes.
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ Self(CompactLength::auto())
+ }
+
+ /// The size should be the "min-content" size.
+ /// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ Self(CompactLength::min_content())
+ }
+
+ /// The size should be the "max-content" size.
+ /// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ Self(CompactLength::max_content())
+ }
+
+ /// A `calc()` value. The value passed here is treated as an opaque handle to
+ /// the actual calc representation and may be a pointer, index, etc.
+ ///
+ /// The low 3 bits are used as a tag value and will be returned as 0.
+ #[inline]
+ #[cfg(feature = "calc")]
+ pub fn calc(ptr: *const ()) -> Self {
+ Self(CompactLength::calc(ptr))
+ }
+
+ /// Create a LengthPercentageAuto from a raw `CompactLength`.
+ /// # Safety
+ /// CompactLength must represent a valid variant for LengthPercentageAuto
+ #[allow(unsafe_code)]
+ pub unsafe fn from_raw(val: CompactLength) -> Self {
+ Self(val)
+ }
+
+ /// Get the underlying `CompactLength` representation of the value
+ pub fn into_raw(self) -> CompactLength {
+ self.0
+ }
+
+ /// Returns true if the min track sizing function is `MinContent`, `MaxContent` or `Auto`, else false.
+ #[inline(always)]
+ pub fn is_intrinsic(&self) -> bool {
+ self.0.is_intrinsic()
+ }
+
+ /// Returns true if the min track sizing function is `MinContent` or `MaxContent`, else false.
+ #[inline(always)]
+ pub fn is_min_or_max_content(&self) -> bool {
+ self.0.is_min_or_max_content()
+ }
+
+ /// Returns true if the value is an fr value
+ #[inline(always)]
+ pub fn is_fr(&self) -> bool {
+ self.0.is_fr()
+ }
+
+ /// Returns true if the is `Auto`, else false.
+ #[inline(always)]
+ pub fn is_auto(&self) -> bool {
+ self.0.is_auto()
+ }
+
+ /// Returns true if the value is `Auto`, or is a percentage and `parent_size` is `None`
+ #[inline(always)]
+ pub fn behaves_as_auto(&self, parent_size: Option<f32>) -> bool {
+ self.0.is_auto() || (parent_size.is_none() && self.0.uses_percentage())
+ }
+
+ /// Returns true if value is MinContent
+ #[inline(always)]
+ pub fn is_min_content(&self) -> bool {
+ self.0.is_min_content()
+ }
+
+ /// Returns true if value is MaxContent
+ #[inline(always)]
+ pub fn is_max_content(&self) -> bool {
+ self.0.is_max_content()
+ }
+
+ /// Returns fixed point values directly. Attempts to resolve percentage values against
+ /// the passed available_space and returns if this results in a concrete value (which it
+ /// will if the available_space is `Some`). Otherwise returns `None`.
+ #[inline(always)]
+ pub fn definite_value(
+ self,
+ parent_size: Option<f32>,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => parent_size.map(|size| self.0.value() * size),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => parent_size.map(|size| calc_resolver(self.0.calc_value(), size)),
+ _ => None,
+ }
+ }
+
+ /// Resolve percentage values against the passed parent_size, returning Some(value)
+ /// Non-percentage values always return None.
+ #[inline(always)]
+ pub fn resolved_percentage_size(
+ self,
+ parent_size: f32,
+ calc_resolver: impl Fn(*const (), f32) -> f32,
+ ) -> Option<f32> {
+ self.0.resolved_percentage_size(parent_size, calc_resolver)
+ }
+
+ /// Whether the track sizing functions depends on the size of the parent node
+ #[inline(always)]
+ pub fn uses_percentage(self) -> bool {
+ self.0.uses_percentage()
+ }
+
+ /// Expand the compact representation into an [`ExpandedMinTrackSizingFunction`] enum.
+ ///
+ /// This is useful when integrating with other libraries (e.g. for style inspection or
+ /// serialization) as it allows the value to be pattern-matched without having to work
+ /// with the raw [`CompactLength`] tagged-pointer representation directly.
+ pub fn expand(self) -> ExpandedMinTrackSizingFunction {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => ExpandedMinTrackSizingFunction::Length(self.0.value()),
+ CompactLength::PERCENT_TAG => ExpandedMinTrackSizingFunction::Percent(self.0.value()),
+ CompactLength::AUTO_TAG => ExpandedMinTrackSizingFunction::Auto,
+ CompactLength::MIN_CONTENT_TAG => ExpandedMinTrackSizingFunction::MinContent,
+ CompactLength::MAX_CONTENT_TAG => ExpandedMinTrackSizingFunction::MaxContent,
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => ExpandedMinTrackSizingFunction::Calc(self.0.calc_value()),
+ _ => unreachable!("MinTrackSizingFunction contains a value with an invalid tag"),
+ }
+ }
+}
+
+/// The expanded, non-compact representation of a [`MinTrackSizingFunction`].
+///
+/// Obtained via [`MinTrackSizingFunction::expand`]. Can be converted back into a
+/// [`MinTrackSizingFunction`] using the [`From`] implementation.
+#[derive(Copy, Clone, PartialEq, Debug)]
+pub enum ExpandedMinTrackSizingFunction {
+ /// An absolute length (see [`MinTrackSizingFunction::length`])
+ Length(f32),
+ /// A percentage length (see [`MinTrackSizingFunction::percent`])
+ Percent(f32),
+ /// The automatic keyword (see [`MinTrackSizingFunction::auto`])
+ Auto,
+ /// The `min-content` keyword (see [`MinTrackSizingFunction::min_content`])
+ MinContent,
+ /// The `max-content` keyword (see [`MinTrackSizingFunction::max_content`])
+ MaxContent,
+ /// A `calc()` value (see [`MinTrackSizingFunction::calc`]). The pointer is an opaque handle to
+ /// the calc representation, exactly as passed to the constructor.
+ #[cfg(feature = "calc")]
+ Calc(*const ()),
+}
+
+impl From<MinTrackSizingFunction> for ExpandedMinTrackSizingFunction {
+ fn from(value: MinTrackSizingFunction) -> Self {
+ value.expand()
+ }
+}
+
+impl From<ExpandedMinTrackSizingFunction> for MinTrackSizingFunction {
+ fn from(value: ExpandedMinTrackSizingFunction) -> Self {
+ match value {
+ ExpandedMinTrackSizingFunction::Length(val) => Self::length(val),
+ ExpandedMinTrackSizingFunction::Percent(val) => Self::percent(val),
+ ExpandedMinTrackSizingFunction::Auto => Self::auto(),
+ ExpandedMinTrackSizingFunction::MinContent => Self::min_content(),
+ ExpandedMinTrackSizingFunction::MaxContent => Self::max_content(),
+ #[cfg(feature = "calc")]
+ ExpandedMinTrackSizingFunction::Calc(ptr) => Self::calc(ptr),
+ }
+ }
+}
+
+/// The sizing function for a grid track (row/column)
+///
+/// May either be a MinMax variant which specifies separate values for the min-/max- track sizing functions
+/// or a scalar value which applies to both track sizing functions.
+pub type TrackSizingFunction = MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>;
+impl TrackSizingFunction {
+ /// Extract the min track sizing function
+ pub fn min_sizing_function(&self) -> MinTrackSizingFunction {
+ self.min
+ }
+ /// Extract the max track sizing function
+ pub fn max_sizing_function(&self) -> MaxTrackSizingFunction {
+ self.max
+ }
+ /// Determine whether at least one of the components ("min" and "max") are fixed sizing function
+ pub fn has_fixed_component(&self) -> bool {
+ self.min.0.is_length_or_percentage() || self.max.0.is_length_or_percentage()
+ }
+}
+impl TaffyAuto for TrackSizingFunction {
+ const AUTO: Self = Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::AUTO };
+}
+impl TaffyMinContent for TrackSizingFunction {
+ const MIN_CONTENT: Self =
+ Self { min: MinTrackSizingFunction::MIN_CONTENT, max: MaxTrackSizingFunction::MIN_CONTENT };
+}
+impl TaffyMaxContent for TrackSizingFunction {
+ const MAX_CONTENT: Self =
+ Self { min: MinTrackSizingFunction::MAX_CONTENT, max: MaxTrackSizingFunction::MAX_CONTENT };
+}
+impl TaffyFitContent for TrackSizingFunction {
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::fit_content(argument) }
+ }
+}
+impl TaffyZero for TrackSizingFunction {
+ const ZERO: Self = Self { min: MinTrackSizingFunction::ZERO, max: MaxTrackSizingFunction::ZERO };
+}
+impl FromLength for TrackSizingFunction {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self { min: MinTrackSizingFunction::from_length(value), max: MaxTrackSizingFunction::from_length(value) }
+ }
+}
+impl FromPercent for TrackSizingFunction {
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Self { min: MinTrackSizingFunction::from_percent(percent), max: MaxTrackSizingFunction::from_percent(percent) }
+ }
+}
+impl FromFr for TrackSizingFunction {
+ fn from_fr<Input: Into<f64> + Copy>(flex: Input) -> Self {
+ Self { min: MinTrackSizingFunction::AUTO, max: MaxTrackSizingFunction::from_fr(flex) }
+ }
+}
+impl From<LengthPercentage> for TrackSizingFunction {
+ fn from(input: LengthPercentage) -> Self {
+ Self { min: input.into(), max: input.into() }
+ }
+}
+impl From<LengthPercentageAuto> for TrackSizingFunction {
+ fn from(input: LengthPercentageAuto) -> Self {
+ Self { min: input.into(), max: input.into() }
+ }
+}
+impl From<Dimension> for TrackSizingFunction {
+ fn from(input: Dimension) -> Self {
+ Self { min: input.into(), max: input.into() }
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for TrackSizingFunction {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ // Try to parse a minmax() function
+ if let Ok(value) = parser.try_parse(|parser| {
+ parser.expect_function_matching("minmax")?;
+ parser.parse_nested_block(|parser| {
+ let min = MinTrackSizingFunction::from_css(parser)?;
+ parser.expect_comma()?;
+ let max = MaxTrackSizingFunction::from_css(parser)?;
+
+ Ok(Self { min, max })
+ })
+ }) {
+ return Ok(value);
+ }
+
+ // Else parse a max track sizing function
+ let max = MaxTrackSizingFunction::from_css(parser)?;
+ let min = max.into();
+ Ok(Self { min, max })
+ }
+}
+
+#[cfg(feature = "parse")]
+from_str_from_css!(TrackSizingFunction);
+
+/// The first argument to a repeated track definition. This type represents the type of automatic repetition to perform.
+///
+/// See <https://www.w3.org/TR/css-grid-1/#auto-repeat> for an explanation of how auto-repeated track definitions work
+/// and the difference between AutoFit and AutoFill.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum RepetitionCount {
+ /// Auto-repeating tracks should be generated to fit the container
+ /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/repeat#auto-fill>
+ AutoFill,
+ /// Auto-repeating tracks should be generated to fit the container
+ /// See: <https://developer.mozilla.org/en-US/docs/Web/CSS/repeat#auto-fit>
+ AutoFit,
+ /// The specified tracks should be repeated exacts N times
+ Count(u16),
+}
+impl From<u16> for RepetitionCount {
+ fn from(value: u16) -> Self {
+ Self::Count(value)
+ }
+}
+
+/// Error returned when trying to convert a string to a GridTrackRepetition and that string is not
+/// either "auto-fit" or "auto-fill"
+#[derive(Debug)]
+pub struct InvalidStringRepetitionValue;
+#[cfg(feature = "std")]
+impl std::error::Error for InvalidStringRepetitionValue {}
+impl core::fmt::Display for InvalidStringRepetitionValue {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str("&str can only be converted to GridTrackRepetition if it's value is 'auto-fit' or 'auto-fill'")
+ }
+}
+impl TryFrom<&str> for RepetitionCount {
+ type Error = InvalidStringRepetitionValue;
+ fn try_from(value: &str) -> Result<Self, InvalidStringRepetitionValue> {
+ match value {
+ "auto-fit" => Ok(Self::AutoFit),
+ "auto-fill" => Ok(Self::AutoFill),
+ _ => Err(InvalidStringRepetitionValue),
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+impl FromCss for RepetitionCount {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ match parser.next()?.clone() {
+ Token::Number { int_value: Some(value), .. } if value.is_positive() => {
+ Ok(Self::Count(saturating_u16(value)))
+ }
+ Token::Ident(ident) if ident == "auto-fit" => Ok(Self::AutoFit),
+ Token::Ident(ident) if ident == "auto-fill" => Ok(Self::AutoFill),
+ token => Err(parser.new_unexpected_token_error(token))?,
+ }
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(RepetitionCount);
+
+/// A typed representation of a `repeat(..)` in `grid-template-*` value
+#[derive(Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct GridTemplateRepetition<S: CheapCloneStr> {
+ /// The number of the times the repeat is repeated
+ pub count: RepetitionCount,
+ /// The tracks to repeat
+ pub tracks: Vec<TrackSizingFunction>,
+ /// The line names for the repeated tracks
+ ///
+ /// Line name sets are positional: set `i` names the `i`th line of each repetition. This must
+ /// either be empty (all lines are unnamed) or contain exactly `tracks.len() + 1` sets (one set
+ /// per line, including both edge lines; sets may be empty). Other lengths panic during layout.
+ pub line_names: Vec<Vec<S>>,
+}
+
+#[rustfmt::skip]
+impl<S: CheapCloneStr> GenericRepetition for &'_ GridTemplateRepetition<S> {
+ type CustomIdent = S;
+ type RepetitionTrackList<'a> = core::iter::Copied<core::slice::Iter<'a, TrackSizingFunction>> where Self: 'a;
+ type TemplateLineNames<'a> = core::iter::Map<core::slice::Iter<'a, Vec<S>>, fn(&Vec<S>) -> core::slice::Iter<'_, S>> where Self: 'a;
+ #[inline(always)]
+ fn count(&self) -> RepetitionCount {
+ self.count
+ }
+ #[inline(always)]
+ fn track_count(&self) -> u16 {
+ self.tracks.len().min(u16::MAX as usize) as u16
+ }
+ #[inline(always)]
+ fn tracks(&self) -> Self::RepetitionTrackList<'_> {
+ self.tracks.iter().copied()
+ }
+ #[inline(always)]
+ fn lines_names(&self) -> Self::TemplateLineNames<'_> {
+ self.line_names.iter().map(|names| names.iter())
+ }
+}
+
+/// An element in a `grid-template-columns` or `grid-template-rows` definition.
+/// Either a track sizing function or a repeat().
+///
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
+#[derive(Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum GridTemplateComponent<S: CheapCloneStr> {
+ /// A single non-repeated track
+ Single(TrackSizingFunction),
+ /// Automatically generate grid tracks to fit the available space using the specified definite track lengths
+ /// Only valid if every track in template (not just the repetition) has a fixed size.
+ Repeat(GridTemplateRepetition<S>),
+}
+
+impl<S: CheapCloneStr> GridTemplateComponent<S> {
+ /// Convert a `GridTemplateComponent` into a `GridTemplateComponentRef`
+ pub fn as_component_ref(&self) -> GenericGridTemplateComponent<S, &GridTemplateRepetition<S>> {
+ match self {
+ GridTemplateComponent::Single(size) => GenericGridTemplateComponent::Single(*size),
+ GridTemplateComponent::Repeat(repetition) => GenericGridTemplateComponent::Repeat(repetition),
+ }
+ }
+}
+
+impl<S: CheapCloneStr> GridTemplateComponent<S> {
+ /// Whether the track definition is a auto-repeated fragment
+ pub fn is_auto_repetition(&self) -> bool {
+ matches!(
+ self,
+ Self::Repeat(GridTemplateRepetition { count: RepetitionCount::AutoFit | RepetitionCount::AutoFill, .. })
+ )
+ }
+}
+impl<S: CheapCloneStr> TaffyAuto for GridTemplateComponent<S> {
+ const AUTO: Self = Self::Single(TrackSizingFunction::AUTO);
+}
+impl<S: CheapCloneStr> TaffyMinContent for GridTemplateComponent<S> {
+ const MIN_CONTENT: Self = Self::Single(TrackSizingFunction::MIN_CONTENT);
+}
+impl<S: CheapCloneStr> TaffyMaxContent for GridTemplateComponent<S> {
+ const MAX_CONTENT: Self = Self::Single(TrackSizingFunction::MAX_CONTENT);
+}
+impl<S: CheapCloneStr> TaffyFitContent for GridTemplateComponent<S> {
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Self::Single(TrackSizingFunction::fit_content(argument))
+ }
+}
+impl<S: CheapCloneStr> TaffyZero for GridTemplateComponent<S> {
+ const ZERO: Self = Self::Single(TrackSizingFunction::ZERO);
+}
+impl<S: CheapCloneStr> FromLength for GridTemplateComponent<S> {
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Self::Single(TrackSizingFunction::from_length(value))
+ }
+}
+impl<S: CheapCloneStr> FromPercent for GridTemplateComponent<S> {
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Self::Single(TrackSizingFunction::from_percent(percent))
+ }
+}
+impl<S: CheapCloneStr> FromFr for GridTemplateComponent<S> {
+ fn from_fr<Input: Into<f64> + Copy>(flex: Input) -> Self {
+ Self::Single(TrackSizingFunction::from_fr(flex))
+ }
+}
+impl<S: CheapCloneStr> From<MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>> for GridTemplateComponent<S> {
+ fn from(input: MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>) -> Self {
+ Self::Single(input)
+ }
+}
+
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr> FromCss for GridTemplateComponent<S> {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ // Try to parse a minmax() function
+ if let Ok(value) = parser.try_parse(|parser| {
+ parser.expect_function_matching("repeat")?;
+ parser.parse_nested_block(|parser| {
+ let count = RepetitionCount::from_css(parser)?;
+ parser.expect_comma()?;
+ let tracks = GridTemplateTracks::<S, TrackSizingFunction>::from_css(parser)?;
+
+ Ok(Self::Repeat(GridTemplateRepetition { count, tracks: tracks.tracks, line_names: tracks.line_names }))
+ })
+ }) {
+ return Ok(value);
+ }
+
+ // Else parse a track sizing function
+ let track_sizing_function = TrackSizingFunction::from_css(parser)?;
+ Ok(Self::Single(track_sizing_function))
+ }
+}
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr> core::str::FromStr for GridTemplateComponent<S> {
+ type Err = ParseError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ parse_css_str_entirely(input)
+ }
+}
+
+#[derive(Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[doc(hidden)]
+pub struct GridTemplateTracks<S: CheapCloneStr, Track> {
+ /// The tracks to repeat
+ pub tracks: Vec<Track>,
+ /// The line names for the repeated tracks
+ pub line_names: Vec<Vec<S>>,
+}
+
+impl<S: CheapCloneStr, Track> Default for GridTemplateTracks<S, Track> {
+ fn default() -> Self {
+ Self { tracks: Vec::new(), line_names: Vec::new() }
+ }
+}
+
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr, Track: FromCss + Debug> FromCss for GridTemplateTracks<S, Track> {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ fn try_parse_line_names<'i, S: CheapCloneStr>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Vec<S>> {
+ parser.try_parse(|parser| {
+ parser.expect_square_bracket_block()?;
+ parser.parse_nested_block(|parser| {
+ let mut line_names = Vec::new();
+ while !parser.is_exhausted() {
+ line_names.push(S::from(parser.expect_ident_cloned()?.as_ref()));
+ }
+ Ok(line_names)
+ })
+ })
+ }
+
+ // Line name groups are positional (group `i` names line `i`), so a group is pushed for
+ // every line, empty when the line has no `[...]` in the source
+ let mut tracks = Self::default();
+ tracks.line_names.push(try_parse_line_names(parser).unwrap_or_default());
+
+ while !parser.is_exhausted() {
+ tracks.tracks.push(Track::from_css(parser)?);
+ tracks.line_names.push(try_parse_line_names(parser).unwrap_or_default());
+ }
+
+ if tracks.tracks.is_empty() {
+ return Err(parser.new_error(cssparser::BasicParseErrorKind::EndOfInput));
+ }
+
+ Ok(tracks)
+ }
+}
+#[cfg(feature = "parse")]
+impl<S: CheapCloneStr, Track: FromCss + Debug> core::str::FromStr for GridTemplateTracks<S, Track> {
+ type Err = ParseError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ parse_css_str_entirely(input)
+ }
+}
+
+#[derive(Default)]
+#[doc(hidden)]
+pub struct GridAutoTracks(pub Vec<TrackSizingFunction>);
+
+#[cfg(feature = "parse")]
+impl FromCss for GridAutoTracks {
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
+ let mut tracks = Self::default();
+ while !parser.is_exhausted() {
+ tracks.0.push(TrackSizingFunction::from_css(parser)?);
+ }
+ if tracks.0.is_empty() {
+ return Err(parser.new_error(cssparser::BasicParseErrorKind::EndOfInput));
+ }
+ Ok(tracks)
+ }
+}
+#[cfg(feature = "parse")]
+from_str_from_css!(GridAutoTracks);
+
+#[cfg(all(test, feature = "parse"))]
+mod tests {
+ use super::*;
+ use crate::sys::DefaultCheapStr;
+
+ #[test]
+ fn grid_placement_parser_saturates_numeric_values() {
+ assert_eq!(
+ "32768".parse::<GridPlacement<DefaultCheapStr>>().unwrap(),
+ GridPlacement::Line(GridLine::from(i16::MAX))
+ );
+ assert_eq!(
+ "-32769".parse::<GridPlacement<DefaultCheapStr>>().unwrap(),
+ GridPlacement::Line(GridLine::from(i16::MIN))
+ );
+ assert_eq!("span 65536".parse::<GridPlacement<DefaultCheapStr>>().unwrap(), GridPlacement::Span(u16::MAX));
+
+ let named_line = "32768 line".parse::<GridPlacement<DefaultCheapStr>>().unwrap();
+ assert!(matches!(named_line, GridPlacement::NamedLine(_, i16::MAX)));
+
+ let named_span = "span 65536 line".parse::<GridPlacement<DefaultCheapStr>>().unwrap();
+ assert!(matches!(named_span, GridPlacement::NamedSpan(_, u16::MAX)));
+ }
+
+ #[test]
+ fn repetition_parser_saturates_numeric_values() {
+ assert_eq!("65536".parse::<RepetitionCount>().unwrap(), RepetitionCount::Count(u16::MAX));
+
+ let component = "repeat(65536, 1px)".parse::<GridTemplateComponent<DefaultCheapStr>>().unwrap();
+ assert!(matches!(
+ component,
+ GridTemplateComponent::Repeat(GridTemplateRepetition { count: RepetitionCount::Count(u16::MAX), .. })
+ ));
+ }
+
+ #[test]
+ fn repetition_track_count_saturates() {
+ let repetition = GridTemplateRepetition::<DefaultCheapStr> {
+ count: RepetitionCount::Count(1),
+ tracks: vec![TrackSizingFunction::AUTO; u16::MAX as usize + 1],
+ line_names: Vec::new(),
+ };
+ assert_eq!((&repetition).track_count(), u16::MAX);
+ }
+}
+
+#[cfg(test)]
+mod expand_tests {
+ use super::*;
+
+ #[test]
+ fn max_track_sizing_function_round_trips() {
+ let cases = [
+ MaxTrackSizingFunction::length(12.0),
+ MaxTrackSizingFunction::percent(0.5),
+ MaxTrackSizingFunction::auto(),
+ MaxTrackSizingFunction::min_content(),
+ MaxTrackSizingFunction::max_content(),
+ MaxTrackSizingFunction::fit_content_px(30.0),
+ MaxTrackSizingFunction::fit_content_percent(0.75),
+ MaxTrackSizingFunction::fr(2.0),
+ ];
+ for value in cases {
+ assert_eq!(MaxTrackSizingFunction::from(value.expand()), value);
+ assert_eq!(ExpandedMaxTrackSizingFunction::from(value), value.expand());
+ }
+ assert_eq!(MaxTrackSizingFunction::fr(2.0).expand(), ExpandedMaxTrackSizingFunction::Fr(2.0));
+ assert_eq!(
+ MaxTrackSizingFunction::fit_content_px(30.0).expand(),
+ ExpandedMaxTrackSizingFunction::FitContentPx(30.0)
+ );
+ }
+
+ #[test]
+ fn min_track_sizing_function_round_trips() {
+ let cases = [
+ MinTrackSizingFunction::length(12.0),
+ MinTrackSizingFunction::percent(0.5),
+ MinTrackSizingFunction::auto(),
+ MinTrackSizingFunction::min_content(),
+ MinTrackSizingFunction::max_content(),
+ ];
+ for value in cases {
+ assert_eq!(MinTrackSizingFunction::from(value.expand()), value);
+ assert_eq!(ExpandedMinTrackSizingFunction::from(value), value.expand());
+ }
+ assert_eq!(MinTrackSizingFunction::max_content().expand(), ExpandedMinTrackSizingFunction::MaxContent);
+ }
+
+ #[cfg(feature = "calc")]
+ #[test]
+ fn track_sizing_function_calc_round_trips() {
+ #[allow(dead_code)]
+ #[repr(align(8))]
+ struct Aligned(u64);
+ static HANDLE: Aligned = Aligned(0);
+ let handle = &HANDLE as *const Aligned as *const ();
+
+ assert_eq!(MaxTrackSizingFunction::calc(handle).expand(), ExpandedMaxTrackSizingFunction::Calc(handle));
+ assert_eq!(
+ MaxTrackSizingFunction::fit_content_calc(handle).expand(),
+ ExpandedMaxTrackSizingFunction::FitContentCalc(handle)
+ );
+ assert_eq!(
+ MaxTrackSizingFunction::from(ExpandedMaxTrackSizingFunction::FitContentCalc(handle)),
+ MaxTrackSizingFunction::fit_content_calc(handle)
+ );
+ assert_eq!(
+ MaxTrackSizingFunction::fit_content(LengthPercentage::calc(handle)),
+ MaxTrackSizingFunction::fit_content_calc(handle)
+ );
+ assert_eq!(
+ MinTrackSizingFunction::from(MaxTrackSizingFunction::fit_content_calc(handle)),
+ MinTrackSizingFunction::AUTO
+ );
+ assert_eq!(MinTrackSizingFunction::from(Dimension::fit_content_calc(handle)), MinTrackSizingFunction::AUTO);
+ assert_eq!(
+ MaxTrackSizingFunction::from(ExpandedMaxTrackSizingFunction::Calc(handle)),
+ MaxTrackSizingFunction::calc(handle)
+ );
+ assert_eq!(MinTrackSizingFunction::calc(handle).expand(), ExpandedMinTrackSizingFunction::Calc(handle));
+ }
+}
diff --git a/vendor/taffy/src/style/mod.rs b/vendor/taffy/src/style/mod.rs
new file mode 100644
index 00000000..a9e57f33
--- /dev/null
+++ b/vendor/taffy/src/style/mod.rs
@@ -0,0 +1,1816 @@
+//! A typed representation of [CSS style properties](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) in Rust. Used as input to layout computation.
+mod alignment;
+mod available_space;
+mod compact_length;
+mod dimension;
+
+#[cfg(feature = "block_layout")]
+mod block;
+#[cfg(feature = "flexbox")]
+mod flex;
+#[cfg(feature = "float_layout")]
+mod float;
+#[cfg(feature = "grid")]
+mod grid;
+
+pub use self::alignment::{
+ AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, JustifyContent,
+ JustifyItems, JustifySelf,
+};
+pub use self::available_space::AvailableSpace;
+pub use self::compact_length::CompactLength;
+pub use self::dimension::{
+ Dimension, ExpandedDimension, ExpandedLengthPercentage, ExpandedLengthPercentageAuto, LengthPercentage,
+ LengthPercentageAuto,
+};
+use crate::sys::DefaultCheapStr;
+
+#[cfg(feature = "block_layout")]
+pub use self::block::{BlockContainerStyle, BlockItemStyle, TextAlign};
+#[cfg(feature = "flexbox")]
+pub use self::flex::{FlexDirection, FlexWrap, FlexboxContainerStyle, FlexboxItemStyle};
+#[cfg(feature = "float_layout")]
+pub use self::float::{Clear, Float, FloatDirection};
+#[cfg(feature = "grid")]
+pub use self::grid::{
+ ExpandedMaxTrackSizingFunction, ExpandedMinTrackSizingFunction, GenericGridPlacement, GenericGridTemplateComponent,
+ GenericRepetition, GridAutoFlow, GridAutoTracks, GridContainerStyle, GridItemStyle, GridPlacement,
+ GridTemplateComponent, GridTemplateRepetition, GridTemplateTracks, MaxTrackSizingFunction, MinTrackSizingFunction,
+ RepetitionCount, TrackSizingFunction,
+};
+#[cfg(feature = "grid")]
+pub(crate) use self::grid::{GridAreaAxis, GridAreaEnd};
+#[cfg(feature = "grid")]
+pub use self::grid::{GridTemplateArea, GridTemplateAreas, NamedGridLine, TemplateLineNames};
+#[cfg(feature = "grid")]
+pub(crate) use self::grid::{NonNamedGridPlacement, OriginZeroGridPlacement};
+
+use crate::geometry::{Point, Rect, Size};
+use crate::style_helpers::TaffyAuto as _;
+use core::fmt::Debug;
+
+#[cfg(feature = "grid")]
+use crate::geometry::Line;
+#[cfg(feature = "serde")]
+use crate::style_helpers;
+#[cfg(feature = "grid")]
+use crate::util::sys::GridTrackVec;
+
+use crate::sys::String;
+
+/// Trait that represents a cheaply clonable string. If you're unsure what to use here
+/// consider `Arc<str>` or `string_cache::Atom`.
+pub trait CheapCloneStr:
+ AsRef<str> + for<'a> From<&'a str> + From<String> + PartialEq + Eq + Clone + Default + Debug + 'static
+{
+}
+impl<T> CheapCloneStr for T where
+ T: AsRef<str> + for<'a> From<&'a str> + From<String> + PartialEq + Eq + Clone + Default + Debug + 'static
+{
+}
+
+/// The core set of styles that are shared between all CSS layout nodes
+///
+/// Note that all methods come with a default implementation which simply returns the default value for that style property
+/// but this is a just a convenience to save on boilerplate for styles that your implementation doesn't support. You will need
+/// to override the default implementation for each style property that your style type actually supports.
+pub trait CoreStyle {
+ /// The type of custom identifiers used to identify named grid lines and areas
+ type CustomIdent: CheapCloneStr;
+
+ /// Which box generation mode should be used
+ #[inline(always)]
+ fn box_generation_mode(&self) -> BoxGenerationMode {
+ BoxGenerationMode::DEFAULT
+ }
+ /// Is block layout?
+ ///
+ /// This should only return `true` for `display: block`, and NOT for `display: flow-root`.
+ /// Flow-root boxes establish a new block formatting context and must not be treated as
+ /// being part of their parent's block formatting context (which is what this method controls).
+ #[inline(always)]
+ fn is_block(&self) -> bool {
+ false
+ }
+ /// Is it a compressible replaced element: a replaced element (image, video, canvas, ...) or a
+ /// form control with an intrinsic size (`input`, `select`, `textarea`, `meter`, ...)?
+ /// Such boxes resolve an `auto` width to their intrinsic size rather than being stretched by
+ /// block layout, and have a zero min-content contribution in grid layout.
+ /// <https://drafts.csswg.org/css-sizing-3/#compressible>
+ #[inline(always)]
+ fn is_compressible_replaced(&self) -> bool {
+ false
+ }
+ /// Is it a replaced element (image, video, canvas, ...)? Unlike other compressible replaced
+ /// elements (form controls), an `auto`-sized replaced element is not stretched between its
+ /// insets under `normal` alignment.
+ /// <https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements>
+ #[inline(always)]
+ fn is_replaced(&self) -> bool {
+ false
+ }
+ /// Which box do size styles apply to
+ #[inline(always)]
+ fn box_sizing(&self) -> BoxSizing {
+ BoxSizing::BorderBox
+ }
+
+ /// The direction of text, table and grid columns, and horizontal overflow.
+ #[inline(always)]
+ fn direction(&self) -> Direction {
+ Direction::Ltr
+ }
+
+ // Overflow properties
+ /// How children overflowing their container should affect layout
+ #[inline(always)]
+ fn overflow(&self) -> Point<Overflow> {
+ Style::<Self::CustomIdent>::DEFAULT.overflow
+ }
+ /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
+ #[inline(always)]
+ fn scrollbar_width(&self) -> f32 {
+ 0.0
+ }
+
+ // Position properties
+ /// What should the `position` value of this struct use as a base offset?
+ #[inline(always)]
+ fn position(&self) -> Position {
+ Style::<Self::CustomIdent>::DEFAULT.position
+ }
+ /// How should the position of this element be tweaked relative to the layout defined?
+ #[inline(always)]
+ fn inset(&self) -> Rect<LengthPercentageAuto> {
+ Style::<Self::CustomIdent>::DEFAULT.inset
+ }
+ /// Which out-of-flow (`absolute`/`fixed`) descendants this node establishes the containing block for.
+ ///
+ /// This is the single policy point for containing-block establishment: it decides both which
+ /// out-of-flow boxes a node claims and lays out, and (for grid containers) whether the static
+ /// position of an out-of-flow child is derived from its grid area.
+ ///
+ /// The default matches plain CSS positioning: a node is the containing block for `absolute` boxes
+ /// when its own `position` is not `static`, and never for `fixed` boxes (which are claimed by the
+ /// root). Implementations may override this so that other style properties (such as `transform`,
+ /// `filter` or `will-change` in a full CSS implementation) establish a containing block.
+ #[inline(always)]
+ fn is_containing_block(&self) -> ContainingBlockClaims {
+ ContainingBlockClaims { absolute: self.position().is_positioned(), fixed: false }
+ }
+
+ // Size properies
+ /// Sets the initial size of the item
+ #[inline(always)]
+ fn size(&self) -> Size<Dimension> {
+ Style::<Self::CustomIdent>::DEFAULT.size
+ }
+ /// Controls the minimum size of the item
+ #[inline(always)]
+ fn min_size(&self) -> Size<LengthPercentageAuto> {
+ Style::<Self::CustomIdent>::DEFAULT.min_size
+ }
+ /// Controls the maximum size of the item
+ #[inline(always)]
+ fn max_size(&self) -> Size<LengthPercentageAuto> {
+ Style::<Self::CustomIdent>::DEFAULT.max_size
+ }
+ /// Sets the preferred aspect ratio for the item
+ /// The ratio is calculated as width divided by height.
+ #[inline(always)]
+ fn aspect_ratio(&self) -> Option<f32> {
+ Style::<Self::CustomIdent>::DEFAULT.aspect_ratio
+ }
+
+ // Spacing Properties
+ /// How large should the margin be on each side?
+ #[inline(always)]
+ fn margin(&self) -> Rect<LengthPercentageAuto> {
+ Style::<Self::CustomIdent>::DEFAULT.margin
+ }
+ /// How large should the padding be on each side?
+ #[inline(always)]
+ fn padding(&self) -> Rect<LengthPercentage> {
+ Style::<Self::CustomIdent>::DEFAULT.padding
+ }
+ /// How large should the border be on each side?
+ #[inline(always)]
+ fn border(&self) -> Rect<LengthPercentage> {
+ Style::<Self::CustomIdent>::DEFAULT.border
+ }
+
+ /// The layout-affecting parts of the CSS `contain` property that apply to this node
+ #[inline(always)]
+ fn contain(&self) -> Contain {
+ Contain::NONE
+ }
+}
+
+/// The styles of an out-of-flow (`position: absolute` / `position: fixed`) box that are read by
+/// its containing block's out-of-flow positioning pass
+pub trait OofItemStyle: CoreStyle {
+ /// How the box is aligned in the block axis of its inset-modified containing block
+ /// (`align-self`). `None` corresponds to `normal`/`auto`.
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ None
+ }
+ /// How the box is aligned in the inline axis of its inset-modified containing block
+ /// (`justify-self`). `None` corresponds to `normal`/`auto`.
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ None
+ }
+ /// Whether the box is a table wrapper box. A `normal` self-alignment does not stretch
+ /// tables to fill their inset-modified containing block.
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ false
+ }
+ /// Defines which row in the grid the box should start and end at, when the box's containing
+ /// block is a grid container
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ Default::default()
+ }
+ /// Defines which column in the grid the box should start and end at, when the box's
+ /// containing block is a grid container
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ Default::default()
+ }
+}
+
+/// Sets the layout used for the children of this node
+///
+/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Display {
+ /// The children will follow the block layout algorithm
+ #[cfg(feature = "block_layout")]
+ Block,
+ /// The children will follow the block layout algorithm and establish a new block formatting context
+ #[cfg(feature = "block_layout")]
+ FlowRoot,
+ /// The children will follow the flexbox layout algorithm
+ #[cfg(feature = "flexbox")]
+ Flex,
+ /// The children will follow the CSS Grid layout algorithm
+ #[cfg(feature = "grid")]
+ Grid,
+ /// The node is hidden, and it's children will also be hidden
+ None,
+}
+
+impl Display {
+ /// The default Display mode
+ #[cfg(feature = "flexbox")]
+ pub const DEFAULT: Display = Display::Flex;
+
+ /// The default Display mode
+ #[cfg(all(feature = "grid", not(feature = "flexbox")))]
+ pub const DEFAULT: Display = Display::Grid;
+
+ /// The default Display mode
+ #[cfg(all(feature = "block_layout", not(feature = "flexbox"), not(feature = "grid")))]
+ pub const DEFAULT: Display = Display::Block;
+
+ /// The default Display mode
+ #[cfg(all(not(feature = "flexbox"), not(feature = "grid"), not(feature = "block_layout")))]
+ pub const DEFAULT: Display = Display::None;
+}
+
+impl Default for Display {
+ fn default() -> Self {
+ Self::DEFAULT
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Display,
+ "none" => None,
+ #[cfg(feature = "flexbox")]
+ "flex" => Flex,
+ #[cfg(feature = "grid")]
+ "grid" => Grid,
+ #[cfg(feature = "block_layout")]
+ "block" => Block,
+ #[cfg(feature = "block_layout")]
+ "flow-root" => FlowRoot,
+);
+
+impl core::fmt::Display for Display {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match self {
+ Display::None => write!(f, "NONE"),
+ #[cfg(feature = "block_layout")]
+ Display::Block => write!(f, "BLOCK"),
+ #[cfg(feature = "block_layout")]
+ Display::FlowRoot => write!(f, "FLOW-ROOT"),
+ #[cfg(feature = "flexbox")]
+ Display::Flex => write!(f, "FLEX"),
+ #[cfg(feature = "grid")]
+ Display::Grid => write!(f, "GRID"),
+ }
+ }
+}
+
+/// An abstracted version of the CSS `display` property where any value other than "none" is represented by "normal"
+/// See: <https://www.w3.org/TR/css-display-3/#box-generation>
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum BoxGenerationMode {
+ /// The node generates a box in the regular way
+ Normal,
+ /// The node and it's descendants generate no boxes (they are hidden)
+ None,
+}
+
+impl BoxGenerationMode {
+ /// The default of BoxGenerationMode
+ pub const DEFAULT: BoxGenerationMode = BoxGenerationMode::Normal;
+}
+
+impl Default for BoxGenerationMode {
+ fn default() -> Self {
+ Self::DEFAULT
+ }
+}
+
+/// The positioning strategy for this item.
+///
+/// This controls both how the origin is determined for the [`Style::position`] field,
+/// and whether or not the item will be controlled by flexbox's layout algorithm.
+///
+/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
+/// which can be unintuitive.
+///
+/// [`Position::Static`] is the default value, matching the default behavior in CSS.
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Position {
+ /// The item is laid out in normal flow. `inset` has no effect on statically positioned items,
+ /// and they do not act as a containing block for absolutely positioned descendants.
+ #[default]
+ Static,
+ /// The item is laid out in normal flow, then the `inset` offset is applied as a correction factor.
+ /// Offsets do not affect the position of any other items.
+ /// Relatively positioned items act as a containing block for absolutely positioned descendants.
+ Relative,
+ /// The item is taken out of normal flow and positioned relative to its closest positioned ancestor
+ /// (its containing block), if any. Otherwise, it is placed relative to the root.
+ /// No space is created for the item in the page layout, and its size will not be altered.
+ ///
+ /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
+ Absolute,
+ /// The item is taken out of normal flow and positioned relative to the root (viewport),
+ /// unless an ancestor overrides containing-block behavior (e.g. via transforms in a full CSS implementation).
+ Fixed,
+ /// The item is laid out in normal flow exactly like a statically positioned item: `inset` is *not* applied
+ /// as an offset (in CSS, sticky insets are scroll thresholds, which Taffy has no knowledge of; applying the
+ /// sticky offset is the responsibility of the caller once it knows the scroll position).
+ /// Like `Relative`, a sticky item acts as a containing block for absolutely positioned descendants.
+ Sticky,
+}
+
+impl Position {
+ /// Returns true if this position takes the item out of normal flow (`Absolute` or `Fixed`)
+ #[inline(always)]
+ pub fn is_out_of_flow(self) -> bool {
+ matches!(self, Position::Absolute | Position::Fixed)
+ }
+
+ /// Returns true if this position causes the item to act as a containing block
+ /// for absolutely positioned descendants (any value other than `Static`)
+ #[inline(always)]
+ pub fn is_positioned(self) -> bool {
+ !matches!(self, Position::Static)
+ }
+}
+
+/// Which out-of-flow positions a node establishes a containing block for.
+///
+/// Returned by [`CoreStyle::is_containing_block`].
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub struct ContainingBlockClaims {
+ /// Whether the node is the containing block for `position: absolute` boxes
+ pub absolute: bool,
+ /// Whether the node is the containing block for `position: fixed` boxes
+ pub fixed: bool,
+}
+
+impl ContainingBlockClaims {
+ /// Claims nothing
+ pub const NONE: Self = Self { absolute: false, fixed: false };
+ /// Claims every out-of-flow box (the initial containing block)
+ pub const ALL: Self = Self { absolute: true, fixed: true };
+
+ /// Whether the node is the containing block for a box with the given `position`
+ #[inline(always)]
+ pub fn for_position(self, position: Position) -> bool {
+ match position {
+ Position::Absolute => self.absolute,
+ Position::Fixed => self.fixed,
+ _ => false,
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Position,
+ "static" => Static,
+ "relative" => Relative,
+ "absolute" => Absolute,
+ "fixed" => Fixed,
+ "sticky" => Sticky,
+);
+
+/// Specifies whether size styles for this node are assigned to the node's "content box" or "border box"
+///
+/// - The "content box" is the node's inner size excluding padding, border and margin
+/// - The "border box" is the node's outer size including padding and border (but still excluding margin)
+///
+/// This property modifies the application of the following styles:
+///
+/// - `size`
+/// - `min_size`
+/// - `max_size`
+/// - `flex_basis`
+///
+/// See <https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing>
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum BoxSizing {
+ /// Size styles such size, min_size, max_size specify the box's "border box" (the size excluding margin but including padding/border)
+ #[default]
+ BorderBox,
+ /// Size styles such size, min_size, max_size specify the box's "content box" (the size excluding padding/border/margin)
+ ContentBox,
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(BoxSizing,
+ "border-box" => BorderBox,
+ "content-box" => ContentBox,
+);
+
+/// How children overflowing their container should affect layout
+///
+/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
+/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
+/// the main ones being:
+///
+/// - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
+/// - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
+///
+/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
+/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
+///
+/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Overflow {
+ /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
+ /// Content that overflows this node *should* contribute to the scroll region of its parent.
+ #[default]
+ Visible,
+ /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
+ /// Content that overflows this node should *not* contribute to the scroll region of its parent.
+ Clip,
+ /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
+ /// Content that overflows this node should *not* contribute to the scroll region of its parent.
+ Hidden,
+ /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
+ /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
+ /// Content that overflows this node should *not* contribute to the scroll region of its parent.
+ Scroll,
+}
+
+impl Overflow {
+ /// Returns true for overflow modes that contain their contents (`Overflow::Hidden`, `Overflow::Scroll`, `Overflow::Auto`)
+ /// or else false for overflow modes that allow their contains to spill (`Overflow::Visible`).
+ #[inline(always)]
+ pub fn is_scroll_container(self) -> bool {
+ match self {
+ Self::Visible | Self::Clip => false,
+ Self::Hidden | Self::Scroll => true,
+ }
+ }
+
+ /// Returns `Some(0.0)` if the overflow mode would cause the automatic minimum size of a Flexbox or CSS Grid item
+ /// to be `0`. Else returns None.
+ #[inline(always)]
+ pub(crate) fn maybe_into_automatic_min_size(self) -> Option<f32> {
+ match self.is_scroll_container() {
+ true => Some(0.0),
+ false => None,
+ }
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Overflow,
+ "visible" => Visible,
+ "hidden" => Hidden,
+ "clip" => Clip,
+ "scroll" => Scroll,
+);
+
+/// The layout-affecting parts of the CSS `contain` property.
+///
+/// Containment limits the ways in which a box's contents can affect layout outside of the box
+/// (and vice versa). Taffy implements the layout-relevant containment types:
+///
+/// - [`Contain::LAYOUT`]: the box establishes an independent formatting context, and is treated
+/// as having no baseline for baseline-alignment purposes (layout containment).
+/// - [`Contain::PAINT`]: the box establishes an independent formatting context. Paint
+/// containment's other effects (clipping, containing absolutely-positioned descendants,
+/// stacking context) are outside of Taffy's scope.
+///
+/// The `style` containment type has no effect on layout and is therefore not represented
+/// (it is accepted and ignored when parsing). Size and inline-size containment are not
+/// currently implemented.
+///
+/// <https://developer.mozilla.org/en-US/docs/Web/CSS/contain>
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct Contain(u8);
+
+impl Contain {
+ /// No containment (the default)
+ pub const NONE: Contain = Contain(0);
+ /// Layout containment: the box establishes an independent formatting context and is treated
+ /// as having no baseline for baseline-alignment purposes.
+ /// <https://drafts.csswg.org/css-contain-2/#containment-layout>
+ pub const LAYOUT: Contain = Contain(1 << 0);
+ /// Paint containment: the box establishes an independent formatting context. Its other
+ /// effects don't affect layout.
+ /// <https://drafts.csswg.org/css-contain-2/#containment-paint>
+ pub const PAINT: Contain = Contain(1 << 1);
+ /// The containment implied by `contain: content` (`layout paint`, ignoring style containment)
+ pub const CONTENT: Contain = Contain(Contain::LAYOUT.0 | Contain::PAINT.0);
+
+ /// The default containment (no containment)
+ pub const DEFAULT: Contain = Contain::NONE;
+
+ /// Returns whether `self` contains all of the containment types in `other`
+ #[inline(always)]
+ pub const fn contains(self, other: Contain) -> bool {
+ self.0 & other.0 == other.0
+ }
+
+ /// Returns whether `self` contains any of the containment types in `other`
+ #[inline(always)]
+ pub const fn intersects(self, other: Contain) -> bool {
+ self.0 & other.0 != 0
+ }
+
+ /// Returns the union of the containment types in `self` and `other`
+ #[inline(always)]
+ pub const fn union(self, other: Contain) -> Contain {
+ Contain(self.0 | other.0)
+ }
+
+ /// Whether this containment causes the box to establish an independent formatting context
+ /// (both layout and paint containment do)
+ #[inline(always)]
+ pub const fn establishes_independent_formatting_context(self) -> bool {
+ self.intersects(Contain::LAYOUT.union(Contain::PAINT))
+ }
+
+ /// Whether this containment suppresses the box's baseline for baseline-alignment purposes
+ /// (layout containment does, paint containment does not)
+ #[inline(always)]
+ pub const fn suppresses_baseline(self) -> bool {
+ self.contains(Contain::LAYOUT)
+ }
+
+ /// Whether this containment prevents the box's overflowing content from contributing to an
+ /// ancestor's scrollable overflow region (layout containment treats such overflow as ink
+ /// overflow; paint containment clips it)
+ #[inline(always)]
+ pub const fn contains_scrollable_overflow(self) -> bool {
+ self.intersects(Contain::LAYOUT.union(Contain::PAINT))
+ }
+}
+
+impl core::ops::BitOr for Contain {
+ type Output = Contain;
+ #[inline(always)]
+ fn bitor(self, rhs: Contain) -> Contain {
+ self.union(rhs)
+ }
+}
+
+impl core::ops::BitOrAssign for Contain {
+ #[inline(always)]
+ fn bitor_assign(&mut self, rhs: Contain) {
+ *self = self.union(rhs);
+ }
+}
+
+#[cfg(feature = "parse")]
+impl crate::util::parse::FromCss for Contain {
+ fn from_css<'i>(input: &mut crate::util::parse::Parser<'i, '_>) -> crate::util::parse::CssParseResult<'i, Self> {
+ /// Duplicate-detection bit for the ignored `style` keyword, which does not map to a
+ /// `Contain` flag
+ const STYLE_BIT: u8 = 1 << 6;
+
+ let mut flags = Contain::NONE;
+ let mut seen: u8 = 0;
+
+ loop {
+ let ident = input.expect_ident()?.clone();
+ let (flag, seen_bit) = cssparser::match_ignore_ascii_case! { &*ident,
+ // Single-keyword values (only valid on their own; `parse_entirely` in the
+ // `FromStr` impl rejects trailing keywords, and a leading keyword before them
+ // is rejected by the `seen != 0` check below)
+ "none" | "content" => {
+ if seen != 0 || !input.is_exhausted() {
+ return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
+ }
+ return Ok(cssparser::match_ignore_ascii_case! { &*ident,
+ "content" => Contain::CONTENT,
+ _ => Contain::NONE,
+ });
+ },
+ "layout" => (Contain::LAYOUT, Contain::LAYOUT.0),
+ "paint" => (Contain::PAINT, Contain::PAINT.0),
+ // `style` containment has no layout effect: accept and ignore it so that real
+ // CSS values round-trip
+ "style" => (Contain::NONE, STYLE_BIT),
+ _ => {
+ return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
+ }
+ };
+
+ // Reject duplicate keywords
+ if seen & seen_bit != 0 {
+ return Err(input.new_unexpected_token_error(crate::util::parse::Token::Ident(ident)));
+ }
+ seen |= seen_bit;
+ flags |= flag;
+
+ if input.is_exhausted() {
+ return Ok(flags);
+ }
+ }
+ }
+}
+#[cfg(feature = "parse")]
+crate::util::parse::from_str_from_css!(Contain);
+
+/// Sets the direction of text, table and grid columns, and horizontal overflow.
+/// <https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/direction>
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub enum Direction {
+ #[default]
+ /// Left-to-right
+ Ltr,
+ /// Right-to-left
+ Rtl,
+}
+
+impl Direction {
+ /// Returns true if the direction is right-to-left
+ #[inline]
+ pub fn is_rtl(&self) -> bool {
+ matches!(self, Direction::Rtl)
+ }
+}
+
+#[cfg(feature = "parse")]
+crate::util::parse::impl_parse_for_keyword_enum!(Direction,
+ "ltr" => Ltr,
+ "rtl" => Rtl,
+);
+
+/// A typed representation of the CSS style information for a single node.
+///
+/// The most important idea in flexbox is the notion of a "main" and "cross" axis, which are always perpendicular to each other.
+/// The orientation of these axes are controlled via the [`FlexDirection`] field of this struct.
+///
+/// This struct follows the [CSS equivalent](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) directly;
+/// information about the behavior on the web should transfer directly.
+///
+/// Detailed information about the exact behavior of each of these fields
+/// can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS) by searching for the field name.
+/// The distinction between margin, padding and border is explained well in
+/// this [introduction to the box model](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model).
+///
+/// If the behavior does not match the flexbox layout algorithm on the web, please file a bug!
+#[derive(Clone, PartialEq, Debug)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[cfg_attr(feature = "serde", serde(default))]
+pub struct Style<S: CheapCloneStr = DefaultCheapStr> {
+ /// This is a dummy field which is necessary to make Taffy compile with the `grid` feature disabled
+ /// It should always be set to `core::marker::PhantomData`.
+ pub dummy: core::marker::PhantomData<S>,
+ /// What layout strategy should be used?
+ pub display: Display,
+ /// Whether a child is display:table or not. This affects children of block layouts.
+ /// This should really be part of `Display`, but it is currently seperate because table layout isn't implemented
+ pub item_is_table: bool,
+ /// Is it a replaced element like an image or video? Implies `is_compressible_replaced`.
+ /// <https://html.spec.whatwg.org/multipage/rendering.html#replaced-elements>
+ pub item_is_replaced: bool,
+ /// Is it a compressible replaced element that is not a replaced element (a form control with
+ /// an intrinsic size)? <https://drafts.csswg.org/css-sizing-3/#compressible>
+ pub item_is_compressible_replaced: bool,
+ /// Should size styles apply to the content box or the border box of the node
+ pub box_sizing: BoxSizing,
+ /// Sets the direction of text, table and grid columns, and horizontal overflow.
+ pub direction: Direction,
+
+ // Overflow properties
+ /// How children overflowing their container should affect layout
+ pub overflow: Point<Overflow>,
+ /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
+ pub scrollbar_width: f32,
+ /// The layout-affecting parts of the CSS `contain` property
+ pub contain: Contain,
+
+ #[cfg(feature = "float_layout")]
+ /// Should the box be floated
+ pub float: Float,
+ #[cfg(feature = "float_layout")]
+ /// Should the box clear floats
+ pub clear: Clear,
+
+ // Position properties
+ /// What should the `position` value of this struct use as a base offset?
+ pub position: Position,
+ /// How should the position of this element be tweaked relative to the layout defined?
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
+ pub inset: Rect<LengthPercentageAuto>,
+
+ // Size properties
+ /// Sets the initial size of the item
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
+ pub size: Size<Dimension>,
+ /// Controls the minimum size of the item
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
+ pub min_size: Size<LengthPercentageAuto>,
+ /// Controls the maximum size of the item
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::auto"))]
+ pub max_size: Size<LengthPercentageAuto>,
+ /// Sets the preferred aspect ratio for the item
+ ///
+ /// The ratio is calculated as width divided by height.
+ pub aspect_ratio: Option<f32>,
+
+ // Spacing Properties
+ /// How large should the margin be on each side?
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
+ pub margin: Rect<LengthPercentageAuto>,
+ /// How large should the padding be on each side?
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
+ pub padding: Rect<LengthPercentage>,
+ /// How large should the border be on each side?
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
+ pub border: Rect<LengthPercentage>,
+
+ // Alignment properties
+ /// How this node's children aligned in the cross/block axis?
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ pub align_items: AlignItems,
+ /// How this node should be aligned in the cross/block axis
+ /// Falls back to the parents [`AlignItems`] if not set
+ pub align_self: Option<AlignSelf>,
+ /// How this node's children should be aligned in the inline axis
+ #[cfg(any(feature = "grid", feature = "block_layout"))]
+ pub justify_items: AlignItems,
+ /// How this node should be aligned in the inline axis
+ /// Falls back to the parents [`JustifyItems`] if not set
+ pub justify_self: Option<AlignSelf>,
+ /// How should content contained within this item be aligned in the cross/block axis
+ #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
+ pub align_content: AlignContent,
+ /// How should content contained within this item be aligned in the main/inline axis
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ pub justify_content: JustifyContent,
+ /// How large should the gaps between items in a grid or flex container be?
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ #[cfg_attr(feature = "serde", serde(default = "style_helpers::zero"))]
+ pub gap: Size<LengthPercentage>,
+
+ // Block container properties
+ /// How items elements should aligned in the inline axis
+ #[cfg(feature = "block_layout")]
+ pub text_align: TextAlign,
+
+ // Flexbox container properties
+ /// Which direction does the main axis flow in?
+ #[cfg(feature = "flexbox")]
+ pub flex_direction: FlexDirection,
+ /// Should elements wrap, or stay in a single line?
+ #[cfg(feature = "flexbox")]
+ pub flex_wrap: FlexWrap,
+ /// The minimum number of flex lines requested for a multi-line container. When items are
+ /// balanced ([`FlexWrap::Balance`] or [`FlexWrap::BalanceReverse`]) they are balanced into
+ /// at least this many lines. For any multi-line container, definite cross-axis available
+ /// space for measuring items is divided between this many lines.
+ ///
+ /// 1 is the default value, and this value must be at least 1.
+ #[cfg(feature = "flexbox_balance")]
+ pub flex_line_count: u16,
+
+ // Flexbox item properties
+ /// Sets the initial main axis size of the item
+ #[cfg(feature = "flexbox")]
+ pub flex_basis: Dimension,
+ /// The relative rate at which this item grows when it is expanding to fill space
+ ///
+ /// 0.0 is the default value, and this value must be positive.
+ #[cfg(feature = "flexbox")]
+ pub flex_grow: f32,
+ /// The relative rate at which this item shrinks when it is contracting to fit into space
+ ///
+ /// 1.0 is the default value, and this value must be positive.
+ #[cfg(feature = "flexbox")]
+ pub flex_shrink: f32,
+
+ // Grid container properies
+ /// Defines the track sizing functions (heights) of the grid rows
+ #[cfg(feature = "grid")]
+ pub grid_template_rows: GridTrackVec<GridTemplateComponent<S>>,
+ /// Defines the track sizing functions (widths) of the grid columns
+ #[cfg(feature = "grid")]
+ pub grid_template_columns: GridTrackVec<GridTemplateComponent<S>>,
+ /// Defines the size of implicitly created rows
+ #[cfg(feature = "grid")]
+ pub grid_auto_rows: GridTrackVec<TrackSizingFunction>,
+ /// Defined the size of implicitly created columns
+ #[cfg(feature = "grid")]
+ pub grid_auto_columns: GridTrackVec<TrackSizingFunction>,
+ /// Controls how items get placed into the grid for auto-placed items
+ #[cfg(feature = "grid")]
+ pub grid_auto_flow: GridAutoFlow,
+
+ // Grid container named properties
+ /// Defines the rectangular grid areas
+ #[cfg(feature = "grid")]
+ pub grid_template_areas: Option<GridTemplateAreas<S>>,
+ /// The named lines between the columns
+ #[cfg(feature = "grid")]
+ pub grid_template_column_names: GridTrackVec<GridTrackVec<S>>,
+ /// The named lines between the rows
+ #[cfg(feature = "grid")]
+ pub grid_template_row_names: GridTrackVec<GridTrackVec<S>>,
+
+ // Grid child properties
+ /// Defines which row in the grid the item should start and end at
+ #[cfg(feature = "grid")]
+ pub grid_row: Line<GridPlacement<S>>,
+ /// Defines which column in the grid the item should start and end at
+ #[cfg(feature = "grid")]
+ pub grid_column: Line<GridPlacement<S>>,
+}
+
+impl<S: CheapCloneStr> Style<S> {
+ /// The [`Default`] layout, in a form that can be used in const functions
+ pub const DEFAULT: Style<S> = Style {
+ dummy: core::marker::PhantomData,
+ display: Display::DEFAULT,
+ item_is_table: false,
+ item_is_replaced: false,
+ item_is_compressible_replaced: false,
+ box_sizing: BoxSizing::BorderBox,
+ direction: Direction::Ltr,
+ overflow: Point { x: Overflow::Visible, y: Overflow::Visible },
+ scrollbar_width: 0.0,
+ contain: Contain::NONE,
+ #[cfg(feature = "float_layout")]
+ float: Float::None,
+ #[cfg(feature = "float_layout")]
+ clear: Clear::None,
+ position: Position::Static,
+ inset: Rect::auto(),
+ margin: Rect::zero(),
+ padding: Rect::zero(),
+ border: Rect::zero(),
+ size: Size::auto(),
+ min_size: Size::auto(),
+ max_size: Size::auto(),
+ aspect_ratio: None,
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ gap: Size::zero(),
+ // Alignment
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ align_items: AlignItems::NORMAL,
+ align_self: None,
+ #[cfg(any(feature = "grid", feature = "block_layout"))]
+ justify_items: AlignItems::NORMAL,
+ justify_self: None,
+ #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
+ align_content: AlignContent::NORMAL,
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ justify_content: JustifyContent::NORMAL,
+ // Block
+ #[cfg(feature = "block_layout")]
+ text_align: TextAlign::Auto,
+ // Flexbox
+ #[cfg(feature = "flexbox")]
+ flex_direction: FlexDirection::Row,
+ #[cfg(feature = "flexbox")]
+ flex_wrap: FlexWrap::NoWrap,
+ #[cfg(feature = "flexbox_balance")]
+ flex_line_count: 1,
+ #[cfg(feature = "flexbox")]
+ flex_grow: 0.0,
+ #[cfg(feature = "flexbox")]
+ flex_shrink: 1.0,
+ #[cfg(feature = "flexbox")]
+ flex_basis: Dimension::AUTO,
+ // Grid
+ #[cfg(feature = "grid")]
+ grid_template_rows: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_template_columns: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_template_areas: None,
+ #[cfg(feature = "grid")]
+ grid_template_column_names: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_template_row_names: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_auto_rows: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_auto_columns: GridTrackVec::new(),
+ #[cfg(feature = "grid")]
+ grid_auto_flow: GridAutoFlow::Row,
+ #[cfg(feature = "grid")]
+ grid_row: Line { start: GridPlacement::<S>::Auto, end: GridPlacement::<S>::Auto },
+ #[cfg(feature = "grid")]
+ grid_column: Line { start: GridPlacement::<S>::Auto, end: GridPlacement::<S>::Auto },
+ };
+}
+
+impl<S: CheapCloneStr> Default for Style<S> {
+ fn default() -> Self {
+ Style::DEFAULT
+ }
+}
+
+impl<S: CheapCloneStr> CoreStyle for Style<S> {
+ type CustomIdent = S;
+
+ #[inline(always)]
+ fn box_generation_mode(&self) -> BoxGenerationMode {
+ match self.display {
+ Display::None => BoxGenerationMode::None,
+ _ => BoxGenerationMode::Normal,
+ }
+ }
+ #[inline(always)]
+ #[cfg(feature = "block_layout")]
+ fn is_block(&self) -> bool {
+ matches!(self.display, Display::Block)
+ }
+ #[inline(always)]
+ fn is_compressible_replaced(&self) -> bool {
+ self.item_is_replaced || self.item_is_compressible_replaced
+ }
+ #[inline(always)]
+ fn is_replaced(&self) -> bool {
+ self.item_is_replaced
+ }
+ #[inline(always)]
+ fn box_sizing(&self) -> BoxSizing {
+ self.box_sizing
+ }
+ #[inline(always)]
+ fn direction(&self) -> Direction {
+ self.direction
+ }
+ #[inline(always)]
+ fn overflow(&self) -> Point<Overflow> {
+ self.overflow
+ }
+ #[inline(always)]
+ fn scrollbar_width(&self) -> f32 {
+ self.scrollbar_width
+ }
+ #[inline(always)]
+ fn position(&self) -> Position {
+ self.position
+ }
+ #[inline(always)]
+ fn inset(&self) -> Rect<LengthPercentageAuto> {
+ self.inset
+ }
+ #[inline(always)]
+ fn size(&self) -> Size<Dimension> {
+ self.size
+ }
+ #[inline(always)]
+ fn min_size(&self) -> Size<LengthPercentageAuto> {
+ self.min_size
+ }
+ #[inline(always)]
+ fn max_size(&self) -> Size<LengthPercentageAuto> {
+ self.max_size
+ }
+ #[inline(always)]
+ fn aspect_ratio(&self) -> Option<f32> {
+ self.aspect_ratio
+ }
+ #[inline(always)]
+ fn margin(&self) -> Rect<LengthPercentageAuto> {
+ self.margin
+ }
+ #[inline(always)]
+ fn padding(&self) -> Rect<LengthPercentage> {
+ self.padding
+ }
+ #[inline(always)]
+ fn border(&self) -> Rect<LengthPercentage> {
+ self.border
+ }
+ #[inline(always)]
+ fn contain(&self) -> Contain {
+ self.contain
+ }
+}
+
+impl<S: CheapCloneStr> OofItemStyle for Style<S> {
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ self.align_self
+ }
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ self.justify_self
+ }
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ self.item_is_table
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<S>> {
+ // TODO: Investigate eliminating clone
+ self.grid_row.clone()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<S>> {
+ // TODO: Investigate eliminating clone
+ self.grid_column.clone()
+ }
+}
+
+impl<T: CoreStyle> CoreStyle for &'_ T {
+ type CustomIdent = T::CustomIdent;
+
+ #[inline(always)]
+ fn box_generation_mode(&self) -> BoxGenerationMode {
+ (*self).box_generation_mode()
+ }
+ #[inline(always)]
+ fn is_block(&self) -> bool {
+ (*self).is_block()
+ }
+ #[inline(always)]
+ fn is_compressible_replaced(&self) -> bool {
+ (*self).is_compressible_replaced()
+ }
+ #[inline(always)]
+ fn is_replaced(&self) -> bool {
+ (*self).is_replaced()
+ }
+ #[inline(always)]
+ fn box_sizing(&self) -> BoxSizing {
+ (*self).box_sizing()
+ }
+ #[inline(always)]
+ fn direction(&self) -> Direction {
+ (*self).direction()
+ }
+ #[inline(always)]
+ fn overflow(&self) -> Point<Overflow> {
+ (*self).overflow()
+ }
+ #[inline(always)]
+ fn scrollbar_width(&self) -> f32 {
+ (*self).scrollbar_width()
+ }
+ #[inline(always)]
+ fn position(&self) -> Position {
+ (*self).position()
+ }
+ #[inline(always)]
+ fn inset(&self) -> Rect<LengthPercentageAuto> {
+ (*self).inset()
+ }
+ #[inline(always)]
+ fn is_containing_block(&self) -> ContainingBlockClaims {
+ (*self).is_containing_block()
+ }
+ #[inline(always)]
+ fn size(&self) -> Size<Dimension> {
+ (*self).size()
+ }
+ #[inline(always)]
+ fn min_size(&self) -> Size<LengthPercentageAuto> {
+ (*self).min_size()
+ }
+ #[inline(always)]
+ fn max_size(&self) -> Size<LengthPercentageAuto> {
+ (*self).max_size()
+ }
+ #[inline(always)]
+ fn aspect_ratio(&self) -> Option<f32> {
+ (*self).aspect_ratio()
+ }
+ #[inline(always)]
+ fn margin(&self) -> Rect<LengthPercentageAuto> {
+ (*self).margin()
+ }
+ #[inline(always)]
+ fn padding(&self) -> Rect<LengthPercentage> {
+ (*self).padding()
+ }
+ #[inline(always)]
+ fn border(&self) -> Rect<LengthPercentage> {
+ (*self).border()
+ }
+ #[inline(always)]
+ fn contain(&self) -> Contain {
+ (*self).contain()
+ }
+}
+
+impl<T: OofItemStyle> OofItemStyle for &'_ T {
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ (*self).align_self()
+ }
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ (*self).justify_self()
+ }
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ (*self).is_table()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ (*self).grid_row()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ (*self).grid_column()
+ }
+}
+
+#[cfg(feature = "block_layout")]
+impl<S: CheapCloneStr> BlockContainerStyle for Style<S> {
+ #[inline(always)]
+ fn text_align(&self) -> TextAlign {
+ self.text_align
+ }
+
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ self.align_content
+ }
+
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ self.justify_items
+ }
+}
+
+#[cfg(feature = "block_layout")]
+impl<T: BlockContainerStyle> BlockContainerStyle for &'_ T {
+ #[inline(always)]
+ fn text_align(&self) -> TextAlign {
+ (*self).text_align()
+ }
+
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ (*self).align_content()
+ }
+
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ (*self).justify_items()
+ }
+}
+
+#[cfg(feature = "block_layout")]
+impl<S: CheapCloneStr> BlockItemStyle for Style<S> {
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ self.item_is_table
+ }
+
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ self.align_self
+ }
+
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ self.justify_self
+ }
+
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ self.align_content
+ }
+
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn float(&self) -> Float {
+ self.float
+ }
+
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn clear(&self) -> Clear {
+ self.clear
+ }
+}
+
+#[cfg(feature = "block_layout")]
+impl<T: BlockItemStyle> BlockItemStyle for &'_ T {
+ #[inline(always)]
+ fn is_table(&self) -> bool {
+ (*self).is_table()
+ }
+
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ (*self).align_self()
+ }
+
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ (*self).justify_self()
+ }
+
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ (*self).align_content()
+ }
+
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn float(&self) -> Float {
+ (*self).float()
+ }
+
+ #[cfg(feature = "float_layout")]
+ #[inline(always)]
+ fn clear(&self) -> Clear {
+ (*self).clear()
+ }
+}
+
+#[cfg(feature = "flexbox")]
+impl<S: CheapCloneStr> FlexboxContainerStyle for Style<S> {
+ #[inline(always)]
+ fn flex_direction(&self) -> FlexDirection {
+ self.flex_direction
+ }
+ #[inline(always)]
+ fn flex_wrap(&self) -> FlexWrap {
+ self.flex_wrap
+ }
+ #[cfg(feature = "flexbox_balance")]
+ #[inline(always)]
+ fn flex_line_count(&self) -> u16 {
+ self.flex_line_count
+ }
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ self.gap
+ }
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ self.align_content
+ }
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ self.align_items
+ }
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ self.justify_content
+ }
+}
+
+#[cfg(feature = "flexbox")]
+impl<T: FlexboxContainerStyle> FlexboxContainerStyle for &'_ T {
+ #[inline(always)]
+ fn flex_direction(&self) -> FlexDirection {
+ (*self).flex_direction()
+ }
+ #[inline(always)]
+ fn flex_wrap(&self) -> FlexWrap {
+ (*self).flex_wrap()
+ }
+ #[cfg(feature = "flexbox_balance")]
+ #[inline(always)]
+ fn flex_line_count(&self) -> u16 {
+ (*self).flex_line_count()
+ }
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ (*self).gap()
+ }
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ (*self).align_content()
+ }
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ (*self).align_items()
+ }
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ (*self).justify_content()
+ }
+}
+
+#[cfg(feature = "flexbox")]
+impl<S: CheapCloneStr> FlexboxItemStyle for Style<S> {
+ #[inline(always)]
+ fn flex_basis(&self) -> Dimension {
+ self.flex_basis
+ }
+ #[inline(always)]
+ fn flex_grow(&self) -> f32 {
+ self.flex_grow
+ }
+ #[inline(always)]
+ fn flex_shrink(&self) -> f32 {
+ self.flex_shrink
+ }
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ self.align_self
+ }
+}
+
+#[cfg(feature = "flexbox")]
+impl<T: FlexboxItemStyle> FlexboxItemStyle for &'_ T {
+ #[inline(always)]
+ fn flex_basis(&self) -> Dimension {
+ (*self).flex_basis()
+ }
+ #[inline(always)]
+ fn flex_grow(&self) -> f32 {
+ (*self).flex_grow()
+ }
+ #[inline(always)]
+ fn flex_shrink(&self) -> f32 {
+ (*self).flex_shrink()
+ }
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ (*self).align_self()
+ }
+}
+
+#[cfg(feature = "grid")]
+impl<S: CheapCloneStr> GridContainerStyle for Style<S> {
+ type Repetition<'a>
+ = &'a GridTemplateRepetition<S>
+ where
+ Self: 'a;
+
+ type TemplateTrackList<'a>
+ = core::iter::Map<
+ core::slice::Iter<'a, GridTemplateComponent<S>>,
+ fn(&'a GridTemplateComponent<S>) -> GenericGridTemplateComponent<S, &'a GridTemplateRepetition<S>>,
+ >
+ where
+ Self: 'a;
+
+ type AutoTrackList<'a>
+ = core::iter::Copied<core::slice::Iter<'a, TrackSizingFunction>>
+ where
+ Self: 'a;
+
+ #[cfg(feature = "grid")]
+ type TemplateLineNames<'a>
+ = core::iter::Map<core::slice::Iter<'a, GridTrackVec<S>>, fn(&GridTrackVec<S>) -> core::slice::Iter<'_, S>>
+ where
+ Self: 'a;
+ #[cfg(feature = "grid")]
+ type GridTemplateAreas<'a>
+ = core::iter::Cloned<core::slice::Iter<'a, GridTemplateArea<S>>>
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
+ Some(self.grid_template_rows.iter().map(|c| c.as_component_ref()))
+ }
+ #[inline(always)]
+ fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
+ Some(self.grid_template_columns.iter().map(|c| c.as_component_ref()))
+ }
+ #[inline(always)]
+ fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
+ self.grid_auto_rows.iter().copied()
+ }
+ #[inline(always)]
+ fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
+ self.grid_auto_columns.iter().copied()
+ }
+ #[inline(always)]
+ fn grid_auto_flow(&self) -> GridAutoFlow {
+ self.grid_auto_flow
+ }
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ self.gap
+ }
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ self.align_content
+ }
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ self.justify_content
+ }
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ self.align_items
+ }
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ self.justify_items
+ }
+
+ #[inline(always)]
+ #[cfg(feature = "grid")]
+ fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
+ self.grid_template_areas.as_ref().map(|template| template.areas.iter().cloned())
+ }
+ #[inline(always)]
+ #[cfg(feature = "grid")]
+ fn grid_template_area_row_count(&self) -> u16 {
+ self.grid_template_areas.as_ref().map(|template| template.row_count).unwrap_or(0)
+ }
+ #[inline(always)]
+ #[cfg(feature = "grid")]
+ fn grid_template_area_column_count(&self) -> u16 {
+ self.grid_template_areas.as_ref().map(|template| template.column_count).unwrap_or(0)
+ }
+
+ #[inline(always)]
+ #[cfg(feature = "grid")]
+ fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
+ Some(self.grid_template_column_names.iter().map(|names| names.iter()))
+ }
+
+ #[inline(always)]
+ #[cfg(feature = "grid")]
+ fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
+ Some(self.grid_template_row_names.iter().map(|names| names.iter()))
+ }
+}
+
+#[cfg(feature = "grid")]
+impl<T: GridContainerStyle> GridContainerStyle for &'_ T {
+ type Repetition<'a>
+ = T::Repetition<'a>
+ where
+ Self: 'a;
+
+ type TemplateTrackList<'a>
+ = T::TemplateTrackList<'a>
+ where
+ Self: 'a;
+
+ type AutoTrackList<'a>
+ = T::AutoTrackList<'a>
+ where
+ Self: 'a;
+
+ /// The type returned by grid_template_row_names and grid_template_column_names
+ #[cfg(feature = "grid")]
+ type TemplateLineNames<'a>
+ = T::TemplateLineNames<'a>
+ where
+ Self: 'a;
+ #[cfg(feature = "grid")]
+ type GridTemplateAreas<'a>
+ = T::GridTemplateAreas<'a>
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
+ (*self).grid_template_rows()
+ }
+ #[inline(always)]
+ fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
+ (*self).grid_template_columns()
+ }
+ #[inline(always)]
+ fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
+ (*self).grid_auto_rows()
+ }
+ #[inline(always)]
+ fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
+ (*self).grid_auto_columns()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
+ (*self).grid_template_areas()
+ }
+ #[inline(always)]
+ fn grid_template_area_row_count(&self) -> u16 {
+ (*self).grid_template_area_row_count()
+ }
+ #[inline(always)]
+ fn grid_template_area_column_count(&self) -> u16 {
+ (*self).grid_template_area_column_count()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
+ (*self).grid_template_column_names()
+ }
+ #[cfg(feature = "grid")]
+ #[inline(always)]
+ fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
+ (*self).grid_template_row_names()
+ }
+ #[inline(always)]
+ fn grid_auto_flow(&self) -> GridAutoFlow {
+ (*self).grid_auto_flow()
+ }
+ #[inline(always)]
+ fn gap(&self) -> Size<LengthPercentage> {
+ (*self).gap()
+ }
+ #[inline(always)]
+ fn align_content(&self) -> AlignContent {
+ (*self).align_content()
+ }
+ #[inline(always)]
+ fn justify_content(&self) -> JustifyContent {
+ (*self).justify_content()
+ }
+ #[inline(always)]
+ fn align_items(&self) -> AlignItems {
+ (*self).align_items()
+ }
+ #[inline(always)]
+ fn justify_items(&self) -> AlignItems {
+ (*self).justify_items()
+ }
+}
+
+#[cfg(feature = "grid")]
+impl<S: CheapCloneStr> GridItemStyle for Style<S> {
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<S>> {
+ // TODO: Investigate eliminating clone
+ self.grid_row.clone()
+ }
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<S>> {
+ // TODO: Investigate eliminating clone
+ self.grid_column.clone()
+ }
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ self.align_self
+ }
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ self.justify_self
+ }
+}
+
+#[cfg(feature = "grid")]
+impl<T: GridItemStyle> GridItemStyle for &'_ T {
+ #[inline(always)]
+ fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ (*self).grid_row()
+ }
+ #[inline(always)]
+ fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
+ (*self).grid_column()
+ }
+ #[inline(always)]
+ fn align_self(&self) -> Option<AlignSelf> {
+ (*self).align_self()
+ }
+ #[inline(always)]
+ fn justify_self(&self) -> Option<AlignSelf> {
+ (*self).justify_self()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use super::Style;
+ use crate::sys::DefaultCheapStr;
+ use crate::{geometry::*, style_helpers::TaffyAuto as _};
+
+ #[test]
+ fn defaults_match() {
+ #[cfg(feature = "grid")]
+ use super::GridPlacement;
+
+ let old_defaults: Style<DefaultCheapStr> = Style {
+ dummy: core::marker::PhantomData,
+ display: Default::default(),
+ item_is_table: false,
+ item_is_replaced: false,
+ item_is_compressible_replaced: false,
+ box_sizing: Default::default(),
+ #[cfg(feature = "float_layout")]
+ float: Default::default(),
+ #[cfg(feature = "float_layout")]
+ clear: Default::default(),
+ direction: Default::default(),
+ overflow: Default::default(),
+ scrollbar_width: 0.0,
+ contain: Default::default(),
+ position: Default::default(),
+ #[cfg(feature = "flexbox")]
+ flex_direction: Default::default(),
+ #[cfg(feature = "flexbox")]
+ flex_wrap: Default::default(),
+ #[cfg(feature = "flexbox_balance")]
+ flex_line_count: 1,
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ align_items: Default::default(),
+ align_self: Default::default(),
+ #[cfg(any(feature = "grid", feature = "block_layout"))]
+ justify_items: Default::default(),
+ justify_self: Default::default(),
+ #[cfg(any(feature = "flexbox", feature = "grid", feature = "block_layout"))]
+ align_content: Default::default(),
+ #[cfg(any(feature = "flexbox", feature = "grid"))]
+ justify_content: Default::default(),
+ inset: Rect::auto(),
+ margin: Rect::zero(),
+ padding: Rect::zero(),
+ border: Rect::zero(),
+ gap: Size::zero(),
+ #[cfg(feature = "block_layout")]
+ text_align: Default::default(),
+ #[cfg(feature = "flexbox")]
+ flex_grow: 0.0,
+ #[cfg(feature = "flexbox")]
+ flex_shrink: 1.0,
+ #[cfg(feature = "flexbox")]
+ flex_basis: super::Dimension::AUTO,
+ size: Size::auto(),
+ min_size: Size::auto(),
+ max_size: Size::auto(),
+ aspect_ratio: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_template_rows: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_template_columns: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_template_row_names: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_template_column_names: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_template_areas: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_auto_rows: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_auto_columns: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_auto_flow: Default::default(),
+ #[cfg(feature = "grid")]
+ grid_row: Line { start: GridPlacement::Auto, end: GridPlacement::Auto },
+ #[cfg(feature = "grid")]
+ grid_column: Line { start: GridPlacement::Auto, end: GridPlacement::Auto },
+ };
+
+ assert_eq!(Style::DEFAULT, Style::<DefaultCheapStr>::default());
+ assert_eq!(Style::DEFAULT, old_defaults);
+ }
+
+ #[test]
+ #[cfg(feature = "parse")]
+ fn parse_contain() {
+ use super::Contain;
+
+ fn parse(input: &str) -> Contain {
+ input.parse().unwrap()
+ }
+
+ assert_eq!(parse("none"), Contain::NONE);
+ assert_eq!(parse("content"), Contain::LAYOUT | Contain::PAINT);
+ assert_eq!(parse("layout"), Contain::LAYOUT);
+ assert_eq!(parse("style"), Contain::NONE);
+ assert_eq!(parse("paint"), Contain::PAINT);
+ assert_eq!(parse("layout paint"), Contain::LAYOUT | Contain::PAINT);
+ assert_eq!(parse("paint layout"), Contain::LAYOUT | Contain::PAINT);
+ assert_eq!(parse("layout paint style"), Contain::LAYOUT | Contain::PAINT);
+ assert_eq!(parse("Paint LAYOUT"), Contain::LAYOUT | Contain::PAINT);
+ assert!("paint paint".parse::<Contain>().is_err());
+
+ assert!("".parse::<Contain>().is_err());
+ assert!("banana".parse::<Contain>().is_err());
+ assert!("layout layout".parse::<Contain>().is_err());
+ assert!("none layout".parse::<Contain>().is_err());
+ assert!("layout none".parse::<Contain>().is_err());
+ assert!("content layout".parse::<Contain>().is_err());
+ assert!("layout content".parse::<Contain>().is_err());
+ }
+
+ // NOTE: Please feel free the update the sizes in this test as required. This test is here to prevent unintentional size changes
+ // and to serve as accurate up-to-date documentation on the sizes.
+ #[test]
+ fn style_sizes() {
+ use super::*;
+ type S = crate::sys::DefaultCheapStr;
+
+ fn assert_type_size<T>(expected_size: usize) {
+ let name = ::core::any::type_name::<T>();
+ let name = name.replace("taffy::geometry::", "");
+ let name = name.replace("taffy::style::dimension::", "");
+ let name = name.replace("taffy::style::alignment::", "");
+ let name = name.replace("taffy::style::flex::", "");
+ let name = name.replace("taffy::style::grid::", "");
+
+ assert_eq!(
+ ::core::mem::size_of::<T>(),
+ expected_size,
+ "Expected {} for be {} byte(s) but it was {} byte(s)",
+ name,
+ expected_size,
+ ::core::mem::size_of::<T>(),
+ );
+ }
+
+ // Display and Position
+ assert_type_size::<Display>(1);
+ assert_type_size::<BoxSizing>(1);
+ assert_type_size::<Position>(1);
+ assert_type_size::<Overflow>(1);
+
+ // Dimensions and aggregations of Dimensions
+ assert_type_size::<f32>(4);
+ assert_type_size::<LengthPercentage>(8);
+ assert_type_size::<LengthPercentageAuto>(8);
+ assert_type_size::<Dimension>(8);
+ assert_type_size::<Size<LengthPercentage>>(16);
+ assert_type_size::<Size<LengthPercentageAuto>>(16);
+ assert_type_size::<Size<Dimension>>(16);
+ assert_type_size::<Rect<LengthPercentage>>(32);
+ assert_type_size::<Rect<LengthPercentageAuto>>(32);
+ assert_type_size::<Rect<Dimension>>(32);
+
+ // Alignment — `AlignContent` and `AlignItems` are structs of two `#[repr(u8)]` enums
+ // (position keyword + safety modifier). Niche-packing in the safety byte (only 2 of
+ // 256 values used) lets `Option<_>` stay the same size as the bare struct.
+ assert_type_size::<AlignContentKeyword>(1);
+ assert_type_size::<AlignItemsKeyword>(1);
+ assert_type_size::<AlignmentSafety>(1);
+ assert_type_size::<AlignContent>(2);
+ assert_type_size::<AlignItems>(2);
+ assert_type_size::<Option<AlignItems>>(2);
+
+ // Flexbox Container
+ assert_type_size::<FlexDirection>(1);
+ assert_type_size::<FlexWrap>(1);
+
+ // CSS Grid Container
+ assert_type_size::<GridAutoFlow>(1);
+ assert_type_size::<MinTrackSizingFunction>(8);
+ assert_type_size::<MaxTrackSizingFunction>(8);
+ assert_type_size::<TrackSizingFunction>(16);
+ assert_type_size::<Vec<TrackSizingFunction>>(24);
+ assert_type_size::<Vec<GridTemplateComponent<S>>>(24);
+
+ // String-type dependent (String)
+ assert_type_size::<GridTemplateComponent<String>>(56);
+ assert_type_size::<GridPlacement<String>>(32);
+ assert_type_size::<Line<GridPlacement<String>>>(64);
+ assert_type_size::<Style<String>>(560);
+
+ // String-type dependent (Arc<str>)
+ assert_type_size::<GridTemplateComponent<Arc<str>>>(56);
+ assert_type_size::<GridPlacement<Arc<str>>>(24);
+ assert_type_size::<Line<GridPlacement<Arc<str>>>>(48);
+ assert_type_size::<Style<Arc<str>>>(528);
+ }
+}
diff --git a/vendor/taffy/src/style_helpers.rs b/vendor/taffy/src/style_helpers.rs
new file mode 100644
index 00000000..44cb3490
--- /dev/null
+++ b/vendor/taffy/src/style_helpers.rs
@@ -0,0 +1,634 @@
+//! Helper functions which it make it easier to create instances of types in the `style` and `geometry` modules.
+use crate::{
+ geometry::{Line, Point, Rect, Size},
+ style::LengthPercentage,
+};
+
+#[cfg(feature = "grid")]
+use crate::{
+ geometry::MinMax,
+ style::{
+ GridTemplateComponent, GridTemplateRepetition, MaxTrackSizingFunction, MinTrackSizingFunction, RepetitionCount,
+ TrackSizingFunction,
+ },
+ util::sys::Vec,
+ CheapCloneStr,
+};
+#[cfg(feature = "grid")]
+use core::fmt::Debug;
+
+/// Returns an auto-repeated track definition
+#[cfg(feature = "grid")]
+#[inline(always)]
+pub fn repeat<Input, S>(repetition_kind: Input, tracks: Vec<TrackSizingFunction>) -> GridTemplateComponent<S>
+where
+ Input: TryInto<RepetitionCount>,
+ <Input as TryInto<RepetitionCount>>::Error: Debug,
+ S: CheapCloneStr,
+{
+ GridTemplateComponent::Repeat(GridTemplateRepetition {
+ count: repetition_kind.try_into().unwrap(),
+ tracks,
+ line_names: Vec::new(),
+ })
+}
+
+#[cfg(feature = "grid")]
+/// Returns a grid template containing `count` evenly sized tracks
+pub fn evenly_sized_tracks<S: CheapCloneStr>(count: u16) -> Vec<GridTemplateComponent<S>> {
+ use crate::util::sys::new_vec_with_capacity;
+ let mut repeated_tracks = new_vec_with_capacity(1);
+ repeated_tracks.push(flex(1.0f32));
+ let mut tracks = new_vec_with_capacity(1);
+ tracks.push(repeat(count, repeated_tracks));
+ tracks
+}
+
+/// Specifies a grid line to place a grid item between in CSS Grid Line coordinates:
+/// - Positive indices count upwards from the start (top or left) of the explicit grid
+/// - Negative indices count downwards from the end (bottom or right) of the explicit grid
+/// - ZERO IS INVALID index, and will be treated as a GridPlacement::Auto.
+#[inline(always)]
+pub fn line<T: TaffyGridLine>(index: i16) -> T {
+ T::from_line_index(index)
+}
+/// Trait to abstract over grid line values
+pub trait TaffyGridLine {
+ /// Converts an i16 into Self
+ fn from_line_index(index: i16) -> Self;
+}
+
+/// Returns a GridPlacement::Span
+#[inline(always)]
+pub fn span<T: TaffyGridSpan>(span: u16) -> T {
+ T::from_span(span)
+}
+/// Trait to abstract over grid span values
+pub trait TaffyGridSpan {
+ /// Converts an u16 into Self
+ fn from_span(span: u16) -> Self;
+}
+
+/// Returns a MinMax with min value of min and max value of max
+#[cfg(feature = "grid")]
+#[inline(always)]
+pub fn minmax<Output>(min: MinTrackSizingFunction, max: MaxTrackSizingFunction) -> Output
+where
+ Output: From<MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>>,
+{
+ MinMax { min, max }.into()
+}
+
+/// Shorthand for minmax(0, Nfr). Probably what you want if you want exactly evenly sized tracks.
+#[cfg(feature = "grid")]
+#[inline(always)]
+pub fn flex<Input, Output>(flex_fraction: Input) -> Output
+where
+ Input: Into<f64> + Copy,
+ Output: From<MinMax<MinTrackSizingFunction, MaxTrackSizingFunction>>,
+{
+ MinMax { min: zero(), max: fr(flex_fraction) }.into()
+}
+
+/// Returns the zero value for that type
+#[inline(always)]
+pub const fn zero<T: TaffyZero>() -> T {
+ T::ZERO
+}
+
+/// Trait to abstract over zero values
+pub trait TaffyZero {
+ /// The zero value for type implementing TaffyZero
+ const ZERO: Self;
+}
+impl TaffyZero for f32 {
+ const ZERO: f32 = 0.0;
+}
+impl<T: TaffyZero> TaffyZero for Option<T> {
+ const ZERO: Option<T> = Some(T::ZERO);
+}
+impl<T: TaffyZero> TaffyZero for Point<T> {
+ const ZERO: Point<T> = Point { x: T::ZERO, y: T::ZERO };
+}
+impl<T: TaffyZero> Point<T> {
+ /// Returns a Point where both the x and y values are the zero value of the contained type
+ /// (e.g. 0.0, Some(0.0), or Dimension::Length(0.0))
+ #[inline(always)]
+ pub const fn zero() -> Self {
+ zero::<Self>()
+ }
+}
+impl<T: TaffyZero> TaffyZero for Line<T> {
+ const ZERO: Line<T> = Line { start: T::ZERO, end: T::ZERO };
+}
+impl<T: TaffyZero> Line<T> {
+ /// Returns a Line where both the start and end values are the zero value of the contained type
+ /// (e.g. 0.0, Some(0.0), or Dimension::Length(0.0))
+ #[inline(always)]
+ pub const fn zero() -> Self {
+ zero::<Self>()
+ }
+}
+impl<T: TaffyZero> TaffyZero for Size<T> {
+ const ZERO: Size<T> = Size { width: T::ZERO, height: T::ZERO };
+}
+impl<T: TaffyZero> Size<T> {
+ /// Returns a Size where both the width and height values are the zero value of the contained type
+ /// (e.g. 0.0, Some(0.0), or Dimension::Length(0.0))
+ #[inline(always)]
+ pub const fn zero() -> Self {
+ zero::<Self>()
+ }
+}
+impl<T: TaffyZero> TaffyZero for Rect<T> {
+ const ZERO: Rect<T> = Rect { left: T::ZERO, right: T::ZERO, top: T::ZERO, bottom: T::ZERO };
+}
+impl<T: TaffyZero> Rect<T> {
+ /// Returns a Rect where the left, right, top, and bottom values are all the zero value of the contained type
+ /// (e.g. 0.0, Some(0.0), or Dimension::Length(0.0))
+ #[inline(always)]
+ pub const fn zero() -> Self {
+ zero::<Self>()
+ }
+}
+
+/// Returns the auto value for that type
+#[inline(always)]
+pub const fn auto<T: TaffyAuto>() -> T {
+ T::AUTO
+}
+
+/// Trait to abstract over auto values
+pub trait TaffyAuto {
+ /// The auto value for type implementing TaffyAuto
+ const AUTO: Self;
+}
+impl<T: TaffyAuto> TaffyAuto for Option<T> {
+ const AUTO: Option<T> = Some(T::AUTO);
+}
+impl<T: TaffyAuto> TaffyAuto for Point<T> {
+ const AUTO: Point<T> = Point { x: T::AUTO, y: T::AUTO };
+}
+impl<T: TaffyAuto> Point<T> {
+ /// Returns a Point where both the x and y values are the auto value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ auto::<Self>()
+ }
+}
+impl<T: TaffyAuto> TaffyAuto for Line<T> {
+ const AUTO: Line<T> = Line { start: T::AUTO, end: T::AUTO };
+}
+impl<T: TaffyAuto> Line<T> {
+ /// Returns a Line where both the start and end values are the auto value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ auto::<Self>()
+ }
+}
+impl<T: TaffyAuto> TaffyAuto for Size<T> {
+ const AUTO: Size<T> = Size { width: T::AUTO, height: T::AUTO };
+}
+impl<T: TaffyAuto> Size<T> {
+ /// Returns a Size where both the width and height values are the auto value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ auto::<Self>()
+ }
+}
+impl<T: TaffyAuto> TaffyAuto for Rect<T> {
+ const AUTO: Rect<T> = Rect { left: T::AUTO, right: T::AUTO, top: T::AUTO, bottom: T::AUTO };
+}
+impl<T: TaffyAuto> Rect<T> {
+ /// Returns a Rect where the left, right, top, and bottom values are all the auto value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn auto() -> Self {
+ auto::<Self>()
+ }
+}
+
+/// Returns the auto value for that type
+#[inline(always)]
+pub const fn min_content<T: TaffyMinContent>() -> T {
+ T::MIN_CONTENT
+}
+
+/// Trait to abstract over min_content values
+pub trait TaffyMinContent {
+ /// The min_content value for type implementing TaffyZero
+ const MIN_CONTENT: Self;
+}
+impl<T: TaffyMinContent> TaffyMinContent for Option<T> {
+ const MIN_CONTENT: Option<T> = Some(T::MIN_CONTENT);
+}
+impl<T: TaffyMinContent> TaffyMinContent for Point<T> {
+ const MIN_CONTENT: Point<T> = Point { x: T::MIN_CONTENT, y: T::MIN_CONTENT };
+}
+impl<T: TaffyMinContent> Point<T> {
+ /// Returns a Point where both the x and y values are the min_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ min_content::<Self>()
+ }
+}
+impl<T: TaffyMinContent> TaffyMinContent for Line<T> {
+ const MIN_CONTENT: Line<T> = Line { start: T::MIN_CONTENT, end: T::MIN_CONTENT };
+}
+impl<T: TaffyMinContent> Line<T> {
+ /// Returns a Line where both the start and end values are the min_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ min_content::<Self>()
+ }
+}
+impl<T: TaffyMinContent> TaffyMinContent for Size<T> {
+ const MIN_CONTENT: Size<T> = Size { width: T::MIN_CONTENT, height: T::MIN_CONTENT };
+}
+impl<T: TaffyMinContent> Size<T> {
+ /// Returns a Size where both the width and height values are the min_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ min_content::<Self>()
+ }
+}
+impl<T: TaffyMinContent> TaffyMinContent for Rect<T> {
+ const MIN_CONTENT: Rect<T> =
+ Rect { left: T::MIN_CONTENT, right: T::MIN_CONTENT, top: T::MIN_CONTENT, bottom: T::MIN_CONTENT };
+}
+impl<T: TaffyMinContent> Rect<T> {
+ /// Returns a Rect where the left, right, top, and bottom values are all the min_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn min_content() -> Self {
+ min_content::<Self>()
+ }
+}
+
+/// Returns the auto value for that type
+#[inline(always)]
+pub const fn max_content<T: TaffyMaxContent>() -> T {
+ T::MAX_CONTENT
+}
+
+/// Trait to abstract over max_content values
+pub trait TaffyMaxContent {
+ /// The max_content value for type implementing TaffyZero
+ const MAX_CONTENT: Self;
+}
+impl<T: TaffyMaxContent> TaffyMaxContent for Option<T> {
+ const MAX_CONTENT: Option<T> = Some(T::MAX_CONTENT);
+}
+impl<T: TaffyMaxContent> TaffyMaxContent for Point<T> {
+ const MAX_CONTENT: Point<T> = Point { x: T::MAX_CONTENT, y: T::MAX_CONTENT };
+}
+impl<T: TaffyMaxContent> Point<T> {
+ /// Returns a Point where both the x and y values are the max_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ max_content::<Self>()
+ }
+}
+impl<T: TaffyMaxContent> TaffyMaxContent for Line<T> {
+ const MAX_CONTENT: Line<T> = Line { start: T::MAX_CONTENT, end: T::MAX_CONTENT };
+}
+impl<T: TaffyMaxContent> Line<T> {
+ /// Returns a Line where both the start and end values are the max_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ max_content::<Self>()
+ }
+}
+impl<T: TaffyMaxContent> TaffyMaxContent for Size<T> {
+ const MAX_CONTENT: Size<T> = Size { width: T::MAX_CONTENT, height: T::MAX_CONTENT };
+}
+impl<T: TaffyMaxContent> Size<T> {
+ /// Returns a Size where both the width and height values are the max_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ max_content::<Self>()
+ }
+}
+impl<T: TaffyMaxContent> TaffyMaxContent for Rect<T> {
+ const MAX_CONTENT: Rect<T> =
+ Rect { left: T::MAX_CONTENT, right: T::MAX_CONTENT, top: T::MAX_CONTENT, bottom: T::MAX_CONTENT };
+}
+impl<T: TaffyMaxContent> Rect<T> {
+ /// Returns a Rect where the left, right, top, and bottom values are all the max_content value of the contained type
+ /// (e.g. Dimension::Auto or LengthPercentageAuto::Auto)
+ #[inline(always)]
+ pub const fn max_content() -> Self {
+ max_content::<Self>()
+ }
+}
+
+/// Returns a value of the inferred type which represent a `fit-content(…)` value
+/// with the given argument.
+#[inline(always)]
+pub fn fit_content<T: TaffyFitContent>(argument: LengthPercentage) -> T {
+ T::fit_content(argument)
+}
+
+/// Trait to create `fit-content(…)` values from plain numbers
+pub trait TaffyFitContent {
+ /// Converts a LengthPercentage into Self
+ fn fit_content(argument: LengthPercentage) -> Self;
+}
+impl<T: TaffyFitContent> TaffyFitContent for Point<T> {
+ #[inline(always)]
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Point { x: T::fit_content(argument), y: T::fit_content(argument) }
+ }
+}
+impl<T: TaffyFitContent> Point<T> {
+ /// Returns a Point with x and y set to the same `fit-content(…)` value
+ /// with the given argument.
+ #[inline(always)]
+ pub fn fit_content(argument: LengthPercentage) -> Self {
+ fit_content(argument)
+ }
+}
+impl<T: TaffyFitContent> TaffyFitContent for Line<T> {
+ #[inline(always)]
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Line { start: T::fit_content(argument), end: T::fit_content(argument) }
+ }
+}
+impl<T: TaffyFitContent> Line<T> {
+ /// Returns a Line with start and end set to the same `fit-content(…)` value
+ /// with the given argument.
+ #[inline(always)]
+ pub fn fit_content(argument: LengthPercentage) -> Self {
+ fit_content(argument)
+ }
+}
+impl<T: TaffyFitContent> TaffyFitContent for Size<T> {
+ #[inline(always)]
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Size { width: T::fit_content(argument), height: T::fit_content(argument) }
+ }
+}
+impl<T: TaffyFitContent> Size<T> {
+ /// Returns a Size where with width and height set to the same `fit-content(…)` value
+ /// with the given argument.
+ #[inline(always)]
+ pub fn fit_content(argument: LengthPercentage) -> Self {
+ fit_content(argument)
+ }
+}
+impl<T: TaffyFitContent> TaffyFitContent for Rect<T> {
+ #[inline(always)]
+ fn fit_content(argument: LengthPercentage) -> Self {
+ Rect {
+ left: T::fit_content(argument),
+ right: T::fit_content(argument),
+ top: T::fit_content(argument),
+ bottom: T::fit_content(argument),
+ }
+ }
+}
+impl<T: TaffyFitContent> Rect<T> {
+ /// Returns a Rect where the left, right, top and bottom values are all constant fit_content value of the contained type
+ /// (e.g. 2.1, Some(2.1), or Dimension::Length(2.1))
+ #[inline(always)]
+ pub fn fit_content(argument: LengthPercentage) -> Self {
+ fit_content(argument)
+ }
+}
+
+/// Returns a value of the inferred type which represent an absolute length
+#[inline(always)]
+pub fn length<Input: Into<f64> + Copy, T: FromLength>(value: Input) -> T {
+ T::from_length(value)
+}
+
+/// Trait to create absolute length values from plain numbers
+pub trait FromLength {
+ /// Converts into an `Into<f64>` into Self
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self;
+}
+impl FromLength for f32 {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ value.into() as f32
+ }
+}
+impl FromLength for Option<f32> {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Some(value.into() as f32)
+ }
+}
+impl<T: FromLength> FromLength for Point<T> {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Point { x: T::from_length(value), y: T::from_length(value) }
+ }
+}
+impl<T: FromLength> Point<T> {
+ /// Returns a Point where x and y values are the same given absolute length
+ #[inline(always)]
+ pub fn length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ length::<Input, Self>(value)
+ }
+}
+impl<T: FromLength> FromLength for Line<T> {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Line { start: T::from_length(value), end: T::from_length(value) }
+ }
+}
+impl<T: FromLength> Line<T> {
+ /// Returns a Line where both the start and end values are the same given absolute length
+ #[inline(always)]
+ pub fn length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ length::<Input, Self>(value)
+ }
+}
+impl<T: FromLength> FromLength for Size<T> {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Size { width: T::from_length(value), height: T::from_length(value) }
+ }
+}
+impl<T: FromLength> Size<T> {
+ /// Returns a Size where both the width and height values the same given absolute length
+ #[inline(always)]
+ pub fn length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ length::<Input, Self>(value)
+ }
+}
+impl<T: FromLength> FromLength for Rect<T> {
+ #[inline(always)]
+ fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ Rect {
+ left: T::from_length(value),
+ right: T::from_length(value),
+ top: T::from_length(value),
+ bottom: T::from_length(value),
+ }
+ }
+}
+impl<T: FromLength> Rect<T> {
+ /// Returns a Rect where the left, right, top and bottom values are all the same given absolute length
+ #[inline(always)]
+ pub fn length<Input: Into<f64> + Copy>(value: Input) -> Self {
+ length::<Input, Self>(value)
+ }
+}
+
+/// Returns a value of the inferred type which represent a percentage
+#[inline(always)]
+pub fn percent<Input: Into<f64> + Copy, T: FromPercent>(percent: Input) -> T {
+ T::from_percent(percent)
+}
+
+/// Trait to create constant percent values from plain numbers
+pub trait FromPercent {
+ /// Converts into an `Into<f64>` into Self
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self;
+}
+impl FromPercent for f32 {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ percent.into() as f32
+ }
+}
+impl FromPercent for Option<f32> {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Some(percent.into() as f32)
+ }
+}
+impl<T: FromPercent> FromPercent for Point<T> {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Point { x: T::from_percent(percent), y: T::from_percent(percent) }
+ }
+}
+impl<T: FromPercent> Point<T> {
+ /// Returns a Point where both the x and y values are the constant percent value of the contained type
+ /// (e.g. 2.1, Some(2.1), or Dimension::Length(2.1))
+ #[inline(always)]
+ pub fn percent<Input: Into<f64> + Copy>(percent_value: Input) -> Self {
+ percent::<Input, Self>(percent_value)
+ }
+}
+impl<T: FromPercent> FromPercent for Line<T> {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Line { start: T::from_percent(percent), end: T::from_percent(percent) }
+ }
+}
+impl<T: FromPercent> Line<T> {
+ /// Returns a Line where both the start and end values are the constant percent value of the contained type
+ /// (e.g. 2.1, Some(2.1), or Dimension::Length(2.1))
+ #[inline(always)]
+ pub fn percent<Input: Into<f64> + Copy>(percent_value: Input) -> Self {
+ percent::<Input, Self>(percent_value)
+ }
+}
+impl<T: FromPercent> FromPercent for Size<T> {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Size { width: T::from_percent(percent), height: T::from_percent(percent) }
+ }
+}
+impl<T: FromPercent> Size<T> {
+ /// Returns a Size where both the width and height values are the constant percent value of the contained type
+ /// (e.g. 2.1, Some(2.1), or Dimension::Length(2.1))
+ #[inline(always)]
+ pub fn percent<Input: Into<f64> + Copy>(percent_value: Input) -> Self {
+ percent::<Input, Self>(percent_value)
+ }
+}
+impl<T: FromPercent> FromPercent for Rect<T> {
+ #[inline(always)]
+ fn from_percent<Input: Into<f64> + Copy>(percent: Input) -> Self {
+ Rect {
+ left: T::from_percent(percent),
+ right: T::from_percent(percent),
+ top: T::from_percent(percent),
+ bottom: T::from_percent(percent),
+ }
+ }
+}
+impl<T: FromPercent> Rect<T> {
+ /// Returns a Rect where the left, right, top and bottom values are all constant percent value of the contained type
+ /// (e.g. 2.1, Some(2.1), or Dimension::Length(2.1))
+ #[inline(always)]
+ pub fn percent<Input: Into<f64> + Copy>(percent_value: Input) -> Self {
+ percent::<Input, Self>(percent_value)
+ }
+}
+
+/// Create a `Fraction` track sizing function (`fr` in CSS)
+#[cfg(feature = "grid")]
+#[inline(always)]
+pub fn fr<Input: Into<f64> + Copy, T: FromFr>(flex: Input) -> T {
+ T::from_fr(flex)
+}
+
+/// Trait to create constant percent values from plain numbers
+pub trait FromFr {
+ /// Converts into an `Into<f64>` into Self
+ fn from_fr<Input: Into<f64> + Copy>(flex: Input) -> Self;
+}
+
+#[cfg(feature = "grid")]
+#[cfg(test)]
+mod repeat_fn_tests {
+ type S = crate::sys::DefaultCheapStr;
+ use super::repeat;
+ use crate::{
+ style::{GridTemplateComponent, RepetitionCount, TrackSizingFunction},
+ GridTemplateRepetition,
+ };
+
+ const TEST_VEC: Vec<TrackSizingFunction> = Vec::new();
+
+ #[test]
+ fn test_repeat_u16() {
+ assert_eq!(
+ repeat::<_, S>(123, TEST_VEC),
+ GridTemplateComponent::Repeat(GridTemplateRepetition {
+ count: RepetitionCount::Count(123),
+ tracks: TEST_VEC,
+ line_names: Vec::new(),
+ })
+ );
+ }
+
+ #[test]
+ fn test_repeat_auto_fit_str() {
+ assert_eq!(
+ repeat::<_, S>("auto-fit", TEST_VEC),
+ GridTemplateComponent::Repeat(GridTemplateRepetition {
+ count: RepetitionCount::AutoFit,
+ tracks: TEST_VEC,
+ line_names: Vec::new(),
+ })
+ );
+ }
+
+ #[test]
+ fn test_repeat_auto_fill_str() {
+ assert_eq!(
+ repeat::<_, S>("auto-fill", TEST_VEC),
+ GridTemplateComponent::Repeat(GridTemplateRepetition {
+ count: RepetitionCount::AutoFill,
+ tracks: TEST_VEC,
+ line_names: Vec::new(),
+ })
+ );
+ }
+}
diff --git a/vendor/taffy/src/tree/cache.rs b/vendor/taffy/src/tree/cache.rs
new file mode 100644
index 00000000..6b6e3e37
--- /dev/null
+++ b/vendor/taffy/src/tree/cache.rs
@@ -0,0 +1,555 @@
+//! A cache for storing the results of layout computation
+
+#![allow(clippy::unusual_byte_groupings)]
+
+use crate::geometry::Size;
+use crate::style::AvailableSpace;
+use crate::tree::{CollapsibleMarginSet, LayoutInput, LayoutOutput, RunMode, SizingMode};
+use crate::RequestedAxis;
+
+/// The number of cache entries for each node in the tree
+const CACHE_SIZE: usize = 9;
+
+// Manually written-out results of float to u32 bit casts because
+// `f32::to_bits` is not yet const at our MSRV.
+
+/// `f32::INFINITY` as a u32
+const INFINITY_BITS: u32 = 0b_0_11111111_00000000000000000000000_u32;
+/// `f32::NEG_INFINITY` as a u32
+const NEG_INFINITY_BITS: u32 = 0b_1_11111111_00000000000000000000000_u32;
+
+// The `CacheKey` encodes two f32s as a u64. We know that the f32s will always be
+// non-negative, so we pack two extra bits encoding the `RequestedAxis` into the
+// sign bits of the f32s. These constants help to encode and decode those bits.
+
+/// The sign bit of the first f32
+const SIGN_BIT_1: u64 = 1u64 << 63;
+/// The sign bit of the second f32
+const SIGN_BIT_2: u64 = 1u64 << 31;
+/// Mask of both sign bits (used to compute NON_SIGN_BITS_MASK)
+const BOTH_SIGN_BITS_MASK: u64 = SIGN_BIT_1 | SIGN_BIT_2;
+/// Mask of excluding the sign bits (used when setting/getting the size excluding the packed bits)
+const NON_SIGN_BITS_MASK: u64 = !BOTH_SIGN_BITS_MASK;
+
+/// Mask which includes only the bits which encode the x-axis value that we can use to ignore the
+/// y-axis value when comparing a cache key.
+const X_AXIS_VALUE_MASK: u64 = (u32::MAX as u64) << 32;
+
+/// Pack `Option<f32>` into `u32`
+#[inline(always)]
+fn option_cache_key(input: Option<f32>) -> u32 {
+ match input {
+ Some(value) => value.to_bits(),
+ None => INFINITY_BITS,
+ }
+}
+
+/// Pack `Size<Option<f32>>` into `u64`
+#[inline(always)]
+fn size_option_cache_key(input: Size<Option<f32>>) -> u64 {
+ (option_cache_key(input.width) as u64) << 32 | option_cache_key(input.height) as u64
+}
+
+/// Pack `AvailableSpace` into `u32`
+#[inline(always)]
+fn available_space_cache_key(input: AvailableSpace) -> u32 {
+ match input {
+ AvailableSpace::Definite(value) => (-value).to_bits(),
+ AvailableSpace::MinContent => NEG_INFINITY_BITS,
+ AvailableSpace::MaxContent => INFINITY_BITS,
+ }
+}
+
+/// Pack `Size<AvailableSpace>` into `u64`
+#[inline(always)]
+#[allow(dead_code)]
+fn size_available_space_cache_key(input: Size<AvailableSpace>) -> u64 {
+ (available_space_cache_key(input.width) as u64) << 32 | available_space_cache_key(input.height) as u64
+}
+
+/// Encodes combination of a `known_dimension` (Option<f32>) and `AvailableSpace` in
+/// a single dimension into a cache key in a single dimension.
+#[inline(always)]
+fn mixed_cache_key(kd: Option<f32>, avs: AvailableSpace) -> u32 {
+ kd.map(|kd| kd.to_bits()).unwrap_or_else(|| available_space_cache_key(avs))
+}
+
+/// Encodes combination of a `known_dimension` (Option<f32>) and `AvailableSpace` in
+/// two dimensions into a cache key in a single dimension.
+#[inline(always)]
+fn size_mixed_cache_key(kd: Size<Option<f32>>, avs: Size<AvailableSpace>) -> u64 {
+ (mixed_cache_key(kd.width, avs.width) as u64) << 32 | mixed_cache_key(kd.height, avs.height) as u64
+}
+
+/// Space-optimised cache key that packs bits into as small a size as possible
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+struct CacheKey {
+ /// The initial cached size of the node itself
+ kd_available_space: u64,
+ /// The initial cached size of the parent's node
+ parent_size: u64,
+ /// Whether each known dimension is definite. Normalized such that an axis
+ /// without a known dimension is always `true`.
+ known_dimensions_are_definite: Size<bool>,
+}
+
+impl CacheKey {
+ #[inline(always)]
+ #[allow(dead_code)]
+ /// Return the parent size with the extra bits that encode the requested axis masked out
+ fn parent_size(&self) -> u64 {
+ self.parent_size & NON_SIGN_BITS_MASK
+ }
+
+ /// Return the parent size with the extra bits that encode the requested axis masked out
+ /// And the y-axis value masked out
+ fn x_axis_parent_size(&self) -> u64 {
+ self.parent_size & (X_AXIS_VALUE_MASK & NON_SIGN_BITS_MASK)
+ }
+
+ /// Return the bits that encode the requested axis
+ fn requested_axis_bits(&self) -> u64 {
+ self.parent_size & BOTH_SIGN_BITS_MASK
+ }
+
+ /// Whether a cached entry with this key contains a valid size for the axis requested by `other`.
+ /// Sizes computed for a single axis may contain garbage values in the other axis, so an entry
+ /// is only usable if it was computed for the same axis (or for both axes).
+ fn size_is_valid_for(&self, other: &CacheKey) -> bool {
+ let entry_axis = self.requested_axis_bits();
+ entry_axis == BOTH_SIGN_BITS_MASK || entry_axis == other.requested_axis_bits()
+ }
+}
+
+impl From<&LayoutInput> for CacheKey {
+ fn from(input: &LayoutInput) -> Self {
+ // Pack axis enum into spare bits in the known_dimensions and available_space values
+ let extra_bits = match input.axis {
+ RequestedAxis::Horizontal => SIGN_BIT_1,
+ RequestedAxis::Vertical => SIGN_BIT_2,
+ RequestedAxis::Both => SIGN_BIT_1 | SIGN_BIT_2,
+ };
+
+ Self {
+ kd_available_space: size_mixed_cache_key(input.known_dimensions, input.available_space),
+ parent_size: (size_option_cache_key(input.parent_size) & NON_SIGN_BITS_MASK) | extra_bits,
+ known_dimensions_are_definite: input
+ .known_dimensions_are_definite
+ .zip_map(input.known_dimensions, |is_definite, kd| is_definite || kd.is_none()),
+ }
+ }
+}
+
+/// The layout inputs that affect a node's layout but are not part of the [`CacheKey`]: the
+/// [`SizingMode`] and whether each of the node's vertical margins is collapsible, packed into a `u8`.
+///
+/// These are determined by the layout algorithm of the node's parent and by the node's own style,
+/// so they only change for a given node when one of those changes. Rather than keying every entry
+/// on them, a [`Cache`] records the single mode that all of its entries were computed with.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+struct CacheMode(u8);
+
+impl CacheMode {
+ /// Set if the sizing mode is `SizingMode::InherentSize`
+ const INHERENT_SIZE_BIT: u8 = 0b001;
+ /// Set if the node's top margin is collapsible
+ const COLLAPSIBLE_START_MARGIN_BIT: u8 = 0b010;
+ /// Set if the node's bottom margin is collapsible
+ const COLLAPSIBLE_END_MARGIN_BIT: u8 = 0b100;
+
+ /// The mode of a cache that has never been stored to. Which mode this is does not matter,
+ /// as such a cache has no entries.
+ const INITIAL: Self = Self(0);
+}
+
+impl From<&LayoutInput> for CacheMode {
+ #[inline(always)]
+ fn from(input: &LayoutInput) -> Self {
+ let inherent_size = matches!(input.sizing_mode, SizingMode::InherentSize) as u8;
+ let collapsible = input.vertical_margins_are_collapsible;
+ Self(
+ (inherent_size * Self::INHERENT_SIZE_BIT)
+ | (collapsible.start as u8 * Self::COLLAPSIBLE_START_MARGIN_BIT)
+ | (collapsible.end as u8 * Self::COLLAPSIBLE_END_MARGIN_BIT),
+ )
+ }
+}
+
+#[cfg(all(debug_assertions, feature = "std"))]
+std::thread_local! {
+ /// See [`cache_mode_change_evictions`]
+ static MODE_CHANGE_EVICTIONS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
+}
+
+/// The number of times that the current thread has stored a result into a non-empty [`Cache`]
+/// whose entries were computed with a different `sizing_mode` or `vertical_margins_are_collapsible`,
+/// dropping those entries.
+///
+/// This is expected when the layout algorithm of a node's parent has changed since the node was
+/// last laid out. It must not happen while laying out a tree whose caches started out empty: that
+/// would mean that Taffy lays a node out with more than one mode in a single pass, with each
+/// change of mode throwing away the node's cache. Taffy's test suite uses this function to check
+/// that. Only available in debug builds.
+#[doc(hidden)]
+#[cfg(all(debug_assertions, feature = "std"))]
+pub fn cache_mode_change_evictions() -> usize {
+ MODE_CHANGE_EVICTIONS.with(|count| count.get())
+}
+
+/// Cached intermediate layout results
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub(crate) struct CacheEntry<T> {
+ /// The key for the cache entry
+ key: CacheKey,
+ /// The cached size and baselines of the item
+ content: T,
+}
+
+/// A cache for caching the results of a sizing a Grid Item or Flexbox Item
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct Cache {
+ /// The cache entry for the node's final layout
+ final_layout_entry: Option<CacheEntry<LayoutOutput>>,
+ /// The cache entries for the node's preliminary size measurements
+ measure_entries: [Option<CacheEntry<Size<f32>>>; CACHE_SIZE],
+ /// Tracks which measure entries have been used since the eviction cursor last passed them
+ recently_used_entries: u16,
+ /// The next measure entry to consider replacing
+ next_measure_entry: u8,
+ /// Tracks if all cache entries are empty
+ is_empty: bool,
+ /// The `sizing_mode` and `vertical_margins_are_collapsible` inputs that all of the cache's
+ /// entries were computed with. Results are only retrieved for inputs that have the same mode,
+ /// and storing a result that was computed with a different mode drops the existing entries.
+ mode: CacheMode,
+}
+
+impl Default for Cache {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Cache {
+ /// Create a new empty cache
+ pub const fn new() -> Self {
+ /// Workaround for `Option<CacheEntry<_>>` not being `Copy` (required for array repeat expressions)
+ const NONE_MEASURE_ENTRY: Option<CacheEntry<Size<f32>>> = None;
+ Self {
+ final_layout_entry: None,
+ measure_entries: [NONE_MEASURE_ENTRY; CACHE_SIZE],
+ recently_used_entries: 0,
+ next_measure_entry: 0,
+ is_empty: true,
+ mode: CacheMode::INITIAL,
+ }
+ }
+
+ /// Try to retrieve a cached result from the cache
+ #[inline]
+ pub fn get(&mut self, input: &LayoutInput) -> Option<LayoutOutput> {
+ if self.mode != CacheMode::from(input) {
+ return None;
+ }
+ let key = CacheKey::from(input);
+ match input.run_mode {
+ RunMode::PerformLayout => {
+ self.final_layout_entry.as_ref().filter(|entry| entry.key == key).map(|e| e.content.clone())
+ }
+ RunMode::ComputeSize => {
+ for (index, entry) in self.measure_entries.iter().enumerate() {
+ let Some(entry) = entry else { continue };
+ if entry.key.kd_available_space == key.kd_available_space
+ && entry.key.known_dimensions_are_definite == key.known_dimensions_are_definite
+ && (entry.key.x_axis_parent_size() == key.x_axis_parent_size())
+ && entry.key.size_is_valid_for(&key)
+ {
+ self.recently_used_entries |= 1 << index;
+ return Some(LayoutOutput::from_outer_size(entry.content));
+ }
+ }
+
+ None
+ }
+ RunMode::PerformHiddenLayout => None,
+ }
+ }
+
+ /// Store a computed size in the cache
+ pub fn store(&mut self, input: &LayoutInput, layout_output: LayoutOutput) {
+ if input.run_mode == RunMode::PerformHiddenLayout {
+ return;
+ }
+ let mode = CacheMode::from(input);
+ if self.mode != mode {
+ #[cfg(all(debug_assertions, feature = "std"))]
+ if !self.is_empty {
+ MODE_CHANGE_EVICTIONS.with(|count| count.set(count.get() + 1));
+ }
+ self.clear();
+ self.mode = mode;
+ }
+ let key = CacheKey::from(input);
+ match input.run_mode {
+ RunMode::PerformLayout => {
+ self.is_empty = false;
+ self.final_layout_entry = Some(CacheEntry { key, content: layout_output })
+ }
+ RunMode::ComputeSize => {
+ // Measure entries only store the size, and cache hits are reconstructed with
+ // `LayoutOutput::from_outer_size`, which resets the margin-collapse metadata
+ // (`top_margin`, `bottom_margin`, `margins_can_collapse_through`). Results that
+ // carry such metadata cannot be reconstructed from their size, so don't cache them.
+ if layout_output.margins_can_collapse_through
+ || layout_output.top_margin != CollapsibleMarginSet::ZERO
+ || layout_output.bottom_margin != CollapsibleMarginSet::ZERO
+ {
+ return;
+ }
+ self.is_empty = false;
+ if let Some(index) =
+ self.measure_entries.iter().position(|entry| entry.as_ref().is_some_and(|entry| entry.key == key))
+ {
+ self.measure_entries[index].as_mut().unwrap().content = layout_output.size;
+ self.recently_used_entries |= 1 << index;
+ return;
+ }
+ while self.recently_used_entries & (1 << self.next_measure_entry) != 0 {
+ self.recently_used_entries &= !(1 << self.next_measure_entry);
+ self.next_measure_entry += 1;
+ if self.next_measure_entry == CACHE_SIZE as u8 {
+ self.next_measure_entry = 0;
+ }
+ }
+ let entry_index = self.next_measure_entry as usize;
+ self.measure_entries[entry_index] = Some(CacheEntry { key, content: layout_output.size });
+ self.recently_used_entries |= 1 << entry_index;
+ self.next_measure_entry += 1;
+ if self.next_measure_entry == CACHE_SIZE as u8 {
+ self.next_measure_entry = 0;
+ }
+ }
+ RunMode::PerformHiddenLayout => {}
+ }
+ }
+
+ /// Clear all cache entries and reports clear operation outcome ([`ClearState`])
+ pub fn clear(&mut self) -> ClearState {
+ if self.is_empty {
+ return ClearState::AlreadyEmpty;
+ }
+ self.is_empty = true;
+ self.final_layout_entry = None;
+ /// Workaround for `Option<CacheEntry<_>>` not being `Copy` (required for array repeat expressions)
+ const NONE_MEASURE_ENTRY: Option<CacheEntry<Size<f32>>> = None;
+ self.measure_entries = [NONE_MEASURE_ENTRY; CACHE_SIZE];
+ self.recently_used_entries = 0;
+ self.next_measure_entry = 0;
+ ClearState::Cleared
+ }
+
+ /// Returns true if all cache entries are None, else false
+ pub fn is_empty(&self) -> bool {
+ self.final_layout_entry.is_none() && !self.measure_entries.iter().any(|entry| entry.is_some())
+ }
+}
+
+/// Clear operation outcome. See [`Cache::clear`]
+pub enum ClearState {
+ /// Cleared some values
+ Cleared,
+ /// Everything was already cleared
+ AlreadyEmpty,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::geometry::Line;
+ use crate::tree::SizingMode;
+
+ fn input(width: f32) -> LayoutInput {
+ LayoutInput {
+ run_mode: RunMode::ComputeSize,
+ sizing_mode: SizingMode::InherentSize,
+ axis: RequestedAxis::Both,
+ known_dimensions: Size { width: Some(width), height: None },
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size: Size::NONE,
+ available_space: Size { width: AvailableSpace::MaxContent, height: AvailableSpace::MaxContent },
+ vertical_margins_are_collapsible: Line::FALSE,
+ }
+ }
+
+ fn output(width: f32) -> LayoutOutput {
+ LayoutOutput::from_outer_size(Size { width, height: width })
+ }
+
+ #[test]
+ fn recently_used_measure_entries_get_a_second_chance() {
+ let mut cache = Cache::new();
+ for width in 0..CACHE_SIZE {
+ cache.store(&input(width as f32), output(width as f32));
+ }
+ cache.store(&input(CACHE_SIZE as f32), output(CACHE_SIZE as f32));
+
+ assert_eq!(cache.get(&input(1.0)), Some(output(1.0)));
+ cache.store(&input((CACHE_SIZE + 1) as f32), output((CACHE_SIZE + 1) as f32));
+
+ assert_eq!(cache.get(&input(1.0)), Some(output(1.0)));
+ assert_eq!(cache.get(&input(2.0)), None);
+ }
+
+ #[test]
+ fn storing_an_existing_measurement_updates_it_in_place() {
+ let mut cache = Cache::new();
+ cache.store(&input(1.0), output(1.0));
+ cache.store(&input(2.0), output(2.0));
+ cache.store(&input(1.0), output(3.0));
+
+ assert_eq!(cache.measure_entries.iter().flatten().count(), 2);
+ assert_eq!(cache.get(&input(1.0)), Some(output(3.0)));
+ }
+
+ #[test]
+ fn measurements_with_margin_collapse_metadata_are_not_cached() {
+ let mut cache = Cache::new();
+
+ let mut collapse_through = output(1.0);
+ collapse_through.margins_can_collapse_through = true;
+ cache.store(&input(1.0), collapse_through);
+ assert_eq!(cache.get(&input(1.0)), None);
+
+ let mut carried_margin = output(2.0);
+ carried_margin.top_margin = CollapsibleMarginSet::from_margin(10.0);
+ cache.store(&input(2.0), carried_margin);
+ assert_eq!(cache.get(&input(2.0)), None);
+ }
+
+ #[test]
+ fn retrieving_a_measurement_only_marks_its_slot_as_used() {
+ let mut cache = Cache::new();
+ cache.store(&input(1.0), output(1.0));
+ cache.store(&input(2.0), output(2.0));
+ cache.recently_used_entries = 0;
+ let entries = cache.measure_entries.clone();
+
+ assert_eq!(cache.get(&input(1.0)), Some(output(1.0)));
+ assert_eq!(cache.measure_entries, entries);
+ assert_ne!(cache.recently_used_entries, 0);
+ }
+
+ fn perform_layout_input(width: f32, height: f32) -> LayoutInput {
+ LayoutInput {
+ run_mode: RunMode::PerformLayout,
+ known_dimensions: Size { width: Some(width), height: Some(height) },
+ parent_size: Size { width: Some(width), height: Some(height) },
+ ..input(width)
+ }
+ }
+
+ /// Inputs that differ from `input`/`perform_layout_input` only in their mode
+ fn other_modes(input: LayoutInput) -> [LayoutInput; 4] {
+ [
+ LayoutInput { sizing_mode: SizingMode::ContentSize, ..input },
+ LayoutInput { vertical_margins_are_collapsible: Line::TRUE, ..input },
+ LayoutInput { vertical_margins_are_collapsible: Line { start: true, end: false }, ..input },
+ LayoutInput { vertical_margins_are_collapsible: Line { start: false, end: true }, ..input },
+ ]
+ }
+
+ #[test]
+ fn cache_mode_distinguishes_every_combination_of_inputs() {
+ let mut modes = [CacheMode::INITIAL; 8];
+ for (index, mode) in modes.iter_mut().enumerate() {
+ *mode = CacheMode::from(&LayoutInput {
+ sizing_mode: if index & 1 == 0 { SizingMode::ContentSize } else { SizingMode::InherentSize },
+ vertical_margins_are_collapsible: Line { start: index & 2 != 0, end: index & 4 != 0 },
+ ..input(1.0)
+ });
+ }
+ for (index, mode) in modes.iter().enumerate() {
+ assert!(!modes[..index].contains(mode));
+ }
+ }
+
+ #[test]
+ fn retrieving_with_a_different_mode_misses_and_keeps_the_entries() {
+ let mut cache = Cache::new();
+ cache.store(&perform_layout_input(100.0, 50.0), output(1.0));
+ cache.store(&input(1.0), output(2.0));
+
+ for other in other_modes(perform_layout_input(100.0, 50.0)) {
+ assert_eq!(cache.get(&other), None);
+ }
+ for other in other_modes(input(1.0)) {
+ assert_eq!(cache.get(&other), None);
+ }
+
+ assert_eq!(cache.get(&perform_layout_input(100.0, 50.0)), Some(output(1.0)));
+ assert_eq!(cache.get(&input(1.0)), Some(output(2.0)));
+ }
+
+ #[test]
+ fn storing_with_a_different_mode_drops_the_existing_entries() {
+ for other in other_modes(input(3.0)) {
+ let mut cache = Cache::new();
+ cache.store(&perform_layout_input(100.0, 50.0), output(1.0));
+ cache.store(&input(1.0), output(2.0));
+
+ cache.store(&other, output(3.0));
+ assert_eq!(cache.get(&other), Some(output(3.0)));
+ assert!(cache.final_layout_entry.is_none());
+ assert_eq!(cache.measure_entries.iter().flatten().count(), 1);
+
+ // The old entries are gone, even for inputs that have the mode that the cache had before
+ cache.store(&input(4.0), output(4.0));
+ assert_eq!(cache.get(&perform_layout_input(100.0, 50.0)), None);
+ assert_eq!(cache.get(&input(1.0)), None);
+ assert_eq!(cache.get(&other), None);
+ assert_eq!(cache.get(&input(4.0)), Some(output(4.0)));
+ }
+
+ for other in other_modes(perform_layout_input(100.0, 50.0)) {
+ let mut cache = Cache::new();
+ cache.store(&perform_layout_input(100.0, 50.0), output(1.0));
+ cache.store(&input(1.0), output(2.0));
+
+ cache.store(&other, output(3.0));
+ assert_eq!(cache.get(&other), Some(output(3.0)));
+ assert!(cache.measure_entries.iter().all(|entry| entry.is_none()));
+ assert_eq!(cache.get(&perform_layout_input(100.0, 50.0)), None);
+ }
+ }
+
+ #[test]
+ fn hidden_layouts_do_not_affect_the_cache() {
+ let mut cache = Cache::new();
+ cache.store(&input(1.0), output(1.0));
+ cache.store(&LayoutInput::HIDDEN, output(2.0));
+ assert_eq!(cache.get(&input(1.0)), Some(output(1.0)));
+ }
+
+ #[test]
+ #[cfg(all(debug_assertions, feature = "std"))]
+ fn mode_change_evictions_are_counted_for_non_empty_caches_only() {
+ let content_size = LayoutInput { sizing_mode: SizingMode::ContentSize, ..input(1.0) };
+ let evictions = cache_mode_change_evictions();
+
+ let mut cache = Cache::new();
+ cache.store(&content_size, output(1.0));
+ cache.store(&LayoutInput { sizing_mode: SizingMode::ContentSize, ..input(2.0) }, output(2.0));
+ assert_eq!(cache_mode_change_evictions(), evictions);
+
+ cache.store(&input(1.0), output(1.0));
+ assert_eq!(cache_mode_change_evictions(), evictions + 1);
+
+ cache.clear();
+ cache.store(&content_size, output(1.0));
+ assert_eq!(cache_mode_change_evictions(), evictions + 1);
+ }
+}
diff --git a/vendor/taffy/src/tree/layout.rs b/vendor/taffy/src/tree/layout.rs
new file mode 100644
index 00000000..bb175dde
--- /dev/null
+++ b/vendor/taffy/src/tree/layout.rs
@@ -0,0 +1,728 @@
+//! Final data structures that represent the high-level UI layout
+use crate::geometry::{AbsoluteAxis, Line, Point, Rect, Size};
+use crate::style::{AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace, CheapCloneStr, Position};
+use crate::style_helpers::TaffyMaxContent;
+use crate::sys::DefaultCheapStr;
+use crate::tree::NodeId;
+use crate::util::sys::{f32_max, f32_min};
+
+/// Whether we are performing a full layout, or we merely need to size the node
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub enum RunMode {
+ /// A full layout for this node and all children should be computed
+ PerformLayout,
+ /// The layout algorithm should be executed such that an accurate container size for the node can be determined.
+ /// Layout steps that aren't necessary for determining the container size of the current node can be skipped.
+ ComputeSize,
+ /// This node should have a null layout set as it has been hidden (i.e. using `Display::None`)
+ PerformHiddenLayout,
+}
+
+/// Whether styles should be taken into account when computing size
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub enum SizingMode {
+ /// Only content contributions should be taken into account
+ ContentSize,
+ /// Inherent size styles should be taken into account in addition to content contributions
+ InherentSize,
+}
+
+/// A set of margins that are available for collapsing with for block layout's margin collapsing
+#[derive(Copy, Clone, Debug, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct CollapsibleMarginSet {
+ /// The largest positive margin
+ positive: f32,
+ /// The smallest negative margin (with largest absolute value)
+ negative: f32,
+}
+
+impl CollapsibleMarginSet {
+ /// A default margin set with no collapsible margins
+ pub const ZERO: Self = Self { positive: 0.0, negative: 0.0 };
+
+ /// Create a set from a single margin
+ pub fn from_margin(margin: f32) -> Self {
+ if margin >= 0.0 {
+ Self { positive: margin, negative: 0.0 }
+ } else {
+ Self { positive: 0.0, negative: margin }
+ }
+ }
+
+ /// Collapse a single margin with this set
+ pub fn collapse_with_margin(mut self, margin: f32) -> Self {
+ if margin >= 0.0 {
+ self.positive = f32_max(self.positive, margin);
+ } else {
+ self.negative = f32_min(self.negative, margin);
+ }
+ self
+ }
+
+ /// Collapse another margin set with this set
+ pub fn collapse_with_set(mut self, other: CollapsibleMarginSet) -> Self {
+ self.positive = f32_max(self.positive, other.positive);
+ self.negative = f32_min(self.negative, other.negative);
+ self
+ }
+
+ /// Resolve the resultant margin from this set once all collapsible margins
+ /// have been collapsed into it
+ pub fn resolve(&self) -> f32 {
+ self.positive + self.negative
+ }
+}
+
+/// An axis that layout algorithms can be requested to compute a size for
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub enum RequestedAxis {
+ /// The horizontal axis
+ Horizontal,
+ /// The vertical axis
+ Vertical,
+ /// Both axes
+ Both,
+}
+
+impl RequestedAxis {
+ /// Swap the horizontal and vertical axes (`Both` is unchanged)
+ #[inline(always)]
+ pub fn transpose(self) -> RequestedAxis {
+ match self {
+ RequestedAxis::Horizontal => RequestedAxis::Vertical,
+ RequestedAxis::Vertical => RequestedAxis::Horizontal,
+ RequestedAxis::Both => RequestedAxis::Both,
+ }
+ }
+}
+
+impl From<AbsoluteAxis> for RequestedAxis {
+ fn from(value: AbsoluteAxis) -> Self {
+ match value {
+ AbsoluteAxis::Horizontal => RequestedAxis::Horizontal,
+ AbsoluteAxis::Vertical => RequestedAxis::Vertical,
+ }
+ }
+}
+impl TryFrom<RequestedAxis> for AbsoluteAxis {
+ type Error = ();
+ fn try_from(value: RequestedAxis) -> Result<Self, Self::Error> {
+ match value {
+ RequestedAxis::Horizontal => Ok(AbsoluteAxis::Horizontal),
+ RequestedAxis::Vertical => Ok(AbsoluteAxis::Vertical),
+ RequestedAxis::Both => Err(()),
+ }
+ }
+}
+
+/// A struct containing the inputs constraints/hints for laying out a node, which are passed in by the parent
+#[derive(Debug, Copy, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct LayoutInput {
+ /// Whether we only need to know the Node's size, or whether we need to perform a full layout
+ pub run_mode: RunMode,
+ /// Whether a Node's style sizes should be taken into account or ignored
+ pub sizing_mode: SizingMode,
+ /// Which axis we need the size of
+ pub axis: RequestedAxis,
+
+ /// Known dimensions represent dimensions (width/height) which should be taken as fixed when performing layout.
+ /// For example, if known_dimensions.width is set to Some(WIDTH) then this means something like:
+ ///
+ /// "What would the height of this node be, assuming the width is WIDTH"
+ ///
+ /// Layout functions will be called with both known_dimensions set for final layout. Where the meaning is:
+ ///
+ /// "The exact size of this node is WIDTHxHEIGHT. Please lay out your children"
+ ///
+ pub known_dimensions: Size<Option<f32>>,
+ /// Whether each known dimension should be treated as a *definite* size when laying out the node's
+ /// own content (resolving percentage sizes of children, and collecting flex items into flex lines).
+ ///
+ /// This should be set to `false` for a dimension when a parent imposes a known dimension on a node
+ /// that is derived from the node's own content, and is therefore indefinite per CSS. For example,
+ /// the post-flexing main size of a flex item is indefinite if the flex container's main size is
+ /// indefinite and the item's used flex basis is not definite
+ /// (see <https://www.w3.org/TR/css-flexbox-1/#definite-sizes>).
+ ///
+ /// This flag is ignored (treated as `true`) for axes where the corresponding known dimension is `None`.
+ pub known_dimensions_are_definite: Size<bool>,
+ /// Parent size dimensions are intended to be used for percentage resolution.
+ pub parent_size: Size<Option<f32>>,
+ /// Available space represents an amount of space to layout into, and is used as a soft constraint
+ /// for the purpose of wrapping.
+ ///
+ /// A definite available space is the space available to the node's border box: the parent
+ /// subtracts the node's margins before passing it, and the node must not subtract them again.
+ pub available_space: Size<AvailableSpace>,
+ /// Specific to CSS Block layout. Used for correctly computing margin collapsing. You probably want to set this to `Line::FALSE`.
+ pub vertical_margins_are_collapsible: Line<bool>,
+}
+
+impl LayoutInput {
+ /// A LayoutInput that can be used to request hidden layout
+ pub const HIDDEN: LayoutInput = LayoutInput {
+ // The important property for hidden layout
+ run_mode: RunMode::PerformHiddenLayout,
+ // The rest will be ignored
+ known_dimensions: Size::NONE,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size: Size::NONE,
+ available_space: Size::MAX_CONTENT,
+ sizing_mode: SizingMode::InherentSize,
+ axis: RequestedAxis::Both,
+ vertical_margins_are_collapsible: Line::FALSE,
+ };
+
+ /// Swap the horizontal and vertical axes of every per-axis input.
+ ///
+ /// Lets a tree lay out a node in a vertical writing mode: transpose the inputs, run the
+ /// (horizontal-tb) algorithm, then transpose the [`LayoutOutput`] back.
+ /// `vertical_margins_are_collapsible` is reset to `Line::FALSE` as margins cannot collapse
+ /// across a change of block axis.
+ pub fn transpose(self) -> LayoutInput {
+ LayoutInput {
+ run_mode: self.run_mode,
+ sizing_mode: self.sizing_mode,
+ axis: self.axis.transpose(),
+ known_dimensions: self.known_dimensions.transpose(),
+ known_dimensions_are_definite: self.known_dimensions_are_definite.transpose(),
+ parent_size: self.parent_size.transpose(),
+ available_space: self.available_space.transpose(),
+ vertical_margins_are_collapsible: Line::FALSE,
+ }
+ }
+}
+
+/// The first and last baselines of a node in the horizontal axis (i.e. baselines for horizontal text,
+/// measured as an offset from the top edge of the node's border box).
+///
+/// A baseline is the line on which text sits. See <https://www.w3.org/TR/css-writing-modes-3/#intro-baselines>
+/// for details.
+#[derive(Debug, Copy, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct Baselines {
+ /// The first baseline of the node, if any
+ pub first: Option<f32>,
+ /// The last baseline of the node, if any
+ pub last: Option<f32>,
+}
+
+impl Baselines {
+ /// A `Baselines` with neither a first nor a last baseline
+ pub const NONE: Self = Self { first: None, last: None };
+
+ /// Create a `Baselines` from just a first baseline
+ pub const fn from_first(first: Option<f32>) -> Self {
+ Self { first, last: None }
+ }
+}
+
+/// The physical alignment of an out-of-flow box's margin box within its static-position
+/// area (per-axis).
+///
+/// The static position of an out-of-flow box may depend on alignment properties
+/// (`justify-content`/`align-self` in flexbox, `justify-self`/`align-self` in grid) which cannot
+/// be fully resolved until the box's final size is known. To defer that resolution, the static
+/// position is recorded as an *area* plus the physical alignment keyword to apply to the box's
+/// margin box within that area.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum AxisStaticEdge {
+ /// Align the start (left/top) edge of the box's margin box to the start of the area
+ Start,
+ /// Center the box within the area
+ Center,
+ /// Align the end (right/bottom) edge of the box's margin box to the end of the area
+ End,
+}
+
+/// The alignment to apply to an out-of-flow box's margin box within its static-position area
+/// in a single axis.
+///
+/// Keywords are physical: container-specific semantics (`justify-content`/`align-self`
+/// resolution, flex-direction/wrap-reverse reversal, RTL flipping, `self-start`/`self-end`)
+/// are resolved by the emitting layout algorithm.
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub struct AxisStaticAlign {
+ /// The physical alignment keyword
+ pub keyword: AxisStaticEdge,
+ /// The `safe` overflow-position keyword from CSS Box Alignment: when `Safe`, the
+ /// `fallback` keyword is used instead if the box's margin box overflows the area
+ pub safety: AlignmentSafety,
+ /// The physical alignment keyword to fall back to when `safety` is `Safe` and the box's
+ /// margin box overflows the area
+ pub fallback: AxisStaticEdge,
+}
+
+impl AxisStaticAlign {
+ /// Create a `AxisStaticAlign` from a keyword with no safe fallback
+ pub const fn from_keyword(keyword: AxisStaticEdge) -> Self {
+ Self { keyword, safety: AlignmentSafety::Default, fallback: keyword }
+ }
+}
+
+/// The static position of an out-of-flow box in a single axis: the alignment container
+/// (start/end coordinates) plus the alignment to apply to the box's margin box within it.
+///
+/// Area coordinates are initially relative to the border box of the node which produced the
+/// candidate and are translated by each node's location as the candidate bubbles up the tree, so
+/// they are always relative to the border box of the node currently holding the candidate.
+///
+/// Emitters which have no alignment area in an axis (e.g. block layout, where the static
+/// position is a point) emit a degenerate area (`start == end`).
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub struct AxisStaticPosition {
+ /// The alignment container in this axis
+ pub area: Line<f32>,
+ /// The alignment to apply to the box's margin box within `area`
+ pub align: AxisStaticAlign,
+}
+
+impl AxisStaticPosition {
+ /// Create a `AxisStaticPosition` with a degenerate (zero-extent) area at `anchor` and no
+ /// safe fallback
+ pub const fn from_edge(anchor: f32, edge: AxisStaticEdge) -> Self {
+ Self { area: Line { start: anchor, end: anchor }, align: AxisStaticAlign::from_keyword(edge) }
+ }
+
+ /// Create a `AxisStaticPosition` which aligns the box within `area` according to its
+ /// self-alignment property in this axis (`justify-self` in the inline axis, `align-self` in
+ /// the block axis). `normal` and `stretch` behave as `start`. This is the static position
+ /// used by block and inline layout.
+ ///
+ /// `alignment` must already be resolved: `auto` (`None`) replaced by the container's
+ /// `justify-items`/`align-items`, and `self-start`/`self-end` resolved against the
+ /// container's direction (see [`AlignSelf::resolve_self_relative`]).
+ /// `axis_is_rtl` is whether this axis is the inline axis of a right-to-left static-position
+ /// containing block, in which case `start` and `end` are flipped.
+ pub fn from_alignment(alignment: AlignSelf, area: Line<f32>, axis_is_rtl: bool) -> Self {
+ debug_assert!(
+ !matches!(alignment.keyword, AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd),
+ "self-start/self-end must be resolved before computing the static position"
+ );
+ /// The edge of the static-position rectangle that a (resolved) alignment keyword
+ /// aligns the box to. Normal and Stretch (and anything else that is not an end or
+ /// center alignment) fall back to start-alignment for static-position purposes.
+ fn edge_for(keyword: AlignItemsKeyword, axis_is_rtl: bool) -> AxisStaticEdge {
+ let start_position = !matches!(keyword, AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd) ^ axis_is_rtl;
+ match keyword {
+ AlignItemsKeyword::Center => AxisStaticEdge::Center,
+ _ if start_position => AxisStaticEdge::Start,
+ _ => AxisStaticEdge::End,
+ }
+ }
+ let fallback = if matches!(alignment.safety, AlignmentSafety::Safe) {
+ AlignItemsKeyword::Start
+ } else {
+ alignment.keyword
+ };
+ Self {
+ area,
+ align: AxisStaticAlign {
+ keyword: edge_for(alignment.keyword, axis_is_rtl),
+ safety: alignment.safety,
+ fallback: edge_for(fallback, axis_is_rtl),
+ },
+ }
+ }
+}
+
+/// A record of an out-of-flow (`position: absolute` or `position: fixed`) box which has not yet
+/// been laid out because its containing block is an ancestor of its parent.
+///
+/// Candidates are produced by the layout algorithm of the box's parent (which computes the static
+/// position) and bubble up through `LayoutOutput` until they reach a node which acts as the box's
+/// containing block, which lays the box out.
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub struct OofCandidate {
+ /// The id of the out-of-flow node
+ pub node: NodeId,
+ /// The `order` value that the node's layout should be assigned (its child index within its parent)
+ pub order: u32,
+ /// The position style of the node (`Position::Absolute` or `Position::Fixed`)
+ pub position: Position,
+ /// The static position of the box in each axis
+ pub static_position: Point<AxisStaticPosition>,
+}
+
+/// A list of [`OofCandidate`]s.
+///
+/// This is a lazily-allocated heap vector (an empty list performs no allocation).
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct OofCandidates {
+ /// Backing storage for the candidates
+ inner: Option<crate::util::sys::Box<crate::util::sys::Vec<OofCandidate>>>,
+}
+
+impl OofCandidates {
+ /// An empty list of candidates
+ pub const NONE: Self = Self { inner: None };
+
+ /// Create a new empty list of candidates
+ pub const fn new() -> Self {
+ Self::NONE
+ }
+
+ /// Whether the list contains no candidates
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.as_slice().is_empty()
+ }
+
+ /// The candidates as a slice
+ #[inline]
+ pub fn as_slice(&self) -> &[OofCandidate] {
+ self.inner.as_ref().map(|boxed| boxed.as_slice()).unwrap_or(&[])
+ }
+
+ /// The candidates as a mutable slice
+ #[inline]
+ pub fn as_mut_slice(&mut self) -> &mut [OofCandidate] {
+ self.inner.as_mut().map(|boxed| boxed.as_mut_slice()).unwrap_or(&mut [])
+ }
+
+ /// Append a candidate to the list
+ #[inline]
+ pub fn push(&mut self, candidate: OofCandidate) {
+ self.inner.get_or_insert_with(Default::default).push(candidate);
+ }
+
+ /// Move all candidates from `other` into `self`, leaving `other` empty
+ #[inline]
+ pub fn append(&mut self, other: &mut OofCandidates) {
+ if other.is_empty() {
+ return;
+ }
+ match &mut self.inner {
+ None => self.inner = other.inner.take(),
+ Some(vec) => vec.append(other.inner.as_mut().unwrap()),
+ }
+ }
+
+ /// Take the candidates out of this list, leaving it empty
+ #[inline]
+ pub fn take(&mut self) -> Self {
+ core::mem::take(self)
+ }
+
+ /// Remove all candidates from the list
+ #[inline]
+ pub fn clear(&mut self) {
+ self.inner = None;
+ }
+
+ /// Iterate over the candidates
+ #[inline]
+ pub fn iter(&self) -> core::slice::Iter<'_, OofCandidate> {
+ self.as_slice().iter()
+ }
+
+ /// Translate the static-position areas of every candidate in the list by `offset`.
+ ///
+ /// This is used to convert areas from being relative to a child node's border box to being
+ /// relative to the parent node's border box as candidates bubble up the tree.
+ #[inline]
+ pub fn translate(&mut self, offset: Point<f32>) {
+ for candidate in self.as_mut_slice() {
+ candidate.static_position.x.area.start += offset.x;
+ candidate.static_position.x.area.end += offset.x;
+ candidate.static_position.y.area.start += offset.y;
+ candidate.static_position.y.area.end += offset.y;
+ }
+ }
+}
+
+impl<'a> IntoIterator for &'a OofCandidates {
+ type Item = &'a OofCandidate;
+ type IntoIter = core::slice::Iter<'a, OofCandidate>;
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+/// The area of a container against which the insets of its out-of-flow (absolute/fixed) boxes
+/// are resolved: the container's border box minus its borders and scrollbar gutters.
+///
+/// Container layout algorithms record this on [`LayoutOutput`] (for `RunMode::PerformLayout` runs)
+/// so that the out-of-flow positioning pass ([`compute_oof_layout`](crate::compute_oof_layout))
+/// can run after the algorithm has finished. When the container is a grid, per-box grid areas are
+/// resolved within this area by the positioning pass itself (from the container's detailed grid
+/// info).
+#[derive(Debug, Copy, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct OofPositioningArea {
+ /// The size of the area
+ pub size: Size<f32>,
+ /// The offset of the area from the container's border box origin
+ pub offset: Point<f32>,
+}
+
+/// A struct containing the result of laying a single node, which is returned up to the parent node
+///
+/// A baseline is the line on which text sits. Your node likely has a baseline if it is a text node, or contains
+/// children that may be text nodes. See <https://www.w3.org/TR/css-writing-modes-3/#intro-baselines> for details.
+/// If your node does not have a baseline (or you are unsure how to compute it), then simply return `Baselines::NONE`
+/// for the baselines field
+#[derive(Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct LayoutOutput {
+ /// The size of the node
+ pub size: Size<f32>,
+ #[cfg(feature = "content_size")]
+ /// The scrollable overflow rectangle of the node's content
+ /// (see [`Layout::scrollable_overflow_rect`] for the coordinate conventions)
+ pub scrollable_overflow_rect: Rect<f32>,
+ /// The first and last baselines of the node in the horizontal axis, if any
+ pub baselines: Baselines,
+ /// Top margin that can be collapsed with. This is used for CSS block layout and can be set to
+ /// `CollapsibleMarginSet::ZERO` for other layout modes that don't support margin collapsing
+ pub top_margin: CollapsibleMarginSet,
+ /// Bottom margin that can be collapsed with. This is used for CSS block layout and can be set to
+ /// `CollapsibleMarginSet::ZERO` for other layout modes that don't support margin collapsing
+ pub bottom_margin: CollapsibleMarginSet,
+ /// Whether margins can be collapsed through this node. This is used for CSS block layout and can
+ /// be set to `false` for other layout modes that don't support margin collapsing
+ pub margins_can_collapse_through: bool,
+ /// Out-of-flow (absolute/fixed) descendants of this node for which this node is *not* the
+ /// containing block. These bubble up the tree until they reach their containing block, which
+ /// lays them out. Empty (allocation-free) when there are no such descendants (the common case).
+ ///
+ /// Candidates are only produced by `RunMode::PerformLayout` passes.
+ ///
+ /// Container layout algorithms place the *full* document-ordered candidate list here (direct
+ /// out-of-flow children plus candidates bubbled from in-flow children). The out-of-flow
+ /// positioning pass ([`compute_oof_layout`](crate::compute_oof_layout)) then lays out those
+ /// for which the node is the containing block and replaces this list with the unclaimed
+ /// remainder.
+ #[cfg_attr(feature = "serde", serde(skip_serializing))]
+ pub oof_candidates: OofCandidates,
+ /// The node's inset-resolution area for out-of-flow boxes. Set by container layout
+ /// algorithms for `RunMode::PerformLayout` runs; `None` for leaves and size-only runs
+ /// (in which case the out-of-flow positioning pass is a no-op).
+ pub oof_positioning_area: Option<OofPositioningArea>,
+}
+
+impl LayoutOutput {
+ /// An all-zero `LayoutOutput` for hidden nodes
+ pub const HIDDEN: Self = Self {
+ size: Size::ZERO,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: Rect::ZERO,
+ baselines: Baselines::NONE,
+ top_margin: CollapsibleMarginSet::ZERO,
+ bottom_margin: CollapsibleMarginSet::ZERO,
+ margins_can_collapse_through: false,
+ oof_candidates: OofCandidates::NONE,
+ oof_positioning_area: None,
+ };
+
+ /// A blank layout output
+ pub const DEFAULT: Self = Self::HIDDEN;
+
+ /// Constructor to create a `LayoutOutput` from just the size, scrollable overflow rectangle and baselines
+ pub fn from_sizes_and_baselines(
+ size: Size<f32>,
+ #[cfg_attr(not(feature = "content_size"), allow(unused_variables))] scrollable_overflow_rect: Rect<f32>,
+ baselines: Baselines,
+ ) -> Self {
+ Self {
+ size,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect,
+ baselines,
+ top_margin: CollapsibleMarginSet::ZERO,
+ bottom_margin: CollapsibleMarginSet::ZERO,
+ margins_can_collapse_through: false,
+ oof_candidates: OofCandidates::NONE,
+ oof_positioning_area: None,
+ }
+ }
+
+ /// Construct a `LayoutOutput` from just the container size and scrollable overflow rectangle
+ pub fn from_sizes(size: Size<f32>, scrollable_overflow_rect: Rect<f32>) -> Self {
+ Self::from_sizes_and_baselines(size, scrollable_overflow_rect, Baselines::NONE)
+ }
+
+ /// Swap the horizontal and vertical axes of the output (inverse of [`LayoutInput::transpose`]).
+ ///
+ /// Baselines and collapsible margins are block-axis quantities that have no meaning on the
+ /// parent's inline axis, so they are dropped. Out-of-flow candidates are unaffected.
+ pub fn transpose(self) -> Self {
+ Self {
+ size: self.size.transpose(),
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: self.scrollable_overflow_rect.transpose(),
+ baselines: Baselines::NONE,
+ top_margin: CollapsibleMarginSet::ZERO,
+ bottom_margin: CollapsibleMarginSet::ZERO,
+ margins_can_collapse_through: false,
+ oof_candidates: self.oof_candidates,
+ oof_positioning_area: self
+ .oof_positioning_area
+ .map(|area| OofPositioningArea { size: area.size.transpose(), offset: area.offset.transpose() }),
+ }
+ }
+
+ /// Construct a `LayoutOutput` from just the container's size.
+ pub fn from_outer_size(size: Size<f32>) -> Self {
+ Self::from_sizes(size, Rect::ZERO)
+ }
+}
+
+/// The final result of a layout algorithm for a single node.
+#[derive(Debug, Copy, Clone, PartialEq)]
+#[cfg_attr(feature = "serde", derive(Serialize))]
+pub struct Layout {
+ /// The relative ordering of the node
+ ///
+ /// Nodes with a higher order should be rendered on top of those with a lower order.
+ /// This is effectively a topological sort of each tree.
+ pub order: u32,
+ /// The top-left corner of the node
+ pub location: Point<f32>,
+ /// The width and height of the node
+ pub size: Size<f32>,
+ #[cfg(feature = "content_size")]
+ /// The scrollable overflow rectangle of the node: the axis-aligned rectangle containing the
+ /// content of the node (the border boxes of its descendants plus their non-clipped overflow),
+ /// corresponding to the CSS "scrollable overflow rectangle"
+ /// (<https://www.w3.org/TR/css-overflow-3/#scrollable>), except that transforms are not
+ /// accounted for.
+ ///
+ /// Coordinates are measured from the node's *scroll origin*: the corner of the padding box at
+ /// the block-start/inline-start edge (the top-left corner in LTR, the top-*right* corner in
+ /// RTL), with `left`/`right` measuring along the inline axis in the direction of reachable
+ /// scrolling. The rectangle always contains the origin, so `left`/`top` are `<= 0.0` (negative
+ /// values represent overflow before the scroll origin, which is unreachable by scrolling) and
+ /// `right`/`bottom` are `>= 0.0` (representing the reachable extent of the content, which is
+ /// useful for computing a "scroll width/height" for scrollable nodes).
+ pub scrollable_overflow_rect: Rect<f32>,
+ /// The size of the scrollbars in each dimension. If there is no scrollbar then the size will be zero.
+ pub scrollbar_size: Size<f32>,
+ /// The size of the borders of the node
+ pub border: Rect<f32>,
+ /// The size of the padding of the node
+ pub padding: Rect<f32>,
+ /// The size of the margin of the node
+ pub margin: Rect<f32>,
+}
+
+impl Default for Layout {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Layout {
+ /// Creates a new zero-[`Layout`].
+ ///
+ /// The Zero-layout has size and location set to ZERO.
+ /// The `order` value of this layout is set to the minimum value of 0.
+ /// This means it should be rendered below all other [`Layout`]s.
+ #[must_use]
+ pub const fn new() -> Self {
+ Self {
+ order: 0,
+ location: Point::ZERO,
+ size: Size::zero(),
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: Rect::ZERO,
+ scrollbar_size: Size::zero(),
+ border: Rect::zero(),
+ padding: Rect::zero(),
+ margin: Rect::zero(),
+ }
+ }
+
+ /// Creates a new zero-[`Layout`] with the supplied `order` value.
+ ///
+ /// Nodes with a higher order should be rendered on top of those with a lower order.
+ /// The Zero-layout has size and location set to ZERO.
+ #[must_use]
+ pub const fn with_order(order: u32) -> Self {
+ Self {
+ order,
+ size: Size::zero(),
+ location: Point::ZERO,
+ #[cfg(feature = "content_size")]
+ scrollable_overflow_rect: Rect::ZERO,
+ scrollbar_size: Size::zero(),
+ border: Rect::zero(),
+ padding: Rect::zero(),
+ margin: Rect::zero(),
+ }
+ }
+
+ /// Get the width of the node's content box
+ #[inline]
+ pub fn content_box_width(&self) -> f32 {
+ self.size.width - self.padding.left - self.padding.right - self.border.left - self.border.right
+ }
+
+ /// Get the height of the node's content box
+ #[inline]
+ pub fn content_box_height(&self) -> f32 {
+ self.size.height - self.padding.top - self.padding.bottom - self.border.top - self.border.bottom
+ }
+
+ /// Get the size of the node's content box
+ #[inline]
+ pub fn content_box_size(&self) -> Size<f32> {
+ Size { width: self.content_box_width(), height: self.content_box_height() }
+ }
+
+ /// Get x offset of the node's content box relative to it's parent's border box
+ pub fn content_box_x(&self) -> f32 {
+ self.location.x + self.border.left + self.padding.left
+ }
+
+ /// Get x offset of the node's content box relative to it's parent's border box
+ pub fn content_box_y(&self) -> f32 {
+ self.location.y + self.border.top + self.padding.top
+ }
+}
+
+#[cfg(feature = "content_size")]
+impl Layout {
+ /// Return the maximum horizontal scroll offset of the node.
+ /// This is the reachable extent of the content less the width of the padding box, floored at zero.
+ pub fn scroll_width(&self) -> f32 {
+ f32_max(
+ 0.0,
+ self.scrollable_overflow_rect.right + f32_min(self.scrollbar_size.width, self.size.width) - self.size.width
+ + self.border.left
+ + self.border.right,
+ )
+ }
+
+ /// Return the maximum vertical scroll offset of the node.
+ /// This is the reachable extent of the content less the height of the padding box, floored at zero.
+ pub fn scroll_height(&self) -> f32 {
+ f32_max(
+ 0.0,
+ self.scrollable_overflow_rect.bottom + f32_min(self.scrollbar_size.height, self.size.height)
+ - self.size.height
+ + self.border.top
+ + self.border.bottom,
+ )
+ }
+}
+
+/// The additional information from layout algorithm
+#[derive(Debug, Clone, PartialEq)]
+pub enum DetailedLayoutInfo<S: CheapCloneStr = DefaultCheapStr> {
+ /// Enum variant for [`DetailedGridInfo`](crate::compute::grid::DetailedGridInfo)
+ #[cfg(feature = "grid")]
+ Grid(crate::util::sys::Box<crate::compute::grid::DetailedGridInfo<S>>),
+ /// For node that hasn't had any detailed information yet
+ None,
+ /// Unused variant which exists only to consume the `S` type parameter when no variant
+ /// carrying detailed layout info is enabled
+ #[cfg(not(feature = "grid"))]
+ #[doc(hidden)]
+ Phantom(core::convert::Infallible, core::marker::PhantomData<S>),
+}
diff --git a/vendor/taffy/src/tree/mod.rs b/vendor/taffy/src/tree/mod.rs
new file mode 100644
index 00000000..1d704199
--- /dev/null
+++ b/vendor/taffy/src/tree/mod.rs
@@ -0,0 +1,38 @@
+//! Contains both a high-level interface to Taffy using a ready-made node tree, and a set of traits for defining custom node trees.
+//!
+//! - For documentation on the high-level API, see the [`TaffyTree`] struct.
+//! - For documentation on the low-level trait-based API, see the [`traits`] module.
+
+// Submodules
+mod cache;
+mod layout;
+mod node;
+pub mod traits;
+
+#[doc(hidden)]
+#[cfg(all(debug_assertions, feature = "std"))]
+pub use cache::cache_mode_change_evictions;
+pub use cache::{Cache, ClearState};
+pub use layout::{
+ AxisStaticAlign, AxisStaticEdge, AxisStaticPosition, Baselines, CollapsibleMarginSet, Layout, LayoutInput,
+ LayoutOutput, OofCandidate, OofCandidates, OofPositioningArea, RequestedAxis, RunMode, SizingMode,
+};
+pub use node::NodeId;
+pub(crate) use traits::LayoutPartialTreeExt;
+pub use traits::{LayoutContainingBlock, LayoutPartialTree, PrintTree, RoundTree, TraversePartialTree, TraverseTree};
+
+#[cfg(feature = "flexbox")]
+pub use traits::LayoutFlexboxContainer;
+
+#[cfg(feature = "grid")]
+pub use traits::LayoutGridContainer;
+
+#[cfg(feature = "block_layout")]
+pub use traits::LayoutBlockContainer;
+
+#[cfg(feature = "taffy_tree")]
+mod taffy_tree;
+#[cfg(feature = "taffy_tree")]
+pub use taffy_tree::{TaffyError, TaffyResult, TaffyTree};
+
+pub use layout::DetailedLayoutInfo;
diff --git a/vendor/taffy/src/tree/node.rs b/vendor/taffy/src/tree/node.rs
new file mode 100644
index 00000000..9285c22e
--- /dev/null
+++ b/vendor/taffy/src/tree/node.rs
@@ -0,0 +1,60 @@
+//! UI node types and related data structures.
+//!
+//! Layouts are composed of multiple nodes, which live in a tree-like data structure.
+
+#[cfg(feature = "taffy_tree")]
+use slotmap::{DefaultKey, Key, KeyData};
+
+/// A type representing the id of a single node in a tree of nodes
+///
+/// Internally it is a wrapper around a u64 and a `NodeId` can be converted to and from
+/// and u64 if needed.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub struct NodeId(u64);
+impl NodeId {
+ /// Create a new NodeId from a u64 value
+ pub const fn new(val: u64) -> Self {
+ Self(val)
+ }
+}
+
+impl From<u64> for NodeId {
+ #[inline]
+ fn from(raw: u64) -> Self {
+ Self(raw)
+ }
+}
+impl From<NodeId> for u64 {
+ #[inline]
+ fn from(id: NodeId) -> Self {
+ id.0
+ }
+}
+impl From<usize> for NodeId {
+ #[inline]
+ fn from(raw: usize) -> Self {
+ Self(raw as u64)
+ }
+}
+impl From<NodeId> for usize {
+ #[inline]
+ fn from(id: NodeId) -> Self {
+ id.0 as usize
+ }
+}
+
+#[cfg(feature = "taffy_tree")]
+impl From<DefaultKey> for NodeId {
+ #[inline]
+ fn from(key: DefaultKey) -> Self {
+ Self(key.data().as_ffi())
+ }
+}
+
+#[cfg(feature = "taffy_tree")]
+impl From<NodeId> for DefaultKey {
+ #[inline]
+ fn from(key: NodeId) -> Self {
+ KeyData::from_ffi(key.0).into()
+ }
+}
diff --git a/vendor/taffy/src/tree/taffy_tree.rs b/vendor/taffy/src/tree/taffy_tree.rs
new file mode 100644
index 00000000..c8eb01ea
--- /dev/null
+++ b/vendor/taffy/src/tree/taffy_tree.rs
@@ -0,0 +1,1543 @@
+//! Contains [TaffyTree](crate::tree::TaffyTree): the default implementation of [LayoutTree](crate::tree::LayoutTree), and the error type for Taffy.
+#[cfg(not(feature = "std"))]
+use slotmap::SecondaryMap;
+#[cfg(feature = "std")]
+use slotmap::SparseSecondaryMap as SecondaryMap;
+use slotmap::{DefaultKey, SlotMap};
+
+#[cfg(feature = "block_layout")]
+use crate::block::BlockContext;
+use crate::geometry::Size;
+use crate::style::{AvailableSpace, Display, Style};
+use crate::sys::DefaultCheapStr;
+use crate::tree::{
+ Cache, ClearState, Layout, LayoutContainingBlock, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, PrintTree,
+ RoundTree, RunMode, TraversePartialTree, TraverseTree,
+};
+use crate::util::debug::{debug_log, debug_log_node};
+use crate::util::sys::{new_const_children_vec, new_vec_with_capacity, Box, ChildrenVec, Vec};
+
+use crate::compute::{
+ compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_oof_layout, compute_root_layout,
+ round_layout,
+};
+use crate::CacheTree;
+
+#[cfg(feature = "block_layout")]
+use crate::{compute::compute_block_layout, LayoutBlockContainer};
+#[cfg(feature = "flexbox")]
+use crate::{compute::compute_flexbox_layout, LayoutFlexboxContainer};
+#[cfg(feature = "grid")]
+use crate::{compute::compute_grid_layout, LayoutGridContainer};
+
+#[cfg(feature = "grid")]
+use crate::compute::grid::DetailedGridInfo;
+use crate::tree::layout::DetailedLayoutInfo;
+
+/// The error Taffy generates on invalid operations
+pub type TaffyResult<T> = Result<T, TaffyError>;
+
+/// An error that occurs while trying to access or modify a node's children by index.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TaffyError {
+ /// The parent node does not have a child at `child_index`. It only has `child_count` children
+ ChildIndexOutOfBounds {
+ /// The parent node whose child was being looked up
+ parent: NodeId,
+ /// The index that was looked up
+ child_index: usize,
+ /// The total number of children the parent has
+ child_count: usize,
+ },
+ /// The parent node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
+ InvalidParentNode(NodeId),
+ /// The child node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
+ InvalidChildNode(NodeId),
+ /// The supplied node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
+ InvalidInputNode(NodeId),
+}
+
+impl core::fmt::Display for TaffyError {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ match self {
+ TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count } => {
+ write!(f, "Index (is {child_index}) should be < child_count ({child_count}) for parent node {parent:?}")
+ }
+ TaffyError::InvalidParentNode(parent) => {
+ write!(f, "Parent Node {parent:?} is not in the TaffyTree instance")
+ }
+ TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the TaffyTree instance"),
+ TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the TaffyTree instance"),
+ }
+ }
+}
+
+#[cfg(feature = "std")]
+impl std::error::Error for TaffyError {}
+
+/// Global configuration values for a TaffyTree instance
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct TaffyConfig {
+ /// Whether to round layout values
+ pub(crate) use_rounding: bool,
+}
+
+impl Default for TaffyConfig {
+ fn default() -> Self {
+ Self { use_rounding: true }
+ }
+}
+
+/// Layout information for a given [`Node`](crate::node::Node)
+///
+/// Stored in a [`TaffyTree`].
+#[derive(Debug, Clone, PartialEq)]
+struct NodeData {
+ /// The layout strategy used by this node
+ pub(crate) style: Style,
+
+ /// The always unrounded results of the layout computation. We must store this separately from the rounded
+ /// layout to avoid errors from rounding already-rounded values. See <https://github.com/DioxusLabs/taffy/issues/501>.
+ pub(crate) unrounded_layout: Layout,
+
+ /// The final results of the layout computation.
+ /// These may be rounded or unrounded depending on what the `use_rounding` config setting is set to.
+ pub(crate) final_layout: Layout,
+
+ /// Whether the node has context data associated with it or not
+ pub(crate) has_context: bool,
+
+ /// Out-of-flow (absolute/fixed) boxes whose containing block is this node,
+ /// as recorded by the out-of-flow positioning pass
+ pub(crate) hoisted_children: ChildrenVec<NodeId>,
+
+ /// The cached results of the layout computation
+ pub(crate) cache: Cache,
+
+ /// The computation result from layout algorithm
+ pub(crate) detailed_layout_info: DetailedLayoutInfo,
+}
+
+impl NodeData {
+ /// Create the data for a new node
+ #[must_use]
+ pub const fn new(style: Style) -> Self {
+ Self {
+ style,
+ cache: Cache::new(),
+ unrounded_layout: Layout::new(),
+ final_layout: Layout::new(),
+ has_context: false,
+ hoisted_children: new_const_children_vec(),
+ detailed_layout_info: DetailedLayoutInfo::None,
+ }
+ }
+
+ /// Marks a node and all of its ancestors as requiring relayout
+ ///
+ /// This clears any cached data and signals that the data must be recomputed.
+ /// If the node was already marked as dirty, returns true
+ #[inline]
+ pub fn mark_dirty(&mut self) -> ClearState {
+ self.cache.clear()
+ }
+}
+
+/// An entire tree of UI nodes. The entry point to Taffy's high-level API.
+///
+/// Allows you to build a tree of UI nodes, run Taffy's layout algorithms over that tree, and then access the resultant layout.]
+#[derive(Debug, Clone)]
+pub struct TaffyTree<NodeContext = ()> {
+ /// The [`NodeData`] for each node stored in this tree
+ nodes: SlotMap<DefaultKey, NodeData>,
+
+ /// Functions/closures that compute the intrinsic size of leaf nodes
+ node_context_data: SecondaryMap<DefaultKey, NodeContext>,
+
+ /// The children of each node
+ ///
+ /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
+ children: SlotMap<DefaultKey, ChildrenVec<NodeId>>,
+
+ /// The parents of each node
+ ///
+ /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
+ parents: SlotMap<DefaultKey, Option<NodeId>>,
+
+ /// Layout mode configuration
+ config: TaffyConfig,
+}
+
+impl Default for TaffyTree {
+ fn default() -> TaffyTree<()> {
+ TaffyTree::new()
+ }
+}
+
+/// Iterator that wraps a slice of nodes, lazily converting them to u64
+pub struct TaffyTreeChildIter<'a>(core::slice::Iter<'a, NodeId>);
+impl Iterator for TaffyTreeChildIter<'_> {
+ type Item = NodeId;
+
+ #[inline]
+ fn next(&mut self) -> Option<Self::Item> {
+ self.0.next().copied()
+ }
+}
+
+// TraversePartialTree impl for TaffyTree
+impl<NodeContext> TraversePartialTree for TaffyTree<NodeContext> {
+ type ChildIter<'a>
+ = TaffyTreeChildIter<'a>
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
+ TaffyTreeChildIter(self.children[parent_node_id.into()].iter())
+ }
+
+ #[inline(always)]
+ fn child_count(&self, parent_node_id: NodeId) -> usize {
+ self.children[parent_node_id.into()].len()
+ }
+
+ #[inline(always)]
+ fn get_child_id(&self, parent_node_id: NodeId, id: usize) -> NodeId {
+ self.children[parent_node_id.into()][id]
+ }
+}
+
+// TraverseTree impl for TaffyTree
+impl<NodeContext> TraverseTree for TaffyTree<NodeContext> {}
+
+// CacheTree impl for TaffyTree
+impl<NodeContext> CacheTree for TaffyTree<NodeContext> {
+ fn cache_get(&mut self, node_id: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
+ self.nodes[node_id.into()].cache.get(input)
+ }
+
+ fn cache_store(&mut self, node_id: NodeId, input: &LayoutInput, layout_output: LayoutOutput) {
+ self.nodes[node_id.into()].cache.store(input, layout_output)
+ }
+
+ fn cache_clear(&mut self, node_id: NodeId) {
+ self.nodes[node_id.into()].cache.clear();
+ }
+}
+
+// PrintTree impl for TaffyTree
+impl<NodeContext> PrintTree for TaffyTree<NodeContext> {
+ #[inline(always)]
+ fn get_debug_label(&self, node_id: NodeId) -> &'static str {
+ let node = &self.nodes[node_id.into()];
+ let display = node.style.display;
+ let num_children = self.child_count(node_id);
+
+ match (num_children, display) {
+ (_, Display::None) => "NONE",
+ (0, _) => "LEAF",
+ #[cfg(feature = "block_layout")]
+ (_, Display::Block) => "BLOCK",
+ #[cfg(feature = "block_layout")]
+ (_, Display::FlowRoot) => "FLOW-ROOT",
+ #[cfg(feature = "flexbox")]
+ (_, Display::Flex) => {
+ use crate::FlexDirection;
+ match node.style.flex_direction {
+ FlexDirection::Row | FlexDirection::RowReverse => "FLEX ROW",
+ FlexDirection::Column | FlexDirection::ColumnReverse => "FLEX COL",
+ }
+ }
+ #[cfg(feature = "grid")]
+ (_, Display::Grid) => "GRID",
+ }
+ }
+
+ #[inline(always)]
+ fn get_final_layout(&self, node_id: NodeId) -> Layout {
+ if self.config.use_rounding {
+ self.nodes[node_id.into()].final_layout
+ } else {
+ self.nodes[node_id.into()].unrounded_layout
+ }
+ }
+}
+
+/// View over the Taffy tree that holds the tree itself along with a reference to the context
+/// and implements LayoutTree. This allows the context to be stored outside of the TaffyTree struct
+/// which makes the lifetimes of the context much more flexible.
+pub(crate) struct TaffyView<'t, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ /// A reference to the TaffyTree
+ pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
+ /// The context provided for passing to measure functions if layout is run over this struct
+ pub(crate) measure_function: MeasureFunction,
+}
+
+impl<NodeContext, MeasureFunction> TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ #[inline(always)]
+ /// Unified implementation that both `LayoutPartialTree::compute_child_layout`
+ /// and `LayoutBlockContainer::compute_block_child_layout` delegate to.
+ fn compute_child_layout(
+ &mut self,
+ node_id: NodeId,
+ inputs: LayoutInput,
+ #[cfg(feature = "block_layout")] block_ctx: Option<&mut BlockContext<'_>>,
+ ) -> LayoutOutput {
+ // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
+ // and thus that we should lay out this node using hidden layout regardless of it's own display style.
+ if inputs.run_mode == RunMode::PerformHiddenLayout {
+ debug_log!("HIDDEN");
+ return compute_hidden_layout(self, node_id);
+ }
+
+ // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
+ // - Return that entry if exists
+ // - Else call the passed closure (below) to compute the result
+ //
+ // If there was no cache match and a new result needs to be computed then that result will be added to the cache
+ compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
+ let display_mode = tree.taffy.nodes[node_id.into()].style.display;
+ let has_children = tree.child_count(node_id) > 0;
+
+ debug_log!(display_mode);
+ debug_log_node!(inputs);
+
+ // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
+ let mut output = match (display_mode, has_children) {
+ (Display::None, _) => compute_hidden_layout(tree, node_id),
+ #[cfg(feature = "block_layout")]
+ (Display::Block, true) => compute_block_layout(tree, node_id, inputs, block_ctx),
+ #[cfg(feature = "block_layout")]
+ (Display::FlowRoot, true) => compute_block_layout(tree, node_id, inputs, None),
+ #[cfg(feature = "flexbox")]
+ (Display::Flex, true) => compute_flexbox_layout(tree, node_id, inputs),
+ #[cfg(feature = "grid")]
+ (Display::Grid, true) => compute_grid_layout(tree, node_id, inputs),
+ (_, false) => {
+ let node_key = node_id.into();
+ let style = &tree.taffy.nodes[node_key].style;
+ let has_context = tree.taffy.nodes[node_key].has_context;
+ let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
+ (tree.measure_function)(inputs, node_id, node_context, style)
+ }
+ };
+
+ // Lay out any out-of-flow candidates for which this node is the containing block.
+ // The rest bubble up via `output.oof_candidates`. This runs inside the cache-miss
+ // closure so that cached outputs already contain the processed candidate list.
+ // Only full layout passes run it: measure passes must not write hoisted box layouts
+ // (which would not be rewritten if the final layout pass is a cache hit).
+ if inputs.run_mode == RunMode::PerformLayout {
+ compute_oof_layout(tree, node_id, &mut output);
+ }
+
+ output
+ })
+ }
+}
+
+// TraversePartialTree impl for TaffyView
+impl<NodeContext, MeasureFunction> TraversePartialTree for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type ChildIter<'a>
+ = TaffyTreeChildIter<'a>
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
+ self.taffy.child_ids(parent_node_id)
+ }
+
+ #[inline(always)]
+ fn child_count(&self, parent_node_id: NodeId) -> usize {
+ self.taffy.child_count(parent_node_id)
+ }
+
+ #[inline(always)]
+ fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
+ self.taffy.get_child_id(parent_node_id, child_index)
+ }
+}
+
+// TraverseTree impl for TaffyView
+impl<NodeContext, MeasureFunction> TraverseTree for TaffyView<'_, NodeContext, MeasureFunction> where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput
+{
+}
+
+// LayoutPartialTree impl for TaffyView
+impl<NodeContext, MeasureFunction> LayoutPartialTree for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type CoreContainerStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+
+ type CustomIdent = DefaultCheapStr;
+
+ #[inline(always)]
+ fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
+ &self.taffy.nodes[node_id.into()].style
+ }
+
+ #[inline(always)]
+ fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
+ self.taffy.nodes[node_id.into()].unrounded_layout = *layout;
+ }
+
+ #[inline(always)]
+ fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
+ 0.0
+ }
+
+ #[inline(always)]
+ fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput {
+ self.compute_child_layout(
+ node_id,
+ inputs,
+ #[cfg(feature = "block_layout")]
+ None,
+ )
+ }
+}
+
+impl<NodeContext, MeasureFunction> LayoutContainingBlock for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type OofItemStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
+ &self.taffy.nodes[node_id.into()].style
+ }
+
+ #[inline(always)]
+ fn clear_hoisted_children(&mut self, node_id: NodeId) {
+ self.taffy.nodes[node_id.into()].hoisted_children.clear();
+ }
+
+ #[inline(always)]
+ fn add_hoisted_children(&mut self, node_id: NodeId, hoisted: &[NodeId]) {
+ self.taffy.nodes[node_id.into()].hoisted_children.extend_from_slice(hoisted);
+ }
+
+ #[inline(always)]
+ fn get_detailed_layout_info(&self, node_id: NodeId) -> &DetailedLayoutInfo {
+ &self.taffy.nodes[node_id.into()].detailed_layout_info
+ }
+}
+
+impl<NodeContext, MeasureFunction> CacheTree for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ fn cache_get(&mut self, node_id: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
+ self.taffy.nodes[node_id.into()].cache.get(input)
+ }
+
+ fn cache_store(&mut self, node_id: NodeId, input: &LayoutInput, layout_output: LayoutOutput) {
+ self.taffy.nodes[node_id.into()].cache.store(input, layout_output)
+ }
+
+ fn cache_clear(&mut self, node_id: NodeId) {
+ self.taffy.nodes[node_id.into()].cache.clear();
+ }
+}
+
+#[cfg(feature = "block_layout")]
+impl<NodeContext, MeasureFunction> LayoutBlockContainer for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type BlockContainerStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+ type BlockItemStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
+ self.get_core_container_style(node_id)
+ }
+
+ #[inline(always)]
+ fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
+ self.get_core_container_style(child_node_id)
+ }
+
+ #[inline(always)]
+ fn compute_block_child_layout(
+ &mut self,
+ node_id: NodeId,
+ inputs: LayoutInput,
+ block_ctx: Option<&mut BlockContext<'_>>,
+ ) -> LayoutOutput {
+ self.compute_child_layout(node_id, inputs, block_ctx)
+ }
+}
+
+#[cfg(feature = "flexbox")]
+impl<NodeContext, MeasureFunction> LayoutFlexboxContainer for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type FlexboxContainerStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+ type FlexboxItemStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
+ &self.taffy.nodes[node_id.into()].style
+ }
+
+ #[inline(always)]
+ fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
+ &self.taffy.nodes[child_node_id.into()].style
+ }
+}
+
+#[cfg(feature = "grid")]
+impl<NodeContext, MeasureFunction> LayoutGridContainer for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ type GridContainerStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+ type GridItemStyle<'a>
+ = &'a Style
+ where
+ Self: 'a;
+
+ #[inline(always)]
+ fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
+ &self.taffy.nodes[node_id.into()].style
+ }
+
+ #[inline(always)]
+ fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
+ &self.taffy.nodes[child_node_id.into()].style
+ }
+
+ #[inline(always)]
+ fn set_detailed_grid_info(&mut self, node_id: NodeId, detailed_grid_info: DetailedGridInfo) {
+ self.taffy.nodes[node_id.into()].detailed_layout_info = DetailedLayoutInfo::Grid(Box::new(detailed_grid_info));
+ }
+}
+
+// RoundTree impl for TaffyView
+impl<NodeContext, MeasureFunction> RoundTree for TaffyView<'_, NodeContext, MeasureFunction>
+where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+{
+ #[inline(always)]
+ fn get_unrounded_layout(&self, node: NodeId) -> Layout {
+ self.taffy.nodes[node.into()].unrounded_layout
+ }
+
+ #[inline(always)]
+ fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
+ self.taffy.nodes[node_id.into()].final_layout = *layout;
+ }
+
+ #[inline(always)]
+ fn is_out_of_flow(&self, node_id: NodeId) -> bool {
+ let node = &self.taffy.nodes[node_id.into()];
+ node.style.position.is_out_of_flow() && node.style.display != crate::style::Display::None
+ }
+
+ #[inline(always)]
+ fn hoisted_child_count(&self, node_id: NodeId) -> usize {
+ self.taffy.nodes[node_id.into()].hoisted_children.len()
+ }
+
+ #[inline(always)]
+ fn get_hoisted_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
+ self.taffy.nodes[node_id.into()].hoisted_children[index]
+ }
+}
+
+#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
+impl<NodeContext> TaffyTree<NodeContext> {
+ /// Creates a new [`TaffyTree`]
+ ///
+ /// The default capacity of a [`TaffyTree`] is 16 nodes.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::with_capacity(16)
+ }
+
+ /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
+ #[must_use]
+ pub fn with_capacity(capacity: usize) -> Self {
+ TaffyTree {
+ // TODO: make this method const upstream,
+ // so constructors here can be const
+ nodes: SlotMap::with_capacity(capacity),
+ children: SlotMap::with_capacity(capacity),
+ parents: SlotMap::with_capacity(capacity),
+ node_context_data: SecondaryMap::with_capacity(capacity),
+ config: TaffyConfig::default(),
+ }
+ }
+
+ /// Enable rounding of layout values. Rounding is enabled by default.
+ pub fn enable_rounding(&mut self) {
+ self.config.use_rounding = true;
+ }
+
+ /// Disable rounding of layout values. Rounding is enabled by default.
+ pub fn disable_rounding(&mut self) {
+ self.config.use_rounding = false;
+ }
+
+ /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
+ pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
+ let id = self.nodes.insert(NodeData::new(layout));
+ let _ = self.children.insert(new_vec_with_capacity(0));
+ let _ = self.parents.insert(None);
+
+ Ok(id.into())
+ }
+
+ /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
+ ///
+ /// Creates and adds a new leaf node with a supplied context
+ pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
+ let mut data = NodeData::new(layout);
+ data.has_context = true;
+
+ let id = self.nodes.insert(data);
+ self.node_context_data.insert(id, context);
+
+ let _ = self.children.insert(new_vec_with_capacity(0));
+ let _ = self.parents.insert(None);
+
+ Ok(id.into())
+ }
+
+ /// Creates and adds a new node, which may have any number of `children`
+ pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
+ let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
+
+ for child in children {
+ self.parents[(*child).into()] = Some(id);
+ }
+
+ let _ = self.children.insert(children.iter().copied().collect::<_>());
+ let _ = self.parents.insert(None);
+
+ Ok(id)
+ }
+
+ /// Drops all nodes in the tree
+ pub fn clear(&mut self) {
+ self.nodes.clear();
+ self.children.clear();
+ self.parents.clear();
+ // A context belongs to the node that owns it. Leaving it behind keeps arbitrary
+ // user data -- for a measure function, a boxed closure and everything it
+ // captures -- alive after the node it belonged to is gone.
+ self.node_context_data.clear();
+ }
+
+ /// Remove a specific node from the tree and drop it
+ ///
+ /// Returns the id of the node removed.
+ pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
+ let key = node.into();
+ if let Some(parent) = self.parents[key] {
+ if let Some(children) = self.children.get_mut(parent.into()) {
+ children.retain(|f| *f != node);
+ }
+ self.mark_dirty(parent)?;
+ }
+
+ // Remove "parent" references to a node when removing that node
+ if let Some(children) = self.children.get(key) {
+ for child in children.iter().copied() {
+ self.parents[child.into()] = None;
+ }
+ }
+
+ let _ = self.children.remove(key);
+ let _ = self.parents.remove(key);
+ let _ = self.nodes.remove(key);
+ let _ = self.node_context_data.remove(key);
+
+ Ok(node)
+ }
+
+ /// Sets the context data associated with the node
+ #[inline]
+ pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
+ let key = node.into();
+ if let Some(measure) = measure {
+ self.nodes[key].has_context = true;
+ self.node_context_data.insert(key, measure);
+ } else {
+ self.nodes[key].has_context = false;
+ self.node_context_data.remove(key);
+ }
+
+ self.mark_dirty(node)?;
+
+ Ok(())
+ }
+
+ /// Gets a reference to the the context data associated with the node
+ #[inline]
+ pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
+ self.node_context_data.get(node.into())
+ }
+
+ /// Gets a mutable reference to the the context data associated with the node
+ #[inline]
+ pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
+ self.node_context_data.get_mut(node.into())
+ }
+
+ /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
+ pub fn get_disjoint_node_context_mut<const N: usize>(
+ &mut self,
+ keys: [NodeId; N],
+ ) -> Option<[&mut NodeContext; N]> {
+ self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
+ }
+
+ /// Adds a `child` node under the supplied `parent`
+ pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
+ let parent_key = parent.into();
+ let child_key = child.into();
+ self.parents[child_key] = Some(parent);
+ self.children[parent_key].push(child);
+ self.mark_dirty(parent)?;
+
+ Ok(())
+ }
+
+ /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
+ pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
+ let parent_key = parent.into();
+
+ let child_count = self.children[parent_key].len();
+ if child_index > child_count {
+ return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
+ }
+
+ self.parents[child.into()] = Some(parent);
+ self.children[parent_key].insert(child_index, child);
+ self.mark_dirty(parent)?;
+
+ Ok(())
+ }
+
+ /// Directly sets the `children` of the supplied `parent`
+ pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
+ let parent_key = parent.into();
+
+ // Remove node as parent from all its current children.
+ for child in &self.children[parent_key] {
+ self.parents[(*child).into()] = None;
+ }
+
+ // Build up relation node <-> child
+ for &child in children {
+ // Remove child from previous parent
+ if let Some(previous_parent) = self.parents[child.into()] {
+ self.remove_child(previous_parent, child).unwrap();
+ }
+ self.parents[child.into()] = Some(parent);
+ }
+
+ let parent_children = &mut self.children[parent_key];
+ parent_children.clear();
+ children.iter().for_each(|child| parent_children.push(*child));
+
+ self.mark_dirty(parent)?;
+
+ Ok(())
+ }
+
+ /// Removes the `child` of the parent `node`
+ ///
+ /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
+ pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
+ let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
+ self.remove_child_at_index(parent, index)
+ }
+
+ /// Removes the child at the given `index` from the `parent`
+ ///
+ /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
+ pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
+ let parent_key = parent.into();
+ let child_count = self.children[parent_key].len();
+ if child_index >= child_count {
+ return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
+ }
+
+ let child = self.children[parent_key].remove(child_index);
+ self.parents[child.into()] = None;
+
+ self.mark_dirty(parent)?;
+
+ Ok(child)
+ }
+
+ /// Removes children at the given range from the `parent`
+ ///
+ /// Children are not removed from the tree entirely, they are simply no longer attached to their previous parent.
+ ///
+ /// Function will panic if given range is invalid. See [`core::slice::range`]
+ pub fn remove_children_range<R>(&mut self, parent: NodeId, range: R) -> TaffyResult<()>
+ where
+ R: core::ops::RangeBounds<usize>,
+ {
+ let parent_key = parent.into();
+ for child in self.children[parent_key].drain(range) {
+ self.parents[child.into()] = None;
+ }
+
+ self.mark_dirty(parent)?;
+ Ok(())
+ }
+
+ /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
+ ///
+ /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
+ pub fn replace_child_at_index(
+ &mut self,
+ parent: NodeId,
+ child_index: usize,
+ new_child: NodeId,
+ ) -> TaffyResult<NodeId> {
+ let parent_key = parent.into();
+
+ let child_count = self.children[parent_key].len();
+ if child_index >= child_count {
+ return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
+ }
+
+ self.parents[new_child.into()] = Some(parent);
+ let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
+ self.parents[old_child.into()] = None;
+
+ self.mark_dirty(parent)?;
+
+ Ok(old_child)
+ }
+
+ /// Returns the child node of the parent `node` at the provided `child_index`
+ #[inline]
+ pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
+ let parent_key = parent.into();
+ let child_count = self.children[parent_key].len();
+ if child_index >= child_count {
+ return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
+ }
+
+ Ok(self.children[parent_key][child_index])
+ }
+
+ /// Returns the total number of nodes in the tree
+ #[inline]
+ pub fn total_node_count(&self) -> usize {
+ self.nodes.len()
+ }
+
+ /// Returns the `NodeId` of the parent node of the specified node (if it exists)
+ ///
+ /// - Return None if the specified node has no parent
+ /// - Panics if the specified node does not exist
+ #[inline]
+ pub fn parent(&self, child_id: NodeId) -> Option<NodeId> {
+ self.parents[child_id.into()]
+ }
+
+ /// Returns a list of children that belong to the parent node
+ pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
+ Ok(self.children[parent.into()].clone())
+ }
+
+ /// Returns the out-of-flow (absolute/fixed) boxes whose containing block is `node`, as
+ /// recorded by the last layout. These boxes are laid out by `node` rather than by their
+ /// parent, and their [`Layout::location`] is relative to `node`.
+ pub fn hoisted_children(&self, node: NodeId) -> TaffyResult<&[NodeId]> {
+ Ok(&self.nodes[node.into()].hoisted_children)
+ }
+
+ /// Sets the [`Style`] of the provided `node`
+ #[inline]
+ pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
+ self.nodes[node.into()].style = style;
+ self.mark_dirty(node)?;
+ Ok(())
+ }
+
+ /// Gets the [`Style`] of the provided `node`
+ #[inline]
+ pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
+ Ok(&self.nodes[node.into()].style)
+ }
+
+ /// Return this node layout relative to its parent
+ #[inline]
+ pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
+ if self.config.use_rounding {
+ Ok(&self.nodes[node.into()].final_layout)
+ } else {
+ Ok(&self.nodes[node.into()].unrounded_layout)
+ }
+ }
+
+ /// Returns this node layout with unrounded values relative to its parent.
+ #[inline]
+ pub fn unrounded_layout(&self, node: NodeId) -> &Layout {
+ &self.nodes[node.into()].unrounded_layout
+ }
+
+ /// Get the "detailed layout info" for a node.
+ ///
+ /// Currently this is only implemented for CSS Grid containers where it contains
+ /// the computed size of each grid track and the computed placement of each grid item
+ #[inline]
+ pub fn detailed_layout_info(&self, node_id: NodeId) -> &DetailedLayoutInfo {
+ &self.nodes[node_id.into()].detailed_layout_info
+ }
+
+ /// Marks the layout of this node and its ancestors as outdated
+ pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
+ fn mark_dirty_recursive(
+ nodes: &mut SlotMap<DefaultKey, NodeData>,
+ parents: &SlotMap<DefaultKey, Option<NodeId>>,
+ node_key: DefaultKey,
+ ) {
+ match nodes[node_key].mark_dirty() {
+ ClearState::AlreadyEmpty => {
+ // Node was already marked as dirty.
+ // No need to visit ancestors
+ // as they should be marked as dirty already.
+ }
+ ClearState::Cleared => {
+ if let Some(Some(node)) = parents.get(node_key) {
+ mark_dirty_recursive(nodes, parents, (*node).into());
+ }
+ }
+ }
+ }
+
+ mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
+
+ Ok(())
+ }
+
+ /// Indicates whether the layout of this node needs to be recomputed
+ #[inline]
+ pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
+ Ok(self.nodes[node.into()].cache.is_empty())
+ }
+
+ /// Updates the stored layout of the provided `node` and its children
+ pub fn compute_layout_with_measure<MeasureFunction>(
+ &mut self,
+ node_id: NodeId,
+ available_space: Size<AvailableSpace>,
+ measure_function: MeasureFunction,
+ ) -> Result<(), TaffyError>
+ where
+ MeasureFunction: FnMut(LayoutInput, NodeId, Option<&mut NodeContext>, &Style) -> LayoutOutput,
+ {
+ let use_rounding = self.config.use_rounding;
+ let mut taffy_view = TaffyView { taffy: self, measure_function };
+ compute_root_layout(&mut taffy_view, node_id, available_space);
+ if use_rounding {
+ round_layout(&mut taffy_view, node_id);
+ }
+ Ok(())
+ }
+
+ /// Updates the stored layout of the provided `node` and its children
+ pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
+ self.compute_layout_with_measure(node, available_space, |inputs, _, _, style| {
+ compute_leaf_layout(inputs, style, |_, _| 0.0, |_, _| Size::ZERO)
+ })
+ }
+
+ /// Prints a debug representation of the tree's layout
+ #[cfg(feature = "std")]
+ pub fn print_tree(&mut self, root: NodeId) {
+ crate::util::print_tree(self, root)
+ }
+
+ /// Returns an instance of LayoutTree representing the TaffyTree
+ #[cfg(test)]
+ pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + CacheTree + '_ {
+ TaffyView {
+ taffy: self,
+ measure_function: |inputs, _, _, style| compute_leaf_layout(inputs, style, |_, _| 0.0, |_, _| Size::ZERO),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+
+ use super::*;
+ use crate::style::{Dimension, Display, FlexDirection};
+ use crate::style_helpers::*;
+ use crate::util::sys;
+
+ fn size_measure_function(
+ inputs: LayoutInput,
+ _node_id: NodeId,
+ node_context: Option<&mut Size<f32>>,
+ style: &Style,
+ ) -> LayoutOutput {
+ compute_leaf_layout(
+ inputs,
+ style,
+ |_, _| 0.0,
+ |known_dimensions, _available_space| {
+ known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
+ },
+ )
+ }
+
+ #[test]
+ fn new_should_allocate_default_capacity() {
+ const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
+ let taffy: TaffyTree<()> = TaffyTree::new();
+
+ assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
+ assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
+ assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
+ }
+
+ #[test]
+ fn test_with_capacity() {
+ const CAPACITY: usize = 8;
+ let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
+
+ assert!(taffy.children.capacity() >= CAPACITY);
+ assert!(taffy.parents.capacity() >= CAPACITY);
+ assert!(taffy.nodes.capacity() >= CAPACITY);
+ }
+
+ #[test]
+ fn test_new_leaf() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let res = taffy.new_leaf(Style::default());
+ assert!(res.is_ok());
+ let node = res.unwrap();
+
+ // node should be in the taffy tree and have no children
+ assert!(taffy.child_count(node) == 0);
+ }
+
+ #[test]
+ fn new_leaf_with_context() {
+ let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
+
+ let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
+ assert!(res.is_ok());
+ let node = res.unwrap();
+
+ // node should be in the taffy tree and have no children
+ assert!(taffy.child_count(node) == 0);
+ }
+
+ /// Test that new_with_children works as expected
+ #[test]
+ fn test_new_with_children() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ // node should have two children
+ assert_eq!(taffy.child_count(node), 2);
+ assert_eq!(taffy.children(node).unwrap()[0], child0);
+ assert_eq!(taffy.children(node).unwrap()[1], child1);
+ }
+
+ #[test]
+ fn remove_node_should_remove() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let node = taffy.new_leaf(Style::default()).unwrap();
+
+ let _ = taffy.remove(node).unwrap();
+ }
+
+ #[test]
+ fn remove_node_should_detach_hierarchy() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ // Build a linear tree layout: <0> <- <1> <- <2>
+ let node2 = taffy.new_leaf(Style::default()).unwrap();
+ let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
+ let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
+
+ // Both node0 and node1 should have 1 child nodes
+ assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
+ assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
+
+ // Disconnect the tree: <0> <2>
+ let _ = taffy.remove(node1).unwrap();
+
+ // Both remaining nodes should have no child nodes
+ assert!(taffy.children(node0).unwrap().is_empty());
+ assert!(taffy.children(node2).unwrap().is_empty());
+ }
+
+ #[test]
+ fn remove_last_node() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let parent = taffy.new_leaf(Style::default()).unwrap();
+ let child = taffy.new_leaf(Style::default()).unwrap();
+ taffy.add_child(parent, child).unwrap();
+
+ taffy.remove(child).unwrap();
+ taffy.remove(parent).unwrap();
+ }
+
+ // Related to: https://github.com/DioxusLabs/taffy/issues/998
+ #[test]
+ fn remove_node_marks_parent_dirty() {
+ use crate::prelude::*;
+
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ // The root's height comes entirely from its child's 1px bottom border
+ let child = taffy
+ .new_leaf(Style { border: Rect { bottom: length(1f32), ..Rect::zero() }, ..Default::default() })
+ .unwrap();
+ let root = taffy.new_with_children(Style::default(), &[child]).unwrap();
+
+ taffy.compute_layout(root, Size::MIN_CONTENT).unwrap();
+ assert_eq!(taffy.layout(root).unwrap().size.height, 1f32);
+
+ taffy.remove(child).unwrap();
+ assert_eq!(taffy.dirty(root), Ok(true));
+
+ // The root no longer has any children, so its height should shrink back to zero
+ taffy.compute_layout(root, Size::MIN_CONTENT).unwrap();
+ assert_eq!(taffy.layout(root).unwrap().size.height, 0f32);
+ }
+
+ #[test]
+ fn set_measure() {
+ let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
+ let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
+ taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
+ assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
+
+ taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
+ taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
+ assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
+ }
+
+ #[test]
+ fn set_measure_of_previously_unmeasured_node() {
+ let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
+ let node = taffy.new_leaf(Style::default()).unwrap();
+ taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
+ assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
+
+ taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
+ taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
+ assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
+ }
+
+ /// Test that adding `add_child()` works
+ #[test]
+ fn add_child() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let node = taffy.new_leaf(Style::default()).unwrap();
+ assert_eq!(taffy.child_count(node), 0);
+
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ taffy.add_child(node, child0).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ taffy.add_child(node, child1).unwrap();
+ assert_eq!(taffy.child_count(node), 2);
+ }
+
+ #[test]
+ fn insert_child_at_index() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let child2 = taffy.new_leaf(Style::default()).unwrap();
+
+ let node = taffy.new_leaf(Style::default()).unwrap();
+ assert_eq!(taffy.child_count(node), 0);
+
+ taffy.insert_child_at_index(node, 0, child0).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+ assert_eq!(taffy.children(node).unwrap()[0], child0);
+
+ taffy.insert_child_at_index(node, 0, child1).unwrap();
+ assert_eq!(taffy.child_count(node), 2);
+ assert_eq!(taffy.children(node).unwrap()[0], child1);
+ assert_eq!(taffy.children(node).unwrap()[1], child0);
+
+ taffy.insert_child_at_index(node, 1, child2).unwrap();
+ assert_eq!(taffy.child_count(node), 3);
+ assert_eq!(taffy.children(node).unwrap()[0], child1);
+ assert_eq!(taffy.children(node).unwrap()[1], child2);
+ assert_eq!(taffy.children(node).unwrap()[2], child0);
+ }
+
+ #[test]
+ fn set_children() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ assert_eq!(taffy.child_count(node), 2);
+ assert_eq!(taffy.children(node).unwrap()[0], child0);
+ assert_eq!(taffy.children(node).unwrap()[1], child1);
+
+ let child2 = taffy.new_leaf(Style::default()).unwrap();
+ let child3 = taffy.new_leaf(Style::default()).unwrap();
+ taffy.set_children(node, &[child2, child3]).unwrap();
+
+ assert_eq!(taffy.child_count(node), 2);
+ assert_eq!(taffy.children(node).unwrap()[0], child2);
+ assert_eq!(taffy.children(node).unwrap()[1], child3);
+ }
+
+ /// Test that removing a child works
+ #[test]
+ fn remove_child() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ assert_eq!(taffy.child_count(node), 2);
+
+ taffy.remove_child(node, child0).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+ assert_eq!(taffy.children(node).unwrap()[0], child1);
+
+ taffy.remove_child(node, child1).unwrap();
+ assert_eq!(taffy.child_count(node), 0);
+ }
+
+ #[test]
+ fn remove_child_at_index() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ assert_eq!(taffy.child_count(node), 2);
+
+ taffy.remove_child_at_index(node, 0).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+ assert_eq!(taffy.children(node).unwrap()[0], child1);
+
+ taffy.remove_child_at_index(node, 0).unwrap();
+ assert_eq!(taffy.child_count(node), 0);
+ }
+
+ #[test]
+ fn remove_children_range() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let child2 = taffy.new_leaf(Style::default()).unwrap();
+ let child3 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1, child2, child3]).unwrap();
+
+ assert_eq!(taffy.child_count(node), 4);
+
+ taffy.remove_children_range(node, 1..=2).unwrap();
+ assert_eq!(taffy.child_count(node), 2);
+ assert_eq!(taffy.children(node).unwrap(), [child0, child3]);
+ for child in [child0, child3] {
+ assert_eq!(taffy.parent(child), Some(node));
+ }
+ for child in [child1, child2] {
+ assert_eq!(taffy.parent(child), None);
+ }
+ }
+
+ // Related to: https://github.com/DioxusLabs/taffy/issues/510
+ #[test]
+ fn remove_child_updates_parents() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let parent = taffy.new_leaf(Style::default()).unwrap();
+ let child = taffy.new_leaf(Style::default()).unwrap();
+
+ taffy.add_child(parent, child).unwrap();
+
+ taffy.remove(parent).unwrap();
+
+ // Once the parent is removed this shouldn't panic.
+ assert!(taffy.set_children(child, &[]).is_ok());
+ }
+
+ #[test]
+ fn replace_child_at_index() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+
+ let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+ assert_eq!(taffy.children(node).unwrap()[0], child0);
+
+ taffy.replace_child_at_index(node, 0, child1).unwrap();
+ assert_eq!(taffy.child_count(node), 1);
+ assert_eq!(taffy.children(node).unwrap()[0], child1);
+ }
+ #[test]
+ fn test_child_at_index() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let child2 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
+
+ assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
+ assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
+ assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
+ }
+ #[test]
+ fn test_child_count() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ assert!(taffy.child_count(node) == 2);
+ assert!(taffy.child_count(child0) == 0);
+ assert!(taffy.child_count(child1) == 0);
+ }
+
+ #[allow(clippy::vec_init_then_push)]
+ #[test]
+ fn test_children() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ let mut children = sys::Vec::new();
+ children.push(child0);
+ children.push(child1);
+
+ let children_result = taffy.children(node).unwrap();
+ assert_eq!(children_result, children);
+
+ assert!(taffy.children(child0).unwrap().is_empty());
+ }
+ #[test]
+ fn test_set_style() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let node = taffy.new_leaf(Style::default()).unwrap();
+ assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
+
+ taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
+ assert_eq!(taffy.style(node).unwrap().display, Display::None);
+ }
+ #[test]
+ fn test_style() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
+
+ let node = taffy.new_leaf(style.clone()).unwrap();
+
+ let res = taffy.style(node);
+ assert!(res.is_ok());
+ assert!(res.unwrap() == &style);
+ }
+ #[test]
+ fn test_layout() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let node = taffy.new_leaf(Style::default()).unwrap();
+
+ // TODO: Improve this test?
+ let res = taffy.layout(node);
+ assert!(res.is_ok());
+ }
+
+ #[test]
+ fn test_mark_dirty() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child0 = taffy.new_leaf(Style::default()).unwrap();
+ let child1 = taffy.new_leaf(Style::default()).unwrap();
+ let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
+
+ taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
+
+ assert_eq!(taffy.dirty(child0), Ok(false));
+ assert_eq!(taffy.dirty(child1), Ok(false));
+ assert_eq!(taffy.dirty(node), Ok(false));
+
+ taffy.mark_dirty(node).unwrap();
+ assert_eq!(taffy.dirty(child0), Ok(false));
+ assert_eq!(taffy.dirty(child1), Ok(false));
+ assert_eq!(taffy.dirty(node), Ok(true));
+
+ taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
+ taffy.mark_dirty(child0).unwrap();
+ assert_eq!(taffy.dirty(child0), Ok(true));
+ assert_eq!(taffy.dirty(child1), Ok(false));
+ assert_eq!(taffy.dirty(node), Ok(true));
+ }
+
+ #[test]
+ fn compute_layout_should_produce_valid_result() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let node_result = taffy.new_leaf(Style {
+ size: Size { width: Dimension::from_length(10f32), height: Dimension::from_length(10f32) },
+ ..Default::default()
+ });
+ assert!(node_result.is_ok());
+ let node = node_result.unwrap();
+ let layout_result = taffy.compute_layout(
+ node,
+ Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
+ );
+ assert!(layout_result.is_ok());
+ }
+
+ #[test]
+ fn make_sure_layout_location_is_top_left() {
+ use crate::prelude::*;
+
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+
+ let node = taffy
+ .new_leaf(Style {
+ size: Size { width: Dimension::from_percent(1f32), height: Dimension::from_percent(1f32) },
+ ..Default::default()
+ })
+ .unwrap();
+
+ let root = taffy
+ .new_with_children(
+ Style {
+ size: Size { width: Dimension::from_length(100f32), height: Dimension::from_length(100f32) },
+ padding: Rect {
+ left: length(10f32),
+ right: length(20f32),
+ top: length(30f32),
+ bottom: length(40f32),
+ },
+ ..Default::default()
+ },
+ &[node],
+ )
+ .unwrap();
+
+ taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
+
+ // If Layout::location represents top-left coord, 'node' location
+ // must be (due applied 'root' padding): {x: 10, y: 30}.
+ //
+ // It's important, since result will be different for each other
+ // coordinate space:
+ // - bottom-left: {x: 10, y: 40}
+ // - top-right: {x: 20, y: 30}
+ // - bottom-right: {x: 20, y: 40}
+ let layout = taffy.layout(node).unwrap();
+ assert_eq!(layout.location.x, 10f32);
+ assert_eq!(layout.location.y, 30f32);
+ }
+
+ #[test]
+ fn set_children_reparents() {
+ let mut taffy: TaffyTree<()> = TaffyTree::new();
+ let child = taffy.new_leaf(Style::default()).unwrap();
+ let old_parent = taffy.new_with_children(Style::default(), &[child]).unwrap();
+
+ let new_parent = taffy.new_leaf(Style::default()).unwrap();
+ taffy.set_children(new_parent, &[child]).unwrap();
+
+ assert!(taffy.children(old_parent).unwrap().is_empty());
+ }
+
+ /// A context that increments a counter when dropped. Each test owns its own static
+ /// counter so the two can run in parallel.
+ struct DropCounted(&'static core::sync::atomic::AtomicUsize);
+
+ impl Drop for DropCounted {
+ fn drop(&mut self) {
+ self.0.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
+ }
+ }
+
+ #[test]
+ fn remove_drops_the_nodes_context() {
+ static DROPS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
+ let mut taffy: TaffyTree<DropCounted> = TaffyTree::new();
+ let node = taffy.new_leaf_with_context(Style::DEFAULT, DropCounted(&DROPS)).unwrap();
+
+ taffy.remove(node).unwrap();
+
+ assert_eq!(
+ DROPS.load(core::sync::atomic::Ordering::SeqCst),
+ 1,
+ "removing a node must drop its context rather than strand it in node_context_data"
+ );
+ }
+
+ #[test]
+ fn clear_drops_every_nodes_context() {
+ static DROPS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
+ let mut taffy: TaffyTree<DropCounted> = TaffyTree::new();
+ for _ in 0..8 {
+ taffy.new_leaf_with_context(Style::DEFAULT, DropCounted(&DROPS)).unwrap();
+ }
+
+ taffy.clear();
+
+ assert_eq!(
+ DROPS.load(core::sync::atomic::Ordering::SeqCst),
+ 8,
+ "clear() drops all nodes, so it must drop their contexts too"
+ );
+ }
+}
diff --git a/vendor/taffy/src/tree/traits.rs b/vendor/taffy/src/tree/traits.rs
new file mode 100644
index 00000000..7d4adf22
--- /dev/null
+++ b/vendor/taffy/src/tree/traits.rs
@@ -0,0 +1,493 @@
+//! The abstractions that make up the core of Taffy's low-level API
+//!
+//! ## Examples
+//!
+//! The following examples demonstrate end-to-end implementation of Taffy's traits and usage of the low-level compute APIs:
+//!
+//! - [custom_tree_vec](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_vec.rs) which implements a custom Taffy tree using a `Vec` as an arena with NodeId's being index's into the Vec.
+//! - [custom_tree_owned_partial](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_partial.rs) which implements a custom Taffy tree using directly owned children with NodeId's being index's into vec on parent node.
+//! - [custom_tree_owned_unsafe](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_unsafe.rs) which implements a custom Taffy tree using directly owned children with NodeId's being pointers.
+//!
+//! ## Overview
+//!
+//! ### Trait dependency tree
+//!
+//! The tree below illustrates which traits depend on which other traits.
+//!
+//! ```text
+//! TraversePartialTree - Access a node's children
+//! ├── LayoutPartialTree - Run layout algorithms on a node and it's direct children
+//! └── TraverseTree - Recursively access a node's descendants
+//! ├── RoundTree - Round a float-valued` layout to integer pixels
+//! └── PrintTree - Print a debug representation of a node tree
+//! ```
+//!
+//! ### A table of traits
+//!
+//! | Trait | Requires | Enables |
+//! | --- | --- | --- |
+//! | [`LayoutPartialTree`] | [`TraversePartialTree`] | [`compute_flexbox_layout`](crate::compute_flexbox_layout)<br />[`compute_grid_layout`](crate::compute_grid_layout)<br />[`compute_block_layout`](crate::compute_block_layout)<br />[`compute_root_layout`](crate::compute_root_layout)<br />[`compute_leaf_layout`](crate::compute_leaf_layout)<br />[`compute_hidden_layout`](crate::compute_hidden_layout)<br />[`compute_cached_layout`](crate::compute_cached_layout) |
+//! | [`RoundTree`] | [`TraverseTree`] | [`round_layout`](crate::round_layout) |
+//! | [`PrintTree`] | [`TraverseTree`] | [`print_tree`](crate::print_tree) |
+//!
+//! ## All of the traits on one page
+//!
+//! ### TraversePartialTree and TraverseTree
+//! These traits are Taffy's abstraction for downward tree traversal:
+//! - [`TraversePartialTree`] allows access to a single container node, and it's immediate children. This is the only "traverse" trait that is required
+//! for use of Taffy's core layout algorithms (flexbox, grid, etc).
+//! - [`TraverseTree`] is a marker trait which uses the same API signature as `TraversePartialTree`, but extends it with a guarantee that the child/children methods can be used to recurse
+//! infinitely down the tree. It is required by the `RoundTree` and
+//! the `PrintTree` traits.
+//! ```rust
+//! # use taffy::*;
+//! pub trait TraversePartialTree {
+//! /// Type representing an iterator of the children of a node
+//! type ChildIter<'a>: Iterator<Item = NodeId>
+//! where
+//! Self: 'a;
+//!
+//! /// Get the list of children IDs for the given node
+//! fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_>;
+//!
+//! /// Get the number of children for the given node
+//! fn child_count(&self, parent_node_id: NodeId) -> usize;
+//!
+//! /// Get a specific child of a node, where the index represents the nth child
+//! fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId;
+//! }
+//!
+//! pub trait TraverseTree: TraversePartialTree {}
+//! ```
+//!
+//! You must implement [`TraversePartialTree`] to access any of Taffy's low-level API. If your tree implementation allows you to implement [`TraverseTree`] with
+//! the correct semantics (full recursive traversal is available) then you should.
+//!
+//! ### LayoutPartialTree
+//!
+//! **Requires:** `TraversePartialTree`<br />
+//! **Enables:** Flexbox, Grid, Block and Leaf layout algorithms from the [`crate::compute`] module
+//!
+//! Any type that implements [`LayoutPartialTree`] can be laid out using [Taffy's algorithms](crate::compute)
+//!
+//! Note that this trait extends [`TraversePartialTree`] (not [`TraverseTree`]). Taffy's algorithm implementations have been designed such that they can be used for a laying out a single
+//! node that only has access to it's immediate children.
+//!
+//! ```rust
+//! # use taffy::*;
+//! pub trait LayoutPartialTree: TraversePartialTree {
+//! /// Get a reference to the [`Style`] for this node.
+//! fn get_style(&self, node_id: NodeId) -> &Style;
+//!
+//! /// Set the node's unrounded layout
+//! fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout);
+//!
+//! /// Get a mutable reference to the [`Cache`] for this node.
+//! fn get_cache_mut(&mut self, node_id: NodeId) -> &mut Cache;
+//!
+//! /// Compute the specified node's size or full layout given the specified constraints
+//! fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput;
+//! }
+//! ```
+//!
+//! ### RoundTree
+//!
+//! **Requires:** `TraverseTree`
+//!
+//! Trait used by the `round_layout` method which takes a tree of unrounded float-valued layouts and performs
+//! rounding to snap the values to the pixel grid.
+//!
+//! As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
+//!
+//! ```rust
+//! # use taffy::*;
+//! pub trait RoundTree: TraverseTree {
+//! /// Get the node's unrounded layout
+//! fn get_unrounded_layout(&self, node_id: NodeId) -> Layout;
+//! /// Get a reference to the node's final layout
+//! fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout);
+//! }
+//! ```
+//!
+//! ### PrintTree
+//!
+//! **Requires:** `TraverseTree`
+//!
+//! ```rust
+//! /// Trait used by the `print_tree` method which prints a debug representation
+//! ///
+//! /// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
+//! # use taffy::*;
+//! pub trait PrintTree: TraverseTree {
+//! /// Get a debug label for the node (typically the type of node: flexbox, grid, text, image, etc)
+//! fn get_debug_label(&self, node_id: NodeId) -> &'static str;
+//! /// Get a reference to the node's final layout
+//! fn get_final_layout(&self, node_id: NodeId) -> Layout;
+//! }
+//! ```
+//!
+use super::{DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, NodeId, RequestedAxis, RunMode, SizingMode};
+use crate::debug::debug_log;
+use crate::geometry::{AbsoluteAxis, Line, Size};
+use crate::style::{AvailableSpace, CoreStyle, OofItemStyle};
+#[cfg(feature = "flexbox")]
+use crate::style::{FlexboxContainerStyle, FlexboxItemStyle};
+#[cfg(feature = "grid")]
+use crate::style::{GridContainerStyle, GridItemStyle};
+use crate::CheapCloneStr;
+#[cfg(feature = "block_layout")]
+use crate::{BlockContainerStyle, BlockContext, BlockItemStyle};
+
+#[cfg(feature = "grid")]
+use crate::compute::grid::DetailedGridInfo;
+
+/// Taffy's abstraction for downward tree traversal.
+///
+/// However, this trait does *not* require access to any node's other than a single container node's immediate children unless you also intend to implement `TraverseTree`.
+pub trait TraversePartialTree {
+ /// Type representing an iterator of the children of a node
+ type ChildIter<'a>: Iterator<Item = NodeId>
+ where
+ Self: 'a;
+
+ /// Get the list of children IDs for the given node
+ fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_>;
+
+ /// Get the number of children for the given node
+ fn child_count(&self, parent_node_id: NodeId) -> usize;
+
+ /// Get a specific child of a node, where the index represents the nth child
+ fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId;
+}
+
+/// A marker trait which extends `TraversePartialTree`
+///
+/// Implementing this trait implies the additional guarantee that the child/children methods can be used to recurse
+/// infinitely down the tree. Is required by the `RoundTree` and the `PrintTree` traits.
+pub trait TraverseTree: TraversePartialTree {}
+
+/// Any type that implements [`LayoutPartialTree`] can be laid out using [Taffy's algorithms](crate::compute)
+///
+/// Note that this trait extends [`TraversePartialTree`] (not [`TraverseTree`]). Taffy's algorithm implementations have been designed such that they can be used for a laying out a single
+/// node that only has access to it's immediate children.
+pub trait LayoutPartialTree: TraversePartialTree {
+ /// The style type representing the core container styles that all containers should have
+ /// Used when laying out the root node of a tree
+ type CoreContainerStyle<'a>: CoreStyle<CustomIdent = Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// String type for representing "custom identifiers" (for example, named grid lines or areas)
+ /// If you are unsure what to use here then consider `Arc<str>`.
+ type CustomIdent: CheapCloneStr;
+
+ /// Get core style
+ ///
+ /// Only called for the node being laid out, never for its children (those go through the
+ /// `get_*_child_style` methods), so it may be expressed in the node's own axes while child
+ /// styles are expressed in the axes of the node laying them out.
+ fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_>;
+
+ /// Resolve calc value
+ #[inline(always)]
+ fn resolve_calc_value(&self, val: *const (), basis: f32) -> f32 {
+ let _ = val;
+ let _ = basis;
+ 0.0
+ }
+
+ /// Set the node's unrounded layout
+ fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout);
+
+ /// Compute the specified node's size or full layout given the specified constraints
+ fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput;
+}
+
+/// Extends [`LayoutPartialTree`] with the operations needed by the out-of-flow positioning pass
+/// ([`compute_oof_layout`](crate::compute_oof_layout)), which lays out the absolute/fixed boxes
+/// for which a node acts as the containing block.
+///
+/// This trait is required by [`compute_oof_layout`](crate::compute_oof_layout) and
+/// [`compute_root_layout`](crate::compute_root_layout).
+pub trait LayoutContainingBlock: LayoutPartialTree {
+ /// The style type representing the styles of an out-of-flow (absolute/fixed) box being
+ /// positioned by its containing block
+ type OofItemStyle<'a>: OofItemStyle<CustomIdent = Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// Get the style of an out-of-flow box being positioned by its containing block
+ ///
+ /// Interpreted in the containing block's axes (see [`LayoutPartialTree::get_core_container_style`]).
+ fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_>;
+
+ /// Clear the list of out-of-flow (absolute/fixed) boxes whose containing block is `node_id`.
+ ///
+ /// This is called (exactly once) for each node laid out with `RunMode::PerformLayout`, before
+ /// the boxes it lays out are recorded with [`add_hoisted_children`](Self::add_hoisted_children),
+ /// so that lists recorded by previous layout runs do not persist.
+ fn clear_hoisted_children(&mut self, node_id: NodeId);
+
+ /// Append to the list of out-of-flow boxes whose containing block is `node_id`.
+ ///
+ /// This is called by each containing block for the boxes it lays out, and by
+ /// [`compute_root_layout`](crate::compute_root_layout) to record boxes (e.g. `position: fixed`
+ /// boxes) which are positioned by the final root positioning pass, which runs after the root
+ /// node's own layout algorithm has already recorded its list. The recorded lists are consumed
+ /// by [`round_layout`](crate::round_layout) (out-of-flow boxes are rounded via their
+ /// containing block rather than via their parent), and are also useful for consumers
+ /// implementing paint/hit-testing traversals.
+ fn add_hoisted_children(&mut self, node_id: NodeId, hoisted: &[NodeId]);
+
+ /// Read back the detailed layout information most recently recorded for `node_id`
+ /// (as stored by [`LayoutGridContainer::set_detailed_grid_info`]).
+ ///
+ /// This is used by the out-of-flow positioning pass to resolve the grid area of absolutely
+ /// positioned boxes whose containing block is a grid container. Implementing this method is
+ /// optional: the default implementation returns [`DetailedLayoutInfo::None`], in which case
+ /// such boxes are positioned relative to the grid container's padding box instead of their
+ /// grid area.
+ #[inline(always)]
+ fn get_detailed_layout_info(&self, node_id: NodeId) -> &DetailedLayoutInfo<Self::CustomIdent> {
+ let _ = node_id;
+ &DetailedLayoutInfo::None
+ }
+}
+
+/// Trait used by the `compute_cached_layout` method which allows cached layout results to be stored and retrieved.
+///
+/// The `Cache` struct implements a per-node cache that is compatible with this trait.
+pub trait CacheTree {
+ /// Try to retrieve a cached result from the cache
+ fn cache_get(&mut self, node_id: NodeId, input: &LayoutInput) -> Option<LayoutOutput>;
+
+ /// Store a computed size in the cache
+ fn cache_store(&mut self, node_id: NodeId, input: &LayoutInput, layout_output: LayoutOutput);
+
+ /// Clear all cache entries for the node
+ fn cache_clear(&mut self, node_id: NodeId);
+}
+
+/// Trait used by the `round_layout` method which takes a tree of unrounded float-valued layouts and performs
+/// rounding to snap the values to the pixel grid.
+///
+/// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
+pub trait RoundTree: TraverseTree {
+ /// Get the node's unrounded layout
+ fn get_unrounded_layout(&self, node_id: NodeId) -> Layout;
+ /// Get a reference to the node's final layout
+ fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout);
+ /// Whether the node is an out-of-flow (absolute/fixed) box. Out-of-flow boxes are hoisted to
+ /// their containing block, so [`round_layout`](crate::round_layout) skips them when visiting a
+ /// node's children and instead visits them via their containing block's hoisted child list.
+ ///
+ /// This should return `true` for box-generating nodes whose position style is `absolute` or
+ /// `fixed`, and `false` otherwise (including for `display: none` nodes).
+ fn is_out_of_flow(&self, node_id: NodeId) -> bool;
+ /// The number of out-of-flow boxes whose containing block is `node_id`
+ /// (as recorded by [`LayoutContainingBlock::add_hoisted_children`])
+ fn hoisted_child_count(&self, node_id: NodeId) -> usize;
+ /// Get the nth out-of-flow box whose containing block is `node_id`
+ /// (as recorded by [`LayoutContainingBlock::add_hoisted_children`])
+ fn get_hoisted_child_id(&self, node_id: NodeId, index: usize) -> NodeId;
+}
+
+/// Trait used by the `print_tree` method which prints a debug representation
+///
+/// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
+pub trait PrintTree: TraverseTree {
+ /// Get a debug label for the node (typically the type of node: flexbox, grid, text, image, etc)
+ fn get_debug_label(&self, node_id: NodeId) -> &'static str;
+ /// Get a reference to the node's final layout
+ fn get_final_layout(&self, node_id: NodeId) -> Layout;
+}
+
+#[cfg(feature = "flexbox")]
+/// Extends [`LayoutPartialTree`] with getters for the styles required for Flexbox layout
+pub trait LayoutFlexboxContainer: LayoutPartialTree {
+ /// The style type representing the Flexbox container's styles
+ type FlexboxContainerStyle<'a>: FlexboxContainerStyle
+ where
+ Self: 'a;
+ /// The style type representing each Flexbox item's styles
+ type FlexboxItemStyle<'a>: FlexboxItemStyle
+ where
+ Self: 'a;
+
+ /// Get the container's styles
+ fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_>;
+
+ /// Get the child's styles
+ ///
+ /// Interpreted in the container's axes (see [`LayoutPartialTree::get_core_container_style`]).
+ fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_>;
+}
+
+#[cfg(feature = "grid")]
+/// Extends [`LayoutPartialTree`] with getters for the styles required for CSS Grid layout
+pub trait LayoutGridContainer: LayoutPartialTree {
+ /// The style type representing the CSS Grid container's styles
+ type GridContainerStyle<'a>: GridContainerStyle<CustomIdent = Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// The style type representing each CSS Grid item's styles
+ type GridItemStyle<'a>: GridItemStyle<CustomIdent = Self::CustomIdent>
+ where
+ Self: 'a;
+
+ /// Get the container's styles
+ fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_>;
+
+ /// Get the child's styles
+ ///
+ /// Interpreted in the container's axes (see [`LayoutPartialTree::get_core_container_style`]).
+ fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_>;
+
+ /// Set the node's detailed grid information
+ ///
+ /// Implementing this method is optional. Doing so allows you to access details about the the grid such as
+ /// the computed size of each grid track and the computed placement of each grid item.
+ fn set_detailed_grid_info(&mut self, _node_id: NodeId, _detailed_grid_info: DetailedGridInfo<Self::CustomIdent>) {
+ debug_log!("LayoutGridContainer::set_detailed_grid_info called");
+ }
+}
+
+#[cfg(feature = "block_layout")]
+/// Extends [`LayoutPartialTree`] with getters for the styles required for CSS Block layout
+pub trait LayoutBlockContainer: LayoutPartialTree {
+ /// The style type representing the CSS Block container's styles
+ type BlockContainerStyle<'a>: BlockContainerStyle
+ where
+ Self: 'a;
+ /// The style type representing each CSS Block item's styles
+ type BlockItemStyle<'a>: BlockItemStyle
+ where
+ Self: 'a;
+
+ /// Get the container's styles
+ fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_>;
+
+ /// Get the child's styles
+ ///
+ /// Interpreted in the container's axes (see [`LayoutPartialTree::get_core_container_style`]).
+ fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_>;
+
+ /// Compute the specified node's size or full layout given the specified constraints
+ #[cfg(feature = "block_layout")]
+ fn compute_block_child_layout(
+ &mut self,
+ node_id: NodeId,
+ inputs: LayoutInput,
+ block_ctx: Option<&mut BlockContext<'_>>,
+ ) -> LayoutOutput {
+ let _ = block_ctx;
+ self.compute_child_layout(node_id, inputs)
+ }
+}
+
+// --- PRIVATE TRAITS
+
+/// A private trait which allows us to add extra convenience methods to types which implement
+/// LayoutTree without making those methods public.
+pub(crate) trait LayoutPartialTreeExt: LayoutPartialTree {
+ /// Compute the size of the node given the specified constraints
+ #[inline(always)]
+ #[allow(clippy::too_many_arguments)]
+ fn measure_child_size(
+ &mut self,
+ node_id: NodeId,
+ known_dimensions: Size<Option<f32>>,
+ parent_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+ sizing_mode: SizingMode,
+ axis: AbsoluteAxis,
+ vertical_margins_are_collapsible: Line<bool>,
+ ) -> f32 {
+ self.compute_child_layout(
+ node_id,
+ LayoutInput {
+ known_dimensions,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size,
+ available_space,
+ sizing_mode,
+ axis: axis.into(),
+ run_mode: RunMode::ComputeSize,
+ vertical_margins_are_collapsible,
+ },
+ )
+ .size
+ .get_abs(axis)
+ }
+
+ /// Compute the size of the node given the specified constraints
+ #[inline(always)]
+ #[allow(clippy::too_many_arguments)]
+ fn measure_child_size_both(
+ &mut self,
+ node_id: NodeId,
+ known_dimensions: Size<Option<f32>>,
+ parent_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+ sizing_mode: SizingMode,
+ vertical_margins_are_collapsible: Line<bool>,
+ ) -> Size<f32> {
+ self.compute_child_layout(
+ node_id,
+ LayoutInput {
+ known_dimensions,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size,
+ available_space,
+ sizing_mode,
+ axis: RequestedAxis::Both,
+ run_mode: RunMode::ComputeSize,
+ vertical_margins_are_collapsible,
+ },
+ )
+ .size
+ }
+
+ /// Perform a full layout on the node given the specified constraints
+ #[inline(always)]
+ fn perform_child_layout(
+ &mut self,
+ node_id: NodeId,
+ known_dimensions: Size<Option<f32>>,
+ parent_size: Size<Option<f32>>,
+ available_space: Size<AvailableSpace>,
+ sizing_mode: SizingMode,
+ vertical_margins_are_collapsible: Line<bool>,
+ ) -> LayoutOutput {
+ self.compute_child_layout(
+ node_id,
+ LayoutInput {
+ known_dimensions,
+ known_dimensions_are_definite: Size { width: true, height: true },
+ parent_size,
+ available_space,
+ sizing_mode,
+ axis: RequestedAxis::Both,
+ run_mode: RunMode::PerformLayout,
+ vertical_margins_are_collapsible,
+ },
+ )
+ }
+
+ /// Alias to `resolve_calc_value` with a shorter function name
+ #[inline(always)]
+ #[cfg(feature = "calc")]
+ fn calc(&self, val: *const (), basis: f32) -> f32 {
+ self.resolve_calc_value(val, basis)
+ }
+
+ /// Alias to `resolve_calc_value` with a shorter function name
+ #[inline(always)]
+ #[cfg(not(feature = "calc"))]
+ fn calc(&self, _val: *const (), _basis: f32) -> f32 {
+ 0.0
+ }
+}
+
+impl<T: LayoutPartialTree> LayoutPartialTreeExt for T {}
diff --git a/vendor/taffy/src/util/debug.rs b/vendor/taffy/src/util/debug.rs
new file mode 100644
index 00000000..ad693247
--- /dev/null
+++ b/vendor/taffy/src/util/debug.rs
@@ -0,0 +1,143 @@
+#![allow(dead_code)]
+
+#[cfg(any(feature = "debug", feature = "profile"))]
+use core::fmt::{Debug, Display, Write};
+#[cfg(any(feature = "debug", feature = "profile"))]
+use std::sync::Mutex;
+
+#[doc(hidden)]
+#[cfg(any(feature = "debug", feature = "profile"))]
+pub struct DebugLogger {
+ stack: Mutex<Vec<String>>,
+}
+
+#[cfg(any(feature = "debug", feature = "profile"))]
+static EMPTY_STRING: String = String::new();
+#[cfg(any(feature = "debug", feature = "profile"))]
+impl DebugLogger {
+ pub const fn new() -> Self {
+ Self { stack: Mutex::new(Vec::new()) }
+ }
+
+ pub fn push_node(&self, new_key: crate::NodeId) {
+ let mut stack = self.stack.lock().unwrap();
+ let mut key_string = String::new();
+ write!(&mut key_string, "{:?}", new_key).unwrap();
+ stack.push(key_string);
+ }
+
+ pub fn pop_node(&self) {
+ let mut stack = self.stack.lock().unwrap();
+ stack.pop();
+ }
+
+ pub fn log(&self, message: impl Display) {
+ let stack = self.stack.lock().unwrap();
+ let key = stack.last().unwrap_or(&EMPTY_STRING);
+ let level = stack.len() * 4;
+ let space = " ";
+ println!("{space:level$}{key}: {message}");
+ }
+
+ pub fn labelled_log(&self, label: &str, message: impl Display) {
+ let stack = self.stack.lock().unwrap();
+ let key = stack.last().unwrap_or(&EMPTY_STRING);
+ let level = stack.len() * 4;
+ let space = " ";
+ println!("{space:level$}{key}: {label} {message}");
+ }
+
+ pub fn debug_log(&self, message: impl Debug) {
+ let stack = self.stack.lock().unwrap();
+ let key = stack.last().unwrap_or(&EMPTY_STRING);
+ let level = stack.len() * 4;
+ let space = " ";
+ println!("{space:level$}{key}: {message:?}");
+ }
+
+ pub fn labelled_debug_log(&self, label: &str, message: impl Debug) {
+ let stack = self.stack.lock().unwrap();
+ let key = stack.last().unwrap_or(&EMPTY_STRING);
+ let level = stack.len() * 4;
+ let space = " ";
+ println!("{space:level$}{key}: {label} {message:?}");
+ }
+}
+
+#[cfg(any(feature = "debug", feature = "profile"))]
+pub(crate) static NODE_LOGGER: DebugLogger = DebugLogger::new();
+
+macro_rules! debug_log {
+ // String literal label with debug printing
+ ($label:literal, dbg:$item:expr) => {{
+ #[cfg(feature = "debug")]
+ $crate::util::debug::NODE_LOGGER.labelled_debug_log($label, $item);
+ }};
+ // String literal label with display printing
+ ($label:literal, $item:expr) => {{
+ #[cfg(feature = "debug")]
+ $crate::util::debug::NODE_LOGGER.labelled_log($label, $item);
+ }};
+ // Debug printing
+ (dbg:$item:expr) => {{
+ #[cfg(feature = "debug")]
+ $crate::util::debug::NODE_LOGGER.debug_log($item);
+ }};
+ // Display printing
+ ($item:expr) => {{
+ #[cfg(feature = "debug")]
+ $crate::util::debug::NODE_LOGGER.log($item);
+ }};
+ // Blank newline
+ () => {{
+ #[cfg(feature = "debug")]
+ println!();
+ }};
+}
+
+macro_rules! debug_log_node {
+ ($inputs: expr) => {
+ debug_log!(dbg:$inputs.run_mode);
+ debug_log!("sizing_mode", dbg:$inputs.sizing_mode);
+ debug_log!("known_dimensions", dbg:$inputs.known_dimensions);
+ debug_log!("parent_size", dbg:$inputs.parent_size);
+ debug_log!("available_space", dbg:$inputs.available_space);
+ };
+}
+
+macro_rules! debug_push_node {
+ ($node_id:expr) => {
+ #[cfg(any(feature = "debug", feature = "profile"))]
+ $crate::util::debug::NODE_LOGGER.push_node($node_id);
+ debug_log!("");
+ };
+}
+
+macro_rules! debug_pop_node {
+ () => {
+ #[cfg(any(feature = "debug", feature = "profile"))]
+ $crate::util::debug::NODE_LOGGER.pop_node();
+ };
+}
+
+#[cfg(feature = "profile")]
+#[allow(unused_macros)]
+macro_rules! time {
+ ($label:expr, $($code:tt)*) => {
+ let start = ::std::time::Instant::now();
+ $($code)*
+ let duration = ::std::time::Instant::now().duration_since(start);
+ crate::util::debug::NODE_LOGGER.log(format_args!("Performed {} in {}ms", $label, duration.as_millis()));
+ };
+}
+
+#[cfg(not(feature = "profile"))]
+#[allow(unused_macros)]
+macro_rules! time {
+ ($label:expr, $($code:tt)*) => {
+ $($code)*
+ };
+}
+
+#[allow(unused_imports)]
+pub(crate) use {debug_log, debug_log_node, debug_pop_node, debug_push_node, time};
diff --git a/vendor/taffy/src/util/front_back_vec_builder.rs b/vendor/taffy/src/util/front_back_vec_builder.rs
new file mode 100644
index 00000000..b82c387f
--- /dev/null
+++ b/vendor/taffy/src/util/front_back_vec_builder.rs
@@ -0,0 +1,168 @@
+//! A fixed-capacity `Vec` builder that can be filled from both ends
+use crate::util::sys::Vec;
+
+/// Builds a `Vec` of a fixed length that is known up front by pushing items to either its front or its back.
+///
+/// Items pushed to the front end up at the start of the `Vec` in the order that they were pushed. Items pushed to the
+/// back end up at the end of the `Vec` in the reverse of the order that they were pushed. This allows a list of items
+/// to be partitioned into two groups in a single pass and with a single allocation.
+///
+/// Exactly `capacity` items must be pushed before calling [`into_vec`](Self::into_vec), which panics otherwise.
+/// If the `FrontBackVecBuilder` is dropped before then (or if too many items are pushed), then items that were
+/// pushed to it are leaked rather than dropped.
+pub(crate) struct FrontBackVecBuilder<T> {
+ /// The underlying storage. Its length is kept at zero until `into_vec` is called, and its allocated capacity
+ /// is at least `capacity`.
+ vec: Vec<T>,
+ /// The total number of items that the `Vec` will contain
+ capacity: usize,
+ /// The number of items pushed to the front. The slots `0..front_len` are initialized.
+ front_len: usize,
+ /// The number of items pushed to the back. The slots `(capacity - back_len)..capacity` are initialized.
+ back_len: usize,
+}
+
+impl<T> FrontBackVecBuilder<T> {
+ /// Create a new `FrontBackVecBuilder` that will contain exactly `capacity` items
+ #[inline(always)]
+ pub(crate) fn with_capacity(capacity: usize) -> Self {
+ Self { vec: Vec::with_capacity(capacity), capacity, front_len: 0, back_len: 0 }
+ }
+
+ /// Add an item after the items that have already been pushed to the front.
+ ///
+ /// Pushing more than `capacity` items in total is not checked here: it either panics or overwrites (and leaks)
+ /// a previously pushed item, and then causes [`into_vec`](Self::into_vec) to panic.
+ #[inline(always)]
+ pub(crate) fn push_front(&mut self, value: T) {
+ self.vec.spare_capacity_mut()[self.front_len].write(value);
+ self.front_len += 1;
+ }
+
+ /// Add an item before the items that have already been pushed to the back.
+ ///
+ /// Pushing more than `capacity` items in total is not checked here: it either panics or overwrites (and leaks)
+ /// a previously pushed item, and then causes [`into_vec`](Self::into_vec) to panic.
+ #[inline(always)]
+ pub(crate) fn push_back(&mut self, value: T) {
+ self.vec.spare_capacity_mut()[self.capacity - self.back_len - 1].write(value);
+ self.back_len += 1;
+ }
+
+ /// Returns the completed `Vec`, along with the number of items that were pushed to the front (which is also
+ /// the index of the first item that was pushed to the back).
+ ///
+ /// Panics if the total number of items that have been pushed is not exactly `capacity`.
+ #[inline(always)]
+ pub(crate) fn into_vec(self) -> (Vec<T>, usize) {
+ let Self { mut vec, capacity, front_len, back_len } = self;
+ assert_eq!(
+ front_len + back_len,
+ capacity,
+ "the number of items pushed to a FrontBackVecBuilder must equal its capacity"
+ );
+ // SAFETY:
+ // - `vec` was allocated with a capacity of at least `capacity` and has not been reallocated since.
+ // - Each `push_front` initializes the slot at index `front_len` and then increments `front_len`, so the
+ // slots `0..front_len` are initialized. Likewise each `push_back` initializes the slot just before the
+ // ones it has already initialized, so the slots `(capacity - back_len)..capacity` are initialized.
+ // (These writes are bounds checked, and writing to a slot that is already initialized is safe).
+ // - `front_len + back_len == capacity` (asserted above), so `capacity - back_len == front_len` and those
+ // two ranges cover all of `0..capacity`.
+ #[allow(unsafe_code)]
+ unsafe {
+ vec.set_len(capacity);
+ }
+ (vec, front_len)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::FrontBackVecBuilder;
+ use crate::util::sys::Vec;
+
+ #[test]
+ fn front_items_keep_their_order_and_back_items_are_reversed() {
+ let mut builder = FrontBackVecBuilder::with_capacity(6);
+ for value in 0..6 {
+ if value % 2 == 0 {
+ builder.push_front(value);
+ } else {
+ builder.push_back(value);
+ }
+ }
+ let (vec, front_len) = builder.into_vec();
+ assert_eq!(vec, [0, 2, 4, 5, 3, 1]);
+ assert_eq!(front_len, 3);
+ }
+
+ #[test]
+ fn all_items_pushed_to_one_end() {
+ let mut builder = FrontBackVecBuilder::with_capacity(3);
+ (0..3).for_each(|value| builder.push_front(value));
+ assert_eq!(builder.into_vec(), (Vec::from([0, 1, 2]), 3));
+
+ let mut builder = FrontBackVecBuilder::with_capacity(3);
+ (0..3).for_each(|value| builder.push_back(value));
+ assert_eq!(builder.into_vec(), (Vec::from([2, 1, 0]), 0));
+ }
+
+ #[test]
+ fn zero_capacity() {
+ let (vec, front_len) = FrontBackVecBuilder::<u8>::with_capacity(0).into_vec();
+ assert!(vec.is_empty());
+ assert_eq!(front_len, 0);
+ }
+
+ #[test]
+ fn owned_items_are_moved_into_the_vec() {
+ let mut builder = FrontBackVecBuilder::with_capacity(2);
+ builder.push_back(Vec::from([1, 2]));
+ builder.push_front(Vec::from([3]));
+ let (vec, front_len) = builder.into_vec();
+ assert_eq!(vec, [Vec::from([3]), Vec::from([1, 2])]);
+ assert_eq!(front_len, 1);
+ }
+
+ #[test]
+ #[should_panic(expected = "must equal its capacity")]
+ fn pushing_too_many_items_to_the_front_panics_in_into_vec() {
+ let mut builder = FrontBackVecBuilder::with_capacity(1);
+ builder.push_back(1);
+ builder.push_front(2);
+ let _ = builder.into_vec();
+ }
+
+ #[test]
+ #[should_panic(expected = "must equal its capacity")]
+ fn pushing_too_many_items_to_the_back_panics_in_into_vec() {
+ let mut builder = FrontBackVecBuilder::with_capacity(1);
+ builder.push_front(1);
+ builder.push_back(2);
+ let _ = builder.into_vec();
+ }
+
+ #[test]
+ #[should_panic]
+ fn push_front_out_of_bounds_panics() {
+ let mut builder = FrontBackVecBuilder::with_capacity(0);
+ builder.push_front(1);
+ }
+
+ #[test]
+ #[should_panic]
+ fn push_back_out_of_bounds_panics() {
+ let mut builder = FrontBackVecBuilder::with_capacity(1);
+ builder.push_back(1);
+ builder.push_back(2);
+ }
+
+ #[test]
+ #[should_panic(expected = "must equal its capacity")]
+ fn into_vec_before_full_panics() {
+ let mut builder = FrontBackVecBuilder::with_capacity(2);
+ builder.push_front(1);
+ let _ = builder.into_vec();
+ }
+}
diff --git a/vendor/taffy/src/util/math.rs b/vendor/taffy/src/util/math.rs
new file mode 100644
index 00000000..35f5f60f
--- /dev/null
+++ b/vendor/taffy/src/util/math.rs
@@ -0,0 +1,356 @@
+//! Contains numerical helper traits and functions
+#![allow(clippy::manual_clamp)]
+
+use crate::geometry::Size;
+use crate::style::AvailableSpace;
+
+/// A trait to conveniently calculate minimums and maximums when some data may not be defined
+///
+/// If the left-hand value is [`None`], these operations return [`None`].
+/// If the right-hand value is [`None`], it is treated as zero.
+pub trait MaybeMath<In, Out> {
+ /// Returns the minimum of `self` and `rhs`
+ fn maybe_min(self, rhs: In) -> Out;
+
+ /// Returns the maximum of `self` and `rhs`
+ fn maybe_max(self, rhs: In) -> Out;
+
+ /// Returns `self` clamped between `min` and `max`
+ fn maybe_clamp(self, min: In, max: In) -> Out;
+
+ /// Adds `self` and `rhs`.
+ fn maybe_add(self, rhs: In) -> Out;
+
+ /// Subtracts rhs from `self`, treating [`None`] values as default
+ fn maybe_sub(self, rhs: In) -> Out;
+}
+
+impl MaybeMath<Option<f32>, Option<f32>> for Option<f32> {
+ fn maybe_min(self, rhs: Option<f32>) -> Option<f32> {
+ match (self, rhs) {
+ (Some(l), Some(r)) => Some(l.min(r)),
+ (Some(_l), None) => self,
+ (None, Some(_r)) => None,
+ (None, None) => None,
+ }
+ }
+
+ fn maybe_max(self, rhs: Option<f32>) -> Option<f32> {
+ match (self, rhs) {
+ (Some(l), Some(r)) => Some(l.max(r)),
+ (Some(_l), None) => self,
+ (None, Some(_r)) => None,
+ (None, None) => None,
+ }
+ }
+
+ fn maybe_clamp(self, min: Option<f32>, max: Option<f32>) -> Option<f32> {
+ match (self, min, max) {
+ (Some(base), Some(min), Some(max)) => Some(base.min(max).max(min)),
+ (Some(base), None, Some(max)) => Some(base.min(max)),
+ (Some(base), Some(min), None) => Some(base.max(min)),
+ (Some(_), None, None) => self,
+ (None, _, _) => None,
+ }
+ }
+
+ fn maybe_add(self, rhs: Option<f32>) -> Option<f32> {
+ match (self, rhs) {
+ (Some(l), Some(r)) => Some(l + r),
+ (Some(_l), None) => self,
+ (None, Some(_r)) => None,
+ (None, None) => None,
+ }
+ }
+
+ fn maybe_sub(self, rhs: Option<f32>) -> Option<f32> {
+ match (self, rhs) {
+ (Some(l), Some(r)) => Some(l - r),
+ (Some(_l), None) => self,
+ (None, Some(_r)) => None,
+ (None, None) => None,
+ }
+ }
+}
+
+impl MaybeMath<f32, Option<f32>> for Option<f32> {
+ fn maybe_min(self, rhs: f32) -> Option<f32> {
+ self.map(|val| val.min(rhs))
+ }
+
+ fn maybe_max(self, rhs: f32) -> Option<f32> {
+ self.map(|val| val.max(rhs))
+ }
+
+ fn maybe_clamp(self, min: f32, max: f32) -> Option<f32> {
+ self.map(|val| val.min(max).max(min))
+ }
+
+ fn maybe_add(self, rhs: f32) -> Option<f32> {
+ self.map(|val| val + rhs)
+ }
+
+ fn maybe_sub(self, rhs: f32) -> Option<f32> {
+ self.map(|val| val - rhs)
+ }
+}
+
+impl MaybeMath<Option<f32>, f32> for f32 {
+ fn maybe_min(self, rhs: Option<f32>) -> f32 {
+ match rhs {
+ Some(val) => self.min(val),
+ None => self,
+ }
+ }
+
+ fn maybe_max(self, rhs: Option<f32>) -> f32 {
+ match rhs {
+ Some(val) => self.max(val),
+ None => self,
+ }
+ }
+
+ fn maybe_clamp(self, min: Option<f32>, max: Option<f32>) -> f32 {
+ match (min, max) {
+ (Some(min), Some(max)) => self.min(max).max(min),
+ (None, Some(max)) => self.min(max),
+ (Some(min), None) => self.max(min),
+ (None, None) => self,
+ }
+ }
+
+ fn maybe_add(self, rhs: Option<f32>) -> f32 {
+ match rhs {
+ Some(val) => self + val,
+ None => self,
+ }
+ }
+
+ fn maybe_sub(self, rhs: Option<f32>) -> f32 {
+ match rhs {
+ Some(val) => self - val,
+ None => self,
+ }
+ }
+}
+
+impl MaybeMath<f32, AvailableSpace> for AvailableSpace {
+ fn maybe_min(self, rhs: f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(val.min(rhs)),
+ AvailableSpace::MinContent => AvailableSpace::Definite(rhs),
+ AvailableSpace::MaxContent => AvailableSpace::Definite(rhs),
+ }
+ }
+ fn maybe_max(self, rhs: f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(val.max(rhs)),
+ AvailableSpace::MinContent => AvailableSpace::MinContent,
+ AvailableSpace::MaxContent => AvailableSpace::MaxContent,
+ }
+ }
+
+ fn maybe_clamp(self, min: f32, max: f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(val.min(max).max(min)),
+ AvailableSpace::MinContent => AvailableSpace::MinContent,
+ AvailableSpace::MaxContent => AvailableSpace::MaxContent,
+ }
+ }
+
+ fn maybe_add(self, rhs: f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(val + rhs),
+ AvailableSpace::MinContent => AvailableSpace::MinContent,
+ AvailableSpace::MaxContent => AvailableSpace::MaxContent,
+ }
+ }
+ fn maybe_sub(self, rhs: f32) -> AvailableSpace {
+ match self {
+ AvailableSpace::Definite(val) => AvailableSpace::Definite(val - rhs),
+ AvailableSpace::MinContent => AvailableSpace::MinContent,
+ AvailableSpace::MaxContent => AvailableSpace::MaxContent,
+ }
+ }
+}
+
+impl MaybeMath<Option<f32>, AvailableSpace> for AvailableSpace {
+ fn maybe_min(self, rhs: Option<f32>) -> AvailableSpace {
+ match (self, rhs) {
+ (AvailableSpace::Definite(val), Some(rhs)) => AvailableSpace::Definite(val.min(rhs)),
+ (AvailableSpace::Definite(val), None) => AvailableSpace::Definite(val),
+ (AvailableSpace::MinContent, Some(rhs)) => AvailableSpace::Definite(rhs),
+ (AvailableSpace::MinContent, None) => AvailableSpace::MinContent,
+ (AvailableSpace::MaxContent, Some(rhs)) => AvailableSpace::Definite(rhs),
+ (AvailableSpace::MaxContent, None) => AvailableSpace::MaxContent,
+ }
+ }
+ fn maybe_max(self, rhs: Option<f32>) -> AvailableSpace {
+ match (self, rhs) {
+ (AvailableSpace::Definite(val), Some(rhs)) => AvailableSpace::Definite(val.max(rhs)),
+ (AvailableSpace::Definite(val), None) => AvailableSpace::Definite(val),
+ (AvailableSpace::MinContent, _) => AvailableSpace::MinContent,
+ (AvailableSpace::MaxContent, _) => AvailableSpace::MaxContent,
+ }
+ }
+
+ fn maybe_clamp(self, min: Option<f32>, max: Option<f32>) -> AvailableSpace {
+ match (self, min, max) {
+ (AvailableSpace::Definite(val), Some(min), Some(max)) => AvailableSpace::Definite(val.min(max).max(min)),
+ (AvailableSpace::Definite(val), None, Some(max)) => AvailableSpace::Definite(val.min(max)),
+ (AvailableSpace::Definite(val), Some(min), None) => AvailableSpace::Definite(val.max(min)),
+ (AvailableSpace::Definite(val), None, None) => AvailableSpace::Definite(val),
+ (AvailableSpace::MinContent, _, _) => AvailableSpace::MinContent,
+ (AvailableSpace::MaxContent, _, _) => AvailableSpace::MaxContent,
+ }
+ }
+
+ fn maybe_add(self, rhs: Option<f32>) -> AvailableSpace {
+ match (self, rhs) {
+ (AvailableSpace::Definite(val), Some(rhs)) => AvailableSpace::Definite(val + rhs),
+ (AvailableSpace::Definite(val), None) => AvailableSpace::Definite(val),
+ (AvailableSpace::MinContent, _) => AvailableSpace::MinContent,
+ (AvailableSpace::MaxContent, _) => AvailableSpace::MaxContent,
+ }
+ }
+ fn maybe_sub(self, rhs: Option<f32>) -> AvailableSpace {
+ match (self, rhs) {
+ (AvailableSpace::Definite(val), Some(rhs)) => AvailableSpace::Definite(val - rhs),
+ (AvailableSpace::Definite(val), None) => AvailableSpace::Definite(val),
+ (AvailableSpace::MinContent, _) => AvailableSpace::MinContent,
+ (AvailableSpace::MaxContent, _) => AvailableSpace::MaxContent,
+ }
+ }
+}
+
+impl<In, Out, T: MaybeMath<In, Out>> MaybeMath<Size<In>, Size<Out>> for Size<T> {
+ fn maybe_min(self, rhs: Size<In>) -> Size<Out> {
+ Size { width: self.width.maybe_min(rhs.width), height: self.height.maybe_min(rhs.height) }
+ }
+
+ fn maybe_max(self, rhs: Size<In>) -> Size<Out> {
+ Size { width: self.width.maybe_max(rhs.width), height: self.height.maybe_max(rhs.height) }
+ }
+
+ fn maybe_clamp(self, min: Size<In>, max: Size<In>) -> Size<Out> {
+ Size {
+ width: self.width.maybe_clamp(min.width, max.width),
+ height: self.height.maybe_clamp(min.height, max.height),
+ }
+ }
+
+ fn maybe_add(self, rhs: Size<In>) -> Size<Out> {
+ Size { width: self.width.maybe_add(rhs.width), height: self.height.maybe_add(rhs.height) }
+ }
+
+ fn maybe_sub(self, rhs: Size<In>) -> Size<Out> {
+ Size { width: self.width.maybe_sub(rhs.width), height: self.height.maybe_sub(rhs.height) }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ mod lhs_option_f32_rhs_option_f32 {
+ use crate::util::MaybeMath;
+
+ #[test]
+ fn test_maybe_min() {
+ assert_eq!(Some(3.0).maybe_min(Some(5.0)), Some(3.0));
+ assert_eq!(Some(5.0).maybe_min(Some(3.0)), Some(3.0));
+ assert_eq!(Some(3.0).maybe_min(None), Some(3.0));
+ assert_eq!(None.maybe_min(Some(3.0)), None);
+ assert_eq!(None.maybe_min(None), None);
+ }
+
+ #[test]
+ fn test_maybe_max() {
+ assert_eq!(Some(3.0).maybe_max(Some(5.0)), Some(5.0));
+ assert_eq!(Some(5.0).maybe_max(Some(3.0)), Some(5.0));
+ assert_eq!(Some(3.0).maybe_max(None), Some(3.0));
+ assert_eq!(None.maybe_max(Some(3.0)), None);
+ assert_eq!(None.maybe_max(None), None);
+ }
+
+ #[test]
+ fn test_maybe_add() {
+ assert_eq!(Some(3.0).maybe_add(Some(5.0)), Some(8.0));
+ assert_eq!(Some(5.0).maybe_add(Some(3.0)), Some(8.0));
+ assert_eq!(Some(3.0).maybe_add(None), Some(3.0));
+ assert_eq!(None.maybe_add(Some(3.0)), None);
+ assert_eq!(None.maybe_add(None), None);
+ }
+
+ #[test]
+ fn test_maybe_sub() {
+ assert_eq!(Some(3.0).maybe_sub(Some(5.0)), Some(-2.0));
+ assert_eq!(Some(5.0).maybe_sub(Some(3.0)), Some(2.0));
+ assert_eq!(Some(3.0).maybe_sub(None), Some(3.0));
+ assert_eq!(None.maybe_sub(Some(3.0)), None);
+ assert_eq!(None.maybe_sub(None), None);
+ }
+ }
+
+ mod lhs_option_f32_rhs_f32 {
+ use crate::util::MaybeMath;
+
+ #[test]
+ fn test_maybe_min() {
+ assert_eq!(Some(3.0).maybe_min(5.0), Some(3.0));
+ assert_eq!(Some(5.0).maybe_min(3.0), Some(3.0));
+ assert_eq!(None.maybe_min(3.0), None);
+ }
+
+ #[test]
+ fn test_maybe_max() {
+ assert_eq!(Some(3.0).maybe_max(5.0), Some(5.0));
+ assert_eq!(Some(5.0).maybe_max(3.0), Some(5.0));
+ assert_eq!(None.maybe_max(3.0), None);
+ }
+
+ #[test]
+ fn test_maybe_add() {
+ assert_eq!(Some(3.0).maybe_add(5.0), Some(8.0));
+ assert_eq!(Some(5.0).maybe_add(3.0), Some(8.0));
+ assert_eq!(None.maybe_add(3.0), None);
+ }
+
+ #[test]
+ fn test_maybe_sub() {
+ assert_eq!(Some(3.0).maybe_sub(5.0), Some(-2.0));
+ assert_eq!(Some(5.0).maybe_sub(3.0), Some(2.0));
+ assert_eq!(None.maybe_sub(3.0), None);
+ }
+ }
+
+ mod lhs_f32_rhs_option_f32 {
+ use crate::util::MaybeMath;
+
+ #[test]
+ fn test_maybe_min() {
+ assert_eq!(3.0.maybe_min(Some(5.0)), 3.0);
+ assert_eq!(5.0.maybe_min(Some(3.0)), 3.0);
+ assert_eq!(3.0.maybe_min(None), 3.0);
+ }
+
+ #[test]
+ fn test_maybe_max() {
+ assert_eq!(3.0.maybe_max(Some(5.0)), 5.0);
+ assert_eq!(5.0.maybe_max(Some(3.0)), 5.0);
+ assert_eq!(3.0.maybe_max(None), 3.0);
+ }
+
+ #[test]
+ fn test_maybe_add() {
+ assert_eq!(3.0.maybe_add(Some(5.0)), 8.0);
+ assert_eq!(5.0.maybe_add(Some(3.0)), 8.0);
+ assert_eq!(3.0.maybe_add(None), 3.0);
+ }
+
+ #[test]
+ fn test_maybe_sub() {
+ assert_eq!(3.0.maybe_sub(Some(5.0)), -2.0);
+ assert_eq!(5.0.maybe_sub(Some(3.0)), 2.0);
+ assert_eq!(3.0.maybe_sub(None), 3.0);
+ }
+ }
+}
diff --git a/vendor/taffy/src/util/mod.rs b/vendor/taffy/src/util/mod.rs
new file mode 100644
index 00000000..26c78e26
--- /dev/null
+++ b/vendor/taffy/src/util/mod.rs
@@ -0,0 +1,41 @@
+//! Helpful misc. utilities such as a function to debug print a tree
+mod math;
+mod resolve;
+pub(crate) mod sys;
+
+pub use math::MaybeMath;
+pub use resolve::{MaybeResolve, ResolveOrZero};
+
+#[cfg(feature = "grid")]
+mod front_back_vec_builder;
+#[cfg(feature = "grid")]
+pub(crate) use front_back_vec_builder::FrontBackVecBuilder;
+
+#[doc(hidden)]
+#[macro_use]
+pub(crate) mod debug;
+
+#[cfg(feature = "std")]
+mod print;
+#[cfg(feature = "std")]
+pub use print::print_tree;
+#[cfg(feature = "std")]
+pub use print::write_tree;
+
+#[cfg(feature = "parse")]
+pub(crate) mod parse;
+#[cfg(feature = "parse")]
+pub use parse::{ParseError, ParseResult};
+
+/// Deserialize a type `S` by deserializing a string, then using the `FromStr`
+/// impl of `S` to create the result. The generic type `S` is not required to
+/// implement `Deserialize`.
+#[cfg(feature = "serde")]
+pub(crate) fn deserialize_from_str<'de, S, D>(deserializer: D) -> Result<S, D::Error>
+where
+ S: for<'a> From<&'a str>,
+ D: serde::Deserializer<'de>,
+{
+ let s: crate::util::sys::String = serde::Deserialize::deserialize(deserializer)?;
+ Ok(S::from(&s))
+}
diff --git a/vendor/taffy/src/util/parse.rs b/vendor/taffy/src/util/parse.rs
new file mode 100644
index 00000000..24743fbb
--- /dev/null
+++ b/vendor/taffy/src/util/parse.rs
@@ -0,0 +1,118 @@
+//! Helpers for parsing style types from strings
+
+use cssparser::BasicParseError;
+pub(crate) use cssparser::{Parser, ParserInput, Token};
+use std::borrow::Cow;
+
+/// Error type for parsing a type from `cssparser::Parser`
+pub(crate) type CssParseError<'i> = cssparser::ParseError<'i, Cow<'i, str>>;
+
+/// Result type for parsing a type from `cssparser::Parser`
+pub(crate) type CssParseResult<'i, T> = Result<T, CssParseError<'i>>;
+
+/// Error type for parsing a type from string
+#[derive(Clone, Debug)]
+pub struct ParseError(String);
+
+impl core::fmt::Display for ParseError {
+ fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(fmt, "{}", &self.0)
+ }
+}
+impl<'i> From<CssParseError<'i>> for ParseError {
+ fn from(value: CssParseError<'i>) -> Self {
+ Self(value.to_string())
+ }
+}
+impl<'i> From<BasicParseError<'i>> for ParseError {
+ fn from(value: BasicParseError<'i>) -> Self {
+ Self(CssParseError::from(value).to_string())
+ }
+}
+#[cfg(feature = "std")]
+impl std::error::Error for ParseError {}
+
+/// Result type for parsing a type from string
+pub type ParseResult<T> = Result<T, ParseError>;
+
+/// Trait for parsing a type from a `cssparser::Parser` input
+pub(crate) trait FromCss: Sized {
+ /// Parse type from a `cssparser::Parser` input
+ fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self>;
+}
+
+/// Parse a string into a type that implements `FromCss`, ensuring that the
+/// entire input string is consumed.
+pub(crate) fn parse_css_str_entirely<T: FromCss>(input: &str) -> Result<T, ParseError> {
+ let mut parser_input = ParserInput::new(input);
+ let mut parser = Parser::new(&mut parser_input);
+ parser.parse_entirely(|parser| T::from_css(parser)).map_err(|err| ParseError(err.to_string()))
+}
+
+/// Automatically implement `FromStr` for a type that already implemented `FromCss`
+macro_rules! from_str_from_css {
+ ($ty:ident) => {
+ #[cfg(feature = "parse")]
+ impl core::str::FromStr for $ty {
+ type Err = $crate::ParseError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ $crate::util::parse::parse_css_str_entirely(input)
+ }
+ }
+ };
+}
+pub(crate) use from_str_from_css;
+
+/// Implements the `FromCss` and `FromStr` traits for a simple enum that consists of just keywords
+macro_rules! impl_parse_for_keyword_enum {
+ (
+ // The type name (followed by a comma)
+ $ty:ident,
+
+ // Repeat 1-or-more times
+ $(
+ // 0-or-more metadata attributes (e.g. #[cfg] attributes for conditional compilation)
+ $( #[$meta: meta] )*
+
+ // keyword => enum_variant (e.g. "center" => AlignItems::Center)
+ $keyword:literal => $enum_variant:ident,
+ )+
+ ) => {
+
+ // Impl FromCss for the type
+ impl $crate::util::parse::FromCss for $ty {
+ fn from_css<'i>(input: &mut cssparser::Parser<'i, '_>) -> $crate::util::parse::CssParseResult<'i, Self> {
+
+ // Parse an ident (or return an error)
+ let ident = input.expect_ident()?;
+
+ // Match on the ident (case insensitive)
+ cssparser::match_ignore_ascii_case! { &*ident,
+
+ // Define each item in the macro definition as a match case
+ $(
+ // Add the metadata attributes to the match case
+ $( #[$meta] )*
+ // If the keyword matches, return the corresponding variant of the enum
+ $keyword => return Ok(Self::$enum_variant),
+ )+
+
+ // If none of the cases match the input, return an "unexpected token" error
+ _ => {
+ let ident = ident.clone();
+ Err(input.new_unexpected_token_error(cssparser::Token::Ident(ident)))
+ }
+ }
+ }
+ }
+
+ // Impl FromStr for the type
+ impl core::str::FromStr for $ty {
+ type Err = $crate::ParseError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ $crate::util::parse::parse_css_str_entirely(input)
+ }
+ }
+ };
+}
+pub(crate) use impl_parse_for_keyword_enum;
diff --git a/vendor/taffy/src/util/print.rs b/vendor/taffy/src/util/print.rs
new file mode 100644
index 00000000..4c4f039e
--- /dev/null
+++ b/vendor/taffy/src/util/print.rs
@@ -0,0 +1,80 @@
+//! Contains functions for printing a debug representation of the tree
+use crate::tree::{NodeId, PrintTree};
+use std::io;
+
+/// Prints a debug representation of the computed layout for a tree of nodes, starting with the passed root node.
+pub fn print_tree(tree: &impl PrintTree, root: NodeId) {
+ // Buffer into a string so that output can be captured in tests
+ let mut buffer = Vec::<u8>::new();
+ write_tree(&mut buffer, tree, root).expect("Wrote tree debug representation to Stdout");
+ println!("{}", std::str::from_utf8(&buffer).unwrap());
+}
+
+/// Writes a debug representation of the computed layout to the writer, starting with the passed root node.
+pub fn write_tree(mut writer: impl io::Write, tree: &impl PrintTree, root: NodeId) -> io::Result<()> {
+ writeln!(writer, "TREE")?;
+ write_node(&mut writer, tree, root, false, String::new())?;
+
+ /// Recursive function that writes each node in the tree
+ fn write_node(
+ writer: &mut impl io::Write,
+ tree: &impl PrintTree,
+ node_id: NodeId,
+ has_sibling: bool,
+ lines_string: String,
+ ) -> io::Result<()> {
+ let layout = &tree.get_final_layout(node_id);
+ let display = tree.get_debug_label(node_id);
+ let num_children = tree.child_count(node_id);
+
+ let fork_string = if has_sibling { "├── " } else { "└── " };
+ #[cfg(feature = "content_size")]
+ writeln!(
+ writer,
+ "{lines}{fork} {display} [x: {x:<4} y: {y:<4} w: {width:<4} h: {height:<4} overflow: l:{ol} r:{or} t:{ot} b:{ob}, border: l:{bl} r:{br} t:{bt} b:{bb}, padding: l:{pl} r:{pr} t:{pt} b:{pb}] ({key:?})",
+ lines = lines_string,
+ fork = fork_string,
+ display = display,
+ x = layout.location.x,
+ y = layout.location.y,
+ width = layout.size.width,
+ height = layout.size.height,
+ ol = layout.scrollable_overflow_rect.left,
+ or = layout.scrollable_overflow_rect.right,
+ ot = layout.scrollable_overflow_rect.top,
+ ob = layout.scrollable_overflow_rect.bottom,
+ bl = layout.border.left,
+ br = layout.border.right,
+ bt = layout.border.top,
+ bb = layout.border.bottom,
+ pl = layout.padding.left,
+ pr = layout.padding.right,
+ pt = layout.padding.top,
+ pb = layout.padding.bottom,
+ key = node_id,
+ )?;
+ #[cfg(not(feature = "content_size"))]
+ writeln!(
+ writer,
+ "{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({key:?})",
+ lines = lines_string,
+ fork = fork_string,
+ display = display,
+ x = layout.location.x,
+ y = layout.location.y,
+ width = layout.size.width,
+ height = layout.size.height,
+ key = node_id,
+ );
+ let bar = if has_sibling { "│ " } else { " " };
+ let new_string = lines_string + bar;
+
+ // Recurse into children
+ for (index, child) in tree.child_ids(node_id).enumerate() {
+ let has_sibling = index < num_children - 1;
+ write_node(writer, tree, child, has_sibling, new_string.clone())?;
+ }
+ Ok(())
+ }
+ Ok(())
+}
diff --git a/vendor/taffy/src/util/resolve.rs b/vendor/taffy/src/util/resolve.rs
new file mode 100644
index 00000000..1f578624
--- /dev/null
+++ b/vendor/taffy/src/util/resolve.rs
@@ -0,0 +1,371 @@
+//! Helper trait to calculate dimensions during layout resolution
+
+use crate::geometry::{Rect, Size};
+use crate::style::{Dimension, LengthPercentage, LengthPercentageAuto};
+use crate::style_helpers::TaffyZero;
+use crate::CompactLength;
+
+/// Trait to encapsulate behaviour where we need to resolve from a
+/// potentially context-dependent size or dimension into
+/// a context-independent size or dimension.
+///
+/// Will return a `None` if it unable to resolve.
+pub trait MaybeResolve<In, Out> {
+ /// Resolve a dimension that might be dependent on a context, with `None` as fallback value
+ fn maybe_resolve(self, context: In, calc: impl Fn(*const (), f32) -> f32) -> Out;
+}
+
+/// Trait to encapsulate behaviour where we need to resolve from a
+/// potentially context-dependent size or dimension into
+/// a context-independent size or dimension.
+///
+/// Will return a default value if it unable to resolve.
+pub trait ResolveOrZero<TContext, TOutput: TaffyZero> {
+ /// Resolve a dimension that might be dependent on a context, with a default fallback value
+ fn resolve_or_zero(self, context: TContext, calc: impl Fn(*const (), f32) -> f32) -> TOutput;
+}
+
+impl MaybeResolve<Option<f32>, Option<f32>> for LengthPercentage {
+ /// Converts the given [`LengthPercentage`] into an absolute length
+ /// Can return `None`
+ fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
+ _ => unreachable!(),
+ }
+ }
+}
+
+impl MaybeResolve<Option<f32>, Option<f32>> for LengthPercentageAuto {
+ /// Converts the given [`LengthPercentageAuto`] into an absolute length
+ /// Can return `None`
+ fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::AUTO_TAG => None,
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
+ _ => unreachable!(),
+ }
+ }
+}
+
+impl MaybeResolve<Option<f32>, Option<f32>> for Dimension {
+ /// Converts the given [`Dimension`] into an absolute length
+ ///
+ /// Can return `None`
+ fn maybe_resolve(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
+ match self.0.tag() {
+ CompactLength::AUTO_TAG => None,
+ // The content keyword is only valid for flex-basis. In any other context it behaves as auto.
+ CompactLength::CONTENT_TAG => None,
+ CompactLength::LENGTH_TAG => Some(self.0.value()),
+ CompactLength::PERCENT_TAG => context.map(|dim| dim * self.0.value()),
+ #[cfg(feature = "calc")]
+ _ if self.0.is_plain_calc() => context.map(|dim| calc(self.0.calc_value(), dim)),
+ // Intrinsic sizing keywords cannot be resolved to a definite size out of context.
+ // Layout algorithms that support them must handle them explicitly.
+ _ if self.0.is_sizing_keyword() => None,
+ _ => unreachable!(),
+ }
+ }
+}
+
+// Generic implementation of MaybeResolve for f32 context where MaybeResolve is implemented
+// for Option<f32> context
+impl<T: MaybeResolve<Option<f32>, Option<f32>>> MaybeResolve<f32, Option<f32>> for T {
+ /// Converts the given MaybeResolve value into an absolute length
+ /// Can return `None`
+ fn maybe_resolve(self, context: f32, calc: impl Fn(*const (), f32) -> f32) -> Option<f32> {
+ self.maybe_resolve(Some(context), calc)
+ }
+}
+
+// Generic MaybeResolve for Size
+impl<In, Out, T: MaybeResolve<In, Out>> MaybeResolve<Size<In>, Size<Out>> for Size<T> {
+ /// Converts any `parent`-relative values for size into an absolute size
+ #[inline(always)]
+ fn maybe_resolve(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Size<Out> {
+ Size {
+ width: self.width.maybe_resolve(context.width, &calc),
+ height: self.height.maybe_resolve(context.height, &calc),
+ }
+ }
+}
+
+impl ResolveOrZero<Option<f32>, f32> for LengthPercentage {
+ /// Will return a default value of result is evaluated to `None`
+ fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
+ self.maybe_resolve(context, calc).unwrap_or(0.0)
+ }
+}
+
+impl ResolveOrZero<Option<f32>, f32> for LengthPercentageAuto {
+ /// Will return a default value of result is evaluated to `None`
+ fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
+ self.maybe_resolve(context, calc).unwrap_or(0.0)
+ }
+}
+
+impl ResolveOrZero<Option<f32>, f32> for Dimension {
+ /// Will return a default value of result is evaluated to `None`
+ fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> f32 {
+ self.maybe_resolve(context, calc).unwrap_or(0.0)
+ }
+}
+
+// Generic ResolveOrZero for Size
+impl<In, Out: TaffyZero, T: ResolveOrZero<In, Out>> ResolveOrZero<Size<In>, Size<Out>> for Size<T> {
+ /// Converts any `parent`-relative values for size into an absolute size
+ fn resolve_or_zero(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Size<Out> {
+ Size {
+ width: self.width.resolve_or_zero(context.width, &calc),
+ height: self.height.resolve_or_zero(context.height, &calc),
+ }
+ }
+}
+
+// Generic ResolveOrZero for resolving Rect against Size
+impl<In: Copy, Out: TaffyZero, T: ResolveOrZero<In, Out>> ResolveOrZero<Size<In>, Rect<Out>> for Rect<T> {
+ /// Converts any `parent`-relative values for Rect into an absolute Rect
+ fn resolve_or_zero(self, context: Size<In>, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
+ Rect {
+ left: self.left.resolve_or_zero(context.width, &calc),
+ right: self.right.resolve_or_zero(context.width, &calc),
+ top: self.top.resolve_or_zero(context.height, &calc),
+ bottom: self.bottom.resolve_or_zero(context.height, &calc),
+ }
+ }
+}
+
+// Generic ResolveOrZero for resolving Rect against Option
+impl<Out: TaffyZero, T: ResolveOrZero<Option<f32>, Out>> ResolveOrZero<Option<f32>, Rect<Out>> for Rect<T> {
+ /// Converts any `parent`-relative values for Rect into an absolute Rect
+ #[inline(always)]
+ fn resolve_or_zero(self, context: Option<f32>, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
+ Rect {
+ left: self.left.resolve_or_zero(context, &calc),
+ right: self.right.resolve_or_zero(context, &calc),
+ top: self.top.resolve_or_zero(context, &calc),
+ bottom: self.bottom.resolve_or_zero(context, &calc),
+ }
+ }
+}
+
+// Generic ResolveOrZero for resolving Rect against f32
+impl<Out: TaffyZero, T: ResolveOrZero<f32, Out>> ResolveOrZero<f32, Rect<Out>> for Rect<T> {
+ /// Converts any `parent`-relative values for Rect into an absolute Rect
+ fn resolve_or_zero(self, context: f32, calc: impl Fn(*const (), f32) -> f32) -> Rect<Out> {
+ Rect {
+ left: self.left.resolve_or_zero(context, &calc),
+ right: self.right.resolve_or_zero(context, &calc),
+ top: self.top.resolve_or_zero(context, &calc),
+ bottom: self.bottom.resolve_or_zero(context, &calc),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{MaybeResolve, ResolveOrZero};
+ use crate::style_helpers::TaffyZero;
+ use core::fmt::Debug;
+
+ // MaybeResolve test runner
+ fn mr_case<Lhs, Rhs, Out>(input: Lhs, context: Rhs, expected: Out)
+ where
+ Lhs: MaybeResolve<Rhs, Out>,
+ Out: PartialEq + Debug,
+ {
+ assert_eq!(input.maybe_resolve(context, |_, _| 42.42), expected);
+ }
+
+ // ResolveOrZero test runner
+ fn roz_case<Lhs, Rhs, Out>(input: Lhs, context: Rhs, expected: Out)
+ where
+ Lhs: ResolveOrZero<Rhs, Out>,
+ Out: PartialEq + Debug + TaffyZero,
+ {
+ assert_eq!(input.resolve_or_zero(context, |_, _| 42.42), expected);
+ }
+
+ mod maybe_resolve_dimension {
+ use super::mr_case;
+ use crate::style::Dimension;
+ use crate::style_helpers::*;
+
+ /// `Dimension::Auto` should always return `None`
+ ///
+ /// The parent / context should not affect the outcome.
+ #[test]
+ fn resolve_auto() {
+ mr_case(Dimension::AUTO, None, None);
+ mr_case(Dimension::AUTO, Some(5.0), None);
+ mr_case(Dimension::AUTO, Some(-5.0), None);
+ mr_case(Dimension::AUTO, Some(0.), None);
+ }
+
+ /// `Dimension::Length` should always return `Some(f32)`
+ /// where the f32 value is the inner absolute length.
+ ///
+ /// The parent / context should not affect the outcome.
+ #[test]
+ fn resolve_length() {
+ mr_case(Dimension::from_length(1.0), None, Some(1.0));
+ mr_case(Dimension::from_length(1.0), Some(5.0), Some(1.0));
+ mr_case(Dimension::from_length(1.0), Some(-5.0), Some(1.0));
+ mr_case(Dimension::from_length(1.0), Some(0.), Some(1.0));
+ }
+
+ /// `Dimension::Percent` should return `None` if context is `None`.
+ /// Otherwise it should return `Some(f32)`
+ /// where the f32 value is the inner value of the percent * context value.
+ ///
+ /// The parent / context __should__ affect the outcome.
+ #[test]
+ fn resolve_percent() {
+ mr_case(Dimension::from_percent(1.0), None, None);
+ mr_case(Dimension::from_percent(1.0), Some(5.0), Some(5.0));
+ mr_case(Dimension::from_percent(1.0), Some(-5.0), Some(-5.0));
+ mr_case(Dimension::from_percent(1.0), Some(50.0), Some(50.0));
+ }
+ }
+
+ mod maybe_resolve_size_dimension {
+ use super::mr_case;
+ use crate::geometry::Size;
+ use crate::style::Dimension;
+
+ /// Size<Dimension::Auto> should always return Size<None>
+ ///
+ /// The parent / context should not affect the outcome.
+ #[test]
+ fn maybe_resolve_auto() {
+ mr_case(Size::<Dimension>::auto(), Size::NONE, Size::NONE);
+ mr_case(Size::<Dimension>::auto(), Size::new(5.0, 5.0), Size::NONE);
+ mr_case(Size::<Dimension>::auto(), Size::new(-5.0, -5.0), Size::NONE);
+ mr_case(Size::<Dimension>::auto(), Size::new(0.0, 0.0), Size::NONE);
+ }
+
+ /// Size<Dimension::Length> should always return a Size<Some(f32)>
+ /// where the f32 values are the absolute length.
+ ///
+ /// The parent / context should not affect the outcome.
+ #[test]
+ fn maybe_resolve_length() {
+ mr_case(Size::from_lengths(5.0, 5.0), Size::NONE, Size::new(5.0, 5.0));
+ mr_case(Size::from_lengths(5.0, 5.0), Size::new(5.0, 5.0), Size::new(5.0, 5.0));
+ mr_case(Size::from_lengths(5.0, 5.0), Size::new(-5.0, -5.0), Size::new(5.0, 5.0));
+ mr_case(Size::from_lengths(5.0, 5.0), Size::new(0.0, 0.0), Size::new(5.0, 5.0));
+ }
+
+ /// `Size<Dimension::Percent>` should return `Size<None>` if context is `Size<None>`.
+ /// Otherwise it should return `Size<Some(f32)>`
+ /// where the f32 value is the inner value of the percent * context value.
+ ///
+ /// The context __should__ affect the outcome.
+ #[test]
+ fn maybe_resolve_percent() {
+ mr_case(Size::from_percent(5.0, 5.0), Size::NONE, Size::NONE);
+ mr_case(Size::from_percent(5.0, 5.0), Size::new(5.0, 5.0), Size::new(25.0, 25.0));
+ mr_case(Size::from_percent(5.0, 5.0), Size::new(-5.0, -5.0), Size::new(-25.0, -25.0));
+ mr_case(Size::from_percent(5.0, 5.0), Size::new(0.0, 0.0), Size::new(0.0, 0.0));
+ }
+ }
+
+ mod resolve_or_zero_dimension_to_option_f32 {
+ use super::roz_case;
+ use crate::style::Dimension;
+ use crate::style_helpers::*;
+
+ #[test]
+ fn resolve_or_zero_auto() {
+ roz_case(Dimension::AUTO, None, 0.0);
+ roz_case(Dimension::AUTO, Some(5.0), 0.0);
+ roz_case(Dimension::AUTO, Some(-5.0), 0.0);
+ roz_case(Dimension::AUTO, Some(0.0), 0.0);
+ }
+ #[test]
+ fn resolve_or_zero_length() {
+ roz_case(Dimension::from_length(5.0), None, 5.0);
+ roz_case(Dimension::from_length(5.0), Some(5.0), 5.0);
+ roz_case(Dimension::from_length(5.0), Some(-5.0), 5.0);
+ roz_case(Dimension::from_length(5.0), Some(0.0), 5.0);
+ }
+ #[test]
+ fn resolve_or_zero_percent() {
+ roz_case(Dimension::from_percent(5.0), None, 0.0);
+ roz_case(Dimension::from_percent(5.0), Some(5.0), 25.0);
+ roz_case(Dimension::from_percent(5.0), Some(-5.0), -25.0);
+ roz_case(Dimension::from_percent(5.0), Some(0.0), 0.0);
+ }
+ }
+
+ mod resolve_or_zero_rect_dimension_to_rect {
+ use super::roz_case;
+ use crate::geometry::{Rect, Size};
+ use crate::style::Dimension;
+
+ #[test]
+ fn resolve_or_zero_auto() {
+ roz_case(Rect::<Dimension>::auto(), Size::NONE, Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Size::new(5.0, 5.0), Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Size::new(-5.0, -5.0), Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Size::new(0.0, 0.0), Rect::zero());
+ }
+
+ #[test]
+ fn resolve_or_zero_length() {
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::NONE, Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(5.0, 5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(-5.0, -5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Size::new(0.0, 0.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ }
+
+ #[test]
+ fn resolve_or_zero_percent() {
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::NONE, Rect::zero());
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::new(5.0, 5.0), Rect::new(25.0, 25.0, 25.0, 25.0));
+ roz_case(
+ Rect::from_percent(5.0, 5.0, 5.0, 5.0),
+ Size::new(-5.0, -5.0),
+ Rect::new(-25.0, -25.0, -25.0, -25.0),
+ );
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Size::new(0.0, 0.0), Rect::zero());
+ }
+ }
+
+ mod resolve_or_zero_rect_dimension_to_rect_f32_via_option {
+ use super::roz_case;
+ use crate::geometry::Rect;
+ use crate::style::Dimension;
+
+ #[test]
+ fn resolve_or_zero_auto() {
+ roz_case(Rect::<Dimension>::auto(), None, Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Some(5.0), Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Some(-5.0), Rect::zero());
+ roz_case(Rect::<Dimension>::auto(), Some(0.0), Rect::zero());
+ }
+
+ #[test]
+ fn resolve_or_zero_length() {
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), None, Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(-5.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ roz_case(Rect::from_length(5.0, 5.0, 5.0, 5.0), Some(0.0), Rect::new(5.0, 5.0, 5.0, 5.0));
+ }
+
+ #[test]
+ fn resolve_or_zero_percent() {
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), None, Rect::zero());
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(5.0), Rect::new(25.0, 25.0, 25.0, 25.0));
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(-5.0), Rect::new(-25.0, -25.0, -25.0, -25.0));
+ roz_case(Rect::from_percent(5.0, 5.0, 5.0, 5.0), Some(0.0), Rect::zero());
+ }
+ }
+}
diff --git a/vendor/taffy/src/util/sys.rs b/vendor/taffy/src/util/sys.rs
new file mode 100644
index 00000000..1ee56783
--- /dev/null
+++ b/vendor/taffy/src/util/sys.rs
@@ -0,0 +1,213 @@
+//! Allocator-flexible data types
+
+// When std is enabled, prefer those types
+#[cfg(feature = "std")]
+pub(crate) use self::std::*;
+
+// Otherwise, use the types from the alloc crate
+#[cfg(not(feature = "std"))]
+pub(crate) use self::alloc::*;
+
+/// For when `std` is enabled
+#[cfg(feature = "std")]
+mod std {
+ /// A string
+ pub(crate) type String = std::string::String;
+ /// The default type for representing strings in Taffy styles
+ pub(crate) type DefaultCheapStr = String;
+ /// A map
+ pub(crate) type Map<K, V> = std::collections::HashMap<K, V, std::collections::hash_map::RandomState>;
+ /// An allocation-backend agnostic vector type
+ pub(crate) type Vec<A> = std::vec::Vec<A>;
+ /// An allocation-backend agnostic boxed pointer type
+ pub(crate) type Box<A> = std::boxed::Box<A>;
+ /// A vector of child nodes
+ pub(crate) type ChildrenVec<A> = std::vec::Vec<A>;
+ #[cfg(feature = "grid")]
+ /// A vector of grid tracks
+ pub(crate) type GridTrackVec<A> = std::vec::Vec<A>;
+
+ /// Creates a new vector with the capacity for the specified number of items before it must be resized
+ #[must_use]
+ pub(crate) fn new_vec_with_capacity<A>(capacity: usize) -> Vec<A> {
+ Vec::with_capacity(capacity)
+ }
+
+ /// Creates a new empty `ChildrenVec` in a const context
+ #[must_use]
+ pub(crate) const fn new_const_children_vec<A>() -> ChildrenVec<A> {
+ Vec::new()
+ }
+
+ /// Rounds to the nearest whole number
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn round(value: f32) -> f32 {
+ (value + 0.5).floor()
+ }
+
+ /// Rounds up to the nearest whole number
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn ceil(value: f32) -> f32 {
+ value.ceil()
+ }
+
+ /// Rounds down to the nearest whole number
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn floor(value: f32) -> f32 {
+ value.floor()
+ }
+
+ /// Computes the absolute value
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn abs(value: f32) -> f32 {
+ value.abs()
+ }
+
+ /// Returns the largest of two f32 values
+ #[inline(always)]
+ pub(crate) fn f32_max(a: f32, b: f32) -> f32 {
+ a.max(b)
+ }
+
+ /// Returns the smallest of two f32 values
+ #[inline(always)]
+ pub(crate) fn f32_min(a: f32, b: f32) -> f32 {
+ a.min(b)
+ }
+}
+
+/// For when `std` is not enabled
+#[cfg(not(feature = "std"))]
+mod alloc {
+ extern crate alloc;
+
+ /// A string
+ pub(crate) type String = alloc::string::String;
+ /// The default type for representing strings in Taffy styles
+ pub(crate) type DefaultCheapStr = String;
+ /// A map
+ // TODO: consider using hashbrown
+ pub(crate) type Map<K, V> = alloc::collections::BTreeMap<K, V>;
+ /// An allocation-backend agnostic vector type
+ pub(crate) type Vec<A> = alloc::vec::Vec<A>;
+ /// An allocation-backend agnostic boxed pointer type
+ pub(crate) type Box<A> = alloc::boxed::Box<A>;
+ /// A vector of child nodes
+ pub(crate) type ChildrenVec<A> = alloc::vec::Vec<A>;
+ #[cfg(feature = "grid")]
+ /// A vector of grid tracks
+ pub(crate) type GridTrackVec<A> = alloc::vec::Vec<A>;
+
+ /// Creates a new vector with the capacity for the specified number of items before it must be resized
+ #[must_use]
+ pub(crate) fn new_vec_with_capacity<A>(capacity: usize) -> Vec<A> {
+ Vec::with_capacity(capacity)
+ }
+
+ /// Creates a new empty `ChildrenVec` in a const context
+ #[must_use]
+ pub(crate) const fn new_const_children_vec<A>() -> ChildrenVec<A> {
+ Vec::new()
+ }
+
+ /// Rounds to the nearest whole number
+ pub(crate) use super::polyfill::round;
+
+ /// Rounds up to the nearest whole number
+ pub(crate) use super::polyfill::ceil;
+
+ /// Rounds down to the nearest whole number
+ pub(crate) use super::polyfill::floor;
+
+ /// Computes the absolute value
+ pub(crate) use super::polyfill::abs;
+
+ /// Returns the largest of two f32 values
+ #[inline(always)]
+ pub(crate) fn f32_max(a: f32, b: f32) -> f32 {
+ a.max(b)
+ }
+
+ /// Returns the smallest of two f32 values
+ #[inline(always)]
+ pub(crate) fn f32_min(a: f32, b: f32) -> f32 {
+ a.min(b)
+ }
+}
+
+/// Implementations of float functions for no_std builds
+/// Copied from `num-traits` crate
+#[cfg(not(feature = "std"))]
+mod polyfill {
+ #[must_use]
+ #[inline(always)]
+ fn fract(value: f32) -> f32 {
+ if value == 0.0 {
+ 0.0
+ } else {
+ value % 1.0
+ }
+ }
+
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn round(value: f32) -> f32 {
+ let f = fract(value);
+ if f.is_nan() || f == 0.0 {
+ value
+ } else if value > 0.0 {
+ if f < 0.5 {
+ value - f
+ } else {
+ value - f + 1.0
+ }
+ } else if -f < 0.5 {
+ value - f
+ } else {
+ value - f - 1.0
+ }
+ }
+
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn floor(value: f32) -> f32 {
+ let f = fract(value);
+ if f.is_nan() || f == 0.0 {
+ value
+ } else if value < 0.0 {
+ value - f - 1.0
+ } else {
+ value - f
+ }
+ }
+
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn ceil(value: f32) -> f32 {
+ let f = fract(value);
+ if f.is_nan() || f == 0.0 {
+ value
+ } else if value > 0.0 {
+ value - f + 1.0
+ } else {
+ value - f
+ }
+ }
+
+ /// Computes the absolute value
+ #[must_use]
+ #[inline(always)]
+ pub(crate) fn abs(value: f32) -> f32 {
+ if value.is_sign_positive() {
+ return value;
+ } else if value.is_sign_negative() {
+ return -value;
+ } else {
+ f32::NAN
+ }
+ }
+}
diff --git a/vendor/vendor.toml b/vendor/vendor.toml
index f55d8b80..4e992e67 100644
--- a/vendor/vendor.toml
+++ b/vendor/vendor.toml
@@ -77,7 +77,7 @@ exit = "a Blitz release that draws these"
path = "vendor/blitz-dom"
upstream = "crates.io:0.3.0-beta.4"
kind = "patch"
-reason = "inline flex/grid baselines, auto table columns, table row rects, inline image load events, SVG text fonts, SVG non-scaling strokes, url() filters; Blitz main's #1244 and #1246; a node removed in a mutation batch dropped from the style, form and title nodes the batch flushes (raea #24); a node in a 3D rendering context (or with a projection) placed again on every resolve, so it follows a preserve-3d parent whose transform a script set (raea #19); a ParseErrorReporter (not_applied.rs) on every author parse, keeping what stylo drops for the render to say once (raea #34); a bevy_text box whose lines are no finite size (an Apple bitmap-only face, which parley scales by a units-per-em of 0) measures 0 by 0, as bevy_text does; a family list ending in ; getBoundingClientRect and the geometry walks stop at a freed containing-block link instead of panicking on its key, and an element in a display: none subtree answers a zero rect (raea #108)"raea-bevy fallback" (bevy_text's FontSource::Family) falls to the collection's fallback families, not to serif nor to the CoreText pick (parley: NO_HOOK_FAMILY); an out-of-flow box painted by the stacking context between it and its containing block, inside its opacity group (raea #39); an SVG's paint properties from CSS written into its serialized source for usvg (raea #45); transform-box: stroke-box as fill-box under non-scaling-stroke, a stylesheet's stroke in the stroke box, and the non-scaling mark on an element with its own id (raea #50); an SVG element's rewritten style attribute without a leading `;` when its own declarations were transforms alone; transform-box: view-box's reference box at the origin of user space, not at the viewBox's x and y; every inline box laid out in full while its line is only measured, since Taffy's measure cache keeps a box's size without its baseline (raea #109); an inline element has a border edge only where its border has a style, so a plain span (border-style none, its width still `medium`) doesn't split the shaping at its edges and lose the kerning across them (docs/layout-reads.feature LR10); an app-bundled svg face of a family the page already gave is left out, as one given before the page's is removed (raea/text loadFont fetches Google's faces at import, LR10); getBoundingClientRect through a perspective's projection (the node's Projection), and transformed_rect for a rect inside a node's box (LR10); an element whose `:has()` was matched is matched again when a node under it is inserted or removed (raea layers LA2a: a caption a <Sequence> put on the page stayed hidden under `:not(:has(...))`); a picture fitted to the raea-w/raea-h its URL asks (net.rs fit); the UA sheet's `svg|svg:not(:root) { overflow: clip }` (Chrome's hidden, as clip so layout is unchanged), which blitz-paint's draw_svg reads (raea #251)"
+reason = "inline flex/grid baselines, auto table columns, table row rects, inline image load events, SVG text fonts, SVG non-scaling strokes, url() filters; Blitz main's #1244 and #1246; a node removed in a mutation batch dropped from the style, form and title nodes the batch flushes (raea #24); a node in a 3D rendering context (or with a projection) placed again on every resolve, so it follows a preserve-3d parent whose transform a script set (raea #19); a ParseErrorReporter (not_applied.rs) on every author parse, keeping what stylo drops for the render to say once (raea #34); a bevy_text box whose lines are no finite size (an Apple bitmap-only face, which parley scales by a units-per-em of 0) measures 0 by 0, as bevy_text does; a family list ending in ; getBoundingClientRect and the geometry walks stop at a freed containing-block link instead of panicking on its key, and an element in a display: none subtree answers a zero rect (raea #108)"raea-bevy fallback" (bevy_text's FontSource::Family) falls to the collection's fallback families, not to serif nor to the CoreText pick (parley: NO_HOOK_FAMILY); an out-of-flow box painted by the stacking context between it and its containing block, inside its opacity group (raea #39); an SVG's paint properties from CSS written into its serialized source for usvg (raea #45); transform-box: stroke-box as fill-box under non-scaling-stroke, a stylesheet's stroke in the stroke box, and the non-scaling mark on an element with its own id (raea #50); an SVG element's rewritten style attribute without a leading `;` when its own declarations were transforms alone; transform-box: view-box's reference box at the origin of user space, not at the viewBox's x and y; every inline box laid out in full while its line is only measured, since Taffy's measure cache keeps a box's size without its baseline (raea #109); an inline element has a border edge only where its border has a style, so a plain span (border-style none, its width still `medium`) doesn't split the shaping at its edges and lose the kerning across them (docs/layout-reads.feature LR10); an app-bundled svg face of a family the page already gave is left out, as one given before the page's is removed (raea/text loadFont fetches Google's faces at import, LR10); getBoundingClientRect through a perspective's projection (the node's Projection), and transformed_rect for a rect inside a node's box (LR10); an element whose `:has()` was matched is matched again when a node under it is inserted or removed (raea layers LA2a: a caption a <Sequence> put on the page stayed hidden under `:not(:has(...))`); a picture fitted to the raea-w/raea-h its URL asks (net.rs fit); the UA sheet's `svg|svg:not(:root) { overflow: clip }` (Chrome's hidden, as clip so layout is unchanged), which blitz-paint's draw_svg reads (raea #251); a table's children that are no table box (text, a block) wrapped in an anonymous row and cell, as css-tables-3 wraps them, so a display: table element around its text draws, shrink-wrapped (raea #254); small capitals synthesised (capitals at 70% of the font size, as Chrome) where the face has no smcp feature (layout/small_caps.rs, raea #249)"
exit = "a Blitz release with #1244/#1246 and these"
[parley_engine]
@@ -192,3 +192,10 @@ upstream = "crates.io:0.48.1"
kind = "patch"
reason = "letter-spacing after a text chunk's last letter too, as Chrome spaces it (an anchored svg text was drawn half a spacing off and measured a spacing wide)"
exit = "a usvg release that spaces the last cluster, or none: usvg drops it on purpose"
+
+[taffy]
+path = "vendor/taffy"
+upstream = "crates.io:0.15.0"
+kind = "patch"
+reason = "a flex line whose items overflow its container by less than 1/64 px (Chrome's layout unit) still fits, so f32 rounding doesn't wrap items that add up to its width (raea #252); its examples left out"
+exit = "a Taffy release that breaks flex lines with a tolerance (or in fixed-point units)"