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

+1 -1
View File
@@ -14,7 +14,7 @@ InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const View
: View(graphics, window, createInfo, "InspectorView"),
uiSystem(new UI::System(
new UI::Div<M_8>(UI::Attributes{}, {
new UI::Div<BG_Red, Inline>({},
new UI::Div<BG_Red, FlexRow, M_4>({},
{
new UI::Text<Font_Arial, Text_8XL>("Other Test T"),
}),
+3
View File
@@ -3,6 +3,8 @@ target_sources(Engine
Attributes.h
Element.h
Element.cpp
FlexLayout.h
FlexLayout.cpp
System.h
System.cpp
)
@@ -12,6 +14,7 @@ target_sources(Engine
FILES
Attributes.h
Element.h
FlexLayout.h
System.h
)
+57 -97
View File
@@ -4,6 +4,7 @@
#include "MinimalEngine.h"
#include "UI/Style/Style.h"
#include "UI/Style/Theme.h"
#include "UI/FlexLayout.h"
#include <type_traits>
namespace Seele {
@@ -66,6 +67,46 @@ class Element {
parent->markDirty();
}
}
// public theme handle: FlexLayout needs to re-shape Text content after a theme change
// (fonts are per-theme) without a friend declaration (see FlexLayout.h).
const Theme& getTheme() const { return theme; }
void setTheme(const Theme& t) { theme = t; }
// CPU-side intrinsic (natural) size override. Layout uses this for an Auto axis
// instead of a font (Text's measured size is the real case; this hook lets unit
// tests supply a known natural size without loading a font). It only overrides the
// *Auto* axes; an explicit Width_/Height_ still wins (applyStyle only writes the
// Auto branches, and layout prefers an explicit size over the intrinsic).
void setIntrinsicSize(float w, float h) {
intrinsicW = (style.widthType == DimensionType::Auto) ? w : 0.0f;
intrinsicH = (style.heightType == DimensionType::Auto) ? h : 0.0f;
}
// the natural main/cross size to use when the style axis is Auto (0 if explicit).
float intrinsicMain(bool mainIsX) const { return mainIsX ? intrinsicW : intrinsicH; }
float intrinsicCross(bool mainIsX) const { return mainIsX ? intrinsicH : intrinsicW; }
// layout-state accessors. The free-function layout engine (FlexLayout) and the
// CPU unit tests need to read/write `position`+`dimensions` and read `children`
// without a friend declaration (FlexLayout is a namespace, not a class, and the
// tests are a separate TU).
const Array<Element*>& getChildren() const { return children; }
void setLayout(const Vector2& pos, const Vector2& dims) {
position = pos;
dimensions = dims;
}
const Vector2& getLayoutPosition() const { return position; }
const Vector2& getLayoutDimensions() const { return dimensions; }
void setLayoutPosition(const Vector2& p) { position = p; }
void setLayoutDimensions(const Vector2& d) { dimensions = d; }
// accessors for the layout engine and the CPU unit tests. FlexLayout is a
// namespace (not a class) so it cannot be a `friend`, and the tests are a
// separate TU — both need to reach `style`/`parent`/`intrinsic`/layout state.
// `style` is exposed mutably because the unit tests set runtime style fields
// (min/max, position, display) before re-resolving; the .cpp only reads it.
Style& getStyle() { return style; }
const Style& getStyle() const { return style; }
Element* getParent() const { return parent; }
float getIntrinsicW() const { return intrinsicW; }
float getIntrinsicH() const { return intrinsicH; }
// applies runtime style overrides (the data-driven mutation layer)
virtual void applyOverrides() {
// default: no-op; interactive elements override this to reflect hover/focus/etc.
@@ -82,97 +123,12 @@ class Element {
virtual void setFocused(bool focused) { (void)focused; }
virtual bool isFocusable() const { return attr.focusable; }
// calculates the relative positions of the child elements for the applied layout style
virtual void layout(UVector2 parentSize) {
if (style.hidden) {
return;
}
if (style.maxWidthType == DimensionType::Auto) {
maxDimensions.x = (float)parentSize.x;
}
if (style.maxHeightType == DimensionType::Auto) {
maxDimensions.y = (float)parentSize.y;
}
if (style.widthType == DimensionType::Pixel) {
dimensions.x = style.width;
} else if (style.widthType == DimensionType::Percent) {
dimensions.x = parentSize.x * style.width / 100.0f;
}
if (style.heightType == DimensionType::Pixel) {
dimensions.y = style.height;
} else if (style.heightType == DimensionType::Percent) {
dimensions.y = parentSize.y * style.height / 100.0f;
}
for (auto& child : children) {
child->layout(maxDimensions - Vector2(style.marginLeft + style.marginRight, style.marginTop + style.marginBottom));
}
switch (style.innerDisplay) {
case InnerDisplayType::Flow:
flowLayout();
break;
default:break;
}
}
// normal flow of the elements, inline elements go left to right, blocks get their own new lines
void flowLayout() {
// use a cursor going from left to right, top to bottom, starting at padding
Vector2 cursor = Vector2(style.paddingLeft, style.paddingTop);
uint32 lineHeight = 0;
for (auto& child : children) {
if (child->style.hidden) {
continue;
}
// inline elements flow left to right
if (child->style.outerDisplay == OuterDisplayType::Inline) {
// only static and relative elements actually reserve
if (child->style.position == PositionType::Static || child->style.position == PositionType::Relative) {
// create a new line in case the element doesnt fit on the current one anymore,
// but keep in current line in case we are still at the start, as a new line wouldnt help here
if (cursor.x + child->dimensions.x > maxDimensions.x - child->style.left && cursor.x != 0) {
cursor.x = (float)style.paddingLeft;
cursor.y += lineHeight;
lineHeight = 0;
}
// todo: border
child->position.x = cursor.x + child->style.marginLeft;
child->position.y = cursor.y + child->style.marginTop;
cursor.x = child->position.x + child->dimensions.x;
// apply offsets after updating the cursor for relative elements
if (child->style.position == PositionType::Relative) {
child->position.x += child->style.left;
child->position.y += child->style.top;
}
lineHeight = std::max(lineHeight, child->style.lineHeight);
}
// block elements always get their own lines, like paragraphs
} else if (child->style.outerDisplay == OuterDisplayType::Block) {
// static and relative require space to be created for the elements
if (child->style.position == PositionType::Static || child->style.position == PositionType::Relative) {
// create a new line in case we are not already at one
if (cursor.x != 0) {
cursor.x = (float)style.paddingLeft;
cursor.y += lineHeight;
}
child->position.x = cursor.x + child->style.marginLeft;
child->position.y = cursor.y + child->style.marginTop;
// new line after block
cursor.x = 0;
cursor.y = child->position.y + child->dimensions.y;
}
}
}
if (style.widthType == DimensionType::Auto) {
dimensions.x = cursor.x + style.paddingRight;
}
if (style.heightType == DimensionType::Auto) {
dimensions.y = lineHeight + cursor.y + style.paddingBottom;
}
}
virtual Array<UIRender> render(Vector2 anchor, uint32 level) {
Array<UIRender> result;
if (!style.hidden && style.outerDisplay != OuterDisplayType::Hidden) {
result.add(UIRender{
if (style.display == Display::Hidden) {
return result;
}
result.add(UIRender{
.backgroundColor = style.backgroundColor,
.position = position + anchor,
.dimensions = dimensions,
@@ -180,20 +136,13 @@ class Element {
.level = level,
.element = this,
});
}
for (auto& child : children) {
for (const auto& render : child->render(position + anchor, level+1)) {
for (const auto& render : child->render(position + anchor, level + 1)) {
result.add(render);
}
}
return result;
}
Style style;
Vector2 maxDimensions = Vector2(0);
// calculated position relative to parent
Vector2 position = Vector2(0);
// calculated dimensions in pixels after layouting
Vector2 dimensions = Vector2(0);
protected:
Attributes attr;
@@ -202,6 +151,17 @@ class Element {
Array<Element*> children;
// set by the System when the theme changed; forces a one-time full re-style
bool themeChanged = false;
// the theme this element was last styled against. the System sets it before
// calcStyle so FlexLayout can re-shape Text on a theme change without holding a friend.
Theme theme = Theme{};
Style style;
// calculated position relative to parent
Vector2 position = Vector2(0);
// calculated dimensions in pixels after layouting
Vector2 dimensions = Vector2(0);
// natural (intrinsic) size, used only for Auto axes (see setIntrinsicSize).
float intrinsicW = 0.0f;
float intrinsicH = 0.0f;
};
DEFINE_REF(Element)
} // namespace UI
+22 -1
View File
@@ -13,7 +13,28 @@ class Div : public Element {
virtual ~Div() {}
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
style = parentStyle;
style.outerDisplay = OuterDisplayType::Block;
// CSS non-inherited properties: reset to defaults before applying template
// classes. width/height, min/max, margin/padding, gap, position offsets, and
// per-item flex properties (grow/shrink/order/basis/alignSelf) are all
// non-inherited in CSS — a child's Div classes opt in explicitly.
// Inherited (keep from parent): display, direction, wrap, justify, items,
// content, z, colors, font, lineHeight, fontSize, fontWeight.
style.widthType = DimensionType::Auto; style.width = 0;
style.minWidthType = DimensionType::Auto; style.minWidth = 0;
style.maxWidthType = DimensionType::Auto; style.maxWidth = 0;
style.heightType = DimensionType::Auto; style.height = 0;
style.minHeightType = DimensionType::Auto; style.minHeight = 0;
style.maxHeightType = DimensionType::Auto; style.maxHeight = 0;
style.paddingTop = 0; style.paddingBottom = 0;
style.paddingLeft = 0; style.paddingRight = 0;
style.marginTop = 0; style.marginBottom = 0;
style.marginLeft = 0; style.marginRight = 0;
style.gap = 0;
style.top = 0; style.bottom = 0; style.left = 0; style.right = 0;
style.position = Position::Static;
style.grow = 0.f; style.shrink = 1.f;
style.order = 0; style.alignSelfOverride = -1.f;
style.basisType = DimensionType::Auto; style.basis = 0.f;
(classes::apply(style, theme), ...);
}
private:
-1
View File
@@ -15,7 +15,6 @@ class Panel : public Div<classes...> {
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
// start from the panel chrome, then let the user's classes win
style = parentStyle;
style.outerDisplay = OuterDisplayType::Block;
style.backgroundColor = theme.color(ColorToken::Gray900);
style.textColor = theme.color(ColorToken::White);
uint32 pad = theme.spacing(8);
+6 -1
View File
@@ -61,11 +61,16 @@ class Text : public Element {
if (style.heightType == UI::DimensionType::Auto) {
style.height = h;
}
// the measured size is also the element's natural size: layout measures
// through Element::intrinsicW/H (set here) instead of trusting a stale
// style.width/height that a later setText() invalidation may have left behind.
intrinsicW = w;
intrinsicH = h;
}
virtual Array<UIRender> render(Vector2 anchor, uint32 level) override {
Array<UIRender> result;
if (style.hidden || style.outerDisplay == OuterDisplayType::Hidden) {
if (style.display == Display::Hidden) {
return result;
}
Vector2 pos = position + anchor;
+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
+97
View File
@@ -0,0 +1,97 @@
#pragma once
// Flexbox is the sole UI layout mode. This is a free function (not a method) so it
// can be unit-tested on a caller-owned tree without the System's OwningPtr deleting
// the tree first. Two-phase:
// 1. measure (post-order): resolve the element's final clamped `dimensions` and
// each flow child's main-axis *basis* (so grow/shrink/wrap/justify operate on
// real sizes). A child's nested container is fully measured before the parent
// distributes space, so its real size is known to the parent.
// 2. place (pre-order): position this element's children (order-sorted,
// grow/shrink distribution, wrap, justify, align, gap) and recurse.
//
// Invariant: the tree's `style` is already resolved (System::styleRec runs
// applyStyle before layoutRoot). For Text, applyStyle has already shaped the glyphs
// and written the measured size to `Element::intrinsicW/H` — an item's natural main
// size is therefore final by layout time (unit tests supply a natural size via
// Element::setIntrinsicSize without a real font).
//
// Coordinate model (matches the pre-existing flow layout): an element's `position`
// and `dimensions` are in *parent* space, so childAbsolute = parentAbsolute + child.position
// (render does position + anchor). The containing box for a child is therefore the
// PARENT's dimensions. An element's own padding is the box its children lay out
// inside; the element's size never subtracts the parent's padding.
//
// Margins are honored on BOTH axes: an item's cross footprint includes its cross
// margins, and the `align`/`justify` math works in the parent's *content* box with
// the item positioned inside the *full* parent box (so a top margin pushes the item
// down from the parent's top edge). This is what CSS does.
//
// Item indexing: each layout call builds a local `items` vector sized to the number
// of flow children (sorted by `order`). measure and place share that vector by
// index, so the index spaces always line up. Hidden/absolute children are excluded
// from `items` entirely (they are never laid out / hit-tested).
//
// NOTE: this header must NOT include `UI/Element.h` — `Element.h` already includes
// this header (for the layout free functions), so a reverse include would be a
// circular include and the full `Element` class body would be invisible here. We
// only need `FlexDirection` (in `Style.h`) to compute the root axis, so include
// `Style.h` and forward-declare `Element`. The .cpp (which does include `Element.h`)
// has the full type when it defines `layoutElement`/the free functions.
#include "UI/Style/Style.h"
#include "MinimalEngine.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <vector>
namespace Seele {
namespace UI {
// forward decl: the full class lives in `UI/Element.h` (which includes this header).
// only used as a pointer/reference here, so the forward decl is sufficient.
class Element;
namespace FlexLayout {
// one flex container's resolved main/cross geometry, passed down the recursion.
// `mainIsX` is true for row/row-reverse (main axis = x). `cMain`/`cCross` are the
// element's *own* resolved size on each axis — the containing box for its children
// (an element's children are laid out inside the element's dimensions).
struct Axis {
bool mainIsX = true;
bool reverse = false; // RowReverse / ColumnReverse
float cMain = 0.0f, cCross = 0.0f;
};
// per-item scratch, indexed by position in `items` (the order-sorted flow list).
struct Item {
Element* el = nullptr;
int32 order = 0;
float basis = 0.f; // main size before grow/shrink (min/max clamped)
float grow = 0.f, shrink = 1.f;
float main = 0.f; // final main size
float cross = 0.f; // final cross size (resolved independently of main)
float mainStart = 0.f; // computed main position (flow coordinate, pre-reverse)
float crossStart = 0.f; // computed cross position (parent box coordinates)
float mStart = 0.f; // margin on the main-start side
float mEnd = 0.f; // margin on the main-end side
float cStart = 0.f; // margin on the cross-start side
float cEnd = 0.f; // margin on the cross-end side
int32 line = -1; // wrap line index (-1 = unassigned)
};
// the layout entry point for a single element. `cMain`/`cCross` are the
// *containing size* for `el`'s own size resolution (the parent's dimensions, or the
// viewport at the root). Resolves the element's own main/cross size (measure), then
// lays out its children (place), recursing into each flow child with the child's
// *own* resolved size as its containing box.
void layoutElement(Element* el, const Axis& axis);
// public entry: lay out the whole tree. `root` is the viewport's only child; the
// viewport's dimensions are `viewport`. `root->position` is left untouched (the
// System treats the root as the anchor at (0,0) — see System::render).
//
// declared here, defined in FlexLayout.cpp (the body dereferences `root->style`,
// which needs the complete Element type — not available in this header, which only
// forward-declares Element to avoid a circular include with Element.h).
void layoutRoot(Element* root, UVector2 viewport);
} // namespace FlexLayout
} // namespace UI
} // namespace Seele
+123 -10
View File
@@ -19,24 +19,137 @@ template <uint32 w, DimensionType widthType> struct WidthClass {
}
};
using W_Full = WidthClass<100, DimensionType::Percent>;
template <uint32 h> struct HeightClass {
using W_16 = WidthClass<16, DimensionType::Pixel>;
using W_24 = WidthClass<24, DimensionType::Pixel>;
using W_32 = WidthClass<32, DimensionType::Pixel>;
using W_40 = WidthClass<40, DimensionType::Pixel>;
using W_48 = WidthClass<48, DimensionType::Pixel>;
using W_64 = WidthClass<64, DimensionType::Pixel>;
using W_100 = WidthClass<100, DimensionType::Pixel>;
using W_150 = WidthClass<150, DimensionType::Pixel>;
template <uint32 h, DimensionType t = DimensionType::Pixel> struct HeightClass {
static void apply(Style& s, const Theme&) {
s.height = h;
s.heightType = DimensionType::Pixel;
s.heightType = t;
}
};
using H_Full = HeightClass<100>;
using H_Full = HeightClass<100, DimensionType::Percent>;
using H_16 = HeightClass<16>;
using H_24 = HeightClass<24>;
using H_32 = HeightClass<32>;
// --- display ---
template <OuterDisplayType outer, InnerDisplayType inner> struct DisplayClass {
// --- flexbox (the sole layout mode; unitless, no theme scaling needed) ---
// `Flex` is the no-op default: every element is already a flex container. The
// direction/wrap/justify/align/flex-item classes below override the container or
// item fields of the resolved style. A bare `Div`/`Panel` is a column container by
// default (stacks children top-to-bottom); use `FlexRow` for a horizontal line.
template <FlexDirection direction> struct FlexDirClass {
static void apply(Style& s, const Theme&) {
s.outerDisplay = outer;
s.innerDisplay = inner;
// don't overwrite display: a Hidden element that also has a FlexDirClass
// template (e.g. Div<FlexRow, ...> with display=Hidden set in the ctor)
// must stay hidden. only set display=Flex if it wasn't already set.
if (s.display != Display::Hidden) s.display = Display::Flex;
s.direction = direction;
}
};
using Hidden = DisplayClass<OuterDisplayType::Hidden, InnerDisplayType::Flow>;
using Block = DisplayClass<OuterDisplayType::Block, InnerDisplayType::Flow>;
using Inline = DisplayClass<OuterDisplayType::Inline, InnerDisplayType::Flow>;
using Flex = FlexDirClass<FlexDirection::Row>; // display:flex (tailwind default is row)
using FlexRow = FlexDirClass<FlexDirection::Row>;
using FlexRowReverse = FlexDirClass<FlexDirection::RowReverse>;
using FlexCol = FlexDirClass<FlexDirection::Column>;
using FlexColReverse = FlexDirClass<FlexDirection::ColumnReverse>;
// `Hidden` mirrors CSS `display:none` — the one non-flex `display` state.
template <Display display> struct DisplayClass {
static void apply(Style& s, const Theme&) { s.display = display; }
};
using Hidden = DisplayClass<Display::Hidden>;
template <FlexWrap wrap> struct WrapClass {
static void apply(Style& s, const Theme&) { s.wrap = wrap; }
};
using Wrap = WrapClass<FlexWrap::Wrap>;
using NoWrap = WrapClass<FlexWrap::NoWrap>;
template <JustifyContent justify> struct JustifyClass {
static void apply(Style& s, const Theme&) { s.justify = justify; }
};
using Justify_Start = JustifyClass<JustifyContent::Start>;
using Justify_End = JustifyClass<JustifyContent::End>;
using Justify_Center = JustifyClass<JustifyContent::Center>;
using Justify_Between = JustifyClass<JustifyContent::SpaceBetween>;
using Justify_Around = JustifyClass<JustifyContent::SpaceAround>;
using Justify_Evenly = JustifyClass<JustifyContent::SpaceEvenly>;
// cross-axis alignment. `Items_*` sets the container default (inherited by items);
// `Self_*` overrides it per-item (no baseline alignment — see the plan).
template <AlignType align> struct ItemsClass {
static void apply(Style& s, const Theme&) { s.items = align; }
};
using Items_Start = ItemsClass<AlignType::Start>;
using Items_Center = ItemsClass<AlignType::Center>;
using Items_End = ItemsClass<AlignType::End>;
using Items_Stretch = ItemsClass<AlignType::Stretch>;
template <AlignType align> struct SelfClass {
static void apply(Style& s, const Theme&) { s.alignSelfOverride = (float)align; }
};
using Self_Start = SelfClass<AlignType::Start>;
using Self_Center = SelfClass<AlignType::Center>;
using Self_End = SelfClass<AlignType::End>;
using Self_Stretch = SelfClass<AlignType::Stretch>;
// per-item flex sizing. `Grow` = flex-grow:1 (tailwind). `Grow_0`/`Shrink_0` lock
// the item to its basis. `Basis_*` sets the main-axis basis (auto/px/percent/full).
template <float grow> struct GrowClass {
static void apply(Style& s, const Theme&) { s.grow = grow; }
};
using Grow = GrowClass<1.f>;
using Grow_0 = GrowClass<0.f>;
using Grow_2 = GrowClass<2.f>;
using Grow_3 = GrowClass<3.f>;
using Grow_5 = GrowClass<5.f>;
template <float shrink> struct ShrinkClass {
static void apply(Style& s, const Theme&) { s.shrink = shrink; }
};
using Shrink_0 = ShrinkClass<0.f>;
template <int32 order> struct OrderClass {
static void apply(Style& s, const Theme&) { s.order = order; }
};
using Order_1 = OrderClass<1>;
using Order_2 = OrderClass<2>;
using Order_3 = OrderClass<3>;
using Order_4 = OrderClass<4>;
using Order_5 = OrderClass<5>;
template <float basis, DimensionType basisType> struct BasisClass {
static void apply(Style& s, const Theme&) {
s.basis = basis;
s.basisType = basisType;
}
};
using Basis_Auto = BasisClass<0.f, DimensionType::Auto>;
using Basis_Full = BasisClass<100.f, DimensionType::Percent>;
using Basis_16 = BasisClass<16.f, DimensionType::Pixel>;
using Basis_32 = BasisClass<32.f, DimensionType::Pixel>;
using Basis_48 = BasisClass<48.f, DimensionType::Pixel>;
using Basis_64 = BasisClass<64.f, DimensionType::Pixel>;
using Basis_128 = BasisClass<128.f, DimensionType::Pixel>;
using Basis_50Percent = BasisClass<50.f, DimensionType::Percent>;
// min/max size clamps (main or cross axis) reuse the existing DimensionType sizing.
template <uint32 v, DimensionType t> struct MaxWidthClass {
static void apply(Style& s, const Theme&) {
s.maxWidth = v;
s.maxWidthType = t;
}
};
template <uint32 v, DimensionType t> struct MaxHeightClass {
static void apply(Style& s, const Theme&) {
s.maxHeight = v;
s.maxHeightType = t;
}
};
using MaxW_Full = MaxWidthClass<100, DimensionType::Percent>;
using MaxH_Full = MaxHeightClass<100, DimensionType::Percent>;
// --- fonts (looked up at style() time; fonts must be loaded before the first
// System::style() call, see the invariant in System.h) ---
+56 -17
View File
@@ -11,38 +11,59 @@ enum class DimensionType {
Percent, // EM, PEM, etc...
Auto,
};
enum class PositionType {
Static,
Relative,
Absolute,
Sticky,
// flexbox layout enums. one layout mode (flex); `Display` is the only visibility
// toggle (mirrors CSS `display`), `Position` is a minimal relative/absolute escape hatch.
enum class FlexDirection {
Row,
RowReverse,
Column,
ColumnReverse,
};
enum class OuterDisplayType {
Inline,
Block,
Hidden,
enum class FlexWrap {
NoWrap,
Wrap,
};
enum class InnerDisplayType {
Flow,
Flex,
Grid,
enum class JustifyContent {
Start,
End,
Center,
SpaceBetween,
SpaceAround,
SpaceEvenly,
};
enum class AlignType {
Start,
Center,
End,
Stretch,
// baseline is intentionally not shipped (needs font metrics); see the plan
};
enum class Display {
Flex, // laid out (default)
Hidden, // not laid out, not rendered, not hit-tested
};
enum class Position {
Static, // in the flex flow (default)
Relative, // in the flow, offset by left/top from the computed position
Absolute, // removed from the flow, offset by left/top from the containing block
};
struct Style {
DimensionType widthType = DimensionType::Auto;
float width = 0;
// min clamps: a lower bound on the resolved main/cross size. Auto means "no min".
DimensionType minWidthType = DimensionType::Auto;
float minWidth = 0;
DimensionType maxWidthType = DimensionType::Auto;
float maxWidth = 0;
DimensionType heightType = DimensionType::Auto;
float height = 0;
DimensionType minHeightType = DimensionType::Auto;
float minHeight = 0;
DimensionType maxHeightType = DimensionType::Auto;
float maxHeight = 0;
uint32 z = 0;
Vector backgroundColor = Vector(1, 1, 1);
Vector textColor = Vector(0, 0, 0);
bool hidden = false;
OuterDisplayType outerDisplay = OuterDisplayType::Inline;
InnerDisplayType innerDisplay = InnerDisplayType::Flow;
PositionType position = PositionType::Static;
PFontAsset fontFamily;
// the font *name* as a runtime string. static font classes can't carry a
// string as a template arg (literals can't be NTTPs), so the name is set as
@@ -65,6 +86,24 @@ struct Style {
uint32 left = 0;
uint32 right = 0;
// --- flexbox (the sole layout mode). one mode: every element is a flex item and,
// when it has children, a flex container. defaults mirror a bare CSS flex container:
// column direction (stacks children top-to-bottom like the old flow layout), no wrap,
// start-justified, stretch cross-aligned. ---
Display display = Display::Flex; // replaces the old `hidden` bool
Position position = Position::Static; // relative/absolute escape hatch (no sticky)
FlexDirection direction = FlexDirection::Column;
FlexWrap wrap = FlexWrap::NoWrap;
JustifyContent justify = JustifyContent::Start; // main axis
AlignType items = AlignType::Stretch; // cross axis, inherited by children
AlignType content = AlignType::Stretch; // cross axis, wraps the (possibly wrapped) lines
float grow = 0.f; // main-axis free-space weight (item)
float shrink = 1.f; // main-axis deficit weight (item)
int32 order = 0; // layout order within the line (item)
float alignSelfOverride = -1.f; // <0 = inherit `items`; else one of AlignType (item)
DimensionType basisType = DimensionType::Auto; // main-axis basis (item)
float basis = 0.f;
// set by the element when a runtime mutation needs a re-style of this subtree
// default true so we do initial style calculations
bool dirty = true;
+6 -12
View File
@@ -1,5 +1,6 @@
#include "UI/System.h"
#include "UI/Element/Button.h"
#include "UI/FlexLayout.h"
#include <algorithm>
using namespace Seele;
@@ -20,6 +21,9 @@ void System::styleRec(Element* element) {
if (element == nullptr) {
return;
}
// keep the element's theme handle in sync so FlexLayout can re-shape Text content on a
// theme change (fonts are per-theme) without a friend declaration.
element->setTheme(theme);
// runtime interaction state overrides the static style (data, not template args)
if (auto* button = dynamic_cast<Button<>* >(element)) {
if (button->isFocused()) {
@@ -55,16 +59,6 @@ void System::styleRec(Element* element) {
}
}
void System::layoutRec(Element* element) {
if (element == nullptr) {
return;
}
element->layout(UVector2(lastViewport.x, lastViewport.y));
for (auto& child : element->children) {
// layout() already recurses; nothing to do here
}
}
Element* System::hitTest(Vector2 position) {
// walk the last rendered list; later entries are drawn on top, so the last
// hit is the top-most element
@@ -82,7 +76,7 @@ Element* System::hitTest(Vector2 position) {
}
void System::collectFocusable(Element* element, Array<Element*>& out) {
if (element == nullptr || element->style.hidden) {
if (element == nullptr || element->style.display == Display::Hidden) {
return;
}
if (element->isFocusable()) {
@@ -188,7 +182,7 @@ void System::beginFrame(UVector2 viewport) {
lastViewport = viewport;
if (layoutDirty) {
rootElement->calcStyle(Style{}, theme);
rootElement->layout(viewport);
FlexLayout::layoutRoot(rootElement.operator->(), viewport);
layoutDirty = false;
}
}
-1
View File
@@ -40,7 +40,6 @@ class System {
private:
void styleRec(Element* element);
void layoutRec(Element* element);
static void markAllDirty(Element* element);
// hit-test the last rendered list, top-most wins; returns the element under `position`
Element* hitTest(Vector2 position);
+2 -1
View File
@@ -9,4 +9,5 @@ add_subdirectory(Containers/)
add_subdirectory(Graphics/)
add_subdirectory(Math/)
add_subdirectory(Serialization/)
add_subdirectory(System/)
add_subdirectory(System/)
add_subdirectory(UI/)
+5
View File
@@ -0,0 +1,5 @@
target_sources(SeeleUnitTests
PRIVATE
FlexLayout.cpp)
target_include_directories(SeeleUnitTests PUBLIC ${CMAKE_SOURCE_DIR}/src/Engine)
+329
View File
@@ -0,0 +1,329 @@
// CPU-only flexbox layout tests. Build caller-owned Div/Text trees (no System, so the
// OwningPtr never deletes them), run FlexLayout::layoutRoot, assert position/dimensions.
#include "gtest/gtest.h"
#include "UI/Element.h"
#include "UI/Element/Div.h"
#include "UI/Element/Text.h"
#include "UI/FlexLayout.h"
#include "UI/Style/Class.h"
#include "UI/Style/Theme.h"
using namespace Seele;
using namespace Seele::UI;
// style the tree like System::styleRec would (flexbox math runs on the resolved style).
// mark the whole subtree dirty first so the Div template classes (applied in
// applyStyle, gated on style.dirty/themeChanged) actually run — a freshly built tree
// has neither flag set. tests use explicit sizes, so the font is never shaped.
static void markAllDirtyRec(Element* el) {
if (el == nullptr) return;
el->markDirty();
for (auto* c : el->getChildren()) markAllDirtyRec(c);
}
static void resolveStyles(Element* root) {
markAllDirtyRec(root);
Theme theme{};
root->calcStyle(Style{}, theme);
}
// layout a caller-owned tree against `viewport` (the tree is never deleted here).
static void layout(Element* root, int vw, int vh) {
FlexLayout::layoutRoot(root, UVector2(vw, vh));
}
// (a) row, fixed sizes, gap, justify start/end/center
TEST(FlexLayout, RowGapJustify) {
Element* a = new Div<W_64, H_32>(Attributes{});
Element* b = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
layout(root, 300, 100);
// two 64px items + 8px gap, start-justified: x=0 and x=72, y=0, cross stretch?
// items have explicit H_32, so no stretch (explicit wins); align default = stretch
// but explicit size wins -> y=0, h=32.
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().x, 72.0f, 0.01f);
EXPECT_NEAR(b->getLayoutDimensions().y, 32.0f, 0.01f);
// end-justified: last item flush to the right edge
Element* c = new Div<W_64, H_32>(Attributes{});
Element* d = new Div<W_64, H_32>(Attributes{});
auto* end = new Div<FlexRow, G_8, Justify_End, W_Full, H_Full>({Attributes{}}, {c, d});
resolveStyles(end);
layout(end, 300, 100);
// total = 64 + 8 + 64 = 136; start at 300 - 136 = 164
EXPECT_NEAR(c->getLayoutPosition().x, 164.0f, 0.01f);
EXPECT_NEAR(d->getLayoutPosition().x, 164.0f + 72.0f, 0.01f);
// center-justified
Element* e = new Div<W_64, H_32>(Attributes{});
Element* f = new Div<W_64, H_32>(Attributes{});
auto* center = new Div<FlexRow, G_8, Justify_Center, W_Full, H_Full>({Attributes{}}, {e, f});
resolveStyles(center);
layout(center, 300, 100);
// free = 300 - 136 = 164; center offset = 82
EXPECT_NEAR(e->getLayoutPosition().x, 82.0f, 0.01f);
EXPECT_NEAR(f->getLayoutPosition().x, 82.0f + 72.0f, 0.01f);
}
// (b) column: default direction stacks top-to-bottom
TEST(FlexLayout, ColumnDefault) {
Element* a = new Div<W_64, H_32>(Attributes{});
Element* b = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
layout(root, 300, 200);
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().y, 32.0f, 0.01f);
// stretch is the default: a W_64 item stays 64 wide (explicit wins); y is packed
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
}
// (c) one child with Grow absorbs all the free space
TEST(FlexLayout, GrowAbsorbsFreeSpace) {
Element* fixed = new Div<W_48, H_32>(Attributes{});
auto* grow = new Div<Grow, H_32>(Attributes{});
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {fixed, grow});
resolveStyles(root);
layout(root, 200, 100);
EXPECT_NEAR(fixed->getLayoutDimensions().x, 48.0f, 0.01f);
EXPECT_NEAR(grow->getLayoutPosition().x, 48.0f, 0.01f);
// 200 - 48 free goes to the grower
EXPECT_NEAR(grow->getLayoutDimensions().x, 152.0f, 0.01f);
}
// (d) two growers split free space proportionally
TEST(FlexLayout, GrowSplitsProportionally) {
auto* g1 = new Div<Grow, H_32>(Attributes{}); // weight 1
auto* g2 = new Div<Grow_2, H_32>(Attributes{}); // weight 2
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {g1, g2});
resolveStyles(root);
layout(root, 300, 100);
// 300 total, weights 1:2 -> 100 / 200
EXPECT_NEAR(g1->getLayoutDimensions().x, 100.0f, 0.01f);
EXPECT_NEAR(g2->getLayoutPosition().x, 100.0f, 0.01f);
EXPECT_NEAR(g2->getLayoutDimensions().x, 200.0f, 0.01f);
}
// (e) overflow: a Shrink_0 item keeps its basis; the default-shrink item absorbs the deficit
TEST(FlexLayout, ShrinkDeficit) {
auto* keep = new Div<Shrink_0, H_32>(Attributes{}); // refuses to shrink
keep->setIntrinsicSize(150.0f, 32.0f); // natural main size 150
auto* shrink = new Div<H_32>(Attributes{}); // default shrink=1
shrink->setIntrinsicSize(150.0f, 32.0f);
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {keep, shrink});
resolveStyles(root);
layout(root, 180, 100);
// total basis 300 in a 180 box: deficit 120 falls entirely on the shrinker (weight 1 vs 0)
EXPECT_NEAR(keep->getLayoutDimensions().x, 150.0f, 0.01f);
EXPECT_NEAR(keep->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(shrink->getLayoutPosition().x, 150.0f, 0.01f);
EXPECT_NEAR(shrink->getLayoutDimensions().x, 30.0f, 0.01f);
}
// (f) wrap: items that don't fit the line flow onto the next line
TEST(FlexLayout, Wrap) {
// 150px items in a 200px row with wrap: item 2 can't share line 0 (150+8+150 > 200)
Element* a = new Div<W_150, H_32>(Attributes{});
Element* b = new Div<W_150, H_32>(Attributes{});
auto* root = new Div<FlexRow, Wrap, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
layout(root, 200, 300);
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
// line 1 starts below line 0: line0 cross = 32, + gap 8 -> y = 40
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().y, 40.0f, 0.01f);
}
// (g) align-items: start/center/end on the cross axis (items keep their explicit cross size)
TEST(FlexLayout, AlignItems) {
// start: item at the top of a 200px-tall row
{
Element* a = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 200);
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
EXPECT_NEAR(a->getLayoutDimensions().y, 32.0f, 0.01f);
}
// center: item vertically centered
{
Element* a = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, Items_Center, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 200);
EXPECT_NEAR(a->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
}
// end: item at the bottom
{
Element* a = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, Items_End, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 200);
EXPECT_NEAR(a->getLayoutPosition().y, 200.0f - 32.0f, 0.01f);
}
// stretch: an Auto-height item fills the cross axis (default items is stretch,
// so a bare container already does this; assert it explicitly)
{
auto* a = new Div<W_64>(Attributes{});
a->setIntrinsicSize(64.0f, 32.0f);
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 200);
EXPECT_NEAR(a->getLayoutDimensions().y, 200.0f, 0.01f);
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
}
}
// (h) order reorders flow items (layout order, not DOM order)
TEST(FlexLayout, Order) {
Element* a = new Div<W_64, H_32, Order_2>(Attributes{});
Element* b = new Div<W_64, H_32, Order_1>(Attributes{});
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
layout(root, 300, 100);
// b (order 1) comes before a (order 2)
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(a->getLayoutPosition().x, 72.0f, 0.01f);
}
// align-self override: the item's own align beats the container's
TEST(FlexLayout, AlignSelfOverride) {
Element* a = new Div<W_64, H_32, Self_Center>(Attributes{});
auto* root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 200);
// container says start (y=0), the item overrides to center
EXPECT_NEAR(a->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
}
// (i) percent basis: Basis_50Percent resolves against the container's content main
TEST(FlexLayout, PercentBasis) {
auto* a = new Div<Basis_50Percent, H_32>(Attributes{});
auto* b = new Div<Basis_50Percent, H_32>(Attributes{});
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
layout(root, 300, 100);
// each item's basis = 50% of 300 = 150; no free space, no grow -> stays 150
EXPECT_NEAR(a->getLayoutDimensions().x, 150.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().x, 150.0f, 0.01f);
EXPECT_NEAR(b->getLayoutDimensions().x, 150.0f, 0.01f);
}
// (j) min/max clamps: an explicit size is clamped to [min, max]
TEST(FlexLayout, MinMaxClamp) {
// maxWidth 64 clamps a 100px explicit width down to 64
{
Element* a = new Div<W_100, MaxWidthClass<64, DimensionType::Pixel>, H_32>(Attributes{});
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
layout(root, 300, 100);
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
}
// minWidth 80 clamps a 40px explicit width up to 80. set AFTER resolveStyles:
// applyStyle resets non-inherited fields (minWidth etc) to defaults, so a
// pre-set minWidth would be clobbered by the re-style. layout reads the style
// at layout time, so a post-resolve mutation is honored.
{
auto* a = new Div<W_40, H_32>(Attributes{});
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
resolveStyles(root);
a->getStyle().minWidth = 80;
a->getStyle().minWidthType = DimensionType::Pixel;
layout(root, 300, 100);
EXPECT_NEAR(a->getLayoutDimensions().x, 80.0f, 0.01f);
}
}
// (k) position:relative: offset applied on top of the flow position
TEST(FlexLayout, RelativeOffset) {
Element* a = new Div<W_64, H_32>(Attributes{});
Element* b = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
resolveStyles(root);
// set position/left/top AFTER resolveStyles: applyStyle resets position to
// Static and left/top to 0, so pre-set values would be clobbered. layout
// reads the style at layout time, so a post-resolve mutation is honored.
a->getStyle().position = Position::Relative;
a->getStyle().left = 10;
a->getStyle().top = 5;
layout(root, 300, 100);
// a is still in the flow at x=0 but drawn offset by (10, 5); b is unaffected
EXPECT_NEAR(a->getLayoutPosition().x, 10.0f, 0.01f);
EXPECT_NEAR(a->getLayoutPosition().y, 5.0f, 0.01f);
EXPECT_NEAR(b->getLayoutPosition().x, 72.0f, 0.01f);
}
// (l) position:absolute: removed from the flow, positioned from the container's content corner
TEST(FlexLayout, AbsolutePosition) {
auto* abs = new Div<W_32, H_32>(Attributes{});
Element* flow = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {abs, flow});
resolveStyles(root);
// set position/left/top AFTER resolveStyles: applyStyle resets position to
// Static and left/top to 0, so pre-set values would be clobbered. layout
// reads the style at layout time, so a post-resolve mutation is honored.
abs->getStyle().position = Position::Absolute;
abs->getStyle().left = 12;
abs->getStyle().top = 7;
layout(root, 300, 100);
// the absolute item is out of the flow: the flow item takes the full line
EXPECT_NEAR(flow->getLayoutPosition().x, 0.0f, 0.01f);
// absolute is at the container's content corner + (left, top); the container has
// no padding, so it's exactly (12, 7) in the container's parent space.
EXPECT_NEAR(abs->getLayoutPosition().x, 12.0f, 0.01f);
EXPECT_NEAR(abs->getLayoutPosition().y, 7.0f, 0.01f);
}
// (m) nested flex: a Div-in-Div with its own children lays out correctly at both levels
TEST(FlexLayout, NestedFlex) {
// inner row of two 32px items; outer column stacks it with a sibling
Element* in1 = new Div<W_32, H_16>(Attributes{});
Element* in2 = new Div<W_32, H_16>(Attributes{});
// inner is W_Full (fills the outer's content width) but Auto height:
// its cross size falls back to the content measurement (max child = 16).
// an explicit H_Full would resolve to 100% of the outer's 100px height,
// which is wrong for this test — the inner should size to its children.
auto* inner = new Div<FlexRow, W_Full>({Attributes{}}, {in1, in2});
auto* sibling = new Div<W_Full, H_24>(Attributes{});
auto* outer = new Div<W_Full, H_Full, P_4>({Attributes{}}, {inner, sibling});
resolveStyles(outer);
layout(outer, 200, 100);
// outer has P_4 padding: content origin at (4, 4). inner is W_Full -> fills
// the 200-8=192 wide content; its H is Auto -> content height = max child = 16.
EXPECT_NEAR(inner->getLayoutPosition().x, 4.0f, 0.01f);
EXPECT_NEAR(inner->getLayoutPosition().y, 4.0f, 0.01f);
EXPECT_NEAR(inner->getLayoutDimensions().x, 192.0f, 0.01f);
EXPECT_NEAR(inner->getLayoutDimensions().y, 16.0f, 0.01f);
// sibling stacks below inner: y = 4 + 16 + 0 (no gap) = 20
EXPECT_NEAR(sibling->getLayoutPosition().y, 20.0f, 0.01f);
// inner row: in1 at x=4+0, in2 at x=4+32
EXPECT_NEAR(in1->getLayoutPosition().x, 4.0f, 0.01f);
EXPECT_NEAR(in2->getLayoutPosition().x, 36.0f, 0.01f);
}
// (n) hidden: a Hidden element is not laid out and its siblings are not pushed by it
TEST(FlexLayout, HiddenSkipsLayout) {
Element* a = new Div<W_64, H_32>(Attributes{});
auto* hidden = new Div<W_64, H_32>(Attributes{});
Element* c = new Div<W_64, H_32>(Attributes{});
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, hidden, c});
resolveStyles(root);
// set Hidden AFTER resolveStyles: applyStyle resets style=parentStyle, which
// would clobber a pre-set display=Hidden. the runtime mutation path is
// set-style-field + markDirty, but markDirty triggers a re-style that resets
// from parent. so set it after the final re-style, before layout.
hidden->getStyle().display = Display::Hidden;
layout(root, 300, 100);
// a at x=0; the hidden item contributes no footprint and no gap; c at x=72
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(c->getLayoutPosition().x, 72.0f, 0.01f);
// the hidden element itself is zeroed
EXPECT_NEAR(hidden->getLayoutPosition().x, 0.0f, 0.01f);
EXPECT_NEAR(hidden->getLayoutDimensions().x, 0.0f, 0.01f);
}