Cotton code
467 lines · 18.0 KB · SwiftRaw
// Cotton Vault's own controls: every visible piece is drawn here from the// look's roles (colour, type, space, corner), never the platform's stock// styling, so the iPhone and Android come out the same design.import CottonKitimport SwiftUI// VaultAsking and VaultWords live here, outside VaultModel's iOS-only block,// because these controls (the toast every app's Toast.swift may draw) compile// on the Mac too./// A question asked before an act is sent.struct VaultAsking: Identifiable {    let id = UUID()    let confirm: VaultConfirm    let tone: VaultTone    let answer: (Bool) -> Void}/// The words Vault's own controls say that no answer carries (Hide, Generate,/// the kind picker's question): the kit's `vault` line set.enum VaultWords {    static func line(_ path: String, _ fills: [String: String] = [:]) -> String {        ShellLines.line("vault", path, fills)    }}extension VaultLook {    /// A look with nothing in it: what a Vault view reads before the root has    /// set the core's.    static let blank = VaultLook(fonts: [:], colours: [:], type: [:], space: [:], corners: [:], roles: [:])}extension EnvironmentValues {    /// The look the shell's Vault-shaped pieces draw with (Health's screens, the standing cards).    @Entry var vault: VaultLook = .blank}/// The glyph name for a symbol the core gives (SHAPES' list and each kind/// id, drawn by `VaultGlyphView`), and for an act with no symbol of its own.enum VaultGlyph {    static func name(_ symbol: String) -> String { symbol }    static func of(_ act: VaultAct) -> String {        if let symbol = act.symbol { return symbol }        switch act.id {        case "copy", "copy_username", "copy_password", "copy_code": return "copy"        case "reveal": return "eye"        case "favourite": return "star"        case "unfavourite": return "star.slash"        case "open", "open_site": return "safari"        case "edit": return "pencil"        case "trash": return "trash"        case "restore": return "arrow.uturn.left"        default: return "chevron"        }    }}/// A row's or item's picture: typed initials on a grey tint, or the kind's glyph.struct VaultPictureView: View {    let picture: VaultPicture    var size: CGFloat?    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        let side = size ?? look.gap("picture")        ZStack {            RoundedRectangle(cornerRadius: look.corner("picture"), style: .continuous)                .fill(look.colour("tint.\(picture.tint)", scheme))            if let symbol = picture.symbol {                VaultGlyphView(symbol: symbol, ink: look.colour("on_tint", scheme), size: look.gap("xl"))            } else {                Text(picture.initials)                    .vault(look, "initials", "on_tint")                    .minimumScaleFactor(0.6)                    .lineLimit(1)            }        }        .frame(width: side, height: side)        .accessibilityHidden(true)    }}/// How a Vault button is filled.enum VaultButtonFill {    /// The main action: solid `accent` (a confirm's danger yes: solid `danger`).    case main    /// Any other: the `surface` fill, in `text` (or its tone's ink).    case quiet    /// Words alone, in the tone's ink (Cancel, Hide).    case plain}/// Vault's button (SHAPES "Decided" 7): neutral ones on `surface` in `text`;/// only the main action (`tone: accent`) is solid `accent`; a `danger` act is/// `danger` text on `surface`, and only its confirm's yes is solid `danger`.struct VaultButton: View {    let label: String    var tone: VaultTone = .neutral    var fill: VaultButtonFill = .quiet    var wide = false    let action: () -> Void    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    @Environment(\.isEnabled) private var enabled    /// The solid colour role, when this is a main action.    private var solid: String? {        guard fill != .plain else { return nil }        if tone == .accent { return "accent" }        if fill == .main { return tone == .danger ? "danger" : "accent" }        return nil    }    var body: some View {        Button(action: action) {            Text(label)                .font(look.font("button"))                .lineLimit(1)                .foregroundStyle(enabled ? ink : look.colour("disabled", scheme))                .padding(.horizontal, fill == .plain ? look.gap("s") : look.gap("l"))                .padding(.vertical, look.gap("s"))                .frame(minWidth: fill == .plain ? look.gap("tap") : nil, minHeight: look.gap("tap"))                .frame(maxWidth: wide ? .infinity : nil)                .background {                    if fill != .plain {                        // A main action that cannot run yet is drawn quiet, not in its solid colour (the iPhone walk,                        // 24 Nov 2026: Send code stood in full blue before a number was typed).                        RoundedRectangle(cornerRadius: look.corner("button"), style: .continuous)                            .fill(look.colour(enabled ? (solid ?? "surface") : "surface", scheme))                    }                }                .contentShape(Rectangle())        }        .buttonStyle(VaultPressStyle())    }    private var ink: Color {        if solid != nil && enabled { return look.colour("on_accent", scheme) }        switch tone {        case .neutral, .accent: return look.colour("text", scheme)        default: return look.colour(tone.role, scheme)        }    }}/// A round glyph button (a row's quick act, a field's Copy).struct VaultIconButton: View {    let symbol: String    let label: String    var tone: VaultTone = .neutral    let action: () -> Void    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Button(action: action) {            VaultGlyphView(symbol: symbol, ink: look.colour(tone == .neutral ? "secondary" : tone.role, scheme), size: look.gap("xl"))                .frame(width: look.gap("tap"), height: look.gap("tap"))                .contentShape(Rectangle())        }        .buttonStyle(VaultPressStyle())        .accessibilityLabel(label)    }}/// A press dims; nothing else moves.struct VaultPressStyle: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? 0.55 : 1)    }}/// A filter chip.struct VaultChipView: View {    let chip: VaultChip    let action: () -> Void    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Button(action: action) {            Text(chip.label)                .vault(look, "chip", chip.on ? "on_accent" : "text")                .padding(.horizontal, look.gap("m"))                .padding(.vertical, look.gap("s"))                .background(Capsule().fill(look.colour(chip.on ? "accent" : "field", scheme)))        }        .buttonStyle(VaultPressStyle())        .accessibilityAddTraits(chip.on ? .isSelected : [])        .accessibilityIdentifier("vault-chip-\(chip.id)")    }}/// A section's title over its rows.struct VaultSectionTitle: View {    let title: String    var detail: String?    @Environment(\.vault) private var look    var body: some View {        VStack(alignment: .leading, spacing: look.gap("xs")) {            Text(title.uppercased()).vault(look, "section", "tertiary")            if let detail { Text(detail).vault(look, "row_detail", "secondary").fixedSize(horizontal: false, vertical: true) }        }        .frame(maxWidth: .infinity, alignment: .leading)        .padding(.top, look.gap("xl"))        .padding(.bottom, look.gap("s"))        .accessibilityAddTraits(.isHeader)    }}/// A group of rows on the surface, rounded, with hairlines between.struct VaultCard<Content: View>: View {    @ViewBuilder let content: Content    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        VStack(spacing: 0) { content }            .background(RoundedRectangle(cornerRadius: look.corner("card"), style: .continuous).fill(look.colour("surface", scheme)))            .clipShape(RoundedRectangle(cornerRadius: look.corner("card"), style: .continuous))    }}/// The hairline between two rows.struct VaultHairline: View {    var inset: CGFloat = 0    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Rectangle().fill(look.colour("separator", scheme)).frame(height: 1 / 3).padding(.leading, inset)    }}/// A mark (weak, reused, old): a small word in its tone.struct VaultMarkView: View {    let mark: VaultMark    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Text(mark.label)            .vault(look, "label", mark.tone.role)            .padding(.horizontal, look.gap("s"))            .padding(.vertical, look.gap("xxs"))            .background(Capsule().fill(look.colour(mark.tone.wash, scheme)))    }}/// A screen's large title, with what stands at its trailing edge.struct VaultLargeTitle<Trailing: View>: View {    let title: String    @ViewBuilder var trailing: Trailing    @Environment(\.vault) private var look    var body: some View {        HStack(alignment: .firstTextBaseline) {            Text(title).vault(look, "large_title").accessibilityAddTraits(.isHeader)            Spacer(minLength: look.gap("s"))            trailing        }        .padding(.top, look.gap("s"))    }}/// A pushed screen's top bar: back, a title, what stands at its trailing edge.struct VaultTopBar<Trailing: View>: View {    var title: String = ""    let back: () -> Void    @ViewBuilder var trailing: Trailing    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        HStack(spacing: look.gap("s")) {            Button(action: back) {                VaultGlyphView(symbol: "back", ink: look.colour("text", scheme), size: look.gap("xl"))                    .frame(width: look.gap("tap"), height: look.gap("tap"))                    .contentShape(Rectangle())            }            .buttonStyle(VaultPressStyle())            .accessibilityLabel(ShellLines.line("chrome", "lifted.back"))            .accessibilityIdentifier("vault-back")            Text(title).vault(look, "headline").lineLimit(1)            Spacer(minLength: 0)            trailing        }        .padding(.horizontal, look.gap("gutter") - look.gap("m"))        .frame(minHeight: look.gap("tap"))    }}/// A text field on the look's field ground.struct VaultTextField: View {    let placeholder: String    @Binding var text: String    var mono = false    var secure = false    var multiline = false    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Group {            if secure {                SecureField("", text: $text, prompt: prompt)            } else if multiline {                TextField("", text: $text, prompt: prompt, axis: .vertical).lineLimit(3...8)            } else {                TextField("", text: $text, prompt: prompt)            }        }        .textFieldStyle(.plain)        .font(look.font(mono ? "secret" : "body"))        .foregroundStyle(look.colour("text", scheme))        .tint(look.colour("accent", scheme))        .padding(.horizontal, look.gap("m"))        .padding(.vertical, look.gap("m"))        .frame(minHeight: look.gap("tap"))        .background(RoundedRectangle(cornerRadius: look.corner("field"), style: .continuous).fill(look.colour("field", scheme)))    }    private var prompt: Text {        Text(placeholder).foregroundStyle(look.colour("tertiary", scheme))    }}/// A switch drawn in the look: a track and a knob.struct VaultSwitch: View {    let label: String    let on: Bool    let action: () -> Void    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Button(action: action) {            HStack {                Text(label).vault(look, "body")                Spacer(minLength: look.gap("s"))                ZStack(alignment: on ? .trailing : .leading) {                    Capsule().fill(look.colour(on ? "accent" : "separator", scheme))                        .frame(width: look.gap("tap") + look.gap("s"), height: look.gap("xl") + look.gap("xs") + look.gap("xxs"))                    Circle().fill(look.colour(on ? "on_accent" : "raised", scheme))                        .padding(look.gap("xxs"))                        .frame(width: look.gap("xl") + look.gap("xs") + look.gap("xxs"), height: look.gap("xl") + look.gap("xs") + look.gap("xxs"))                }            }            .frame(minHeight: look.gap("tap"))            .contentShape(Rectangle())        }        .buttonStyle(VaultPressStyle())        .accessibilityAddTraits(on ? .isSelected : [])        .accessibilityValue(on ? "1" : "0")    }}/// The receipt, in Vault's look: the toast every Vault screen speaks into/// (`ToastStrip` draws this when the look is set).struct VaultToastView: View {    let toast: CottonToast    let look: VaultLook    let onUndo: () -> Void    let onDismiss: () -> Void    @Environment(\.colorScheme) private var scheme    var body: some View {        HStack(spacing: look.gap("m")) {            Text(toast.message)                .vault(look, "body", toast.tone == .error ? "danger" : "text")                .lineLimit(toast.tone == .error || toast.tone == .warning ? 6 : 3)                .frame(maxWidth: .infinity, alignment: .leading)            if toast.undo != nil {                Button(action: onUndo) {                    Text(VaultWords.line("item.undo")).vault(look, "button", "accent")                        .frame(minWidth: look.gap("tap"), minHeight: look.gap("tap"))                        .contentShape(Rectangle())                }                .buttonStyle(VaultPressStyle())            }        }        .padding(.horizontal, look.gap("l"))        .padding(.vertical, look.gap("m"))        .background(RoundedRectangle(cornerRadius: look.corner("card"), style: .continuous).fill(look.colour("raised", scheme)))        .overlay(RoundedRectangle(cornerRadius: look.corner("card"), style: .continuous).stroke(look.colour("separator", scheme)))        .fixedSize(horizontal: false, vertical: true)        .padding(.horizontal, look.gap("gutter"))        // Above the bottom bar (SHAPES "Decided" 11), not at the shell's top edge.        .padding(.bottom, look.gap("row_height") + look.gap("s"))        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("toast-look")        .accessibilityAction(named: "Dismiss", onDismiss)        .onTapGesture(perform: onDismiss)    }}/// An act's question, over the screen, in Vault's look.struct VaultConfirmView: View {    let asking: VaultAsking    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        ZStack {            look.colour("scrim", scheme).ignoresSafeArea().onTapGesture { asking.answer(false) }            VStack(alignment: .leading, spacing: look.gap("s")) {                Text(asking.confirm.title).vault(look, "headline").fixedSize(horizontal: false, vertical: true)                if !asking.confirm.body.isEmpty {                    Text(asking.confirm.body).vault(look, "body", "secondary").fixedSize(horizontal: false, vertical: true)                }                HStack(spacing: look.gap("s")) {                    Spacer(minLength: 0)                    if !asking.confirm.no.isEmpty {                        VaultButton(label: asking.confirm.no) { asking.answer(false) }                            .accessibilityIdentifier("vault-confirm-no")                    }                    VaultButton(label: asking.confirm.yes, tone: asking.tone == .danger ? .danger : .accent, fill: .main) { asking.answer(true) }                        .accessibilityIdentifier("vault-confirm-yes")                }                .padding(.top, look.gap("xl") - look.gap("s"))            }            .padding(look.gap("xl"))            .background(RoundedRectangle(cornerRadius: look.corner("card"), style: .continuous).fill(look.colour("sheet", scheme)))            .padding(look.gap("gutter"))        }        .accessibilityAddTraits(.isModal)    }}/// Vault's own panel over the screen: a scrim, and its content rising from/// the foot on the sheet ground with the sheet corner. Cotton presents no/// system sheet (`NoBottomSheetsTests`); this is drawn in the window.struct VaultPanel<Content: View>: View {    let close: () -> Void    @ViewBuilder let content: Content    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        ZStack(alignment: .bottom) {            look.colour("scrim", scheme).ignoresSafeArea().onTapGesture(perform: close).accessibilityHidden(true)            VStack(spacing: 0) {                Capsule().fill(look.colour("separator", scheme))                    .frame(width: look.gap("xxxl"), height: look.gap("xs"))                    .padding(.top, look.gap("s"))                    .accessibilityHidden(true)                content            }            .frame(maxWidth: .infinity)            .background(                UnevenRoundedRectangle(topLeadingRadius: look.corner("sheet"), topTrailingRadius: look.corner("sheet"), style: .continuous)                    .fill(look.colour("sheet", scheme))                    .ignoresSafeArea(edges: .bottom)            )            .padding(.top, look.gap("xxxl"))            .gesture(DragGesture().onEnded { drag in if drag.translation.height > look.gap("xxxl") { close() } })            .transition(.move(edge: .bottom))        }        .accessibilityAddTraits(.isModal)        .accessibilityAction(.escape, close)    }}