Sources/OrgApp/FlowLayout.swift
46 lines · 1996 bytes
4 symbols in this file
1import SwiftUI
2
3/// Lays its subviews out in a row, starting a new row where the next one doesn't fit. A subview
4/// wider than the whole width gets the whole width.
5public struct FlowLayout: Layout {
6 public var spacing: CGFloat
7 public var lineSpacing: CGFloat
8
9 public init(spacing: CGFloat = 5, lineSpacing: CGFloat = 3) {
10 self.spacing = spacing
11 self.lineSpacing = lineSpacing
12 }
13
14 public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
15 let frames = place(subviews, width: proposal.width ?? .infinity)
16 let width = frames.map(\.maxX).max() ?? 0
17 return CGSize(width: proposal.width.map { min($0, width) } ?? width, height: frames.map(\.maxY).max() ?? 0)
18 }
19
20 public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
21 for (subview, frame) in zip(subviews, place(subviews, width: bounds.width)) {
22 subview.place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), proposal: ProposedViewSize(frame.size))
23 }
24 }
25
26 /// Each subview's frame, in rows from the top left.
27 private func place(_ subviews: Subviews, width: CGFloat) -> [CGRect] {
28 var frames: [CGRect] = []
29 var x: CGFloat = 0
30 var y: CGFloat = 0
31 var rowHeight: CGFloat = 0
32 for subview in subviews {
33 var size = subview.sizeThatFits(.unspecified)
34 if size.width > width { size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)) }
35 if x > 0, x + size.width > width {
36 x = 0
37 y += rowHeight + lineSpacing
38 rowHeight = 0
39 }
40 frames.append(CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: min(size.width, width), height: size.height)))
41 x += size.width + spacing
42 rowHeight = max(rowHeight, size.height)
43 }
44 return frames
45 }
46}