Cotton code
353 lines · 15.1 KB · SwiftRaw
// The tray: a page's menu, raised by the stack of cards at its top corner.//// The architect's ruling of 13 Oct 2026 (owner: "the bottom bar of act cards is// confusing … without tapping anything there should be no bottom bar"): AT REST// NO PAGE HAS A BOTTOM BAR — a conversation's composer is the one bar, and it// is the conversation's, not the tray's. The page's acts are cards on the page,// in one row after its field cards; the tray is the shortcut to the same cards// when the page is long. The stack button (`TrayStackButton`) is the one page// menu — there is no three-dots menu anywhere — and tapping it raises the tray:////   pulled    every act as the lifted list a held slip hangs (`LiftedActs`),//             under the stack button over the dimmed page: one idiom, the//             tray its anchor (architect, walk 298 row 4)//   offering  the acts of one thing on the page (a held message, a person's//             channels) under its own title//// The sheet (offering) drops when a card fires, when the dimmed page is// tapped, and when it is pulled down; the pulled list folds as a lift folds.// The page behind never moves; it dims.//// The tray owns no record. It is told what to show and says what happened (an// act fired, an act asks); the page's interpreter does// the writing.import CottonKitimport SwiftUIstruct Tray: View {    @Environment(\.theme) private var theme    @Binding var state: TrayState    /// Every act allowed now, the main one first. An act that is not allowed    /// is not here: the definition's `when` decides, not the tray.    let acts: [ActCardReading]    /// What the raised tray is titled: the record it acts on.    var title: String? = nil    var onFire: (ActCardReading) -> Void = { _ in }    @State private var holding: String?    @Environment(\.actLift) private var lift    @Environment(\.trayAnchor) private var anchor    /// This tray's lift, told apart from a slip's in the same region.    @State private var liftID = "tray-" + UUID().uuidString    var body: some View {        sheet            // Pulled, the acts lift under the stack button; the list folding            // without a question or a hold raised in its place puts the tray down.            .onChange(of: state == .pulled, initial: true) { _, pulled in if pulled { liftActs() } }            .onChange(of: lift?.lifted?.id) { _, id in                if state == .pulled, id != liftID { state = .rest }            }    }    /// The page's acts as the lifted list, hung from the stack button: a row    /// fires its act; an act whose hold is its asking is offered alone, so    /// the hold still asks.    private func liftActs() {        // Every tray host is a lift region (`TrayHost`), so a lift is here.        guard let lift else { return }        let rows = acts.map { act in            let object: CardEnamel? = if case .enamel(let enamel) = act.object { enamel } else { nil }            return LiftedAct(id: act.id, word: act.verb, object: object, destroys: act.does == .destroys || act.isRed) {                switch act.gesture {                case .fires: onFire(act)                case .holds: state = .offering(TrayOffer(id: liftID, title: title ?? act.verb, acts: [act]))                }            }        }        lift.lift(Lifted(id: liftID, frame: anchor?.frame ?? .zero, face: AnyView(TrayStackButton {}), acts: rows))    }    @ViewBuilder private var sheet: some View {        if state.isSheet {            VStack(alignment: .leading, spacing: 0) {                TrayHandle { state = .rest }                switch state {                case .rest, .pulled:                    EmptyView()                case .offering(let offer):                    TrayTitle(title: offer.title, subject: offer.subject).padding(.bottom, TrayKnobs.trayTitleBottomGap)                    cards(offer.acts)                }            }            .padding(.horizontal, TrayMetrics(scale: theme.scale).side)            .padding(.top, TrayKnobs.trayTopInset)            .padding(.bottom, TrayKnobs.trayBottomInset)            .frame(maxWidth: .infinity, alignment: .leading)            .background { TrayGround() }            .gesture(                DragGesture(minimumDistance: TrayKnobs.trayPullMinDistance).onEnded { drag in                    if drag.translation.height > TrayKnobs.trayPullDismissDistance { state = .rest }                }            )            .transition(.move(edge: .bottom))            .accessibilityElement(children: .contain)            .accessibilityIdentifier("tray")        }    }    private func cards(_ shown: [ActCardReading]) -> some View {        VStack(spacing: 0) {            CardRows(scale: theme.scale) {                ForEach(shown) { act in                    ActCard(                        act: act,                        standsBack: holding != nil && holding != act.id,                        onFire: { fired in                            state = .rest                            onFire(fired)                        },                        onHolding: { held in holding = held ? act.id : nil }                    )                }            }            if let holding { TrayNote(words: CardWords.keepHolding(shown.first { $0.id == holding }?.verb ?? "")) }        }    }}/// The pencilled line under a row of cards: what a hold is doing.struct TrayNote: View {    @Environment(\.theme) private var theme    let words: String    var body: some View {        Text(words)            .font(theme.type.hand(theme.scale.handSize + 1))            .foregroundStyle(theme.print(.pencil))            .frame(maxWidth: .infinity)            .padding(.top, TrayKnobs.trayNoteTopInset)    }}/// The raised sheet's handle: a tap or a pull puts it down.private struct TrayHandle: View {    @Environment(\.theme) private var theme    let putDown: () -> Void    var body: some View {        Capsule()            .fill(theme.print(.ink).opacity(Double(TrayKnobs.trayHandleInkOpacity)))            .frame(width: TrayKnobs.trayHandleWidth, height: TrayKnobs.trayHandleHeight)            .frame(maxWidth: .infinity)            .padding(.top, TrayKnobs.trayHandleTopInset)            .padding(.bottom, TrayKnobs.trayHandleBottomInset)            .contentShape(Rectangle())            .onTapGesture(perform: putDown)            .accessibilityElement()            .accessibilityLabel(CardWords.putDown)            .accessibilityAddTraits(.isButton)            .accessibilityAction(.default, putDown)            .accessibilityIdentifier("tray-handle")    }}/// The stack of cards at a page's top corner: the page's one menu. It raises/// the tray with every act of the page.struct TrayStackButton: View {    @Environment(\.theme) private var theme    @Environment(\.trayAnchor) private var anchor    let action: () -> Void    var body: some View {        ZStack {            ForEach(theme.cards.trayStackStocks.indices, id: \.self) { index in                let card = RoundedRectangle(cornerRadius: TrayKnobs.trayStackCardCorner, style: .continuous)                card.fill(theme.sheet(theme.cards.trayStackStocks[index].paper))                    .overlay(                        card.strokeBorder(                            theme.print(.ink).opacity(Double(TrayKnobs.trayStackCardInkOpacity)),                            lineWidth: TrayKnobs.trayStackCardRuleWidth))                    .frame(width: TrayKnobs.trayStackCardWidth, height: TrayKnobs.trayStackCardHeight)                    .rotationEffect(.degrees(Double(index - 1) * Double(TrayKnobs.trayStackCardRotationStep)))                    .offset(x: CGFloat(index - 1) * TrayKnobs.trayStackCardOffsetStep)            }        }        .background(            Circle()                .fill(NavChrome.circleFill)                .frame(width: theme.scale.navCircle, height: theme.scale.navCircle)                .softShadow()        )        .frame(width: TrayMetrics(scale: theme.scale).target, height: TrayMetrics(scale: theme.scale).target)        .contentShape(Rectangle())        .onTapGesture(perform: action)        // Where the pulled tray's list hangs from.        .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { anchor?.button = $0 }        .accessibilityElement()        .accessibilityLabel(CardWords.pullUp)        .accessibilityAddTraits(.isButton)        .accessibilityAction(.default, action)        .accessibilityIdentifier("tray-stack")    }}/// Where a tray's pulled list hangs: the stack button as it stands on the/// screen, or — where a host's menu has no stack drawn inside it — the top/// trailing corner of the host, where the stack always stands.@MainActor @Observablefinal class TrayAnchor {    var button: CGRect?    var host: CGRect = .zero    var frame: CGRect {        if let button { return button }        let side = TrayKnobs.trayTargetSide        return CGRect(x: host.maxX - TrayKnobs.traySideInset - side, y: host.minY, width: side, height: side)    }}extension EnvironmentValues {    /// The tray host's anchor, which its stack button marks.    @Entry var trayAnchor: TrayAnchor? = nil}/// The tray's measures, read from the theme's scale.struct TrayMetrics {    let scale: ThemeScale    /// The stack button's hit area: a fingertip, whatever the circle's size.    var target: CGFloat { TrayKnobs.trayTargetSide }    /// The tray's own side margin: the page's.    var side: CGFloat { TrayKnobs.traySideInset }    /// How far the page dims behind a raised tray.    var dim: Double { Double(TrayKnobs.trayDimOpacity) }}/// The tray's paper: a cream sheet cut like the slips, its top corners/// showing, running off the page's sides and bottom.private struct TrayGround: View {    @Environment(\.theme) private var theme    var body: some View {        PaperSurface(dye: .cream, edge: .cut, seed: "tray")            .padding(.bottom, TrayKnobs.trayGroundBottomBleed)            .modifier(PaperLift(shadow: .lifted))            .ignoresSafeArea(edges: .bottom)            .accessibilityHidden(true)    }}// MARK: - Over the page/// Lays a tray over a page. Nothing is laid while it rests: the page keeps no/// inset for it and nothing stands at its foot. Raised, the page dims behind it/// and a tap on the dimmed page drops it, and the page says so where it/// stands (`Navigator.tray`), so Home puts the fan away while it is up:/// every tray, a list's, a record's or a board's, rises over the dial's band,/// never under it (walker pass 4, 16 Oct 2026).private struct TrayHost<TrayView: View>: ViewModifier {    @Environment(\.theme) private var theme    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.screenRoute) private var screenRoute    @Binding var state: TrayState    @ViewBuilder let tray: TrayView    @State private var host = UUID()    @State private var anchor = TrayAnchor()    func body(content: Content) -> some View {        content            // The page under a raised tray is covered: out of the tree, with            // every UIKit arc in it — the lifted list of a pulled tray too.            .coveredUnread(state.isRaised)            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { anchor.host = $0 }            .onChange(of: state.isRaised, initial: true) { _, up in                if let screenRoute { navigator?.tray(host, up: up, on: screenRoute) }            }            .onDisappear { if let screenRoute { navigator?.tray(host, up: false, on: screenRoute) } }            .overlay {                if state.isSheet {                    theme.colors.ground.color.opacity(TrayMetrics(scale: theme.scale).dim)                        .ignoresSafeArea()                        .contentShape(Rectangle())                        .onTapGesture { state = .rest }                        .transition(.opacity)                        .accessibilityHidden(true)                }            }            .overlay(alignment: .bottom) { tray.coversTheRest(state.isSheet) }            .animation(                .spring(                    response: Double(TrayKnobs.traySpringResponse),                    dampingFraction: Double(TrayKnobs.traySpringDamping)),                value: state)            .environment(\.trayAnchor, anchor)            // A pulled tray lifts its acts: every tray host is a lift region            // (the widest one hosts — under one already, this passes through).            .liftsActs()    }}extension View {    /// Out of the accessibility tree while something covers it — a raised    /// tray, a page over a list, the viewer's hand — with every UIKit arc    /// inside it (`fanArcHidden`): a covered view is never read under what    /// covers it.    func coveredUnread(_ covered: Bool) -> some View {        #if os(iOS)        fanArcHidden(covered)        #else        accessibilityHidden(true, isEnabled: covered)        #endif    }    /// The view that stands over the rest while `covering` — a raised tray,    /// a page's layer: a tree reader stops at it. Hiding what is under it    /// alone did not hold where that lives in the same hosting view (a    /// PaperScreen's UIKit-backed scroll): the hand-only record page read    /// under the viewer's tray, the Copies list under a copy's page    /// (walker294 rows 93, 99, 115).    func coversTheRest(_ covering: Bool) -> some View {        accessibilityAddTraits(covering ? .isModal : [])    }    /// The page's tray, laid over it while it is raised.    func tray(state: Binding<TrayState>, @ViewBuilder _ tray: () -> some View) -> some View {        modifier(TrayHost(state: state, tray: tray))    }}/// The sizes, counts and timings Tray draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum TrayKnobs {    static let trayBottomInset: CGFloat = 18    static let trayDimOpacity: CGFloat = 0.35    static let trayGroundBottomBleed: CGFloat = -80    static let trayHandleBottomInset: CGFloat = 12    static let trayHandleHeight: CGFloat = 4    static let trayHandleInkOpacity: CGFloat = 0.22    static let trayHandleTopInset: CGFloat = 4    static let trayHandleWidth: CGFloat = 36    static let trayLeaveDrop: CGFloat = 420    static let trayLeaveScale: CGFloat = 0.86    static let trayLeaveSeconds: CGFloat = 0.32    static let trayNoteTopInset: CGFloat = 8    static let trayPullDismissDistance: CGFloat = 40    static let trayPullMinDistance: CGFloat = 16    static let traySideInset: CGFloat = 16    static let traySpringDamping: CGFloat = 0.88    static let traySpringResponse: CGFloat = 0.34    static let trayStackCardCorner: CGFloat = 2    static let trayStackCardHeight: CGFloat = 17    static let trayStackCardInkOpacity: CGFloat = 0.28    static let trayStackCardOffsetStep: CGFloat = 5    static let trayStackCardRotationStep: CGFloat = 12    static let trayStackCardRuleWidth: CGFloat = 0.75    static let trayStackCardWidth: CGFloat = 13    static let trayTargetSide: CGFloat = 44    static let trayTitleBottomGap: CGFloat = 12    static let trayTopInset: CGFloat = 6    /// The undo line's words stop here, so Undo stands on the narrowest phone.}