Cotton code
325 lines · 14.5 KB · SwiftRaw
// The acts a store offers (`ActingRecords`), drawn once for every list and// page: plain typed buttons on the paper — "Connect Google", "Sync now",// "Disconnect" in red — with the reason the last one was not done under them,// the store's one typed line about the table over them (`listNote`), and a// value shown once (an assistant's new key) as a ruled block with Copy and// "I've saved it". An act that asks for a value first (`RecordAction.input`:// a new login's password) opens one field under the buttons; its words go to// the act and the field forgets them. Nothing here performs anything: the// list and the page hand each tap to their model.import CottonKitimport SwiftUI/// A row of acts, wrapping, and the reason the last one was not done.struct RecordActionButtons: View {    let actions: [RecordAction]    let problem: String?    /// `list-<table>` or `page-<table>`: each button's identifier is this and    /// the act's id.    let identifier: String    /// The store's typed line over the acts (`ActingRecords.listNote`).    var note: String? = nil    /// Page feet honour the source's placement; list controls stay plain.    var pageDye: PaperDye? = nil    /// A list's head "+" that opens the fold: given, the fold draws no "+"    /// of its own under the head (walker 604bcce6: Passwords' bare 12 pt    /// glyph), and the head's circle opens and closes it.    var headOpens: Binding<Bool>? = nil    let onTap: (RecordAction) -> Void    /// The act whose input is open, one at a time, and what is typed in it.    @State private var typing: RecordAction?    @State private var draft = ""    /// Whether a folded head ("+") has been opened to show its choices.    @State private var ownFanned = false    private var fanned: Bool {        get { headOpens?.wrappedValue ?? ownFanned }        nonmutating set { if let headOpens { headOpens.wrappedValue = newValue } else { ownFanned = newValue } }    }    /// Whether a head's acts fold into one "+": three or more acts that each    /// make a record by asking its fields (Passwords' five "New …" links wrapped    /// onto two lines above the list). One "+" opens them; a tap on a choice    /// closes the fold again.    static func folds(_ actions: [RecordAction]) -> Bool {        actions.count >= 3 && actions.allSatisfy { !$0.fields.isEmpty && $0.input == nil }    }    private var folded: Bool { pageDye == nil && Self.folds(actions) }    var body: some View {        if !actions.isEmpty || problem != nil || note != nil {            VStack(alignment: .leading, spacing: 2) {                if let note {                    Text(note)                        .paperBody(13, ink: .pencil)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.bottom, 6)                        .accessibilityIdentifier("\(identifier)-note")                }                if folded, headOpens == nil {                    PaperTypedButton(fanned ? "\u{2212}" : "+", size: 22) { fanned.toggle() }                        .accessibilityLabel(ShellLines.line("record", fanned ? "fan.close" : "fan.new"))                        .accessibilityIdentifier("\(identifier)-action-new")                }                PaperWrap(spacing: 18) {                    ForEach(folded && !fanned ? [] : actions) { action in                        if let pageDye, action.placement == .main {                            RecordInkPill(action.label, dye: pageDye) { tap(action) }                                .accessibilityIdentifier("\(identifier)-action-\(action.id)")                        } else {                            PaperTypedButton(action.label, destructive: action.placement == .away || action.confirmation?.destructive == true) { tap(action) }                                .accessibilityIdentifier("\(identifier)-action-\(action.id)")                        }                    }                }                if let typing, let input = typing.input {                    VStack(alignment: .leading, spacing: 8) {                        EnteredValueField(input: input, text: $draft, seed: "\(identifier)-\(typing.id)")                            .accessibilityIdentifier("\(identifier)-action-\(typing.id)-input")                        HStack(spacing: 18) {                            PaperTypedButton(typing.label) { submit(typing) }                                .disabled(!EnteredValue.isGiven(draft))                                .accessibilityIdentifier("\(identifier)-action-\(typing.id)-submit")                            PaperTypedButton("Cancel") {                                draft = ""                                self.typing = nil                            }                            .accessibilityIdentifier("\(identifier)-action-\(typing.id)-cancel")                        }                    }                    .padding(.top, 8)                }                if let problem {                    Text(problem)                        .paperBody(13, ink: .red)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("\(identifier)-action-problem")                }            }            .frame(maxWidth: .infinity, alignment: .leading)        }    }    private func tap(_ action: RecordAction) {        if action.input != nil {            draft = ""            typing = typing?.id == action.id ? nil : action        } else {            fanned = false            onTap(action)        }    }    /// Hands the act its words and forgets them here.    private func submit(_ action: RecordAction) {        guard EnteredValue.isGiven(draft) else { return }        let words = draft        draft = ""        typing = nil        onTap(action.entering(words))    }}/// What a typed value counts as. Pure, so the rule is a test's.enum EnteredValue {    /// Whether anything was typed: a field of spaces is nothing, but the words    /// themselves are handed on exactly as typed — never trimmed.    static func isGiven(_ words: String) -> Bool {        !words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty    }}/// One value typed under a button or a sealed row: a SECURE line on the/// form's pencil rule (as a token is typed on a connection's page), or several/// plain lines for a note's body.struct EnteredValueField: View {    @Environment(\.theme) private var theme    let input: RecordActionInput    @Binding var text: String    let seed: String    @FocusState private var focused: Bool    var body: some View {        Group {            if input.multiline {                // No autocorrection or capitals: the keyboard must not learn                // a sealed note's words.                PaperTextField(input.prompt, text: $text, axis: .vertical, lines: 3...12, focus: $focused)                    .textInputAutocapitalization(.never)                    .autocorrectionDisabled()            } else if input.secure {                VStack(alignment: .leading, spacing: 5) {                    SecureField(                        "", text: $text,                        prompt: Text(input.prompt)                            .font(CottonFonts.type(theme.scale.titleSize - 1))                            .foregroundStyle(theme.print(.pencil))                    )                    .textInputAutocapitalization(.never)                    .autocorrectionDisabled()                    .font(CottonFonts.type(theme.scale.titleSize - 1))                    .foregroundStyle(theme.print(.ink))                    .tint(theme.print(.red))                    .focused($focused)                    PaperFormRule(seed: "secret-\(seed)")                }            } else {                PaperTextField(input.prompt, text: $text, focus: $focused)                    .textInputAutocapitalization(.never)                    .autocorrectionDisabled()            }        }        .onAppear { focused = true }    }}/// A value shown once: its title, the handwritten warning in red, the value/// typed in a ruled block, Copy, and "I've saved it", which lets it go./// A secret column stays masked: Copy alone releases it through its policy.struct RevealedValueCard: View {    @Environment(\.theme) private var theme    let revealed: RevealedValue    let identifier: String    /// The card's own tap (architect, 13 Oct: as the sealed value's): a value    /// shown once is copied by touching it, never by a link under it.    let onCopy: () -> Void    /// "I've saved it", where the surface draws no act cards of its own; a    /// card page deals it as a card in its grid and passes nil.    var onSaved: (() -> Void)? = nil    /// Copied just now: the caption line says so for a moment.    var copied = false    var body: some View {        Paper(dye: .cream, edge: .cut, seed: "\(identifier)-revealed", tilt: false, inset: 18) {            VStack(alignment: .leading, spacing: 10) {                Text(revealed.title)                    .paperTitle(20)                    .accessibilityAddTraits(.isHeader)                Text(copied ? RevealedWords.copied : revealed.note)                    .paperHand(19, ink: copied ? .pencil : .red)                    .accessibilityIdentifier("\(identifier)-revealed-caption")                Text(revealed.column == nil ? revealed.value : "••••••••")                    .paperBody(15)                    // Copy must go through expiry; system text selection                    // would put the same bytes on a permanent pasteboard.                    .textSelection(.disabled)                    .fixedSize(horizontal: false, vertical: true)                    .frame(maxWidth: .infinity, alignment: .leading)                    .padding(14)                    .overlay {                        Rectangle().strokeBorder(theme.print(.ink).opacity(0.8), lineWidth: 1.2)                    }                    .accessibilityIdentifier("\(identifier)-revealed-value")                if let onSaved {                    PaperTypedButton(RevealedWords.saved, action: onSaved)                        .accessibilityIdentifier("\(identifier)-revealed-saved")                }            }            .frame(maxWidth: .infinity, alignment: .leading)        }        .contentShape(Rectangle())        .onTapGesture(perform: onCopy)        .accessibilityElement(children: .contain)        .accessibilityAddTraits(.isButton)        .accessibilityHint(RevealedWords.copyHint)        .accessibilityIdentifier("\(identifier)-revealed")    }}enum RevealedWords {    static var copied: String { ShellLines.line("record", "copied") }    static var saved: String { ShellLines.line("record", "saved_it") }    static var copyHint: String { ShellLines.line("record", "copy_hint") }}/// What a list or a page does with an act's outcome that is not a record:/// an address opens in the system browser, a value goes on the clipboard/// (through the `Clipboard` seam, with its expiry when it has one), a sentence/// is said.@MainActorenum RecordActionOutcomes {    /// `toasts` is nil where nobody holding the surface draws them: the    /// address still opens and the value is still copied.    static func finish(        _ outcome: ActionOutcome?, openURL: OpenURLAction, toasts: ToastCenter?,        clipboard: any Clipboard = SystemClipboard()    ) {        switch outcome {        case .opened(let url)?:            let said: (Bool) -> Void = { accepted in                if !accepted { toasts?.show(ShellLines.line("record", "browser_failed"), tone: .error) }            }            #if os(macOS)            // Never the browser broker's headless Chrome (BrowserOpening).            BrowserOpening.open(url, fallback: { openURL($0, completion: $1) }, accepted: said)            #else            openURL(url, completion: said)            #endif        case .copy(let value, let expiry, let column, _)?:            guard column == nil else {                toasts?.show(ShellLines.line("record", "copy_no_expiry"), tone: .error)                return            }            let words = copy(value, expiresAfter: expiry, clipboard: clipboard)            toasts?.show(words, tone: .success)        case .refused(let sentence)?:            toasts?.show(sentence, tone: .error)        case .said(let sentence)?:            toasts?.show(sentence, tone: .success)        case .shared(let file)?:            ShareSheet.present(file)        default:            break        }    }    /// A named secret is consumed before copying; other outcomes keep their    /// ordinary clipboard, browser and receipt behavior.    static func finish(        _ outcome: ActionOutcome?, definition: TableDefinition?, store: (any Records)?,        openURL: OpenURLAction, toasts: ToastCenter?, clipboard: any Clipboard = SystemClipboard()    ) async -> ChangeRecord? {        if case .copy(let value, _, let column?, let record)? = outcome {            guard let definition, let store else {                toasts?.show(ShellLines.line("record", "unreadable"), tone: .error)                return nil            }            do {                let change = try await SecretCopy.copy(                    RevealedValue(title: "", value: value, note: "", record: record, column: column),                    definition: definition, store: store, clipboard: clipboard)                toasts?.show(ShellLines.line("record", "copied_expires"), tone: .success)                return change            } catch {                toasts?.show(SecretCopy.problem(error), tone: .error)            }        } else {            finish(outcome, openURL: openURL, toasts: toasts, clipboard: clipboard)        }        return nil    }    /// Puts `value` on the clipboard and answers the receipt's words: a value    /// that should be forgotten says whether the platform promised to — iOS    /// does, macOS does not, and a promise the platform will not keep is worse    /// than none.    @discardableResult    static func copy(_ value: String, expiresAfter expiry: TimeInterval? = nil, clipboard: any Clipboard = SystemClipboard()) -> String {        guard let expiry else {            clipboard.put(value)            return ShellLines.line("record", "copied")        }        return copiedLine(forgets: clipboard.put(value, expiringAfter: expiry))    }    /// The receipt of a copy that should be forgotten. Pure, so both    /// platforms' sentences are held by a test.    static func copiedLine(forgets: Bool) -> String {        forgets            ? ShellLines.line("record", "copied_forgets")            : ShellLines.line("record", "copied_keeps")    }}