Cotton code
450 lines · 22.2 KB · SwiftRaw
// The card itself: Home's tile stock, cut for a hand.//// The architect's ruling of 13 Oct 2026 (feedback 44d96d90: "the screen looks// a bit too skeuomorphic … look at Home, the colours are more pastel … I don't// know why we use darker cards") and the owner's word after it ("the UI is// aesthetic first: the slip lists and the Home tiles are the standard"): every// card in the app is cut from ONE stock — the 3:4 tile in cream, sage, rose,// slate, tan or grey, on the SAME paper the slip lists are cut from (the// photographed dye and its grain, `PaperSurface`), with the slips' cut corner,// their contact shadow and a single printed hairline inside the edge. No aged// photograph with an ornamental double border, no bevel, no ink-black card: a// main act is told apart by its colour and by coming first.//// `ToolCardTint.paper` is the one map from a stock to its paper. `ActCard` is// this card with a verb on it.//// The arithmetic is the theme's scale: the tool card's keys (`tool_card_*`)// wherever the cards share a piece with a tile (the rule), and the same values// under `card_*` for the aspect and the object's centre, so a field card next// to a tile reads as cut from the same deck; `CardMetrics` reads them as// fractions of the card's width or height, so one card is one drawing in a// hand of three, a row of acts and a strip of five.import SwiftUI/// What a card is printed on.enum CardPaper: Equatable, Sendable {    /// One of the six flat stocks.    case stock(ToolCardTint)    /// No stock at all: the card's outline, dashed — an empty field.    case outline}extension ToolCardTint {    /// The paper a card of this stock is cut from: the slip lists' own dyes.    var paper: PaperDye {        switch self {        case .cream: return .cream        case .sage: return .sage        case .rose: return .pink        case .slate: return .blue        case .tan: return .buff        case .grey: return .newsprint        }    }}/// The rule under the object.enum CardRule: Equatable, Sendable {    case plain    /// An act that cannot be taken back carries a red rule.    case red    /// An empty field has no rule: there is nothing under it to rule off.    case none}/// The card's arithmetic, read from the theme's scale (`card_*`): each a/// fraction of the card's width or height unless it says otherwise.struct CardMetrics {    let scale: ThemeScale    var aspect: CGFloat { ActCardKnobs.cardAspect }    var inset: CGFloat { CardStockKnobs.cardContentInset }    /// The small word at the top: its centre down the card, its size.    var keyCentre: CGFloat { CardStockKnobs.cardKeyCentre }    func keySize(width: CGFloat) -> CGFloat {        min(CardStockKnobs.cardKeySizeMax, max(CardStockKnobs.cardKeySizeMin, width * CardStockKnobs.cardKeySizeFraction))    }    /// The room the name has over the object: two lines at most.    var keyBox: CGFloat { CardStockKnobs.cardKeyBox }    /// The size a card `width` wide sets its name at — never under the    /// caption size — and the width the name stands in: what a definition's    /// card label must fit in two lines (`CardLabelFitTests`).    func keyRoom(width: CGFloat) -> (size: CGFloat, span: CGFloat) {        (max(keySize(width: width), scale[.typeCaptionSize]),         width * (1 - CardStockKnobs.cardKeyWidthInsetMultiplier * inset))    }    /// Where a card `width` wide, standing in a row `rowWidth` wide, sets its    /// name `key`: centred over its object in the card's own room when the    /// name stands whole there; on a card that takes its row and whose name    /// does not — one word wider than the room, which the type would break    /// inside the word ("Passwo/rd", walker294) — from the card's leading    /// edge across the row's room. `centre` is the name's box's middle.    func keyPlace(_ key: String, face: ThemeFace, width: CGFloat, rowWidth: CGFloat)        -> (size: CGFloat, span: CGFloat, centre: CGFloat, leading: Bool)    {        let (size, span) = keyRoom(width: width)        let wide = rowWidth > width + CardStockKnobs.cardWideThreshold        guard wide, !InkFit.fits(key, face: face, size: size, width: span, lines: CardStockKnobs.cardKeyLineLimit) else {            return (size, span, width * 0.5, false)        }        let edge = (width - span) * 0.5        let row = max(span, rowWidth - 2 * edge)        return (size, row, edge + row * 0.5, true)    }    /// The object's square against the card's width. Smaller than the tool    /// card's: the word at the top needs the space.    var objectFraction: CGFloat { CardStockKnobs.cardObjectFraction }    var objectCentre: CGFloat { CardStockKnobs.cardObjectCentre }    /// The room a line alone has: from under the rule to the stock's printed    /// frame, one line set about where the tool's name sits, a label that    /// wraps taking two. A value with a small line under it shares the room.    var lineBox: CGFloat { CardStockKnobs.cardLineBox }    var lineBoxCentre: CGFloat { CardStockKnobs.cardLineBoxCentre }    var pairedLineCentre: CGFloat { CardStockKnobs.cardPairedLineCentre }    var pairedSmallCentre: CGFloat { CardStockKnobs.cardPairedSmallCentre }    /// Two lines are each set a little smaller than one alone.    var pairedScale: CGFloat { CardStockKnobs.cardPairedScale }    func lineSize(width: CGFloat) -> CGFloat {        min(CardStockKnobs.cardLineSizeMax, max(CardStockKnobs.cardLineSizeMin, width * CardStockKnobs.cardLineSizeFraction))    }    func smallSize(width: CGFloat) -> CGFloat {        min(CardStockKnobs.cardSmallSizeMax, max(CardStockKnobs.cardSmallSizeMin, width * CardStockKnobs.cardSmallSizeFraction))    }    /// A card too narrow for two lines under its rule (a strip's) sets one.    var pairedFromWidth: CGFloat { CardStockKnobs.cardPairedFromWidth }    /// The tile's corner, as a fraction of the card's width: the stock, the    /// outline of an empty field and the line a hold draws share it.    var corner: CGFloat { ActCardKnobs.cardCornerFraction }    /// The single printed frame inside the edge: how far in, and its corner.    var frameInset: CGFloat { CardStockKnobs.cardFrameInset }    var frameCorner: CGFloat { CardStockKnobs.cardFrameCorner }    /// A stamp lands the way the hand put it.    var stampTilt: Double { Double(CardStockKnobs.cardStampTiltDegrees) }    func height(width: CGFloat) -> CGFloat { width / aspect }}/// The card's silhouette, for an empty field's outline and a hold's line. The/// path starts at the top's middle and runs clockwise, so a trim draws round/// the card the way a hand would.struct CardOutline: Shape {    /// The corner, as a fraction of the card's width (`CardMetrics.corner`).    let corner: CGFloat    func path(in rect: CGRect) -> Path {        let radius = rect.width * corner        let quarter = Double.pi * 0.5        var path = Path()        path.move(to: CGPoint(x: rect.midX, y: rect.minY))        path.addLine(to: CGPoint(x: rect.maxX - radius, y: rect.minY))        path.addArc(            center: CGPoint(x: rect.maxX - radius, y: rect.minY + radius), radius: radius,            startAngle: .radians(-quarter), endAngle: .degrees(0), clockwise: false)        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - radius))        path.addArc(            center: CGPoint(x: rect.maxX - radius, y: rect.maxY - radius), radius: radius,            startAngle: .degrees(0), endAngle: .radians(quarter), clockwise: false)        path.addLine(to: CGPoint(x: rect.minX + radius, y: rect.maxY))        path.addArc(            center: CGPoint(x: rect.minX + radius, y: rect.maxY - radius), radius: radius,            startAngle: .radians(quarter), endAngle: .radians(.pi), clockwise: false)        path.addLine(to: CGPoint(x: rect.minX, y: rect.minY + radius))        path.addArc(            center: CGPoint(x: rect.minX + radius, y: rect.minY + radius), radius: radius,            startAngle: .radians(.pi), endAngle: .radians(.pi + quarter), clockwise: false)        path.closeSubpath()        return path    }}/// One card at a decided size: the paper, the word at the top, the object, the/// rule and the lines under it.struct CardStock<Object: View>: View {    @Environment(\.theme) private var theme    let paper: CardPaper    let size: CGSize    var key: String? = nil    var rule: CardRule = .plain    var line: String? = nil    var small: String? = nil    var smallInk: PaperInk? = nil    /// A scalar shares one stack for its figure and caption.    var figure: String? = nil    /// An empty field's line is a pencilled invitation, not a value.    var pencilled = false    /// The line's ink when it is not the card's lettering: an act that cannot    /// be taken back is named in red.    var lineInk: PaperInk? = nil    /// Seeds the paper's cut, so a hand is not one card three times.    var seed = "card"    /// The most lines the line under the rule takes before it is cut at a    /// word: a web address takes one, cut at a part of the address, its    /// whole on the card's tap.    var lineLines = CardStockKnobs.cardLineLines    /// The object, handed the square it stands in.    @ViewBuilder let object: (CGFloat) -> Object    private var metrics: CardMetrics { CardMetrics(scale: theme.scale) }    /// The card's own width — the unit every piece is a fraction of. A card    /// that takes its row is wider than this: its pieces stay a card's, at the    /// leading end, and its words take the rest.    private var width: CGFloat { min(size.width, size.height * metrics.aspect) }    private var wide: Bool { size.width > width + CardStockKnobs.cardWideThreshold }    private var paired: Bool { small != nil && line != nil && width >= metrics.pairedFromWidth }    var body: some View {        ZStack {            ground            if let key { keyWord(key) }            if let figure {                figureReading(figure)            } else {                object(width * metrics.objectFraction)                    .position(x: width * 0.5, y: size.height * metrics.objectCentre)                if wide {                    wideLines                } else {                    if line != nil || small != nil { ruleLine }                    lines                }            }        }        .frame(width: size.width, height: size.height)    }    @ViewBuilder private var ground: some View {        switch paper {        case .outline:            CardOutline(corner: metrics.corner).stroke(                theme.print(.pencil).opacity(theme.cards.emptyOutlineOpacity),                style: StrokeStyle(                    lineWidth: CardStockKnobs.cardOutlineRuleWidth, lineCap: .round, dash: theme.cards.emptyOutlineDash)            )        case .stock(let tint):            PaperSurface(dye: tint.paper, edge: .cut, seed: seed)                .overlay {                    // The tile's printed frame, once: a single hairline inside the edge.                    RoundedRectangle(cornerRadius: width * metrics.frameCorner, style: .continuous)                        .strokeBorder(                            tone(Double(CardStockKnobs.cardFrameInkOpacity)),                            lineWidth: max(                                CardStockKnobs.cardFrameLineWidthMin, width * CardStockKnobs.cardFrameLineWidthFraction))                        .padding(width * metrics.frameInset)                }                .modifier(PaperLift(shadow: .resting))                .accessibilityHidden(true)        }    }    /// The field's name: one line, or two when it is longer — a card never    /// cuts a name off ("minutes to re…", architect 13 Oct 2026). Two lines    /// share the room over the object and are set a little smaller.    /// A card's words are never set under the theme's caption size: a long    /// one wraps and then cuts at a word, and never shrinks to fit (the    /// architect's frame rule, 16 Oct 2026).    private func legible(_ size: CGFloat) -> CGFloat { max(size, theme.scale[.typeCaptionSize]) }    private func keyWord(_ key: String) -> some View {        let place = metrics.keyPlace(key, face: theme.type.meta, width: width, rowWidth: size.width)        let (keySize, span) = (place.size, place.span)        return Text(InkFit.fitting(key, face: theme.type.meta, size: keySize, width: span,                                   lines: CardStockKnobs.cardKeyLineLimit))            .accessibilityLabel(key)            .font(theme.type.meta(keySize))            .foregroundStyle(tone(Double(CardStockKnobs.cardKeyInkOpacity)))            .lineLimit(CardStockKnobs.cardKeyLineLimit)            .multilineTextAlignment(place.leading ? .leading : .center)            // Its two lines stand whole about the key's centre: a box one            // caption line high dropped the second and cut the name            // ("notificati…", "on this d…" on Storage, walker291).            .fixedSize(horizontal: false, vertical: true)            .frame(                width: span,                height: size.height * metrics.keyBox,                alignment: place.leading ? .leading : .center)            .position(x: place.centre, y: size.height * metrics.keyCentre)    }    @ViewBuilder private var ruleLine: some View {        if rule != .none {            Rectangle()                .fill(rule == .red ? theme.print(.red) : tone(Double(CardStockKnobs.cardRuleInkOpacity)))                .frame(                    width: width * CardStockKnobs.toolCardRuleWidth,                    height: max(CardStockKnobs.toolCardRuleHairlineMin, width * CardStockKnobs.toolCardRuleHairlineFraction)                        * (rule == .red ? CardStockKnobs.cardRedRuleWidthMultiplier : 1)                )                .position(x: width * 0.5, y: size.height * CardStockKnobs.toolCardRuleCentre)        }    }    @ViewBuilder private var lines: some View {        if let line {            let face = pencilled ? theme.type.meta : theme.type.title            let lineSize = legible(metrics.lineSize(width: width)                * (pencilled ? CardStockKnobs.cardPencilledLineSizeMultiplier : paired ? metrics.pairedScale : 1))            let span = width * (1 - CardStockKnobs.cardLineWidthInsetMultiplier * metrics.inset)            // Under the rule the line wraps to a second line rather than            // shrink, and a line two do not hold cuts at a word: a card never            // sets its words under the caption size (architect, 16 Oct 2026).            Text(InkFit.fitting(line, face: face, size: lineSize, width: span, lines: lineLines))                .accessibilityLabel(line)                .font(face.font(lineSize))                .foregroundStyle(lineColour)                .fixedSize(horizontal: false, vertical: true)                .multilineTextAlignment(.center)                .frame(                    width: span,                    height: paired ? nil : size.height * metrics.lineBox)                .position(                    x: width * 0.5,                    y: size.height * (paired ? metrics.pairedLineCentre : metrics.lineBoxCentre)                )        }        if paired || line == nil, let small {            // In the hand, whose swash a shrunk Text would cut: sized by `InkFit`.            let lineWidth = width * (1 - CardStockKnobs.cardLineWidthInsetMultiplier * metrics.inset)            let set = InkFit.set(                small, face: theme.type.hand,                preferred: metrics.smallSize(width: width) * CardStockKnobs.cardSmallPreferredSizeMultiplier,                width: lineWidth, lines: 1, floor: CardStockKnobs.cardSmallInkFitFloor, scale: theme.scale)            Text(set.words)                .accessibilityLabel(small)                .font(theme.type.hand(set.size))                .foregroundStyle(smallInk.map(theme.print) ?? tone(Double(CardStockKnobs.cardSmallInkOpacity)))                .fixedSize(horizontal: false, vertical: true)                .frame(width: lineWidth)                .position(x: width * 0.5, y: size.height * (paired ? metrics.pairedSmallCentre : metrics.lineBoxCentre))        }    }    /// One scalar shape in a narrow card or a whole row: the figure on    /// one line, with its complete caption beneath it.    private func figureReading(_ figure: String) -> some View {        VStack(spacing: CardStockKnobs.cardWideStackGap) {            Text(figure)                .font(theme.type.display(InkFit.figureSize(figure, face: theme.type.display,                    preferred: width * metrics.objectFraction * CardObjectKnobs.cardObjectFigureTypeFraction,                    width: max(0, size.width - width * CardStockKnobs.cardWideTrailingInsetMultiplier * metrics.inset), scale: theme.scale)))                .foregroundStyle(tone(Double(CardObjectKnobs.cardObjectFigureInkOpacity)))                .lineLimit(1)                .fixedSize(horizontal: true, vertical: true)            if let line {                Text(line)                    .font(theme.type.title(legible(metrics.lineSize(width: width))))                    .foregroundStyle(lineColour)                    .fixedSize(horizontal: false, vertical: true)            }            if let small {                Text(small)                    .font(theme.type.hand(legible(metrics.smallSize(width: width))))                    .foregroundStyle(smallInk.map(theme.print) ?? tone(Double(CardStockKnobs.cardSmallInkOpacity)))                    .fixedSize(horizontal: false, vertical: true)            }        }        .multilineTextAlignment(.center)        .frame(width: max(0, size.width - width * CardStockKnobs.cardWideTrailingInsetMultiplier * metrics.inset))        .position(x: size.width * 0.5, y: size.height * 0.5)    }    /// A wide card's complete words, beside the object.    private var wideLines: some View {        let leading = width * (1 + metrics.inset)        let span = size.width - leading - width * CardStockKnobs.cardWideTrailingInsetMultiplier * metrics.inset        return VStack(alignment: .leading, spacing: CardStockKnobs.cardWideStackGap) {            if let line {                let face = pencilled ? theme.type.meta : theme.type.title                let lineSize = legible(metrics.lineSize(width: width) * (pencilled ? 1 : CardStockKnobs.cardWideLineSizeMultiplier))                // A wide card's words are whole, but a line held to fewer                // lines (an address) is cut there, at a word.                Text(lineLines < CardStockKnobs.cardLineLines                    ? InkFit.fitting(line, face: face, size: lineSize, width: max(0, span), lines: lineLines) : line)                    .accessibilityLabel(line)                    .font(face.font(lineSize))                    .foregroundStyle(pencilled ? theme.print(.pencil) : tone(Double(CardStockKnobs.cardWideLineInkOpacity)))                    .fixedSize(horizontal: false, vertical: true)                    .multilineTextAlignment(.leading)            }            if let small {                Text(small)                    .font(theme.type.hand(legible(metrics.smallSize(width: width) * CardStockKnobs.cardWideSmallSizeMultiplier)))                    .foregroundStyle(smallInk.map(theme.print) ?? tone(Double(CardStockKnobs.cardSmallInkOpacity)))                    .fixedSize(horizontal: false, vertical: true)                    .multilineTextAlignment(.leading)            }        }        .frame(width: max(0, span), alignment: .leading)        .position(x: leading + max(0, span) * 0.5, y: size.height * 0.5)    }    private var lineColour: Color {        if let lineInk { return theme.print(lineInk) }        return pencilled ? theme.print(.pencil) : tone(Double(CardStockKnobs.cardLineInkOpacity))    }    /// The lettering's ink at a strength: one ink on every stock.    private func tone(_ strength: Double) -> Color { theme.print(.ink).opacity(strength) }}/// The sizes, counts and timings CardStock draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum CardStockKnobs {    static let cardContentInset: CGFloat = 0.0625    static let cardFrameCorner: CGFloat = 0.03    static let cardFrameInkOpacity: CGFloat = 0.16    static let cardFrameInset: CGFloat = 0.045    static let cardFrameLineWidthFraction: CGFloat = 0.005    static let cardFrameLineWidthMin: CGFloat = 0.5    static let cardKeyBox: CGFloat = 0.12    static let cardKeyCentre: CGFloat = 0.108    static let cardKeyInkOpacity: CGFloat = 0.6    static let cardKeyLineLimit = 2    static let cardKeySizeFraction: CGFloat = 0.092    static let cardKeySizeMax: CGFloat = 10    static let cardKeySizeMin: CGFloat = 8    static let cardKeyWidthInsetMultiplier: CGFloat = 4    static let cardLineBox: CGFloat = 0.19    static let cardLineBoxCentre: CGFloat = 0.855    static let cardLineInkOpacity: CGFloat = 0.9    static let cardLineSizeFraction: CGFloat = 0.125    static let cardLineSizeMax: CGFloat = 14    static let cardLineSizeMin: CGFloat = 10.5    static let cardLineWidthInsetMultiplier: CGFloat = 2.4    static let cardObjectCentre: CGFloat = 0.4    static let cardObjectFraction: CGFloat = 0.7    static let cardOutlineRuleWidth: CGFloat = 1    static let cardPairedFromWidth: CGFloat = 76    static let cardPairedLineCentre: CGFloat = 0.795    static let cardPairedScale: CGFloat = 0.92    static let cardPairedSmallCentre: CGFloat = 0.89    static let cardPencilledLineSizeMultiplier: CGFloat = 0.9    static let cardRedRuleWidthMultiplier: CGFloat = 1.5    static let cardRuleInkOpacity: CGFloat = 0.3    static let cardLineLines = 2    static let cardSmallInkFitFloor: CGFloat = 0.6    static let cardSmallInkOpacity: CGFloat = 0.62    static let cardSmallPreferredSizeMultiplier: CGFloat = 0.88    static let cardSmallSizeFraction: CGFloat = 0.125    static let cardSmallSizeMax: CGFloat = 14    static let cardSmallSizeMin: CGFloat = 10.5    static let cardStampTiltDegrees: CGFloat = -9    static let cardWideLineInkOpacity: CGFloat = 0.9    static let cardWideLineSizeMultiplier: CGFloat = 1.1    static let cardWideSmallSizeMultiplier: CGFloat = 1.1    static let cardWideStackGap: CGFloat = 2    static let cardWideThreshold: CGFloat = 1    static let cardWideTrailingInsetMultiplier: CGFloat = 2    static let toolCardRuleCentre: CGFloat = 0.745    static let toolCardRuleHairlineFraction: CGFloat = 0.006    static let toolCardRuleHairlineMin: CGFloat = 0.5    static let toolCardRuleWidth: CGFloat = 0.45}