Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@ would want.
- Lay out from `SceneLayout` (the visible and safe rects), never from the
scene's size, so every screen works on phones and tablets, upright and in
landscape.
- Lay a screen out with `LayoutItem` (rows, columns, grids, overlays,
insets) rather than position arithmetic, and name horizontal places by
reading order: `leading` and `trailing`, never left and right, so the
screen mirrors in a right-to-left language (`LayoutDirection`). What
shows a physical direction (a board, a track) lays its contents out in
its own with `direction(_:)`, standing where its parent puts it; art that points along the reading order (a back
chevron) flips with `mirrorScale`.
- Never share an `SKUniform` between shaders that may be built on different
threads; give each shader its own.
- Every random draw comes from a named, seedable stream (`Random`), never a
Expand Down
72 changes: 72 additions & 0 deletions Platform/Sources/PlatformSprite/LayoutDirection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import Foundation
import SpriteKitShim

/// Which way the interface reads: left to right, or right to left (Arabic,
/// Hebrew, Persian, Urdu). Layout written with leading and trailing edges
/// (`LayoutItem`, `SceneLayout`'s edge helpers) mirrors by it; what shows
/// a physical direction (a board, a slider's track, a clock) stays as drawn.
public nonisolated enum LayoutDirection: Sendable, Equatable {
case leftToRight
case rightToLeft

/// The direction the game's language reads in, unless `forced`.
public static var current: LayoutDirection {
forced ?? resolve()
}

/// The direction of the game's language: set by `Typography.follow`, or
/// by a game that resolves its language another way.
public nonisolated(unsafe) static var resolve: () -> LayoutDirection = { .leftToRight }

/// A direction every layout takes whatever the language (a debug launch
/// argument mirroring the interface in English, say); nil follows it.
public nonisolated(unsafe) static var forced: LayoutDirection?

/// Languages whose script reads right to left, by language code.
private static let rightToLeftLanguages: Set<String> = ["ar", "arc", "ckb", "dv", "fa", "he", "iw", "ks", "ku-Arab", "ps", "sd", "ug", "ur", "yi"]

/// The direction a language code (`"ar"`, `"he-IL"`, `"pt-BR"`) reads in.
public static func of(language code: String) -> LayoutDirection {
let parts = code.split(whereSeparator: { $0 == "-" || $0 == "_" })
guard let language = parts.first.map({ $0.lowercased() }) else { return .leftToRight }
if rightToLeftLanguages.contains(language) { return .rightToLeft }
if let script = parts.dropFirst().first, rightToLeftLanguages.contains("\(language)-\(script)") { return .rightToLeft }
return .leftToRight
}

public var isRightToLeft: Bool { self == .rightToLeft }

/// The screen side an edge is on: -1 left, 1 right, as `SceneLayout`'s
/// `side` arguments take it.
public func side(_ edge: HorizontalEdge) -> CGFloat {
let leadingSide: CGFloat = isRightToLeft ? 1 : -1
return edge == .leading ? leadingSide : -leadingSide
}

/// The x of `rect`'s `edge`.
public func x(_ edge: HorizontalEdge, of rect: CGRect) -> CGFloat {
side(edge) < 0 ? rect.minX : rect.maxX
}

/// An `xScale` sign that turns art drawn for left to right (a back
/// chevron, a "next" arrow) to face this direction.
public var mirrorScale: CGFloat { isRightToLeft ? -1 : 1 }

/// A label's alignment for text set against `edge`.
public func labelAlignment(_ edge: HorizontalEdge) -> SKLabelHorizontalAlignmentMode {
side(edge) < 0 ? .left : .right
}
}

/// A horizontal edge named by reading order: leading is where lines start
/// (the left in English, the right in Arabic).
public nonisolated enum HorizontalEdge: Sendable, Equatable {
case leading
case trailing
}

extension LocalizationLanguage {
/// The direction this language reads in, from its raw value as a
/// language code.
public var layoutDirection: LayoutDirection { LayoutDirection.of(language: rawValue) }
}
281 changes: 281 additions & 0 deletions Platform/Sources/PlatformSprite/LayoutItem.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
import Foundation
import SpriteKitShim

