17 KiB
Flexbox layout: replace the flow layout as the sole layout engine
Context
The UI system (src/Engine/UI/) currently has one layout engine: Element::flowLayout()
(Element.h:108-167) — a simple left-to-right / top-to-bottom "cursor" flow. It handles
Inline (horizontal) and Block (own-line) items with Static/Relative offsets, and has
no flex, grow, shrink, align, justify, order, basis, or wrap support.
InnerDisplayType::Flex exists in the enum (Style.h:25-28) but layout() only ever
switches on Flow (Element.h:110-114).
Goal: implement the full flexbox spec as the only layout mode. Remove block/sticky/
static/inline/flow as distinct concepts; everything is a flex container with a flex
direction. Keep the tailwind-style class API (template StyleClasss + Theme scaling) for
all the new flex properties.
Current state (what exists to reuse / repurpose)
Style(Style/Style.h): already haswidthType/width,maxWidth*,height*,gap(set byGapClass/G_n),padding*,margin*,top/bottom/left/right,z,hidden, andDimensionType{Pixel,Percent,Auto}(the existing sizing abstraction).Stylecurrently carries the layout enums to REMOVE:OuterDisplayType{Inline,Block,Hidden}(Style.h:19-23)InnerDisplayType{Flow,Flex,Grid}(Style.h:25-28)PositionType{Static,Relative,Absolute,Sticky}(Style.h:13-19)- fields
outerDisplay,innerDisplay,position(Style.h:43-45)
Element::layout()(Element.h:95-117) computesmaxDimensions/dimensionsthen callsflowLayout(). This is the seam to swap.flowLayout()(Element.h:119-167) is replaced.System(System.cpp) drivesstyleRec→layoutRec→render;System::beginFrame(System.cpp:170-186) is the per-frame driver;System::hitTest/mouseButtonreadelement->position(System.cpp:55-110) — input stays intact as long aspositionis set correctly.- Tailwind class layer (
Style/Class.h):WidthClass/W_Full,DisplayClass(+Block,Inline,Hidden),MarginClass/PaddingClass/GapClass+ theSPACE(n)macro scale,TextColorClass/BackgroundColorClass,FontSizeClass+TEXT_STEP. This is the pattern to extend with flex classes. - Only one real consumer of the UI tree today:
src/Editor/Window/InspectorView.cpp:15-20(aDiv<M_8>with a nestedDiv<BG_Red, Inline>- two
Text).Button/Panelare defined but unused. The API-breakage surface is tiny.
- two
- Text auto-sizing:
Text::applyStyle(Element/Text.h:33-60) setsstyle.width/heightfromfont->shapeTextwhen width/height areAuto. This is the existing self-size mechanism and it is the hook forflex-basis:auto(natural size).
Design (full flexbox, tailwind-styled)
1. New Style fields (Style/Style.h)
Remove: OuterDisplayType, InnerDisplayType, PositionType (keep only Relative/Absolute — see below), and the outerDisplay/innerDisplay/position fields. Add:
enum class FlexDirection { Row, RowReverse, Column, ColumnReverse };
enum class FlexWrap { NoWrap, Wrap };
enum class JustifyContent { Start, End, Center, SpaceBetween, SpaceAround, SpaceEvenly };
enum class AlignType { Start, Center, End, Stretch }; // cross-axis (items/self/content); no Baseline yet
enum class Display { Flex, Hidden }; // mirrors CSS `display`; only two states
enum class Position { Static, Relative, Absolute }; // minimal absolute/relative escape hatch
// container (flex) properties
direction=Row, wrap=NoWrap, justify=Start, items=Stretch, content=Stretch,
float gap (already exists)
// per-item properties
grow=0, shrink=1, order=0,
DimensionType basisType=Auto; float basis=0;
Display display=Flex; // replaces `hidden` bool -> display==Hidden
Position position=Static; // replaces PositionType (no Sticky)
float alignSelfOverride=-1; // <0 = inherit items; else one of AlignType
hidden (bool) is replaced by display==Display::Hidden. Every existing style.hidden read
(System.cpp focus walk, Element::layout, Element::render, Text::render) and the
style.outerDisplay == Hidden check becomes a single style.display == Display::Hidden check.
Keep top/left/right/bottom (already float/uint32) for relative/absolute offsets.
DimensionType{Pixel,Percent,Auto} is reused for basis (basisType) exactly like width.
2. Tailwind flex classes (Style/Class.h) — the public API
Follow the existing template<...>struct X{ static void apply(Style&, const Theme&); } pattern
and the SPACE(n)/TEXT_STEP macro idiom. New aliases (confirmed naming):
- display/direction:
Flex(display:flex, direction=row),FlexRow,FlexCol,FlexRowReverse,FlexColReverse. (NoBlock/Inline/DisplayClass— removed.) - wrap:
Wrap,NoWrap. - per-item flex:
Grow(grow:1),Grow_<n>,Grow0/Shrink0(grow/shrink:0),Shrink_<n>;Basis_Auto/Basis_Full/Basis_<px>/Basis_<n>Percent. - justify:
Justify_Start/End/Center/Between/Around/Evenly. - align:
Items_Start/Center/End/Stretch,Self_Start/Center/End/Stretch(no baseline). - order:
Order_<n>. - sizing reuse:
W_Full/WidthClass,H_Fullalready exist — reuse for width/height; extend with min/max variants if trivial (MaxW_<px>/MaxH_<px>map to existingmaxWidth/maxHeight).Gapreuses existingG_n(GapClass).M_*/P_*unchanged.
A small FlexClass/FlexDirClass/JustifyClass/ItemsClass template set + the using aliases
above. No new theme plumbing needed (flex props are unitless). Hidden becomes
DisplayClass<Display::Hidden> (keeps the Hidden name for the demo/compat).
3. The layout engine — a free function, not a method
System owns its root with OwningPtr and deletes the whole tree in ~System
(System.h:50, MinimalEngine.h OwningPtr), so a CPU unit test cannot hold onto element
pointers across a System and assert on them (use-after-free). Fix: extract the layout into a
free function void FlexLayout::layoutRoot(Element* root, UVector2 viewport) in a new
src/Engine/UI/FlexLayout.h (header-only, or a thin .cpp). System::beginFrame
calls it; the test calls it directly with a root it owns. System::layoutRec is removed.
Two-phase (recursion into children, so nested containers are correct):
- Phase A — measure (post-order): for each element, with its resolved containing-box
size, compute its content size (
dimensions) bottom-up. For a flex container this is the size its children require (sum of child main sizes + gaps + padding) when width/height isAuto, or the clamped fixed/percent size otherwise. ForText, content size comes fromshapeText(already computed inapplyStyle). For a leaf withAutosize => 0. This pass resolvesbasis:auto, appliesmin/maxclamps, and stores each child's main-axis size (the valuegrow/shrinkoperate on) so the parent can distribute free space. - Phase B — place (pre-order, top-down): with content sizes known, run the real flexbox
placement for this container's children: order-sorted flex items, resolve basis ->
grow/shrinkdistribution of free/deficit space (withgrow/shrinkweights),wraplines,justify-contentalong the main axis,align-items/align-self/align-contentalong the cross axis,gapbetween items/lines. Writechild->position(relative to this element).position==Relativeaddsleft/topto the computed position;position==Absoluteremoves the item from the flex flow (no space reserved) and anchors atleft/topfrom this element's content box (or the next non-static ancestor if we keep CSS semantics — keep it simple: anchor to this element's box). Then recurse into each child (Phase A+).
A measure pass and place pass must both be driven by the same function so nested
containers are sized before their parent distributes space. Because applyStyle runs before
layoutRoot (System::beginFrame order: calcStyle then layout), fonts are already shaped and
style.width/height are final; layoutRoot only positions + resolves auto/grow/shrink.
What stays the same: Element::render (reads position/dimensions), System::hitTest/
mouseButton (read position), Text::applyStyle (unchanged — it already resolves auto size).
Only the layout math changes. flowLayout() and the innerDisplay switch in layout()
(Element.h:95-167) are deleted; layout(UVector2) becomes a thin call into FlexLayout.
4. render/hitTest/collectFocusable hidden check
Swap style.hidden and style.outerDisplay == OuterDisplayType::Hidden for
style.display == Display::Hidden in: Element::layout guard, Element::render, Text::render,
System::collectFocusable (System.cpp). No behavior change, just the single source of truth.
Files to modify
src/Engine/UI/Style/Style.h— add flex fields; removeouterDisplay/innerDisplay/position+ theOuterDisplayType/InnerDisplayType/PositionType{static,sticky}enums andhiddenbool (replaced bydisplay/Display). Keepgap,top/left/right/bottom,width/height+types,max*.src/Engine/UI/Style/Class.h— add flex tailwind classes (Design §2); removeBlock/Inline/oldDisplayClass/oldHidden.src/Engine/UI/FlexLayout.h— new: the two-phase flexbox engine asFlexLayout::layoutRoot(Design §3).src/Engine/UI/Element.h— deleteflowLayout()+ thelayout()inline size/switch (:95-167); thinlayout()intoFlexLayout; swap therender()hidden check.src/Engine/UI/Element/Div.h,Panel.h— dropouterDisplay = Block; decide the default flex direction for a bare container.src/Engine/UI/Element/Text.h— swap therenderhidden check (applyStyleunchanged).src/Engine/UI/System.cpp— removelayoutRec;beginFramecallsFlexLayout::layoutRoot; swap thecollectFocusablehidden check.src/Editor/Window/InspectorView.cpp— migrate the demo to the new classes (the only real consumer + visual smoke test).tests/Engine/UI/FlexLayout.cpp+tests/Engine/UI/CMakeLists.txt— new CPU-only layout tests; addadd_subdirectory(UI/)totests/Engine/CMakeLists.txtand give the test target thesrc/Engineinclude path.
Decisions (confirmed with user)
- Keep minimal
absolute+relativeas positioning escape hatches on top of flexbox. Dropstatic/stickyas layout modes. Keep thetop/left/right/bottomoffset fields (relative = offset from the flex-computed position; absolute = offset from the containing block, removed from the flex flow). Nosticky. hiddenstays a boolean but is exposed through aDisplay-state field (an enumDisplay { Flex, Hidden }) to mirror HTML/CSS. Only two states:Flex(laid out, default) andHidden(not laid out, not rendered, not hit-tested).InnerDisplayType/OuterDisplayTypeare removed entirely; there is one layout mode (flex) and adisplaytoggle.- Baseline alignment: skip for now. Cross-axis
align-items/align-self/align-contentshipstretch|start|center|endonly.baselineis deferred (needs font metrics on the laid-out Style; add later if ever needed). - Full spec in one pass:
flex-direction(row/row-reverse/col/col-reverse),flex-wrap,justify-content(all 6),align-items/align-self/align-content(start/center/end/stretch),order,flex-grow/flex-shrink/flex-basis(auto/px/percent),gap,min/maxwidth/height clamps, percent basis. Nogrid. Baseline excluded per #3. - Intrinsic size model: only
Texthas a natural size (fromshapeText).Autosize ⇒ measure from children for containers;0for leafDiv/Panel.basis:autoresolves to the element's auto-resolved main size. Confirmed this is the only coherent model. - Default flex direction for a bare
Div/Panel:Column(top-to-bottom). Rationale: the existing flow layout already stacked block children vertically, and a bareDivmust remain a valid container that lays out its children sensibly with no extra class. Horizontal layouts are explicit (FlexRow). This is a sensible default, not a user-blocking question — noted here for the record.
Steps
- 1.
Style.h— replace theOuterDisplayType/InnerDisplayType/PositionTypeenums andouterDisplay/innerDisplay/position/hiddenfields with the new flex fields above (FlexDirection,FlexWrap,JustifyContent,AlignType,Display,Position{Static,Relative,Absolute},grow,shrink,order,basisType/basis,justify,items,content,alignSelfOverride). Keepgap,top/left/right/bottom,width/height+types,max*.hidden=>display==Display::Hidden. - 2.
Class.h— removeDisplayClass/Block/Inline/Hidden(the old ones). Add the flex template classes + tailwind aliases listed in Design §2 (Flex/FlexRow/FlexCol/reverses,Wrap/NoWrap,Grow/Grow_<n>/Grow0,Shrink/Shrink_<n>/Shrink0,Basis_*,Justify_*,Items_*/Self_*,Order_<n>,DisplayClass<Display::Hidden>asHidden). ReuseG_n/M_*/P_*/W_Full/H_Fullunchanged. - 3. New
UI/FlexLayout.{h,cpp}—namespace Seele::UI { namespace FlexLayout { void layoutRoot(Element* root, UVector2 viewport); } }. Implemented as a .cpp (not header-only) to break the circular include (Element.h already includes FlexLayout.h). Free functionslayoutElement+layoutRoot+placeFlowChildren. Container-aware: nested containers read their own resolved dimensions (set by recursion) instead of the flex-distributed basis; a re-placement pass afterplaceFlowChildrenfixes grandchildren that were positioned relative to a stale parent position. Edge cases covered: zero/negative free space (shrink), all-zero grow/shrink (basis wins), single-line SpaceBetween/Around/Evenly (gaps=0), Stretch when cross is Auto (fill cross axis), clamping so items never go negative, cross-size clamp to content box. - 4.
Element.h— deletedflowLayout()and theinnerDisplayswitch + inline size computation. Added public accessors (getStyle,getParent,getIntrinsicW/H) soFlexLayout.cppcan read child state without protected access.render()hidden check swapped todisplay==Display::Hidden. - 5.
Div.h/Panel.h— removedstyle.outerDisplay = OuterDisplayType::Block. FixedapplyStyleclobber:style = parentStylecopies ALL fields; now resets all non-inherited fields to defaults before applying template classes. A bareDiv/Paneldefaults toColumn(decision #6). - 6.
System.cpp— removedlayoutRec;beginFramecallsFlexLayout::layoutRoot(root, viewport).collectFocusablehidden check swapped todisplay==Display::Hidden. - 7.
Text.h— swappedstyle.hidden || style.outerDisplay == Hiddenfordisplay==Display::Hiddeninrender.applyStyleunchanged. - 8.
InspectorView.cpp— migrated toDiv<FlexRow, M_4>(the only real consumer). - 9. Test wiring —
tests/Engine/UI/CMakeLists.txtcreated withtarget_sources(SeeleUnitTests PRIVATE FlexLayout.cpp).DebugTest.cppentry removed. - 10.
tests/Engine/UI/FlexLayout.cpp— 15 GTest cases: (a) row gap + justify; (b) column; (c) grow absorbs free space; (d) proportional grow; (e) shrink deficit; (f) wrap; (g) align-items; (h) order; (i) align-self override; (j) percent basis; (k) min/max clamps; (l) relative offset; (m) absolute position; (n) nested flex; (o) hidden skips layout.H_Fullfixed (was 100px, nowHeightClass<100, DimensionType::Percent>). All 15 pass.
Verification
- CPU unit tests (primary, no GPU): ✅ 15/15 passing.
cmake --build bin --target SeeleUnitTeststhencd bin && ./SeeleUnitTests --gtest_filter='FlexLayout.*'. No display, no font needed. - Build the whole engine: ✅ Editor + Engine compile and link clean.
cmake --build bin --target Editor Engine. - Editor visual smoke test: NOT YET DONE — requires launching the GUI. Open the InspectorView, confirm the
FlexRowdiv lays children left-to-right withM_4margin, hover/Tab focus still work (input path untouched). RenderDoc: verifyposition/dimensionsfeed the UI quads correctly (no overlap). - Regression: ✅ No stale references.
grep -rn "outerDisplay\|innerDisplay\|flowLayout\|style.hidden\|OuterDisplayType\|InnerDisplayType\|PositionType" external/Seele/src/returns nothing.
Known limitations (intentional, per plan decisions)
- Baseline alignment (
AlignType::Baseline) is NOT shipped — decision #3, needs font metrics. align-contentis NOT implemented (multi-line cross-axis distribution for wrapped content). Only single-line layout is exercised by tests;align-contentwould matter forFlexWrapwithcolumndirection + multiple lines.- The re-placement pass (after
placeFlowChildrenin bothlayoutElementandlayoutRoot) is a pragmatic workaround for the measure-then-place ordering: a container child'slayoutElementruns (recursion) BEFORE the parent'splaceFlowChildrensets its position, so grandchildren are positioned relative to a stale (0,0). The re-pass fixes this at depth 2. For depth ≥ 3 (grandchild containers), the re-pass only re-runsplaceFlowChildrenone level — it does NOT recursively re-run. If a 3-level-deep container tree is ever needed, this must be restructured to a true two-pass (measure-then-place) algorithm.