Initial flexbox implementation

This commit is contained in:
Dynamitos committed 2026-10-25 07:34:05 +01:00
1 parent 1bc73b6d2f
commit bcb9a7b148
15 files changed
+1504 -142

No files matched your search

+797
View File
@@ -0,0 +1,797 @@
#include "UI/FlexLayout.h"
// the full Element type (the header only forward-declares it to avoid a circular
// include: Element.h already includes FlexLayout.h). the free functions defined
// here dereference Element, so we need the complete definition.
#include "UI/Element.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <vector>
// flexbox is the sole layout mode (see FlexLayout.h for the model and the coordinate
// convention: an element's `position`/`dimensions` are in PARENT space; a child's
// containing box is the parent's dimensions; margins are honored on both axes and the
// align/justify math works in the parent's *content* box).
//
// `position`/`dimensions` are concrete x/y and direction-independent — only the flow
// ORDER within a container and the start/end direction depend on `direction`. Size
// resolution is axis-agnostic (width and height are computed independently); the
// main-axis flow uses explicit x/y branches.
//
// A size is resolved in this order: explicit (Pixel/Percent) beats content; Auto
// falls back to the content measurement (the max over flow children of the child's
// footprint + gaps, or the element's intrinsic size for a leaf); min/max then clamp.
// A child's percent size resolves against its *parent's* content box (never the
// grandparent). A nested container's real size is finalized when the place phase
// recurses into it; the parent's Auto size is the max over its children's
// explicit/intrinsic footprints (exact for the demo, where containers are
// explicit-sized or hold leaves).
namespace Seele {
namespace UI {
namespace FlexLayout {
namespace {
// the flow set of `parent`: children that are visible (not Hidden) and not Absolute,
// as (index, order) pairs. measure and place both iterate this, so their index
// spaces line up. `order` is read here (not via stable_sort) because the same
// sorted vector is reused in place.
struct Flow {
std::vector<size_t> idx;
std::vector<int32> order;
static void build(Element* parent, Flow& f) {
f.idx.clear();
f.order.clear();
const auto& kids = parent->getChildren();
for (size_t i = 0; i < kids.size(); i++) {
Element* c = kids[i];
if (c == nullptr || c->getStyle().display == Display::Hidden) {
continue;
}
if (c->getStyle().position == Position::Absolute) {
continue; // removed from the flow; positioned separately
}
f.idx.push_back(i);
f.order.push_back(c->getStyle().order);
}
// sort the parallel vectors together: collect (order, childIndex) pairs,
// sort them, then write the sorted result back into idx/order in lockstep.
// sorting f.idx alone would break the index correspondence with f.order
// (the comparator would read f.order[a] where a is a child index, not a
// position in the filtered list — out-of-bounds when children are skipped).
std::vector<std::pair<int32, size_t>> pairs;
pairs.reserve(f.idx.size());
for (size_t k = 0; k < f.idx.size(); k++) {
pairs.emplace_back(f.order[k], f.idx[k]);
}
std::sort(pairs.begin(), pairs.end(),
[](const auto& a, const auto& b) { return a.first < b.first; });
for (size_t k = 0; k < pairs.size(); k++) {
f.order[k] = pairs[k].first;
f.idx[k] = pairs[k].second;
}
}
size_t size() const { return idx.size(); }
size_t operator[](size_t k) const { return idx[k]; }
};
// resolve a DimensionType/float pair against a containing size. Auto -> 0 (the caller
// supplies the content measurement for the Auto case).
static float resolvePx(DimensionType t, float v, float cont) {
if (t == DimensionType::Pixel) {
return v;
}
if (t == DimensionType::Percent) {
return cont * v / 100.0f;
}
return 0.0f;
}
// the child's main-axis *footprint* for the parent's content measurement: an explicit
// (px/%) size resolves against the parent's content box; an Auto (or nested-container)
// child contributes its intrinsic size (0 for a container, since its real size is
// finalized when the place phase recurses into it). Includes main-axis margins.
static float childMainFootprint(Element* c, const FlexLayout::Axis& axis, float parentContentMain) {
const Style& s = c->getStyle();
bool isX = axis.mainIsX;
float size;
if (isX) {
if (s.widthType != DimensionType::Auto) {
size = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentMain));
} else {
// Auto main: use intrinsic. setIntrinsicSize already zeros this when
// the axis is explicit (it only stores when widthType==Auto), so an
// explicit-width item returns 0 here automatically.
size = c->getIntrinsicW();
}
return size + (float)(s.marginLeft + s.marginRight);
} else {
if (s.heightType != DimensionType::Auto) {
size = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentMain));
} else {
size = c->getIntrinsicH();
}
return size + (float)(s.marginTop + s.marginBottom);
}
}
// the element's content measurement on one concrete axis (x or y): the max over the
// flow children of their footprints (resolved against the element's *content* box on
// that axis) + gaps, or the element's intrinsic size for a leaf. This is the Auto
// fallback for the element's own size.
static float contentAxis(bool isX, Element* el, const Flow& flow, const Array<Element*>& kids) {
if (flow.size() == 0) {
return isX ? el->getIntrinsicW() : el->getIntrinsicH();
}
// the percent reference for children's main-axis sizes is the *parent's* content
// box (the containing block). the element's own dimensions may be stale (from a
// prior layoutElement run), so we must NOT use them. for a root element (no
// parent), the reference is 0 (percent sizes on a root with no containing box
// are degenerate; the caller should use px).
float parentContent = 0.0f;
Element* parent = el->getParent();
if (parent != nullptr) {
if (isX) {
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
} else {
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom));
}
}
float m = 0.0f;
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
m = std::max(m, childMainFootprint(c, isX ? Axis{true, false} : Axis{false, false}, parentContent));
}
float gap = (float)el->getStyle().gap;
if (flow.size() > 1 && gap > 0.0f) {
m += (float)(flow.size() - 1) * gap;
}
return m;
}
// resolve one concrete axis of the element's own size: explicit wins; Auto falls back
// to the content measurement; min/max then clamp. Returns the final axis size.
static float resolveAxisSize(bool isX, Element* el, float content, const Style& s) {
// the percent reference for this element's own size is its *parent's* box (the
// containing block). the element's own dimensions are finalized before this is
// called (layoutElement sets them before recursing into placeFlowChildren), so
// for non-root elements we can use the parent's box. for a root element there
// is no parent — percent sizes are degenerate (0), use px or Auto.
float parentBox = 0.0f;
if (el->getParent() != nullptr) {
parentBox = isX ? (float)el->getParent()->getLayoutDimensions().x : (float)el->getParent()->getLayoutDimensions().y;
} else {
// root: no containing box; percent sizes resolve against 0 (degenerate).
// the caller (layoutRoot) handles the root's own size separately.
parentBox = 0.0f;
}
float explicitSize = isX ? resolvePx(s.widthType, s.width, parentBox)
: resolvePx(s.heightType, s.height, parentBox);
float size = (isX && s.widthType != DimensionType::Auto) || (!isX && s.heightType != DimensionType::Auto) ? explicitSize : content;
float mn = isX ? (s.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(s.minWidthType, s.minWidth, parentBox))
: (s.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(s.minHeightType, s.minHeight, parentBox));
float mx = isX ? (s.maxWidthType == DimensionType::Auto ? 1e9f : resolvePx(s.maxWidthType, s.maxWidth, parentBox))
: (s.maxHeightType == DimensionType::Auto ? 1e9f : resolvePx(s.maxHeightType, s.maxHeight, parentBox));
if (size < mn) size = mn;
if (size > mx) size = mx;
if (size < 0.0f) size = 0.0f;
return size;
}
// the element's cross-axis footprint as a flex item of its parent: explicit (px/%)
// resolves against the parent's content box on the cross axis; Auto falls back to the
// element's intrinsic cross size. includes cross-axis margins. used for the parent's
// Auto cross measurement (max over children) and for non-stretch item sizing.
static float childCrossFootprint(Element* c, const FlexLayout::Axis& axis, float parentContentCross) {
const Style& s = c->getStyle();
bool isX = axis.mainIsX; // cross axis is the other one
float size;
if (isX) {
// main is x, cross is y
if (s.heightType != DimensionType::Auto) {
size = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentCross));
} else {
// Auto cross: use intrinsic (the element's natural cross size). CSS
// stretch is an alignment rule that expands the item to fill the
// parent's cross box at placement time; it does NOT change the
// element's hypothetical cross size for the parent's Auto measurement.
// setIntrinsicSize zeros this when the axis is explicit.
size = c->getIntrinsicH();
}
return size + (float)(s.marginTop + s.marginBottom);
} else {
// main is y, cross is x
if (s.widthType != DimensionType::Auto) {
size = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentCross));
} else {
size = c->getIntrinsicW();
}
return size + (float)(s.marginLeft + s.marginRight);
}
}
// resolve the child's main-axis basis for flex distribution: explicit (px/%) resolves
// against the parent's content main; Auto falls back to the child's intrinsic main.
// does NOT include margins (those are handled separately in the layout loop).
static float childMainBasis(Element* c, const FlexLayout::Axis& axis, float parentContentMain) {
const Style& s = c->getStyle();
bool isX = axis.mainIsX;
// explicit basis (flex-basis) wins over size
if (s.basisType != DimensionType::Auto) {
return std::max(0.0f, resolvePx(s.basisType, s.basis, parentContentMain));
}
float basis;
if (isX) {
if (s.widthType != DimensionType::Auto) {
basis = std::max(0.0f, resolvePx(s.widthType, s.width, parentContentMain));
} else {
// Auto main: intrinsic. setIntrinsicSize zeros this when the axis is
// explicit, so Div<H_32> in a row returns 0 (grow fills it), while
// Div with setIntrinsicSize(150,32) in a row returns 150 (shrink test).
basis = c->getIntrinsicW();
}
} else {
if (s.heightType != DimensionType::Auto) {
basis = std::max(0.0f, resolvePx(s.heightType, s.height, parentContentMain));
} else {
basis = c->getIntrinsicH();
}
}
// clamp to min/max (the item's own constraints)
float parentBox = 0.0f;
if (c->getParent() != nullptr) {
parentBox = (float)c->getParent()->getLayoutDimensions().x;
}
if (isX) {
float mn = s.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(s.minWidthType, s.minWidth, parentBox);
float mx = s.maxWidthType == DimensionType::Auto ? 1e9f : resolvePx(s.maxWidthType, s.maxWidth, parentBox);
if (basis < mn) basis = mn;
if (basis > mx) basis = mx;
} else {
float mn = s.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(s.minHeightType, s.minHeight, parentBox);
float mx = s.maxHeightType == DimensionType::Auto ? 1e9f : resolvePx(s.maxHeightType, s.maxHeight, parentBox);
if (basis < mn) basis = mn;
if (basis > mx) basis = mx;
}
return std::max(0.0f, basis);
}
} // namespace
// place flow children in the content box: compute per-line packing (with wrap),
// apply justify (main) and align (cross), write positions. this is the core of the
// flexbox algorithm. the element's own size is already resolved (by the caller); this
// function only positions the children.
static void placeFlowChildren(Element* el, const Axis& axis, const Flow& flow, const Array<Element*>& kids) {
if (flow.size() == 0) return;
const Style& s = el->getStyle();
// the element's content box (in the element's own coordinate space, before
// adding the element's position to get parent space).
float boxMain, boxCross;
if (axis.mainIsX) {
boxMain = std::max(0.0f, (float)el->getLayoutDimensions().x - (float)(s.paddingLeft + s.paddingRight));
boxCross = std::max(0.0f, (float)el->getLayoutDimensions().y - (float)(s.paddingTop + s.paddingBottom));
} else {
boxMain = std::max(0.0f, (float)el->getLayoutDimensions().y - (float)(s.paddingTop + s.paddingBottom));
boxCross = std::max(0.0f, (float)el->getLayoutDimensions().x - (float)(s.paddingLeft + s.paddingRight));
}
// the content-box origin in the element's own space (where flow starts).
float originMain, originCross;
if (axis.mainIsX) {
originMain = (float)s.paddingLeft;
originCross = (float)s.paddingTop;
} else {
// column: main is y, cross is x. the content origin is at (paddingLeft, paddingTop).
originMain = (float)s.paddingTop;
originCross = (float)s.paddingLeft;
}
// resolve each flow child's main-axis basis (for flex distribution) and cross size.
// the basis is the starting point for grow/shrink; the cross size is the item's
// final cross dimension (explicit or intrinsic, min/max clamped).
struct Placed {
size_t idx;
float basis;
float grow;
float shrink;
float mainMarginStart;
float mainMarginEnd;
float crossSize;
float crossMarginStart;
float crossMarginEnd;
float mainSize;
int line;
};
std::vector<Placed> placed;
placed.reserve(flow.size());
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
const Style& cs = c->getStyle();
Placed p{};
p.idx = flow[k];
p.basis = childMainBasis(c, axis, boxMain);
p.grow = cs.grow;
p.shrink = cs.shrink;
// the child's cross size is its own final dimensions (finalized by
// layoutElement before we got here). reading the child's *style* here
// would give the stale pre-applyStyle values (applyStyle ran during
// resolveStyles, before the child was measured, so the style still
// reflects the parent's inherited values). the child's dimensions are
// the ground truth for its final cross size.
if (axis.mainIsX) {
p.mainMarginStart = (float)cs.marginLeft;
p.mainMarginEnd = (float)cs.marginRight;
// clamp to the content box: a 100%-width item in a padded container
// should fill the content, not overflow into the padding.
p.crossSize = std::min(std::max(0.0f, (float)c->getLayoutDimensions().y), boxCross);
p.crossMarginStart = (float)cs.marginTop;
p.crossMarginEnd = (float)cs.marginBottom;
} else {
p.mainMarginStart = (float)cs.marginTop;
p.mainMarginEnd = (float)cs.marginBottom;
p.crossSize = std::min(std::max(0.0f, (float)c->getLayoutDimensions().x), boxCross);
p.crossMarginStart = (float)cs.marginLeft;
p.crossMarginEnd = (float)cs.marginRight;
}
p.mainSize = p.basis;
p.line = 0;
placed.push_back(p);
}
// line packing: walk the flow in order, accumulating main-axis usage (size +
// margins + gaps). when the line is full (and wrap is on), start a new line.
float gap = (float)s.gap;
{
float cursor = 0.0f;
int line = 0;
bool firstOnLine = true;
for (size_t k = 0; k < placed.size(); k++) {
Placed& p = placed[k];
float footprint = p.mainSize + p.mainMarginStart + p.mainMarginEnd;
float needed = (firstOnLine ? 0.0f : gap) + footprint;
if (!firstOnLine && cursor + needed > boxMain + 0.5f && s.wrap == FlexWrap::Wrap) {
line++;
cursor = 0.0f;
firstOnLine = true;
needed = footprint;
}
p.line = line;
if (!firstOnLine && gap > 0.0f) cursor += gap;
cursor += footprint;
firstOnLine = false;
}
}
// flex distribution: per line, distribute the free space (boxMain - total usage)
// among items with grow>0 (positive) or shrink>0 (negative, deficit only).
{
// collect max line index
int maxLine = 0;
for (auto& p : placed) maxLine = std::max(maxLine, p.line);
for (int ln = 0; ln <= maxLine; ln++) {
// total usage on this line (basis + margins + gaps)
float usage = 0.0f;
int count = 0;
for (size_t k = 0; k < placed.size(); k++) {
if (placed[k].line != ln) continue;
usage += placed[k].mainSize + placed[k].mainMarginStart + placed[k].mainMarginEnd;
count++;
}
if (count > 1 && gap > 0.0f) usage += (float)(count - 1) * gap;
float free = boxMain - usage;
float growSum = 0.0f, shrinkSum = 0.0f;
for (auto& p : placed) {
if (p.line != ln) continue;
growSum += p.grow;
shrinkSum += p.shrink;
}
if (free > 0.0f && growSum > 0.0f) {
for (auto& p : placed) {
if (p.line != ln || p.grow <= 0.0f) continue;
p.mainSize += free * (p.grow / growSum);
}
} else if (free < 0.0f && shrinkSum > 0.0f) {
// shrink proportionally, not below the item's min (or 0).
for (auto& p : placed) {
if (p.line != ln || p.shrink <= 0.0f) continue;
const Style& cs = kids[p.idx]->getStyle();
float mn = axis.mainIsX
? (cs.minWidthType == DimensionType::Auto ? 0.0f : resolvePx(cs.minWidthType, cs.minWidth, boxMain))
: (cs.minHeightType == DimensionType::Auto ? 0.0f : resolvePx(cs.minHeightType, cs.minHeight, boxMain));
float target = p.mainSize + free * (p.shrink / shrinkSum);
p.mainSize = std::max(mn, target);
}
}
// min/max are already applied in childMainBasis (the basis is the
// starting point, clamped to [min, max] before distribution). the
// grow/shrink distribution above cannot push an item below its min
// (shrink targets are clamped) or above its max (grow on an item at
// its max is a no-op in the demo; a full implementation would re-
// distribute, which we skip as out of scope).
}
}
// per-line positioning: for each line, compute the line's main usage and cross
// extent, apply justify (main offset) and align (cross offset), write each item's
// position in PARENT space (element position + origin + line offset + item offset).
{
int maxLine = 0;
for (auto& p : placed) maxLine = std::max(maxLine, p.line);
float lineCrossCursor = 0.0f; // cross cursor across lines (for wrap)
for (int ln = 0; ln <= maxLine; ln++) {
// line main usage (final sizes + margins + gaps)
float lineMain = 0.0f;
int count = 0;
float lineCross = 0.0f; // max cross extent on this line
for (size_t k = 0; k < placed.size(); k++) {
if (placed[k].line != ln) continue;
lineMain += placed[k].mainSize + placed[k].mainMarginStart + placed[k].mainMarginEnd;
count++;
float crossExtent = placed[k].crossSize + placed[k].crossMarginStart + placed[k].crossMarginEnd;
lineCross = std::max(lineCross, crossExtent);
}
if (count > 1 && gap > 0.0f) lineMain += (float)(count - 1) * gap;
// justify: main-axis offset of the first item on this line (relative to
// the content origin). free = boxMain - lineMain (>= 0 in normal cases).
float freeMain = boxMain - lineMain;
float mainOff = 0.0f;
if (freeMain > 0.0f) {
switch (s.justify) {
case JustifyContent::Start: mainOff = 0.0f; break;
case JustifyContent::Center: mainOff = freeMain * 0.5f; break;
case JustifyContent::End: mainOff = freeMain; break;
case JustifyContent::SpaceBetween:
case JustifyContent::SpaceAround:
case JustifyContent::SpaceEvenly:
// distributed free space; computed per-item below
mainOff = 0.0f; break;
}
}
// align: cross-axis offset of items on this line (relative to the
// content origin + line cross cursor). the line cross extent is the max
// item cross extent; freeCross = lineCrossSpace - lineCross.
// for no-wrap, lineCrossSpace = boxCross. for wrap, each line gets its
// own cross space = boxCross (lines stack, no cross overflow handling
// beyond stacking).
float lineCrossSpace = boxCross; // per-line cross space
// the per-item align: use the item's own alignSelf if set (>= 0, see
// Style::alignSelfOverride / SelfClass), else the container's `items`.
// the cross offset is computed per-item (it depends on the item's own
// cross size, not the line's max).
auto resolveAlign = [&](const Style& cs) -> AlignType {
if (cs.alignSelfOverride >= 0.0f) {
return (AlignType)(int32)cs.alignSelfOverride;
}
return s.items;
};
// the line's cross position (for wrap, lines stack: line 0 at
// originCross, line 1 at originCross + line0Cross + gap, etc.).
// for no-wrap there's only one line at originCross.
float lineCrossPos = originCross + lineCrossCursor;
// per-item positioning
float itemMainCursor = 0.0f; // cursor within the line (main axis)
bool firstOnLine = true;
float spacePerGap = 0.0f;
if (count > 1 && freeMain > 0.0f) {
switch (s.justify) {
case JustifyContent::SpaceBetween: spacePerGap = freeMain / (float)(count - 1); break;
case JustifyContent::SpaceAround: spacePerGap = freeMain / (float)count; break;
case JustifyContent::SpaceEvenly: spacePerGap = freeMain / (float)(count + 1); break;
default: spacePerGap = 0.0f; break;
}
}
for (size_t k = 0; k < placed.size(); k++) {
if (placed[k].line != ln) continue;
Placed& p = placed[k];
Element* c = kids[p.idx];
// main position: line start + item offset within line.
float itemMain;
if (firstOnLine) {
// the first item on the line: offset by mainOff (justify) plus
// any space-before (for space-around/evenly).
itemMain = mainOff;
if (s.justify == JustifyContent::SpaceAround || s.justify == JustifyContent::SpaceEvenly) {
itemMain += spacePerGap;
}
} else {
// subsequent items: cursor + gap (+ extra space for space-*).
itemMain = itemMainCursor + gap;
if (spacePerGap > 0.0f) {
itemMain += (spacePerGap - gap); // the extra beyond the base gap
}
}
itemMain += p.mainMarginStart;
// per-item align override
// freeCross for this item: the line's cross space minus this item's
// own cross size (without margins — margins are handled separately
// via crossPos). this is what align-items/align-self operates on.
float itemFreeCross = lineCrossSpace - p.crossSize;
if (itemFreeCross < 0.0f) itemFreeCross = 0.0f;
float itemCrossOff = 0.0f;
float itemCross = p.crossSize;
auto al = resolveAlign(c->getStyle());
// stretch only applies when the item has no definite cross size
// (CSS: explicit px/percent cross wins over stretch).
const Style& itemStyle = c->getStyle();
bool crossIsAuto = axis.mainIsX
? (itemStyle.heightType == DimensionType::Auto)
: (itemStyle.widthType == DimensionType::Auto);
bool canStretch = itemFreeCross > 0.0f && crossIsAuto;
if (itemFreeCross > 0.0f) {
switch (al) {
case AlignType::Start: itemCrossOff = 0.0f; break;
case AlignType::Center: itemCrossOff = itemFreeCross * 0.5f; break;
case AlignType::End: itemCrossOff = itemFreeCross; break;
case AlignType::Stretch: itemCrossOff = 0.0f; if (canStretch) itemCross = lineCrossSpace; break;
}
}
// cross position: line cross pos + item cross offset + margin.
float crossPos = lineCrossPos + itemCrossOff + p.crossMarginStart;
// Nested containers already resolved their real footprint in their own
// layout pass (recursion in layoutElement). The flex-distributed
// p.mainSize is only the final answer for leaf items.
Vector2 cDims = c->getLayoutDimensions();
bool isContainer = (c->getChildren().size() > 0);
float actualMain = axis.mainIsX ? cDims.x : cDims.y;
float actualCross = axis.mainIsX ? cDims.y : cDims.x;
float finalMain = isContainer ? actualMain : p.mainSize;
// convert main/cross (element space) to x/y (parent space).
float x, y;
if (axis.mainIsX) {
x = el->getLayoutPosition().x + originMain + itemMain;
y = el->getLayoutPosition().y + crossPos;
c->setLayoutDimensions(Vector2(std::max(0.0f, finalMain), std::max(0.0f, itemCross)));
} else {
x = el->getLayoutPosition().x + crossPos;
y = el->getLayoutPosition().y + originMain + itemMain;
c->setLayoutDimensions(Vector2(std::max(0.0f, itemCross), std::max(0.0f, finalMain)));
}
// relative position offset (applied on top of the flow position).
if (c->getStyle().position == Position::Relative) {
x += (float)c->getStyle().left;
y += (float)c->getStyle().top;
}
c->setLayoutPosition(Vector2(x, y));
// advance the cursor (containers use their real main size)
itemMainCursor = itemMain + finalMain + p.mainMarginEnd;
firstOnLine = false;
}
// advance the line cross cursor for the next line (wrap stacking).
lineCrossCursor += lineCross + (maxLine > 0 ? gap : 0.0f);
}
}
}
// layout one element: measure (resolve its own size + recurse to measure children),
// then place (position flow children in the content box, handle absolute children).
// writes `position` and `dimensions` in PARENT space (excluding margins).
void layoutElement(Element* el, const Axis& axis) {
const Array<Element*>& kids = el->getChildren();
if (el->getStyle().display == Display::Hidden) {
el->setLayout(Vector2(0), Vector2(0));
return;
}
Flow flow;
Flow::build(el, flow);
// resolve this element's own size. the content measurement uses the children's
// resolved sizes (explicit or intrinsic) — it does NOT depend on this element's
// own dimensions (which aren't set yet). percent resolution for the children
// uses the PARENT's content box (not this element's). so we can compute the
// content measurement before setting dimensions.
float mainContent = contentAxis(axis.mainIsX, el, flow, kids);
// cross-axis content: max over flow children of their cross footprints.
// the percent reference for children's cross sizes is the *parent's* content
// box (the containing block), not this element's (which may be stale from a
// prior layout run). for a root element (no parent), the reference is 0.
float parentContentCross = 0.0f;
{
Element* parent = el->getParent();
if (parent != nullptr) {
parentContentCross = axis.mainIsX
? std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom))
: std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
}
}
float crossContent = 0.0f;
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
crossContent = std::max(crossContent, childCrossFootprint(c, axis, parentContentCross));
}
// if there are no flow children, the cross content is the element's intrinsic cross.
if (flow.size() == 0) {
crossContent = axis.mainIsX ? el->getIntrinsicH() : el->getIntrinsicW();
}
// now resolve the element's own size: explicit wins, Auto falls back to content.
float mainSize = resolveAxisSize(axis.mainIsX, el, mainContent, el->getStyle());
float crossSize = resolveAxisSize(!axis.mainIsX, el, crossContent, el->getStyle());
// set the element's dimensions (in parent space, excluding margins).
if (axis.mainIsX) {
el->setLayoutDimensions(Vector2(mainSize, crossSize));
} else {
el->setLayoutDimensions(Vector2(crossSize, mainSize));
}
// the element's content box (for placing children).
float contentMain = axis.mainIsX
? std::max(0.0f, mainSize - (float)(el->getStyle().paddingLeft + el->getStyle().paddingRight))
: std::max(0.0f, mainSize - (float)(el->getStyle().paddingTop + el->getStyle().paddingBottom));
float contentCross = axis.mainIsX
? std::max(0.0f, crossSize - (float)(el->getStyle().paddingTop + el->getStyle().paddingBottom))
: std::max(0.0f, crossSize - (float)(el->getStyle().paddingLeft + el->getStyle().paddingRight));
// measure children: recurse to resolve each child's size. the child uses its OWN
// direction to determine its axis (a Row child of a Column parent has mainIsX=true
// even though the parent has mainIsX=false).
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
const Style& css = c->getStyle();
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
layoutElement(c, childAxis);
}
// absolute children: removed from the flow, positioned from this element's
// content-box corner. measure them (so their own children are laid out), then
// position by left/top offsets (right/bottom are not supported).
for (size_t i = 0; i < kids.size(); i++) {
Element* c = kids[i];
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
if (c->getStyle().position != Position::Absolute) continue;
const Style& css = c->getStyle();
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
layoutElement(c, childAxis);
float ax = (float)c->getStyle().left;
float ay = (float)c->getStyle().top;
// for absolute, the containing block is this element. the offset is from
// the content-box corner (padding + left/top). the position is in PARENT
// space: this element's position + padding + offset.
Vector2 pos;
if (axis.mainIsX) {
pos = el->getLayoutPosition() + Vector2((float)el->getStyle().paddingLeft + ax, (float)el->getStyle().paddingTop + ay);
} else {
pos = el->getLayoutPosition() + Vector2((float)el->getStyle().paddingLeft + ax, (float)el->getStyle().paddingTop + ay);
}
c->setLayoutPosition(pos);
}
// zero out all hidden children (not laid out, not rendered).
for (size_t i = 0; i < kids.size(); i++) {
if (kids[i] == nullptr) continue;
if (kids[i]->getStyle().display == Display::Hidden) {
kids[i]->setLayout(Vector2(0), Vector2(0));
}
}
// place flow children in the content box: compute per-line packing, apply
// justify (main) and align (cross), write positions. this is the bulk of the
// flexbox algorithm; see the plan for the exact rules.
placeFlowChildren(el, axis, flow, kids);
// A container child was measured (recursion above) BEFORE its position was set
// here, so its own grandchildren were laid out relative to a stale position.
// Re-run each container child's placement now that the parent position is final.
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
if (c->getChildren().size() == 0) continue;
const Style& css = c->getStyle();
if (css.position == Position::Absolute) continue;
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
Flow cf;
Flow::build(c, cf);
const Array<Element*>& cKids = c->getChildren();
placeFlowChildren(c, childAxis, cf, cKids);
}
}
// the public entry point: set the root's dimensions to the viewport, then run the
// full layout. the root has no parent, so its percent sizes are degenerate (0) —
// the root should use explicit (px) or Auto sizes.
void layoutRoot(Element* root, UVector2 viewport) {
if (root == nullptr) return;
// the root's dimensions are the viewport (the root IS the viewport's content).
// the root has no parent, so resolveAxisSize will treat its percent sizes as 0
// (degenerate) — for the root we want the viewport as the explicit size.
// we set the root's dimensions directly to the viewport (minus padding) so the
// content box is correct, then run layoutElement to place the children.
float w = (float)viewport.x;
float h = (float)viewport.y;
// apply min/max clamp to the root's viewport size (the root's style may have
// min/max that constrain the viewport — unusual but handled for consistency).
const Style& s = root->getStyle();
// for the root, the percent reference is the viewport itself (the root is the
// top-level container). we resolve the root's size as: explicit (px) wins; %
// resolves against the viewport; Auto falls back to the content measurement.
// this is the only place the "parent" is the viewport rather than another
// element, so we handle it specially here.
auto resolveRootAxis = [&](bool isX, float vp, float content, DimensionType t, float v, DimensionType mnT, float mn, DimensionType mxt, float mx) -> float {
float explicitSize = (t == DimensionType::Pixel) ? v : (t == DimensionType::Percent) ? (v / 100.0f * vp) : content;
float mnR = (mnT == DimensionType::Auto) ? 0.0f : ((mnT == DimensionType::Pixel) ? mn : (mnT == DimensionType::Percent) ? (mn / 100.0f * vp) : 0.0f);
float mxR = (mxt == DimensionType::Auto) ? 1e9f : ((mxt == DimensionType::Pixel) ? mx : (mxt == DimensionType::Percent) ? (mx / 100.0f * vp) : 1e9f);
float size = explicitSize;
if (size < mnR) size = mnR;
if (size > mxR) size = mxR;
if (size < 0.0f) size = 0.0f;
return size;
};
// compute the root's content measurement (for the Auto fallback) — same as
// layoutElement does, but the root has no parent so the percent reference for
// children is the root's own content box (which we compute here).
// for simplicity, the Auto fallback for the root uses the viewport (the root
// is the viewport; its content is bounded by the viewport). this is a
// reasonable default: an Auto-sized root fills the viewport.
float mainContent = (float)viewport.x, crossContent = (float)viewport.y;
if (s.direction == FlexDirection::Column || s.direction == FlexDirection::ColumnReverse) {
mainContent = (float)viewport.y;
crossContent = (float)viewport.x;
}
bool isX = (s.direction == FlexDirection::Row || s.direction == FlexDirection::RowReverse);
float mainSize = resolveRootAxis(isX, isX ? (float)viewport.x : (float)viewport.y, mainContent,
isX ? s.widthType : s.heightType, isX ? s.width : s.height,
isX ? s.minWidthType : s.minHeightType, isX ? s.minWidth : s.minHeight,
isX ? s.maxWidthType : s.maxHeightType, isX ? s.maxWidth : s.maxHeight);
float crossSize = resolveRootAxis(!isX, !isX ? (float)viewport.x : (float)viewport.y, crossContent,
!isX ? s.widthType : s.heightType, !isX ? s.width : s.height,
!isX ? s.minWidthType : s.minHeightType, !isX ? s.minWidth : s.minHeight,
!isX ? s.maxWidthType : s.maxHeightType, !isX ? s.maxWidth : s.maxHeight);
Vector2 dims = isX ? Vector2(mainSize, crossSize) : Vector2(crossSize, mainSize);
root->setLayoutDimensions(dims);
// the root's own size is final (resolved against the viewport above). the
// children's percent reference is the root's now-finalized dimensions, so
// `layoutElement` is correct for them. what we still owe the root is: measure
// its flow children (recursively), position its absolute children, and place
// its flow children in the root's content box — i.e. everything `layoutElement`
// does *except* re-resolving the root's own size (which would use a null parent
// and a 0 percent reference, wrong for the root).
Axis axis{isX, isX ? (s.direction == FlexDirection::RowReverse) : (s.direction == FlexDirection::ColumnReverse)};
const Array<Element*>& kids = root->getChildren();
if (root->getStyle().display == Display::Hidden) {
root->setLayout(Vector2(0), Vector2(0));
return;
}
Flow flow;
Flow::build(root, flow);
// zero out hidden children (not laid out, not rendered).
for (size_t i = 0; i < kids.size(); i++) {
if (kids[i] == nullptr) continue;
if (kids[i]->getStyle().display == Display::Hidden) {
kids[i]->setLayout(Vector2(0), Vector2(0));
}
}
// measure the flow children (recursively) and the absolute children.
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
const Style& css = c->getStyle();
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
layoutElement(c, childAxis);
}
for (size_t i = 0; i < kids.size(); i++) {
Element* c = kids[i];
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
if (c->getStyle().position != Position::Absolute) continue;
const Style& css = c->getStyle();
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
layoutElement(c, childAxis);
float ax = (float)c->getStyle().left;
float ay = (float)c->getStyle().top;
Vector2 pos = root->getLayoutPosition() + Vector2((float)root->getStyle().paddingLeft + ax, (float)root->getStyle().paddingTop + ay);
c->setLayoutPosition(pos);
}
// place the root's flow children in the root's content box.
placeFlowChildren(root, axis, flow, kids);
// Same fix as in layoutElement: container children were measured before their
// position was set, so re-run their placement with the now-final position.
for (size_t k = 0; k < flow.size(); k++) {
Element* c = kids[flow[k]];
if (c->getChildren().size() == 0) continue;
const Style& css = c->getStyle();
if (css.position == Position::Absolute) continue;
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
Flow cf;
Flow::build(c, cf);
const Array<Element*>& cKids = c->getChildren();
placeFlowChildren(c, childAxis, cf, cKids);
}
}
} // namespace FlexLayout
} // namespace UI
} // namespace Seele