#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
+4 -3
View File
@@ -20,13 +20,14 @@ internal typealias AssetImageTypeAlias = ImageAsset.Image
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Images {
internal static let encryptionNormal = ImageAsset(name: "Images/encryption_normal")
internal static let encryptionTrusted = ImageAsset(name: "Images/encryption_trusted")
internal static let encryptionWarning = ImageAsset(name: "Images/encryption_warning")
internal static let serverSelectionIcon = ImageAsset(name: "Images/Server Selection Icon")
internal static let splashScreenPage1 = ImageAsset(name: "Images/Splash Screen Page 1")
internal static let splashScreenPage2 = ImageAsset(name: "Images/Splash Screen Page 2")
internal static let splashScreenPage3 = ImageAsset(name: "Images/Splash Screen Page 3")
internal static let splashScreenPage4 = ImageAsset(name: "Images/Splash Screen Page 4")
internal static let encryptionNormal = ImageAsset(name: "Images/encryption_normal")
internal static let encryptionTrusted = ImageAsset(name: "Images/encryption_trusted")
internal static let encryptionWarning = ImageAsset(name: "Images/encryption_warning")
internal static let appLogo = ImageAsset(name: "Images/app-logo")
internal static let closeCircle = ImageAsset(name: "Images/close_circle")
internal static let timelineComposerSendMessage = ImageAsset(name: "Images/timelineComposerSendMessage")
@@ -10,6 +10,10 @@ import Foundation
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces
extension ElementL10n {
/// Confirm
public static let actionConfirm = ElementL10n.tr("Untranslated", "action_confirm")
/// Next
public static let actionNext = ElementL10n.tr("Untranslated", "action_next")
/// Forgot password
public static let authenticationLoginForgotPassword = ElementL10n.tr("Untranslated", "authentication_login_forgot_password")
/// Welcome back!
@@ -26,6 +30,16 @@ extension ElementL10n {
public static let screenshotDetectedMessage = ElementL10n.tr("Untranslated", "screenshot_detected_message")
/// You took a screenshot
public static let screenshotDetectedTitle = ElementL10n.tr("Untranslated", "screenshot_detected_title")
/// Cannot find a server at this URL, please check it is correct.
public static let serverSelectionGenericError = ElementL10n.tr("Untranslated", "server_selection_generic_error")
/// What is the address of your server? A server is like a home for all your data.
public static let serverSelectionMessage = ElementL10n.tr("Untranslated", "server_selection_message")
/// You can only connect to a server that has already been set up
public static let serverSelectionServerFooter = ElementL10n.tr("Untranslated", "server_selection_server_footer")
/// Server URL
public static let serverSelectionServerUrl = ElementL10n.tr("Untranslated", "server_selection_server_url")
/// Choose your server
public static let serverSelectionTitle = ElementL10n.tr("Untranslated", "server_selection_title")
/// Timeline Style
public static let settingsTimelineStyle = ElementL10n.tr("Untranslated", "settings_timeline_style")
/// Untranslated
@@ -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)
}
}
}
@@ -38,7 +38,7 @@ final class SplashScreenCoordinator: Coordinator, Presentable {
init() {
let viewModel = SplashScreenViewModel()
let view = SplashScreen(viewModel: viewModel.context)
let view = SplashScreen(context: viewModel.context)
splashScreenViewModel = viewModel
splashScreenHostingController = UIHostingController(rootView: view)
@@ -28,7 +28,7 @@ struct SplashScreen: View {
@Environment(\.layoutDirection) private var layoutDirection
private var isLeftToRight: Bool { layoutDirection == .leftToRight }
private var pageCount: Int { viewModel.viewState.content.count }
private var pageCount: Int { context.viewState.content.count }
/// A timer to automatically animate the pages.
@State private var pageTimer: Timer?
@@ -37,7 +37,7 @@ struct SplashScreen: View {
// MARK: Public
@ObservedObject var viewModel: SplashScreenViewModel.Context
@ObservedObject var context: SplashScreenViewModel.Context
var body: some View {
GeometryReader { geometry in
@@ -49,12 +49,12 @@ struct SplashScreen: View {
HStack(alignment: .top, spacing: 0) {
// Add a hidden page at the start of the carousel duplicating the content of the last page
SplashScreenPage(content: viewModel.viewState.content[pageCount - 1])
SplashScreenPage(content: context.viewState.content[pageCount - 1])
.frame(width: geometry.size.width)
.accessibilityIdentifier("hiddenPage")
ForEach(0..<pageCount, id: \.self) { index in
SplashScreenPage(content: viewModel.viewState.content[index])
SplashScreenPage(content: context.viewState.content[index])
.frame(width: geometry.size.width)
}
@@ -63,7 +63,7 @@ struct SplashScreen: View {
Spacer()
SplashScreenPageIndicator(pageCount: pageCount, pageIndex: viewModel.pageIndex)
SplashScreenPageIndicator(pageCount: pageCount, pageIndex: context.pageIndex)
.frame(width: geometry.size.width)
.padding(.bottom)
@@ -93,7 +93,7 @@ struct SplashScreen: View {
/// The main action buttons.
var buttons: some View {
VStack(spacing: 12) {
Button { viewModel.send(viewAction: .login) } label: {
Button { context.send(viewAction: .login) } label: {
Text(ElementL10n.loginSplashSubmit)
}
.buttonStyle(.elementAction(.xLarge))
@@ -107,7 +107,7 @@ struct SplashScreen: View {
/// The view's background, showing a gradient in light mode and a solid colour in dark mode.
var background: some View {
if colorScheme == .light {
LinearGradient(gradient: viewModel.viewState.backgroundGradient,
LinearGradient(gradient: context.viewState.backgroundGradient,
startPoint: .leading,
endPoint: .trailing)
.flipsForRightToLeftLayoutDirection(true)
@@ -123,7 +123,7 @@ struct SplashScreen: View {
guard pageTimer == nil else { return }
pageTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
if viewModel.pageIndex == pageCount - 1 {
if context.pageIndex == pageCount - 1 {
showHiddenPage()
withAnimation(.easeInOut(duration: 0.7)) {
@@ -147,22 +147,22 @@ struct SplashScreen: View {
private func showNextPage() {
// Wrap back round to the first page index when reaching the end.
viewModel.pageIndex = (viewModel.pageIndex + 1) % viewModel.viewState.content.count
context.pageIndex = (context.pageIndex + 1) % context.viewState.content.count
}
private func showPreviousPage() {
// Prevent the hidden page at index -1 from being shown.
viewModel.pageIndex = max(0, (viewModel.pageIndex - 1))
context.pageIndex = max(0, (context.pageIndex - 1))
}
private func showHiddenPage() {
// Hidden page for a nicer animation when looping back to the start.
viewModel.pageIndex = -1
context.pageIndex = -1
}
/// The offset to apply to the `HStack` of pages.
private func pageOffset(in geometry: GeometryProxy) -> CGFloat {
(CGFloat(viewModel.pageIndex + 1) * -geometry.size.width) + dragOffset
(CGFloat(context.pageIndex + 1) * -geometry.size.width) + dragOffset
}
// MARK: - Gestures
@@ -171,9 +171,9 @@ struct SplashScreen: View {
/// - Parameter width: The gesture's translation width.
/// - Returns: `true` if there is another page to drag to.
private func shouldSwipeForTranslation(_ width: CGFloat) -> Bool {
if viewModel.pageIndex == 0 {
if context.pageIndex == 0 {
return isLeftToRight ? width < 0 : width > 0
} else if viewModel.pageIndex == pageCount - 1 {
} else if context.pageIndex == pageCount - 1 {
return isLeftToRight ? width > 0 : width < 0
}
@@ -220,7 +220,7 @@ struct SplashScreen_Previews: PreviewProvider {
static let viewModel = SplashScreenViewModel()
static var previews: some View {
SplashScreen(viewModel: viewModel.context)
SplashScreen(context: viewModel.context)
.tint(.element.accent)
}
}