Cotton code
436 lines · 21.6 KB · SwiftRaw
// The scaffold every rebuilt screen stands on.//// The owner's second rule: **the background is never the metaphor; the pieces of// information are.** 80–90 % of a screen is quiet plaster ground and 10–20 % is// the objects — the shell paints the ground once, and this page supplies// its name and its objects.//// THE PARTS, and why each is where it is:////   • the GROUND belongs to the shell, visible through this page;//   • the NAME stands in the head row, left, in the display serif one size//     down (`head_title_size`), with the screen's circles at the row's right//     (fan3 part 7, owner 15 Oct: the separate large-title line went); an//     optional typewriter line scrolls under the row. A detail screen passes no name at all://     the object IS the title, and the reference pictures show it that way.//     Either one starts `theme.scale.navRowAir` under the nav circles//     (`pageClearance`), not a bar's clearance under them: the pictures have//     no empty band between the circles and the page — a bar screen's 75pt//     clearance left one ~50pt deep on every paper screen;//   • the two CONTROLS float as circles, back at the top left and the screen's//     own action at the top right, over the wash rather than in a bar. **The//     back circle takes no closure.** A screen never declares what back does —//     `NavigationTests.testNoScreenDeclaresItsOwnBack` is the guard, and the//     reason is that a screen that answers back has answered it for every route//     that ever pushes it. Back is `\.dismiss`, exactly as `ScreenBar`'s is, and//     a screen that is the bottom of its own stack passes `showsBack: false`.//     The ONE exception is the one `ScreenBar` and `ScreenPage` keep: an editor//     that must save before it leaves passes `onBack`, and does its own dismiss;//   • the WASH is solid only to the safe area by default. A screen whose//     controls row carries more than two circles — a conversation's print and//     name — passes `washDepth`, so what scrolls up passes UNDER that header//     rather than through it;//   • the ASIDE sits on the name's own line, at its right — for a control//     that belongs to the list under the name and not to the screen's chrome.//// It is NOT a `ScreenBar` screen: there is no bar, no hairline and no collapsing// title. There is a wash, for the reason Home has one — without it the first// object slides up behind the clock unmasked.import CottonFacesimport SwiftUIpublic struct PaperScreen<Content: View, Trailing: View, Aside: View>: View {    @Environment(\.theme) private var theme    private let clearsFan: Bool    @Environment(\.fanCover) private var fanCover    private let title: String?    private let subtitle: String?    private let showsBack: Bool    /// A record's page (fan3 part 10): no chevron; its own title stands in    /// the head row (the content's first line, beside the circles) and an X    /// at the row's right closes it one level, as does a pull down past the    /// page's top.    private let closes: Bool    private let onBack: (() -> Void)?    private let washDepth: CGFloat    /// Where this screen's page OPENS, and where it stays as the page grows.    /// `nil` — the default — is the scroll view's own answer, the top.    ///    /// It is a parameter rather than a `.defaultScrollAnchor` the screen writes    /// outside the scaffold, because that modifier sets an ENVIRONMENT value:    /// written outside, it reaches the sheets and covers the screen presents as    /// well, and a details sheet that opens at its bottom is nobody's idea of a    /// chat. Here it lands on this scaffold's one scroll view and nothing else.    private let scrollAnchor: UnitPoint?    private let place: PagePlace?    /// A value whose change brings the page back to its top — a list's search    /// words, so a search's answer opens at the top, never at the place the    /// whole list was scrolled to.    private let topOn: AnyHashable?    private let trailing: Trailing    /// The circles that give way first when the head row is short — each    /// one's act is reached another way (the tray, the search slip) — so the    /// name never shrinks (`HeadRow`).    private let yielding: AnyView?    private let aside: Aside    private let content: Content    private let faceGround: FaceGround?    @Environment(\.cottonHaptics) private var haptics    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    /// On a page surface the way back is the X (`TileBackCircle`) — unless    /// this screen was presented from inside the page (a sheet), whose own    /// dismiss is its Back.    @Environment(\.tileBack) private var tileBack    /// The width the head row's circles take at its right.    @State private var headTrailing: CGFloat = 0    /// The yielding circles gave way: the row was too short for them.    @State private var gaveWay = false    /// How much taller the head row stands than its circles: a long title    /// wraps to a second line, and the page starts under it.    @State private var headExtra: CGFloat = 0    @Environment(\.isPresented) private var isPresented    /// A column's root has nothing beneath it, so it wears no back — the rule    /// `ScreenBar` already keeps, read from the same environment key the Mac's    /// host sets.    @Environment(\.cottonAtColumnRoot) private var atColumnRoot    @Environment(\.cottonTopInset) private var topInset    @Environment(\.cottonListKeyboard) private var keyboard    @Environment(\.accessibilityReduceMotion) private var reduceMotion    /// The projects the content is narrowed to — a row of caps under the title    /// while there are any (Mac redesign spec §4). Empty on the phone.    @Environment(\.cottonProjectScope) private var scope    public init<Yielding: View>(        title: String? = nil,        clearsFan: Bool = false,        faceGround: FaceGround? = nil,        subtitle: String? = nil,        showsBack: Bool = true,        closes: Bool = false,        onBack: (() -> Void)? = nil,        washDepth: CGFloat = 0,        scrollAnchor: UnitPoint? = nil,        place: PagePlace? = nil,        topOn: AnyHashable? = nil,        @ViewBuilder yielding: () -> Yielding = { EmptyView() },        @ViewBuilder trailing: () -> Trailing = { EmptyView() },        @ViewBuilder aside: () -> Aside = { EmptyView() },        @ViewBuilder content: () -> Content    ) {        self.clearsFan = clearsFan        self.faceGround = faceGround        self.title = title        self.subtitle = subtitle        self.showsBack = showsBack        self.closes = closes        self.onBack = onBack        self.washDepth = washDepth        self.scrollAnchor = scrollAnchor        self.place = place        self.topOn = topOn        self.trailing = trailing()        self.yielding = Yielding.self == EmptyView.self ? nil : AnyView(yielding())        self.aside = aside()        self.content = content()    }    /// The page's top, where `topOn` brings it.    static var top: String { "paper-screen-top" }    /// How far a record's page has scrolled under its head row, up to the    /// row's foot: its wash grows with it (`RecordTopWash`).    @State private var underRow = UnderRow()    public var body: some View {        ZStack(alignment: .top) {            ScrollViewReader { proxy in                ScrollView {                    VStack(alignment: .leading, spacing: 0) {                        Color.clear.frame(height: Self.contentTop(                            scale: theme.scale, topInset: topInset, controls: hasControls, closes: closes) + headExtra)                            .id(Self.top)                        VStack(alignment: .leading, spacing: PaperScreenKnobs.paperScreenSectionGap) {                            if subtitle != nil || Aside.self != EmptyView.self {                                heading.cottonContentMargin()                            }                            if !scope.isEmpty {                                ScopeChipRow(chips: scope).cottonContentMargin()                            }                            // THE GUTTER IS THE SCAFFOLD'S, ALWAYS. There used                            // to be a `marginsContent: false` here, for the one                            // caller that wanted its content to pay the side                            // margin itself (`ScreenPage`). That made the                            // gutter an OPT-IN, and the only two things that                            // ever opted in were the record row (off its own                            // row margin) and a block that remembered                            // to write `.cottonContentMargin()`. The moment a                            // screen drew a SLIP instead of a row — which                            // `/projects/[slug]/{journal,notes,…}` began doing                            // in phase 29 — the margin was nobody's, and the                            // slips ran to the glass while the name above them                            // sat at 29pt. Two reports on 2026-09-21 are the                            // receipt.                            //                            // So there is no flag: every paper screen's content                            // is margined here. A screen that wants                            // something wider than the column is the case to                            // design for when one appears — not a page-wide                            // switch that silently takes the margin off                            // everything. Guard: `PaperScreenMarginTests`.                            content.cottonContentMargin()                                .environment(\.headRowTrailing, closes ? headTrailing : 0)                                .environment(\.headCirclesGaveWay, gaveWay)                            Color.clear.frame(height: PaperScreenKnobs.paperScreenBottomClearance)                        }                    }                    // The column is the SCROLL VIEW'S width, not "at least" it.                    // Every paper screen scrolls in this one column, so the                    // sideways pan the owner reported on Home (TestFlight 145)                    // was here too: a wrapping paragraph's measured width rounds                    // up past the column it was proposed, the content comes out                    // a sixth of a point wider than the scroller, and the whole                    // page rubber-bands left, right and diagonally under the                    // finger. `Chrome/ScrollColumn.swift` has the measurements.                    .pageColumn(screen: title ?? "a paper page")                }                .defaultScrollAnchor(scrollAnchor)                // A record's page pulled down past its top closes it.                .onScrollGeometryChange(for: Bool.self) { geometry in                    closes && geometry.contentOffset.y + geometry.contentInsets.top < -PaperScreenKnobs.paperScreenPullToClose                } action: { _, pulled in                    if pulled { close() }                }                // Read only to the head row's foot, so a long scroll writes it                // no more once the row stands on paper.                .onScrollGeometryChange(for: CGFloat.self) { geometry in                    guard closes else { return 0 }                    let span = theme.scale.headRowBottom(topInset: 0) - theme.scale.navRowTop                    return min(max(0, geometry.contentOffset.y + geometry.contentInsets.top), span).rounded()                } action: { _, scrolled in                    underRow.scrolled = scrolled                }                .modifier(KeptPlace(place: place))                // The object a keyboard selected in a list column comes into                // view (`Chrome/ListKeyboard.swift`). Nil on the phone, so                // this never fires there.                .onChange(of: topOn) { _, _ in proxy.scrollTo(Self.top, anchor: .top) }                .onChange(of: keyboard?.selectedAnchor) { _, anchor in                    guard let anchor else { return }                    withAnimation(reduceMotion ? nil : .easeOut(                        duration: Double(PaperScreenKnobs.paperScreenScrollDurationSeconds))) {                        proxy.scrollTo(anchor)                    }                }            }            // These pages keep acts outside the rail's viewport, even before            // scrolling. A content inset alone still draws under the fan.            .padding(.bottom, clearsFan ? (fanCover?.scrollClearance ?? 0) : 0)            .ignoresSafeArea(edges: .top)            // The wash is solid behind the Back and menu circles, so nothing            // scrolling under them is read through them, and is gone by the            // line the page's first words start on (the wash's band is drawn            // from the safe-area top, so the row's air is part of its depth).            // The fade ENDS where the first line starts: a wash solid to the            // content's top faded its first 12 pt, so a list's hint, its            // filter line or its first entry read half washed out under the            // head (walker 604bcce6: Goals, Thoughts, Journal).            if faceGround == nil, closes {                // A record's title stands IN the head row, so at rest the wash                // stops under the status bar; scrolled, it grows with the page                // to the row's foot, and nothing reads under the tray and                // Close (walker292: a meeting's summary ran under them with no                // paper behind).                RecordTopWash(underRow: underRow, rest: theme.scale.navRowTop, fade: PaperScreenKnobs.paperScreenWashFade)                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)            } else if faceGround == nil {                ScreenTopWash(                    solidBelowInset: max(washDepth, hasControls                        ? theme.scale.pageClearance(topInset: 0) + headExtra - PaperScreenKnobs.paperScreenWashFade                        : theme.scale.navRowTop),                    fade: PaperScreenKnobs.paperScreenWashFade)                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)            }            if hasControls { controls }        }        .cottonPageGround(.groundMuted)        .cottonPageTexture(.plaster)        .background {            if let faceGround { FaceGroundSurface(faceGround).ignoresSafeArea() }        }        .preference(key: DeckGroundPreference.self, value: .known(faceGround))        .preference(key: PageTitleKey.self, value: title)    }    /// Whether the head row stands at the top: a Back, the screen's own    /// circles, or its name.    private var hasControls: Bool {        (showsBack && !atColumnRoot) || Trailing.self != EmptyView.self || yielding != nil || title != nil || closes    }    /// Where a page's first thing starts, from the physical top of its    /// scroll: under the head row — or, on a record's page, IN it: the    /// record's title is the row's first line. Nothing stands between the    /// status bar and the head row but the theme's head padding.    static func contentTop(scale: ThemeScale, topInset: CGFloat, controls: Bool, closes: Bool) -> CGFloat {        if closes { return headRowTop(scale: scale, topInset: topInset) }        return controls ? scale.pageClearance(topInset: topInset) : scale.barePageClearance(topInset: topInset)    }    /// The head row's top: the safe area and the theme's head padding.    static func headRowTop(scale: ThemeScale, topInset: CGFloat) -> CGFloat {        topInset + scale.navRowTop    }    /// One level back: the zoom's own step, a column's Back, or dismiss.    private func close() {        haptics.select()        if let tileBack, !isPresented { tileBack.close() }        else if let onBack { onBack() } else { CardClosing.close(closeCard, else: dismiss) }    }    private var heading: some View {        HStack(alignment: .firstTextBaseline, spacing: PaperScreenKnobs.paperScreenHeadingGap) {            VStack(alignment: .leading, spacing: PaperScreenKnobs.paperScreenHeadingStackGap) {                if let subtitle {                    Text(subtitle)                        .font(theme.type.body(theme.scale.metaSize))                        .foregroundStyle(theme.colors.inkSecondary.color)                }            }            Spacer(minLength: PaperScreenKnobs.paperScreenHeadingAsideMinGap)            aside        }    }    /// On a page surface (a fan tile's page, the root's, a layer) every page    /// closes with the X at its head row's right, its title at the left, as a    /// record does (lane inplace, 16 Oct 2026): no chevron.    private var inPlace: Bool { tileBack != nil && !isPresented }    private var controls: some View {        // One head rule (walker pass 4, 16 Oct 2026): the name never shrinks        // and never drops under the circles — the circles give way. Beside        // them on one row at its full size; when the row is short the        // yielding circles go first (their acts stay in reach); a name longer        // than the row then wraps to a second line beside the circles, still        // at its full size — never an ellipsis.        ViewThatFits(in: .horizontal) {            if let yielding {                headRow(title.map { headTitle($0).lineLimit(1).fixedSize() }, yielding: yielding)                    .onAppear { gaveWay = false }            }            headRow(title.map { headTitle($0).lineLimit(1).fixedSize() }, yielding: nil)                .onAppear { gaveWay = yielding != nil }            headRow(title.map { headTitle($0).lineLimit(2).fixedSize(horizontal: false, vertical: true) }, yielding: nil)                .onAppear { gaveWay = yielding != nil }        }        .onGeometryChange(for: CGFloat.self, of: { $0.size.height }) { height in            headExtra = max(0, height - ScreenBarKnobs.chromeNavCircleTarget)        }        .cottonContentMargin()        .padding(.top, theme.scale.navRowTop)    }    private func headRow(_ name: (some View)?, yielding: AnyView?) -> some View {        HStack(alignment: .center, spacing: PaperScreenKnobs.paperScreenHeadingGap) {            backCircle            name            Spacer(minLength: 0)            trailingCircles(yielding: yielding)        }    }    @ViewBuilder private var backCircle: some View {        if showsBack, !atColumnRoot, !closes, !inPlace {            NavCircle(symbol: "chevron.left", label: CottonStrings.back) {                haptics.select()                if let onBack { onBack() } else { CardClosing.close(closeCard, else: dismiss) }            }        }    }    private func headTitle(_ title: String) -> some View {        Text(title)            .font(theme.type.display(theme.scale[.headTitleSize]))            .foregroundStyle(theme.colors.ink.color)            .accessibilityAddTraits(.isHeader)    }    private func trailingCircles(yielding: AnyView?) -> some View {        HStack(spacing: PaperScreenKnobs.paperScreenHeadingGap) {            yielding            trailing            // A record closes with an X, the row's last circle; a long            // press lists the stack (the zoom's card idiom).            if closes || inPlace, showsBack, !atColumnRoot {                if let tileBack, !isPresented {                    TileBackCircle(back: tileBack)                } else {                    NavCircle(symbol: Glyph.symbol("x") ?? "xmark", label: CottonStrings.close) { close() }                        .accessibilityIdentifier("page-back")                }            }        }        .fixedSize()        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { headTrailing = $0 }    }}/// The sizes, counts and timings PaperScreen draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum PaperScreenKnobs {    static let paperScreenBottomClearance: CGFloat = 90    static let paperScreenHeadingAsideMinGap: CGFloat = 8    static let paperScreenHeadingGap: CGFloat = 12    static let paperScreenHeadingStackGap: CGFloat = 3    /// How far a record's page is pulled down past its top to close it.    static let paperScreenPullToClose: CGFloat = 90    static let paperScreenScrollDurationSeconds: CGFloat = 0.2    static let paperScreenSectionGap: CGFloat = 20    static let paperScreenWashFade: CGFloat = 12}/// The width the head row's circles take at its right, handed to a record's/// page so its title — the row's first line — stops short of them.private struct HeadRowTrailingKey: EnvironmentKey {    static let defaultValue: CGFloat = 0}extension EnvironmentValues {    var headRowTrailing: CGFloat {        get { self[HeadRowTrailingKey.self] }        set { self[HeadRowTrailingKey.self] = newValue }    }}extension EnvironmentValues {    /// The head row's yielding circles gave way (`PaperScreen.controls`): a    /// page that yields one puts its act back in the page — the search slip    /// for the magnifier.    @Entry var headCirclesGaveWay = false}/// How far a record's page has scrolled under its head row, in a box of its/// own: only the wash reads it, so a scroll redraws the wash and never the/// page.@MainActor@Observablefinal class UnderRow {    var scrolled: CGFloat = 0}/// A record page's top wash: solid to `rest` under the status bar at rest,/// growing with the scroll to the head row's foot.private struct RecordTopWash: View {    let underRow: UnderRow    let rest: CGFloat    let fade: CGFloat    var body: some View {        ScreenTopWash(solidBelowInset: rest + underRow.scrolled, fade: fade).accessibilityHidden(true)    }}