From 5e60c3dda275e2f18c51f9b0d8c7087deb5c62f7 Mon Sep 17 00:00:00 2001 From: Himanshu Kapoor Date: Sun, 29 Nov 2026 14:50:56 +0100 Subject: [PATCH 1/3] PlatformLayout: an optional layout module of rows, columns, grids and overlays placed in a rect --- Platform/Package.swift | 20 + Platform/Sources/PlatformLayout/Layout.swift | 429 ++++++++++++++++++ .../PlatformLayoutTests/LayoutTests.swift | 249 ++++++++++ README.md | 51 ++- 4 files changed, 748 insertions(+), 1 deletion(-) create mode 100644 Platform/Sources/PlatformLayout/Layout.swift create mode 100644 Platform/Tests/PlatformLayoutTests/LayoutTests.swift diff --git a/Platform/Package.swift b/Platform/Package.swift index 994e34e0..cf6956b5 100644 --- a/Platform/Package.swift +++ b/Platform/Package.swift @@ -49,6 +49,7 @@ let package = Package( .library(name: "PlatformAndroid", targets: ["PlatformAndroid"]), .library(name: "PlatformAndroidHost", targets: ["PlatformAndroidHost"]), .library(name: "PlatformSprite", targets: ["PlatformSprite"]), + .library(name: "PlatformLayout", targets: ["PlatformLayout"]), .library(name: "PlatformGameCenter", targets: ["PlatformGameCenter"]), .library(name: "PlatformStore", targets: ["PlatformStore"]), .library(name: "PlatformShare", targets: ["PlatformShare"]), @@ -270,6 +271,25 @@ let package = Package( ], swiftSettings: settings ), + // Optional, adopted screen by screen: rows, columns, grids and + // overlays with gaps, padding and alignment, placed in a rect + // (`Layout`) instead of worked out position by position. + .target( + name: "PlatformLayout", + dependencies: [ + "PlatformCore", + .product(name: "SpriteKitShim", package: "spritekit-android", condition: onShim), + ], + swiftSettings: settings + ), + .testTarget( + name: "PlatformLayoutTests", + dependencies: [ + "PlatformLayout", + .product(name: "SpriteKitShim", package: "spritekit-android", condition: onShim), + ], + swiftSettings: settings + ), // Game Center: sign-in, achievements reported as they move, scores, // the dashboard. GameKit on Apple; Play Games (PlatformShim) on // Android. diff --git a/Platform/Sources/PlatformLayout/Layout.swift b/Platform/Sources/PlatformLayout/Layout.swift new file mode 100644 index 00000000..91b2581f --- /dev/null +++ b/Platform/Sources/PlatformLayout/Layout.swift @@ -0,0 +1,429 @@ +import Foundation +#if SPRITEKIT_SHIM +import SpriteKitShim +#else +import SpriteKit +import UIKit +#endif +@_exported import PlatformCore + +/// A screen's arrangement, said once: rows and columns with gaps, grids, +/// overlays, padding and alignment, placed in a rect (one of +/// `SceneLayout`'s, or a card's own) instead of worked out position by +/// position. +/// +/// Every item states the room it asks for (`size`), from design tokens or a +/// text block's measured size; nodes are never measured. `place(in:)` sets +/// each node's resting position, once on load and again when the layout +/// changes, never per frame, and leaves running actions alone. +/// +/// Rows run from the reading direction's leading edge, and `leading` and +/// `trailing` mirror in a right-to-left language. Nothing grows or wraps +/// except spaces: `space(_:scales:)` and `spacer(_:)` take up or give back +/// a stack's spare room. +/// +/// Layout.column([ +/// .node(title, size: sz(.titleWidth, .titleHeight), anchor: pt(0.5, 1)), +/// .grid(tiles.map { .node($0, size: .tileSize) }, columns: 2, gap: sz(.tileGap)), +/// ], gap: .listGap) +/// .padding(top: .titleGap) +/// .aligned(.center, .top) +/// .place(in: layout.contentRect) +public struct Layout { + /// The room the item asks for, padding included. + public let size: CGSize + /// How a space stretches along its stack; nil for everything else. + fileprivate let flex: Flex? + fileprivate let placer: (CGRect, LayoutDirection) -> Void + + fileprivate init(size: CGSize, flex: Flex? = nil, placer: @escaping (CGRect, LayoutDirection) -> Void) { + self.size = size + self.flex = flex + self.placer = placer + } + + /// Places the item, and all it holds, in `rect`: an item with nothing + /// that stretches stands in the middle of it at its own size. + public func place(in rect: CGRect, direction: LayoutDirection = .current) { + placer(rect, direction) + } +} + +// MARK: - Direction and alignment + +/// Which way a language reads, which way rows run. +public enum LayoutDirection: Equatable, Sendable { + case leftToRight, rightToLeft + + /// The game's reading direction; set it with the language. + public nonisolated(unsafe) static var current: LayoutDirection = .leftToRight +} + +extension Layout { + /// Where an item stands across a column, or across its rect. + public enum Horizontal: Equatable, Sendable { + /// The side a line of text starts on: left, or right in a + /// right-to-left language. + case leading + case center + case trailing + /// Left or right whichever way the language reads (a board, a track). + case left, right + /// The whole width. + case fill + } + + /// Where an item stands across a row, or up and down its rect. + public enum Vertical: Equatable, Sendable { + case top, center, bottom + /// The whole height. + case fill + } + + /// Room kept inside a rect's edges, by reading direction. + public struct Insets: Equatable, Sendable { + public var top: CGFloat + public var leading: CGFloat + public var bottom: CGFloat + public var trailing: CGFloat + + public init(top: CGFloat = 0, leading: CGFloat = 0, bottom: CGFloat = 0, trailing: CGFloat = 0) { + self.top = top + self.leading = leading + self.bottom = bottom + self.trailing = trailing + } + + public init(_ all: CGFloat) { + self.init(top: all, leading: all, bottom: all, trailing: all) + } + + public init(horizontal: CGFloat = 0, vertical: CGFloat = 0) { + self.init(top: vertical, leading: horizontal, bottom: vertical, trailing: horizontal) + } + } +} + +extension CGRect { + /// The rect less `insets`, its leading side on the right in a + /// right-to-left language. + public func inset(by insets: Layout.Insets, direction: LayoutDirection = .current) -> CGRect { + let left = direction == .leftToRight ? insets.leading : insets.trailing + let right = direction == .leftToRight ? insets.trailing : insets.leading + return rect(minX + left, minY + insets.bottom, width - left - right, height - insets.top - insets.bottom) + } + + /// `size` standing in the rect as `horizontal` and `vertical` say (the + /// rect's own width or height where they `fill`). + public func aligning( + _ size: CGSize, _ horizontal: Layout.Horizontal, _ vertical: Layout.Vertical, + direction: LayoutDirection = .current + ) -> CGRect { + let (x, w) = Layout.align(size.width, horizontal, in: minX, width, direction) + let (y, h) = Layout.align(size.height, vertical, in: minY, height) + return rect(x, y, w, h) + } +} + +extension CGRect { + /// The rect with the edges given moved there: the room between two + /// things, say. + public func with(minX: CGFloat? = nil, maxX: CGFloat? = nil, minY: CGFloat? = nil, maxY: CGFloat? = nil) -> CGRect { + let left = minX ?? self.minX, right = maxX ?? self.maxX + let bottom = minY ?? self.minY, top = maxY ?? self.maxY + return rect(left, bottom, right - left, top - bottom) + } +} + +extension Layout { + /// Where `length` starts, and how long it is, along `span` from `start`. + fileprivate static func align( + _ length: CGFloat, _ alignment: Layout.Horizontal, in start: CGFloat, _ span: CGFloat, + _ direction: LayoutDirection + ) -> (CGFloat, CGFloat) { + let rightToLeft = direction == .rightToLeft + switch alignment { + case .fill: return (start, span) + case .center: return (start + (span - length) / 2, length) + case .left: return (start, length) + case .right: return (start + span - length, length) + case .leading: return (rightToLeft ? start + span - length : start, length) + case .trailing: return (rightToLeft ? start : start + span - length, length) + } + } + + fileprivate static func align( + _ length: CGFloat, _ alignment: Layout.Vertical, in start: CGFloat, _ span: CGFloat + ) -> (CGFloat, CGFloat) { + switch alignment { + case .fill: return (start, span) + case .center: return (start + (span - length) / 2, length) + case .bottom: return (start, length) + case .top: return (start + span - length, length) + } + } +} + +// MARK: - Leaves + +extension Layout { + /// `node`, `size` big, standing in the middle of the room it's given. + /// Its position goes where `anchor` (a share of `size`) falls: by + /// default a sprite's anchor point, read as it's placed, else the + /// middle, as a container node draws round its origin. + public static func node(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) -> Layout { + Layout(size: size) { room, _ in + let anchor = anchor ?? (node as? SKSpriteNode)?.anchorPoint ?? pt(0.5, 0.5) + let frame = room.aligning(size, .center, .center) + node.position = pt(frame.minX + anchor.x * size.width, frame.minY + anchor.y * size.height) + } + } + + /// `node` where only its height counts (in a column) or only its width + /// (in a row). + public static func node(_ node: SKNode, width: CGFloat = 0, height: CGFloat = 0, anchor: CGPoint? = nil) -> Layout { + self.node(node, size: sz(width, height), anchor: anchor) + } + + /// `label`, `size` big, its position where its alignment modes put the + /// text, read as it's placed (a baseline stands on the foot). + public static func label(_ label: SKLabelNode, size: CGSize) -> Layout { + Layout(size: size) { room, _ in + let x: CGFloat = switch label.horizontalAlignmentMode { + case .left: 0 + case .right: 1 + default: 0.5 + } + let y: CGFloat = switch label.verticalAlignmentMode { + case .center: 0.5 + case .top: 1 + default: 0 + } + let frame = room.aligning(size, .center, .center) + label.position = pt(frame.minX + x * size.width, frame.minY + y * size.height) + } + } + + /// Asks for `size` and hands `place` the rect it's given, whole: for + /// what's sized to its room (a backdrop, a card's face) or placed by + /// rules of its own. + public static func custom(size: CGSize = .zero, _ place: @escaping (CGRect) -> Void) -> Layout { + Layout(size: size) { room, _ in place(room) } + } + + /// `length` of room along a stack, in place of its gap. + public static func space(_ length: CGFloat) -> Layout { + Layout(size: sz(length), flex: Flex(natural: length, minimum: length, maximum: length, weight: 0)) { _, _ in } + } + + /// `length` of room along a stack that grows to fill the stack's spare + /// room, or gives it back where it's short, by a factor within + /// `scales`. A stack's scaled spaces keep their proportions. + public static func space(_ length: CGFloat, scales: ClosedRange) -> Layout { + Layout( + size: sz(length), + flex: Flex(natural: length, minimum: length * scales.lowerBound, maximum: length * scales.upperBound, weight: length) + ) { _, _ in } + } + + /// Room that takes a share of a stack's spare room, `weight` against + /// the stack's other spacers: spacers at both ends and between spread a + /// row evenly. Never less than `minimum`. + public static func spacer(_ weight: CGFloat = 1, minimum: CGFloat = 0) -> Layout { + Layout(size: sz(minimum), flex: Flex(natural: minimum, minimum: minimum, maximum: .infinity, weight: weight)) { _, _ in } + } +} + +// MARK: - Containers + +extension Layout { + /// `items` top down, `gap` apart (a space between two stands in for the + /// gap), each standing across the column as `align` says: by default + /// given the column's whole width, in the middle of which an item that + /// doesn't stretch stands. + public static func column(_ items: [Layout], gap: CGFloat = 0, align: Layout.Horizontal = .fill) -> Layout { + stack(items, vertical: true, gap: gap) { room, size, direction in + room.aligning(size, align, .fill, direction: direction) + } + } + + /// `items` from the leading edge, `gap` apart (a space between two + /// stands in for the gap), each standing across the row as `align` says: + /// by default given the row's whole height, so a column in it can + /// stretch its spaces. + public static func row(_ items: [Layout], gap: CGFloat = 0, align: Layout.Vertical = .fill) -> Layout { + stack(items, vertical: false, gap: gap) { room, size, direction in + room.aligning(size, .fill, align, direction: direction) + } + } + + /// `items` one over another in the same rect, as big as the biggest. + public static func overlay(_ items: [Layout]) -> Layout { + let size = sz(items.map(\.size.width).max() ?? 0, items.map(\.size.height).max() ?? 0) + return Layout(size: size) { room, direction in + for item in items { item.placer(room, direction) } + } + } + + /// `items` in `columns` across, filled a row at a time from the leading + /// top corner, each cell as big as the biggest item and `gap` apart + /// (across, then down). A short last row starts at the leading edge. + public static func grid(_ items: [Layout], columns: Int, gap: CGSize = .zero) -> Layout { + let columns = max(1, columns) + let cell = sz(items.map(\.size.width).max() ?? 0, items.map(\.size.height).max() ?? 0) + let across = min(columns, items.count) + let rows = (items.count + columns - 1) / columns + let size = sz( + CGFloat(across) * cell.width + CGFloat(max(0, across - 1)) * gap.width, + CGFloat(rows) * cell.height + CGFloat(max(0, rows - 1)) * gap.height) + return Layout(size: size) { room, direction in + let frame = room.aligning(size, .center, .center) + for (index, item) in items.enumerated() { + let column = CGFloat(index % columns), row = CGFloat(index / columns) + let fromLeading = column * (cell.width + gap.width) + let x = direction == .leftToRight ? frame.minX + fromLeading : frame.maxX - fromLeading - cell.width + let y = frame.maxY - row * (cell.height + gap.height) - cell.height + item.placer(rect(x, y, cell.width, cell.height), direction) + } + } + } + + /// A row or a column: `slot` stands each item across it, given the + /// room along it the item takes. + private static func stack( + _ items: [Layout], vertical: Bool, gap: CGFloat, + slot: @escaping (CGRect, CGSize, LayoutDirection) -> CGRect + ) -> Layout { + // The gap goes between neighbours unless a space stands there. + var parts: [Layout] = [] + for item in items { + if let last = parts.last, gap != 0, last.flex == nil, item.flex == nil { parts.append(.space(gap)) } + parts.append(item) + } + let flexes = parts.map { $0.flex ?? Flex(fixed: vertical ? $0.size.height : $0.size.width) } + let along = flexes.map(\.natural).reduce(0, +) + let across = parts.filter { $0.flex == nil }.map { vertical ? $0.size.width : $0.size.height }.max() ?? 0 + let size = vertical ? sz(across, along) : sz(along, across) + return Layout(size: size) { room, direction in + let lengths = Flex.lengths(flexes, filling: vertical ? room.height : room.width) + let total = lengths.reduce(0, +) + // What's short of filling the room stands in its middle. + let rightToLeft = !vertical && direction == .rightToLeft + var cursor = vertical ? room.midY + total / 2 : (rightToLeft ? room.midX + total / 2 : room.midX - total / 2) + for (part, length) in zip(parts, lengths) { + let band: CGRect + if vertical { + cursor -= length + band = rect(room.minX, cursor, room.width, length) + } else if rightToLeft { + cursor -= length + band = rect(cursor, room.minY, length, room.height) + } else { + band = rect(cursor, room.minY, length, room.height) + cursor += length + } + guard part.flex == nil else { continue } + part.placer(slot(band, part.size, direction), direction) + } + } + } +} + +// MARK: - Modifiers + +extension Layout { + /// Stands the item at its own size in its room, as `horizontal` and + /// `vertical` say, rather than in the middle (or across the whole of + /// it, where they `fill`). + public func aligned(_ horizontal: Layout.Horizontal = .center, _ vertical: Layout.Vertical = .center) -> Layout { + Layout(size: size, flex: flex) { room, direction in + placer(room.aligning(size, horizontal, vertical, direction: direction), direction) + } + } + + /// Keeps `insets` of room round the item. + public func padding(_ insets: Layout.Insets) -> Layout { + let padded = sz(size.width + insets.leading + insets.trailing, size.height + insets.top + insets.bottom) + return Layout(size: padded) { room, direction in + placer(room.inset(by: insets, direction: direction), direction) + } + } + + public func padding(_ all: CGFloat) -> Layout { + padding(Layout.Insets(all)) + } + + public func padding(top: CGFloat = 0, leading: CGFloat = 0, bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { + padding(Layout.Insets(top: top, leading: leading, bottom: bottom, trailing: trailing)) + } + + /// Asks for `width` and `height` in place of the item's own (each where + /// given); the item stands in the middle of what it's then given. + public func frame(width: CGFloat? = nil, height: CGFloat? = nil) -> Layout { + Layout(size: sz(width ?? size.width, height ?? size.height)) { room, direction in + placer(room, direction) + } + } + + /// Lays what the item holds out in `direction` whatever the language + /// (a board, a track): where the item itself stands is still its + /// parent's to say. + public func direction(_ direction: LayoutDirection) -> Layout { + Layout(size: size, flex: flex) { room, _ in placer(room, direction) } + } +} + +// MARK: - Stretching + +/// How far a stack's part stretches along it. +nonisolated struct Flex: Equatable { + var natural: CGFloat + var minimum: CGFloat + var maximum: CGFloat + /// Its share of what's spare or short, against the stack's others. + var weight: CGFloat + + init(natural: CGFloat, minimum: CGFloat, maximum: CGFloat, weight: CGFloat) { + self.natural = natural + self.minimum = minimum + self.maximum = maximum + self.weight = weight + } + + init(fixed length: CGFloat) { + self.init(natural: length, minimum: length, maximum: length, weight: 0) + } + + /// Each part's length once they share `room`: what's spare or short + /// goes by weight to the parts that can still stretch, each kept within + /// its bounds. + static func lengths(_ parts: [Flex], filling room: CGFloat) -> [CGFloat] { + var lengths = parts.map(\.natural) + var left = room - lengths.reduce(0, +) + let growing = left > 0 + var open = Set(parts.indices.filter { index in + let part = parts[index] + return part.weight > 0 && (growing ? part.maximum > part.natural : part.minimum < part.natural) + }) + while abs(left) > 1e-9, !open.isEmpty { + let weights = open.map { parts[$0].weight }.reduce(0, +) + let share = left / weights + var clamped = false + for index in open { + let part = parts[index] + let bound = growing ? part.maximum : part.minimum + let wanted = lengths[index] + share * part.weight + if growing ? wanted >= bound : wanted <= bound { + left -= bound - lengths[index] + lengths[index] = bound + open.remove(index) + clamped = true + } + } + guard !clamped else { continue } + for index in open { lengths[index] += share * parts[index].weight } + left = 0 + } + return lengths + } +} diff --git a/Platform/Tests/PlatformLayoutTests/LayoutTests.swift b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift new file mode 100644 index 00000000..e0fe961b --- /dev/null +++ b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift @@ -0,0 +1,249 @@ +import Foundation +import Testing +import SpriteKitShim +@testable import PlatformLayout + +struct LayoutTests { + private let room = rect(-100, -200, 200, 400) + + private func nodes(_ count: Int) -> [SKNode] { + (0.. Date: Sun, 29 Nov 2026 15:29:56 +0100 Subject: [PATCH 2/3] PlatformLayout: write layouts in a result builder (Column, Row, Tiles, Overlay, Item, Gap, Spacer) --- Platform/Sources/PlatformLayout/Items.swift | 127 +++++++++++++ Platform/Sources/PlatformLayout/Layout.swift | 99 +++++----- .../PlatformLayoutTests/LayoutTests.swift | 179 ++++++++++-------- README.md | 58 +++--- 4 files changed, 311 insertions(+), 152 deletions(-) create mode 100644 Platform/Sources/PlatformLayout/Items.swift diff --git a/Platform/Sources/PlatformLayout/Items.swift b/Platform/Sources/PlatformLayout/Items.swift new file mode 100644 index 00000000..6f50e591 --- /dev/null +++ b/Platform/Sources/PlatformLayout/Items.swift @@ -0,0 +1,127 @@ +import Foundation +#if SPRITEKIT_SHIM +import SpriteKitShim +#else +import SpriteKit +import UIKit +#endif + +// The items a layout is written in, inside a stack's braces: +// +// Column(gap: .alertPadding) { +// Item(content, height: contentHeight) +// Row(gap: .alertButtonSpacing) { +// for button in buttons { Item(button, width: button.width, height: .buttonHeight) } +// } +// } + +/// Lists a stack's items, with `if`, `switch` and `for` among them. +@resultBuilder +public enum LayoutBuilder { + public static func buildExpression(_ item: some LayoutItem) -> [Layout] { [item.layout] } + public static func buildExpression(_ items: [some LayoutItem]) -> [Layout] { items.map(\.layout) } + public static func buildBlock(_ parts: [Layout]...) -> [Layout] { parts.flatMap { $0 } } + public static func buildOptional(_ part: [Layout]?) -> [Layout] { part ?? [] } + public static func buildEither(first part: [Layout]) -> [Layout] { part } + public static func buildEither(second part: [Layout]) -> [Layout] { part } + public static func buildArray(_ parts: [[Layout]]) -> [Layout] { parts.flatMap { $0 } } + public static func buildLimitedAvailability(_ part: [Layout]) -> [Layout] { part } +} + +/// Items top down, `gap` apart (a `Gap` or `Spacer` between two stands in +/// for the gap), each standing across the column as `align` says: by +/// default given the column's whole width, in the middle of which an item +/// that doesn't stretch stands. +public struct Column: LayoutItem { + public let layout: Layout + + public init(gap: CGFloat = 0, align: Layout.Horizontal = .fill, @LayoutBuilder _ items: () -> [Layout]) { + layout = .column(items(), gap: gap, align: align) + } +} + +/// Items from the leading edge, `gap` apart (a `Gap` or `Spacer` between +/// two stands in for the gap), each standing across the row as `align` +/// says: by default given the row's whole height, so a column in it can +/// stretch its gaps. +public struct Row: LayoutItem { + public let layout: Layout + + public init(gap: CGFloat = 0, align: Layout.Vertical = .fill, @LayoutBuilder _ items: () -> [Layout]) { + layout = .row(items(), gap: gap, align: align) + } +} + +/// Items in `columns` across, filled a row at a time from the leading top +/// corner, each cell as big as the biggest item and `gap` apart (across, +/// then down). A short last row starts at the leading edge. +public struct Tiles: LayoutItem { + public let layout: Layout + + public init(columns: Int, gap: CGSize = .zero, @LayoutBuilder _ items: () -> [Layout]) { + layout = .grid(items(), columns: columns, gap: gap) + } +} + +/// Items one over another in the same rect, as big as the biggest. +public struct Overlay: LayoutItem { + public let layout: Layout + + public init(@LayoutBuilder _ items: () -> [Layout]) { + layout = .overlay(items()) + } +} + +/// A node, `size` big, standing in the middle of the room it's given, its +/// position where `anchor` (a share of `size`) falls. By default, read as +/// it's placed: where a label's alignment modes put its text (a baseline on +/// the foot), a sprite's anchor point, or the middle, as a container node +/// draws round its origin. +public struct Item: LayoutItem { + public let layout: Layout + + public init(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) { + layout = .node(node, size: size, anchor: anchor) + } + + /// A node where only its height counts (in a column) or only its width + /// (in a row). + public init(_ node: SKNode, width: CGFloat = 0, height: CGFloat = 0, anchor: CGPoint? = nil) { + layout = .node(node, size: sz(width, height), anchor: anchor) + } + + /// Asks for `size` and hands `place` the rect it's given, whole: for + /// what's sized to its room (a backdrop, a card's face) or placed by + /// rules of its own. + public init(size: CGSize = .zero, place: @escaping (CGRect) -> Void) { + layout = .custom(size: size, place) + } +} + +/// Room along a stack, in place of its gap. +public struct Gap: LayoutItem { + public let layout: Layout + + /// `length`, fixed. + public init(_ length: CGFloat) { + layout = .space(length) + } + + /// `length`, growing into the stack's spare room or giving it back + /// where it's short, by a factor within `scales`. A stack's scaled gaps + /// keep their proportions. + public init(_ length: CGFloat, scales: ClosedRange) { + layout = .space(length, scales: scales) + } +} + +/// Room that takes a share of a stack's spare room, `weight` against the +/// stack's other spacers: spacers at both ends and between spread a row +/// evenly. Never less than `minimum`. +public struct Spacer: LayoutItem { + public let layout: Layout + + public init(_ weight: CGFloat = 1, minimum: CGFloat = 0) { + layout = .spacer(weight, minimum: minimum) + } +} diff --git a/Platform/Sources/PlatformLayout/Layout.swift b/Platform/Sources/PlatformLayout/Layout.swift index 91b2581f..0db02004 100644 --- a/Platform/Sources/PlatformLayout/Layout.swift +++ b/Platform/Sources/PlatformLayout/Layout.swift @@ -7,7 +7,14 @@ import UIKit #endif @_exported import PlatformCore -/// A screen's arrangement, said once: rows and columns with gaps, grids, +/// What every item in a layout is: a node, a stack, a space, or one of +/// those with a modifier on it. `Column`, `Row`, `Tiles`, `Overlay`, +/// `Item`, `Gap` and `Spacer` are items; a modifier makes a `Layout`. +public protocol LayoutItem { + var layout: Layout { get } +} + +/// A screen's arrangement, said once: rows and columns with gaps, tiles, /// overlays, padding and alignment, placed in a rect (one of /// `SceneLayout`'s, or a card's own) instead of worked out position by /// position. @@ -19,17 +26,19 @@ import UIKit /// /// Rows run from the reading direction's leading edge, and `leading` and /// `trailing` mirror in a right-to-left language. Nothing grows or wraps -/// except spaces: `space(_:scales:)` and `spacer(_:)` take up or give back -/// a stack's spare room. +/// except spaces: a scaled `Gap` and a `Spacer` take up or give back a +/// stack's spare room. /// -/// Layout.column([ -/// .node(title, size: sz(.titleWidth, .titleHeight), anchor: pt(0.5, 1)), -/// .grid(tiles.map { .node($0, size: .tileSize) }, columns: 2, gap: sz(.tileGap)), -/// ], gap: .listGap) +/// Column(gap: .listGap) { +/// Item(title, height: .titleHeight, anchor: pt(0.5, 1)) +/// Tiles(columns: 2, gap: sz(.tileGap)) { +/// for tile in tiles { Item(tile, size: .tileSize) } +/// } +/// } /// .padding(top: .titleGap) /// .aligned(.center, .top) /// .place(in: layout.contentRect) -public struct Layout { +public struct Layout: LayoutItem { /// The room the item asks for, padding included. public let size: CGSize /// How a space stretches along its stack; nil for everything else. @@ -42,10 +51,17 @@ public struct Layout { self.placer = placer } + public var layout: Layout { self } +} + +extension LayoutItem { + /// The room the item asks for, padding included. + public var size: CGSize { layout.size } + /// Places the item, and all it holds, in `rect`: an item with nothing /// that stretches stands in the middle of it at its own size. public func place(in rect: CGRect, direction: LayoutDirection = .current) { - placer(rect, direction) + layout.placer(rect, direction) } } @@ -167,28 +183,21 @@ extension Layout { // MARK: - Leaves extension Layout { - /// `node`, `size` big, standing in the middle of the room it's given. - /// Its position goes where `anchor` (a share of `size`) falls: by - /// default a sprite's anchor point, read as it's placed, else the - /// middle, as a container node draws round its origin. - public static func node(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) -> Layout { + /// `node`, `size` big, standing in the middle of the room it's given, + /// its position where `anchor` (a share of `size`) falls. By default, + /// read as it's placed: where a label's alignment modes put its text (a + /// baseline on the foot), a sprite's anchor point, or the middle, as a + /// container node draws round its origin. + static func node(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) -> Layout { Layout(size: size) { room, _ in - let anchor = anchor ?? (node as? SKSpriteNode)?.anchorPoint ?? pt(0.5, 0.5) + let anchor = anchor ?? defaultAnchor(of: node) let frame = room.aligning(size, .center, .center) node.position = pt(frame.minX + anchor.x * size.width, frame.minY + anchor.y * size.height) } } - /// `node` where only its height counts (in a column) or only its width - /// (in a row). - public static func node(_ node: SKNode, width: CGFloat = 0, height: CGFloat = 0, anchor: CGPoint? = nil) -> Layout { - self.node(node, size: sz(width, height), anchor: anchor) - } - - /// `label`, `size` big, its position where its alignment modes put the - /// text, read as it's placed (a baseline stands on the foot). - public static func label(_ label: SKLabelNode, size: CGSize) -> Layout { - Layout(size: size) { room, _ in + private static func defaultAnchor(of node: SKNode) -> CGPoint { + if let label = node as? SKLabelNode { let x: CGFloat = switch label.horizontalAlignmentMode { case .left: 0 case .right: 1 @@ -199,27 +208,27 @@ extension Layout { case .top: 1 default: 0 } - let frame = room.aligning(size, .center, .center) - label.position = pt(frame.minX + x * size.width, frame.minY + y * size.height) + return pt(x, y) } + return (node as? SKSpriteNode)?.anchorPoint ?? pt(0.5, 0.5) } /// Asks for `size` and hands `place` the rect it's given, whole: for /// what's sized to its room (a backdrop, a card's face) or placed by /// rules of its own. - public static func custom(size: CGSize = .zero, _ place: @escaping (CGRect) -> Void) -> Layout { + static func custom(size: CGSize = .zero, _ place: @escaping (CGRect) -> Void) -> Layout { Layout(size: size) { room, _ in place(room) } } /// `length` of room along a stack, in place of its gap. - public static func space(_ length: CGFloat) -> Layout { + static func space(_ length: CGFloat) -> Layout { Layout(size: sz(length), flex: Flex(natural: length, minimum: length, maximum: length, weight: 0)) { _, _ in } } /// `length` of room along a stack that grows to fill the stack's spare /// room, or gives it back where it's short, by a factor within /// `scales`. A stack's scaled spaces keep their proportions. - public static func space(_ length: CGFloat, scales: ClosedRange) -> Layout { + static func space(_ length: CGFloat, scales: ClosedRange) -> Layout { Layout( size: sz(length), flex: Flex(natural: length, minimum: length * scales.lowerBound, maximum: length * scales.upperBound, weight: length) @@ -229,7 +238,7 @@ extension Layout { /// Room that takes a share of a stack's spare room, `weight` against /// the stack's other spacers: spacers at both ends and between spread a /// row evenly. Never less than `minimum`. - public static func spacer(_ weight: CGFloat = 1, minimum: CGFloat = 0) -> Layout { + static func spacer(_ weight: CGFloat = 1, minimum: CGFloat = 0) -> Layout { Layout(size: sz(minimum), flex: Flex(natural: minimum, minimum: minimum, maximum: .infinity, weight: weight)) { _, _ in } } } @@ -241,7 +250,7 @@ extension Layout { /// gap), each standing across the column as `align` says: by default /// given the column's whole width, in the middle of which an item that /// doesn't stretch stands. - public static func column(_ items: [Layout], gap: CGFloat = 0, align: Layout.Horizontal = .fill) -> Layout { + static func column(_ items: [Layout], gap: CGFloat = 0, align: Layout.Horizontal = .fill) -> Layout { stack(items, vertical: true, gap: gap) { room, size, direction in room.aligning(size, align, .fill, direction: direction) } @@ -251,14 +260,14 @@ extension Layout { /// stands in for the gap), each standing across the row as `align` says: /// by default given the row's whole height, so a column in it can /// stretch its spaces. - public static func row(_ items: [Layout], gap: CGFloat = 0, align: Layout.Vertical = .fill) -> Layout { + static func row(_ items: [Layout], gap: CGFloat = 0, align: Layout.Vertical = .fill) -> Layout { stack(items, vertical: false, gap: gap) { room, size, direction in room.aligning(size, .fill, align, direction: direction) } } /// `items` one over another in the same rect, as big as the biggest. - public static func overlay(_ items: [Layout]) -> Layout { + static func overlay(_ items: [Layout]) -> Layout { let size = sz(items.map(\.size.width).max() ?? 0, items.map(\.size.height).max() ?? 0) return Layout(size: size) { room, direction in for item in items { item.placer(room, direction) } @@ -268,7 +277,7 @@ extension Layout { /// `items` in `columns` across, filled a row at a time from the leading /// top corner, each cell as big as the biggest item and `gap` apart /// (across, then down). A short last row starts at the leading edge. - public static func grid(_ items: [Layout], columns: Int, gap: CGSize = .zero) -> Layout { + static func grid(_ items: [Layout], columns: Int, gap: CGSize = .zero) -> Layout { let columns = max(1, columns) let cell = sz(items.map(\.size.width).max() ?? 0, items.map(\.size.height).max() ?? 0) let across = min(columns, items.count) @@ -331,21 +340,23 @@ extension Layout { // MARK: - Modifiers -extension Layout { +extension LayoutItem { /// Stands the item at its own size in its room, as `horizontal` and /// `vertical` say, rather than in the middle (or across the whole of /// it, where they `fill`). public func aligned(_ horizontal: Layout.Horizontal = .center, _ vertical: Layout.Vertical = .center) -> Layout { - Layout(size: size, flex: flex) { room, direction in - placer(room.aligning(size, horizontal, vertical, direction: direction), direction) + let item = layout + return Layout(size: item.size, flex: item.flex) { room, direction in + item.placer(room.aligning(item.size, horizontal, vertical, direction: direction), direction) } } /// Keeps `insets` of room round the item. public func padding(_ insets: Layout.Insets) -> Layout { - let padded = sz(size.width + insets.leading + insets.trailing, size.height + insets.top + insets.bottom) + let item = layout + let padded = sz(item.size.width + insets.leading + insets.trailing, item.size.height + insets.top + insets.bottom) return Layout(size: padded) { room, direction in - placer(room.inset(by: insets, direction: direction), direction) + item.placer(room.inset(by: insets, direction: direction), direction) } } @@ -360,8 +371,9 @@ extension Layout { /// Asks for `width` and `height` in place of the item's own (each where /// given); the item stands in the middle of what it's then given. public func frame(width: CGFloat? = nil, height: CGFloat? = nil) -> Layout { - Layout(size: sz(width ?? size.width, height ?? size.height)) { room, direction in - placer(room, direction) + let item = layout + return Layout(size: sz(width ?? item.size.width, height ?? item.size.height)) { room, direction in + item.placer(room, direction) } } @@ -369,7 +381,8 @@ extension Layout { /// (a board, a track): where the item itself stands is still its /// parent's to say. public func direction(_ direction: LayoutDirection) -> Layout { - Layout(size: size, flex: flex) { room, _ in placer(room, direction) } + let item = layout + return Layout(size: item.size, flex: item.flex) { room, _ in item.placer(room, direction) } } } diff --git a/Platform/Tests/PlatformLayoutTests/LayoutTests.swift b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift index e0fe961b..94549b52 100644 --- a/Platform/Tests/PlatformLayoutTests/LayoutTests.swift +++ b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift @@ -12,11 +12,11 @@ struct LayoutTests { @Test func aColumnStacksTopDownGapsApartInTheMiddle() { let (a, b, c) = (SKNode(), SKNode(), SKNode()) - let column = Layout.column([ - .node(a, size: sz(40, 20)), - .node(b, size: sz(60, 40)), - .node(c, size: sz(20, 20)), - ], gap: 10) + let column = Column(gap: 10) { + Item(a, size: sz(40, 20)) + Item(b, size: sz(60, 40)) + Item(c, size: sz(20, 20)) + } #expect(column.size == sz(60, 100)) column.place(in: room) #expect(a.position == pt(0, 40)) @@ -24,14 +24,14 @@ struct LayoutTests { #expect(c.position == pt(0, -40)) } - @Test func aSpaceStandsInForTheGap() { + @Test func aGapItemStandsInForTheStacksGap() { let (a, b, c) = (SKNode(), SKNode(), SKNode()) - let column = Layout.column([ - .node(a, size: sz(20)), - .space(30), - .node(b, size: sz(20)), - .node(c, size: sz(20)), - ], gap: 10) + let column = Column(gap: 10) { + Item(a, size: sz(20)) + Gap(30) + Item(b, size: sz(20)) + Item(c, size: sz(20)) + } #expect(column.size.height == 20 * 3 + 30 + 10 as CGFloat) column.place(in: room) #expect(a.position.y - b.position.y == 50) @@ -40,10 +40,10 @@ struct LayoutTests { @Test func aColumnAlignsItsItemsAcross() { let (a, b) = (SKNode(), SKNode()) - let column = Layout.column([ - .node(a, size: sz(40, 20)), - .node(b, size: sz(100, 20)), - ], align: .leading) + let column = Column(align: .leading) { + Item(a, size: sz(40, 20)) + Item(b, size: sz(100, 20)) + } column.aligned(.left, .top).place(in: room, direction: .leftToRight) #expect(a.position == pt(-80, 190)) #expect(b.position == pt(-50, 170)) @@ -54,7 +54,9 @@ struct LayoutTests { @Test func aRowRunsFromTheLeadingEdge() { let items = nodes(3) - let row = Layout.row(items.map { .node($0, size: sz(20)) }, gap: 10) + let row = Row(gap: 10) { + for item in items { Item(item, size: sz(20)) } + } #expect(row.size == sz(80, 20)) row.place(in: room, direction: .leftToRight) #expect(items.map(\.position.x) == [-30, 0, 30]) @@ -64,10 +66,10 @@ struct LayoutTests { @Test func aRowAlignsItsItemsUpAndDown() { let (a, b) = (SKNode(), SKNode()) - Layout.row([ - .node(a, size: sz(20, 10)), - .node(b, size: sz(20, 30)), - ], align: .top).place(in: rect(0, 0, 40, 30), direction: .leftToRight) + Row(align: .top) { + Item(a, size: sz(20, 10)) + Item(b, size: sz(20, 30)) + }.place(in: rect(0, 0, 40, 30), direction: .leftToRight) #expect(a.position == pt(10, 25)) #expect(b.position == pt(30, 15)) } @@ -76,13 +78,13 @@ struct LayoutTests { /// and at the edges. @Test func spacersSpreadARowEvenly() { let (a, b) = (SKNode(), SKNode()) - Layout.row([ - .spacer(), - .node(a, size: sz(40)), - .spacer(), - .node(b, size: sz(100)), - .spacer(), - ]).place(in: rect(0, 0, 200, 100), direction: .leftToRight) + Row { + Spacer() + Item(a, size: sz(40)) + Spacer() + Item(b, size: sz(100)) + Spacer() + }.place(in: rect(0, 0, 200, 100), direction: .leftToRight) let gap: CGFloat = (200 - 140) / 3 #expect(a.position.x == gap + 20) #expect(b.position.x == gap * 2 + 40 + 50) @@ -90,28 +92,28 @@ struct LayoutTests { @Test func spacersShareByWeight() { let (a, b) = (SKNode(), SKNode()) - Layout.column([ - .node(a, size: sz(20)), - .spacer(), - .node(b, size: sz(20)), - .spacer(0.5), - .spacer(), - ]).place(in: rect(0, 0, 20, 140)) + Column { + Item(a, size: sz(20)) + Spacer() + Item(b, size: sz(20)) + Spacer(0.5) + Spacer() + }.place(in: rect(0, 0, 20, 140)) // 100 spare: 40, 20, 40. #expect(a.position.y == 130) #expect(b.position.y == 70) } - @Test func scaledSpacesGrowTogetherUpToTheirMost() { + @Test func scaledGapsGrowTogetherUpToTheirMost() { let (a, b, c) = (SKNode(), SKNode(), SKNode()) - let column = Layout.column([ - .node(a, size: sz(20)), - .space(10, scales: 0.5...1.5), - .node(b, size: sz(20)), - .space(20, scales: 0.5...1.5), - .node(c, size: sz(20)), - ]) - // 15 spare of the 30 the spaces could take: half again as much. + let column = Column { + Item(a, size: sz(20)) + Gap(10, scales: 0.5...1.5) + Item(b, size: sz(20)) + Gap(20, scales: 0.5...1.5) + Item(c, size: sz(20)) + } + // 15 spare of the 30 the gaps could take: half again as much. column.place(in: rect(0, 0, 20, 105)) #expect(a.position.y - b.position.y == 20 + 15 as CGFloat) #expect(b.position.y - c.position.y == 20 + 30 as CGFloat) @@ -121,15 +123,15 @@ struct LayoutTests { #expect(a.position.y == 150 + (60 + 45) / 2 - 10 as CGFloat) } - @Test func scaledSpacesGiveBackRoomDownToTheirLeast() { + @Test func scaledGapsGiveBackRoomDownToTheirLeast() { let (a, b, c) = (SKNode(), SKNode(), SKNode()) - let column = Layout.column([ - .node(a, size: sz(20)), - .space(10, scales: 0.5...1.5), - .node(b, size: sz(20)), - .space(20, scales: 0.5...1.5), - .node(c, size: sz(20)), - ]) + let column = Column { + Item(a, size: sz(20)) + Gap(10, scales: 0.5...1.5) + Item(b, size: sz(20)) + Gap(20, scales: 0.5...1.5) + Item(c, size: sz(20)) + } column.place(in: rect(0, 0, 20, 81)) #expect(abs(a.position.y - b.position.y - (20 + 7)) < 1e-9) #expect(abs(b.position.y - c.position.y - (20 + 14)) < 1e-9) @@ -139,7 +141,9 @@ struct LayoutTests { @Test func aGridFillsRowsFromTheLeadingTopCorner() { let items = nodes(5) - let grid = Layout.grid(items.map { .node($0, size: sz(20, 10)) }, columns: 2, gap: sz(10, 5)) + let grid = Tiles(columns: 2, gap: sz(10, 5)) { + for item in items { Item(item, size: sz(20, 10)) } + } #expect(grid.size == sz(50, 40)) grid.place(in: rect(0, 0, 50, 40), direction: .leftToRight) #expect(items.map(\.position) == [pt(10, 35), pt(40, 35), pt(10, 20), pt(40, 20), pt(10, 5)]) @@ -149,7 +153,7 @@ struct LayoutTests { @Test func paddingKeepsRoomByReadingDirection() { let a = SKNode() - let item = Layout.node(a, size: sz(20)).padding(top: 10, leading: 30).aligned(.leading, .top) + let item = Item(a, size: sz(20)).padding(top: 10, leading: 30).aligned(.leading, .top) #expect(item.size == sz(50, 30)) item.place(in: rect(0, 0, 100, 100), direction: .leftToRight) #expect(a.position == pt(40, 80)) @@ -159,20 +163,20 @@ struct LayoutTests { @Test func frameAsksForOtherRoom() { let (a, b) = (SKNode(), SKNode()) - Layout.row([ - .node(a, size: sz(20)).frame(width: 60), - .node(b, size: sz(20)), - ]).place(in: rect(0, 0, 80, 20), direction: .leftToRight) + Row { + Item(a, size: sz(20)).frame(width: 60) + Item(b, size: sz(20)) + }.place(in: rect(0, 0, 80, 20), direction: .leftToRight) #expect(a.position.x == 30) #expect(b.position.x == 70) } @Test func anOverlayPlacesEachInTheSameRoom() { let (back, card) = (SKSpriteNode(color: .black, size: .zero), SKNode()) - Layout.overlay([ - .custom { back.size = $0.size; back.position = pt($0.midX, $0.midY) }, - .node(card, size: sz(100, 60)).aligned(.center, .bottom), - ]).place(in: room) + Overlay { + Item { back.size = $0.size; back.position = pt($0.midX, $0.midY) } + Item(card, size: sz(100, 60)).aligned(.center, .bottom) + }.place(in: room) #expect(back.size == room.size) #expect(back.position == pt(0, 0)) #expect(card.position == pt(0, -170)) @@ -180,12 +184,12 @@ struct LayoutTests { @Test func aNodeStandsByItsAnchorReadAsItsPlaced() { let sprite = SKSpriteNode(color: .black, size: sz(20)) - let item = Layout.node(sprite, size: sz(20)) + let item = Item(sprite, size: sz(20)) sprite.anchorPoint = pt(0, 1) item.place(in: rect(0, 0, 20, 20)) #expect(sprite.position == pt(0, 20)) let block = SKNode() - Layout.node(block, size: sz(40, 20), anchor: pt(0.5, 1)).place(in: rect(0, 0, 40, 20)) + Item(block, size: sz(40, 20), anchor: pt(0.5, 1)).place(in: rect(0, 0, 40, 20)) #expect(block.position == pt(20, 20)) } @@ -193,7 +197,7 @@ struct LayoutTests { /// after building the layout still counts. @Test func aLabelStandsByItsAlignmentModes() { let label = SKLabelNode() - let item = Layout.label(label, size: sz(60, 20)) + let item = Item(label, size: sz(60, 20)) label.horizontalAlignmentMode = .left label.verticalAlignmentMode = .top item.place(in: rect(0, 0, 60, 20)) @@ -208,29 +212,31 @@ struct LayoutTests { /// stands where its right-to-left parent puts it. @Test func aFixedDirectionKeepsItsContentsNotItsPlace() { let (title, first, second) = (SKNode(), SKNode(), SKNode()) - Layout.column([ - .node(title, size: sz(20)), - Layout.row([ - .node(first, size: sz(20)), - .node(second, size: sz(20)), - ]).direction(.leftToRight), - ], align: .leading).aligned(.leading, .top).place(in: rect(0, 0, 100, 100), direction: .rightToLeft) + Column(align: .leading) { + Item(title, size: sz(20)) + Row { + Item(first, size: sz(20)) + Item(second, size: sz(20)) + }.direction(.leftToRight) + }.aligned(.leading, .top).place(in: rect(0, 0, 100, 100), direction: .rightToLeft) #expect(title.position == pt(90, 90)) #expect(first.position == pt(70, 70)) #expect(second.position == pt(90, 70)) } /// A row gives each item its whole height by default, so a column in - /// it stretches its spaces to fill. + /// it stretches its gaps to fill. @Test func aColumnInARowStretches() { let (a, b, board) = (SKNode(), SKNode(), SKNode()) - let panel = Layout.column([ - .node(a, height: 20), - .space(10, scales: 1...3), - .node(b, height: 20), - ]) - Layout.row([panel, .node(board, size: sz(100))], gap: 20) - .place(in: rect(0, 0, 200, 100), direction: .leftToRight) + let panel = Column { + Item(a, height: 20) + Gap(10, scales: 1...3) + Item(b, height: 20) + } + Row(gap: 20) { + panel + Item(board, size: sz(100)) + }.place(in: rect(0, 0, 200, 100), direction: .leftToRight) #expect(a.position.y - b.position.y == 20 + 30 as CGFloat) #expect(board.position.y == 50) } @@ -240,10 +246,21 @@ struct LayoutTests { #expect(rect(0, 0, 100, 100).with(minX: 10) == rect(10, 0, 90, 100)) } + @Test func aStackTakesConditionsAndLoops() { + let items = nodes(3) + let showsFirst = false + let column = Column { + if showsFirst { Item(SKNode(), size: sz(100)) } + for item in items { Item(item, size: sz(10)) } + if let last = items.last { Item(last, size: sz(10)) } else { Gap(50) } + } + #expect(column.size == sz(10, 40)) + } + @Test func placingLeavesRunningActionsAlone() { let a = SKNode() a.run(.wait(forDuration: 10), withKey: "pulse") - Layout.node(a, size: sz(10)).place(in: rect(0, 0, 10, 10)) + Item(a, size: sz(10)).place(in: rect(0, 0, 10, 10)) #expect(a.action(forKey: "pulse") != nil) } } diff --git a/README.md b/README.md index e5de404c..3990d431 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ IDs, achievement IDs, constants), and the module does the rest. | --- | --- | | `PlatformCore` | Geometry shorthands, timing curves and eased `SKAction`s, a node added at its z-position in one line, action keys as an enum, seeded randomness you can replay, a launch-argument reader for debug switches, notification observers removed together (`ObserverBag`), stepping through an enum's cases (`index`, `next()`, `previous()`) | | `PlatformSprite` | A texture cache and sprite helpers, path and label builders, colours, text and font handling, SVG paths drawn as icons, shape sprites without `SKShapeNode`, scenes built off the main thread behind a loading screen, a studio's launch splash, safe-area layout, localization, debug markers | -| `PlatformLayout` | Optional, adopted a screen at a time: rows, columns, grids and overlays with gaps, padding and alignment, placed in `SceneLayout`'s rects, so positions stop being arithmetic and mirror for right-to-left languages | +| `PlatformLayout` | Optional, adopted a screen at a time: a result builder of columns, rows, tiles and overlays with gaps, padding and alignment, placed in `SceneLayout`'s rects, so positions stop being arithmetic and mirror for right-to-left languages | | `PlatformAudio` | Sound effects, and a soundtrack that loops seamlessly, crossfades between tracks, ducks for a jingle, and follows only the game's music switch, whatever other apps play | | `PlatformStore` | In-app purchases (StoreKit 2, or Play Billing): products, entitlements, restores, promoted purchases | | `PlatformGameCenter` | Sign-in, achievements and leaderboards that catch up from saved progress (GameKit, or Play Games) | @@ -576,39 +576,41 @@ decides, it hands in: ### Layout (`PlatformLayout`) Optional: a game links it and moves a screen onto it when it next works on -that screen. `Layout` says a screen's arrangement once, and `place(in:)` -sets every node's position from it in the rect it's given, `SceneLayout`'s -or a card's own: +that screen. A layout says a screen's arrangement once, in a result builder, +and `place(in:)` sets every node's position from it in the rect it's given, +`SceneLayout`'s or a card's own: ```swift -Layout.column([ - .node(heading, height: headingHeight, anchor: pt(0.5, 1)), - .space(.headingGap), - .grid(tiles.map { .node($0, size: tileSize) }, columns: columns, gap: sz(.tileGap)), - .space(.padding), - .node(closeButton, width: closeButton.width, height: .buttonHeight), -]) +Column { + Item(heading, height: headingHeight, anchor: pt(0.5, 1)) + Gap(.headingGap) + Tiles(columns: columns, gap: sz(.tileGap)) { + for tile in tiles { Item(tile, size: tileSize) } + } + Gap(.padding) + Item(closeButton, width: closeButton.width, height: .buttonHeight) +} .padding(top: .padding, bottom: .closeFoot) .place(in: sheetRect) ``` - **Items** state the room they ask for, from tokens or a text block's - measured size; nodes are never measured. `node` stands a node by its - anchor (a sprite's anchor point, read as it's placed), `label` by its - alignment modes, and `custom` hands its rect to a closure (a backdrop, a - card's face). -- **Containers:** `column`, `row`, `grid` and `overlay`. A stack's `gap` - goes between neighbours, a `space` in between stands in for it, and - `align` stands each item across the stack (by default each gets the whole - width or height and stands in its middle). `size` is the whole thing's - size, so a card's face is drawn from the same description its content is - placed by. -- **Stretching:** only spaces stretch. `space(_:scales:)` grows into a - stack's spare room or gives it back where it's short, within a factor of - its length; `spacer(_:)` takes a weighted share of what's spare, so - spacers at both ends and between spread a row evenly. Items don't grow or - wrap. -- **Modifiers:** `aligned`, `padding`, `frame` and `direction`. + measured size; nodes are never measured. `Item` stands a node by its + anchor, read as it's placed (a label's alignment modes, a sprite's anchor + point, or the middle); `Item(size:place:)` hands its rect to a closure (a + backdrop, a card's face). +- **Stacks:** `Column`, `Row`, `Tiles(columns:)` and `Overlay`, whose braces + take `if`, `switch` and `for`. A stack's `gap` goes between neighbours, a + `Gap` in between stands in for it, and `align` stands each item across + the stack (by default each gets the whole width or height and stands in + its middle). `size` is the whole thing's size, so a card's face is drawn + from the same description its content is placed by. +- **Stretching:** only gaps stretch. `Gap(_:scales:)` grows into a stack's + spare room or gives it back where it's short, within a factor of its + length; `Spacer(_:)` takes a weighted share of what's spare, so spacers + at both ends and between spread a row evenly. Items don't grow or wrap. +- **Modifiers:** `aligned`, `padding`, `frame` and `direction`, on the line + after an item as in SwiftUI. - **Direction:** rows run from the leading edge, and `leading`, `trailing` and padding mirror with `LayoutDirection.current`. `direction(_:)` keeps a board's or a track's contents as drawn, while where it stands is still @@ -617,7 +619,7 @@ Layout.column([ Placing sets resting positions and leaves running actions alone. Round buttons in the screen's corners stay with `SceneLayout`'s helpers -(`cornerButtonCenter`, the rail); `Layout` places what stands between them. +(`cornerButtonCenter`, the rail); a layout places what stands between them. ### Haptics, ratings and play time (`PlatformDevice`) From 625c176fb1a5b0f49f1e6356a9d7af6da7f34a16 Mon Sep 17 00:00:00 2001 From: Himanshu Kapoor Date: Sun, 29 Nov 2026 15:43:25 +0100 Subject: [PATCH 3/3] PlatformLayout: LayoutSized, so Item(node) takes a node's own size; text blocks know theirs --- Platform/Package.swift | 8 ++-- Platform/Sources/PlatformLayout/Items.swift | 39 +++++++++++++++---- Platform/Sources/PlatformLayout/Layout.swift | 8 ++-- .../PlatformLayout/TextBlockLayout.swift | 25 ++++++++++++ .../Sources/PlatformSprite/TextHelpers.swift | 13 ++++++- .../PlatformLayoutTests/LayoutTests.swift | 39 +++++++++++++++++++ README.md | 18 +++++---- 7 files changed, 128 insertions(+), 22 deletions(-) create mode 100644 Platform/Sources/PlatformLayout/TextBlockLayout.swift diff --git a/Platform/Package.swift b/Platform/Package.swift index cf6956b5..d27a5824 100644 --- a/Platform/Package.swift +++ b/Platform/Package.swift @@ -271,13 +271,15 @@ let package = Package( ], swiftSettings: settings ), - // Optional, adopted screen by screen: rows, columns, grids and - // overlays with gaps, padding and alignment, placed in a rect - // (`Layout`) instead of worked out position by position. + // Optional, adopted screen by screen: columns, rows, tiles and + // overlays with gaps, padding and alignment, written in a result + // builder and placed in a rect instead of worked out position by + // position. Text blocks (`PlatformSprite`) know their own size. .target( name: "PlatformLayout", dependencies: [ "PlatformCore", + "PlatformSprite", .product(name: "SpriteKitShim", package: "spritekit-android", condition: onShim), ], swiftSettings: settings diff --git a/Platform/Sources/PlatformLayout/Items.swift b/Platform/Sources/PlatformLayout/Items.swift index 6f50e591..bb4dab09 100644 --- a/Platform/Sources/PlatformLayout/Items.swift +++ b/Platform/Sources/PlatformLayout/Items.swift @@ -72,24 +72,47 @@ public struct Overlay: LayoutItem { } } -/// A node, `size` big, standing in the middle of the room it's given, its -/// position where `anchor` (a share of `size`) falls. By default, read as -/// it's placed: where a label's alignment modes put its text (a baseline on -/// the foot), a sprite's anchor point, or the middle, as a container node -/// draws round its origin. +/// A node that knows the room it takes, so `Item(node)` needs no size: a +/// game's button, its board, a text block. A size given to `Item` wins. +public protocol LayoutSized: SKNode { + /// The room it asks for, read as the layout is made. + var layoutSize: CGSize { get } + /// Where its position falls in that room, as a share of it, read as it's + /// placed; nil (the default) for an item's usual default. + var layoutAnchor: CGPoint? { get } +} + +extension LayoutSized { + public var layoutAnchor: CGPoint? { nil } +} + +/// A node standing in the middle of the room it's given, its position where +/// `anchor` (a share of its size) falls. By default, read as it's placed: a +/// `LayoutSized` node's `layoutAnchor`, where a label's alignment modes put +/// its text (a baseline on the foot), a sprite's anchor point, or the +/// middle, as a container node draws round its origin. public struct Item: LayoutItem { public let layout: Layout + /// A node that knows its size (`LayoutSized`). + public init(_ node: some LayoutSized, anchor: CGPoint? = nil) { + layout = .node(node, size: node.layoutSize, anchor: anchor) + } + public init(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) { layout = .node(node, size: size, anchor: anchor) } - /// A node where only its height counts (in a column) or only its width - /// (in a row). - public init(_ node: SKNode, width: CGFloat = 0, height: CGFloat = 0, anchor: CGPoint? = nil) { + /// A node where only its height counts (in a column), or its width too. + public init(_ node: SKNode, width: CGFloat = 0, height: CGFloat, anchor: CGPoint? = nil) { layout = .node(node, size: sz(width, height), anchor: anchor) } + /// A node where only its width counts (in a row). + public init(_ node: SKNode, width: CGFloat, anchor: CGPoint? = nil) { + layout = .node(node, size: sz(width, 0), anchor: anchor) + } + /// Asks for `size` and hands `place` the rect it's given, whole: for /// what's sized to its room (a backdrop, a card's face) or placed by /// rules of its own. diff --git a/Platform/Sources/PlatformLayout/Layout.swift b/Platform/Sources/PlatformLayout/Layout.swift index 0db02004..a592f961 100644 --- a/Platform/Sources/PlatformLayout/Layout.swift +++ b/Platform/Sources/PlatformLayout/Layout.swift @@ -185,9 +185,10 @@ extension Layout { extension Layout { /// `node`, `size` big, standing in the middle of the room it's given, /// its position where `anchor` (a share of `size`) falls. By default, - /// read as it's placed: where a label's alignment modes put its text (a - /// baseline on the foot), a sprite's anchor point, or the middle, as a - /// container node draws round its origin. + /// read as it's placed: a `LayoutSized` node's `layoutAnchor`, where a + /// label's alignment modes put its text (a baseline on the foot), a + /// sprite's anchor point, or the middle, as a container node draws + /// round its origin. static func node(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) -> Layout { Layout(size: size) { room, _ in let anchor = anchor ?? defaultAnchor(of: node) @@ -197,6 +198,7 @@ extension Layout { } private static func defaultAnchor(of node: SKNode) -> CGPoint { + if let anchor = (node as? LayoutSized)?.layoutAnchor { return anchor } if let label = node as? SKLabelNode { let x: CGFloat = switch label.horizontalAlignmentMode { case .left: 0 diff --git a/Platform/Sources/PlatformLayout/TextBlockLayout.swift b/Platform/Sources/PlatformLayout/TextBlockLayout.swift new file mode 100644 index 00000000..1c6cf9e6 --- /dev/null +++ b/Platform/Sources/PlatformLayout/TextBlockLayout.swift @@ -0,0 +1,25 @@ +import Foundation +#if SPRITEKIT_SHIM +import SpriteKitShim +#else +import SpriteKit +import UIKit +#endif +import PlatformSprite + +#if canImport(UIKit) || !canImport(Darwin) +/// A text block asks for its measured lines and stands by its alignment, +/// from its top or its first baseline. +extension TextBlockNode: LayoutSized { + public var layoutSize: CGSize { sz(width, height) } + + public var layoutAnchor: CGPoint? { + let x: CGFloat = switch lines.first?.horizontalAlignmentMode { + case .left: 0 + case .right: 1 + default: 0.5 + } + return pt(x, height > 0 ? (height - topAboveOrigin) / height : 1) + } +} +#endif diff --git a/Platform/Sources/PlatformSprite/TextHelpers.swift b/Platform/Sources/PlatformSprite/TextHelpers.swift index 5491d28b..1d649e08 100644 --- a/Platform/Sources/PlatformSprite/TextHelpers.swift +++ b/Platform/Sources/PlatformSprite/TextHelpers.swift @@ -299,6 +299,9 @@ public final class TextBlockNode: SKNode { public let lineAdvance: CGFloat /// The lines, top first. public let lines: [SKLabelNode] + /// How far the block's top stands above its origin: 0 hung from its + /// top, the first line's ascent above its baseline otherwise. + public let topAboveOrigin: CGFloat public convenience init( _ text: String, @@ -340,10 +343,18 @@ public final class TextBlockNode: SKNode { height = CGFloat(texts.count) * advance - lineSpacing width = texts.map { ($0 as NSString).size(withAttributes: [.font: font]).width }.max() ?? 0 self.font = font + let topBandMiddle = -font.baseline(.center, at: 0, band: band) let bandMiddle: CGFloat? = switch anchor { - case .top: -font.baseline(.center, at: 0, band: band) + case .top: topBandMiddle case .firstBaseline: nil } + // Hung from its baseline, the top stands where the first baseline + // would stand below it hung from its top. + topAboveOrigin = switch anchor { + case .top: 0 + case .firstBaseline: + -(textBlockBaselines(count: 1, advance: advance, lineSpacing: lineSpacing, bandMiddle: topBandMiddle).first ?? 0) + } let baselines = textBlockBaselines(count: texts.count, advance: advance, lineSpacing: lineSpacing, bandMiddle: bandMiddle) lines = zip(texts, baselines).map { line, baseline in let label = SKLabelNode() diff --git a/Platform/Tests/PlatformLayoutTests/LayoutTests.swift b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift index 94549b52..ad567dec 100644 --- a/Platform/Tests/PlatformLayoutTests/LayoutTests.swift +++ b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift @@ -2,6 +2,13 @@ import Foundation import Testing import SpriteKitShim @testable import PlatformLayout +import PlatformSprite + +/// A node that says its own size and where it hangs, as a game's button would. +private final class Badge: SKNode, LayoutSized { + var layoutSize: CGSize { sz(40, 20) } + var layoutAnchor: CGPoint? = pt(0, 1) +} struct LayoutTests { private let room = rect(-100, -200, 200, 400) @@ -257,6 +264,38 @@ struct LayoutTests { #expect(column.size == sz(10, 40)) } + /// `Item(node)` takes a `LayoutSized` node's size, and its anchor as + /// it's placed; a size given wins. + @Test func aSizedNodeNeedsNoSize() { + let badge = Badge() + let item = Item(badge) + #expect(item.size == sz(40, 20)) + badge.layoutAnchor = pt(0.5, 0.5) + item.place(in: rect(0, 0, 40, 20)) + #expect(badge.position == pt(20, 10)) + badge.layoutAnchor = pt(0, 1) + Item(badge, height: 30).place(in: rect(0, 0, 0, 30)) + #expect(badge.position == pt(0, 30)) + } + + #if canImport(UIKit) + /// A text block asks for its measured lines and hangs by its alignment + /// from its top, or from its first baseline that far below it. + @Test func aTextBlockKnowsItsSize() { + for anchor in [TextBlockNode.Anchor.top, .firstBaseline] { + let block = TextBlockNode( + "Two words", maxWidth: 1000, font: .systemFont(ofSize: 20), color: .white, + alignment: .left, anchor: anchor) + let item = Item(block) + #expect(item.size == sz(block.width, block.height)) + item.place(in: rect(0, 0, block.width, block.height)) + #expect(abs(block.position.x) < 1e-9) + #expect(abs(block.position.y + block.topAboveOrigin - block.height) < 1e-9) + #expect((anchor == .top) == (block.topAboveOrigin == 0)) + } + } + #endif + @Test func placingLeavesRunningActionsAlone() { let a = SKNode() a.run(.wait(forDuration: 10), withKey: "pulse") diff --git a/README.md b/README.md index 3990d431..892a0253 100644 --- a/README.md +++ b/README.md @@ -582,23 +582,27 @@ and `place(in:)` sets every node's position from it in the rect it's given, ```swift Column { - Item(heading, height: headingHeight, anchor: pt(0.5, 1)) + Item(heading) Gap(.headingGap) Tiles(columns: columns, gap: sz(.tileGap)) { for tile in tiles { Item(tile, size: tileSize) } } Gap(.padding) - Item(closeButton, width: closeButton.width, height: .buttonHeight) + Item(closeButton) } .padding(top: .padding, bottom: .closeFoot) .place(in: sheetRect) ``` -- **Items** state the room they ask for, from tokens or a text block's - measured size; nodes are never measured. `Item` stands a node by its - anchor, read as it's placed (a label's alignment modes, a sprite's anchor - point, or the middle); `Item(size:place:)` hands its rect to a closure (a - backdrop, a card's face). +- **Items** state the room they ask for; nodes are never measured (their + frames take in shadows, glows and running animations). A node that knows + its size adopts `LayoutSized` (`layoutSize`, and `layoutAnchor` if its + origin isn't its middle), so `Item(node)` needs nothing more; a + `TextBlockNode` does, from its measured lines. Any other node takes + `size:`, `width:` or `height:`, which also override. `Item` stands a node + by its anchor, read as it's placed (`layoutAnchor`, a label's alignment + modes, a sprite's anchor point, or the middle); `Item(size:place:)` hands + its rect to a closure (a backdrop, a card's face). - **Stacks:** `Column`, `Row`, `Tiles(columns:)` and `Overlay`, whose braces take `if`, `switch` and `for`. A stack's `gap` goes between neighbours, a `Gap` in between stands in for it, and `align` stands each item across