Onboarding flow coordinator and FTUE changes (#2578)

Fixes #2595, fixes #2594, fixes #2593, fixes #2592, fixes #2591
This commit is contained in:
Stefan Ceriu
2024-03-21 14:01:23 +02:00
committed by GitHub
parent 9e6b6ba60a
commit a62c96f1c5
176 changed files with 1886 additions and 912 deletions
@@ -0,0 +1,63 @@
//
// 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 Combine
import SwiftUI
enum AnalyticsPromptScreenCoordinatorAction {
case done
}
final class AnalyticsPromptScreenCoordinator: CoordinatorProtocol {
private let analytics: AnalyticsService
private var viewModel: AnalyticsPromptScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<AnalyticsPromptScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<AnalyticsPromptScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(analytics: AnalyticsService, termsURL: URL) {
self.analytics = analytics
viewModel = AnalyticsPromptScreenViewModel(termsURL: termsURL)
}
// MARK: - Public
func start() {
viewModel.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .enable:
MXLog.info("Enable Analytics")
analytics.optIn()
actionsSubject.send(.done)
case .disable:
MXLog.info("Disable Analytics")
analytics.optOut()
actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(AnalyticsPromptScreen(context: viewModel.context))
}
}
@@ -0,0 +1,58 @@
//
// 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
enum AnalyticsPromptScreenViewAction {
/// Enable analytics.
case enable
/// Disable analytics.
case disable
}
enum AnalyticsPromptScreenViewModelAction {
/// Enable analytics.
case enable
/// Disable analytics.
case disable
}
struct AnalyticsPromptScreenViewState: BindableState {
/// Attributed strings created from localized HTML.
let strings: AnalyticsPromptScreenStrings
}
/// A collection of strings for the UI that need to be parsed from HTML
struct AnalyticsPromptScreenStrings {
let optInContent: AttributedString
let point1 = L10n.screenAnalyticsPromptDataUsage
let point2 = L10n.screenAnalyticsPromptThirdPartySharing
let point3 = L10n.screenAnalyticsPromptSettings
init(termsURL: URL) {
let content = AttributedString(L10n.screenAnalyticsPromptHelpUsImprove)
// Create the 'read terms' with a placeholder.
let linkPlaceholder = "{link}"
var readTerms = AttributedString(L10n.screenAnalyticsSettingsReadTerms(linkPlaceholder))
var linkString = AttributedString(L10n.screenAnalyticsSettingsReadTermsContentLink)
linkString.link = termsURL
linkString.bold()
readTerms.replace(linkPlaceholder, with: linkString)
optInContent = content + "\n\n" + readTerms
}
}
@@ -0,0 +1,45 @@
//
// 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 Combine
import SwiftUI
typealias AnalyticsPromptScreenViewModelType = StateStoreViewModel<AnalyticsPromptScreenViewState, AnalyticsPromptScreenViewAction>
class AnalyticsPromptScreenViewModel: AnalyticsPromptScreenViewModelType, AnalyticsPromptScreenViewModelProtocol {
private var actionsSubject: PassthroughSubject<AnalyticsPromptScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<AnalyticsPromptScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
/// Initialize a view model with the specified prompt type and app display name.
init(termsURL: URL) {
let promptStrings = AnalyticsPromptScreenStrings(termsURL: termsURL)
super.init(initialViewState: AnalyticsPromptScreenViewState(strings: promptStrings))
}
// MARK: - Public
override func process(viewAction: AnalyticsPromptScreenViewAction) {
switch viewAction {
case .enable:
actionsSubject.send(.enable)
case .disable:
actionsSubject.send(.disable)
}
}
}
@@ -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 Combine
@MainActor
protocol AnalyticsPromptScreenViewModelProtocol {
var actions: AnyPublisher<AnalyticsPromptScreenViewModelAction, Never> { get }
var context: AnalyticsPromptScreenViewModelType.Context { get }
}
@@ -0,0 +1,113 @@
//
// 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 prompt that asks the user whether they would like to enable Analytics or not.
struct AnalyticsPromptScreen: View {
@ObservedObject var context: AnalyticsPromptScreenViewModel.Context
var body: some View {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding, showBackgroundGradient: true) {
mainContent
} bottomContent: {
buttons
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.interactiveDismissDisabled()
}
/// The main content of the screen that is shown inside the scroll view.
private var mainContent: some View {
VStack(spacing: 40) {
header
checkmarkList
}
}
private var header: some View {
VStack(spacing: 8) {
HeroImage(icon: \.chart)
.padding(.bottom, 8)
Text(L10n.screenAnalyticsPromptTitle(InfoPlistReader.main.bundleDisplayName))
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
.accessibilityIdentifier(A11yIdentifiers.analyticsPromptScreen.title)
Text(context.viewState.strings.optInContent)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
}
}
@ViewBuilder
private var checkMark: some View {
Image(systemName: "checkmark.circle")
.symbolVariant(.fill)
.symbolRenderingMode(.palette)
.foregroundStyle(Color.compound.iconAccentTertiary, Color.compound.textOnSolidPrimary)
}
/// The list of re-assurances about analytics.
private var checkmarkList: some View {
VStack(alignment: .leading, spacing: 4) {
checkMarkItem(title: context.viewState.strings.point1, position: .top)
checkMarkItem(title: context.viewState.strings.point2, position: .middle)
checkMarkItem(title: context.viewState.strings.point3, position: .bottom)
}
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity)
.environment(\.backgroundStyle, AnyShapeStyle(.compound.bgSubtleSecondary))
}
@ViewBuilder
private func checkMarkItem(title: String, position: ListPosition) -> some View {
RoundedLabelItem(title: title, listPosition: position) {
checkMark
}
}
/// The stack of enable/disable buttons.
private var buttons: some View {
VStack(spacing: 16) {
Button(L10n.actionOk) { context.send(viewAction: .enable) }
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.analyticsPromptScreen.enable)
Button { context.send(viewAction: .disable) } label: {
Text(L10n.actionNotNow)
.font(.compound.bodyLGSemibold)
.padding(14)
}
.accessibilityIdentifier(A11yIdentifiers.analyticsPromptScreen.notNow)
}
}
}
// MARK: - Previews
struct AnalyticsPromptScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = AnalyticsPromptScreenViewModel(termsURL: ServiceLocator.shared.settings.analyticsConfiguration.termsURL)
static var previews: some View {
AnalyticsPromptScreen(context: viewModel.context)
}
}
@@ -0,0 +1,70 @@
//
// 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.
//
// periphery:ignore:all - this is just a identityConfirmation remove this comment once generating the final file
import Combine
import SwiftUI
struct IdentityConfirmationScreenCoordinatorParameters {
let userSession: UserSessionProtocol
let appSettings: AppSettings
let userIndicatorController: UserIndicatorControllerProtocol
}
enum IdentityConfirmationScreenCoordinatorAction {
case otherDevice
case recoveryKey
}
final class IdentityConfirmationScreenCoordinator: CoordinatorProtocol {
private let parameters: IdentityConfirmationScreenCoordinatorParameters
private let viewModel: IdentityConfirmationScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<IdentityConfirmationScreenCoordinatorAction, Never> = .init()
var actionsPublisher: AnyPublisher<IdentityConfirmationScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: IdentityConfirmationScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = IdentityConfirmationScreenViewModel(userSession: parameters.userSession,
appSettings: parameters.appSettings,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actionsPublisher.sink { [weak self] action in
guard let self else { return }
MXLog.info("Coordinator: received view model action: \(action)")
switch action {
case .otherDevice:
actionsSubject.send(.otherDevice)
case .recoveryKey:
actionsSubject.send(.recoveryKey)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(IdentityConfirmationScreen(context: viewModel.context))
}
}
@@ -0,0 +1,37 @@
//
// 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 Foundation
enum IdentityConfirmationScreenViewModelAction {
case otherDevice
case recoveryKey
}
struct IdentityConfirmationScreenViewState: BindableState {
enum Mode {
case recoveryOnly
case recoveryAndVerification
}
var mode = Mode.recoveryOnly
let learnMoreURL: URL
}
enum IdentityConfirmationScreenViewAction {
case otherDevice
case recoveryKey
}
@@ -0,0 +1,95 @@
//
// 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 Combine
import SwiftUI
typealias IdentityConfirmationScreenViewModelType = StateStoreViewModel<IdentityConfirmationScreenViewState, IdentityConfirmationScreenViewAction>
class IdentityConfirmationScreenViewModel: IdentityConfirmationScreenViewModelType, IdentityConfirmationScreenViewModelProtocol {
private let userSession: UserSessionProtocol
private let userIndicatorController: UserIndicatorControllerProtocol
private let actionsSubject: PassthroughSubject<IdentityConfirmationScreenViewModelAction, Never> = .init()
var actionsPublisher: AnyPublisher<IdentityConfirmationScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(userSession: UserSessionProtocol, appSettings: AppSettings, userIndicatorController: UserIndicatorControllerProtocol) {
self.userSession = userSession
self.userIndicatorController = userIndicatorController
super.init(initialViewState: IdentityConfirmationScreenViewState(learnMoreURL: appSettings.encryptionURL))
userSession.sessionSecurityStatePublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
Task {
await self?.updateWithSessionSecurityState(state)
}
}
.store(in: &cancellables)
Task {
await updateWithSessionSecurityState(userSession.sessionSecurityStatePublisher.value)
}
}
// MARK: - Public
override func process(viewAction: IdentityConfirmationScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .otherDevice:
actionsSubject.send(.otherDevice)
case .recoveryKey:
actionsSubject.send(.recoveryKey)
}
}
// MARK: - Private
private func updateWithSessionSecurityState(_ sessionSecurityState: SessionSecurityState) async {
if sessionSecurityState.verificationState == .unknown {
showLoadingIndicator()
} else {
hideLoadingIndicator()
}
guard sessionSecurityState.verificationState == .unverified else {
return
}
guard case let .success(isOnlyDeviceLeft) = await userSession.clientProxy.isOnlyDeviceLeft() else {
return
}
state.mode = isOnlyDeviceLeft ? .recoveryOnly : .recoveryAndVerification
}
private static let loadingIndicatorIdentifier = "\(IdentityConfirmationScreenViewModel.self)-Loading"
private func showLoadingIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
type: .modal,
title: L10n.commonLoading,
persistent: true))
}
private func hideLoadingIndicator() {
userIndicatorController.retractIndicatorWithId(Self.loadingIndicatorIdentifier)
}
}
@@ -0,0 +1,23 @@
//
// 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 Combine
@MainActor
protocol IdentityConfirmationScreenViewModelProtocol {
var actionsPublisher: AnyPublisher<IdentityConfirmationScreenViewModelAction, Never> { get }
var context: IdentityConfirmationScreenViewModelType.Context { get }
}
@@ -0,0 +1,107 @@
//
// 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 Compound
import SwiftUI
struct IdentityConfirmationScreen: View {
@ObservedObject var context: IdentityConfirmationScreenViewModel.Context
var body: some View {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding) {
screenHeader
} bottomContent: {
actionButtons
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.interactiveDismissDisabled()
}
// MARK: - Private
@ViewBuilder
private var screenHeader: some View {
VStack(spacing: 0) {
HeroImage(icon: \.lockSolid)
.padding(.bottom, 16)
Text(L10n.screenIdentityConfirmationTitle)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
.padding(.bottom, 8)
Text(L10n.screenIdentityConfirmationSubtitle)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
Button(L10n.actionLearnMore) {
UIApplication.shared.open(context.viewState.learnMoreURL)
}
.buttonStyle(.compound(.plain))
.padding(.top, 16)
}
}
@ViewBuilder
private var actionButtons: some View {
VStack(spacing: 32) {
switch context.viewState.mode {
case .recoveryOnly:
Button(L10n.screenSessionVerificationEnterRecoveryKey) {
context.send(viewAction: .recoveryKey)
}
.buttonStyle(.compound(.primary))
case .recoveryAndVerification:
Button(L10n.actionStartVerification) {
context.send(viewAction: .otherDevice)
}
.buttonStyle(.compound(.primary))
Button(L10n.screenSessionVerificationEnterRecoveryKey) {
context.send(viewAction: .recoveryKey)
}
.buttonStyle(.compound(.plain))
}
}
}
}
// MARK: - Previews
struct IdentityConfirmationScreen_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
NavigationStack {
IdentityConfirmationScreen(context: viewModel.context)
}
}
private static var viewModel: IdentityConfirmationScreenViewModel {
let userSession = MockUserSession(clientProxy: ClientProxyMock(.init(userID: "@user:example.com",
roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded([]))))),
mediaProvider: MockMediaProvider(),
voiceMessageMediaManager: VoiceMessageMediaManagerMock())
return IdentityConfirmationScreenViewModel(userSession: userSession,
appSettings: ServiceLocator.shared.settings,
userIndicatorController: ServiceLocator.shared.userIndicatorController)
}
}
@@ -0,0 +1,61 @@
//
// 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.
//
// periphery:ignore:all - this is just a identityConfirmed remove this comment once generating the final file
import Combine
import SwiftUI
struct IdentityConfirmedScreenCoordinatorParameters { }
enum IdentityConfirmedScreenCoordinatorAction {
case done
}
final class IdentityConfirmedScreenCoordinator: CoordinatorProtocol {
private let parameters: IdentityConfirmedScreenCoordinatorParameters
private let viewModel: IdentityConfirmedScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<IdentityConfirmedScreenCoordinatorAction, Never> = .init()
var actionsPublisher: AnyPublisher<IdentityConfirmedScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: IdentityConfirmedScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = IdentityConfirmedScreenViewModel()
}
func start() {
viewModel.actionsPublisher.sink { [weak self] action in
MXLog.info("Coordinator: received view model action: \(action)")
guard let self else { return }
switch action {
case .done:
self.actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(IdentityConfirmedScreen(context: viewModel.context))
}
}
@@ -0,0 +1,27 @@
//
// 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 Foundation
enum IdentityConfirmedScreenViewModelAction {
case done
}
struct IdentityConfirmedScreenViewState: BindableState { }
enum IdentityConfirmedScreenViewAction {
case done
}
@@ -0,0 +1,42 @@
//
// 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 Combine
import SwiftUI
typealias IdentityConfirmedScreenViewModelType = StateStoreViewModel<IdentityConfirmedScreenViewState, IdentityConfirmedScreenViewAction>
class IdentityConfirmedScreenViewModel: IdentityConfirmedScreenViewModelType, IdentityConfirmedScreenViewModelProtocol {
private let actionsSubject: PassthroughSubject<IdentityConfirmedScreenViewModelAction, Never> = .init()
var actionsPublisher: AnyPublisher<IdentityConfirmedScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init() {
super.init(initialViewState: .init())
}
// MARK: - Public
override func process(viewAction: IdentityConfirmedScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .done:
actionsSubject.send(.done)
}
}
}
@@ -0,0 +1,23 @@
//
// 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 Combine
@MainActor
protocol IdentityConfirmedScreenViewModelProtocol {
var actionsPublisher: AnyPublisher<IdentityConfirmedScreenViewModelAction, Never> { get }
var context: IdentityConfirmedScreenViewModelType.Context { get }
}
@@ -0,0 +1,75 @@
//
// 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 Compound
import SwiftUI
struct IdentityConfirmedScreen: View {
@ObservedObject var context: IdentityConfirmedScreenViewModel.Context
var body: some View {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding) {
screenHeader
} bottomContent: {
actionButtons
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.interactiveDismissDisabled()
}
// MARK: - Private
@ViewBuilder
private var screenHeader: some View {
VStack(spacing: 0) {
HeroImage(icon: \.checkCircle, style: .positive)
.padding(.bottom, 16)
Text(L10n.screenIdentityConfirmedTitle)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
.padding(.bottom, 8)
Text(L10n.screenIdentityConfirmedSubtitle)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
}
}
@ViewBuilder
private var actionButtons: some View {
Button(L10n.actionContinue) {
context.send(viewAction: .done)
}
.buttonStyle(.compound(.primary))
}
}
// MARK: - Previews
struct IdentityConfirmedScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = IdentityConfirmedScreenViewModel()
static var previews: some View {
NavigationStack {
IdentityConfirmedScreen(context: viewModel.context)
}
}
}
@@ -0,0 +1,59 @@
//
// 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 Combine
import SwiftUI
struct NotificationPermissionsScreenCoordinatorParameters {
let notificationManager: NotificationManagerProtocol
}
enum NotificationPermissionsScreenCoordinatorAction {
case done
}
final class NotificationPermissionsScreenCoordinator: CoordinatorProtocol {
private var viewModel: NotificationPermissionsScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<NotificationPermissionsScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<NotificationPermissionsScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: NotificationPermissionsScreenCoordinatorParameters) {
viewModel = NotificationPermissionsScreenViewModel(notificationManager: parameters.notificationManager)
}
// MARK: - Public
func start() {
viewModel.actionsPublisher
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(NotificationPermissionsScreen(context: viewModel.context))
}
}
@@ -0,0 +1,28 @@
//
// 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
enum NotificationPermissionsScreenViewAction {
case enable
case notNow
}
enum NotificationPermissionsScreenViewModelAction {
case done
}
struct NotificationPermissionsScreenViewState: BindableState { }
@@ -0,0 +1,48 @@
//
// 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 Combine
import SwiftUI
typealias NotificationPermissionsScreenViewModelType = StateStoreViewModel<NotificationPermissionsScreenViewState, NotificationPermissionsScreenViewAction>
class NotificationPermissionsScreenViewModel: NotificationPermissionsScreenViewModelType, NotificationPermissionsScreenViewModelProtocol {
private let notificationManager: NotificationManagerProtocol
private var actionsSubject: PassthroughSubject<NotificationPermissionsScreenViewModelAction, Never> = .init()
var actionsPublisher: AnyPublisher<NotificationPermissionsScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(notificationManager: NotificationManagerProtocol) {
self.notificationManager = notificationManager
super.init(initialViewState: .init())
}
// MARK: - Public
override func process(viewAction: NotificationPermissionsScreenViewAction) {
switch viewAction {
case .enable:
notificationManager.requestAuthorization()
actionsSubject.send(.done)
case .notNow:
actionsSubject.send(.done)
}
}
}
@@ -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 Combine
@MainActor
protocol NotificationPermissionsScreenViewModelProtocol {
var actionsPublisher: AnyPublisher<NotificationPermissionsScreenViewModelAction, Never> { get }
var context: NotificationPermissionsScreenViewModelType.Context { get }
}
@@ -0,0 +1,77 @@
//
// 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 prompt that asks the user whether they would like to enable Analytics or not.
struct NotificationPermissionsScreen: View {
@ObservedObject var context: NotificationPermissionsScreenViewModel.Context
var body: some View {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding, showBackgroundGradient: true) {
mainContent
} bottomContent: {
buttons
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.interactiveDismissDisabled()
}
/// The main content of the screen that is shown inside the scroll view.
private var mainContent: some View {
VStack(spacing: 8) {
HeroImage(icon: \.notificationsSolid)
.padding(.bottom, 8)
Text(L10n.screenNotificationOptinTitle)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
Text(L10n.screenNotificationOptinSubtitle)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
Asset.Images.notificationsPromptGraphic.swiftUIImage.resizable().aspectRatio(contentMode: .fit)
}
}
private var buttons: some View {
VStack(spacing: 16) {
Button(L10n.actionOk) { context.send(viewAction: .enable) }
.buttonStyle(.compound(.primary))
Button { context.send(viewAction: .notNow) } label: {
Text(L10n.actionNotNow)
.font(.compound.bodyLGSemibold)
.padding(14)
}
}
}
}
// MARK: - Previews
struct NotificationPermissionsScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = NotificationPermissionsScreenViewModel(notificationManager: NotificationManagerMock())
static var previews: some View {
NotificationPermissionsScreen(context: viewModel.context)
}
}
@@ -0,0 +1,64 @@
//
// 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 Combine
import SwiftUI
enum SessionVerificationScreenCoordinatorAction {
case done
}
struct SessionVerificationScreenCoordinatorParameters {
let sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol
}
final class SessionVerificationScreenCoordinator: CoordinatorProtocol {
private var viewModel: SessionVerificationScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<SessionVerificationScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<SessionVerificationScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SessionVerificationScreenCoordinatorParameters) {
viewModel = SessionVerificationScreenViewModel(sessionVerificationControllerProxy: parameters.sessionVerificationControllerProxy)
}
// MARK: - Public
func start() {
viewModel.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .finished:
actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func stop() {
viewModel.stop()
}
func toPresentable() -> AnyView {
AnyView(SessionVerificationScreen(context: viewModel.context))
}
}
@@ -0,0 +1,91 @@
//
// 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 Foundation
enum SessionVerificationScreenViewModelAction {
case finished
}
struct SessionVerificationScreenViewState: BindableState {
var verificationState: SessionVerificationScreenStateMachine.State = .initial
var title: String? {
switch verificationState {
case .initial:
return L10n.screenSessionVerificationOpenExistingSessionTitle
case .requestingVerification:
return L10n.screenSessionVerificationWaitingToAcceptTitle
case .verificationRequestAccepted:
return L10n.screenSessionVerificationCompareEmojisTitle
case .startingSasVerification:
return nil
case .sasVerificationStarted:
return nil
case .showingChallenge:
return L10n.screenSessionVerificationCompareEmojisTitle
case .acceptingChallenge:
return L10n.screenSessionVerificationCompareEmojisTitle
case .decliningChallenge:
return nil
case .verified:
return L10n.commonVerificationComplete
case .cancelling:
return nil
case .cancelled:
return L10n.commonVerificationCancelled
}
}
var titleAccessibilityIdentifier: String {
verificationState == .verified ? A11yIdentifiers.sessionVerificationScreen.verificationComplete : ""
}
var message: String {
switch verificationState {
case .initial:
return L10n.screenSessionVerificationOpenExistingSessionSubtitle
case .requestingVerification:
return L10n.screenSessionVerificationWaitingToAcceptSubtitle
case .verificationRequestAccepted:
return L10n.screenSessionVerificationRequestAcceptedSubtitle
case .startingSasVerification:
return L10n.commonWaiting
case .sasVerificationStarted:
return L10n.commonWaiting
case .acceptingChallenge:
return L10n.screenSessionVerificationCompareEmojisSubtitle
case .decliningChallenge:
return L10n.commonWaiting
case .cancelling:
return L10n.commonWaiting
case .showingChallenge:
return L10n.screenSessionVerificationCompareEmojisSubtitle
case .verified:
return L10n.screenSessionVerificationCompleteSubtitle
case .cancelled:
return L10n.screenSessionVerificationCancelledSubtitle
}
}
}
enum SessionVerificationScreenViewAction {
case requestVerification
case startSasVerification
case restart
case accept
case decline
}
@@ -0,0 +1,148 @@
//
// 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 Foundation
import SwiftState
class SessionVerificationScreenStateMachine {
/// States the SessionVerificationViewModel can find itself in
enum State: StateType {
/// The initial state, before verification started
case initial
/// Waiting for verification acceptance
case requestingVerification
/// Verification request accepted. Waiting for start
case verificationRequestAccepted
/// Waiting for SaS verification start
case startingSasVerification
/// A SaS verification flow has been started
case sasVerificationStarted
/// Verification accepted and emojis received
case showingChallenge(emojis: [SessionVerificationEmoji])
/// Emojis match locally
case acceptingChallenge(emojis: [SessionVerificationEmoji])
/// Emojis do not match locally
case decliningChallenge(emojis: [SessionVerificationEmoji])
/// Verification successful
case verified
/// User requested verification cancellation
case cancelling
/// The verification has been cancelled, remotely or locally
case cancelled
}
/// Events that can be triggered on the SessionVerification state machine
enum Event: EventType {
/// Request verification
case requestVerification
/// The current verification request has been accepted
case didAcceptVerificationRequest
/// Start a SaS verification flow
case startSasVerification
/// Started a SaS verification flow
case didStartSasVerification
/// Has received emojis
case didReceiveChallenge(emojis: [SessionVerificationEmoji])
/// Emojis match
case acceptChallenge
/// Emojis do not match
case declineChallenge
/// Remote accepted challenge
case didAcceptChallenge
/// Request cancellation
case cancel
/// Verification cancelled
case didCancel
/// Request failed
case didFail
/// Restart the verification flow
case restart
}
private let stateMachine: StateMachine<State, Event>
var state: State {
stateMachine.state
}
init() {
stateMachine = StateMachine(state: .initial)
configure()
}
private func configure() {
stateMachine.addRoutes(event: .requestVerification, transitions: [.initial => .requestingVerification])
stateMachine.addRoutes(event: .didAcceptVerificationRequest, transitions: [.requestingVerification => .verificationRequestAccepted])
stateMachine.addRoutes(event: .startSasVerification, transitions: [.verificationRequestAccepted => .startingSasVerification])
stateMachine.addRoutes(event: .didFail, transitions: [.requestingVerification => .initial])
stateMachine.addRoutes(event: .restart, transitions: [.cancelled => .initial])
// Transitions with associated values need to be handled through `addRouteMapping`
stateMachine.addRouteMapping { event, fromState, _ in
switch (fromState, event) {
case (_, .didStartSasVerification):
return .sasVerificationStarted
case (.sasVerificationStarted, .didReceiveChallenge(let emojis)):
return .showingChallenge(emojis: emojis)
case (.showingChallenge(let emojis), .acceptChallenge):
return .acceptingChallenge(emojis: emojis)
case (.acceptingChallenge(let emojis), .didFail):
return .showingChallenge(emojis: emojis)
case (.acceptingChallenge, .didAcceptChallenge):
return .verified
case (.showingChallenge(let emojis), .declineChallenge):
return .decliningChallenge(emojis: emojis)
case (.decliningChallenge(let emojis), .didFail):
return .showingChallenge(emojis: emojis)
case (_, .cancel):
return .cancelling
case (_, .didCancel):
return .cancelled
default:
return nil
}
}
addTransitionHandler { context in
if let event = context.event {
MXLog.info("Transitioning from `\(context.fromState)` to `\(context.toState)` with event `\(event)`")
} else {
MXLog.info("Transitioning from \(context.fromState)` to `\(context.toState)`")
}
}
}
/// Attempt to move the state machine to another state through an event
/// It will either invoke the `transitionHandler` or the `errorHandler` depending on its current state
func processEvent(_ event: Event) {
stateMachine.tryEvent(event)
}
/// Registers a callback for processing state machine transitions
func addTransitionHandler(_ handler: @escaping StateMachine<State, Event>.Handler) {
stateMachine.addAnyHandler(.any => .any, handler: handler)
}
/// Registers a callback for processing state machine errors
func addErrorHandler(_ handler: @escaping StateMachine<State, Event>.Handler) {
stateMachine.addErrorHandler(handler: handler)
}
}
@@ -0,0 +1,182 @@
//
// 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 Combine
import SwiftUI
typealias SessionVerificationViewModelType = StateStoreViewModel<SessionVerificationScreenViewState, SessionVerificationScreenViewAction>
class SessionVerificationScreenViewModel: SessionVerificationViewModelType, SessionVerificationScreenViewModelProtocol {
private let sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol
private var stateMachine: SessionVerificationScreenStateMachine
private var actionsSubject: PassthroughSubject<SessionVerificationScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<SessionVerificationScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol,
verificationState: SessionVerificationScreenStateMachine.State = .initial) {
self.sessionVerificationControllerProxy = sessionVerificationControllerProxy
stateMachine = SessionVerificationScreenStateMachine()
super.init(initialViewState: .init(verificationState: verificationState))
setupStateMachine()
sessionVerificationControllerProxy.callbacks
.receive(on: DispatchQueue.main)
.sink { [weak self] callback in
guard let self else { return }
switch callback {
case .acceptedVerificationRequest:
self.stateMachine.processEvent(.didAcceptVerificationRequest)
case .startedSasVerification:
self.stateMachine.processEvent(.didStartSasVerification)
case .receivedVerificationData(let emojis):
guard self.stateMachine.state == .sasVerificationStarted else {
MXLog.warning("Callbacks: Ignoring receivedVerificationData due to invalid state.")
return
}
self.stateMachine.processEvent(.didReceiveChallenge(emojis: emojis))
case .finished:
self.stateMachine.processEvent(.didAcceptChallenge)
case .cancelled:
self.stateMachine.processEvent(.didCancel)
case .failed:
self.stateMachine.processEvent(.didFail)
}
}
.store(in: &cancellables)
}
override func process(viewAction: SessionVerificationScreenViewAction) {
switch viewAction {
case .requestVerification:
stateMachine.processEvent(.requestVerification)
case .startSasVerification:
stateMachine.processEvent(.startSasVerification)
case .restart:
stateMachine.processEvent(.restart)
case .accept:
stateMachine.processEvent(.acceptChallenge)
case .decline:
stateMachine.processEvent(.declineChallenge)
}
}
func stop() {
let uncancellableStates: [SessionVerificationScreenStateMachine.State] = [.initial, .verified, .cancelled]
if !uncancellableStates.contains(stateMachine.state) {
stateMachine.processEvent(.cancel)
}
}
// MARK: - Private
private func setupStateMachine() {
stateMachine.addTransitionHandler { [weak self] context in
guard let self else { return }
state.verificationState = context.toState
switch (context.fromState, context.event, context.toState) {
case (.initial, .requestVerification, .requestingVerification):
requestVerification()
case (.verificationRequestAccepted, .startSasVerification, .startingSasVerification):
startSasVerification()
case (.showingChallenge, .acceptChallenge, .acceptingChallenge):
acceptChallenge()
case (.showingChallenge, .declineChallenge, .decliningChallenge):
declineChallenge()
case (_, .cancel, .cancelling):
cancelVerification()
case (_, _, .verified):
actionsSubject.send(.finished)
default:
break
}
}
stateMachine.addErrorHandler { context in
MXLog.error("Failed transition with context: \(context)")
}
}
private func requestVerification() {
Task {
switch await sessionVerificationControllerProxy.requestVerification() {
case .success:
// Need to wait for the callback from the remote
break
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func cancelVerification() {
Task {
switch await sessionVerificationControllerProxy.cancelVerification() {
case .success:
stateMachine.processEvent(.didCancel)
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func startSasVerification() {
Task {
switch await sessionVerificationControllerProxy.startSasVerification() {
case .success:
// Need to wait for the callback from the remote
break
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func acceptChallenge() {
Task {
switch await sessionVerificationControllerProxy.approveVerification() {
case .success:
// Need to wait for the callback from the remote
break
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func declineChallenge() {
Task {
switch await sessionVerificationControllerProxy.declineVerification() {
case .success:
stateMachine.processEvent(.didCancel)
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
}
@@ -0,0 +1,25 @@
//
// 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 Combine
@MainActor
protocol SessionVerificationScreenViewModelProtocol {
var actions: AnyPublisher<SessionVerificationScreenViewModelAction, Never> { get }
var context: SessionVerificationViewModelType.Context { get }
func stop()
}
@@ -0,0 +1,233 @@
//
// 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
struct SessionVerificationScreen: View {
@ObservedObject var context: SessionVerificationScreenViewModel.Context
var body: some View {
FullscreenDialog {
VStack(spacing: 32) {
screenHeader
Spacer()
mainContent
}
} bottomContent: {
actionButtons
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.interactiveDismissDisabled()
}
// MARK: - Private
private var headerImageName: String {
switch context.viewState.verificationState {
case .initial:
return "lock"
case .cancelled:
return "exclamationmark.shield"
case .requestingVerification:
return "hourglass"
case .verificationRequestAccepted:
return "face.smiling"
case .startingSasVerification:
return "hourglass"
case .sasVerificationStarted:
return "hourglass"
case .cancelling:
return "hourglass"
case .acceptingChallenge:
return "hourglass"
case .decliningChallenge:
return "hourglass"
case .showingChallenge:
return "face.smiling"
case .verified:
return "checkmark.shield"
}
}
@ViewBuilder
private var screenHeader: some View {
VStack(spacing: 0) {
if context.viewState.verificationState == .initial {
HeroImage(icon: \.lockSolid)
.padding(.bottom, 16)
} else {
Image(systemName: headerImageName)
.heroImage()
.padding(.bottom, 16)
}
Text(context.viewState.title ?? "")
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
.padding(.bottom, 8)
.accessibilityIdentifier(context.viewState.titleAccessibilityIdentifier)
Text(context.viewState.message)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
}
}
@ViewBuilder
private var mainContent: some View {
switch context.viewState.verificationState {
case .showingChallenge(let emojis):
emojisPanel(with: emojis)
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.emojiWrapper)
case .acceptingChallenge(let emojis):
emojisPanel(with: emojis)
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.emojiWrapper)
case .requestingVerification:
ProgressView()
.tint(.compound.textSecondary)
.scaleEffect(2)
default:
// In All other cases, we just want an empty view
EmptyView()
}
}
@ViewBuilder
private func emojisPanel(with emojis: [SessionVerificationEmoji]) -> some View {
VStack(spacing: 32) {
HStack(spacing: 16) {
ForEach(emojis.prefix(4), id: \.self) { emoji in
EmojiView(emoji: emoji)
}
}
HStack(spacing: 16) {
ForEach(emojis.suffix(from: 4), id: \.self) { emoji in
EmojiView(emoji: emoji)
}
}
}
}
@ViewBuilder
private var actionButtons: some View {
switch context.viewState.verificationState {
case .initial:
VStack(spacing: 32) {
Button(L10n.actionStartVerification) {
context.send(viewAction: .requestVerification)
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.requestVerification)
}
case .cancelled:
Button(L10n.actionRetry) {
context.send(viewAction: .restart)
}
.buttonStyle(.compound(.primary))
case .verificationRequestAccepted:
Button(L10n.actionStart) {
context.send(viewAction: .startSasVerification)
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.startSasVerification)
case .showingChallenge:
VStack(spacing: 32) {
Button(L10n.screenSessionVerificationTheyMatch) {
context.send(viewAction: .accept)
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.acceptChallenge)
Button(L10n.screenSessionVerificationTheyDontMatch) {
context.send(viewAction: .decline)
}
.font(.compound.bodyLGSemibold)
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.declineChallenge)
}
case .acceptingChallenge:
VStack(spacing: 32) {
Button { context.send(viewAction: .accept) } label: {
HStack(spacing: 16) {
ProgressView()
.tint(.compound.textOnSolidPrimary)
Text(L10n.screenSessionVerificationTheyMatch)
}
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.acceptChallenge)
.disabled(true)
Button(L10n.screenSessionVerificationTheyDontMatch) {
context.send(viewAction: .decline)
}
.font(.compound.bodyLGSemibold)
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.declineChallenge)
.disabled(true)
}
default:
EmptyView()
}
}
struct EmojiView: View {
let emoji: SessionVerificationEmoji
var body: some View {
VStack(spacing: 16.0) {
Text(emoji.symbol)
.font(.compound.headingXLBold)
Text(emoji.localizedDescription)
.font(.compound.bodyMD)
.foregroundColor(.compound.textSecondary)
}
.padding(8.0)
}
}
}
// MARK: - Previews
struct SessionVerification_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
sessionVerificationScreen(state: .initial)
.previewDisplayName("Initial")
sessionVerificationScreen(state: .requestingVerification)
.previewDisplayName("Requesting Verification")
sessionVerificationScreen(state: .verificationRequestAccepted)
.previewDisplayName("Request Accepted")
sessionVerificationScreen(state: .cancelled)
.previewDisplayName("Cancelled")
sessionVerificationScreen(state: .showingChallenge(emojis: SessionVerificationControllerProxyMock.emojis))
.previewDisplayName("Showing Challenge")
sessionVerificationScreen(state: .verified)
.previewDisplayName("Verified")
}
static func sessionVerificationScreen(state: SessionVerificationScreenStateMachine.State) -> some View {
let viewModel = SessionVerificationScreenViewModel(sessionVerificationControllerProxy: SessionVerificationControllerProxyMock.configureMock(),
verificationState: state)
return SessionVerificationScreen(context: viewModel.context)
}
}