OTP/OTP/Views/AddURLForm.swift

91 lines
2.6 KiB
Swift
Raw Normal View History

2021-08-24 22:19:31 +00:00
//
// AddURLForm.swift
// OTP
//
// Created by Shadowfacts on 8/22/21.
//
import SwiftUI
import OTPKit
struct AddURLForm: View {
let dismiss: (DismissAction) -> Void
@State private var inputURL = ""
@State private var extractedKey = EditedKey()
@FocusState private var urlFocused: Bool
private var isValid: Bool {
extractedKey.toTOTPKey() != nil
}
var body: some View {
Form {
HStack {
TextField("URL", text: $inputURL)
.focused($urlFocused)
Button {
self.inputURL = UIPasteboard.general.string ?? ""
} label: {
Label("Paste", systemImage: "doc.on.clipboard")
.labelStyle(.iconOnly)
.foregroundColor(.accentColor)
}
.buttonStyle(.plain)
.disabled(!UIPasteboard.general.hasStrings)
}
Section {
TextField("Issuer", text: $extractedKey.issuer)
TextField("Label", text: $extractedKey.label)
TextField("Secret", text: $extractedKey.secret)
} header: {
Text("Extracted Key")
}
.disabled(true)
}
.onSubmit {
if isValid {
dismiss(.save(extractedKey.toTOTPKey()!))
}
}
.onAppear {
// doesn't work, see FB9551099
urlFocused = true
}
.navigationTitle("Add from URL")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
dismiss(.cancel)
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
dismiss(.save(extractedKey.toTOTPKey()!))
}
.disabled(!isValid)
}
}
.onChange(of: inputURL, perform: self.updateExtractedKey(inputURL:))
}
private func updateExtractedKey(inputURL: String) {
let text = inputURL.trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty,
let components = URLComponents(string: inputURL),
let totpKey = TOTPKey(urlComponents: components),
let edited = EditedKey(totpKey: totpKey) {
extractedKey = edited
} else {
extractedKey = EditedKey()
}
}
}
struct AddURLForm_Previews: PreviewProvider {
static var previews: some View {
AddURLForm() { (_) in }
}
}