Cotton code
323 lines · 13.8 KB · SwiftRaw
// Home's projects as a board of bottle caps.//// The owner's design of 2026-09-13, from a reference picture: every active// project is an enamelled bottle cap with its name printed on the face, laid// out four to a row on a plaster ground; the rest of a row that a count does// not fill is bare caps with a plus, and "New project" is the plus over the// grid. It is the first screen of a warmer, more physical phone — "delightful,// joyous software" — and it is deliberately unlike the settings-grammar cards// under it, which change later or not at all.//// THE CAP IS A PHOTOGRAPH, THE NAME IS TYPE. The thirteen caps in// `Media.xcassets` (twelve enamels and the bare one) were generated once, from// one master, so they share a geometry, a lighting and a lens; the name is// set live in `CottonFonts.cap` and BLENDED onto the enamel — multiplied when// the ink is dark, screened when it is cream — so the cap's own scratches and// chips show through the letters the way print on metal wears. A rename is a// redraw, not a new picture, and adding a project costs nothing.//// WHICH CAP A PROJECT GETS is decided here, from the slug, and nowhere else:// a project row carries no colour (`cotton_memory_projects` has none, and the// colour rule wants none), so `CapColour.assign` folds the slug through a// FIXED hash — not `Hasher`, which is seeded per launch — and takes the next// free enamel in slug order when two projects land on one. The same set of// slugs is the same board every launch and on every phone; a project keeps// its cap until a neighbour with a colliding slug is added, which with twelve// enamels and a handful of projects is rare.//// THE COLOUR RULE. The ink on a cap is cream or near-black and does not flip// with the theme, because it is not a colour of the design system: it is paint// on a photograph, fixed the way the photograph is. `PaletteGuardTests` exempts// this file from the CHANNELS sweep for that reason and from nothing else. The// two paints are `PrintInk`, below, and Home's tool objects print with the// same two (`Paper/ToolPrint.swift`).//import SwiftUI// MARK: - The twelve enamels/// The enamels a cap comes in, in the board's order. The raw value is the/// imageset's name less its `cap-` prefix.public enum CapColour: String, CaseIterable, Sendable {    case cream, red, navy, yellow, green, silver, orange, burgundy, sky, pink, black, teal    /// The imageset in `Media.xcassets`.    public var asset: String { "cap-\(rawValue)" }    /// The light enamels take dark ink; the rest take cream.    public var inkIsDark: Bool {        switch self {        case .cream, .yellow, .silver, .sky, .pink: return true        case .red, .navy, .green, .orange, .burgundy, .black, .teal: return false        }    }    /// Which of the two paints this enamel takes — see `PrintInk`.    public var paint: PrintInk { inkIsDark ? .dark : .cream }    /// The ink itself. Two fixed paints, not palette roles — see the header.    public var ink: Color { paint.color }    /// The blend that makes the ink read as PRINTED rather than pasted: dark    /// ink darkens the enamel and cream ink lightens it, so a scratch or a    /// chip under a letter still shows.    public var blend: BlendMode { paint.blend }    /// Each slug's enamel. Deterministic in the SET of slugs, not their order:    /// the slugs are walked alphabetically, each takes the enamel its hash    /// names or the next free one after it, and only once every enamel is    /// taken do two projects share.    public static func assign(_ slugs: [String]) -> [String: CapColour] {        var taken = Set<CapColour>()        var out: [String: CapColour] = [:]        for slug in Set(slugs).sorted() {            let start = Int(fnv1a(slug) % UInt64(allCases.count))            var pick = allCases[start]            for offset in 0..<allCases.count {                let candidate = allCases[(start + offset) % allCases.count]                if !taken.contains(candidate) {                    pick = candidate                    break                }            }            taken.insert(pick)            out[slug] = pick        }        return out    }    /// FNV-1a over the slug's UTF-8 — the same number on every launch and    /// every device, which `Hasher` is not.    public static func fnv1a(_ text: String) -> UInt64 { StableHash.fnv1a(text) }}// MARK: - The board's arithmeticpublic enum CapBoard {    /// Caps to a row, as `scale` sets it (`cap_board_columns`).    public static func columns(in scale: ThemeScale) -> Int { ProjectCapsKnobs.capBoardColumns }}// MARK: - One cap/// One project's cap: the enamel, the name blended onto it, the short rule/// under the name. Square; the caller decides the side.////// **It draws on BOTH hosts.** The enamel used to be `Image(_:bundle: .module)`/// inside `#if canImport(UIKit)`, and the `#else` was a bare `Text(name)` — no/// font, no enamel, squeezed into whatever frame the caller had set. That is/// what the Mac walk photographed (finding 7): "T…" in the sidebar at 22pt,/// "…" on a scope chip at 18pt, and "The Walk" in the SYSTEM font filling the/// project page's 118pt picture slot. The picture is reachable on the Mac —/// `CottonMedia.image` reads it out of the located bundle, compiled catalogue/// or raw imageset, which is how `AllProjectsRing` draws the same enamels —/// and so is the cap face (`CottonFonts.cap`). So there is no platform branch/// here at all now:/// one view, two hosts, and a name that cannot fall back to system text.public struct ProjectCap: View {    @Environment(\.theme) private var theme    public let name: String    public let colour: CapColour    /// The cap's side, when the caller already knows it — a board of caps does,    /// and a board of caps each measuring itself is one layout container per    /// cap for a figure the grid decided. `nil` measures, which is what a chip    /// and a page's picture slot want.    public let side: CGFloat?    public init(name: String, colour: CapColour, side: CGFloat? = nil) {        self.name = name        self.colour = colour        self.side = side    }    public var body: some View {        if let side {            // A cap is a photograph with a name printed on it and nothing in            // it moves, so it is drawn once and kept — on the SIZED path            // alone, which is the board's (as `ToolCard.sized`).            // Rasterised, the subtree is ONE element with no text in it, and            // the tree read the cap as its asset's name ("cap-navy"); the cap            // says its printed name on both paths.            face(side: side).drawingGroup()                .accessibilityElement(children: .ignore)                .accessibilityLabel(name)        } else {            GeometryReader { geo in                face(side: geo.size.width)            }            .aspectRatio(1, contentMode: .fit)            .accessibilityElement(children: .ignore)            .accessibilityLabel(name)        }    }    @ViewBuilder private func face(side: CGFloat) -> some View {        switch theme.cap.texture {        case .enamel: enamel(side: side)        case .flat: flat(side: side)        }    }    /// A flat disc in the enamel's colour, the name set plainly on it.    private func flat(side: CGFloat) -> some View {        ZStack {            Circle().fill(colour.flat.color)            // Whole words, cut at a word, never mid-word (the card-text rule).            let set = InkFit.set(name, face: theme.type.cap, preferred: side * ProjectCapsKnobs.capFlatNameSize,                                 width: side * ProjectCapsKnobs.capFlatNameWidth, lines: ProjectCapsKnobs.capNameLines,                                 scale: theme.scale)            Text(set.words)                .accessibilityLabel(name)                .font(theme.type.cap(set.size))                .multilineTextAlignment(.center)                .lineLimit(ProjectCapsKnobs.capNameLines)                .frame(width: side * ProjectCapsKnobs.capFlatNameWidth, height: side * ProjectCapsKnobs.capFlatNameHeight)                .foregroundStyle(colour.ink)        }        .frame(width: side, height: side)    }    private func enamel(side: CGFloat) -> some View {        ZStack {            CottonMedia.image(colour.asset)?                .resizable()                .interpolation(.medium)                .scaledToFit()                // The enamel is the cap's material; its NAME is the text                // printed on it, below.                .accessibilityHidden(true)            let set = InkFit.set(name, face: theme.type.cap, preferred: side * ProjectCapsKnobs.capEnamelNameSize,                                 width: side * ProjectCapsKnobs.capEnamelPrintWidth, lines: ProjectCapsKnobs.capNameLines,                                 scale: theme.scale)            VStack(spacing: side * ProjectCapsKnobs.capEnamelPrintGap) {                Text(set.words)                    .accessibilityLabel(name)                    .font(theme.type.cap(set.size))                    .multilineTextAlignment(.center)                    .lineLimit(ProjectCapsKnobs.capNameLines)                Capsule()                    .frame(                        width: side * ProjectCapsKnobs.capEnamelRuleWidth,                        height: max(ProjectCapsKnobs.capEnamelRuleHeightMin, side * ProjectCapsKnobs.capEnamelRuleHeight)                    )            }            // The enamel's face is ~64 % of the cap's side once the pad            // and the skirt are taken off; the print stays inside it.            .frame(width: side * ProjectCapsKnobs.capEnamelPrintWidth, height: side * ProjectCapsKnobs.capEnamelPrintHeight)            .foregroundStyle(colour.ink)            .blendMode(colour.blend)            .offset(y: -side * ProjectCapsKnobs.capEnamelPrintLift)        }        .compositingGroup()        .frame(width: side, height: side)    }}/// The bare cap that fills out a row — a plus on unpainted steel.////// The plus is drawn, not baked: the photograph's own plus is a hairline at/// a phone's cap size, so a glyph in tertiary ink is multiplied onto the/// steel over it — printed, like the names, and legible.public struct EmptyCap: View {    @Environment(\.theme) private var theme    /// The cap's side, when the caller knows it — `ProjectCap.side`'s reason,    /// and the bare caps sit in the same board.    public let side: CGFloat?    /// Whether the cap carries its printed plus — a cap that adds (new or    /// join). An empty link card's cap is the cap alone, faint (architect,    /// 13 Oct 2026): the plus is the add card's, never the object's.    public let adds: Bool    public init(side: CGFloat? = nil, adds: Bool = true) {        self.side = side        self.adds = adds    }    public var body: some View {        if let side {            // Steel and a printed plus: nothing moves. Rasterised like a            // painted cap, and on the sized path for the same reason.            face(side: side).drawingGroup()        } else {            GeometryReader { geo in                face(side: geo.size.width)            }            .aspectRatio(1, contentMode: .fit)        }    }    private func face(side: CGFloat) -> some View {        ZStack {            switch theme.cap.texture {            case .enamel:                CottonMedia.image(CapBoard.emptyAsset)?                    .resizable()                    .interpolation(.medium)                    .scaledToFit()                    .accessibilityHidden(true)            case .flat:                Circle().strokeBorder(theme.colors.hairline.color, lineWidth: theme.scale.stroke)            }            if adds {                Image(systemName: Glyph.symbol("plus") ?? "plus")                    .font(theme.type.interface((side * ProjectCapsKnobs.capEmptyPlusSize), weight: .light))                    .foregroundStyle(theme.colors.inkTertiary.color)                    .blendMode(.multiply)            }        }        .compositingGroup()        .frame(width: side, height: side)    }}extension CapBoard {    public static let emptyAsset = "cap-empty"    /// The lift off the plaster. One shadow for every cap on the board.    public static func shadow<V: View>(_ view: V) -> some View {        view.modifier(CapBoardShadow())    }}/// `CapBoard.shadow`, in the theme's shadow colour and only when the theme/// casts one.private struct CapBoardShadow: ViewModifier {    @Environment(\.theme) private var theme    func body(content: Content) -> some View {        if theme.texture.shadow == .none {            content        } else {            content.shadow(                color: theme.colors.shadow.color.opacity(Double(ProjectCapsKnobs.capBoardShadowOpacity)),                radius: ProjectCapsKnobs.capBoardShadowRadius,                x: 0,                y: ProjectCapsKnobs.capBoardShadowY            )        }    }}/// The sizes, counts and timings ProjectCaps draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ProjectCapsKnobs {    static let capBoardColumns = 4    static let capBoardShadowOpacity: CGFloat = 0.22    static let capBoardShadowRadius: CGFloat = 7    static let capBoardShadowY: CGFloat = 5    static let capEmptyPlusSize: CGFloat = 0.2    static let capEnamelNameSize: CGFloat = 0.205    static let capEnamelPrintGap: CGFloat = 0.035    static let capEnamelPrintHeight: CGFloat = 0.56    static let capEnamelPrintLift: CGFloat = 0.005    static let capEnamelPrintWidth: CGFloat = 0.6    static let capEnamelRuleHeight: CGFloat = 0.012    static let capEnamelRuleHeightMin: CGFloat = 1.2    static let capEnamelRuleWidth: CGFloat = 0.15    static let capFlatNameHeight: CGFloat = 0.6    static let capFlatNameSize: CGFloat = 0.19    static let capFlatNameWidth: CGFloat = 0.7    static let capNameLines = 3}