// 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.importCottonKitimportSwiftUI/// Grid or list — and, for a grid, how many across.publicenumPaperLayout: 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.publicvar columns: Int {switchself {case .grid(let columns): return max(1, columns)case .list: return1 } }}// MARK: - The widthextensionPaperLayout {/// 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.publicstaticfunc 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.publicfunc flowing(atWidth width: CGFloat, in scale: ThemeScale) -> PaperLayout {guardcase .grid(let asked) = selfelse { returnself }let across = max(1, asked)guard width > 0else { 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.5return .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.publicfunc trailingGap(atWidth width: CGFloat, spacing: CGFloat, count: Int, in scale: ThemeScale) -> CGFloat {guardcase .grid = self, width > 0, count > 0else { return0 }guardcase .grid(let columns) = flowing(atWidth: width, in: scale) else { return0 }let across = max(1, columns)guard count < across else { return0 }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.publicstructPaperTrailingGap: PreferenceKey {publicstaticlet defaultValue: CGFloat = 0publicstaticfunc reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }}// MARK: - The enginepublicstructPaperCollection<Item: Identifiable, Cell: View>: View { @Environment(\.theme) privatevar theme/// The caller's gap, or the theme's.privatevar gap: CGFloat { spacing ?? theme.scale.spacing }privatelet items: [Item]privatelet layout: PaperLayoutprivatelet spacing: CGFloat?privatelet opens: ((Item) -> Route?)?privatelet cell: (Item, PaperLayout) -> Cell/// The host's keyboard selection, present in a Mac list column only. @Environment(\.cottonListKeyboard) privatevar keyboard/// This collection's width, measured, so the grid re-flows by it. @State privatevar width: CGFloat = 0/// This collection's place in the keyboard's order. @State privatevar 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.publicinit( _ items: [Item], layout: PaperLayout, spacing: CGFloat? = nil, opens: ((Item) -> Route?)? = nil, @ViewBuilder cell: @escaping (Item, PaperLayout) -> Cell ) {self.items = itemsself.layout = layoutself.spacing = spacingself.opens = opensself.cell = cell }publicvar body: someView {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 inif 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.privatevar 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 privatefunc placed(_ item: Item, _ layout: PaperLayout) -> someView {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.privatestructKeyboardSelectionMark: ViewModifier {let route: Route? @Environment(\.cottonListKeyboard) privatevar keyboardfunc body(content: Content) -> someView { 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.privatestructKeyboardSegment: ViewModifier {let keyboard: ListKeyboard?let segment: UUIDlet entries: [ListKeyboard.Entry]func body(content: Content) -> someView {// 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.iflet 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.publicstructPaperSection<Trailing: View>: View { @Environment(\.theme) privatevar themeprivatelet title: Stringprivatelet count: String?privatelet trailing: Trailingpublicinit( title: String, count: String? = nil, @ViewBuilder trailing: () -> Trailing = { EmptyView() } ) {self.title = titleself.count = countself.trailing = trailing() }publicvar body: someView { HStack(alignment: .center, spacing: PaperCollectionKnobs.paperSectionGap) { HStack(spacing: PaperCollectionKnobs.paperSectionTitleGap) { trailingText(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)iflet 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`).enumPaperCollectionKnobs {staticlet paperCollectionFlowBreak1: CGFloat = 420staticlet paperCollectionFlowBreak2: CGFloat = 640staticlet paperCollectionFlowBreak3: CGFloat = 960staticlet paperCollectionFlowBreak4: CGFloat = 1280staticlet paperSectionGap: CGFloat = 12staticlet paperSectionHorizontalInset: CGFloat = 2staticlet paperSectionTitleGap: CGFloat = 10}