Skip to content

PlatformLayout: an optional layout module in a result builder, with Hue Rings before/after - #226

Closed
fleon wants to merge 3 commits into
mainfrom
layout-engine
Closed

fleon wants to merge 3 commits into
mainfrom
layout-engine

Conversation

@fleon

@fleon fleon commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

A new optional module, PlatformLayout, so a screen says its arrangement once (rows, columns, grids, overlays, gaps, padding, alignment) instead of working out each position by hand. A game links it and moves a screen onto it when it next works on that screen; nothing else changes. No game uses it in this PR, so nothing on screen changes.

This PR is for settling the API first. The examples below are real Hue Rings code, before and after; fleon/huerings#56 makes these changes, in a draft that points its submodule at this branch. Open questions are at the end.

The API

Layouts are written in a result builder, like SwiftUI:

Column(gap: .padding) {
    Item(heading, height: headingHeight, anchor: pt(0.5, 1))
    Gap(.headingGap)
    Tiles(columns: 2, gap: sz(.tileGap)) {
        for tile in tiles { Item(tile, size: tileSize) }
    }
}
.padding(top: .padding, bottom: .padding)
.aligned(.center, .top)
.place(in: layout.contentRect)
Stacks Column(gap:align:), Row(gap:align:), Tiles(columns:gap:), Overlay. Their braces take if, if let, switch and for.
Items Item(node) for a node that knows its size (LayoutSized). Item(node, size:), width: and/or height: for any other node, and to override. By default the anchor is read when the node is placed: layoutAnchor, a label's alignment modes, a sprite's anchor point, or the middle. Item(size:) { rect in … } gets its rect: a backdrop, a card's face.
LayoutSized A node reports layoutSize, and layoutAnchor if its origin isn't its middle. Games adopt it for their buttons, boards and pills. TextBlockNode adopts it here, from its measured lines, its alignment and its .top/.firstBaseline mode; it now keeps topAboveOrigin for that. PlatformLayout depends on PlatformSprite for this.
Spaces Gap(20) is fixed and replaces the stack's gap. Gap(20, scales: 1.0 / 3 ... 1.5) grows into spare room or gives it back. Spacer(weight) takes a weighted share of what's spare.
Modifiers .aligned(_:_:), .padding(…), .frame(width:height:), .direction(_:), written on the line after an item, as in SwiftUI
Direction LayoutDirection.current. Rows run from the leading edge, and leading/trailing and padding mirror. left/right stay physical.
Helper CGRect.with(minX:maxX:minY:maxY:) gives the room between two things

Every stack and item conforms to LayoutItem, and a modifier returns a Layout. Either can be kept in a let and used inside another stack.

Why Item(…) and not .item(…): inside a builder, a line starting with . is read as a call on the line above, so .item(a) followed by .grid(…) would parse as .item(a).grid(…). That same rule is what lets .padding(…) on the next line work as a modifier. So the items have to be types.

Names: these type names don't collide with any top-level type in the five games. The exception was Grid, because Hue Rings has class Grid; that's why the grid is called Tiles. A game type with the same name as one of these would hide it inside that game.

Rules:

  • Items state their size: a node through LayoutSized, or a size given to Item. Nodes are never measured: their frames take in shadows, glows and running animations. A plain node with no size given is a compile error, not a zero.
  • A layout's size is its whole tree's size, so a card's face is drawn from the same description its content is placed by.
  • place(in:) runs on load and when SceneLayout changes, never per frame. It sets resting positions and leaves running actions alone.
  • Only gaps stretch. Items don't grow or wrap.
  • Corner buttons stay with SceneLayout (cornerButtonCenter, the rail). A layout places what stands between them.

Two things learned from #209 are built in:

  • direction(_:) changes only how a subtree lays out its contents. Where the subtree stands is still up to its parent.
  • A label's alignment modes are read when it's placed, not when the layout is built.

Before / after, from Hue Rings

The buttons, the board, the score's pill and text blocks adopt LayoutSized in the game (ButtonNode: sz(buttonWidth, buttonSize.height) hung at anchorX; GridNode: .gridBackgroundSize; and so on), so those Items take no size.

