~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
47 lines · 2.0 KB Raw History
import SwiftUI

struct ProfileLinksLayout: Layout {
    private let spacing: CGFloat = 8

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        let result = arrange(subviews: subviews, width: proposal.width)
        return result.size
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        let result = arrange(subviews: subviews, width: bounds.width)
        for (index, item) in result.items.enumerated() {
            subviews[index].place(
                at: CGPoint(x: bounds.minX + item.origin.x, y: bounds.minY + item.origin.y),
                anchor: .topLeading,
                proposal: ProposedViewSize(item.size)
            )
        }
    }

    private func arrange(subviews: Subviews, width: CGFloat?) -> (
        size: CGSize, items: [(origin: CGPoint, size: CGSize)]
    ) {
        let proposedWidth = width.flatMap { $0.isFinite ? max(0, $0) : nil }
        let availableWidth = proposedWidth ?? .greatestFiniteMagnitude
        var items: [(origin: CGPoint, size: CGSize)] = []
        var horizontalOffset: CGFloat = 0
        var verticalOffset: CGFloat = 0
        var rowHeight: CGFloat = 0
        var usedWidth: CGFloat = 0

        for subview in subviews {
            let size = subview.sizeThatFits(ProposedViewSize(width: proposedWidth, height: nil))
            if horizontalOffset > 0 && horizontalOffset + size.width > availableWidth {
                horizontalOffset = 0
                verticalOffset += rowHeight + spacing
                rowHeight = 0
            }
            items.append((CGPoint(x: horizontalOffset, y: verticalOffset), size))
            usedWidth = max(usedWidth, horizontalOffset + size.width)
            rowHeight = max(rowHeight, size.height)
            horizontalOffset += size.width + spacing
        }
        return (CGSize(width: proposedWidth ?? usedWidth, height: verticalOffset + rowHeight), items)
    }
}