// The one list engine for objects, in the one layout a screen is given. // // The owner's rule (15 Oct 2026): **a list shows one layout, chosen by its // definition; the person never switches it.** So a screen hands its items to // `PaperCollection` with that layout and draws a cell for it; nothing on the // device remembers a layout, and no screen draws a toggle. // // THE CELL DECIDES HOW IT LOOKS, not this. A note in a grid is a two-up card and // in a list is a full-width row, and both are the same `Paper` — writing that // choice here would make the engine know about notes. // // WHAT IT REPLACED: `RecordList`, a screen-height `List` with its own // separators and swipes, retired in phase 20 — the last two row screens moved // here as `.list`. // A list of rows and a grid of objects both lay out in the page's own scroll // view, which is what this is. import CottonKit import SwiftUI /// Grid or list — and, for a grid, how many across. public enum PaperLayout: Equatable, Sendable { case grid(columns: Int) case list /// Columns across. A list is one; a grid is at least one, whatever it was /// asked for — a zero-column grid lays nothing out and reads as an empty /// screen. public var columns: Int { switch self { case .grid(let columns): return max(1, columns) case .list: return 1 } } } // MARK: - The width extension PaperLayout { /// The widths the grid re-flows at, in points of the COLLECTION's own /// width (inside the screen's margins), ascending. A phone's content /// column is under 420 on every model, so on the phone a grid is always /// what its screen asked for; a Mac column is a wider desk, and the desk /// keeps going. /// /// **The ladder used to stop at 640**, with "four is the widest a desk /// spreads" written into its test — which was true while a Mac list column /// was capped at a 720 reading width, because then EVERY Mac width landed /// in the top bucket. The Mac walk found what that costs: a 1000-point /// window and a 1460-point one drew the same four notes across, and /// widening the window bought nothing (finding 12). A collection column is /// uncapped now (`ColumnsLayout.columnWidth`), so the two upper rungs are /// reachable and the desk grows with the window. /// The worn theme's rungs: a layout is a value with no environment, so /// its caller hands it the scale it wears. public static func flowBreaks(in scale: ThemeScale) -> [CGFloat] { [ PaperCollectionKnobs.paperCollectionFlowBreak1, PaperCollectionKnobs.paperCollectionFlowBreak2, PaperCollectionKnobs.paperCollectionFlowBreak3, PaperCollectionKnobs.paperCollectionFlowBreak4, ] } /// The same grid at a width: what the screen asked for is the count at a /// phone's width, and a wider desk lays out proportionally more of the /// same objects — a two-up grid is two up to 420 points, three to 640, /// four to 960, five to 1280 and six beyond — so the objects keep their /// size instead of stretching. /// /// A width of zero is "not measured yet" and keeps the asked-for count, so /// the first frame on the phone is the frame it always drew. A list is a /// list at any width. public func flowing(atWidth width: CGFloat, in scale: ThemeScale) -> PaperLayout { guard case .grid(let asked) = self else { return self } let across = max(1, asked) guard width > 0 else { return .grid(columns: across) } // The asked-for count at the narrowest rung, and half as many again // per break passed. let bucket = 1 + Double(Self.flowBreaks(in: scale).filter { width > $0 }.count) * 0.5 return .grid(columns: max(1, Int((Double(across) * bucket).rounded()))) } /// **How much of the collection's width the objects did not reach.** /// /// A grid's columns are `.flexible()`, so they divide the WHOLE width /// however few objects there are: three people in a column wide enough for /// eight leave five empty columns of air to their right. Anything pinned /// to the collection's trailing edge — the A–Z rail is the one — then sits /// a long way from the last object and reads as detached from it (the Mac /// walk's re-shoot, walk-05-v2, where the rail was at x≈870 and the three /// cards ended at x≈390). /// /// This is that distance, so the rail can hug the objects instead. Zero /// whenever the answer is "the objects fill the row": a list, an unmeasured /// first frame, or at least as many objects as there are columns. /// /// The last OCCUPIED COLUMN's edge, not the last object's ink: a cell is /// centred in its column and the few points between the two are the grid's /// own gutter, which the rail should stand in rather than inside. public func trailingGap(atWidth width: CGFloat, spacing: CGFloat, count: Int, in scale: ThemeScale) -> CGFloat { guard case .grid = self, width > 0, count > 0 else { return 0 } guard case .grid(let columns) = flowing(atWidth: width, in: scale) else { return 0 } let across = max(1, columns) guard count < across else { return 0 } let columnWidth = (width - spacing * CGFloat(across - 1)) / CGFloat(across) let occupied = columnWidth * CGFloat(count) + spacing * CGFloat(count - 1) return max(0, width - occupied) } } // MARK: - What the objects left over /// The air to the right of the last object, published by the collection that /// measured it and read by whatever is pinned to the page's trailing edge. /// /// A preference rather than an environment value because it travels UP: the /// collection is the only thing that knows its own width, and the rail is /// drawn by the screen ABOVE it. `max` because a screen with two collections /// in it has one trailing edge, and the one with the most air is the one a /// rail beside them both would be furthest from. public struct PaperTrailingGap: PreferenceKey { public static let defaultValue: CGFloat = 0 public static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } } // MARK: - The engine public struct PaperCollection: View { @Environment(\.theme) private var theme /// The caller's gap, or the theme's. private var gap: CGFloat { spacing ?? theme.scale.spacing } private let items: [Item] private let layout: PaperLayout private let spacing: CGFloat? private let opens: ((Item) -> Route?)? private let cell: (Item, PaperLayout) -> Cell /// The host's keyboard selection, present in a Mac list column only. @Environment(\.cottonListKeyboard) private var keyboard /// This collection's width, measured, so the grid re-flows by it. @State private var width: CGFloat = 0 /// This collection's place in the keyboard's order. @State private var segment = UUID() /// `opens` names the route each object opens when it is pressed — the same /// route its cell pushes. It is what lets a keyboard move through the /// objects and open one; a collection that passes nothing is skipped by /// the keyboard and draws exactly as before. public init( _ items: [Item], layout: PaperLayout, spacing: CGFloat? = nil, opens: ((Item) -> Route?)? = nil, @ViewBuilder cell: @escaping (Item, PaperLayout) -> Cell ) { self.items = items self.layout = layout self.spacing = spacing self.opens = opens self.cell = cell } public var body: some View { let flowing = layout.flowing(atWidth: width, in: theme.scale) Group { switch flowing { case .grid(let columns): LazyVGrid( columns: Array( repeating: GridItem(.flexible(), spacing: gap, alignment: .top), count: max(1, columns) ), alignment: .leading, spacing: gap ) { ForEach(items) { item in placed(item, flowing) } } case .list: LazyVStack(alignment: .leading, spacing: gap) { ForEach(items) { item in placed(item, flowing) } } } } // The width is read with a geometry change rather than a // `GeometryReader` wrapped round the grid: a reader proposes its whole // container to what it holds and collapses a lazy grid's height inside // a scroll view. Reading it beside the grid costs one re-flow on the // first frame of a wide column and nothing on a narrow one. .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { measured in if measured != width { width = measured } } // What the objects left over on the right, for whatever the screen // above has pinned to its trailing edge (`PaperTrailingGap`). .preference( key: PaperTrailingGap.self, value: layout.trailingGap(atWidth: width, spacing: gap, count: items.count, in: theme.scale) ) .modifier(KeyboardSegment(keyboard: opens == nil ? nil : keyboard, segment: segment, entries: entries)) } /// The objects this collection hands the keyboard, in its own order. private var entries: [ListKeyboard.Entry] { guard keyboard != nil, let opens else { return [] } return items.compactMap { item in opens(item).map { ListKeyboard.Entry(route: $0, anchor: AnyHashable(item.id)) } } } @ViewBuilder private func placed(_ item: Item, _ layout: PaperLayout) -> some View { if keyboard != nil, let opens { cell(item, layout) .modifier(KeyboardSelectionMark(route: opens(item))) .id(AnyHashable(item.id)) } else { cell(item, layout) } } } /// The ring on the object the keyboard selected. Its own modifier so it reads /// the selection in its OWN body: a lazy grid builds its cells outside the /// collection's body, and a read there would not be observed. private struct KeyboardSelectionMark: ViewModifier { let route: Route? @Environment(\.cottonListKeyboard) private var keyboard func body(content: Content) -> some View { content.cottonKeyboardSelected(route != nil && keyboard?.selected == route) } } /// A collection's registration with the keyboard: its objects while it is on /// screen, and where its top is so the keyboard can order it among the others. private struct KeyboardSegment: ViewModifier { let keyboard: ListKeyboard? let segment: UUID let entries: [ListKeyboard.Entry] func body(content: Content) -> some View { // Branches on whether there IS a keyboard, which is fixed for the life // of the column — never on whether the objects have loaded yet, which // would rebuild the grid the moment they did. if let keyboard { content .onGeometryChange(for: CGFloat.self, of: { $0.frame(in: .global).minY }) { top in keyboard.place(segment, top: top) } .onAppear { keyboard.register(segment, entries: entries) } .onChange(of: entries) { _, now in keyboard.register(segment, entries: now) } .onDisappear { keyboard.unregister(segment) } } else { content } } } // MARK: - The heading over a run of objects /// A section over a run of objects: the name in the serif, a hairline that takes /// what is left, and the count handwritten on its far end. /// /// It is the todo board's `BoardHeading` generalised — the same lockup, without /// the cap, so every paper screen's sections are one design. public struct PaperSection: View { @Environment(\.theme) private var theme private let title: String private let count: String? private let trailing: Trailing public init( title: String, count: String? = nil, @ViewBuilder trailing: () -> Trailing = { EmptyView() } ) { self.title = title self.count = count self.trailing = trailing() } public var body: some View { HStack(alignment: .center, spacing: PaperCollectionKnobs.paperSectionGap) { HStack(spacing: PaperCollectionKnobs.paperSectionTitleGap) { trailing Text(title) .font(theme.type.title(theme.scale.sectionTitleSize)) .foregroundStyle(theme.colors.ink.color) .lineLimit(1) } .layoutPriority(1) .accessibilityAddTraits(.isHeader) // The rule takes what the name and the count leave, never the other // way round — a name is not cut for a hairline. Rectangle() .fill(theme.colors.hairline.color) .frame(height: theme.scale.hairline) .frame(maxWidth: .infinity) if let count { Text(count) .paperHand(theme.scale.handSize - 1) .lineLimit(1) } } .padding(.horizontal, PaperCollectionKnobs.paperSectionHorizontalInset) } } /// The sizes, counts and timings PaperCollection draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum PaperCollectionKnobs { static let paperCollectionFlowBreak1: CGFloat = 420 static let paperCollectionFlowBreak2: CGFloat = 640 static let paperCollectionFlowBreak3: CGFloat = 960 static let paperCollectionFlowBreak4: CGFloat = 1280 static let paperSectionGap: CGFloat = 12 static let paperSectionHorizontalInset: CGFloat = 2 static let paperSectionTitleGap: CGFloat = 10 }