#40: Add OnboardingSplashScreen from EI.

Update SplashScreen for EXI
This commit is contained in:
Doug
2022-06-13 17:28:36 +01:00
committed by Doug
parent 272fc5000b
commit 8dc5359a44
32 changed files with 5891 additions and 104 deletions
+4 -52
View File
@@ -10,8 +10,6 @@
#endif
// Deprecated typealiases
@available(*, deprecated, renamed: "ColorAsset.Color", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias AssetColorTypeAlias = ColorAsset.Color
@available(*, deprecated, renamed: "ImageAsset.Image", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias AssetImageTypeAlias = ImageAsset.Image
@@ -21,10 +19,11 @@ internal typealias AssetImageTypeAlias = ImageAsset.Image
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Colors {
internal static let codeBlockBackground = ColorAsset(name: "Colors/CodeBlockBackground")
}
internal enum Images {
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 appLogo = ImageAsset(name: "Images/app-logo")
internal static let closeCircle = ImageAsset(name: "Images/close_circle")
internal static let timelineComposerSendMessage = ImageAsset(name: "Images/timelineComposerSendMessage")
@@ -35,53 +34,6 @@ internal enum Asset {
// MARK: - Implementation Details
internal final class ColorAsset {
internal fileprivate(set) var name: String
#if os(macOS)
internal typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
internal typealias Color = UIColor
#endif
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
internal private(set) lazy var color: Color = {
guard let color = Color(asset: self) else {
fatalError("Unable to load color asset named \(name).")
}
return color
}()
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
internal func color(compatibleWith traitCollection: UITraitCollection) -> Color {
let bundle = BundleToken.bundle
guard let color = Color(named: name, in: bundle, compatibleWith: traitCollection) else {
fatalError("Unable to load color asset named \(name).")
}
return color
}
#endif
fileprivate init(name: String) {
self.name = name
}
}
internal extension ColorAsset.Color {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
convenience init?(asset: ColorAsset) {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct ImageAsset {
internal fileprivate(set) var name: String
@@ -140,7 +140,7 @@ struct AttributedStringBuilder: AttributedStringBuilderProtocol {
attributedString.enumerateAttribute(.backgroundColor, in: .init(location: 0, length: attributedString.length), options: []) { value, range, _ in
if let value = value as? UIColor,
value == temporaryCodeBlockMarkingColor {
attributedString.addAttribute(.backgroundColor, value: Asset.Colors.codeBlockBackground.color as Any, range: range)
attributedString.addAttribute(.backgroundColor, value: UIColor.element.quinaryContent as Any, range: range)
}
}
}
@@ -0,0 +1,26 @@
//
// 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
/// A SwiftUI `PreferenceKey` for `CGRect` values such as a view's frame.
struct FramePreferenceKey: PreferenceKey {
static var defaultValue: CGRect = .zero
static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
value = nextValue()
}
}
@@ -0,0 +1,42 @@
//
// 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
import SwiftUI
/// Used to calculate the frame of a view.
///
/// Useful in situations as with `ZStack` where you might want to layout views using alignment guides.
/// ```
/// @State private var frame: CGRect = CGRect.zero
/// ...
/// SomeView()
/// .background(ViewFrameReader(frame: $frame))
/// ```
struct ViewFrameReader: View {
@Binding var frame: CGRect
var body: some View {
GeometryReader { geometry in
Color.clear
.preference(key: FramePreferenceKey.self,
value: geometry.frame(in: .local))
}
.onPreferenceChange(FramePreferenceKey.self) {
frame = $0
}
}
}
@@ -0,0 +1,39 @@
//
// 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
/// Metrics used across the entire onboarding flow.
struct OnboardingMetrics {
static let maxContentWidth: CGFloat = 600
static let maxContentHeight: CGFloat = 750
/// The padding used between the top of the main content and the navigation bar.
static let topPaddingToNavigationBar: CGFloat = 16
/// The padding used between the footer and the bottom of the view.
static let actionButtonBottomPadding: CGFloat = 24
/// The width/height used for the main icon shown in most of the screens.
static let iconSize: CGFloat = 90
/// The padding used to the top of the view for breaker screens that don't have a navigation bar.
static let breakerScreenTopPadding: CGFloat = 80
static let breakerScreenIconBottomPadding: CGFloat = 42
/// The height to use for top/bottom spacers to pad the views to fit the `maxContentHeight`.
static func spacerHeight(in geometry: GeometryProxy) -> CGFloat {
max(0, (geometry.size.height - maxContentHeight) / 2)
}
}
@@ -0,0 +1,29 @@
//
// 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
extension String {
func tinting(_ character: Character, color: Color = .accentColor) -> AttributedString {
var string = AttributedString(self)
let characterView = string.characters
for index in characterView.indices where characterView[index] == character {
string[index..<characterView.index(after: index)].foregroundColor = color
}
return string
}
}
@@ -0,0 +1,87 @@
//
// 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
protocol SplashScreenCoordinatorProtocol: Coordinator, Presentable {
var callback: ((SplashScreenCoordinatorAction) -> Void)? { get set }
}
final class SplashScreenCoordinator: SplashScreenCoordinatorProtocol {
// MARK: - Properties
// MARK: Private
private let splashScreenHostingController: UIViewController
private var splashScreenViewModel: SplashScreenViewModelProtocol
private var indicatorPresenter: UserIndicatorTypePresenterProtocol
private var loadingIndicator: UserIndicator?
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var callback: ((SplashScreenCoordinatorAction) -> Void)?
// MARK: - Setup
init() {
let viewModel = SplashScreenViewModel()
let view = SplashScreen(viewModel: viewModel.context)
splashScreenViewModel = viewModel
splashScreenHostingController = UIHostingController(rootView: view)
indicatorPresenter = UserIndicatorTypePresenter(presentingViewController: splashScreenHostingController)
}
// MARK: - Public
func start() {
MXLog.debug("[SplashScreenCoordinator] did start.")
splashScreenViewModel.callback = { [weak self] action in
MXLog.debug("[SplashScreenCoordinator] SplashScreenViewModel did complete with result: \(action).")
guard let self = self else { return }
switch action {
case .login:
self.callback?(.login)
case .register:
self.callback?(.register)
}
}
}
func toPresentable() -> UIViewController {
return splashScreenHostingController
}
/// Stops any ongoing activities in the coordinator.
func stop() {
stopLoading()
}
// MARK: - Private
/// Show an activity indicator whilst loading.
private func startLoading() {
loadingIndicator = indicatorPresenter.present(.loading(label: ElementL10n.loading, isInteractionBlocking: true))
}
/// Hide the currently displayed activity indicator.
private func stopLoading() {
loadingIndicator = nil
}
}
@@ -0,0 +1,97 @@
//
// 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
// MARK: - Coordinator
enum SplashScreenCoordinatorAction {
case register
case login
}
/// The content displayed in a single splash screen page.
struct SplashScreenPageContent {
let title: AttributedString
let message: String
let image: ImageAsset
let gradient: Gradient
}
// MARK: View model
enum SplashScreenViewModelAction {
case register
case login
}
// MARK: View
struct SplashScreenViewState: BindableState, CustomDebugStringConvertible {
private enum Constants {
static let gradientColors = [
Color(red: 0.95, green: 0.98, blue: 0.96),
Color(red: 0.89, green: 0.96, blue: 0.97),
Color(red: 0.95, green: 0.89, blue: 0.97),
Color(red: 0.81, green: 0.95, blue: 0.91),
Color(red: 0.95, green: 0.98, blue: 0.96)
]
}
/// An array containing all content of the carousel pages
let content: [SplashScreenPageContent]
var bindings: SplashScreenBindings
/// Custom debug description to reduce noise in the logs.
var debugDescription: String {
"SplashScreenViewState at page \(bindings.pageIndex)."
}
init() {
// The pun doesn't translate, so we only use it for English.
let locale = Locale.current
let page4Title = locale.identifier.hasPrefix("en") ? "Cut the slack from teams." : ElementL10n.ftueAuthCarouselWorkplaceTitle
self.content = [
SplashScreenPageContent(title: ElementL10n.ftueAuthCarouselSecureTitle.tinting("."),
message: ElementL10n.ftueAuthCarouselSecureBody,
image: Asset.Images.splashScreenPage1,
gradient: Gradient(colors: [Constants.gradientColors[0], Constants.gradientColors[1]])),
SplashScreenPageContent(title: ElementL10n.ftueAuthCarouselControlTitle.tinting("."),
message: ElementL10n.ftueAuthCarouselControlBody,
image: Asset.Images.splashScreenPage2,
gradient: Gradient(colors: [Constants.gradientColors[1], Constants.gradientColors[2]])),
SplashScreenPageContent(title: ElementL10n.ftueAuthCarouselEncryptedTitle.tinting("."),
message: ElementL10n.ftueAuthCarouselEncryptedBody,
image: Asset.Images.splashScreenPage3,
gradient: Gradient(colors: [Constants.gradientColors[2], Constants.gradientColors[3]])),
SplashScreenPageContent(title: page4Title.tinting("."),
message: ElementL10n.ftueAuthCarouselWorkplaceBody(ElementInfoPlist.cfBundleName),
image: Asset.Images.splashScreenPage4,
gradient: Gradient(colors: [Constants.gradientColors[3], Constants.gradientColors[4]]))
]
self.bindings = SplashScreenBindings()
}
}
struct SplashScreenBindings {
var pageIndex = 0
}
enum SplashScreenViewAction {
case register
case login
}
@@ -0,0 +1,56 @@
//
// 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
import Combine
typealias SplashScreenViewModelType = StateStoreViewModel<SplashScreenViewState, SplashScreenViewAction>
class SplashScreenViewModel: SplashScreenViewModelType, SplashScreenViewModelProtocol {
// MARK: - Properties
// MARK: Private
// MARK: Public
var callback: ((SplashScreenViewModelAction) -> Void)?
// MARK: - Setup
init() {
super.init(initialViewState: SplashScreenViewState())
}
// MARK: - Public
override func process(viewAction: SplashScreenViewAction) async {
switch viewAction {
case .register:
register()
case .login:
login()
}
}
private func register() {
callback?(.register)
}
private func login() {
callback?(.login)
}
}
@@ -0,0 +1,23 @@
//
// 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 SplashScreenViewModelProtocol {
var callback: ((SplashScreenViewModelAction) -> Void)? { get set }
var context: SplashScreenViewModelType.Context { get }
}
@@ -0,0 +1,210 @@
//
// 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
/// The splash screen shown at the beginning of the onboarding flow.
struct SplashScreen: View {
// MARK: - Properties
// MARK: Private
@Environment(\.layoutDirection) private var layoutDirection
private var isLeftToRight: Bool { layoutDirection == .leftToRight }
private var pageCount: Int { viewModel.viewState.content.count }
/// The dimensions of the stack with the action buttons and page indicator.
@State private var overlayFrame: CGRect = .zero
/// A timer to automatically animate the pages.
@State private var pageTimer: Timer?
/// The amount of offset to apply when a drag gesture is in progress.
@State private var dragOffset: CGFloat = .zero
// MARK: Public
@ObservedObject var viewModel: SplashScreenViewModel.Context
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
// The main content of the carousel
HStack(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],
overlayHeight: overlayFrame.height + geometry.safeAreaInsets.bottom)
.frame(width: geometry.size.width)
.tag(-1)
ForEach(0..<pageCount, id: \.self) { index in
SplashScreenPage(content: viewModel.viewState.content[index],
overlayHeight: overlayFrame.height + geometry.safeAreaInsets.bottom)
.frame(width: geometry.size.width)
.tag(index)
}
}
.offset(x: (CGFloat(viewModel.pageIndex + 1) * -geometry.size.width) + dragOffset)
.gesture(
DragGesture()
.onChanged(handleDragGestureChange)
.onEnded { handleDragGestureEnded($0, viewSize: geometry.size) }
)
overlay
.frame(width: geometry.size.width)
}
}
.background(Color.element.background.ignoresSafeArea())
.navigationBarHidden(true)
.onAppear(perform: startTimer)
.onDisappear(perform: stopTimer)
}
/// The only part of the UI that isn't inside of the carousel.
var overlay: some View {
VStack(spacing: 50) {
Color.clear
Color.clear
VStack {
SplashScreenPageIndicator(pageCount: pageCount,
pageIndex: viewModel.pageIndex)
Spacer()
buttons
.padding(.horizontal, 16)
.frame(maxWidth: OnboardingMetrics.maxContentWidth)
Spacer()
}
.background(ViewFrameReader(frame: $overlayFrame))
}
}
/// The main action buttons.
var buttons: some View {
VStack(spacing: 12) {
Button { viewModel.send(viewAction: .login) } label: {
Text(ElementL10n.loginSplashSubmit)
}
.buttonStyle(.elementAction(.xLarge))
}
}
// MARK: - Animation
func nextPage() {
// Wrap back round to the first page index when reaching the end.
viewModel.pageIndex = (viewModel.pageIndex + 1) % viewModel.viewState.content.count
}
func previousPage() {
// Prevent the hidden page at index -1 from being shown.
viewModel.pageIndex = max(0, (viewModel.pageIndex - 1))
}
func hiddenPage() {
// Hidden page for a nicer animation when looping back to the start.
viewModel.pageIndex = -1
}
/// Starts the animation timer for an automatic carousel effect.
private func startTimer() {
guard pageTimer == nil else { return }
pageTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
if viewModel.pageIndex == pageCount - 1 {
hiddenPage()
withAnimation(.easeInOut(duration: 0.7)) {
nextPage()
}
} else {
withAnimation(.easeInOut(duration: 0.7)) {
nextPage()
}
}
}
}
/// Stops the animation timer for manual interaction.
private func stopTimer() {
guard let pageTimer = pageTimer else { return }
self.pageTimer = nil
pageTimer.invalidate()
}
// MARK: - Gestures
/// Whether or not a drag gesture is valid or not.
/// - 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 {
return isLeftToRight ? width < 0 : width > 0
} else if viewModel.pageIndex == pageCount - 1 {
return isLeftToRight ? width > 0 : width < 0
}
return true
}
/// Updates the `dragOffset` based on the gesture's value.
/// - Parameter drag: The drag gesture value to handle.
private func handleDragGestureChange(_ drag: DragGesture.Value) {
guard shouldSwipeForTranslation(drag.translation.width) else { return }
stopTimer()
// Animate the change over a few frames to smooth out any stuttering.
withAnimation(.linear(duration: 0.05)) {
dragOffset = isLeftToRight ? drag.translation.width : -drag.translation.width
}
}
/// Clears the drag offset and informs the view model to switch to another page if necessary.
/// - Parameter viewSize: The size of the view in which the gesture took place.
private func handleDragGestureEnded(_ drag: DragGesture.Value, viewSize: CGSize) {
guard shouldSwipeForTranslation(drag.predictedEndTranslation.width) else {
// Reset the offset just in case.
withAnimation { dragOffset = 0 }
return
}
withAnimation(.easeInOut(duration: 0.2)) {
if drag.predictedEndTranslation.width < -viewSize.width / 2 {
nextPage()
} else if drag.predictedEndTranslation.width > viewSize.width / 2 {
previousPage()
}
dragOffset = 0
}
}
}
// MARK: - Previews
struct SplashScreen_Previews: PreviewProvider {
static let viewModel = SplashScreenViewModel()
static var previews: some View {
SplashScreen(viewModel: viewModel.context)
.accentColor(.element.accent)
}
}
@@ -0,0 +1,86 @@
//
// 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 SplashScreenPage: View {
// MARK: - Properties
// MARK: Private
@Environment(\.colorScheme) private var colorScheme
// MARK: Public
/// The content that this page should display.
let content: SplashScreenPageContent
/// The height of the non-scrollable content in the splash screen.
let overlayHeight: CGFloat
// MARK: - Views
@ViewBuilder
var backgroundGradient: some View {
if colorScheme != .dark {
LinearGradient(gradient: content.gradient, startPoint: .leading, endPoint: .trailing)
.flipsForRightToLeftLayoutDirection(true)
}
}
var body: some View {
VStack {
VStack {
Image(content.image.name)
.resizable()
.scaledToFit()
.frame(maxWidth: 300)
.padding(20)
.accessibilityHidden(true)
VStack(spacing: 8) {
Text(content.title)
.font(.element.title2B)
.foregroundColor(.element.primaryContent)
Text(content.message)
.font(.element.body)
.foregroundColor(.element.secondaryContent)
.multilineTextAlignment(.center)
}
.padding(.bottom)
Spacer()
// Prevent the content from clashing with the overlay content.
Spacer().frame(maxHeight: overlayHeight)
}
.padding(.horizontal, 16)
.frame(maxWidth: OnboardingMetrics.maxContentWidth,
maxHeight: OnboardingMetrics.maxContentHeight)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(backgroundGradient.ignoresSafeArea())
}
}
struct SplashScreenPage_Previews: PreviewProvider {
static let content = SplashScreenViewState().content
static var previews: some View {
ForEach(0..<content.count, id: \.self) { index in
SplashScreenPage(content: content[index], overlayHeight: 200)
}
}
}
@@ -0,0 +1,52 @@
//
// 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 SplashScreenPageIndicator: View {
// MARK: - Properties
// MARK: Public
/// The number of pages that are shown.
let pageCount: Int
/// The index of the current page
let pageIndex: Int
// MARK: - Setup
internal init(pageCount: Int, pageIndex: Int) {
self.pageCount = pageCount
// Clamp the page index to handle the hidden page.
if pageIndex == -1 {
self.pageIndex = pageCount - 1
} else {
self.pageIndex = pageIndex % pageCount
}
}
var body: some View {
HStack {
ForEach(0..<pageCount, id: \.self) { index in
Circle()
.frame(width: 8, height: 8)
.foregroundColor(index == pageIndex ? .accentColor : .element.quaternaryContent)
}
}
}
}
@@ -49,15 +49,7 @@ class AuthenticationCoordinator: Coordinator {
let availableAccessTokens = keychainController.accessTokens()
guard let usernameTokenTuple = availableAccessTokens.first else {
startNewLoginFlow { result in
switch result {
case .success:
self.delegate?.authenticationCoordinatorDidSetupClientProxy(self)
case .failure(let error):
self.delegate?.authenticationCoordinator(self, didFailWithError: error)
MXLog.error("Failed logging in user with error: \(error)")
}
}
showSplashScreen()
return
}
@@ -90,16 +82,43 @@ class AuthenticationCoordinator: Coordinator {
// MARK: - Private
private func showSplashScreen() {
let coordinator = SplashScreenCoordinator()
coordinator.callback = { [weak self] action in
guard let self = self else { return }
switch action {
case .login:
self.startNewLoginFlow { result in
switch result {
case .success:
self.delegate?.authenticationCoordinatorDidSetupClientProxy(self)
case .failure(let error):
self.delegate?.authenticationCoordinator(self, didFailWithError: error)
MXLog.error("Failed logging in user with error: \(error)")
}
}
case .register:
fatalError("Not implemented")
}
}
add(childCoordinator: coordinator)
navigationRouter.setRootModule(coordinator)
coordinator.start()
}
private func startNewLoginFlow(_ completion: @escaping (Result<(), AuthenticationCoordinatorError>) -> Void) {
let parameters = LoginScreenCoordinatorParameters()
let coordinator = LoginScreenCoordinator(parameters: parameters)
coordinator.callback = { [weak self, weak coordinator] result in
coordinator.callback = { [weak self, weak coordinator] action in
guard let self = self, let coordinator = coordinator else {
return
}
switch result {
switch action {
case .login(let result):
Task {
switch await self.login(username: result.username, password: result.password) {
+3 -1
View File
@@ -19,6 +19,7 @@ class UITestsAppCoordinator: Coordinator {
mainNavigationController = UINavigationController()
window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = mainNavigationController
window.tintColor = .element.accent
let screens = mockScreens()
let rootView = UITestsRootView(mockScreens: screens) { id in
@@ -43,7 +44,8 @@ class UITestsAppCoordinator: Coordinator {
MockScreen(id: "Simple Screen - Upgrade", coordinator: TemplateSimpleScreenCoordinator(parameters: .init(promptType: .upgrade))),
MockScreen(id: "Settings screen", coordinator: SettingsCoordinator(parameters: .init(navigationRouter: NavigationRouter(navigationController: UINavigationController()), bugReportService: MockBugReportService()))),
MockScreen(id: "Bug report screen", coordinator: BugReportCoordinator(parameters: .init(bugReportService: MockBugReportService(), screenshot: nil))),
MockScreen(id: "Bug report screen with screenshot", coordinator: BugReportCoordinator(parameters: .init(bugReportService: MockBugReportService(), screenshot: Asset.Images.appLogo.image)))
MockScreen(id: "Bug report screen with screenshot", coordinator: BugReportCoordinator(parameters: .init(bugReportService: MockBugReportService(), screenshot: Asset.Images.appLogo.image))),
MockScreen(id: "Splash Screen", coordinator: SplashScreenCoordinator())
]
}
}