Cotton code
232 lines · 9.2 KB · SwiftRaw
// No bottom sheets (row E of the deck faces, 23 Oct 2026; the owner: sheets are// out of the design). What a sheet carried — a form, a picker, a flow — opens// as a CARD: the sheet's own cream paper cut to a card standing in the middle// of the page it was opened from, the page under it dimmed by `page_dim` and// closed to a tree reader, the X at the card's head (`SheetPaper.close*`),// and a tap on the dim closing it unless the card holds (a recording).//// A card is a LAYER raised as a preference, as a page's own page is// (`PageDestination.swift`): the presenter's environment travels with it, and// it stands over the nearest card host — every page surface is one// (`pageSurface()`), the window is the last (`RootView`), and each card is a// host for the card it opens. A card's content closes it with `closeCard`// (`CardClosing`), which a view that once called `dismiss()` reads first.import SwiftUI/// One card a screen opened, raised to its host.struct CardLayer {    let id: String    let content: AnyView    /// The environment of the screen that opened it.    let environment: EnvironmentValues    let detents: Set<CottonDetent>    /// A tap on the dim leaves it up: only its own controls close it.    let holds: Bool    let close: @MainActor () -> Void}struct CardLayerKey: PreferenceKey {    static var defaultValue: [CardLayer] { [] }    static func reduce(value: inout [CardLayer], nextValue: () -> [CardLayer]) {        value.append(contentsOf: nextValue())    }}private struct CloseCardKey: EnvironmentKey {    static let defaultValue: (@MainActor () -> Void)? = nil}private struct CardHoldsKey: EnvironmentKey {    static let defaultValue = false}extension EnvironmentValues {    /// Closes the card this view stands on; nil off a card.    var closeCard: (@MainActor () -> Void)? {        get { self[CloseCardKey.self] }        set { self[CloseCardKey.self] = newValue }    }    /// The card this view stands on holds: it has no X, and only its own    /// controls close it.    var cardHolds: Bool {        get { self[CardHoldsKey.self] }        set { self[CardHoldsKey.self] = newValue }    }}/// How a view that once dismissed its sheet closes: the card it stands on,/// else the presentation or page it is in.enum CardClosing {    @MainActor static func close(_ card: (@MainActor () -> Void)?, else dismiss: DismissAction) {        if let card { card() } else { dismiss() }    }}extension View {    /// Opens `content` as a card while `isPresented` is true. `onDismiss`    /// runs once it is closed, however it closed.    func cottonCard<Content: View>(        isPresented: Binding<Bool>,        detents: Set<CottonDetent> = [.content],        holds: Bool = false,        onDismiss: (() -> Void)? = nil,        @ViewBuilder content: @escaping () -> Content    ) -> some View {        modifier(CardLayerRaise(            id: isPresented.wrappedValue ? "shown" : nil, detents: detents, holds: holds, onDismiss: onDismiss,            content: { isPresented.wrappedValue ? AnyView(content()) : nil },            close: { isPresented.wrappedValue = false }))    }    /// Opens `content` for `item` as a card while it is set.    func cottonCard<Item: Identifiable, Content: View>(        item: Binding<Item?>,        detents: Set<CottonDetent> = [.content],        holds: Bool = false,        onDismiss: (() -> Void)? = nil,        @ViewBuilder content: @escaping (Item) -> Content    ) -> some View {        modifier(CardLayerRaise(            id: item.wrappedValue.map { String(describing: $0.id) }, detents: detents, holds: holds, onDismiss: onDismiss,            content: { item.wrappedValue.map { AnyView(content($0)) } },            close: { item.wrappedValue = nil }))    }    /// This view is a card host: the cards opened inside it stand over it.    func cardLayers() -> some View {        modifier(CardLayerHost())    }}/// Raises the card while it is open, in the opening screen's environment.private struct CardLayerRaise: ViewModifier {    let id: String?    let detents: Set<CottonDetent>    let holds: Bool    let onDismiss: (() -> Void)?    let content: () -> AnyView?    let close: @MainActor () -> Void    @Environment(\.self) private var environment    /// Where this screen stands, so two screens' cards never share an id.    @State private var place = UUID().uuidString    func body(content view: Content) -> some View {        view            .transformPreference(CardLayerKey.self) { cards in                guard let id, let card = content() else { return }                cards.append(CardLayer(                    id: place + id, content: card, environment: environment, detents: detents, holds: holds, close: close))            }            .onChange(of: id) { was, now in                if was != nil, now == nil { onDismiss?() }            }    }}/// The host: its page, with the top card opened inside it standing over it.private struct CardLayerHost: ViewModifier {    @Environment(\.theme) private var theme    /// A card stands over the page: the page under it is not read out.    @State private var covered = false    func body(content: Content) -> some View {        content            .coveredUnread(covered)            .overlayPreferenceValue(CardLayerKey.self) { cards in                ZStack {                    if let top = cards.last {                        CardLayerPage(card: top)                            .id(top.id)                            .transition(.opacity)                    }                }                .animation(.easeOut(duration: fade), value: cards.last?.id)                .onChange(of: cards.last?.id, initial: true) { _, top in covered = top != nil }            }            // The cards stop here: the host around this one never draws them.            .transformPreference(CardLayerKey.self) { $0 = [] }    }    private var fade: Double { Double(theme.scale[.fanOpenFadeMs]) / 1000 }}/// One card over its page: the dim, and the card of paper in the middle.private struct CardLayerPage: View {    let card: CardLayer    var body: some View {        var environment = card.environment        environment.closeCard = card.close        environment.cardHolds = card.holds        // The card is not the page it was opened on: that page's back is        // not the card's, and a page the card opens is the card's own.        #if os(iOS)        environment.tileBack = nil        environment.tileHere = nil        #endif        environment.cottonAtColumnRoot = false        let theme = environment.theme        return GeometryReader { room in            ZStack {                theme.colors.shadow.color.opacity(Double(theme.scale[.pageDim]))                    .ignoresSafeArea()                    .contentShape(Rectangle())                    .onTapGesture { if !card.holds { card.close() } }                    .accessibilityHidden(true)                CardLayerPaper(detents: card.detents, room: room.size) { card.content }                    .cardLayers()            }        }        .environment(\.self, environment)        .coversTheRest(true)    }}/// The card: the sheet's paper and chrome, as tall as its content asks/// (`.content`), half the room (`.half`) or nearly all of it (`.tall`).private struct CardLayerPaper<Content: View>: View {    let detents: Set<CottonDetent>    let room: CGSize    @ViewBuilder let content: () -> Content    @Environment(\.theme) private var theme    @State private var measured: CGFloat?    var body: some View {        let most = max(0, room.height - CardLayerKnobs.gutter * 2)        let height: CGFloat = switch CardLayerKnobs.height(detents) {        case .half: min(most, room.height * CardLayerKnobs.halfShare)        case .tall: most        case .content: min(most, measured ?? CardLayerKnobs.firstHeight)        }        CottonSheetChrome(fills: !detents.subtracting([.content]).isEmpty, onMeasure: { measured = $0 }, content: content)            .frame(width: min(room.width - CardLayerKnobs.gutter * 2, CardLayerKnobs.widest), height: height)            .background { PaperSurface(dye: SheetPaper.dye, edge: SheetPaper.edge, seed: SheetPaper.seed) }            .clipShape(RoundedRectangle(cornerRadius: SheetsKnobs.paperRadiusMax))            .shadow(color: theme.colors.shadow.color.opacity(CardLayerKnobs.shadowOpacity), radius: CardLayerKnobs.shadowRadius, y: CardLayerKnobs.shadowDrop)            .frame(width: room.width, height: room.height)    }}/// The sizes a card draws with: Swift's own, beside their reader.enum CardLayerKnobs {    /// The page's margin round a card.    static let gutter: CGFloat = 16    static let widest: CGFloat = 560    static let halfShare: CGFloat = 0.55    /// A content-sized card's height for the one frame before it is measured.    static let firstHeight: CGFloat = 240    /// The card's head: the X that closes it.    static let headHeight: CGFloat = 52    static let shadowOpacity: Double = 0.18    static let shadowRadius: CGFloat = 14    static let shadowDrop: CGFloat = 6    /// The one height a card takes of those a sheet once offered: the    /// smallest it named.    static func height(_ detents: Set<CottonDetent>) -> CottonDetent {        detents.contains(.half) ? .half : detents.contains(.tall) ? .tall : .content    }}