163 lines
4.2 KiB
Swift

//
// LoginView.swift
// Login
//
// Created by Javier Cicchelli on 30/11/2022.
// Copyright © 2022 Röck+Cöde. All rights reserved.
//
import APIService
import DataModels
import DependencyInjection
import Dependencies
import KeychainStorage
import SwiftUI
public struct LoginView: View {
// MARK: States
@State private var containerTopPadding: CGFloat = 0
// MARK: Initialisers
public init() {}
// MARK: Body
public var body: some View {
ScrollView(
.vertical,
showsIndicators: false
) {
LoginContainer()
.padding(.horizontal, 24)
.padding(.top, containerTopPadding)
}
.background(Color.red)
.overlay(ViewHeightGeometry())
.onPreferenceChange(ViewHeightPreferenceKey.self) { height in
containerTopPadding = height * 0.1
}
}
}
// MARK: - Views
fileprivate extension LoginView {
struct LoginContainer: View {
// MARK: Dependencies
@Dependency(\.apiService) private var apiService
// MARK: Storages
@KeychainStorage(key: .KeychainStorage.account) private var account: Account?
// MARK: States
@State private var isAuthenticating: Bool = false
@State private var username: String = ""
@State private var password: String = ""
@State private var errorMessage: String?
// MARK: Body
var body: some View {
VStack(spacing: 32) {
Text(
"login.title.text",
bundle: .module,
comment: "Login view title text."
)
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.primary)
LoginForm(
username: $username,
password: $password,
errorMessage: $errorMessage
) {
isAuthenticating = true
}
Button {
isAuthenticating = true
} label: {
Label {
Text(
"login.button.log_in.text",
bundle: .module,
comment: "Log in button text."
)
.fontWeight(.semibold)
} icon: {
if isAuthenticating {
ProgressView()
.controlSize(.regular)
} else {
EmptyView()
}
}
.labelStyle(.logIn)
}
.tint(.orange)
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle(radius: 8))
.controlSize(.large)
.disabled(isLoginDisabled)
.task(id: isAuthenticating) {
await authenticate()
}
}
}
}
}
// MARK: - Helpers
private extension LoginView.LoginContainer {
// MARK: Computed
var isLoginDisabled: Bool {
username.isEmpty || password.isEmpty
}
// MARK: Functions
func authenticate() async {
guard isAuthenticating else { return }
do {
_ = try await apiService.getUser(credentials: .init(
username: username,
password: password
))
account = .init(
username: username,
password: password
)
} catch APIClientError.authenticationFailed {
errorMessage = "login.error.authentication_failed.text"
isAuthenticating = false
} catch {
errorMessage = "login.error.authentication_unknown.text"
isAuthenticating = false
}
}
}
// MARK: - Previews
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}