#40: Add server selection screen from EI.

This commit is contained in:
Doug
2022-06-30 10:49:00 +01:00
committed by GitHub
parent dd739d4766
commit baeffd2121
32 changed files with 710 additions and 40 deletions
@@ -0,0 +1,41 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
/// An image that is styled for use as the screen icon in the onboarding flow.
struct AuthenticationIconImage: View {
let image: ImageAsset
var body: some View {
Image(image.name)
.resizable()
.renderingMode(.template)
.foregroundColor(.element.accent)
.frame(width: 90, height: 90)
.background(.white, in: Circle().inset(by: 2))
.accessibilityHidden(true)
}
}
// MARK: - Previews
struct AuthenticationIconImage_Previews: PreviewProvider {
static var previews: some View {
AuthenticationIconImage(image: Asset.Images.serverSelectionIcon)
}
}
@@ -74,7 +74,7 @@ final class LoginCoordinator: Coordinator, Presentable {
let viewModel = LoginViewModel(homeserver: parameters.homeserver)
loginViewModel = viewModel
let view = LoginScreen(viewModel: viewModel.context)
let view = LoginScreen(context: viewModel.context)
loginHostingController = UIHostingController(rootView: view)
indicatorPresenter = UserIndicatorTypePresenter(presentingViewController: loginHostingController)
@@ -178,7 +178,34 @@ final class LoginCoordinator: Coordinator, Presentable {
/// Presents the server selection screen as a modal.
private func presentServerSelectionScreen() {
loginViewModel.displayError(.alert("Not implemented. Enter a full Matrix ID such as @user:server.com"))
MXLog.debug("[LoginCoordinator] presentServerSelectionScreen")
let parameters = ServerSelectionCoordinatorParameters(homeserver: loginViewModel.context.viewState.homeserver,
hasModalPresentation: true)
let coordinator = ServerSelectionCoordinator(parameters: parameters)
coordinator.callback = { [weak self, weak coordinator] result in
guard let self = self, let coordinator = coordinator else { return }
self.serverSelectionCoordinator(coordinator, didCompleteWith: result)
}
coordinator.start()
add(childCoordinator: coordinator)
let modalRouter = NavigationRouter(navigationController: ElementNavigationController())
modalRouter.setRootModule(coordinator)
navigationRouter.present(modalRouter, animated: true)
}
/// Handles the result from the server selection modal, dismissing it after updating the view.
private func serverSelectionCoordinator(_ coordinator: ServerSelectionCoordinator,
didCompleteWith result: ServerSelectionCoordinatorResult) {
navigationRouter.dismissModule(animated: true) { [weak self] in
if case let .selected(homeserver) = result {
self?.updateViewModel(homeserver: homeserver)
}
self?.remove(childCoordinator: coordinator)
}
}
/// Shows the forgot password screen.
@@ -29,7 +29,7 @@ struct LoginScreen: View {
// MARK: Public
@ObservedObject var viewModel: LoginViewModel.Context
@ObservedObject var context: LoginViewModel.Context
var body: some View {
ScrollView {
@@ -46,7 +46,7 @@ struct LoginScreen: View {
.frame(height: 1)
.padding(.vertical, 21)
switch viewModel.viewState.loginMode {
switch context.viewState.loginMode {
case .password:
loginForm
case .oidc:
@@ -61,7 +61,7 @@ struct LoginScreen: View {
.padding(.bottom, 16)
}
.background(Color.element.background.ignoresSafeArea())
.alert(item: $viewModel.alertInfo) { $0.alert }
.alert(item: $context.alertInfo) { $0.alert }
}
/// The header containing a Welcome Back title.
@@ -74,16 +74,16 @@ struct LoginScreen: View {
/// The sever information section that includes a button to select a different server.
var serverInfo: some View {
LoginServerInfoSection(address: viewModel.viewState.homeserver.address,
showMatrixDotOrgInfo: viewModel.viewState.homeserver.isMatrixDotOrg) {
viewModel.send(viewAction: .selectServer)
LoginServerInfoSection(address: context.viewState.homeserver.address,
showMatrixDotOrgInfo: context.viewState.homeserver.isMatrixDotOrg) {
context.send(viewAction: .selectServer)
}
}
/// The form with text fields for username and password, along with a submit button.
var loginForm: some View {
VStack(spacing: 14) {
TextField(ElementL10n.loginSigninUsernameHint, text: $viewModel.username)
TextField(ElementL10n.loginSigninUsernameHint, text: $context.username)
.focused($isUsernameFocused)
.textFieldStyle(.elementInput())
.disableAutocorrection(true)
@@ -96,7 +96,7 @@ struct LoginScreen: View {
Spacer().frame(height: 20)
SecureField(ElementL10n.loginSignupPasswordHint, text: $viewModel.password)
SecureField(ElementL10n.loginSignupPasswordHint, text: $context.password)
.focused($isPasswordFocused)
.textFieldStyle(.elementInput())
.textContentType(.password)
@@ -104,7 +104,7 @@ struct LoginScreen: View {
.onSubmit(submit)
.accessibilityIdentifier("passwordTextField")
Button { viewModel.send(viewAction: .forgotPassword) } label: {
Button { context.send(viewAction: .forgotPassword) } label: {
Text(ElementL10n.authenticationLoginForgotPassword)
.font(.element.body)
}
@@ -115,14 +115,14 @@ struct LoginScreen: View {
Text(ElementL10n.loginSignupSubmit)
}
.buttonStyle(.elementAction(.xLarge))
.disabled(!viewModel.viewState.canSubmit)
.disabled(!context.viewState.canSubmit)
.accessibilityIdentifier("nextButton")
}
}
/// The OIDC button that can be used for login.
var oidcButton: some View {
Button { viewModel.send(viewAction: .continueWithOIDC) } label: {
Button { context.send(viewAction: .continueWithOIDC) } label: {
Text(ElementL10n.loginContinue)
}
.buttonStyle(.elementAction(.xLarge))
@@ -141,14 +141,14 @@ struct LoginScreen: View {
/// Parses the username for a homeserver.
private func usernameFocusChanged(isFocussed: Bool) {
guard !isFocussed, !viewModel.username.isEmpty else { return }
viewModel.send(viewAction: .parseUsername)
guard !isFocussed, !context.username.isEmpty else { return }
context.send(viewAction: .parseUsername)
}
/// Sends the `next` view action so long as valid credentials have been input.
private func submit() {
guard viewModel.viewState.canSubmit else { return }
viewModel.send(viewAction: .next)
guard context.viewState.canSubmit else { return }
context.send(viewAction: .next)
}
}
@@ -171,7 +171,7 @@ struct Login_Previews: PreviewProvider {
static func screen(for viewModel: LoginViewModel) -> some View {
NavigationView {
LoginScreen(viewModel: viewModel.context)
LoginScreen(context: viewModel.context)
.navigationBarTitleDisplayMode(.inline)
.tint(.element.accent)
}
@@ -0,0 +1,44 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
enum MockServerSelectionScreenState: CaseIterable {
case matrix
case emptyAddress
case invalidAddress
case nonModal
/// Generate the view struct for the screen state.
@MainActor var viewModel: ServerSelectionViewModel {
switch self {
case .matrix:
return ServerSelectionViewModel(homeserverAddress: "https://matrix.org",
hasModalPresentation: true)
case .emptyAddress:
return ServerSelectionViewModel(homeserverAddress: "",
hasModalPresentation: true)
case .invalidAddress:
let viewModel = ServerSelectionViewModel(homeserverAddress: "thisisbad",
hasModalPresentation: true)
viewModel.displayError(.footerMessage(ElementL10n.unknownError))
return viewModel
case .nonModal:
return ServerSelectionViewModel(homeserverAddress: "https://matrix.org",
hasModalPresentation: false)
}
}
}
@@ -0,0 +1,110 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct ServerSelectionCoordinatorParameters {
/// The homeserver to be shown initially.
let homeserver: LoginHomeserver
/// Whether the screen is presented modally or within a navigation stack.
let hasModalPresentation: Bool
}
enum ServerSelectionCoordinatorResult {
case selected(LoginHomeserver)
case dismiss
}
final class ServerSelectionCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: ServerSelectionCoordinatorParameters
private let serverSelectionHostingController: UIViewController
private var serverSelectionViewModel: ServerSelectionViewModelProtocol
private var indicatorPresenter: UserIndicatorTypePresenterProtocol
private var loadingIndicator: UserIndicator?
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var callback: (@MainActor (ServerSelectionCoordinatorResult) -> Void)?
// MARK: - Setup
init(parameters: ServerSelectionCoordinatorParameters) {
self.parameters = parameters
let viewModel = ServerSelectionViewModel(homeserverAddress: parameters.homeserver.address,
hasModalPresentation: parameters.hasModalPresentation)
let view = ServerSelectionScreen(context: viewModel.context)
serverSelectionViewModel = viewModel
serverSelectionHostingController = UIHostingController(rootView: view)
indicatorPresenter = UserIndicatorTypePresenter(presentingViewController: serverSelectionHostingController)
}
// MARK: - Public
func start() {
MXLog.debug("[ServerSelectionCoordinator] did start.")
serverSelectionViewModel.callback = { [weak self] result in
guard let self = self else { return }
MXLog.debug("[ServerSelectionCoordinator] ServerSelectionViewModel did complete with result: \(result).")
switch result {
case .confirm(let homeserverAddress):
self.useHomeserver(homeserverAddress)
case .dismiss:
self.callback?(.dismiss)
}
}
}
func toPresentable() -> UIViewController {
serverSelectionHostingController
}
// MARK: - Private
/// Show an activity indicator whilst loading.
/// - Parameters:
/// - label: The label to show on the indicator.
/// - isInteractionBlocking: Whether the indicator should block any user interaction.
private func startLoading(label: String = ElementL10n.loading, isInteractionBlocking: Bool = true) {
loadingIndicator = indicatorPresenter.present(.loading(label: label, isInteractionBlocking: isInteractionBlocking))
}
/// Hide the currently displayed activity indicator.
private func stopLoading() {
loadingIndicator = nil
}
/// Updates the login flow using the supplied homeserver address, or shows an error when this isn't possible.
private func useHomeserver(_ homeserverAddress: String) {
startLoading()
let homeserverAddress = LoginHomeserver.sanitized(homeserverAddress)
stopLoading()
callback?(.selected(LoginHomeserver(address: homeserverAddress)))
}
}
@@ -0,0 +1,78 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// MARK: View model
enum ServerSelectionViewModelResult {
/// The user would like to use the homeserver at the given address.
case confirm(homeserverAddress: String)
/// Dismiss the view without using the entered address.
case dismiss
}
// MARK: View
struct ServerSelectionViewState: BindableState {
/// View state that can be bound to from SwiftUI.
var bindings: ServerSelectionBindings
/// An error message to be shown in the text field footer.
var footerErrorMessage: String?
/// Whether the screen is presented modally or within a navigation stack.
var hasModalPresentation: Bool
/// The message to show in the text field footer.
var footerMessage: String {
footerErrorMessage ?? ElementL10n.serverSelectionServerFooter
}
/// The title shown on the confirm button.
var buttonTitle: String {
hasModalPresentation ? ElementL10n.actionConfirm : ElementL10n.actionNext
}
/// The text field is showing an error.
var isShowingFooterError: Bool {
footerErrorMessage != nil
}
/// Whether it is possible to continue when tapping the confirmation button.
var hasValidationError: Bool {
bindings.homeserverAddress.isEmpty || isShowingFooterError
}
}
struct ServerSelectionBindings {
/// The homeserver address input by the user.
var homeserverAddress: String
/// Information describing the currently displayed alert.
var alertInfo: AlertInfo<ServerSelectionErrorType>?
}
enum ServerSelectionViewAction {
/// The user would like to use the homeserver at the input address.
case confirm
/// Dismiss the view without using the entered address.
case dismiss
/// Clear any errors shown in the text field footer.
case clearFooterError
}
enum ServerSelectionErrorType: Hashable {
/// An error message to be shown in the text field footer.
case footerMessage(String)
}
@@ -0,0 +1,68 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
typealias ServerSelectionViewModelType = StateStoreViewModel<ServerSelectionViewState, ServerSelectionViewAction>
class ServerSelectionViewModel: ServerSelectionViewModelType, ServerSelectionViewModelProtocol {
// MARK: - Properties
// MARK: Private
// MARK: Public
var callback: (@MainActor (ServerSelectionViewModelResult) -> Void)?
// MARK: - Setup
init(homeserverAddress: String, hasModalPresentation: Bool) {
let bindings = ServerSelectionBindings(homeserverAddress: homeserverAddress)
super.init(initialViewState: ServerSelectionViewState(bindings: bindings,
hasModalPresentation: hasModalPresentation))
}
// MARK: - Public
override func process(viewAction: ServerSelectionViewAction) async {
switch viewAction {
case .confirm:
callback?(.confirm(homeserverAddress: state.bindings.homeserverAddress))
case .dismiss:
callback?(.dismiss)
case .clearFooterError:
clearFooterError()
}
}
func displayError(_ type: ServerSelectionErrorType) {
switch type {
case .footerMessage(let message):
withAnimation {
state.footerErrorMessage = message
}
}
}
// MARK: - Private
/// Clear any errors shown in the text field footer.
private func clearFooterError() {
guard state.footerErrorMessage != nil else { return }
withAnimation { state.footerErrorMessage = nil }
}
}
@@ -0,0 +1,27 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@MainActor
protocol ServerSelectionViewModelProtocol {
var callback: (@MainActor (ServerSelectionViewModelResult) -> Void)? { get set }
var context: ServerSelectionViewModelType.Context { get }
/// Displays an error to the user.
func displayError(_ type: ServerSelectionErrorType)
}
@@ -0,0 +1,123 @@
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct ServerSelectionScreen: View {
// MARK: - Properties
// MARK: Private
@FocusState var isTextFieldFocused: Bool
// MARK: Public
@ObservedObject var context: ServerSelectionViewModel.Context
// MARK: Views
var body: some View {
ScrollView {
VStack(spacing: 0) {
header
.padding(.top, UIConstants.topPaddingToNavigationBar)
.padding(.bottom, 36)
serverForm
}
.readableFrame()
.padding(.horizontal, 16)
}
.background(Color.element.background, ignoresSafeAreaEdges: .all)
.toolbar { toolbar }
.alert(item: $context.alertInfo) { $0.alert }
}
/// The title, message and icon at the top of the screen.
var header: some View {
VStack(spacing: 8) {
AuthenticationIconImage(image: Asset.Images.serverSelectionIcon)
.padding(.bottom, 8)
Text(ElementL10n.serverSelectionTitle)
.font(.element.title2B)
.multilineTextAlignment(.center)
.foregroundColor(.element.primaryContent)
Text(ElementL10n.serverSelectionMessage)
.font(.element.body)
.multilineTextAlignment(.center)
.foregroundColor(.element.secondaryContent)
}
}
/// The text field and confirm button where the user enters a server URL.
var serverForm: some View {
VStack(alignment: .leading, spacing: 12) {
TextField(ElementL10n.serverSelectionServerUrl, text: $context.homeserverAddress)
.focused($isTextFieldFocused)
.textFieldStyle(.elementInput(footerText: context.viewState.footerMessage,
isError: context.viewState.isShowingFooterError))
.keyboardType(.URL)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: context.homeserverAddress) { _ in context.send(viewAction: .clearFooterError) }
.submitLabel(.done)
.onSubmit(submit)
.accessibilityIdentifier("addressTextField")
Button(action: submit) {
Text(context.viewState.buttonTitle)
}
.buttonStyle(.elementAction(.xLarge))
.disabled(context.viewState.hasValidationError)
.accessibilityIdentifier("confirmButton")
}
}
@ToolbarContentBuilder
var toolbar: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
if context.viewState.hasModalPresentation {
Button { context.send(viewAction: .dismiss) } label: {
Text(ElementL10n.actionCancel)
}
.accessibilityIdentifier("dismissButton")
}
}
}
/// Sends the `confirm` view action so long as the text field input is valid.
func submit() {
guard !context.viewState.hasValidationError else { return }
context.send(viewAction: .confirm)
}
}
// MARK: - Previews
struct ServerSelection_Previews: PreviewProvider {
static var previews: some View {
ForEach(MockServerSelectionScreenState.allCases, id: \.self) { state in
NavigationView {
ServerSelectionScreen(context: state.viewModel.context)
.tint(.element.accent)
}
.navigationViewStyle(.stack)
}
}
}