Cotton code
272 lines · 13.6 KB · SwiftRaw
// A scroll view's column is exactly as wide as the scroll view.//// **A scroll view whose content is ONE SIXTH OF A POINT wider than its own// bounds is a HORIZONTALLY scrollable one.** UIKit does not care how small the// excess is: past it the pan recogniser accepts sideways travel and the whole// page rubber-bands left, right and diagonally under the finger and springs// back on release. That is what the owner reported on Home in TestFlight 145 —// "if you drag it to the right the whole content keeps moving around instead of// only scrolling vertically".//// Measured on the simulator (iPhone 16, 402pt wide, the Home column):////   | Dynamic Type | scroll view | column      | pans sideways |//   |--------------|-------------|-------------|---------------|//   | extraSmall   | 402.000     | 402.000     | no            |//   | small        | 402.000     | 402.000     | no            |//   | medium       | 402.000     | **402.167** | YES           |//   | large        | 402.000     | 402.000     | no            |//   | extraLarge   | 402.000     | **402.167** | YES           |//// **`.frame(maxWidth: .infinity)` is not a width — it is a permission to// grow.** A flexible frame reports AT LEAST its child's width, so a column that// ends with one says "as wide as the scroll view, or wider if something in me// is". And something in a column of text eventually is: a wrapping paragraph's// measured width is rounded UP to the display grid (a third of a point on a 3x// screen), and at the Dynamic Type sizes where the scaled font puts a line a// hair over the column it was proposed, that rounding carries the whole column// past. Nothing is visibly clipped and nothing looks wrong — the page just// starts sliding sideways.//// So a scroll column states what its width IS rather than what it may grow to.// Spelled ONCE, here — the rule is in Cotton note "The phone and Mac app — how a screen is built" under// "Scrolling" and held by `Tests/CottonUITests/Scaffold/ScrollingSweepTests.swift`.//// **IT IS A `Layout`, AND `containerRelativeFrame(.horizontal)` IS WHAT IT// STOPPED BEING.** That modifier states the same width by ASKING THE CONTAINER// for it, and on the Mac the container's answer is not independent of the// answer: a column's screen is hosted so that the scroll view's reported width// includes what is laid out in it, which closes a cycle —////     the scroll column's width  ←  the container's (the scroll view's) width//     the scroll view's width    ←  the column laid out in it, plus the 15pt//                                   a legacy (space-taking) scroller occupies//// — and SwiftUI resolves a cycle from the PREVIOUS pass, so each pass came out// exactly 15 points wider than the last and it never settled. Measured on the// built Mac app over `/todos` in an 1831pt window, instrumenting the modifier's// own closure: `1590, 1590, 1590, 1590, 1605, 1620, 1635, …` and still climbing// past 9600 ten seconds later — 539 layout passes, 95 % of a core, the list// column's paper marching out of view on both sides, and RenderBox refusing// textures past Metal's 16384px cap. The owner's report of 2026-09-21 ("all// contents are moving to the left, out of view … impossible to get to// Settings") is that. The phone never saw it: a phone's scroll view is hosted// by a rigid window, so the container's answer is a constant and the first pass// settles. `Boot/HomeSidebar.swift` had already met the Mac half of this and// written the modifier off for its own column.//// A `Layout` is handed the PROPOSAL rather than asking for a container, and the// proposal inside a vertical scroll view is the scroll view's own width. So the// rule is the same rule — "the scroll view's width, never a fraction more" —// with nothing to ask and nothing to close a cycle with. `Paper/Paper.swift`// chose a layout over a `GeometryReader` for the same reason, in the same// words.//// **THE CONTENT IS ASKED ONE QUESTION A PASS.** This layout used to ask its// content three: its width with nothing proposed (to compute a fallback width// that a proposal always overrides), its height at the column's width, and its// size again at the column's width AND the height just answered, to place it.// A plain stack answers all three the same way. A LAZY stack does not: it// answers from an estimate of the rows it has not drawn, built from the rows// it has drawn at the proposal it was given — so three proposals a pass are// three estimates, each pass reports a different height, a different height// re-lays the scroll view, and the next pass starts over. On the large seed// that never settled: the app sat at 100 % of a core with an empty screen// tree, the main thread inside this layout's `sizeThatFits`/`placeSubviews`// and `LazySubviewPlacements` (ws-mini-walk2, 5 Oct, iOS 26.5: on Home at// first launch, and after six quick flings down Calendar; samples// `RJ5/0x-home-HANG-main-thread-sample.txt`,// `RJ5/2x-calendar-06-HANG-main-thread-sample.txt`). So the content is// measured only at the proposal it is placed at — the column's width and the// height the scroll view proposed — and its own width is asked only when there// is no width to state. Guard: `ScrollColumnProposalTests`.import CottonKitimport SwiftUI/// The column's width, stated: whatever it is proposed, never what its content/// would like.////// The arithmetic is `stated(proposal:contentWidth:)`, a static function, so it/// can be asserted without a layout pass (`ScrollColumnTests`).struct ScrollColumnLayout: Layout {    /// Where the content sits in the column it is given — the same parameter    /// `.frame(maxWidth: .infinity, alignment:)` used to carry.    var alignment: Alignment = .leading    /// A proposed dimension, or nil when there is nothing usable in it.    ///    /// **`.infinity` IS NOT A WIDTH.** `ProposedViewSize.infinity` carries a    /// non-finite number rather than a nil, and a layout that answers with one    /// returns an infinite size — which is how a subview ends up placed at    /// `x = inf` and every sibling after it at zero width. A non-finite    /// proposal is "you decide", the same as no proposal at all.    static func usable(_ dimension: CGFloat?) -> CGFloat? {        guard let dimension, dimension.isFinite else { return nil }        return dimension    }    /// **The width a scroll column states.** The proposal when there is one —    /// that is the scroll view's own width — and the content's own width only    /// when nobody proposed anything, which inside a scroll view never happens.    ///    /// Never `max(proposal, contentWidth)`: that is the flexible frame this    /// rule replaced, and a column a fraction wider than its scroll view is a    /// page that pans sideways.    ///    /// `contentWidth` is asked only when there is no proposal: measuring a    /// lazy stack at a proposal it is never placed at is what kept the layout    /// from settling (the note at the top of this file).    static func stated(proposal: CGFloat?, contentWidth: () -> CGFloat) -> CGFloat {        max(0, usable(proposal) ?? contentWidth())    }    /// The one proposal the content is measured and placed at: the column's    /// width and the height the column itself was proposed (none, inside a    /// vertical scroll view).    static func offered(width: CGFloat, proposal: ProposedViewSize) -> ProposedViewSize {        ProposedViewSize(width: width, height: usable(proposal.height))    }    /// The proposal the content was last measured at. Placing passes on a    /// proposal of its own — often the height this column ANSWERED, not the    /// none it was asked at — so the content is placed at the measured one.    struct Measured {        var inner: ProposedViewSize?    }    func makeCache(subviews: Subviews) -> Measured { Measured() }    func sizeThatFits(        proposal: ProposedViewSize, subviews: Subviews, cache: inout Measured    ) -> CGSize {        let width = Self.stated(proposal: proposal.width) {            subviews.map { $0.sizeThatFits(.unspecified).width }.max() ?? 0        }        let inner = Self.offered(width: width, proposal: proposal)        cache.inner = inner        let height = subviews.map { $0.sizeThatFits(inner).height }.max() ?? 0        return CGSize(width: width, height: height)    }    func placeSubviews(        in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Measured    ) {        // The column IS the bounds' width, so the content is proposed the        // whole of it — at the SAME proposal it was measured at, never the        // bounds' height, which for a lazy stack is a second question with a        // second answer — and placed by the caller's alignment. A subview that        // answers something narrower sits where the alignment puts it; one        // that answers something wider is clipped by the scroll view rather        // than allowed to widen it. A leading column asks nothing more.        let offered = cache.inner.flatMap { $0.width == bounds.width ? $0 : nil }            ?? Self.offered(width: bounds.width, proposal: proposal)        let lead = Self.lead(alignment)        for subview in subviews {            let x = lead == 0 ? bounds.minX : bounds.minX + (bounds.width - subview.sizeThatFits(offered).width) * lead            subview.place(at: CGPoint(x: x, y: bounds.minY), anchor: .topLeading, proposal: offered)        }    }    /// How far along the leftover width the content starts — 0 leading, 0.5    /// centred, 1 trailing. Anything else is leading, because a column has no    /// use for a baseline or a first-text alignment.    static func lead(_ alignment: Alignment) -> CGFloat {        switch alignment.horizontal {        case .center: return 0.5        case .trailing: return 1        default: return 0        }    }}extension View {    /// The width rule for a vertical scroll view's content column: the scroll    /// view's own width, never a fraction more.    ///    /// Write it where `.frame(maxWidth: .infinity, alignment:)` used to close a    /// scroller's column — it carries the same alignment and leaves no room for    /// the sideways pan that a flexible frame allows.    public func cottonScrollColumn(alignment: Alignment = .leading) -> some View {        ScrollColumnLayout(alignment: alignment) { self }    }}// MARK: - The page column (SEV 1, 5 Oct 23:15Z; architect 2335)// A custom Layout between a scroll view and a LAZY stack re-asks the lazy// stack for its size, and a lazy stack answers from an estimate that moves as// rows are drawn — so a pass can fail to settle. That is how a small// database's Home froze (the sample: `ScrollColumnLayout.sizeThatFits`, its// height question, the column's width with no height, over the board's lazy// grid). So every paper page's column — whose content is lazy — states its// width by the system's own rule on the phone, and nothing of ours measures// the lazy stack at all. `ScrollColumnLayout` stays only for content that is// not lazy (`ScrollColumnPlacementTests` fails if a lazy stack is under it).//// The Mac keeps the Layout: there `containerRelativeFrame` closed a width// cycle with a legacy scroller (+15 pt a pass, `ScrollingSweepTests` §4), and// the Mac has no lazy board under it today.extension View {    /// A paper page's column inside its vertical scroll view: the scroll    /// view's width, the content's own height, and the tripwire.    func pageColumn(screen: String) -> some View {        #if os(iOS)        containerRelativeFrame(.horizontal, alignment: .leading)            .modifier(ColumnTripwire(screen: screen))        #else        cottonScrollColumn()            .modifier(ColumnTripwire(screen: screen))        #endif    }}/// BAND-AID — a tripwire, in every build, for a layout that does not settle./// The fault it watches for is a column whose height is answered differently/// pass after pass. A locked phone is worse than a column a few points wrong/// for a second, so past `limit` differing heights within one second the/// column keeps its last height for that second, and says so — one line to the/// log and one report to Feedback, with the screen's name. Never silent.@MainActor final class ColumnStorm {    /// How many differing answers one second may hold.    static let limit = 20    private var since = Date.distantPast    private var last: CGFloat?    private var differing = 0    /// Hears one height; true when it makes the storm.    func heard(_ height: CGFloat, at now: Date) -> Bool {        if now.timeIntervalSince(since) > 1 {            since = now            differing = 0        }        if height != last {            last = height            differing += 1        }        return differing > Self.limit    }}struct ColumnTripwire: ViewModifier {    let screen: String    @State private var storm = ColumnStorm()    @State private var held: CGFloat?    func body(content: Content) -> some View {        content            .frame(height: held, alignment: .top)            .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in                guard held == nil, storm.heard(height, at: Date()) else { return }                held = height                let line = "The page column of \(screen) did not settle: over \(ColumnStorm.limit) heights in a second. Held at \(Int(height)) pt for a second."                Log.warn(line)                Reporting.report(Report(kind: .layoutStorm, message: line, context: ["screen": screen]))                Task { @MainActor in                    try? await Task.sleep(for: .seconds(1))                    held = nil                }            }    }}