Cotton code
296 lines · 14.6 KB · SwiftRaw
// COTTON SECRETS' ROOT (assets/design/keys/DECISIONS.md "The structure", secrets.html; CONTRACT.md): Unlock first,// then three places as text tabs at the foot, Secrets, People and You, each its own stack. The list is always the// first screen. Add and edit, an act's one field, an export and a value shown once rise over the whole app as pages// of their own. Every screen stands in the Plum look (`SecretsLook.swift`); nothing from the old vault screens, the// fan or the shared boards. The core decides every word and act (`vault.*`, `look`, the `secrets` line set); this// file only places them.#if os(iOS)import CottonKitimport SwiftUI/// The `secrets` line set: the few words a screen reads directly (CONTRACT "The words"); everything else arrives in/// a call's answer already in words.enum SecretsWords {    static func line(_ key: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("secrets", key, fills) }    static var cancel: String { line("add.cancel") }    /// A counted line (`one`, `other`, and `zero` where the set has it), its `{n}` filled.    static func count(_ key: String, _ n: Int) -> String {        let form = n == 0 && ShellLines.shipped("secrets", "\(key).zero") != nil ? "zero" : n == 1 ? "one" : "other"        return line("\(key).\(form)", ["n": "\(n)"])    }}struct SecretsRoot: View {    /// Whether this app is Cotton Secrets (registry slug `keys`).    static var applies: Bool { VaultLook.applies }    @Bindable var model: VaultModel    @State private var look = LookModel.standing("keys")    @Environment(\.scenePhase) private var phase    @Environment(\.nativeKeptFlow) private var nativeFlow    var body: some View {        ZStack {            Plum.ground.ignoresSafeArea()            if model.open == true {                VStack(spacing: 0) {                    ZStack {                        ForEach(VaultTab.allCases, id: \.self) { tab in                            stack(tab)                                .opacity(model.tab == tab ? 1 : 0)                                .allowsHitTesting(model.tab == tab)                                .accessibilityHidden(model.tab != tab)                        }                    }                    // The tabs stop growing at the largest ordinary size, as the system's own do; a long press shows them large.                    SecretsTabs(model: model).dynamicTypeSize(...DynamicTypeSize.xxxLarge)                }                // The status bar stands on the ground, so a list scrolled up never runs under the clock.                .overlay(alignment: .top) { Plum.ground.frame(height: 0).ignoresSafeArea(edges: .top) }                .transition(.opacity)            } else if model.open == false {                SecretsUnlock(model: model).transition(.opacity)            }        }        .animation(.easeOut(duration: 0.25), value: model.open)        .fullScreenCover(item: $model.sheet) { sheet in            sheetPage(sheet)                .background(Plum.ground.ignoresSafeArea())                .lookStanding(look)        }        .overlay {            if let asking = model.asking {                SecretsAskCard(title: asking.confirm.title, body_: asking.confirm.body, yes: asking.confirm.yes, no: asking.confirm.no) { yes in                    asking.answer(yes)                }            }        }        .animation(.easeOut(duration: 0.22), value: model.asking?.id)        .lookStanding(look)        .task {            await look.read(model.core)            await model.readChoices()            await readOpen()            model.keep()            #if COTTON_DEV            await SecretsDevOpen.run(model)            #endif        }        .task(id: model.generation) { await readOpen() }        // The home's sync line was tapped: You.        .onReceive(NotificationCenter.default.publisher(for: SyncSeenOpens.notice)) { _ in model.tab = .you }        .onAppear { model.nativeFlow = nativeFlow }        .onChange(of: phase) { _, now in            model.scene(now)            if now == .active, model.gate != nil { Task { await model.unlock() } }        }        .accessibilityIdentifier("secrets-root")    }    /// Whether Secrets stands open at launch: the list's own answer says so (`open`). Once Unlock has opened it, only    /// locking shuts it again (`VaultModel.lock`): a phone with no vault yet, or a five-minute unlock running out while    /// he reads, keeps the app and says on each secret what needs the lock.    private func readOpen() async {        guard model.open != true else { return }        guard let items = await model.read("vault.items", .object(["filter": "all"]), as: VaultItems.self) else {            if model.open == nil { model.open = false }            return        }        model.open = items.open    }    /// A place's own stack: its root, and the screens pushed over it (Back is the bar's, or the edge swipe).    private func stack(_ tab: VaultTab) -> some View {        ZStack {            root(tab).accessibilityHidden(!(model.paths[tab] ?? []).isEmpty)            ForEach(Array((model.paths[tab] ?? []).enumerated()), id: \.offset) { index, route in                destination(route)                    .background(Plum.ground.ignoresSafeArea())                    .accessibilityHidden(index < (model.paths[tab]?.count ?? 0) - 1)                    .transition(.move(edge: .trailing))                    .gesture(DragGesture(minimumDistance: 24).onEnded { drag in                        if drag.startLocation.x < 28, drag.translation.width > 80 { model.pop() }                    })            }        }        .animation(.easeOut(duration: 0.25), value: model.paths[tab] ?? [])    }    @ViewBuilder private func root(_ tab: VaultTab) -> some View {        switch tab {        case .secrets: SecretsListScreen(model: model)        case .people: SecretsPeopleScreen(model: model)        case .you: SecretsYouScreen(model: model)        }    }    @ViewBuilder private func destination(_ route: VaultRoute) -> some View {        switch route {        case .item(let id): SecretsItemScreen(model: model, id: id)        case .items(let filter): SecretsListScreen(model: model, filter: filter, pushed: true)        case .history(let id): SecretsHistoryScreen(model: model, id: id)        case .health: SecretsHealthScreen(model: model)        case .look: SecretsLookPage(model: model)        case .recovery: SecretsRecoveryScreen(model: model)        case .person(let number): SecretsPersonScreen(model: model, number: number)        case .check(let number, let name): SecretsCheckScreen(model: model, number: number, name: name)        case .shared(let share): SecretsSharedScreen(model: model, share: share)        }    }    @ViewBuilder private func sheetPage(_ sheet: VaultSheet) -> some View {        switch sheet {        case .edit(let edit): SecretsEditPage(model: model, edit: edit)        case .kinds(let add): SecretsKindsPage(model: model, add: add)        case .quick(let row): SecretsKindsPage(model: model, add: VaultAddMenu(label: row.title, kinds: row.quick))        case .input(let act): SecretsInputPage(model: model, act: act)        case .export(let title, let answer): SecretsExportPage(model: model, title: title, answer: answer)        case .shown(let title, let value): SecretsShownPage(model: model, title: title, value: value)        // The one Share sheet (CONTACTS-ANSWERS 10): pick from the Circle; only someone checked can get a copy.        case .share(let id): ShareSheetView(core: model.core, app: "secrets", thing: .object(["kind": .string("secret"), "id": .string(id)]), close: { model.sheet = nil })        case .take(let id, let number): SecretsTakePage(model: model, id: id, number: number)        case .answer(let ask): SecretsAnswerPage(model: model, ask: ask)        case .askFor(let number, let name): SecretsAskForPage(model: model, number: number, name: name)        case .dashlane: SecretsImportPage(model: model)        }    }}/// `.tabs`: the three places in words at the foot, the one standing in bold ink with a short rule under it. A tap on/// the place standing goes back to its first screen.struct SecretsTabs: View {    let model: VaultModel    /// The tabs' words grow with the phone's text only as far as the cap where they stand, as the system's own do.    @ScaledMetric(relativeTo: .subheadline) private var size: CGFloat = 15    var body: some View {        VStack(spacing: 0) {            SecretsRule()            HStack(spacing: 0) {                ForEach(VaultTab.allCases, id: \.self) { tab in                    let on = model.tab == tab                    Button {                        if on { model.paths[tab] = [] } else { model.tab = tab }                    } label: {                        VStack(spacing: 3) {                            Text(SecretsWords.line("tab.\(tab.rawValue)"))                                .font(Font(SecretsFonts.ui(mono: false, size * Plum.look.scale, weight: on ? 700 : 400)))                                .foregroundStyle(on ? Plum.ink : Plum.quiet)                                .lineLimit(1)                                .minimumScaleFactor(0.8)                            Capsule().fill(on ? Plum.ink : .clear).frame(width: 18, height: 2)                        }                        .padding(.horizontal, 10)                        .padding(.top, 12)                        .padding(.bottom, 4)                        .frame(maxWidth: .infinity, minHeight: 48)                        .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                    .accessibilityIdentifier("secrets-tab-\(tab.rawValue)")                }            }        }        // The tabs stop growing at the largest ordinary size, as the system's own do; a long press shows them large.        .dynamicTypeSize(...DynamicTypeSize.xxxLarge)        .accessibilityShowsLargeContentViewer()        .background(Plum.ground.ignoresSafeArea(edges: .bottom))    }}/// UNLOCK: the asterisk where the launch screen left it, the app's name, "Locked" and a prompt to look at the phone;/// "Use passcode" below, and the note that it locks again a minute after he leaves. The phone's lock is asked as the/// screen stands. A phone with no passcode is told why Secrets will not open, in the core's words.struct SecretsUnlock: View {    let model: VaultModel    @State private var asked = false    /// Whether the asterisk has come from where the launch screen left it (the middle of the screen, at the launch    /// mark's size) to its place over the app's name; the words fade in as it arrives.    @State private var settled = false    @State private var markMid: CGPoint?    @Environment(\.accessibilityReduceMotion) private var reduceMotion    /// The launch screen's asterisk is drawn about 2.95 times this one's 64 points (`LaunchObject`, 200 points square).    private static let launchScale: CGFloat = 2.95    var body: some View {        VStack(spacing: 0) {            Spacer(minLength: 24)            VStack(spacing: 10) {                SecretsMarkView(mark: .aster, size: 64, ink: Plum.accent)                    .background(GeometryReader { box in                        Color.clear.onAppear { markMid = CGPoint(x: box.frame(in: .global).midX, y: box.frame(in: .global).midY) }                    })                    .scaleEffect(settled ? 1 : Self.launchScale)                    .offset(settled ? .zero : launchOffset)                Text(SecretsWords.line("gate.title"))                    .font(SecretsType.text(28, .bold, relativeTo: .title))                    .foregroundStyle(Plum.ink)                    .padding(.top, 10)                    .opacity(settled ? 1 : 0)                Text(SecretsWords.line("gate.locked")).font(SecretsType.body).foregroundStyle(Plum.quiet)                    .opacity(settled ? 1 : 0)                SecretsMarkView(mark: .face, size: 22, ink: Plum.ink)                    .frame(width: 40, height: 40)                    .overlay(Circle().strokeBorder(Plum.ink, lineWidth: Plum.stroke))                    .padding(.top, 44)                    .opacity(settled ? 1 : 0)                if let title = model.gate?.title {                    Text(title).font(SecretsType.text(17, .bold)).foregroundStyle(Plum.ink).multilineTextAlignment(.center)                }                Text(model.cannotOpen ?? SecretsWords.line("gate.look"))                    .font(SecretsType.text(15, relativeTo: .subheadline))                    .foregroundStyle(Plum.ink)                    .multilineTextAlignment(.center)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("secrets-gate-line")                    .opacity(settled ? 1 : 0)            }            .frame(maxWidth: .infinity)            .accessibilityElement(children: .combine)            Spacer(minLength: 24)            VStack(spacing: 4) {                if let gate = model.gate, let act = gate.act {                    SecretsButton(label: act.label, weight: .go, id: "secrets-gate-settings") { Task { await model.follow(act) } }                } else {                    SecretsButton(label: SecretsWords.line("gate.passcode"), weight: .quiet, id: "secrets-unlock") {                        Task { await model.unlock() }                    }                }                SecretsNote(text: model.lockMinutes.map { SecretsWords.count("gate.relock_after", $0) } ?? SecretsWords.line("gate.relock"))                    .multilineTextAlignment(.center)                    .frame(maxWidth: .infinity)            }            .opacity(settled ? 1 : 0)        }        .padding(.horizontal, Plum.side)        .padding(.bottom, 14)        .onAppear {            if reduceMotion {                settled = true            } else {                // The splash goes in one frame over this screen; the asterisk moves once it can be seen.                Task { @MainActor in                    try? await Task.sleep(for: .milliseconds(120))                    withAnimation(.easeInOut(duration: 0.5)) { settled = true }                }            }        }        .task {            guard !asked else { return }            asked = true            await model.unlock()        }        .accessibilityIdentifier("secrets-unlock-screen")    }    /// From the asterisk's place to the middle of the screen, where the launch screen drew it.    private var launchOffset: CGSize {        guard let markMid else { return .zero }        let screen = UIScreen.main.bounds        return CGSize(width: screen.midX - markMid.x, height: screen.midY - markMid.y)    }}#endif