Cotton code
240 lines · 9.9 KB · SwiftRaw
// An act, as a card.//// The owner's rulings of 12 and 13 Oct 2026: acts are cards — on the page, in// one row after the field cards, and in the tray the stack button raises; the// same cards in both. An act card is a field card's stock with the act's// object and a verb for its name, and its COLOUR says what the act does, the// same in every tool so a person learns it once (`ActCardReading.stock`). The// main act is first; it is not drawn differently. There are two gestures and// no menu:////   tap fires   an act that needs nothing just happens (Done, Join, Reopen);//               the page lands its stamp and keeps an undo line.//   hold fires  an act that cannot be taken back (Bin, Cancel, Leave) carries//               a red rule and fires on a hold of three quarters of a second,//               an ink line drawing round the card; let go early and it//               unwinds. No confirm popup anywhere.import SwiftUIenum ActCardGesture: Equatable, Sendable {    case fires, holds}struct ActCardReading: Equatable, Identifiable, Sendable {    /// The act's id in its definition.    var id: String    /// The verb printed under the rule.    var verb: String    var object: CardObject    /// The main act: first on the page and in the tray.    var main = false    var gesture: ActCardGesture = .fires    /// What the act does to the record, which decides its colour.    var does: CommandDoes? = nil    /// The act's colour, from what it does, as the theme prints each class    /// (`theme.acts.<class>.stock`). An act held for a reason its definition    /// does not name is a destructive one.    func stock(_ acts: ThemeActs) -> ToolCardTint { acts.stock(does, held: gesture == .holds) }    /// Lettered in red: only a held act that destroys — one held to put away    /// (Archive) is lettered in ink like any other (architect, 13 Oct 2026).    var isRed: Bool { gesture == .holds && (does == .destroys || does == nil) }    /// The words on the card: a held act says it is held ("Hold to delete"),    /// so a person never taps one and sees nothing (walker, 16 Oct 2026).    var line: String { gesture == .holds ? CardWords.holdTo(verb) : verb }}struct ActCard: View {    @Environment(\.theme) private var theme    let act: ActCardReading    /// Another card in the tray is being held: this one stands back.    var standsBack = false    /// The act fires: a tap on one that needs nothing, or a completed hold.    var onFire: (ActCardReading) -> Void = { _ in }    /// A hold began or ended, so the tray can stand its other cards back.    var onHolding: (Bool) -> Void = { _ in }    /// Its duration is the worn theme's, set by `beginHold` before every press —    /// state is made before the environment reaches the view.    @State private var hold = ActHold(duration: 0)    @State private var drawn: CGFloat = 0    @State private var pressed = false    @State private var thump: CGFloat = 1    @State private var timer: Task<Void, Never>?    @State private var nudged: CGFloat = 0    var body: some View {        GeometryReader { geo in            face(size: geo.size)        }        .aspectRatio(ActCardKnobs.cardAspect, contentMode: .fit)        .scaleEffect(pressed ? ActCardKnobs.cardPressedScale : 1)        .offset(y: hold.isHeld ? ActCardKnobs.cardHoldOffsetY : 0)        .opacity(standsBack ? Double(ActCardKnobs.cardStandsBackOpacity) : 1)        .modifier(ActCardNudge(phase: nudged))        .animation(            .spring(                response: Double(ActCardKnobs.cardPressSpringResponse),                dampingFraction: Double(ActCardKnobs.cardPressSpringDamping)),            value: pressed)        .animation(.easeOut(duration: Double(ActCardKnobs.cardHoldLiftSeconds)), value: hold.isHeld)        .animation(.easeOut(duration: Double(ActCardKnobs.cardStandsBackSeconds)), value: standsBack)        .contentShape(Rectangle())        .onTapGesture(perform: tapped)        .onLongPressGesture(            minimumDuration: Double(ActCardKnobs.cardPressTrackSeconds), maximumDistance: ActCardKnobs.cardPressSlop,            perform: {}, onPressingChanged: pressing)        .onDisappear { timer?.cancel() }        .accessibilityElement(children: .ignore)        .accessibilityLabel(act.verb)        .accessibilityHint(act.gesture == .holds ? CardWords.holdHint : "")        .accessibilityAddTraits(.isButton)        // A reader that cannot hold fires the act by activating it: the hold        // is the sighted hand's confirmation, and activation is theirs.        .accessibilityAction { fire() }        .accessibilityIdentifier("act-\(act.id)")    }    private func face(size: CGSize) -> some View {        CardStock(            paper: .stock(act.stock(theme.acts)),            size: size,            // The red rule and the red name belong to the rose stock, the act            // that destroys: an act held to put away (Archive, on grey) is            // lettered in ink like any other (architect, 13 Oct 2026).            rule: act.isRed ? .red : .plain,            line: act.line,            lineInk: act.isRed ? .red : nil,            seed: "act-" + act.id        ) { side in            CardObjectView(object: act.object, side: side * ActCardKnobs.cardActObjectFraction)                .scaleEffect(thump)        }        .overlay {            // The line a hold draws: ink, round the card's own edge, from the            // top's middle and back to it.            CardOutline(corner: ActCardKnobs.cardCornerFraction)                .trim(from: 0, to: drawn)                .stroke(                    theme.print(.ink),                    style: StrokeStyle(lineWidth: ActCardKnobs.cardHoldOutlineWidth, lineCap: .round, lineJoin: .round)                )                .padding(ActCardKnobs.cardHoldOutlineInset)                .accessibilityHidden(true)        }    }    /// A tap fires. On an act that is held, a tap is not enough: the    /// card shakes its head and its words say what it wants ("Hold to    /// delete") — never nothing.    private func tapped() {        switch act.gesture {        case .fires: fire()        case .holds: withAnimation(.linear(duration: Double(ActCardKnobs.cardNudgeSeconds))) { nudged += 1 }        }    }    private func pressing(_ down: Bool) {        guard act.gesture == .holds else {            pressed = down            return        }        down ? beginHold() : endHold()    }    private func beginHold() {        let duration = Double(ActCardKnobs.cardHoldDurationSeconds)        if !hold.isHeld { hold.duration = duration }        hold.press(at: Date())        onHolding(true)        withAnimation(.linear(duration: hold.duration)) { drawn = 1 }        timer?.cancel()        timer = Task { @MainActor in            try? await Task.sleep(for: .seconds(hold.duration))            guard !Task.isCancelled, hold.completes(at: Date()) else { return }            _ = hold.release(at: Date())            drawn = 0            onHolding(false)            fire()        }    }    private func endHold() {        guard hold.isHeld else { return }        timer?.cancel()        // Let go: the act fires only if the whole time was served.        let fires = hold.release(at: Date())        onHolding(false)        withAnimation(.easeOut(duration: Double(ActCardKnobs.cardHoldUnwindSeconds))) { drawn = 0 }        if fires { fire() }    }    /// The act fires, and its object lands on the card the way a stamp does:    /// from above, at once.    private func fire() {        thump = ActCardKnobs.stampThumpFrom        withAnimation(.easeOut(duration: Double(ActCardKnobs.stampThumpDuration))) { thump = 1 }        onFire(act)    }}/// A held card's answer to a tap: a short shake from side to side, one/// whole `phase` a shake.struct ActCardNudge: GeometryEffect {    var phase: CGFloat    var animatableData: CGFloat {        get { phase }        set { phase = newValue }    }    func effectValue(size: CGSize) -> ProjectionTransform {        let x = ActCardKnobs.cardNudgeDistance * sin(phase * .pi * 2 * ActCardKnobs.cardNudgeShakes)        return ProjectionTransform(CGAffineTransform(translationX: x, y: 0))    }}/// The sizes, counts and timings ActCard draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ActCardKnobs {    static let cardActObjectFraction: CGFloat = 0.92    static let cardAspect: CGFloat = 0.75    static let cardCornerFraction: CGFloat = 0.06    static let cardHoldDurationSeconds: CGFloat = 0.75    static let cardHoldLiftSeconds: CGFloat = 0.18    static let cardHoldOffsetY: CGFloat = -4    static let cardHoldOutlineInset: CGFloat = 1.25    static let cardHoldOutlineWidth: CGFloat = 2.5    static let cardHoldUnwindSeconds: CGFloat = 0.22    static let cardNudgeDistance: CGFloat = 5    static let cardNudgeSeconds: CGFloat = 0.36    static let cardNudgeShakes: CGFloat = 3    static let cardPressSlop: CGFloat = 44    static let cardPressSpringDamping: CGFloat = 0.7    static let cardPressSpringResponse: CGFloat = 0.24    static let cardPressTrackSeconds: CGFloat = 60    static let cardPressedScale: CGFloat = 0.96    static let cardStandsBackOpacity: CGFloat = 0.5    static let cardStandsBackSeconds: CGFloat = 0.18    static let stampThumpDuration: CGFloat = 0.22    static let stampThumpFrom: CGFloat = 1.3}extension ThemeActs {    /// The stock an act of class `does` is printed on; `held` decides an act    /// that names no class. Here rather than beside `ThemeActs`: what an act    /// does is a definition's word, and the look (`CottonPaper`) names none.    func stock(_ does: CommandDoes?, held: Bool) -> ToolCardTint {        switch does {        case .completes: return completes        case .times: return times        case .moves: return moves        case .destroys: return destroys        case .putsAway: return putsAway        case nil: return held ? unnamedHeld : unnamed        }    }}