/// A small rect-based layout: rows and columns with gaps, grids, overlays
/// and insets, over the rects `SceneLayout` gives. Items state their own
/// size (design tokens, a label's measured text) rather than being measured,
/// and placing a tree sets each leaf's resting position once, on load and
/// when the layout changes, never per frame. It leaves running actions
/// alone.
///
/// Horizontal placement is by reading order: rows run from the leading
/// edge, grids fill from it, and `leading`/`trailing` alignment and insets
/// mirror in a right-to-left language (`LayoutDirection.current`). A subtree
/// that shows a physical direction keeps its own with `direction(_:)`.
///
/// LayoutItem.overlay([
/// .node(back, size: buttonSize).aligned(.leading, .top),
/// .node(settings, size: buttonSize).aligned(.trailing, .top),
/// .column([.label(title, height: titleHeight), .grid(coins, columns: 5, gap: sz(12))], gap: 24),
/// ])
/// .aligned(.fill, .fill)
/// .place(in: layout.contentRect)
///
/// No flexible sizing or wrapping: a row wider than the rect it's given
/// runs past it.
public struct LayoutItem {
/// Where an item stands across the rect it's given. `fill` takes the
/// rect's whole width.
public enum HAlign: Equatable { case leading, center, trailing, fill }
/// Where an item stands up and down the rect it's given. `fill` takes
/// the rect's whole height.
public enum VAlign: Equatable { case top, center, bottom, fill }

/// Insets by reading order: `leading` is the left in a left-to-right
/// language and the right in a right-to-left one.
public struct Insets: Equatable {
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)
}

/// `rect` inset, the leading and trailing insets on the sides
/// `direction` puts them.
public func inset(_ rect: CGRect, direction: LayoutDirection) -> CGRect {
let left = direction.isRightToLeft ? trailing : leading
let right = direction.isRightToLeft ? leading : trailing
return CGRect(x: rect.minX + left, y: rect.minY + bottom, width: rect.width - left - right, height: rect.height - top - bottom)
}
}

/// Where a leaf landed: its frame in the parent's space, and the
/// direction it was laid out in.
public struct Placement {
public let frame: CGRect
public let direction: LayoutDirection
}

private indirect enum Content {
case leaf((Placement) -> Void)
case row([LayoutItem], gap: CGFloat, align: VAlign)
case column([LayoutItem], gap: CGFloat, align: HAlign)
case grid([LayoutItem], columns: Int, gap: CGSize, cell: CGSize)
case overlay([LayoutItem])
case inset(LayoutItem, Insets)
}

private let content: Content
/// The size the item asks for.
public private(set) var size: CGSize
private var hAlign: HAlign?
private var vAlign: VAlign?
private var fixedDirection: LayoutDirection?

private init(_ content: Content, size: CGSize) {
self.content = content
self.size = size
}

// MARK: Leaves

/// A leaf of `size`; `place` hears where it landed.
public static func leaf(_ size: CGSize, place: @escaping (Placement) -> Void) -> LayoutItem {
LayoutItem(.leaf(place), size: size)
}

/// Empty space of `size`.
public static func space(_ size: CGSize) -> LayoutItem {
leaf(size) { _ in }
}

/// Empty space `width` wide (in a row) or `height` tall (in a column).
public static func space(width: CGFloat = 0, height: CGFloat = 0) -> LayoutItem {
space(CGSize(width: width, height: height))
}

/// `node`, `size` big, its position the point `anchor` names in its
/// frame ((0.5, 0.5) its middle, (0, 0) its bottom left: the node's own
/// anchor, which doesn't mirror).
public static func node(_ node: SKNode, size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) -> LayoutItem {
leaf(size) { placement in
let frame = placement.frame
node.position = CGPoint(x: frame.minX + frame.width * anchor.x, y: frame.minY + frame.height * anchor.y)
}
}

/// A one-line label as wide as its text and `height` tall (a line's
/// band), positioned by its own horizontal alignment and centred up and
/// down, as a label built with `.vAlign(.center)` keeps its band.
public static func label(_ label: SKLabelNode, height: CGFloat) -> LayoutItem {
let anchorX: CGFloat
switch label.horizontalAlignmentMode {
case .left: anchorX = 0
case .right: anchorX = 1
default: anchorX = 0.5
}
return node(label, size: CGSize(width: label.frame.width, height: height), anchor: CGPoint(x: anchorX, y: 0.5))
}

// MARK: Containers

