#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Justify {
#[default]
Start,
End,
Center,
SpaceBetween,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlexItem {
pub basis: f64,
pub grow: f64,
pub shrink: f64,
pub min: f64,
pub max: f64,
}
impl FlexItem {
pub fn fixed(w: f64) -> Self {
FlexItem { basis: w, grow: 0.0, shrink: 0.0, min: w, max: w }
}
pub fn fill() -> Self {
FlexItem { basis: 0.0, grow: 1.0, shrink: 1.0, min: 0.0, max: f64::INFINITY }
}
pub fn auto(w: f64) -> Self {
FlexItem { basis: w, grow: 0.0, shrink: 1.0, min: 0.0, max: f64::INFINITY }
}
}
pub fn flex_row(avail: f64, items: &[FlexItem], gap: f64, justify: Justify) -> Vec<(f64, f64)> {
if items.is_empty() {
return vec![];
}
let gaps = gap * (items.len() - 1) as f64;
let n = items.len();
let hyp: Vec<f64> = items.iter().map(|i| i.basis.clamp(i.min, i.max)).collect();
let grow = hyp.iter().sum::<f64>() + gaps < avail;
let mut size: Vec<f64> = items.iter().map(|i| i.basis).collect();
let mut frozen: Vec<bool> = (0..n)
.map(|k| {
let it = &items[k];
let factor = if grow { it.grow } else { it.shrink };
factor == 0.0 || (grow && it.basis > hyp[k]) || (!grow && it.basis < hyp[k])
})
.collect();
for k in 0..n {
if frozen[k] {
size[k] = hyp[k];
}
}
for _ in 0..=n {
if frozen.iter().all(|f| *f) {
break;
}
let used: f64 = (0..n).map(|k| if frozen[k] { size[k] } else { items[k].basis }).sum();
let free = avail - gaps - used;
let weight = |k: usize| if grow { items[k].grow } else { items[k].shrink * items[k].basis };
let total: f64 = (0..n).filter(|&k| !frozen[k]).map(weight).sum();
let mut viol = vec![0.0; n];
for k in (0..n).filter(|&k| !frozen[k]) {
let want = if total > 0.0 { items[k].basis + free * weight(k) / total } else { items[k].basis };
let got = want.clamp(items[k].min, items[k].max);
viol[k] = got - want;
size[k] = got;
}
let tv: f64 = viol.iter().sum();
let open: Vec<usize> = (0..n).filter(|&k| !frozen[k]).collect();
for k in open {
if tv.abs() < 1e-9 || (tv > 0.0 && viol[k] > 0.0) || (tv < 0.0 && viol[k] < 0.0) {
frozen[k] = true;
}
}
}
let used = size.iter().sum::<f64>() + gaps;
let rest = (avail - used).max(0.0);
let (mut x, step) = match justify {
Justify::Start => (0.0, gap),
Justify::End => (rest, gap),
Justify::Center => (rest / 2.0, gap),
Justify::SpaceBetween if items.len() > 1 => (0.0, gap + rest / (items.len() - 1) as f64),
Justify::SpaceBetween => (0.0, gap),
};
size.iter()
.map(|&w| {
let r = (x, w);
x += w + step;
r
})
.collect()
}
pub fn flex_wrap(avail: f64, sizes: &[(f64, f64)], gap_x: f64, gap_y: f64) -> (Vec<(f64, f64)>, f64) {
let (mut x, mut y, mut line_h) = (0.0, 0.0, 0.0f64);
let mut out = Vec::with_capacity(sizes.len());
for &(w, h) in sizes {
if x > 0.0 && x + w > avail + 1e-9 {
y += line_h + gap_y;
x = 0.0;
line_h = 0.0;
}
out.push((x, y));
x += w + gap_x;
line_h = line_h.max(h);
}
(out, if sizes.is_empty() { 0.0 } else { y + line_h })
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Track {
Px(f64),
Fr(f64),
MinMax(f64, f64),
}
pub fn grid_tracks(avail: f64, tracks: &[Track], gap: f64) -> Vec<(f64, f64)> {
let fr: f64 = tracks.iter().map(|t| match *t { Track::Px(_) => 0.0, Track::Fr(f) | Track::MinMax(_, f) => f }).sum();
let fixed: f64 = tracks.iter().filter_map(|t| if let Track::Px(w) = t { Some(*w) } else { None }).sum::<f64>()
+ gap * tracks.len().saturating_sub(1) as f64;
let flex_space = (avail - fixed).max(0.0);
let mut x = 0.0;
tracks
.iter()
.map(|t| {
let w = match *t {
Track::Px(w) => w,
Track::Fr(f) => flex_space * f / fr.max(1e-9),
Track::MinMax(m, f) => (flex_space * f / fr.max(1e-9)).max(m),
};
let r = (x, w);
x += w + gap;
r
})
.collect()
}
pub fn auto_fill(avail: f64, min: f64, gap: f64) -> (usize, f64) {
let n = (((avail + gap) / (min + gap)).floor() as usize).max(1);
(n, ((avail - gap * (n - 1) as f64) / n as f64).max(0.0))
}
use crate::ui::style::Style;
use crate::Rect;
pub type Measure<'a> = &'a dyn Fn(Option<f64>) -> (f64, f64);
pub struct LBox<'a> {
pub style: Style,
pub measure: Option<Measure<'a>>,
pub children: Vec<LBox<'a>>,
}
impl<'a> LBox<'a> {
pub fn new(style: Style) -> Self {
LBox { style, measure: None, children: Vec::new() }
}
pub fn css(decls: &str) -> Self {
LBox::new(crate::ui::style::inline(decls))
}
pub fn child(mut self, c: LBox<'a>) -> Self {
self.children.push(c);
self
}
pub fn text(mut self, m: Measure<'a>) -> Self {
self.measure = Some(m);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Laid {
pub rect: Rect,
pub children: Vec<Laid>,
}
impl Laid {
pub fn flatten(&self) -> Vec<Rect> {
let mut v = vec![self.rect];
for c in &self.children {
v.extend(c.flatten());
}
v
}
}
fn hz(s: &Style) -> f64 {
let (p, b) = (s.pad(), s.border_edges());
p[1] + p[3] + b[1] + b[3]
}
fn vt(s: &Style) -> f64 {
let (p, b) = (s.pad(), s.border_edges());
p[0] + p[2] + b[0] + b[2]
}
fn mh(s: &Style) -> f64 {
let m = s.mar();
m[1] + m[3]
}
#[cfg(any(feature = "flow-flex", feature = "flow-grid"))]
fn mv(s: &Style) -> f64 {
let m = s.mar();
m[0] + m[2]
}
fn clamp_w(s: &Style, w: f64) -> f64 {
w.min(s.max_width.unwrap_or(f64::INFINITY)).max(s.min_width.unwrap_or(0.0))
}
fn clamp_h(s: &Style, h: f64) -> f64 {
h.min(s.max_height.unwrap_or(f64::INFINITY)).max(s.min_height.unwrap_or(0.0))
}
#[cfg(feature = "flow-flex")]
fn is(s: &Option<String>, v: &str) -> bool {
s.as_deref() == Some(v)
}
fn display(s: &Style) -> &str {
s.display.as_deref().unwrap_or("block")
}
#[cfg(feature = "flow-flex")]
fn is_col(s: &Style) -> bool {
matches!(s.flex_direction.as_deref(), Some("column") | Some("column-reverse"))
}
#[cfg(any(feature = "flow-flex", feature = "flow-grid"))]
fn row_gap(s: &Style) -> f64 {
s.row_gap.or(s.gap).unwrap_or(0.0)
}
#[cfg(any(feature = "flow-flex", feature = "flow-grid"))]
fn col_gap(s: &Style) -> f64 {
s.gap.unwrap_or(0.0)
}
pub fn parse_tracks(spec: &str, avail: f64, gap: f64) -> Vec<Track> {
fn one(t: &str) -> Option<Track> {
let t = t.trim();
if let Some(f) = t.strip_suffix("fr") {
return f.trim().parse().ok().map(Track::Fr);
}
if let Some(inner) = t.strip_prefix("minmax(").and_then(|r| r.strip_suffix(')')) {
let (a, b) = inner.split_once(',')?;
let m = a.trim().trim_end_matches("px").parse().ok()?;
let f = b.trim().strip_suffix("fr")?.trim().parse().ok()?;
return Some(Track::MinMax(m, f));
}
t.trim_end_matches("px").parse().ok().map(Track::Px)
}
let mut parts = Vec::new();
let (mut depth, mut cur) = (0, String::new());
for ch in spec.chars() {
match ch {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
if ch.is_whitespace() && depth == 0 {
if !cur.is_empty() {
parts.push(std::mem::take(&mut cur));
}
} else {
cur.push(ch);
}
}
if !cur.is_empty() {
parts.push(cur);
}
let mut out = Vec::new();
for p in parts {
if let Some(inner) = p.strip_prefix("repeat(").and_then(|r| r.strip_suffix(')')) {
let Some((n, t)) = inner.split_once(',') else { continue };
let Some(t) = one(t) else { continue };
let count = match n.trim() {
"auto-fill" | "auto-fit" => {
let min = match t {
Track::Px(w) | Track::MinMax(w, _) => w,
Track::Fr(_) => 0.0,
};
auto_fill(avail, min, gap).0
}
k => k.parse().unwrap_or(1),
};
out.extend(std::iter::repeat_n(t, count));
} else if let Some(t) = one(&p) {
out.push(t);
}
}
out
}
pub fn max_content(b: &LBox<'_>) -> f64 {
intrinsic(b, false)
}
pub fn min_content(b: &LBox<'_>) -> f64 {
intrinsic(b, true)
}
fn intrinsic(b: &LBox<'_>, min: bool) -> f64 {
let s = &b.style;
if let Some(w) = s.width {
return clamp_w(s, w);
}
let kids = b.children.iter().filter(|c| !c.style.out_of_flow()).map(|c| intrinsic(c, min) + mh(&c.style));
let content = if let Some(m) = b.measure {
m(if min { Some(0.0) } else { None }).0
} else {
match display(s) {
#[cfg(feature = "flow-flex")]
"flex" if !is_col(s) => {
let n = b.children.iter().filter(|c| !c.style.out_of_flow()).count();
let gaps = col_gap(s) * n.saturating_sub(1) as f64;
if min && is(&s.flex_wrap, "wrap") {
kids.fold(0.0, f64::max)
} else {
kids.sum::<f64>() + gaps
}
}
#[cfg(feature = "flow-grid")]
"grid" => {
let tracks = parse_tracks(s.grid_template_columns.as_deref().unwrap_or("1fr"), 0.0, col_gap(s));
let n = tracks.len().max(1);
let widest = b.children.iter().filter(|c| !c.style.out_of_flow()).map(|c| intrinsic(c, min) + mh(&c.style)).fold(0.0, f64::max);
let mut sum = col_gap(s) * (n - 1) as f64;
for t in &tracks {
sum += match *t {
Track::Px(w) => w,
Track::MinMax(m, _) => m.max(widest),
Track::Fr(_) => widest,
};
}
sum
}
_ => kids.fold(0.0, f64::max),
}
};
clamp_w(s, content + hz(s))
}
pub fn layout(b: &LBox<'_>, x: f64, y: f64, avail: f64) -> Laid {
let w = clamp_w(&b.style, b.style.width.unwrap_or(avail - mh(&b.style)));
let mut l = lay(b, x + b.style.mar()[3], y + b.style.mar()[0], w, None);
if !b.style.positioned() {
let cb = l.rect;
place_abs(b, &mut l, cb);
}
l
}
fn translate(l: &mut Laid, dx: f64, dy: f64) {
l.rect = Rect::new(l.rect.x + dx, l.rect.y + dy, l.rect.width, l.rect.height);
for c in &mut l.children {
translate(c, dx, dy);
}
}
fn padding_box(s: &Style, r: Rect) -> Rect {
let b = s.border_edges();
Rect::new(r.x + b[3], r.y + b[0], (r.width - b[1] - b[3]).max(0.0), (r.height - b[0] - b[2]).max(0.0))
}
fn place_abs(b: &LBox<'_>, l: &mut Laid, cb: Rect) {
for (c, cl) in b.children.iter().zip(l.children.iter_mut()) {
let s = &c.style;
if s.out_of_flow() {
*cl = lay_abs(c, cb, (cl.rect.x, cl.rect.y));
} else if !s.positioned() {
place_abs(c, cl, cb);
}
}
}
fn lay_abs(c: &LBox<'_>, cb: Rect, stat: (f64, f64)) -> Laid {
let s = &c.style;
let m = s.mar();
let w = match (s.width, s.left, s.right) {
(Some(w), _, _) => clamp_w(s, w),
(None, Some(l), Some(r)) => clamp_w(s, cb.width - l - r - m[1] - m[3]),
(None, l, r) => {
let avail = cb.width - l.unwrap_or(0.0) - r.unwrap_or(0.0) - m[1] - m[3];
clamp_w(s, max_content(c).min(avail.max(min_content(c))))
}
};
let forced = match (s.height, s.top, s.bottom) {
(None, Some(t), Some(bt)) => Some(clamp_h(s, (cb.height - t - bt - m[0] - m[2]).max(0.0))),
_ => None,
};
let mut l = lay(c, 0.0, 0.0, w, forced);
let x = match (s.left, s.right) {
(Some(left), _) => cb.x + left + m[3],
(None, Some(r)) => cb.x + cb.width - r - m[1] - w,
(None, None) => stat.0,
};
let y = match (s.top, s.bottom) {
(Some(t), _) => cb.y + t + m[0],
(None, Some(bt)) => cb.y + cb.height - bt - m[2] - l.rect.height,
(None, None) => stat.1,
};
translate(&mut l, x, y);
l
}
#[cfg(any(feature = "flow-flex", feature = "flow-grid"))]
fn height_at(b: &LBox<'_>, w: f64) -> f64 {
lay(b, 0.0, 0.0, w, None).rect.height
}
#[cfg(feature = "flow-flex")]
fn justify_of(s: &Style) -> Justify {
match s.justify_content.as_deref() {
Some("flex-end") | Some("end") => Justify::End,
Some("center") => Justify::Center,
Some("space-between") => Justify::SpaceBetween,
_ => Justify::Start,
}
}
#[cfg(any(feature = "flow-flex", feature = "flow-grid"))]
fn align_of<'s>(parent: &'s Style, child: &'s Style) -> &'s str {
match child.align_self.as_deref() {
Some(a) if a != "auto" => a,
_ => parent.align_items.as_deref().unwrap_or("stretch"),
}
}
fn lay(b: &LBox<'_>, x: f64, y: f64, w: f64, forced_h: Option<f64>) -> Laid {
let s = &b.style;
let p = s.pad();
let be = s.border_edges();
let (cx, cy) = (x + p[3] + be[3], y + p[0] + be[0]);
let cw = (w - hz(s)).max(0.0);
let def_h = forced_h.or(s.height.map(|h| clamp_h(s, h)));
#[cfg_attr(not(feature = "flow-flex"), allow(unused_variables))]
let ch_def = def_h.map(|h| (h - vt(s)).max(0.0));
let abs = b.children.iter().any(|c| c.style.out_of_flow());
let flow: Vec<&LBox<'_>> = b.children.iter().filter(|c| !c.style.out_of_flow()).collect();
let (laid, content_h) = if let Some(m) = b.measure {
(Vec::new(), m(Some(cw)).1)
} else {
match display(s) {
#[cfg(feature = "flow-flex")]
"flex" if is_col(s) => flex_col(s, &flow, cx, cy, cw, ch_def),
#[cfg(feature = "flow-flex")]
"flex" => flex_rowbox(s, &flow, cx, cy, cw, ch_def),
#[cfg(feature = "flow-grid")]
"grid" => grid_box(s, &flow, cx, cy, cw),
_ => block(&flow, cx, cy, cw),
}
};
let children = if abs && b.measure.is_none() {
let mut it = laid.into_iter();
let mut out = Vec::with_capacity(b.children.len());
let mut stat = (cx, cy);
for c in &b.children {
if c.style.out_of_flow() {
out.push(Laid { rect: Rect::new(stat.0, stat.1, 0.0, 0.0), children: Vec::new() });
} else if let Some(l) = it.next() {
if display(s) == "block" {
stat = (cx, l.rect.y + l.rect.height + c.style.mar()[2]);
}
out.push(l);
}
}
out
} else {
laid
};
let h = def_h.unwrap_or_else(|| clamp_h(s, content_h + vt(s)));
let mut l = Laid { rect: Rect::new(x, y, w, h), children };
if s.positioned() {
let cb = padding_box(s, l.rect);
place_abs(b, &mut l, cb);
}
if s.position.as_deref() == Some("relative") {
let dx = s.left.or(s.right.map(|r| -r)).unwrap_or(0.0);
let dy = s.top.or(s.bottom.map(|b| -b)).unwrap_or(0.0);
if dx != 0.0 || dy != 0.0 {
translate(&mut l, dx, dy);
}
}
l
}
fn block(kids: &[&LBox<'_>], cx: f64, cy: f64, cw: f64) -> (Vec<Laid>, f64) {
let mut yy = 0.0;
let mut prev_mb: Option<f64> = None;
let mut out = Vec::new();
for &c in kids {
let m = c.style.mar();
let top = match prev_mb {
Some(pm) => pm.max(m[0]) - pm,
None => m[0],
};
yy += top;
let w = clamp_w(&c.style, c.style.width.unwrap_or(cw - m[1] - m[3]));
let l = lay(c, cx + m[3], cy + yy, w, None);
yy += l.rect.height + m[2];
prev_mb = Some(m[2]);
out.push(l);
}
(out, yy)
}
#[cfg(feature = "flow-flex")]
fn item(c: &LBox<'_>, main_col: bool, cross_w: f64) -> FlexItem {
let s = &c.style;
let (basis, min, max) = if main_col {
let w = s.width.unwrap_or(cross_w);
let content = height_at(c, w);
let basis = s.flex_basis.or(s.height).unwrap_or(content);
(basis, s.min_height.unwrap_or(if s.height.is_some() { 0.0 } else { content.min(basis) }), s.max_height.unwrap_or(f64::INFINITY))
} else {
let mc = min_content(c);
let basis = s.flex_basis.or(s.width).unwrap_or_else(|| max_content(c));
let auto_min = if let Some(w) = s.width { mc.min(w) } else { mc };
(basis, s.min_width.unwrap_or(auto_min), s.max_width.unwrap_or(f64::INFINITY))
};
let m = if main_col { mv(s) } else { mh(s) };
FlexItem { basis: basis + m, grow: s.flex_grow.unwrap_or(0.0), shrink: s.flex_shrink.unwrap_or(1.0), min: min + m, max: max + m }
}
#[cfg(feature = "flow-flex")]
fn flex_rowbox(s: &Style, kids: &[&LBox<'_>], cx: f64, cy: f64, cw: f64, ch: Option<f64>) -> (Vec<Laid>, f64) {
let wrap = is(&s.flex_wrap, "wrap");
let items: Vec<FlexItem> = kids.iter().map(|c| item(c, false, cw)).collect();
let mut lines: Vec<Vec<usize>> = vec![vec![]];
let mut used = 0.0;
for (i, it) in items.iter().enumerate() {
let hyp = it.basis.clamp(it.min, it.max);
let cur = lines.last_mut().unwrap();
if wrap && !cur.is_empty() && used + col_gap(s) + hyp > cw + 1e-9 {
lines.push(vec![i]);
used = hyp;
} else {
used += if cur.is_empty() { hyp } else { col_gap(s) + hyp };
cur.push(i);
}
}
let mut out: Vec<Option<Laid>> = (0..kids.len()).map(|_| None).collect();
lines.retain(|l| !l.is_empty());
let solved: Vec<(Vec<(f64, f64)>, Vec<(f64, f64)>, f64)> = lines
.iter()
.map(|line| {
let its: Vec<FlexItem> = line.iter().map(|&i| items[i]).collect();
let main = flex_row(cw, &its, col_gap(s), justify_of(s));
let sizes: Vec<(f64, f64)> = line
.iter()
.zip(&main)
.map(|(&i, &(_, ow))| {
let c = kids[i];
let w = ow - mh(&c.style);
(w, c.style.height.unwrap_or_else(|| height_at(c, w)))
})
.collect();
let lh = line.iter().zip(&sizes).map(|(&i, &(_, h))| h + mv(&kids[i].style)).fold(0.0, f64::max);
(main, sizes, lh)
})
.collect();
let natural: f64 = solved.iter().map(|l| l.2).sum::<f64>() + row_gap(s) * solved.len().saturating_sub(1) as f64;
let extra = match ch {
Some(h) if solved.len() == 1 => h - natural,
Some(h) if h > natural => h - natural,
_ => 0.0,
} / solved.len().max(1) as f64;
let mut yy = 0.0;
for (li, (line, (main, sizes, lh))) in lines.iter().zip(&solved).enumerate() {
if li > 0 {
yy += row_gap(s);
}
let line_h = lh + extra;
for ((&i, &(ox, _)), &(w, h)) in line.iter().zip(main).zip(sizes) {
let c = kids[i];
let m = c.style.mar();
let (hh, dy) = match align_of(s, &c.style) {
"stretch" if c.style.height.is_none() => (clamp_h(&c.style, line_h - mv(&c.style)), 0.0),
"center" => (h, (line_h - h - mv(&c.style)) / 2.0),
"flex-end" | "end" => (h, line_h - h - mv(&c.style)),
_ => (h, 0.0),
};
out[i] = Some(lay(c, cx + ox + m[3], cy + yy + m[0] + dy, w, Some(hh)));
}
yy += line_h;
}
(out.into_iter().flatten().collect(), ch.unwrap_or(yy))
}
#[cfg(feature = "flow-flex")]
fn flex_col(s: &Style, kids: &[&LBox<'_>], cx: f64, cy: f64, cw: f64, ch: Option<f64>) -> (Vec<Laid>, f64) {
let widths: Vec<f64> = kids
.iter()
.map(|c| {
let avail = cw - mh(&c.style);
let w = match (c.style.width, align_of(s, &c.style)) {
(Some(w), _) => w,
(None, "stretch") => avail,
(None, _) => max_content(c).min(avail),
};
clamp_w(&c.style, w)
})
.collect();
let items: Vec<FlexItem> = kids.iter().zip(&widths).map(|(c, &w)| item(c, true, w)).collect();
let main = match ch {
Some(h) => flex_row(h, &items, row_gap(s), justify_of(s)),
None => flex_row(f64::NEG_INFINITY.max(items.iter().map(|i| i.basis.clamp(i.min, i.max)).sum::<f64>() + row_gap(s) * items.len().saturating_sub(1) as f64), &items, row_gap(s), Justify::Start),
};
let mut out = Vec::new();
let mut end: f64 = 0.0;
for ((&c, &(oy, oh)), &w) in kids.iter().zip(&main).zip(&widths) {
let m = c.style.mar();
let dx = match align_of(s, &c.style) {
"center" => (cw - w - mh(&c.style)) / 2.0,
"flex-end" | "end" => cw - w - mh(&c.style),
_ => 0.0,
};
let l = lay(c, cx + m[3] + dx, cy + oy + m[0], w, Some(oh - mv(&c.style)));
end = end.max(oy + oh);
out.push(l);
}
(out, ch.unwrap_or(end))
}
#[cfg(feature = "flow-grid")]
fn grid_box(s: &Style, kids: &[&LBox<'_>], cx: f64, cy: f64, cw: f64) -> (Vec<Laid>, f64) {
let tracks = parse_tracks(s.grid_template_columns.as_deref().unwrap_or("1fr"), cw, col_gap(s));
let cols = grid_tracks(cw, &tracks, col_gap(s));
let n = cols.len().max(1);
let mut out = Vec::new();
let mut yy = 0.0;
for (ri, row) in kids.chunks(n).enumerate() {
if ri > 0 {
yy += row_gap(s);
}
let hs: Vec<f64> = row
.iter()
.zip(&cols)
.map(|(&c, &(_, tw))| c.style.height.unwrap_or_else(|| height_at(c, tw - mh(&c.style))) + mv(&c.style))
.collect();
let rh = hs.iter().copied().fold(0.0, f64::max);
for ((&c, &(tx, tw)), &h) in row.iter().zip(&cols).zip(&hs) {
let m = c.style.mar();
let w = c.style.width.unwrap_or(tw - mh(&c.style));
let hh = match align_of(s, &c.style) {
"stretch" if c.style.height.is_none() => rh - mv(&c.style),
_ => h - mv(&c.style),
};
let dy = match align_of(s, &c.style) {
"center" => (rh - h) / 2.0,
"end" | "flex-end" => rh - h,
_ => 0.0,
};
out.push(lay(c, cx + tx + m[3], cy + yy + m[0] + dy, w, Some(hh)));
}
yy += rh;
}
(out, yy)
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.0 - q.0).abs() < 1e-6 && (p.1 - q.1).abs() < 1e-6)
}
#[test]
fn flex_grow_and_justify() {
let r = flex_row(300.0, &[FlexItem::fixed(50.0), FlexItem::fill(), FlexItem::fixed(70.0)], 10.0, Justify::Start);
assert!(close(&r, &[(0.0, 50.0), (60.0, 160.0), (230.0, 70.0)]));
let r = flex_row(100.0, &[FlexItem::fixed(20.0), FlexItem::fixed(20.0)], 0.0, Justify::End);
assert!(close(&r, &[(60.0, 20.0), (80.0, 20.0)]));
let r = flex_row(100.0, &[FlexItem::fixed(20.0), FlexItem::fixed(20.0)], 0.0, Justify::Center);
assert!(close(&r, &[(30.0, 20.0), (50.0, 20.0)]));
let r = flex_row(100.0, &[FlexItem::fixed(20.0), FlexItem::fixed(20.0), FlexItem::fixed(20.0)], 0.0, Justify::SpaceBetween);
assert!(close(&r, &[(0.0, 20.0), (40.0, 20.0), (80.0, 20.0)]));
}
#[test]
fn flex_shrink_respects_min_and_max() {
let r = flex_row(150.0, &[FlexItem::auto(100.0), FlexItem::auto(100.0)], 0.0, Justify::Start);
assert!(close(&r, &[(0.0, 75.0), (75.0, 75.0)]));
let a = FlexItem { min: 90.0, ..FlexItem::auto(100.0) };
let r = flex_row(150.0, &[a, FlexItem::auto(100.0)], 0.0, Justify::Start);
assert!(close(&r, &[(0.0, 90.0), (90.0, 60.0)]));
let capped = FlexItem { max: 40.0, ..FlexItem::fill() };
let r = flex_row(200.0, &[capped, FlexItem::fill()], 0.0, Justify::Start);
assert!(close(&r, &[(0.0, 40.0), (40.0, 160.0)]));
}
#[test]
fn wrap_breaks_lines() {
let (pos, h) = flex_wrap(100.0, &[(40.0, 24.0), (40.0, 24.0), (40.0, 24.0)], 5.0, 5.0);
assert_eq!(pos, vec![(0.0, 0.0), (45.0, 0.0), (0.0, 29.0)]);
assert_eq!(h, 53.0);
assert_eq!(flex_wrap(10.0, &[(40.0, 20.0)], 5.0, 5.0), (vec![(0.0, 0.0)], 20.0));
}
#[test]
fn grid_fr_and_minmax() {
let r = grid_tracks(310.0, &[Track::Fr(2.0), Track::Fr(1.0)], 10.0);
assert!(close(&r, &[(0.0, 200.0), (210.0, 100.0)]));
let r = grid_tracks(100.0, &[Track::MinMax(140.0, 1.0), Track::Px(50.0)], 0.0);
assert!(close(&r, &[(0.0, 140.0), (140.0, 50.0)]));
assert_eq!(auto_fill(800.0, 380.0, 10.0), (2, 395.0));
assert_eq!(auto_fill(300.0, 380.0, 10.0), (1, 300.0));
}
#[cfg(all(feature = "flow-flex", feature = "flow-grid"))]
fn words<'a>(text: &'a str) -> impl Fn(Option<f64>) -> (f64, f64) + 'a {
move |limit| {
let ws: Vec<f64> = text.split(' ').map(|w| w.len() as f64 * 7.0).collect();
let (mut lines, mut cur, mut widest) = (1.0, 0.0f64, 0.0f64);
for (i, w) in ws.iter().enumerate() {
let add = if i == 0 || cur == 0.0 { *w } else { cur + 10.0 + w };
if cur > 0.0 && limit.is_some_and(|l| add > l) {
lines += 1.0;
widest = widest.max(cur);
cur = *w;
} else {
cur = add;
}
}
(widest.max(cur), lines * 20.0)
}
}
#[test]
#[cfg(all(feature = "flow-flex", feature = "flow-grid"))]
fn text_intrinsic_sizes_and_shrink_to_min_content() {
let a = words("aaaa bb cccccc");
let t = LBox::css("").text(&a);
assert_eq!((min_content(&t), max_content(&t)), (42.0, 28.0 + 10.0 + 14.0 + 10.0 + 42.0));
let b = words("x");
let row = LBox::css("display:flex;width:70px").child(LBox::css("").text(&a)).child(LBox::css("").text(&b));
let l = layout(&row, 0.0, 0.0, 500.0);
assert_eq!(l.children[0].rect.width, 63.0);
assert_eq!(l.children[0].rect.height, 40.0);
assert_eq!(l.rect.height, 40.0, "the row is as tall as its wrapped text");
}
#[test]
#[cfg(all(feature = "flow-flex", feature = "flow-grid"))]
fn golden_layouts_match_chrome() {
let raw = include_str!("../../tests/golden/flow.json");
let cases: serde_json::Value = serde_json::from_str(raw).unwrap();
fn build(v: &serde_json::Value) -> LBox<'static> {
let mut b = LBox::css(v["style"].as_str().unwrap_or(""));
for c in v["children"].as_array().into_iter().flatten() {
b.children.push(build(c));
}
b
}
let mut bad = Vec::new();
for case in cases.as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let root = build(&case["tree"]);
let got = layout(&root, 0.0, 0.0, case["viewport"].as_f64().unwrap()).flatten();
let want: Vec<Vec<f64>> = serde_json::from_value(case["chrome"].clone()).unwrap();
assert_eq!(got.len(), want.len(), "{name}: box count");
for (i, (g, w)) in got.iter().zip(&want).enumerate() {
let d = [g.x - w[0], g.y - w[1], g.width - w[2], g.height - w[3]];
if d.iter().any(|x| x.abs() > 0.5) {
bad.push(format!("{name} box {i}: uzor {:?} chrome {:?}", (g.x, g.y, g.width, g.height), w));
}
}
}
assert!(bad.is_empty(), "{}", bad.join("\n"));
}
}