Cotton code
47 lines · 2.0 KB · SwiftRaw
import SwiftUI/// A row: tiles side by side that scroll sideways when they do not fit. Its/// tiles share the row's width `across` at a time, but never at less than/// the theme's minimum tile width (the `shelfTileMinW` scale key — a slip's/// own width) so a slip in a row never folds its words a letter a line/// (smsmac2's walk, shot 21: a todo's foot drawn a character per line on the/// person page).struct PaperRow<Item: Identifiable, Tile: View>: View {    @Environment(\.theme) private var theme    private let items: [Item]    private let across: Int    private let spacing: CGFloat    private let tile: (Item) -> Tile    /// The row's own width, measured beside it, as `PaperCollection` does.    @State private var width: CGFloat = 0    init(_ items: [Item], across: Int, spacing: CGFloat, @ViewBuilder tile: @escaping (Item) -> Tile) {        self.items = items        self.across = across        self.spacing = spacing        self.tile = tile    }    var body: some View {        let each = Self.tileWidth(row: width, across: across, spacing: spacing, minimum: theme.scale[.shelfTileMinW])        ScrollView(.horizontal, showsIndicators: false) {            HStack(alignment: .top, spacing: spacing) {                ForEach(items) { item in                    tile(item).frame(width: each, alignment: .topLeading)                }            }        }        .scrollBounceBehavior(.basedOnSize, axes: .horizontal)        .scrollClipDisabled()        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { measured in            if measured != width { width = measured }        }    }    /// What each tile is laid out at in a row `row` wide: its share of the    /// width, `across` at a time, and never less than `minimum`.    static func tileWidth(row: CGFloat, across: Int, spacing: CGFloat, minimum: CGFloat) -> CGFloat {        let count = CGFloat(max(1, across))        return max(minimum, (row - spacing * (count - 1)) / count)    }}