Each "after" places every node exactly where the "before" does, except one deliberate simplification in 1 and 2. DesignLayout.column gave the gaps only a quarter of the spare room. The "after" lets them take all of it until they're half again as big, then keeps the column centred. Matching the old rule exactly needed weighted margin spacers, which were hard to read. The result is a shift of up to about 12 points on some screens (fleon/huerings#56 lists them). To check this, I copied each "before" calculation word for word into a throwaway test, ran it beside the "after" with the same numbers, and compared positions to 1e-6. DesignLayout.column was checked at four room heights, covering both shrinking and the 1.5× cap, in the exact (weighted) form. That test isn't committed because it is game code. fleon/huerings#56 also checks the real app on an iOS simulator. Every node's position on the title, settings popup and More Games, portrait, landscape and iPad, is identical to main's. The game screen differs only by the shift above.

1. The game screen's column, upright (GameScene.layoutUpright, DesignLayout.column)

BeforeAfter
top = menuButtonNode.position.y - size / 2
    - .columnMargin
bottom = hintButtonNode.position.y + size / 2
    + .columnMargin
centerX = layout.visibleRect.midX
// …
let ys = DesignLayout.column(
    [backgroundOverlayNode.containerSize.height,
     .progressBarFullHeight + .borderWidth,
     .gridBackgroundSize,
     .progressBarFullHeight],
    gaps: [20, 26, 26],
    between: bottom, and: top)
backgroundOverlayNode.position = pt(centerX, ys[0])
dottedProgressBarNode.position = pt(centerX, ys[1])
gridNode.position = pt(centerX, ys[2])
progressBarNode.position = pt(centerX, ys[3])

// DesignLayout.swift
static func column(_ heights: [CGFloat],
                   gaps: [CGFloat],
                   between bottom: CGFloat,
                   and top: CGFloat) -> [CGFloat] {
    let room = top - bottom
    let content = heights.reduce(0, +)
    let baseGaps = gaps.reduce(0, +)
    let spare = room - content - baseGaps
    let scale: CGFloat = spare >= 0
        ? 1 + min(0.5, spare / max(baseGaps, 1) * 0.25)
        : max(1.0 / 3,
              (room - content) / max(baseGaps, 1))
    let scaled = gaps.map { $0 * scale }
    let total = content + scaled.reduce(0, +)
    var y = (top + bottom) / 2 + total / 2
    return heights.enumerated().map { index, height in
        defer { y -= height
            + (index < scaled.count ? scaled[index] : 0) }
        return y - height / 2
    }
}
let room = layout.visibleRect.with(
    minY: hintButtonNode.position.y + size / 2
        + .columnMargin,
    maxY: menuButtonNode.position.y - size / 2
        - .columnMargin)
Column {
    Item(backgroundOverlayNode)
    Gap(20, scales: .columnGap)
    Item(dottedProgressBarNode,
         height: .progressBarFullHeight + .borderWidth)
    Gap(26, scales: .columnGap)
    Item(gridNode)
    Gap(26, scales: .columnGap)
    Item(progressBarNode,
         height: .progressBarFullHeight)
}.place(in: room)

// DesignSystem.swift
extension ClosedRange<CGFloat> {
    /// A column's gaps: half again, or a third.
    static var columnGap: Self { 1.0 / 3 ... 1.5 }
}

The heights, the gaps and the order are written once, next to each other. Neither the index-matched ys[n] nor the centre x appears anywhere.

2. The game screen, turned (GameScene.layoutTurned, SceneLayout.landscapeColumns)

BeforeAfter
let safe = layout.safeRect
let board = CGFloat.gridBackgroundSize
let barWidth = Shadow.rectInScene(
    withoutShadows: progressBarNode, scene: self).width
let buttons = 2 * size + .landscapeButtonGap
let panel = max(barWidth, buttons,
    backgroundOverlayNode.containerSize.width)
let columns = layout.landscapeColumns(
    [panel, board],
    from: menuButtonNode.position.x + size / 2)
let midY = layout.visibleRect.midY
let half = min(midY - safe.minY, safe.maxY - midY)
    - .columnMargin
gridNode.position = pt(columns[1].midX, midY)

let x = columns[0].midX
let ys = DesignLayout.column(
    [backgroundOverlayNode.containerSize.height,
     .progressBarFullHeight + .borderWidth,
     .progressBarFullHeight, size],
    gaps: [20, 18, 30],
    between: midY - half, and: midY + half)
