Cotton code
271 lines · 12.1 KB · SwiftRaw
// The paper a card is cut from (`CardLayer`), once the bottom sheet's.//// There are no bottom sheets (row E of the deck faces, 23 Oct 2026: the owner// ruled sheets out of the design). What a sheet carried opens as a card// standing on its page (`Chrome/CardLayer.swift`); what stays here is the// dress every card wears — the cream `.cut` paper every card in the app is// cut from (`SheetPaper`), the chrome whose paper scrolls// (`CottonSheetChrome`), the one close control by one word — and the named// heights a card may take (`CottonDetent`).import SwiftUI#if os(iOS)import UIKit#endif/// The detents a Cotton sheet may take. Named rather than free-form: a sheet/// that invented its own height would be the one surface whose grammar is its/// own.enum CottonDetent: Sendable, Hashable {    /// As tall as its content, and no taller — the form sheets.    ///    /// This is NOT one of the system's detents: iOS has no "measure the    /// content" detent, and the nearest one (`.medium`) is half the screen — the    /// same height as `.half`, which would make two of the three names mean one    /// thing. The dress measures the content and hands the height back as a    /// `.height` detent (`fitted(_:)`).    case content    /// Half the screen — a picker over a list you want to keep seeing.    case half    /// Nearly full.    case tall    /// `nil` for `.content`, which is sized rather than detented.    var detent: PresentationDetent? {        switch self {        case .content: return nil        case .half: return .fraction(0.5)        case .tall: return .large        }    }    /// The system detents a set of names asks for. EMPTY means the sheet is    /// sized by its content — a set that named only `.content`.    static func heights(_ detents: Set<CottonDetent>) -> Set<PresentationDetent> {        Set(detents.compactMap(\.detent))    }    /// Content taller than this is content that may not fit the phone at all.    /// It is a FLOOR on "ask for full height as well", not a measurement of any    /// device: a `.height` detent bigger than the screen is clamped by the    /// system and there is then no taller detent to drag to, so a long roster    /// sat in a sheet that could not grow.    static let tallContent: CGFloat = 520    /// The detent a content-sized sheet takes once its content has been    /// measured — and `.medium` for the one frame before it has, so a sheet    /// rises part-way rather than to the top and back down.    ///    /// Tall content ALSO offers `.large`, so a sheet whose paper is longer than    /// the screen can be dragged to full height; the chrome's own scroll    /// (`CottonSheetChrome`) reaches the rest either way.    static func fitted(_ measured: CGFloat?) -> Set<PresentationDetent> {        guard let measured, measured > 0 else { return [.medium] }        let height = measured.rounded(.up)        return height >= tallContent ? [.height(height), .large] : [.height(height)]    }}/// The paper a sheet is cut from, by name — one place, so a test can hold it.enum SheetPaper {    static let dye: PaperDye = .cream    static let edge: PaperEdge = .cut    /// A sheet has no record behind it; one seed means every sheet is the same    /// piece of paper, which is right — it is the same surface each time.    static let seed = "sheet"    /// The drawn grip: as wide as the system's, a pencil stroke thick.    static let gripWidth: CGFloat = 38    static let gripHeight: CGFloat = 4    static let gripStroke: CGFloat = 2.2    /// The padding that makes the drawn line a TARGET. The line is 38 × 4;    /// nobody's finger is. The two vertical figures are the space the grip    /// already occupied (9 above it, and the 10 that used to be the content's    /// own top padding), so the control is bigger and the sheet looks the    /// same.    static let gripPadTop: CGFloat = 9    static let gripPadBottom: CGFloat = 10    static let gripPadSide: CGFloat = 24    /// The whole grip row's height — the drawn line plus the padding that makes    /// it a target. A content-sized sheet measures its PAPER and adds this, so    /// the height it asks for is the height it draws.    static let gripTotalHeight: CGFloat = gripHeight + gripPadTop + gripPadBottom    /// **What the sheet's one close control is called.** Said HERE, once, so    /// every sheet in the app closes by the same word and no screen has to    /// remember to offer one.    static let closeLabel = "Close"    static let closeIdentifier = "sheet-close"}/// The sheet's dress: the grip that closes it, and the paper under it.////// **THE PAPER SCROLLS.** A sheet is a fixed height — half the screen, or the/// height its content asked for — and the content under it is not: a record in/// nine projects laid a run of caps taller than the detent, and the rows past/// the fold were simply not reachable (the owner's feedback of 2026-09-20, the/// projects sheet). The scroll is HERE rather than in each sheet's content, so/// no screen has to remember it and none can forget.////// A DETENTED sheet's paper still FILLS the detent — `minHeight` the height on/// offer — so a content that pushes something to the foot with a `Spacer` lays/// out exactly as it did before the scroll went in. A content-sized sheet is as/// tall as its paper by definition, so it measures instead (`onMeasure`) and the/// scroll only earns its keep once the system clamps that height to the screen.public struct CottonSheetChrome<Content: View>: View {    private let content: Content    /// Whether the paper fills the height on offer (a detented sheet) or states    /// its own (a content-sized one).    private let fills: Bool    /// A content-sized sheet's height, paper plus grip, as it changes.    private let onMeasure: ((CGFloat) -> Void)?    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    @Environment(\.cardHolds) private var holds    @Environment(\.theme) private var theme    public init(@ViewBuilder content: () -> Content) {        self.init(fills: true, onMeasure: nil, content: content)    }    init(fills: Bool, onMeasure: ((CGFloat) -> Void)?, @ViewBuilder content: () -> Content) {        self.content = content()        self.fills = fills        self.onMeasure = onMeasure    }    public var body: some View {        VStack(spacing: 0) {            if closeCard == nil { grip } else if !holds { cardHead }            if fills {                GeometryReader { geo in                    ScrollView {                        paper.frame(minHeight: geo.size.height, alignment: .top)                    }                    .scrollBounceBehavior(.basedOnSize)                }            } else {                ScrollView {                    paper                        // The height the PAPER asks for — read inside the                        // scroll, where it is offered as much as it wants, so                        // the measure never reads back the sheet it sits in.                        .onGeometryChange(for: CGFloat.self, of: { $0.size.height }) { height in                            onMeasure?(height + (closeCard == nil ? SheetPaper.gripTotalHeight : holds ? 0 : CardLayerKnobs.headHeight))                        }                }                .scrollBounceBehavior(.basedOnSize)            }        }    }    private var paper: some View {        content            .padding(.horizontal, 20)            .padding(.bottom, 12)            .frame(maxWidth: .infinity, alignment: .leading)    }    /// A card's head (`CardLayer`): the X at its right, the card's one close    /// control, by the same word and identifier as the grip it replaces.    private var cardHead: some View {        HStack {            Spacer()            NavCircle(symbol: "xmark", label: SheetPaper.closeLabel) { closeCard?() }                .accessibilityIdentifier(SheetPaper.closeIdentifier)        }        .padding(.horizontal, 10)        .frame(height: CardLayerKnobs.headHeight)    }    /// The grip: a short pencil line at the top edge, and **the sheet's one    /// close control**.    ///    /// It was a drawing, hidden from VoiceOver, on the reasoning that the    /// sheet's own drag-down was the escape. The capture walk of 2026-09-15    /// (the device sheet, row 182) found what that costs: the sheet offered    /// the accessibility tree NOTHING to close it, and the walker had to drag    /// the sheet down by hand. A drag is a gesture, not a control — a person    /// using VoiceOver or Switch Control or a keyboard has no drag.    ///    /// So the line stays exactly as drawn and the CONTROL is put around it:    /// one labelled button, in the chrome every `cottonCard` wears, so no    /// screen has to offer its own and none can forget. The drawn line is    /// padded out to a target a finger can find (`SheetPaper.gripPad*`)    /// WITHOUT moving anything: the padding is the space the grip and the    /// content's own top inset already took between them.    private var grip: some View {        Button { CardClosing.close(closeCard, else: dismiss) } label: {            PencilRule(seed: "sheet-grip", theme: theme)                .stroke(theme.print(.pencil), style: StrokeStyle(lineWidth: SheetPaper.gripStroke, lineCap: .round))                .blendMode(theme.printBlend)                .frame(width: SheetPaper.gripWidth, height: SheetPaper.gripHeight)                .padding(.top, SheetPaper.gripPadTop)                .padding(.bottom, SheetPaper.gripPadBottom)                .padding(.horizontal, SheetPaper.gripPadSide)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityLabel(SheetPaper.closeLabel)        .accessibilityIdentifier(SheetPaper.closeIdentifier)        .accessibilityAddTraits(.isButton)        .frame(maxWidth: .infinity)    }}#if os(iOS)/// While a sheet is up, the page beneath it is hidden from accessibility/// (architect, 5 Oct 2026): a half-height sheet left the page in the tree, so/// VoiceOver started reading at the page and the composer and dev corner,/// lifted by the keyboard, sat inside the sheet's frame in a walker's/// describe. The PRESENTER's view is hidden — the whole page, or the sheet/// under a sheet — and given back as it was when this sheet goes.struct SheetModalAnchor: UIViewRepresentable {    func makeUIView(context: Context) -> AnchorView { AnchorView() }    func updateUIView(_ view: AnchorView, context: Context) {}    static func dismantleUIView(_ view: AnchorView, coordinator: ()) { view.giveBack() }    final class AnchorView: UIView {        private weak var hiddenPresenter: UIView?        private var wasHidden = false        override func didMoveToWindow() {            super.didMoveToWindow()            if window == nil { giveBack() } else { hidePresenter() }        }        private func hidePresenter() {            guard hiddenPresenter == nil, let presenter = sheetController?.presentingViewController?.view else { return }            wasHidden = presenter.accessibilityElementsHidden            presenter.accessibilityElementsHidden = true            hiddenPresenter = presenter            UIAccessibility.post(notification: .screenChanged, argument: nil)        }        func giveBack() {            hiddenPresenter?.accessibilityElementsHidden = wasHidden            hiddenPresenter = nil        }        /// The controller the sheet is: the outermost one this view sits in.        private var sheetController: UIViewController? {            var responder: UIResponder? = self            while let next = responder?.next {                if let controller = next as? UIViewController {                    var outer = controller                    while let parent = outer.parent { outer = parent }                    return outer                }                responder = next            }            return nil        }    }}#endif/// The sizes, counts and timings Sheets draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum SheetsKnobs {    static let paperRadiusMax: CGFloat = 8}