SPB Git

Repository Public

ItemEditorView.swift 16.0 KB 294 lines swift

1// Editor for the 13 item types: template fields, generator, strength, URL match rules with look-alike warning,2// one-time-code validation (and QR scan on iOS), custom fields, tags, expiry and rotation.3import SharedVaultKit4import SwiftUI56struct ItemEditorView: View {7    @Environment(AppModel.self) private var model8    @Environment(\.dismiss) private var dismiss9    let request: EditorRequest1011    @State private var item: Item12    @State private var vaultId: String13    @State private var tagsText: String14    @State private var hasExpiry: Bool15    @State private var expiry: Date16    @State private var revealed = Set<String>()17    @State private var generatorFor: String?18    @State private var scanning = false19    @State private var error: String?20    @State private var saving = false2122    init(request: EditorRequest) {23        self.request = request24        _item = State(initialValue: request.item)25        _vaultId = State(initialValue: request.vaultId)26        _tagsText = State(initialValue: request.item.tags.joined(separator: ", "))27        let d = request.item.expiresAt.flatMap(ItemMeta.parseISO)28        _hasExpiry = State(initialValue: d != nil)29        _expiry = State(initialValue: d ?? Date().addingTimeInterval(365 * 86400))30    }3132    private var isNew: Bool { request.recordId == nil }33    private var template: ItemTemplate { item.type.template }34    private var totpError: String? {35        guard let t = item.fields["totp"], !t.isEmpty else { return nil }36        return (try? SPV1.parseTotp(t)) == nil ? "This is not a valid secret: paste the base32 key or the otpauth:// link shown by the site." : nil37    }38    private var canSave: Bool { !item.title.trimmingCharacters(in: .whitespaces).isEmpty && totpError == nil && !saving }3940    var body: some View {41        VStack(spacing: 0) {42            titleBar43            Divider().overlay(Palette.line)44            ScrollView {45                VStack(alignment: .leading, spacing: 16) {46                    ErrorText(text: error)47                    if isNew { typeAndVault }48                    LabeledField(label: "Title") {49                        TextField("", text: $item.title, prompt: Text(titlePrompt)).textFieldStyle(.vault).accessibilityIdentifier("editor-title")50                    }51                    ForEach(template.fields, id: \.key) { def in field(def) }52                    if item.type == .login || item.type == .passkey || !item.urls.isEmpty { urls }53                    LabeledField(label: "Notes") {54                        TextField("", text: $item.notes, axis: .vertical).lineLimit(3...10).textFieldStyle(.vault).accessibilityIdentifier("editor-notes")55                    }56                    custom57                    LabeledField(label: "Tags", hint: "Separated by commas.") {58                        TextField("", text: $tagsText).textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("editor-tags")59                    }60                    schedule61                    Toggle("Favorite", isOn: $item.favorite).tint(Palette.accent).accessibilityIdentifier("editor-favorite")62                }63                .padding(20)64                .frame(maxWidth: 640, alignment: .leading).frame(maxWidth: .infinity)65            }66        }67        .background(Palette.s1)68        #if os(macOS)69        .frame(minWidth: 560, idealWidth: 620, minHeight: 560, idealHeight: 720)70        #endif71        .interactiveDismissDisabled(item != request.item)72        .containerID("item-editor")73        .sheet(item: Binding(get: { generatorFor.map(KeyBox.init) }, set: { generatorFor = $0?.key })) { box in74            VStack(alignment: .leading, spacing: 14) {75                HStack {76                    Text("Generator").font(.vaultTitle).foregroundStyle(Palette.text)77                    Spacer()78                    Button("Close") { generatorFor = nil }.buttonStyle(.vaultGhost).keyboardShortcut(.cancelAction)79                }80                ScrollView { GeneratorPanel { v in item.fields[box.key] = v; revealed.insert(box.key); generatorFor = nil } }81            }82            .padding(20).frame(minWidth: 340, idealWidth: 460, minHeight: 480).background(Palette.s1)83        }84        #if os(iOS)85        .sheet(isPresented: $scanning) {86            CodeScannerView(prompt: "Scan the QR code shown by the site when it sets up two-step verification") { code in87                if (try? SPV1.parseTotp(code)) != nil { item.fields["totp"] = code } else { error = "This QR code is not a one-time-code secret." }88            }89        }90        #endif91    }9293    private struct KeyBox: Identifiable { let key: String; var id: String { key } }9495    private var titlePrompt: String {96        switch item.type {97        case .login: "Example Bank"98        case .card: "Personal Visa"99        case .wifi: "Home network"100        default: template.label101        }102    }103104    private var titleBar: some View {105        HStack {106            Button("Cancel") { dismiss() }.buttonStyle(.vaultGhost).keyboardShortcut(.cancelAction).accessibilityIdentifier("editor-cancel")107            Spacer()108            Text(isNew ? "New \(template.label.lowercased())" : "Edit \(template.label.lowercased())").font(.vaultHeadline).foregroundStyle(Palette.text).lineLimit(1)109            Spacer()110            Button(saving ? "Saving…" : "Save") { Task { await save() } }.buttonStyle(.vaultPrimary).disabled(!canSave)111                .keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("editor-save")112        }113        .padding(.horizontal, 16).padding(.vertical, 10)114    }115116    private var typeAndVault: some View {117        HStack(alignment: .top, spacing: 12) {118            LabeledField(label: "Type") {119                Picker("Type", selection: Binding(get: { item.type }, set: { item.type = $0 })) {120                    ForEach(ItemType.allCases, id: \.self) { t in Label(t.template.label, systemImage: ItemMeta.symbol(t)).tag(t) }121                }122                .labelsHidden().accessibilityIdentifier("editor-type")123            }124            if model.writableVaults.count > 1 {125                LabeledField(label: "Vault") {126                    Picker("Vault", selection: $vaultId) { ForEach(model.writableVaults) { Text($0.meta.name).tag($0.vaultId) } }127                        .labelsHidden().accessibilityIdentifier("editor-vault")128                }129            }130            Spacer(minLength: 0)131        }132    }133134    // ── template fields ──135    private func binding(_ key: String) -> Binding<String> {136        Binding(get: { item.fields[key] ?? "" }, set: { item.fields[key] = $0.isEmpty ? nil : $0 })137    }138139    @ViewBuilder private func field(_ def: FieldDef) -> some View {140        switch def.kind {141        case .secret:142            let value = item.fields[def.key] ?? ""143            let isPassword = def.key == "password" || def.key == "passphrase"144            LabeledField(label: def.label) {145                HStack(spacing: 6) {146                    secretInput(def)147                    IconButton(systemName: revealed.contains(def.key) ? "eye.slash" : "eye", label: revealed.contains(def.key) ? "Hide \(def.label)" : "Show \(def.label)") {148                        if revealed.contains(def.key) { revealed.remove(def.key) } else { revealed.insert(def.key) }149                    }150                    if isPassword {151                        IconButton(systemName: "dice", label: "Generate a password", tint: Palette.accent) { generatorFor = def.key }.accessibilityIdentifier("editor-generate-\(def.key)")152                    }153                }154                if isPassword, !value.isEmpty { StrengthMeter(bits: Double(SPV1.estimateBits(value))) }155            }156        case .totp:157            LabeledField(label: def.label, hint: "The base32 key or the otpauth:// link the site shows when you set up two-step verification.", error: totpError) {158                HStack(spacing: 6) {159                    TextField("", text: binding(def.key)).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("editor-field-\(def.key)")160                    #if os(iOS)161                    IconButton(systemName: "qrcode.viewfinder", label: "Scan a QR code", tint: Palette.accent) { scanning = true }.accessibilityIdentifier("editor-scan-totp")162                    #endif163                }164                if totpError == nil, let t = item.fields[def.key], !t.isEmpty { TotpRow(secret: t, label: "Current code").padding(.top, 4) }165            }166        case .multiline:167            LabeledField(label: def.label) {168                TextField("", text: binding(def.key), axis: .vertical).lineLimit(3...8).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("editor-field-\(def.key)")169            }170        case .text, .url, .date:171            LabeledField(label: def.label, hint: def.kind == .date ? "YYYY-MM-DD" : nil) {172                TextField("", text: binding(def.key)).textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("editor-field-\(def.key)")173            }174        }175    }176177    @ViewBuilder private func secretInput(_ def: FieldDef) -> some View {178        if revealed.contains(def.key) {179            TextField("", text: binding(def.key), axis: def.key == "dotenv" || def.key == "privateKey" ? .vertical : .horizontal).lineLimit(1...8)180                .textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("editor-field-\(def.key)")181        } else {182            SecureField("", text: binding(def.key)).textFieldStyle(.vaultMono).accessibilityLabel(def.label).accessibilityIdentifier("editor-field-\(def.key)")183        }184    }185186    // ── URLs ──187    private var savedDomains: [String] { SPV1.savedDomains(model.items.filter { $0.recordId != request.recordId }.map(\.item)) }188189    private var urls: some View {190        VStack(alignment: .leading, spacing: 8) {191            Text("Websites").font(.caption.weight(.semibold)).foregroundStyle(Palette.muted)192            ForEach(item.urls.indices, id: \.self) { i in193                VStack(alignment: .leading, spacing: 5) {194                    HStack(spacing: 6) {195                        TextField("", text: Binding(get: { item.urls[i].url }, set: { item.urls[i].url = $0 }), prompt: Text("https://example.com"))196                            .textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("editor-url-\(i)")197                        Picker("Autofill rule", selection: Binding(get: { item.urls[i].match }, set: { item.urls[i].match = $0 })) {198                            Text("Whole domain").tag(UrlMatch.domain)199                            Text("This host").tag(UrlMatch.host)200                            Text("Exact address").tag(UrlMatch.exact)201                            Text("Never autofill").tag(UrlMatch.never)202                        }203                        .labelsHidden().fixedSize().accessibilityIdentifier("editor-url-match-\(i)")204                        IconButton(systemName: "minus.circle", label: "Remove this website", tint: Palette.danger) { item.urls.remove(at: i) }205                    }206                    urlAdvice(item.urls[i].url)207                }208            }209            Button { item.urls.append(ItemUrl(url: "", match: .domain)) } label: { Label("Add a website", systemImage: "plus") }.buttonStyle(.vaultCompact)210                .accessibilityIdentifier("editor-add-url")211        }212    }213214    @ViewBuilder private func urlAdvice(_ url: String) -> some View {215        if !url.isEmpty {216            if let o = SPV1.parseOrigin(url.contains("://") ? url : "https://\(url)") {217                if let w = SPV1.lookalike(pageUrl: url.contains("://") ? url : "https://\(url)", savedDomains: savedDomains) {218                    Callout(kind: .danger, title: "Look-alike address", text: "“\(w.page)” looks like “\(w.resembles)”, which is already in your vault, but it is a different site. Check the address before saving a password for it.")219                        .accessibilityIdentifier("editor-lookalike")220                } else if o.scheme == "http" {221                    Text("This address is not encrypted (http). SP Vault never offers a saved https password on an http page.").font(.caption).foregroundStyle(Palette.brass)222                } else {223                    Text("Autofill will be offered on \(o.domain ?? o.host).").font(.caption).foregroundStyle(Palette.muted)224                }225            } else {226                Text("This is not a web address.").font(.caption).foregroundStyle(Palette.danger)227            }228        }229    }230231    // ── custom fields ──232    private var custom: some View {233        VStack(alignment: .leading, spacing: 8) {234            Text("Custom fields").font(.caption.weight(.semibold)).foregroundStyle(Palette.muted)235            ForEach(item.custom.indices, id: \.self) { i in236                HStack(spacing: 6) {237                    TextField("", text: Binding(get: { item.custom[i].label }, set: { item.custom[i].label = $0 }), prompt: Text("Label")).textFieldStyle(.vault).frame(maxWidth: 150)238                        .accessibilityLabel("Custom field \(i + 1) label")239                    if item.custom[i].kind == .secret {240                        SecureField("", text: Binding(get: { item.custom[i].value }, set: { item.custom[i].value = $0 }), prompt: Text("Value")).textFieldStyle(.vaultMono)241                            .accessibilityLabel("Custom field \(i + 1) value")242                    } else {243                        TextField("", text: Binding(get: { item.custom[i].value }, set: { item.custom[i].value = $0 }), prompt: Text("Value")).textFieldStyle(.vault)244                            .accessibilityLabel("Custom field \(i + 1) value")245                    }246                    Picker("Kind", selection: Binding(get: { item.custom[i].kind }, set: { item.custom[i].kind = $0 })) {247                        Text("Text").tag(FieldKind.text); Text("Secret").tag(FieldKind.secret)248                    }249                    .labelsHidden().fixedSize()250                    IconButton(systemName: "minus.circle", label: "Remove custom field \(i + 1)", tint: Palette.danger) { item.custom.remove(at: i) }251                }252            }253            Button { item.custom.append(CustomField(label: "", value: "")) } label: { Label("Add a field", systemImage: "plus") }.buttonStyle(.vaultCompact)254                .accessibilityIdentifier("editor-add-custom")255        }256    }257258    // ── expiry / rotation ──259    private var schedule: some View {260        VStack(alignment: .leading, spacing: 8) {261            Toggle("Has an expiry date", isOn: $hasExpiry).tint(Palette.accent).accessibilityIdentifier("editor-has-expiry")262            if hasExpiry { DatePicker("Expires on", selection: $expiry, displayedComponents: .date).accessibilityIdentifier("editor-expiry") }263            if template.section == .developer || item.rotateEveryDays != nil {264                Picker("Rotation reminder", selection: Binding(get: { item.rotateEveryDays ?? 0 }, set: { item.rotateEveryDays = $0 == 0 ? nil : $0 })) {265                    Text("None").tag(0); Text("Every 30 days").tag(30); Text("Every 90 days").tag(90); Text("Every 180 days").tag(180); Text("Every year").tag(365)266                }267                .accessibilityIdentifier("editor-rotation")268            }269        }270    }271272    // ── save ──273    private func save() async {274        saving = true275        defer { saving = false }276        var out = item277        out.title = out.title.trimmingCharacters(in: .whitespaces)278        out.tags = tagsText.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }279        out.urls = out.urls.compactMap { u in280            let t = u.url.trimmingCharacters(in: .whitespaces)281            if t.isEmpty { return nil }282            return ItemUrl(url: t.contains("://") ? t : "https://\(t)", match: u.match)283        }284        out.custom = out.custom.filter { !$0.label.isEmpty || !$0.value.isEmpty }285        out.expiresAt = hasExpiry ? ISO8601DateFormatter().string(from: expiry) : nil286        let target = vaultId, recordId = request.recordId287        error = await model.perform("Saved") {288            let id = try await model.engine.saveItem(vaultId: target, id: recordId, item: out)289            model.selectedItemID = "\(target)/\(id)"290            dismiss()291        }292    }293}294
Files main
Menu

Theme