backgroundOverlayNode.position = pt(x, ys[0])
dottedProgressBarNode.position = pt(x, ys[1])
progressBarNode.position = pt(x, ys[2])
hintButtonNode.position = pt(
    x - (size + .landscapeButtonGap) / 2, ys[3])
undoButtonNode.position = pt(
    x + (size + .landscapeButtonGap) / 2, ys[3])

// DesignLayout.swift
func landscapeColumns(_ widths: [CGFloat],
                      from minX: CGFloat? = nil) -> [CGRect] {
    let start = minX ?? safeRect.minX
    let gap = max(0, (safeRect.maxX - start
        - widths.reduce(0, +)) / CGFloat(widths.count + 1))
    var x = start + gap
    return widths.map { width in
        defer { x += width + gap }
        return rect(x, visibleRect.minY,
                    width, visibleRect.height)
    }
}
let safe = layout.safeRect
let barWidth = Shadow.rectInScene(
    withoutShadows: progressBarNode, scene: self).width
let midY = layout.visibleRect.midY
let half = min(midY - safe.minY, safe.maxY - midY)
    - .columnMargin
// Spaced evenly right of the menu.
Row {
    Spacer()
    Column {
        Item(backgroundOverlayNode)
        Gap(20, scales: .columnGap)
        Item(dottedProgressBarNode,
             height: .progressBarFullHeight + .borderWidth)
        Gap(18, scales: .columnGap)
        Item(progressBarNode, width: barWidth,
             height: .progressBarFullHeight)
        Gap(30, scales: .columnGap)
        Row(gap: .landscapeButtonGap) {
            Item(hintButtonNode)
            Item(undoButtonNode)
        }
    }
    Spacer()
    Item(gridNode)
    Spacer()
}.place(in: safe.with(
    minX: menuButtonNode.position.x + size / 2,
    minY: midY - half, maxY: midY + half))

The column works out its own width (max(barWidth, buttons, overlay) goes away). Spacing "evenly between and at both edges" is three spacers rather than a helper.

3. A popup's card (PopupNode.createContainer)

BeforeAfter
let contentHeight = contentNode
    .calculateAccumulatedFrame().height
let containerHeight =
    .alertIconBackgroundSize / 2 + .alertPadding
    + contentHeight + .alertPadding
    + .alertButtonHeight + .alertPadding
container = shape(.path([.continuousRoundedRect(
    rect(.alertWidth, containerHeight).anchor(0.5),
    .alertCornerRadius)]), …)
// …
let contentY = containerHeight / 2
    - .alertIconBackgroundSize / 2 - .alertPadding
    - contentHeight / 2
contentContainer.position = pt(0, contentY)
let buttonY = -containerHeight / 2 + .alertPadding
    + .alertButtonHeight / 2
// …
if let leftButton = leftButton {
    let leftButtonWidth = leftButton.buttonWidth
    let closeButtonWidth = closeButton.buttonWidth
    let gap = CGFloat.alertButtonSpacing
    let totalWidth = leftButtonWidth + gap
        + closeButtonWidth
    leftButton.position = pt(-totalWidth / 2
        + leftButtonWidth / 2, buttonY)
    closeButton.position = pt(totalWidth / 2
        - closeButtonWidth / 2, buttonY)
    // …
} else {
    closeButton.position = pt(0, buttonY)
    // …
}
let contentHeight = contentNode
    .calculateAccumulatedFrame().height
let buttons = [leftButton, closeButton]
    .compactMap { $0 }
let card = Column(gap: .alertPadding) {
    Item(contentContainer, height: contentHeight)
    Row(gap: .alertButtonSpacing) {
        for button in buttons { Item(button) }
    }
}
.padding(top: .alertIconBackgroundSize / 2
    + .alertPadding, bottom: .alertPadding)
.frame(width: .alertWidth)
container = shape(.path([.continuousRoundedRect(
    rect(card.size).anchor(0.5),
    .alertCornerRadius)]), …)
// …
card.place(in: rect(card.size).anchor(0.5))

The card's height comes from the same description its content is placed by, so the two can't drift apart. Having one button or two is no longer a separate branch.

4. More Games: the sheet and a tile (MoreGamesPopupNode)

BeforeAfter
let rows = CGFloat((tiles.count + columns - 1)
    / columns)
let tilesHeight = rows * tileHeight
    + (rows - 1) * spacing
