diff --git a/Platform/Package.swift b/Platform/Package.swift index 994e34e0..d27a5824 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,27 @@ let package = Package( ], swiftSettings: settings ), + // 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 + ), + .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/Items.swift b/Platform/Sources/PlatformLayout/Items.swift new file mode 100644 index 00000000..bb4dab09 --- /dev/null +++ b/Platform/Sources/PlatformLayout/Items.swift @@ -0,0 +1,150 @@ +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 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 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. + 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 new file mode 100644 index 00000000..a592f961 --- /dev/null +++ b/Platform/Sources/PlatformLayout/Layout.swift @@ -0,0 +1,444 @@ +import Foundation +#if SPRITEKIT_SHIM +import SpriteKitShim +#else +import SpriteKit +import UIKit +#endif +@_exported import PlatformCore + +/// 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. +/// +/// 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: a scaled `Gap` and a `Spacer` take up or give back a +/// stack's spare room. +/// +/// 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: LayoutItem { + /// 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 + } + + 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) { + layout.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 where `anchor` (a share of `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. + static func node(_ node: SKNode, size: CGSize, anchor: CGPoint? = nil) -> Layout { + Layout(size: size) { room, _ in + 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) + } + } + + 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 + case .right: 1 + default: 0.5 + } + let y: CGFloat = switch label.verticalAlignmentMode { + case .center: 0.5 + case .top: 1 + default: 0 + } + 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. + 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. + 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. + 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`. + 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. + 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. + 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. + 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. + 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 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 { + 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 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 + item.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 { + let item = layout + return Layout(size: sz(width ?? item.size.width, height ?? item.size.height)) { room, direction in + item.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 { + let item = layout + return Layout(size: item.size, flex: item.flex) { room, _ in item.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/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 new file mode 100644 index 00000000..ad567dec --- /dev/null +++ b/Platform/Tests/PlatformLayoutTests/LayoutTests.swift @@ -0,0 +1,305 @@ +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) + + private func nodes(_ count: Int) -> [SKNode] { + (0..