/// `items` side by side from the leading edge, `gap` apart, each
/// standing `align` in the row's height unless it says otherwise.
public static func row(_ items: [LayoutItem], gap: CGFloat = 0, align: VAlign = .center) -> LayoutItem {
let width = items.reduce(0) { $0 + $1.size.width } + gap * CGFloat(max(items.count - 1, 0))
let height = items.map(\.size.height).max() ?? 0
return LayoutItem(.row(items, gap: gap, align: align), size: CGSize(width: width, height: height))
}

/// `items` top to bottom, `gap` apart, each standing `align` across the
/// column's width unless it says otherwise.
public static func column(_ items: [LayoutItem], gap: CGFloat = 0, align: HAlign = .center) -> LayoutItem {
let width = items.map(\.size.width).max() ?? 0
let height = items.reduce(0) { $0 + $1.size.height } + gap * CGFloat(max(items.count - 1, 0))
return LayoutItem(.column(items, gap: gap, align: align), size: CGSize(width: width, height: height))
}

/// `items` in a grid `columns` wide, filled a row at a time from the
/// leading edge, top row first. Every cell is `cell` big (the largest
/// item's size by default), each item centred in its own unless it says
/// otherwise.
public static func grid(_ items: [LayoutItem], columns: Int, gap: CGSize = .zero, cell: CGSize? = nil) -> LayoutItem {
let columns = max(columns, 1)
let cell = cell ?? CGSize(width: items.map(\.size.width).max() ?? 0, height: items.map(\.size.height).max() ?? 0)
let across = min(columns, items.count)
let rows = (items.count + columns - 1) / columns
let size = CGSize(
width: cell.width * CGFloat(across) + gap.width * CGFloat(max(across - 1, 0)),
height: cell.height * CGFloat(rows) + gap.height * CGFloat(max(rows - 1, 0))
)
return LayoutItem(.grid(items, columns: columns, gap: gap, cell: cell), size: size)
}

/// `items` over one another, each in the whole of the overlay's frame
/// by its own alignment: as big as the biggest.
public static func overlay(_ items: [LayoutItem]) -> LayoutItem {
let size = CGSize(width: items.map(\.size.width).max() ?? 0, height: items.map(\.size.height).max() ?? 0)
return LayoutItem(.overlay(items), size: size)
}

// MARK: Modifiers

/// This item inside `insets`: as big as it is plus them, and laid out
/// in its frame less them.
public func inset(_ insets: Insets) -> LayoutItem {
let size = CGSize(width: self.size.width + insets.leading + insets.trailing, height: self.size.height + insets.top + insets.bottom)
return LayoutItem(.inset(self, insets), size: size)
}

/// This item standing `horizontal` and `vertical` in the rect it's given.
public func aligned(_ horizontal: HAlign? = nil, _ vertical: VAlign? = nil) -> LayoutItem {
var item = self
if let horizontal { item.hAlign = horizontal }
if let vertical { item.vAlign = vertical }
return item
}

/// This item asking for `width` and `height` rather than its own size
/// (what it holds lays out in that frame).
public func sized(width: CGFloat? = nil, height: CGFloat? = nil) -> LayoutItem {
var item = self
item.size = CGSize(width: width ?? size.width, height: height ?? size.height)
return item
}

/// What this item holds laid out in `direction` whatever the language:
/// for what shows a physical direction (a board, a track). Where the
/// item itself stands in its parent still follows the parent's.
public func direction(_ direction: LayoutDirection) -> LayoutItem {
Comment on lines +196 to +203

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The anchor is read from label.horizontalAlignmentMode once, when the item is built. Anything that changes the mode later leaves the label positioned for the old mode. The third row of the PR's own Before / after table does exactly that: it sets text.horizontalAlignmentMode = LayoutDirection.current.labelAlignment(.leading) after .label(text, …) and .place(in:). The label is built .center, so it gets anchor 0.5 and its position lands on the middle of its slot. Switching to .left then starts the text there, half its width toward the trailing side of where the row put it. In right-to-left, .right ends the text at that middle point instead. Reading the mode inside the place closure would help when it's set between building and placing. The documented pattern also needs to set the alignment before building the item.

var item = self
item.fixedDirection = direction
return item
}

// MARK: Placing

/// Places the tree in `rect`: this item stands in it by its alignment
/// (centred unless it says otherwise) and every leaf hears its frame.
public func place(in rect: CGRect, direction: LayoutDirection = .current) {
place(in: rect, direction: direction, hDefault: .center, vDefault: .center)
}

