Cotton code
204 lines · 9.8 KB · SwiftRaw
// THE LIST (secrets.html "The list"): the title with the round plus, search across names, sites, usernames and notes// (never values), the kind chips, then only when there is something to do the lines above the list (Health for now;// an ask and a secret still known come with sharing), then the rows: each kind's drawn mark, the name, the kind's own// second line (a token's masked tail in the mono face). `vault.items {filter?, q?, after?}`, 200 a page.#if os(iOS)import CottonKitimport SwiftUIstruct SecretsListScreen: View {    let model: VaultModel    var filter = "all"    var pushed = false    @State private var answer: VaultItems?    @State private var more: [VaultRow] = []    @State private var next: String?    @State private var q = ""    @State private var chosen: String?    @State private var health: VaultHealth?    private var shownFilter: String { chosen ?? filter }    var body: some View {        VStack(spacing: 0) {            if pushed {                SecretsBar(back: SecretsWords.line("tab.secrets"), onBack: { model.pop() }).padding(.horizontal, Plum.side)            }            ScrollView {                LazyVStack(alignment: .leading, spacing: 0) {                    if let answer {                        head(answer)                        if !pushed {                            // Where sync stands, in one quiet line (SyncSeenLine); a tap opens You.                            SyncSeenLine(font: SecretsType.small, color: Plum.quiet) { SyncSeenOpens.ask() }                                .padding(.top, 4)                            SecretsSearch(prompt: answer.total > 0 ? SecretsWords.count("list.search", answer.total) : SecretsWords.line("list.search_empty"), text: $q, id: "secrets-search").padding(.top, 10)                            chips(answer.chips).padding(.top, 12)                            needs                            if q.isEmpty, chosen == nil { SecretsNeedsBlock(model: model) }                        }                        content(answer)                        // What his people shared with him, under his own, whose each one is said on its row.                        if !pushed, q.isEmpty, chosen == nil { SecretsInboxBlock(model: model) }                    }                }                .padding(.horizontal, Plum.side)                .padding(.bottom, 40)            }            .scrollDismissesKeyboard(.immediately)        }        .background(Plum.ground)        .task(id: "\(model.generation)|\(shownFilter)|\(q)") { await read() }        .accessibilityIdentifier(pushed ? "secrets-list-\(filter)" : "secrets-list")    }    private func head(_ answer: VaultItems) -> some View {        HStack(alignment: .center) {            SecretsTitle(text: pushed ? answer.title : SecretsWords.line("list.title"))            Spacer(minLength: 12)            if !pushed {                Button { model.sheet = .kinds(answer.add) } label: {                    SecretsMarkView(mark: .plus, size: 22, ink: Plum.ink)                        .frame(width: 40, height: 40)                        .overlay(Circle().strokeBorder(Plum.ink, lineWidth: Plum.stroke))                        .frame(width: 44, height: 44)                        .contentShape(Circle())                }                .buttonStyle(SecretsPress())                .accessibilityLabel(SecretsWords.line("list.add"))                .accessibilityIdentifier("secrets-add")            }        }    }    private func chips(_ chips: [VaultChip]) -> some View {        ScrollView(.horizontal, showsIndicators: false) {            HStack(spacing: 8) {                ForEach(chips) { chip in                    SecretsChip(label: chip.label, on: chip.id == shownFilter, id: "secrets-chip-\(chip.id)") {                        chosen = chip.id == "all" ? nil : chip.id                    }                }            }            .padding(.horizontal, Plum.side)        }        .padding(.horizontal, -Plum.side)        .scrollClipDisabled()    }    /// `.need`: what needs him, above the list, only when there is something (Health's line for now).    @ViewBuilder private var needs: some View {        if let health, health.weak + health.reused + health.old + (health.breached ?? 0) > 0, q.isEmpty, chosen == nil {            VStack(spacing: 0) {                SecretsRule()                Button { model.push(.health) } label: {                    SecretsRow(title: SecretsWords.count("list.health", health.weak + health.reused + health.old + (health.breached ?? 0)), last: true, lead: { Color.clear.frame(width: 26, height: 1) }) {                        SecretsMarkView(mark: .next, size: 18, ink: Plum.quiet)                    }                }                .buttonStyle(.plain)                .accessibilityIdentifier("secrets-need-health")            }            .padding(.top, 12)        }    }    @ViewBuilder private func content(_ answer: VaultItems) -> some View {        if let empty = answer.empty, answer.total == 0 || answer.sections.allSatisfy(\.rows.isEmpty) {            // Nothing kept at all is said in Secrets' own words; a search or a group with nothing in it, in the core's.            let first = answer.total == 0 && q.isEmpty && !pushed && chosen == nil            VStack(alignment: .leading, spacing: 8) {                Text(first ? SecretsWords.line("list.empty") : empty.title).font(SecretsType.text(22, .bold, relativeTo: .title2)).foregroundStyle(Plum.ink)                    .fixedSize(horizontal: false, vertical: true)                Text(first ? SecretsWords.line("list.empty_body") : empty.body).font(SecretsType.body).foregroundStyle(Plum.quiet).fixedSize(horizontal: false, vertical: true)                if let act = empty.act {                    SecretsButton(label: first ? SecretsWords.line("list.add_first") : act.label, weight: .go, id: "secrets-empty-act") { Task { await model.run(act) } }                        .padding(.top, 12)                }            }            .padding(.top, 40)            .accessibilityIdentifier("secrets-empty")        }        ForEach(answer.sections) { section in            if !section.rows.isEmpty {                if let title = section.title { SecretsHeading(text: title) } else { Spacer().frame(height: 12) }                let rows = section.id == answer.sections.last?.id ? section.rows + more : section.rows                // A secret may stand in two sections (Recently used and All): each row is its section's own.                ForEach(Array(rows.enumerated()), id: \.offset) { index, row in                    SecretsSecretRow(model: model, row: row, last: index == rows.count - 1)                        .id("\(section.id)|\(row.id)")                        .onAppear { if row.id == rows.last?.id { Task { await page() } } }                }            }        }        if let bin = answer.bin {            SecretsRule().padding(.top, 24)            Button { Task { await model.run(bin) } } label: {                SecretsRow(title: bin.label, last: true) { SecretsMarkView(mark: .next, size: 18, ink: Plum.quiet) }            }            .buttonStyle(.plain)            .accessibilityIdentifier("secrets-bin")        }    }    private func read() async {        var request: [String: JSONValue] = ["filter": .string(shownFilter)]        if !q.isEmpty { request["q"] = .string(q) }        guard let read = await model.read("vault.items", .object(request), as: VaultItems.self) else { return }        answer = read        more = []        next = read.next        model.open = read.open        if !pushed, read.open {            health = await model.read("vault.security", .object(["platform": "ios"]), as: VaultSecurity.self)?.health        }    }    private func page() async {        guard let after = next else { return }        next = nil        var request: [String: JSONValue] = ["filter": .string(shownFilter), "after": .string(after)]        if !q.isEmpty { request["q"] = .string(q) }        guard let read = await model.read("vault.items", .object(request), as: VaultItems.self) else { return }        more += read.sections.flatMap(\.rows)        next = read.next    }}/// One secret in the list: its kind's mark, its name, its kind's second line; a token's line in the mono face. Tap/// opens it; a long press offers its quick acts (Copy password, Copy user name), as the core names them.struct SecretsSecretRow: View {    let model: VaultModel    let row: VaultRow    var last = false    /// The kind's mark grows with the phone's text size, as the words beside it do.    @ScaledMetric(relativeTo: .body) private var markSize: CGFloat = 26    var body: some View {        Button { Task { await model.run(VaultAct(id: "open", label: row.title, method: "vault.item", request: .object(["id": .string(row.id)]))) } } label: {            SecretsRow(title: row.title, line: row.subtitle, lineMono: SecretsKinds.mono(row.kind), last: last,                       lead: { SecretsMarkView(mark: .kind(row.kind), size: markSize, ink: Plum.ink).frame(width: markSize + 4) }) {                if let mark = row.marks.first {                    Text(mark.label).font(SecretsType.text(13, relativeTo: .caption)).foregroundStyle(Plum.quiet)                }            }        }        .buttonStyle(.plain)        .contextMenu {            ForEach(row.quick) { act in                Button(act.label) { Task { await model.run(act) } }            }        }        .accessibilityElement(children: .combine)        .accessibilityIdentifier("secrets-row-\(row.id)")    }}/// What the screens need to know of a kind the core names.enum SecretsKinds {    /// A developer secret's second line and value are set in the mono face and never wrap mid-token.    static func mono(_ kind: String) -> Bool { ["api_key", "code", "token", "env", "file"].contains(kind) }}#endif