Cotton code
299 lines · 12.5 KB · SwiftRaw
// The pinned quiet bar every screen wears.//// THE BAR HAS NO GROUND. Ground circles and a centred title float over// full-bleed content, so a list visibly slides beneath them; what softens the// top edge is a wash of the page's own background fading to nothing, never a// filled bar and never a hairline.//// The title names the SURFACE you are on, not the tool. It is a heading and// never a control: the peer-surface dropdown that once hung off it went with the// calendar's move onto paper, where peers are a circle of their own.//// The LEADING circle has exactly ONE meaning: back. Two unrelated verbs never// share one control, and the drawer it used to open is repealed.import SwiftUI/// Content clearance above the first row on a `ScreenBar` screen. A screen pads/// its scroller by this; the bar itself is an overlay and takes no space.////// The scroller a screen puts this in IGNORES the top safe area/// (`.ignoresSafeArea(edges: .top)`), which is what makes a list visibly slide/// under the bar and gives the wash something to wash. **So this clearance is/// measured from the PHYSICAL top of the screen and has to carry the safe-area/// inset itself** — the phone's own `insets.top + SCREEN_BAR_CLEARANCE`.////// It once did not, on a written claim that "SwiftUI turns the ignored inset/// into a CONTENT inset on a scroll view, so this stays 75". It does not, and/// the arithmetic says what that cost: the bar is laid out at the safe-area top/// and is 44pt tall, so on a 59pt-inset phone its bottom edge is at 103pt while/// the first row began at 75pt. Every screen whose content followed the/// clearance closely — a project's page title, the Memory list's first entry,/// a helper paragraph — drew UNDER the back circle at rest. Four screenshots on/// 2026-09-10 (build 130), all of them the same 28pt.////// The inset arrives as `\.cottonTopInset`, measured once at the app root by/// `MeasuresTopInset` — `Chrome/ScreenFrame.swift` says why it cannot be/// measured here.public struct ScreenBarClearance: View {    @Environment(\.cottonTopInset) private var topInset    @Environment(\.theme) private var theme    public init() {}    /// The clearance, given the top inset and the worn scale. A function    /// rather than an expression so a test can state the rule without a screen.    public static func height(topInset: CGFloat, scale: ThemeScale) -> CGFloat {        topInset + ScreenBarKnobs.chromeScreenBarClearance    }    public var body: some View {        Color.clear.frame(height: ScreenBarClearance.height(topInset: topInset, scale: theme.scale))    }}public struct ScreenBar<Trailing: View>: View {    private let title: String?    private let titleSymbol: String?    private let subtitle: String?    private let onBack: (() -> Void)?    private let backSymbol: String    private let backLabel: String    private let trailing: Trailing    @Environment(\.cottonHaptics) private var haptics    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    /// On a fan tile's page, Back is the zoom's round chevron    /// (`TileBackCircle`) — unless this screen was presented from inside the    /// page (a sheet), whose own dismiss is its Back.    @Environment(\.tileBack) private var tileBack    @Environment(\.isPresented) private var isPresented    /// A column's root has nothing beneath it — see `controlRow`.    @Environment(\.cottonAtColumnRoot) private var atColumnRoot    @Environment(\.theme) private var theme    /// How wide the trailing controls turned out to be — read, not assumed,    /// because every screen passes its own. See `titleWidth`. Nil until    /// measured, which reads as one worn nav-circle target.    @State private var trailingWidth: CGFloat?    public init(        title: String? = nil,        titleSymbol: String? = nil,        subtitle: String? = nil,        backSymbol: String = "chevron.left",        backLabel: String? = nil,        onBack: (() -> Void)? = nil,        @ViewBuilder trailing: () -> Trailing    ) {        self.title = title        self.titleSymbol = titleSymbol        self.subtitle = subtitle        self.backSymbol = backSymbol        self.backLabel = backLabel ?? CottonStrings.back        self.onBack = onBack        self.trailing = trailing()    }    /// On a page surface (lane inplace, 16 Oct 2026) the page closes with    /// the X at the row's right and its title stands at the left, as a    /// record's does: no chevron.    private var inPlace: Bool { tileBack != nil && !isPresented && !atColumnRoot }    public var body: some View {        VStack(spacing: 0) {            ZStack {                // The title block is CENTRED OVER the row, not laid out inside                // it, so the width of the side controls can never move it.                if inPlace {                    inPlaceRow                } else {                    controlRow                    titleBlock                }            }            .frame(height: CaptureSurfaceKnobs.chromeScreenBarHeight)            subtitleLine            Spacer(minLength: 0)        }        .background(topWash, alignment: .top)        .preference(key: PageTitleKey.self, value: title)        // The bar must not eat the taps meant for the list sliding underneath.        .allowsHitTesting(true)    }    /// THE LEADING CIRCLE IS ALWAYS THERE, and it always means back. `onBack`    /// says what back DOES on this screen; when a screen says nothing, back is    /// the environment's own dismiss — which is what the phone's    /// `onBack ?? router.back()` means. Drawing no circle at all, as this once    /// did, took the only way out off any screen that had not passed one.    ///    /// The haptic is the BAR's, not the circle's: `select` on the way out is    /// what makes a back feel answered before the next screen has drawn.    ///    /// **The one exception is a COLUMN'S ROOT** (`\.cottonAtColumnRoot`, set    /// by the Mac's host and by nothing else). Column 2's list and column 3's    /// first page are the bottom of their own stack: there is no screen under    /// them, so a back circle there would dismiss nothing. The space it took    /// is kept, so the trailing controls do not move and the centred title    /// does not shift when a push arrives.    /// The head row on a page surface: the title left, the screen's own    /// controls, then the X.    private var inPlaceRow: some View {        HStack(spacing: 0) {            if let title {                Text(title)                    .cottonType(.screenTitle)                    .lineLimit(1)                    .accessibilityAddTraits(.isHeader)            }            Spacer(minLength: 0)            trailing            if let tileBack { TileBackCircle(back: tileBack) }        }        .padding(.horizontal, ScreenBarTitle.sideInset)    }    private var controlRow: some View {        HStack(spacing: 0) {            if atColumnRoot {                Color.clear                    .frame(width: ScreenBarKnobs.chromeNavCircleTarget, height: ScreenBarKnobs.chromeNavCircleTarget)                    .accessibilityHidden(true)            } else {                NavCircle(symbol: backSymbol, label: backLabel) {                    haptics.select()                    if let onBack { onBack() } else { CardClosing.close(closeCard, else: dismiss) }                }            }            Spacer(minLength: 0)            trailing                .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { trailingWidth = $0 }        }        .padding(.horizontal, ScreenBarTitle.sideInset)    }    @ViewBuilder private var titleBlock: some View {        if let title {            HStack(spacing: 6) {                if let titleSymbol {                    Image(systemName: titleSymbol)                        .font(.system(size: 17))                        .foregroundStyle(CottonColors.inkSecondary)                }                Text(title)                    .cottonType(.screenTitle)                    .lineLimit(1)                    // A long name gives up size before it gives up letters.            }            .accessibilityElement(children: .combine)            .accessibilityAddTraits(.isHeader)            // A FRACTION OF THE BAR, not a number of points: the phone writes            // `max-w-[60%]`, and a fixed clamp is a different rule on every            // device — too tight on a Pro Max, too loose on a mini. Clamped by            // what the side controls leave, which is `titleWidth`'s reason.            .containerRelativeFrame(.horizontal) { width, _ in                ScreenBarTitle.width(                    barWidth: width,                    sideWidth: max(ScreenBarKnobs.chromeNavCircleTarget, trailingWidth ?? ScreenBarKnobs.chromeNavCircleTarget),                    scale: theme.scale                )            }        }    }    @ViewBuilder private var subtitleLine: some View {        if let subtitle {            Text(subtitle)                .cottonType(.caption)                .lineLimit(1)                .frame(maxWidth: .infinity)                // A transient state line lives OUTSIDE the centred title block                // so the title never jumps when it appears, and outside the                // touch path so the list keeps scrolling under it.                .allowsHitTesting(false)        }    }    /// The page's own ground, fading out. Not a bar: a wash.    private var topWash: some View { ScreenTopWash() }}extension ScreenBar where Trailing == EmptyView {    public init(        title: String? = nil,        titleSymbol: String? = nil,        subtitle: String? = nil,        backSymbol: String = "chevron.left",        backLabel: String? = nil,        onBack: (() -> Void)? = nil    ) {        self.init(            title: title,            titleSymbol: titleSymbol,            subtitle: subtitle,            backSymbol: backSymbol,            backLabel: backLabel,            onBack: onBack,            trailing: { EmptyView() }        )    }}// MARK: - How wide the centred title may be drawn/// The bar's title measurements — outside `ScreenBar`, which is generic over/// its trailing controls and so may hold no stored statics.enum ScreenBarTitle {    /// The air the control row keeps at each end of the bar.    static let sideInset: CGFloat = 16    /// The air a centred title keeps from the nearest circle.    static let titleAir: CGFloat = 10    /// How wide the centred title may be drawn on a bar `barWidth` across    /// whose widest side control is `sideWidth`, under the worn `scale`.    ///    /// 60 % of the bar — BUT NEVER WIDER THAN THE SIDES LEAVE. The title is    /// centred OVER the row rather than laid out inside it, so the room it    /// really has is the bar less TWICE the wider side; 60 % alone is right    /// for the one circle most bars carry and a collision on the ones that    /// carry two. The walk of 2026-09-15 (row 125) found an album title    /// running into the select circle with no gap at all — "A weekend in the    /// hills☑". A one-circle bar is unchanged: its sides leave more than 60 %,    /// so 60 % still wins.    static func width(barWidth: CGFloat, sideWidth: CGFloat, scale: ThemeScale) -> CGFloat {        let free = barWidth - 2 * (sideInset + sideWidth + titleAir)        return max(0, min(barWidth * ScreenBarKnobs.chromeScreenBarTitleFraction, free))    }}/// The sizes, counts and timings ScreenBar draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ScreenBarKnobs {    static let chromeNavCircleTarget: CGFloat = 44    static let chromeScreenBarClearance: CGFloat = 75    static let chromeScreenBarTitleFraction: CGFloat = 0.6}extension ThemeScale {    /// Where a page's first thing starts under the nav circles, from the    /// physical top of a scroller that ignores the top safe area: the head    /// row, then `page_head_gap` (fan3 part 10 refinement).    public func pageClearance(topInset: CGFloat) -> CGFloat {        headRowBottom(topInset: topInset) + self[.pageHeadGap]    }    /// The head row's foot: the safe area, the theme's head padding and the    /// row's drawn circles, which stand centred in their touch targets. Here,    /// beside the circles' touch target, rather than in the theme: the look    /// (`CottonPaper`) knows the circle's drawn size, never a screen's bar.    public func headRowBottom(topInset: CGFloat) -> CGFloat {        topInset + navRowTop + (ScreenBarKnobs.chromeNavCircleTarget + navCircle) / 2    }}