Branchwell

Jotley / app / Shared / Styling / FlowLayout.swift

1//
2// FlowLayout.swift
3// Jotley
4//
5// Wraps items into rows within the proposed width.
6//
7
8import SwiftUI
9
10// MARK: - Flow Layout
11
12struct FlowLayout: Layout {
13 var spacing: CGFloat = 8
14
15 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
16 let result = FlowResult(in: proposal.width ?? .infinity, subviews: subviews, spacing: spacing)
17 return result.size
18 }
19
20 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
21 let result = FlowResult(in: bounds.width, subviews: subviews, spacing: spacing)
22 for (index, element) in result.rows.enumerated() {
23 var x = bounds.minX
24 for (subviewIndex, subview) in zip(element.range, subviews[element.range]) {
25 let itemSize = result.sizes[subviewIndex]
26 // Center each item vertically within the row
27 let yOffset = bounds.minY + result.yOffsets[index] + (element.height - itemSize.height) / 2
28 subview.place(at: CGPoint(x: x, y: yOffset),
29 proposal: ProposedViewSize(itemSize))
30 x += itemSize.width + spacing
31 }
32 }
33 }
34
35 struct FlowResult {
36 var rows: [(range: Range<Int>, height: CGFloat)] = []
37 var yOffsets: [CGFloat] = []
38 var sizes: [CGSize] = []
39 var size: CGSize = .zero
40
41 init(in width: CGFloat, subviews: Subviews, spacing: CGFloat) {
42 var x: CGFloat = 0
43 var y: CGFloat = 0
44 var maxHeight: CGFloat = 0
45 var maxWidth: CGFloat = 0
46 var rangeStart = 0
47
48 for (index, subview) in subviews.enumerated() {
49 let idealSize = subview.sizeThatFits(.unspecified)
50 let size = idealSize.width > width
51 ? subview.sizeThatFits(ProposedViewSize(width: width, height: nil))
52 : idealSize
53 sizes.append(size)
54
55 if x + size.width > width && rangeStart < index {
56 rows.append((rangeStart..<index, maxHeight))
57 yOffsets.append(y)
58 y += maxHeight + spacing
59 x = 0
60 maxHeight = 0
61 rangeStart = index
62 }
63
64 x += size.width + spacing
65 maxWidth = max(maxWidth, x - spacing)
66 maxHeight = max(maxHeight, size.height)
67 }
68
69 if rangeStart < subviews.count {
70 rows.append((rangeStart..<subviews.count, maxHeight))
71 yOffsets.append(y)
72 y += maxHeight
73 }
74
75 self.size = CGSize(width: width.isFinite ? width : maxWidth, height: y)
76 }
77 }
78}