// …
let contentHeight =
    iconOverhang + padding + heading.height
    + .moreGamesHeadingGap + tilesHeight
    + padding + .alertButtonHeight + closeFoot
// …
var y = contentHeight - iconOverhang - padding
container.addChild(heading, z: 1, at: pt(0, y))
y -= heading.height + .moreGamesHeadingGap

let left = -sheetWidth / 2 + padding
for (index, tile) in tiles.enumerated() {
    let column = CGFloat(index % columns),
        row = CGFloat(index / columns)
    tile.position = pt(
        left + column * (tileWidth + spacing)
            + tileWidth / 2,
        y - row * (tileHeight + spacing)
            - tileHeight / 2)
    // …
}
closeButton.position = pt(0,
    closeFoot + .alertButtonHeight / 2)
let sheet = Column {
    Item(heading)
    Gap(.moreGamesHeadingGap)
    Tiles(columns: columns, gap: sz(spacing)) {
        for tile in tiles {
            Item(tile, size: sz(tileWidth, tileHeight))
        }
    }
    Gap(padding)
    Item(closeButton)
}
.padding(top: iconOverhang + padding,
         bottom: closeFoot)
let contentHeight = sheet.size.height
// …
sheet.place(in: rect(-sheetWidth / 2, 0,
    sheetWidth, contentHeight))
// MoreGamesTileNode.layout(height:)
let left = -width / 2 + .moreGamesTilePadding
icon.position = pt(left + .moreGamesIconSize / 2, 0)
iconEdge.position = icon.position
let textX = left + .moreGamesIconSize
    + .moreGamesTextGap
titleBlock.position = pt(textX, textHeight / 2)
lineBlock.position = pt(textX, textHeight / 2
    - titleBlock.height - .moreGamesLineGap)
Row(gap: .moreGamesTextGap) {
    Item(icon, size: sz(.moreGamesIconSize))
    Column(gap: .moreGamesLineGap, align: .leading) {
        Item(titleBlock)
        Item(lineBlock)
    }
}
.padding(leading: .moreGamesTilePadding)
.aligned(.leading)
.place(in: rect(width, height).anchor(0.5))
iconEdge.position = icon.position

The running y cursor, the row/column index math and the sheet height add-up all go away. The tile mirrors in a right-to-left language. In the tile, the text blocks' own left alignment and anchor: pt(0, 1) would still need to follow the reading direction.

5. The title: Play and More games spread below the block (TitleScene.placeColumn)

BeforeAfter
let gap = (blockBottom - edge - 2 * pill) / 2.5
playButtonNode?.position = pt(x,
    blockBottom - gap - pill / 2)
moreGamesButtonNode?.position = pt(x,
    edge + gap + pill / 2)
// As far from the block and the edge as each
// other, and half that apart.
Column {
    Spacer()
    Item(playButtonNode)
    Spacer(0.5)
    Item(moreGamesButtonNode)
    Spacer()
}.place(in: rect(x, edge, 0, blockBottom - edge))

The 2.5 is now spelled out as the spacers' weights.

Open questions

  1. Name of the type-erased value. A modifier returns Layout. SwiftUI also has a Layout protocol, but the two only clash in a file that imports both. The alignment and insets types are nested (Layout.Horizontal, Layout.Insets).
  2. Cross alignment defaults to .fill. Each item gets the stack's whole width (or height) and stands in its middle. This is what lets the panel column in 2 stretch its gaps inside the row. Is that the default we want, or should it be .center with .fill asked for?
  3. Direction. The game sets LayoutDirection.current. Now that the module depends on PlatformSprite (for text blocks), should it follow Typography.follow's language on its own?
  4. The whole screen as one layout. Today the corner buttons stay as SceneLayout calls, and each scene's updateLayout builds its layout and places it, using if layout.isLandscape { … } else { … } inside the braces. Next steps could be corner items that follow SceneLayout's rules, and a layout the scene keeps and the module re-places on every SceneLayout change.

