Files
2026-06-21 12:25:18 -07:00

210 lines
7.2 KiB
Swift

// FlowLayout.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// A SwiftUI `Layout` that arranges subviews left-to-right and wraps to the next
/// row whenever the remaining horizontal space in the current row is exhausted.
///
/// Each row is filled greedily: subviews are placed in insertion order until
/// the next subview would exceed the proposed width, at which point a new row
/// begins. The final layout height is the sum of all row heights plus the
/// inter-row spacing.
///
/// ## Infinite / nil proposed width
///
/// When the container proposes an infinite or `nil` width (e.g. inside a
/// horizontal `ScrollView`), `FlowLayout` falls back to `FlowLayout.fallbackMaxWidth`
/// and lays out subviews on a single logical strip up to that cap. This avoids
/// an unbounded single-row layout that would make `sizeThatFits` report infinite
/// height.
///
/// ## Usage
///
/// ```swift
/// FlowLayout(horizontalSpacing: 12, verticalSpacing: 16) {
/// ForEach(pedals, id: \.id) { pedal in
/// PedalView(pedal: pedal)
/// }
/// }
/// ```
///
/// - Parameters:
/// - horizontalSpacing: Gap between adjacent subviews in the same row.
/// Defaults to `FlowLayout.defaultHorizontalSpacing`.
/// - verticalSpacing: Gap between rows.
/// Defaults to `FlowLayout.defaultVerticalSpacing`.
public struct FlowLayout: Layout {
// MARK: - Named constants
/// Default gap between subviews within the same row (points).
public static let defaultHorizontalSpacing: CGFloat = 16
/// Default gap between rows (points).
public static let defaultVerticalSpacing: CGFloat = 16
/// Maximum width used when the container proposes infinite or zero width,
/// preventing an unbounded single-row layout.
public static let fallbackMaxWidth: CGFloat = 1200
// MARK: - Properties
/// Gap between adjacent subviews in the same row.
public let horizontalSpacing: CGFloat
/// Gap between rows.
public let verticalSpacing: CGFloat
// MARK: - Init
/// Creates a flow layout with the given spacings.
///
/// - Parameters:
/// - horizontalSpacing: Gap between subviews within a row (points).
/// Defaults to `FlowLayout.defaultHorizontalSpacing`.
/// - verticalSpacing: Gap between rows (points).
/// Defaults to `FlowLayout.defaultVerticalSpacing`.
public init(
horizontalSpacing: CGFloat = FlowLayout.defaultHorizontalSpacing,
verticalSpacing: CGFloat = FlowLayout.defaultVerticalSpacing
) {
self.horizontalSpacing = horizontalSpacing
self.verticalSpacing = verticalSpacing
}
// MARK: - Layout protocol
public func sizeThatFits(
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) -> CGSize {
let rows: [[RowItem]] = computeRows(
subviews: subviews,
availableWidth: resolvedWidth(from: proposal)
)
return totalSize(rows: rows)
}
public func placeSubviews(
in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) {
let rows: [[RowItem]] = computeRows(
subviews: subviews,
availableWidth: resolvedWidth(from: proposal)
)
var y: CGFloat = bounds.minY
for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() {
var x: CGFloat = bounds.minX
let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0
for item: RowItem in row {
subviews[item.index].place(
at: CGPoint(x: x, y: y),
anchor: .topLeading,
proposal: ProposedViewSize(item.size)
)
x += item.size.width + horizontalSpacing
}
y += rowHeight
if rowIndex < rows.count - 1 {
y += verticalSpacing
}
}
}
// MARK: - Private helpers
/// A single subview's natural (ideal) size and its index into `subviews`.
private struct RowItem {
let index: Int
let size: CGSize
}
/// Resolves the available width from the container proposal.
///
/// Falls back to `FlowLayout.fallbackMaxWidth` when the proposed width is
/// `nil`, zero, or infinite so the layout algorithm always has a finite bound
/// to wrap against.
private func resolvedWidth(from proposal: ProposedViewSize) -> CGFloat {
guard let width: CGFloat = proposal.width,
width > 0,
width.isFinite else {
return FlowLayout.fallbackMaxWidth
}
return width
}
/// Partitions all subviews into rows given the available width.
///
/// Each subview is measured at its ideal size (`unspecified` proposal).
/// Subviews are appended to the current row while they fit; when adding the
/// next subview would overflow `availableWidth`, a new row is started.
///
/// A subview wider than `availableWidth` is placed alone on its own row so
/// it is always visible rather than silently clipped.
private func computeRows(subviews: Subviews, availableWidth: CGFloat) -> [[RowItem]] {
var rows: [[RowItem]] = []
var currentRow: [RowItem] = []
var currentRowWidth: CGFloat = 0
for index: Int in subviews.indices {
let size: CGSize = subviews[index].sizeThatFits(.unspecified)
let neededWidth: CGFloat = currentRow.isEmpty
? size.width
: currentRowWidth + horizontalSpacing + size.width
if !currentRow.isEmpty, neededWidth > availableWidth {
// The subview doesn't fit — commit the current row and start fresh.
rows.append(currentRow)
currentRow = [RowItem(index: index, size: size)]
currentRowWidth = size.width
} else {
// Fits in the current row (or is the first item on a new row).
currentRow.append(RowItem(index: index, size: size))
currentRowWidth = neededWidth
}
}
if !currentRow.isEmpty {
rows.append(currentRow)
}
return rows
}
/// Computes the bounding size of the finished row layout.
///
/// Width is the widest row; height is the sum of all row heights plus
/// inter-row spacing. Returns `.zero` for an empty subview list.
private func totalSize(rows: [[RowItem]]) -> CGSize {
guard !rows.isEmpty else { return .zero }
var totalHeight: CGFloat = 0
var maxWidth: CGFloat = 0
for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() {
let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0
let rowWidth: CGFloat = row.reduce(0) { acc, item in
acc + item.size.width
} + CGFloat(max(row.count - 1, 0)) * horizontalSpacing
totalHeight += rowHeight
if rowIndex < rows.count - 1 {
totalHeight += verticalSpacing
}
maxWidth = max(maxWidth, rowWidth)
}
return CGSize(width: maxWidth, height: totalHeight)
}
}