/// The frame this item takes in `rect`, standing by its alignment.
public func frame(in rect: CGRect, direction: LayoutDirection = .current) -> CGRect {
frame(in: rect, direction: direction, h: hAlign ?? .center, v: vAlign ?? .center)
}

private func frame(in rect: CGRect, direction: LayoutDirection, h: HAlign, v: VAlign) -> CGRect {
let width = h == .fill ? rect.width : size.width
let height = v == .fill ? rect.height : size.height
let x: CGFloat
switch h {
case .fill: x = rect.minX
case .center: x = rect.midX - width / 2
case .leading, .trailing:
let edge: HorizontalEdge = h == .leading ? .leading : .trailing
x = direction.side(edge) < 0 ? rect.minX : rect.maxX - width
}
let y: CGFloat
switch v {
case .fill, .bottom: y = rect.minY
case .center: y = rect.midY - height / 2
case .top: y = rect.maxY - height
}
return CGRect(x: x, y: y, width: width, height: height)
}

private func place(in rect: CGRect, direction inherited: LayoutDirection, hDefault: HAlign, vDefault: VAlign) {
let frame = frame(in: rect, direction: inherited, h: hAlign ?? hDefault, v: vAlign ?? vDefault)
let direction = fixedDirection ?? inherited
let rightToLeft = direction.isRightToLeft
switch content {
case .leaf(let place):
place(Placement(frame: frame, direction: direction))
case let .row(items, gap, align):
var cursor = rightToLeft ? frame.maxX : frame.minX
for item in items {
let width = item.size.width
let x = rightToLeft ? cursor - width : cursor
item.place(in: CGRect(x: x, y: frame.minY, width: width, height: frame.height), direction: direction, hDefault: .center, vDefault: align)
cursor += (rightToLeft ? -1 : 1) * (width + gap)
}
case let .column(items, gap, align):
var top = frame.maxY
for item in items {
let height = item.size.height
item.place(in: CGRect(x: frame.minX, y: top - height, width: frame.width, height: height), direction: direction, hDefault: align, vDefault: .center)
top -= height + gap
}
case let .grid(items, columns, gap, cell):
for (index, item) in items.enumerated() {
let column = CGFloat(index % columns)
let row = CGFloat(index / columns)
let offset = column * (cell.width + gap.width)
let x = rightToLeft ? frame.maxX - offset - cell.width : frame.minX + offset
let y = frame.maxY - row * (cell.height + gap.height) - cell.height
item.place(in: CGRect(x: x, y: y, width: cell.width, height: cell.height), direction: direction, hDefault: .center, vDefault: .center)
}
case .overlay(let items):
for item in items {
item.place(in: frame, direction: direction, hDefault: .center, vDefault: .center)
}
case let .inset(item, insets):
item.place(in: insets.inset(frame, direction: direction), direction: direction, hDefault: .fill, vDefault: .fill)
}
}
}
20 changes: 20 additions & 0 deletions Platform/Sources/PlatformSprite/SceneLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,23 @@ public struct SceneLayout: Equatable {
cornerButtonCenter(side: 1, end: -1, size: size).offset(0, CGFloat(index) * metrics.railButtonSpacing)
}
}

extension SceneLayout {
/// `edgeX(side:clearsHousing:)` by reading order: the leading edge is
/// the left in a left-to-right language and the right in a
/// right-to-left one.
public func edgeX(_ edge: HorizontalEdge, clearsHousing: Bool, direction: LayoutDirection = .current) -> CGFloat {
edgeX(side: direction.side(edge), clearsHousing: clearsHousing)
}

/// `edgeButtonX(side:size:clearsHousing:)` by reading order.
public func edgeButtonX(_ edge: HorizontalEdge, size: CGFloat, clearsHousing: Bool, direction: LayoutDirection = .current) -> CGFloat {
edgeButtonX(side: direction.side(edge), size: size, clearsHousing: clearsHousing)
}

/// `cornerButtonCenter(side:end:size:)` by reading order: a back button
/// stands in the leading top corner.
public func cornerButtonCenter(_ edge: HorizontalEdge, end: CGFloat, size: CGFloat, direction: LayoutDirection = .current) -> CGPoint {
cornerButtonCenter(side: direction.side(edge), end: end, size: size)
}
}
Loading
Loading