Verification

  • PlatformLayoutTests, 21 tests (22 on Mac Catalyst), covering:
    • columns, rows, gaps and spaces standing in for them;
    • cross alignment, and a column stretching inside a row;
    • spacers by weight, and an evenly spread row;
    • scaled spaces growing to their cap and shrinking to their floor;
    • grids in both directions, including a short last row;
    • padding by reading direction;
    • frame and overlay;
    • node anchors and label modes, both read when placed;
    • a fixed-direction subtree inside a right-to-left column;
    • if, if let/else and for inside a stack;
    • LayoutSized (size taken, anchor read when placed, a given size winning), and a text block's size and anchor from its top or its first baseline (on Catalyst, where TextBlockNode exists);
    • placing leaves running actions alone.
  • The Hue Rings before/after comparison described above, run on the builder version.
  • Checks:
    • swift test --package-path Platform
    • Scripts/check-android.sh arm64-v8a
    • Platform's tests on Mac Catalyst, against Apple's SpriteKit
    • PlatformLayout built for iOS and tvOS

@fleon
fleon marked this pull request as ready for review November 29, 2026 13:52
) { _, _ in }
}

/// Room that takes a share of a stack's spare room, `weight` against

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This says a spacer's weight is measured only against the stack's other spacers. Flex.lengths actually splits spare room across every open part by weight, and space(_:scales:) uses its length in points as its weight (line 225). So a unitless .spacer() (weight 1) next to .space(20, scales: 1...10) in a row with 100 spare gets about 4.5 pt, and the scaled space takes about 91. Anyone reading this comment would expect the spacers to split the room evenly. The PR's own margin trick (spacer(1.5 * (20 + 26 + 26))) works only because the weights are compared in points. Either say that here and in the README (a spacer's weight is weighed against scaled spaces' lengths in points), or fill scaled spaces and spacers in separate passes.

@claude

claude Bot commented Nov 29, 2026

Copy link
Copy Markdown

Claude review (house rules)
Reviewed 4 files after reading AGENTS.md (CONTRIBUTING.md isn't in this repository). Left 1 inline comment.
Also, the title and description quote a game's real code by name. AGENTS.md says this public repository's before/after tables use neutral names, and a game's real code goes only in that game's own pull request.

@claude

claude Bot commented Nov 29, 2026

Copy link
Copy Markdown

Claude review (house rules), correction: CONTRIBUTING.md does exist, and I've now read it too. It doesn't change the inline comment. Its point 2 (no game's names, identifiers, content or reasons in descriptions) backs up the note above about the title and description.

@fleon
fleon marked this pull request as draft November 29, 2026 14:29
@fleon fleon changed the title PlatformLayout: an optional layout module, with Hue Rings before/after PlatformLayout: an optional layout module in a result builder, with Hue Rings before/after Nov 29, 2026
@fleon
fleon marked this pull request as ready for review November 29, 2026 14:30
}
return pt(x, y)
}
return (node as? SKSpriteNode)?.anchorPoint ?? pt(0.5, 0.5)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A TextBlockNode falls through to pt(0.5, 0.5) here, but its origin isn't its middle. With the default anchor: .top, the origin is the top of the first line; with .firstBaseline, it's the first baseline. Horizontally it follows the block's alignment. So Item(block, size: sz(block.width, block.height)), which the docs and README invite ("a text block's measured size"), puts the block's top at the middle of its slot. The text then hangs half its height too low and spills into whatever comes next in the column. The PR's own examples only come out right because they pass anchor: pt(0, 1) / pt(0.5, 1) by hand.

PlatformLayout can't see TextBlockNode, so this needs one of these:

  • a hook a node can conform to, for example a LayoutAnchored protocol in PlatformCore that TextBlockNode adopts;
  • an anchor that's required whenever the node isn't a label or a sprite;
  • at the least, docs saying text blocks need an explicit anchor.

@claude

claude Bot commented Nov 29, 2026

Copy link
Copy Markdown

Claude review (house rules)
Reviewed 5 files (Package.swift, Items.swift, Layout.swift, LayoutTests.swift, README.md) against AGENTS.md; this repository has no CONTRIBUTING.md.
Left 1 inline comment.

@fleon
fleon marked this pull request as draft November 29, 2026 14:43
@fleon
fleon marked this pull request as ready for review November 29, 2026 14:52
@fleon

fleon commented Nov 29, 2026

Copy link
Copy Markdown
Owner Author

Closing for now: not worth it at this point. The design and the Hue Rings before/after stay here for reference.

@fleon fleon closed this Nov 29, 2026
@fleon
fleon deleted the layout-engine branch November 29, 2026 15:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant