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
@@ -83,7 +83,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
MXLog.info("\(appName) \(appVersion) (\(appBuild))")
if ProcessInfo.processInfo.environment["RESET_APP_SETTINGS"].map(Bool.init) == true {
AppSettings.reset()
AppSettings.resetAllSettings()
}
self.appDelegate = appDelegate
@@ -154,11 +154,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
return
}
if appSettings.appLockIsMandatory, !appLockFlowCoordinator.appLockService.isEnabled {
stateMachine.processEvent(.startWithAppLockSetup)
} else {
stateMachine.processEvent(.startWithExistingSession)
}
stateMachine.processEvent(.startWithExistingSession)
}
func stop() {
@@ -319,13 +315,21 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
appSettings.migratedAccounts[userID] = true
}
}
if oldVersion < Version(1, 6, 0) {
MXLog.info("Migrating to v1.6.0, marking identity confirmation onboarding as ran.")
if !userSessionStore.userIDs.isEmpty {
appSettings.hasRunIdentityConfirmationOnboarding = true
appSettings.hasRunNotificationPermissionsOnboarding = true
}
}
}
/// Clears the keychain, app support directory etc ready for a fresh use.
/// - Parameter includingSettings: Whether to additionally wipe the user's app settings too.
private func wipeUserData(includingSettings: Bool = false) {
if includingSettings {
AppSettings.reset()
AppSettings.resetAllSettings()
appLockFlowCoordinator.appLockService.disable()
}
userSessionStore.reset()
@@ -339,20 +343,15 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
case (.initial, .startWithAuthentication, .signedOut):
startAuthentication()
case (.signedOut, .createdUserSession, .signedIn):
setupUserSession()
setupUserSession(isNewLogin: true)
case (.initial, .startWithExistingSession, .restoringSession):
restoreUserSession()
case (.restoringSession, .failedRestoringSession, .signedOut):
showLoginErrorToast()
presentSplashScreen()
case (.restoringSession, .createdUserSession, .signedIn):
setupUserSession()
case (.initial, .startWithAppLockSetup, .mandatoryAppLockSetup):
startMandatoryAppLockSetup()
case (.mandatoryAppLockSetup, .appLockSetupComplete, .restoringSession):
restoreUserSession()
setupUserSession(isNewLogin: false)
case (.signingOut, .signOut, .signingOut):
// We can ignore signOut when already in the process of signing out,
// such as the SDK sending an authError due to token invalidation.
@@ -397,7 +396,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
encryptionKeyProvider: EncryptionKeyProvider(),
appSettings: appSettings)
authenticationFlowCoordinator = AuthenticationFlowCoordinator(authenticationService: authenticationService,
appLockService: appLockFlowCoordinator.appLockService,
bugReportService: ServiceLocator.shared.bugReportService,
navigationRootCoordinator: navigationRootCoordinator,
appSettings: appSettings,
@@ -450,7 +448,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
}
}
private func setupUserSession() {
private func setupUserSession(isNewLogin: Bool) {
guard let userSession else {
fatalError("User session not setup")
}
@@ -462,9 +460,11 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
bugReportService: ServiceLocator.shared.bugReportService,
roomTimelineControllerFactory: RoomTimelineControllerFactory(),
appSettings: appSettings,
analytics: ServiceLocator.shared.analytics)
analytics: ServiceLocator.shared.analytics,
notificationManager: notificationManager,
isNewLogin: isNewLogin)
userSessionFlowCoordinator.actions
userSessionFlowCoordinator.actionsPublisher
.sink { [weak self] action in
guard let self else { return }
@@ -487,32 +487,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
userSessionFlowCoordinator.handleAppRoute(storedAppRoute, animated: false)
}
}
/// Used to add a PIN code to an existing session that somehow missed out mandatory PIN setup.
private func startMandatoryAppLockSetup() {
MXLog.info("Mandatory App Lock enabled but no PIN is set. Showing the setup flow.")
let navigationCoordinator = NavigationStackCoordinator()
let coordinator = AppLockSetupFlowCoordinator(presentingFlow: .onboarding,
appLockService: appLockFlowCoordinator.appLockService,
navigationStackCoordinator: navigationCoordinator)
coordinator.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .complete:
stateMachine.processEvent(.appLockSetupComplete)
appLockSetupFlowCoordinator = nil
case .forceLogout:
fatalError("Creating a PIN shouldn't be able to fail in this way")
}
}
.store(in: &cancellables)
appLockSetupFlowCoordinator = coordinator
navigationRootCoordinator.setRootCoordinator(navigationCoordinator)
coordinator.start()
}
private func logout(isSoft: Bool) {
guard let userSession else {
fatalError("User session not setup")
@@ -544,6 +519,8 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
userSessionStore.logout(userSession: userSession)
tearDownUserSession()
AppSettings.resetSessionSpecificSettings()
// Reset analytics
ServiceLocator.shared.analytics.optOut()
ServiceLocator.shared.analytics.resetConsentState()
@@ -591,7 +568,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
private func configureNotificationManager() {
notificationManager.setUserSession(userSession)
notificationManager.requestAuthorization()
appDelegateObserver = appDelegate.callbacks
.receive(on: DispatchQueue.main)
@@ -689,7 +665,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
// MARK: Toasts and loading indicators
private static let loadingIndicatorIdentifier = "AppCoordinatorLoading"
private static let loadingIndicatorIdentifier = "\(AppCoordinator.self)-Loading"
private func showLoadingIndicator() {
ServiceLocator.shared.userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -28,12 +28,7 @@ class AppCoordinatorStateMachine {
case softLogout
/// Opening an existing session.
case restoringSession
/// Showing the mandatory app lock setup flow before restoring the session.
/// This state should only be allowed before restoring an existing session. For
/// new users the setup is inserted in the middle of the authentication flow.
case mandatoryAppLockSetup
/// User session started
case signedIn
@@ -48,21 +43,13 @@ class AppCoordinatorStateMachine {
/// Start the `AppCoordinator` by restoring an existing account.
case startWithExistingSession
/// Start the `AppCoordinator` by showing the mandatory PIN creation flow.
/// This event should only be sent if an account exists and a mandatory PIN is
/// missing. Normally it will be handled as part of the authentication flow.
case startWithAppLockSetup
/// Restoring session failed.
case failedRestoringSession
/// A session has been created.
case createdUserSession
/// The app lock setup has been completed.
case appLockSetupComplete
/// Request sign out.
case signOut(isSoft: Bool, disableAppLock: Bool)
/// Request the soft logout screen.
@@ -92,10 +79,7 @@ class AppCoordinatorStateMachine {
stateMachine.addRoutes(event: .startWithExistingSession, transitions: [.initial => .restoringSession])
stateMachine.addRoutes(event: .createdUserSession, transitions: [.restoringSession => .signedIn])
stateMachine.addRoutes(event: .failedRestoringSession, transitions: [.restoringSession => .signedOut])
stateMachine.addRoutes(event: .startWithAppLockSetup, transitions: [.initial => .mandatoryAppLockSetup])
stateMachine.addRoutes(event: .appLockSetupComplete, transitions: [.mandatoryAppLockSetup => .restoringSession])
stateMachine.addRoutes(event: .completedSigningOut, transitions: [.signingOut(isSoft: false, disableAppLock: false) => .signedOut,
.signingOut(isSoft: false, disableAppLock: true) => .signedOut])
stateMachine.addRoutes(event: .showSoftLogout, transitions: [.signingOut(isSoft: true, disableAppLock: false) => .softLogout])
+19 -10
View File
@@ -24,10 +24,13 @@ final class AppSettings {
case seenInvites
case appLockNumberOfPINAttempts
case appLockNumberOfBiometricAttempts
case lastLoginDate
case migratedAccounts
case timelineStyle
case analyticsConsentState
case hasRunNotificationPermissionsOnboarding
case hasRunIdentityConfirmationOnboarding
case enableNotifications
case enableInAppNotifications
case pusherProfileTag
@@ -59,11 +62,16 @@ final class AppSettings {
#if IS_MAIN_APP
static func reset() {
static func resetAllSettings() {
MXLog.warning("Resetting the AppSettings.")
store.removePersistentDomain(forName: suiteName)
}
static func resetSessionSpecificSettings() {
MXLog.warning("Resetting the user session specific AppSettings.")
store.removeObject(forKey: UserDefaultsKeys.hasRunIdentityConfirmationOnboarding.rawValue)
}
static func configureWithSuiteName(_ name: String) {
suiteName = name
@@ -120,7 +128,9 @@ final class AppSettings {
let privacyURL: URL = "https://element.io/privacy"
/// An email address that should be used for support requests.
let supportEmailAddress = "support@element.io"
// A URL where users can go read more about the chat backup.
/// A URL where users can go read more about encryption in general.
let encryptionURL: URL = "https://element.io/help#encryption"
/// A URL where users can go read more about the chat backup.
let chatBackupDetailsURL: URL = "https://element.io/help#encryption5"
@UserPreference(key: UserDefaultsKeys.appAppearance, defaultValue: .system, storageType: .userDefaults(store))
@@ -153,13 +163,6 @@ final class AppSettings {
return url
}()
/// The date that the call to `/login` completed successfully. This is used to put
/// a hard wall on the history of encrypted messages until we have key backup.
///
/// Not a multi-account aware setting as key backup will come before multi-account.
@UserPreference(key: UserDefaultsKeys.lastLoginDate, defaultValue: nil, storageType: .userDefaults(store))
var lastLoginDate: Date?
/// A dictionary of accounts that have performed an initial sync through their proxy.
///
@@ -211,6 +214,12 @@ final class AppSettings {
@UserPreference(key: UserDefaultsKeys.analyticsConsentState, defaultValue: AnalyticsConsentState.unknown, storageType: .userDefaults(store))
var analyticsConsentState
@UserPreference(key: UserDefaultsKeys.hasRunNotificationPermissionsOnboarding, defaultValue: false, storageType: .userDefaults(store))
var hasRunNotificationPermissionsOnboarding
@UserPreference(key: UserDefaultsKeys.hasRunIdentityConfirmationOnboarding, defaultValue: false, storageType: .userDefaults(store))
var hasRunIdentityConfirmationOnboarding
// MARK: - Home Screen
@UserPreference(key: UserDefaultsKeys.hideUnreadMessagesBadge, defaultValue: false, storageType: .userDefaults(store))
@@ -24,7 +24,6 @@ protocol AuthenticationFlowCoordinatorDelegate: AnyObject {
class AuthenticationFlowCoordinator: FlowCoordinatorProtocol {
private let authenticationService: AuthenticationServiceProxyProtocol
private let appLockService: AppLockServiceProtocol
private let bugReportService: BugReportServiceProtocol
private let navigationRootCoordinator: NavigationRootCoordinator
private let navigationStackCoordinator: NavigationStackCoordinator
@@ -36,23 +35,18 @@ class AuthenticationFlowCoordinator: FlowCoordinatorProtocol {
private var oidcPresenter: OIDCAuthenticationPresenter?
// periphery: ignore - used to store the coordinator to avoid deallocation
private var appLockFlowCoordinator: AppLockSetupFlowCoordinator?
// periphery:ignore - retaining purpose
private var bugReportFlowCoordinator: BugReportFlowCoordinator?
weak var delegate: AuthenticationFlowCoordinatorDelegate?
init(authenticationService: AuthenticationServiceProxyProtocol,
appLockService: AppLockServiceProtocol,
bugReportService: BugReportServiceProtocol,
navigationRootCoordinator: NavigationRootCoordinator,
appSettings: AppSettings,
analytics: AnalyticsService,
userIndicatorController: UserIndicatorControllerProtocol) {
self.authenticationService = authenticationService
self.appLockService = appLockService
self.bugReportService = bugReportService
self.navigationRootCoordinator = navigationRootCoordinator
self.appSettings = appSettings
@@ -108,7 +102,7 @@ class AuthenticationFlowCoordinator: FlowCoordinatorProtocol {
private func showReportProblemScreen() {
bugReportFlowCoordinator = BugReportFlowCoordinator(parameters: .init(presentationMode: .sheet(navigationStackCoordinator),
userIndicatorController: ServiceLocator.shared.userIndicatorController,
userIndicatorController: userIndicatorController,
bugReportService: bugReportService,
userID: nil,
deviceID: nil))
@@ -265,58 +259,10 @@ class AuthenticationFlowCoordinator: FlowCoordinatorProtocol {
}
private func userHasSignedIn(userSession: UserSessionProtocol) {
appSettings.lastLoginDate = .now
if appSettings.appLockIsMandatory, !appLockService.isEnabled {
showAppLockSetupFlow(userSession: userSession)
} else if analytics.shouldShowAnalyticsPrompt {
showAnalyticsPrompt(userSession: userSession)
} else {
delegate?.authenticationFlowCoordinator(didLoginWithSession: userSession)
}
delegate?.authenticationFlowCoordinator(didLoginWithSession: userSession)
}
private func showAppLockSetupFlow(userSession: UserSessionProtocol) {
let coordinator = AppLockSetupFlowCoordinator(presentingFlow: .onboarding,
appLockService: appLockService,
navigationStackCoordinator: navigationStackCoordinator)
coordinator.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .complete:
appLockFlowCoordinator = nil
if analytics.shouldShowAnalyticsPrompt {
showAnalyticsPrompt(userSession: userSession)
} else {
delegate?.authenticationFlowCoordinator(didLoginWithSession: userSession)
}
case .forceLogout:
fatalError("The PIN creation flow should not fail.")
}
}
.store(in: &cancellables)
appLockFlowCoordinator = coordinator
coordinator.start()
}
private func showAnalyticsPrompt(userSession: UserSessionProtocol) {
let coordinator = AnalyticsPromptScreenCoordinator(analytics: analytics, termsURL: appSettings.analyticsConfiguration.termsURL)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
delegate?.authenticationFlowCoordinator(didLoginWithSession: userSession)
}
}
.store(in: &cancellables)
navigationStackCoordinator.push(coordinator)
}
private static let loadingIndicatorIdentifier = "authenticationFlowCoordinatorLoading"
private static let loadingIndicatorIdentifier = "\(AuthenticationFlowCoordinator.self)-Loading"
private func startLoading() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -0,0 +1,343 @@
//
// Copyright 2024 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 Foundation
import SwiftState
class OnboardingFlowCoordinator: FlowCoordinatorProtocol {
private let userSession: UserSessionProtocol
private let appLockService: AppLockServiceProtocol
private let analyticsService: AnalyticsService
private let appSettings: AppSettings
private let notificationManager: NotificationManagerProtocol
private let rootNavigationStackCoordinator: NavigationStackCoordinator
private let userIndicatorController: UserIndicatorControllerProtocol
private let isNewLogin: Bool
private var navigationStackCoordinator: NavigationStackCoordinator!
enum State: StateType {
case initial
case identityConfirmation
case identityConfirmed
case appLockSetup
case analyticsPrompt
case notificationPermissions
case finished
}
enum Event: EventType {
case next
}
private let stateMachine: StateMachine<State, Event>
private var cancellables = Set<AnyCancellable>()
// periphery: ignore - used to store the coordinator to avoid deallocation
private var appLockFlowCoordinator: AppLockSetupFlowCoordinator?
init(userSession: UserSessionProtocol,
appLockService: AppLockServiceProtocol,
analyticsService: AnalyticsService,
appSettings: AppSettings,
notificationManager: NotificationManagerProtocol,
navigationStackCoordinator: NavigationStackCoordinator,
userIndicatorController: UserIndicatorControllerProtocol,
isNewLogin: Bool) {
self.userSession = userSession
self.appLockService = appLockService
self.analyticsService = analyticsService
self.appSettings = appSettings
self.notificationManager = notificationManager
self.userIndicatorController = userIndicatorController
self.isNewLogin = isNewLogin
rootNavigationStackCoordinator = navigationStackCoordinator
self.navigationStackCoordinator = NavigationStackCoordinator()
stateMachine = .init(state: .initial)
}
var shouldStart: Bool {
guard stateMachine.state == .initial, !ProcessInfo.isRunningIntegrationTests else {
return false
}
return isNewLogin || requiresVerification || requiresAppLockSetup || requiresAnalyticsSetup || requiresNotificationsSetup
}
func start() {
guard shouldStart else {
fatalError("This flow coordinator shouldn't have been started")
}
configureStateMachine()
stateMachine.tryEvent(.next)
rootNavigationStackCoordinator.setFullScreenCoverCoordinator(navigationStackCoordinator, animated: !isNewLogin)
}
func handleAppRoute(_ appRoute: AppRoute, animated: Bool) {
fatalError()
}
func clearRoute(animated: Bool) {
fatalError()
}
// MARK: - Private
private var requiresVerification: Bool {
// We want to make sure onboarding finishes but also every time the user becomes unverified (e.g. account reset)
!appSettings.hasRunIdentityConfirmationOnboarding || userSession.sessionSecurityStatePublisher.value.verificationState == .unverified
}
private var requiresAppLockSetup: Bool {
appSettings.appLockIsMandatory && !appLockService.isEnabled
}
private var requiresAnalyticsSetup: Bool {
analyticsService.shouldShowAnalyticsPrompt
}
private var requiresNotificationsSetup: Bool {
!appSettings.hasRunNotificationPermissionsOnboarding
}
private func configureStateMachine() {
stateMachine.addRouteMapping { [weak self] _, fromState, _ in
guard let self else {
return nil
}
switch (fromState, requiresVerification, requiresAppLockSetup, requiresAnalyticsSetup, requiresNotificationsSetup) {
case (.initial, true, _, _, _):
return .identityConfirmation
case (.initial, false, true, _, _):
return .appLockSetup
case (.initial, false, false, true, _):
return .analyticsPrompt
case (.initial, false, false, false, true):
return .notificationPermissions
case (.identityConfirmation, _, _, _, _):
return .identityConfirmed
case (.identityConfirmed, _, true, _, _):
return .appLockSetup
case (.identityConfirmed, _, false, true, _):
return .analyticsPrompt
case (.identityConfirmed, _, false, false, true):
return .notificationPermissions
case (.identityConfirmed, _, false, false, false):
return .finished
case (.appLockSetup, _, _, true, _):
return .analyticsPrompt
case (.appLockSetup, _, _, false, true):
return .notificationPermissions
case (.appLockSetup, _, _, false, false):
return .finished
case (.analyticsPrompt, _, _, _, true):
return .notificationPermissions
case (.analyticsPrompt, _, _, _, false):
return .finished
case (.notificationPermissions, _, _, _, _):
return .finished
default:
return nil
}
}
stateMachine.addAnyHandler(.any => .any) { [weak self] context in
guard let self else { return }
switch (context.fromState, context.event, context.toState) {
case (_, _, .identityConfirmation):
presentIdentityConfirmationScreen()
case (_, _, .identityConfirmed):
presentIdentityConfirmedScreen()
case (_, _, .appLockSetup):
presentAppLockSetupFlow()
case (_, _, .analyticsPrompt):
presentAnalyticsPromptScreen()
case (_, _, .notificationPermissions):
presentNotificationPermissionsScreen()
case (_, _, .finished):
rootNavigationStackCoordinator.setFullScreenCoverCoordinator(nil)
default:
fatalError("Unknown transition: \(context)")
}
}
stateMachine.addErrorHandler { context in
fatalError("Unexpected transition: \(context)")
}
}
private func presentIdentityConfirmationScreen() {
let parameters = IdentityConfirmationScreenCoordinatorParameters(userSession: userSession,
appSettings: appSettings,
userIndicatorController: userIndicatorController)
let coordinator = IdentityConfirmationScreenCoordinator(parameters: parameters)
coordinator.actionsPublisher.sink { [weak self] action in
guard let self else { return }
switch action {
case .otherDevice:
Task {
await self.presentSessionVerificationScreen()
}
case .recoveryKey:
presentRecoveryKeyScreen()
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentSessionVerificationScreen() async {
guard case let .success(sessionVerificationController) = await userSession.clientProxy.sessionVerificationControllerProxy() else {
fatalError("The sessionVerificationController should aways be valid at this point")
}
let parameters = SessionVerificationScreenCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationController)
let coordinator = SessionVerificationScreenCoordinator(parameters: parameters)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
appSettings.hasRunIdentityConfirmationOnboarding = true
stateMachine.tryEvent(.next)
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentRecoveryKeyScreen() {
let parameters = SecureBackupRecoveryKeyScreenCoordinatorParameters(secureBackupController: userSession.clientProxy.secureBackupController,
userIndicatorController: ServiceLocator.shared.userIndicatorController,
isModallyPresented: false)
let coordinator = SecureBackupRecoveryKeyScreenCoordinator(parameters: parameters)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .recoveryFixed:
appSettings.hasRunIdentityConfirmationOnboarding = true
stateMachine.tryEvent(.next)
default:
fatalError("Other flows shouldn't be possible")
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentIdentityConfirmedScreen() {
let coordinator = IdentityConfirmedScreenCoordinator(parameters: .init())
coordinator.actionsPublisher
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
stateMachine.tryEvent(.next)
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentAppLockSetupFlow() {
let coordinator = AppLockSetupFlowCoordinator(presentingFlow: .onboarding,
appLockService: appLockService,
navigationStackCoordinator: navigationStackCoordinator)
coordinator.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .complete:
appLockFlowCoordinator = nil
stateMachine.tryEvent(.next)
case .forceLogout:
fatalError("The PIN creation flow should not fail.")
}
}
.store(in: &cancellables)
appLockFlowCoordinator = coordinator
coordinator.start()
}
private func presentAnalyticsPromptScreen() {
let coordinator = AnalyticsPromptScreenCoordinator(analytics: analyticsService, termsURL: appSettings.analyticsConfiguration.termsURL)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
stateMachine.tryEvent(.next)
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentNotificationPermissionsScreen() {
let coordinator = NotificationPermissionsScreenCoordinator(parameters: .init(notificationManager: notificationManager))
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .done:
appSettings.hasRunNotificationPermissionsOnboarding = true
stateMachine.tryEvent(.next)
}
}
.store(in: &cancellables)
presentCoordinator(coordinator)
}
private func presentCoordinator(_ coordinator: CoordinatorProtocol) {
if navigationStackCoordinator.rootCoordinator == nil {
navigationStackCoordinator.setRootCoordinator(coordinator)
} else {
navigationStackCoordinator.push(coordinator)
}
}
}
@@ -434,8 +434,7 @@ class RoomFlowCoordinator: FlowCoordinatorProtocol {
stateEventStringBuilder: RoomStateEventStringBuilder(userID: userID))
let timelineController = roomTimelineControllerFactory.buildRoomTimelineController(roomProxy: roomProxy,
timelineItemFactory: timelineItemFactory,
secureBackupController: userSession.clientProxy.secureBackupController)
timelineItemFactory: timelineItemFactory)
self.timelineController = timelineController
analytics.trackViewRoom(isDM: roomProxy.isDirect, isSpace: roomProxy.isSpace)
@@ -918,8 +917,7 @@ class RoomFlowCoordinator: FlowCoordinatorProtocol {
stateEventStringBuilder: RoomStateEventStringBuilder(userID: userID))
let roomTimelineController = roomTimelineControllerFactory.buildRoomTimelineController(roomProxy: roomProxy,
timelineItemFactory: timelineItemFactory,
secureBackupController: userSession.clientProxy.secureBackupController)
timelineItemFactory: timelineItemFactory)
let parameters = RoomPollsHistoryScreenCoordinatorParameters(roomProxy: roomProxy,
pollInteractionHandler: PollInteractionHandler(analyticsService: analytics, roomProxy: roomProxy),
@@ -130,10 +130,6 @@ class SettingsFlowCoordinator: FlowCoordinatorProtocol {
presentLegalInformationScreen()
case .blockedUsers:
presentBlockedUsersScreen()
case .sessionVerification:
Task {
await self.presentSessionVerificationScreen()
}
case .accountSessions:
presentAccountSessionsListURL()
case .notifications:
@@ -212,35 +208,7 @@ class SettingsFlowCoordinator: FlowCoordinatorProtocol {
userIndicatorController: parameters.userIndicatorController))
navigationStackCoordinator.push(coordinator)
}
private func presentSessionVerificationScreen() async {
guard case let .success(sessionVerificationController) = await parameters.userSession.clientProxy.sessionVerificationControllerProxy() else {
fatalError("The sessionVerificationController should aways be valid at this point")
}
let verificationParameters = SessionVerificationScreenCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationController,
recoveryState: parameters.userSession.sessionSecurityStatePublisher.value.recoveryState)
let coordinator = SessionVerificationScreenCoordinator(parameters: verificationParameters)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .recoveryKey:
navigationStackCoordinator.setSheetCoordinator(nil)
handleAppRoute(.chatBackupSettings, animated: true)
case .done:
navigationStackCoordinator.setSheetCoordinator(nil)
}
}
.store(in: &cancellables)
navigationStackCoordinator.setSheetCoordinator(coordinator) { [weak self] in
self?.navigationStackCoordinator.setSheetCoordinator(nil)
}
}
private func presentNotificationSettings() {
let notificationParameters = NotificationSettingsScreenCoordinatorParameters(navigationStackCoordinator: navigationStackCoordinator,
userSession: parameters.userSession,
@@ -31,7 +31,6 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
private let windowManager: WindowManagerProtocol
private let bugReportService: BugReportServiceProtocol
private let appSettings: AppSettings
private let actionsSubject: PassthroughSubject<UserSessionFlowCoordinatorAction, Never> = .init()
private let stateMachine: UserSessionFlowCoordinatorStateMachine
@@ -39,6 +38,8 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
private let settingsFlowCoordinator: SettingsFlowCoordinator
private let onboardingFlowCoordinator: OnboardingFlowCoordinator
// periphery:ignore - retaining purpose
private var bugReportFlowCoordinator: BugReportFlowCoordinator?
@@ -52,7 +53,8 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
private let selectedRoomSubject = CurrentValueSubject<String?, Never>(nil)
var actions: AnyPublisher<UserSessionFlowCoordinatorAction, Never> {
private let actionsSubject: PassthroughSubject<UserSessionFlowCoordinatorAction, Never> = .init()
var actionsPublisher: AnyPublisher<UserSessionFlowCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
@@ -63,7 +65,9 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
bugReportService: BugReportServiceProtocol,
roomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol,
appSettings: AppSettings,
analytics: AnalyticsService) {
analytics: AnalyticsService,
notificationManager: NotificationManagerProtocol,
isNewLogin: Bool) {
stateMachine = UserSessionFlowCoordinatorStateMachine()
self.userSession = userSession
self.navigationRootCoordinator = navigationRootCoordinator
@@ -98,8 +102,29 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
navigationSplitCoordinator: navigationSplitCoordinator,
userIndicatorController: ServiceLocator.shared.userIndicatorController))
onboardingFlowCoordinator = OnboardingFlowCoordinator(userSession: userSession,
appLockService: appLockService,
analyticsService: analytics,
appSettings: appSettings,
notificationManager: notificationManager,
navigationStackCoordinator: detailNavigationStackCoordinator,
userIndicatorController: ServiceLocator.shared.userIndicatorController,
isNewLogin: isNewLogin)
setupStateMachine()
userSession.sessionSecurityStatePublisher
.map(\.verificationState)
.filter { $0 != .unknown }
.removeDuplicates()
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self else { return }
attemptStartingOnboarding()
}
.store(in: &cancellables)
roomFlowCoordinator.actions.sink { [weak self] action in
guard let self else { return }
@@ -208,11 +233,18 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
}
func clearRoute(animated: Bool) {
fatalError("not necessary as of right now")
roomFlowCoordinator.clearRoute(animated: animated)
}
// MARK: - Private
func attemptStartingOnboarding() {
if onboardingFlowCoordinator.shouldStart {
clearRoute(animated: false)
onboardingFlowCoordinator.start()
}
}
private func clearPresentedSheets(animated: Bool, completion: @escaping () -> Void) {
if navigationSplitCoordinator.sheetCoordinator == nil {
completion()
@@ -234,6 +266,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
switch (context.fromState, context.event, context.toState) {
case (.initial, .start, .roomList):
presentHomeScreen()
attemptStartingOnboarding()
case(.roomList, .selectRoom, .roomList):
break
@@ -244,13 +277,6 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
break
case (.invitesScreen, .deselectRoom, .invitesScreen):
break
case (.roomList, .showSessionVerificationScreen, .sessionVerificationScreen):
Task {
await self.presentSessionVerification(animated: animated)
}
case (.sessionVerificationScreen, .dismissedSessionVerificationScreen, .roomList):
break
case (.roomList, .showSettingsScreen, .settingsScreen):
break
@@ -334,8 +360,6 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
settingsFlowCoordinator.handleAppRoute(.settings, animated: true)
case .presentFeedbackScreen:
stateMachine.processEvent(.feedbackScreen)
case .presentSessionVerificationScreen:
stateMachine.processEvent(.showSessionVerificationScreen)
case .presentSecureBackupSettings:
settingsFlowCoordinator.handleAppRoute(.chatBackupSettings, animated: true)
case .presentStartChatScreen:
@@ -400,36 +424,6 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
presentSecureBackupLogoutConfirmationScreen()
}
// MARK: Session verification
private func presentSessionVerification(animated: Bool) async {
guard case let .success(sessionVerificationController) = await userSession.clientProxy.sessionVerificationControllerProxy() else {
fatalError("The sessionVerificationController should aways be valid at this point")
}
let parameters = SessionVerificationScreenCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationController,
recoveryState: userSession.sessionSecurityStatePublisher.value.recoveryState)
let coordinator = SessionVerificationScreenCoordinator(parameters: parameters)
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .recoveryKey:
settingsFlowCoordinator.handleAppRoute(.chatBackupSettings, animated: true)
case .done:
navigationSplitCoordinator.setSheetCoordinator(nil)
}
}
.store(in: &cancellables)
navigationSplitCoordinator.setSheetCoordinator(coordinator, animated: animated) { [weak self] in
self?.stateMachine.processEvent(.dismissedSessionVerificationScreen)
}
}
// MARK: Start Chat
private func presentStartChat(animated: Bool) {
@@ -26,9 +26,6 @@ class UserSessionFlowCoordinatorStateMachine {
/// Showing the home screen. The `selectedRoomID` represents the timeline shown on the detail panel (if any)
case roomList(selectedRoomID: String?)
/// Showing the session verification flows
case sessionVerificationScreen(selectedRoomID: String?)
/// Showing the session verification flows
case feedbackScreen(selectedRoomID: String?)
@@ -70,11 +67,6 @@ class UserSessionFlowCoordinatorStateMachine {
/// The feedback screen has been dismissed
case dismissedFeedbackScreen
/// Request the start of the session verification flow
case showSessionVerificationScreen
/// Session verification has finished
case dismissedSessionVerificationScreen
/// Request the start of the start chat flow
case showStartChatScreen
/// Start chat has been dismissed
@@ -126,11 +118,6 @@ class UserSessionFlowCoordinatorStateMachine {
case (.feedbackScreen(let selectedRoomID), .dismissedFeedbackScreen):
return .roomList(selectedRoomID: selectedRoomID)
case (.roomList(let selectedRoomID), .showSessionVerificationScreen):
return .sessionVerificationScreen(selectedRoomID: selectedRoomID)
case (.sessionVerificationScreen(let selectedRoomID), .dismissedSessionVerificationScreen):
return .roomList(selectedRoomID: selectedRoomID)
case (.roomList(let selectedRoomID), .showStartChatScreen):
return .startChatScreen(selectedRoomID: selectedRoomID)
case (.startChatScreen(let selectedRoomID), .dismissedStartChatScreen):
+2
View File
@@ -33,6 +33,7 @@ internal enum Asset {
internal enum Images {
internal static let appLogo = ImageAsset(name: "images/app-logo")
internal static let serverSelectionIcon = ImageAsset(name: "images/server-selection-icon")
internal static let backgroundBottom = ImageAsset(name: "images/background-bottom")
internal static let closeRte = ImageAsset(name: "images/close-rte")
internal static let composerAttachment = ImageAsset(name: "images/composer-attachment")
internal static let stopRecording = ImageAsset(name: "images/stop-recording")
@@ -41,6 +42,7 @@ internal enum Asset {
internal static let locationMarkerShape = ImageAsset(name: "images/location-marker-shape")
internal static let mediaPause = ImageAsset(name: "images/media-pause")
internal static let mediaPlay = ImageAsset(name: "images/media-play")
internal static let notificationsPromptGraphic = ImageAsset(name: "images/notifications-prompt-graphic")
internal static let waitingGradient = ImageAsset(name: "images/waiting-gradient")
}
}
+8
View File
@@ -991,6 +991,14 @@ internal enum L10n {
internal static var screenEditProfileTitle: String { return L10n.tr("Localizable", "screen_edit_profile_title") }
/// Updating profile…
internal static var screenEditProfileUpdatingDetails: String { return L10n.tr("Localizable", "screen_edit_profile_updating_details") }
/// Verify this device to set up secure messaging.
internal static var screenIdentityConfirmationSubtitle: String { return L10n.tr("Localizable", "screen_identity_confirmation_subtitle") }
/// Confirm that it's you
internal static var screenIdentityConfirmationTitle: String { return L10n.tr("Localizable", "screen_identity_confirmation_title") }
/// Now you can read or send messages securely, and anyone you chat with can also trust this device.
internal static var screenIdentityConfirmedSubtitle: String { return L10n.tr("Localizable", "screen_identity_confirmed_subtitle") }
/// Device verified
internal static var screenIdentityConfirmedTitle: String { return L10n.tr("Localizable", "screen_identity_confirmed_title") }
/// Are you sure you want to decline the invitation to join %1$@?
internal static func screenInvitesDeclineChatMessage(_ p1: Any) -> String {
return L10n.tr("Localizable", "screen_invites_decline_chat_message", String(describing: p1))
+9 -1
View File
@@ -34,10 +34,18 @@ extension ProcessInfo {
false
#endif
}
static var isRunningIntegrationTests: Bool {
#if DEBUG
processInfo.environment["IS_RUNNING_INTEGRATION_TESTS"] == "1"
#else
false
#endif
}
/// Flag indicating whether the app is running the UI tests or unit tests.
static var isRunningTests: Bool {
isRunningUITests || isRunningUnitTests
isRunningUITests || isRunningUnitTests || isRunningIntegrationTests
}
/// The identifier of the screen to be loaded when running UI tests.
@@ -33,6 +33,8 @@ struct FullscreenDialog<Content: View, BottomContent: View>: View {
/// The spacing between the content and the buttons.
var spacing: CGFloat = 16
var showBackgroundGradient = false
/// The main content shown at the top of the layout.
@ViewBuilder var content: () -> Content
/// The content shown at the bottom of the layout.
@@ -62,23 +64,32 @@ struct FullscreenDialog<Content: View, BottomContent: View>: View {
}
.scrollBounceBehavior(.basedOnSize)
.safeAreaInset(edge: .bottom) {
VStack(spacing: 0) {
bottomContent()
.readableFrame()
.padding(.horizontal, horizontalPadding)
.padding(.top, spacing)
.padding(.bottom, UIConstants.actionButtonBottomPadding)
Spacer()
.frame(height: UIConstants.spacerHeight(in: geometry))
if showBackgroundGradient {
adjustedBottomContent(geometry: geometry)
.background(Asset.Images.backgroundBottom.swiftUIImage.resizable().ignoresSafeArea())
} else {
adjustedBottomContent(geometry: geometry)
.background()
}
.background()
}
}
}
private func adjustedBottomContent(geometry: GeometryProxy) -> some View {
VStack(spacing: 0) {
bottomContent()
.readableFrame()
.padding(.horizontal, horizontalPadding)
.padding(.top, spacing)
.padding(.bottom, UIConstants.actionButtonBottomPadding)
Spacer()
.frame(height: UIConstants.spacerHeight(in: geometry))
}
}
/// A continuously scrolling layout used for accessibility font sizes.
var accessibilityLayout: some View {
private var accessibilityLayout: some View {
GeometryReader { geometry in
ScrollView {
VStack(spacing: 0) {
@@ -21,35 +21,61 @@ import SwiftUI
/// takes a compound icon. If you would like to apply it to an SFSymbol, you can call
/// the `heroImage()` modifier directly on the Image.
struct HeroImage: View {
enum Style {
case normal
case positive
var foregroundColor: Color {
switch self {
case .normal:
return .compound.iconPrimary
case .positive:
return .compound.iconSuccessPrimary
}
}
var backgroundFillColor: Color {
switch self {
case .normal:
return .compound.bgSubtleSecondary
case .positive:
return .compound.bgSuccessSubtle
}
}
}
/// The icon that is shown.
let icon: KeyPath<CompoundIcons, Image>
var style: Style = .normal
var body: some View {
CompoundIcon(icon, size: .custom(42), relativeTo: .title)
.modifier(HeroImageModifier())
.modifier(HeroImageModifier(style: style))
}
}
extension Image {
/// Styles the image for use as the main/top/hero screen icon. You should prefer
/// the HeroImage component when possible, by using an icon from Compound.
func heroImage(insets: CGFloat = 16) -> some View {
func heroImage(insets: CGFloat = 16, style: HeroImage.Style = .normal) -> some View {
resizable()
.renderingMode(.template)
.aspectRatio(contentMode: .fit)
.scaledPadding(insets, relativeTo: .title)
.modifier(HeroImageModifier())
.modifier(HeroImageModifier(style: style))
}
}
private struct HeroImageModifier: ViewModifier {
let style: HeroImage.Style
func body(content: Content) -> some View {
content
.foregroundColor(.compound.iconPrimary)
.scaledFrame(size: 70, relativeTo: .title)
.foregroundColor(style.foregroundColor)
.background {
RoundedRectangle(cornerRadius: 14)
.fill(Color.compound.bgSubtleSecondary)
.fill(style.backgroundFillColor)
}
.accessibilityHidden(true)
}
@@ -85,7 +85,7 @@ final class LoginScreenCoordinator: CoordinatorProtocol {
// MARK: - Private
private static let loadingIndicatorIdentifier = "LoginCoordinatorLoading"
private static let loadingIndicatorIdentifier = "\(LoginScreenCoordinatorAction.self)-Loading"
private func startLoading(isInteractionBlocking: Bool) {
if isInteractionBlocking {
@@ -104,7 +104,7 @@ final class SoftLogoutScreenCoordinator: CoordinatorProtocol {
// MARK: - Private
private static let loadingIndicatorIdentifier = "SoftLogoutLoading"
private static let loadingIndicatorIdentifier = "\(SoftLogoutScreenCoordinator.self)-Loading"
/// Show an activity indicator whilst loading.
@MainActor private func startLoading() {
@@ -82,7 +82,7 @@ class BlockedUsersScreenViewModel: BlockedUsersScreenViewModelType, BlockedUsers
// MARK: Loading indicator
private static let loadingIndicatorIdentifier = "BlockedUsersLoading"
private static let loadingIndicatorIdentifier = "\(BlockedUsersScreenViewModel.self)-Loading"
private func showLoadingIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -90,7 +90,7 @@ final class BugReportScreenCoordinator: CoordinatorProtocol {
// MARK: - Private
private static let loadingIndicatorIdentifier = "BugReportLoading"
private static let loadingIndicatorIdentifier = "\(BugReportScreenCoordinator.self)-Loading"
private func startLoading(label: String = L10n.commonLoading, progressPublisher: CurrentValuePublisher<Double, Never>) {
parameters.userIndicatorController?.submitIndicator(
@@ -171,7 +171,7 @@ class CreateRoomViewModel: CreateRoomViewModelType, CreateRoomViewModelProtocol
// MARK: Loading indicator
private static let loadingIndicatorIdentifier = "CreateRoomLoading"
private static let loadingIndicatorIdentifier = "\(CreateRoomViewModel.self)-Loading"
private func showLoadingIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -31,7 +31,6 @@ enum HomeScreenCoordinatorAction {
case roomLeft(roomIdentifier: String)
case presentSettingsScreen
case presentFeedbackScreen
case presentSessionVerificationScreen
case presentSecureBackupSettings
case presentStartChatScreen
case presentInvitesScreen
@@ -74,8 +73,6 @@ final class HomeScreenCoordinator: CoordinatorProtocol {
actionsSubject.send(.presentFeedbackScreen)
case .presentSettingsScreen:
actionsSubject.send(.presentSettingsScreen)
case .presentSessionVerificationScreen:
actionsSubject.send(.presentSessionVerificationScreen)
case .presentSecureBackupSettings:
actionsSubject.send(.presentSecureBackupSettings)
case .logout:
@@ -22,7 +22,6 @@ enum HomeScreenViewModelAction {
case presentRoom(roomIdentifier: String)
case presentRoomDetails(roomIdentifier: String)
case roomLeft(roomIdentifier: String)
case presentSessionVerificationScreen
case presentSecureBackupSettings
case presentSettingsScreen
case presentFeedbackScreen
@@ -39,9 +38,7 @@ enum HomeScreenViewAction {
case confirmLeaveRoom(roomIdentifier: String)
case showSettings
case startChat
case verifySession
case confirmRecoveryKey
case skipSessionVerification
case skipRecoveryKeyConfirmation
case updateVisibleItemRange(range: Range<Int>, isScrolling: Bool)
case selectInvites
@@ -74,7 +71,6 @@ enum HomeScreenRoomListMode: CustomStringConvertible {
enum SecurityBannerMode {
case none
case dismissed
case sessionVerification
case recoveryKeyConfirmation
}
@@ -70,11 +70,6 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
guard let self else { return }
switch (securityState.verificationState, securityState.recoveryState) {
case (.unverified, _):
state.requiresExtraAccountSetup = true
if state.securityBannerMode != .dismissed {
state.securityBannerMode = .sessionVerification
}
case (.verified, .disabled):
state.requiresExtraAccountSetup = true
state.securityBannerMode = .none
@@ -134,12 +129,8 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
leaveRoom(roomId: roomIdentifier)
case .showSettings:
actionsSubject.send(.presentSettingsScreen)
case .verifySession:
actionsSubject.send(.presentSessionVerificationScreen)
case .confirmRecoveryKey:
actionsSubject.send(.presentSecureBackupSettings)
case .skipSessionVerification:
state.securityBannerMode = .dismissed
case .skipRecoveryKeyConfirmation:
state.securityBannerMode = .dismissed
case .updateVisibleItemRange(let range, let isScrolling):
@@ -103,16 +103,13 @@ struct HomeScreenContent: View {
}
@ViewBuilder
/// The session verification banner and invites button if either are needed.
private var topSection: some View {
VStack(spacing: 0) {
if !context.isSearchFieldFocused {
RoomListFiltersView(state: $context.filtersState)
}
if context.viewState.securityBannerMode == .sessionVerification {
HomeScreenSessionVerificationBanner(context: context)
} else if context.viewState.securityBannerMode == .recoveryKeyConfirmation {
if context.viewState.securityBannerMode == .recoveryKeyConfirmation {
HomeScreenRecoveryKeyConfirmationBanner(context: context)
}
@@ -1,81 +0,0 @@
//
// Copyright 2023 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 HomeScreenSessionVerificationBanner: View {
@ObservedObject var context: HomeScreenViewModel.Context
var body: some View {
VStack(alignment: .leading, spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 16) {
Text(L10n.sessionVerificationBannerTitle)
.font(.compound.bodyLGSemibold)
.foregroundColor(.compound.textPrimary)
Spacer()
Button {
context.send(viewAction: .skipSessionVerification)
} label: {
Image(systemName: "xmark")
.foregroundColor(.compound.iconSecondary)
.frame(width: 12, height: 12)
}
}
Text(L10n.sessionVerificationBannerMessage)
.font(.compound.bodyMD)
.foregroundColor(.compound.textSecondary)
}
Button(L10n.actionContinue) {
context.send(viewAction: .verifySession)
}
.frame(maxWidth: .infinity)
.buttonStyle(.compound(.primary, size: .medium))
.accessibilityIdentifier(A11yIdentifiers.homeScreen.verificationBannerContinue)
}
.padding(16)
.background(Color.compound.bgSubtleSecondary)
.cornerRadius(14)
.padding(.horizontal, 16)
}
}
struct HomeScreenSessionVerificationBanner_Previews: PreviewProvider, TestablePreview {
static let viewModel = buildViewModel()
static var previews: some View {
HomeScreenSessionVerificationBanner(context: viewModel.context)
}
static func buildViewModel() -> HomeScreenViewModel {
let clientProxy = ClientProxyMock(.init(userID: "@alice:example.com",
roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loading))))
let userSession = MockUserSession(clientProxy: clientProxy,
mediaProvider: MockMediaProvider(),
voiceMessageMediaManager: VoiceMessageMediaManagerMock())
return HomeScreenViewModel(userSession: userSession,
analyticsService: ServiceLocator.shared.analytics,
appSettings: ServiceLocator.shared.settings,
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
userIndicatorController: ServiceLocator.shared.userIndicatorController)
}
}
@@ -63,7 +63,7 @@ struct CameraPicker: UIViewControllerRepresentable {
self.cameraPicker = cameraPicker
}
private static let loadingIndicatorIdentifier = "CameraPickerLoadingIndicator"
private static let loadingIndicatorIdentifier = "\(CameraPicker.self)-Loading"
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.delegate = nil
@@ -62,7 +62,7 @@ struct DocumentPicker: UIViewControllerRepresentable {
documentPicker.callback(.cancel)
}
private static let loadingIndicatorIdentifier = "DocumentPickerLoadingIndicator"
private static let loadingIndicatorIdentifier = "\(DocumentPicker.self)-Loading"
func documentPicker(_ picker: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else {
@@ -62,7 +62,7 @@ struct PhotoLibraryPicker: UIViewControllerRepresentable {
// MARK: PHPickerViewControllerDelegate
private static let loadingIndicatorIdentifier = "PhotoLibraryPickerLoadingIndicator"
private static let loadingIndicatorIdentifier = "\(PhotoLibraryPicker.self)-Loading"
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
guard let provider = results.first?.itemProvider,
@@ -102,7 +102,7 @@ class MediaUploadPreviewScreenViewModel: MediaUploadPreviewScreenViewModelType,
}
}
private static let loadingIndicatorIdentifier = "MediaUploadPreviewLoading"
private static let loadingIndicatorIdentifier = "\(MediaUploadPreviewScreenViewModel.self)-Loading"
private func startLoading(progressPublisher: CurrentValuePublisher<Double, Never>) {
userIndicatorController.submitIndicator(
@@ -21,7 +21,7 @@ struct AnalyticsPromptScreen: View {
@ObservedObject var context: AnalyticsPromptScreenViewModel.Context
var body: some View {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding) {
FullscreenDialog(topPadding: UIConstants.startScreenBreakerScreenTopPadding, showBackgroundGradient: true) {
mainContent
} bottomContent: {
buttons
@@ -30,6 +30,7 @@ struct AnalyticsPromptScreen: View {
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
.interactiveDismissDisabled()
}
/// The main content of the screen that is shown inside the scroll view.
@@ -88,12 +89,9 @@ struct AnalyticsPromptScreen: View {
/// The stack of enable/disable buttons.
private var buttons: some View {
VStack(spacing: 16) {
Button { context.send(viewAction: .enable) } label: {
Text(L10n.actionOk)
.font(.compound.bodyLGSemibold)
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.analyticsPromptScreen.enable)
Button(L10n.actionOk) { context.send(viewAction: .enable) }
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.analyticsPromptScreen.enable)
Button { context.send(viewAction: .disable) } label: {
Text(L10n.actionNotNow)
@@ -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))
}
}
@@ -1,5 +1,5 @@
//
// Copyright 2023 New Vector Ltd
// 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.
@@ -16,7 +16,12 @@
import Foundation
struct EncryptedHistoryRoomTimelineItem: DecorationTimelineItemProtocol, Equatable {
let id: TimelineItemIdentifier
let isSessionVerified: Bool
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)
}
}
@@ -18,13 +18,11 @@ import Combine
import SwiftUI
enum SessionVerificationScreenCoordinatorAction {
case recoveryKey
case done
}
struct SessionVerificationScreenCoordinatorParameters {
let sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol
let recoveryState: SecureBackupRecoveryState
}
final class SessionVerificationScreenCoordinator: CoordinatorProtocol {
@@ -38,8 +36,7 @@ final class SessionVerificationScreenCoordinator: CoordinatorProtocol {
}
init(parameters: SessionVerificationScreenCoordinatorParameters) {
viewModel = SessionVerificationScreenViewModel(sessionVerificationControllerProxy: parameters.sessionVerificationControllerProxy,
recoveryState: parameters.recoveryState)
viewModel = SessionVerificationScreenViewModel(sessionVerificationControllerProxy: parameters.sessionVerificationControllerProxy)
}
// MARK: - Public
@@ -50,8 +47,6 @@ final class SessionVerificationScreenCoordinator: CoordinatorProtocol {
guard let self else { return }
switch action {
case .recoveryKey:
actionsSubject.send(.recoveryKey)
case .finished:
actionsSubject.send(.done)
}
@@ -59,6 +54,10 @@ final class SessionVerificationScreenCoordinator: CoordinatorProtocol {
.store(in: &cancellables)
}
func stop() {
viewModel.stop()
}
func toPresentable() -> AnyView {
AnyView(SessionVerificationScreen(context: viewModel.context))
}
@@ -17,13 +17,10 @@
import Foundation
enum SessionVerificationScreenViewModelAction {
case recoveryKey
case finished
}
struct SessionVerificationScreenViewState: BindableState {
let showRecoveryOption: Bool
var verificationState: SessionVerificationScreenStateMachine.State = .initial
var title: String? {
@@ -86,11 +83,9 @@ struct SessionVerificationScreenViewState: BindableState {
}
enum SessionVerificationScreenViewAction {
case recoveryKey
case requestVerification
case startSasVerification
case restart
case accept
case decline
case close
}
@@ -31,13 +31,12 @@ class SessionVerificationScreenViewModel: SessionVerificationViewModelType, Sess
}
init(sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol,
recoveryState: SecureBackupRecoveryState,
verificationState: SessionVerificationScreenStateMachine.State = .initial) {
self.sessionVerificationControllerProxy = sessionVerificationControllerProxy
stateMachine = SessionVerificationScreenStateMachine()
super.init(initialViewState: .init(showRecoveryOption: recoveryState == .incomplete, verificationState: verificationState))
super.init(initialViewState: .init(verificationState: verificationState))
setupStateMachine()
@@ -71,23 +70,12 @@ class SessionVerificationScreenViewModel: SessionVerificationViewModelType, Sess
override func process(viewAction: SessionVerificationScreenViewAction) {
switch viewAction {
case .recoveryKey:
actionsSubject.send(.recoveryKey)
case .requestVerification:
stateMachine.processEvent(.requestVerification)
case .startSasVerification:
stateMachine.processEvent(.startSasVerification)
case .restart:
stateMachine.processEvent(.restart)
case .close:
guard stateMachine.state == .initial ||
stateMachine.state == .verified ||
stateMachine.state == .cancelled else {
stateMachine.processEvent(.cancel)
return
}
actionsSubject.send(.finished)
case .accept:
stateMachine.processEvent(.acceptChallenge)
case .decline:
@@ -95,6 +83,14 @@ class SessionVerificationScreenViewModel: SessionVerificationViewModelType, Sess
}
}
func stop() {
let uncancellableStates: [SessionVerificationScreenStateMachine.State] = [.initial, .verified, .cancelled]
if !uncancellableStates.contains(stateMachine.state) {
stateMachine.processEvent(.cancel)
}
}
// MARK: - Private
private func setupStateMachine() {
@@ -115,11 +111,7 @@ class SessionVerificationScreenViewModel: SessionVerificationViewModelType, Sess
case (_, .cancel, .cancelling):
cancelVerification()
case (_, _, .verified):
// Dismiss the success screen automatically.
Task {
try? await Task.sleep(for: .seconds(2))
self.actionsSubject.send(.finished)
}
actionsSubject.send(.finished)
default:
break
}
@@ -20,4 +20,6 @@ import Combine
protocol SessionVerificationScreenViewModelProtocol {
var actions: AnyPublisher<SessionVerificationScreenViewModelAction, Never> { get }
var context: SessionVerificationViewModelType.Context { get }
func stop()
}
@@ -20,23 +20,18 @@ struct SessionVerificationScreen: View {
@ObservedObject var context: SessionVerificationScreenViewModel.Context
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 32) {
screenHeader
Spacer()
mainContent
}
.padding(.horizontal, 16)
.padding(.top, 24)
.frame(maxWidth: .infinity)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbarContent }
FullscreenDialog {
VStack(spacing: 32) {
screenHeader
Spacer()
mainContent
}
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.safeAreaInset(edge: .bottom) { actionButtons.padding() }
} bottomContent: {
actionButtons
}
.interactiveDismissDisabled() // Make sure dismissal goes through the state machine(s).
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.interactiveDismissDisabled()
}
// MARK: - Private
@@ -44,7 +39,7 @@ struct SessionVerificationScreen: View {
private var headerImageName: String {
switch context.viewState.verificationState {
case .initial:
return "macbook.and.iphone"
return "lock"
case .cancelled:
return "exclamationmark.shield"
case .requestingVerification:
@@ -71,19 +66,24 @@ struct SessionVerificationScreen: View {
@ViewBuilder
private var screenHeader: some View {
VStack(spacing: 0) {
Image(systemName: headerImageName)
.heroImage()
.padding(.bottom, 16)
if context.viewState.verificationState == .initial {
HeroImage(icon: \.lockSolid)
.padding(.bottom, 16)
} else {
Image(systemName: headerImageName)
.heroImage()
.padding(.bottom, 16)
}
Text(context.viewState.title ?? "")
.font(.title2.bold())
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textPrimary)
.padding(.bottom, 8)
.accessibilityIdentifier(context.viewState.titleAccessibilityIdentifier)
Text(context.viewState.message)
.font(.subheadline)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
.foregroundColor(.compound.textSecondary)
}
@@ -134,14 +134,6 @@ struct SessionVerificationScreen: View {
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.requestVerification)
if context.viewState.showRecoveryOption {
Button(L10n.screenSessionVerificationEnterRecoveryKey) {
context.send(viewAction: .recoveryKey)
}
.buttonStyle(.compound(.plain))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.enterRecoveryKey)
}
}
case .cancelled:
Button(L10n.actionRetry) {
@@ -157,9 +149,9 @@ struct SessionVerificationScreen: View {
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.startSasVerification)
case .showingChallenge:
VStack(spacing: 30) {
Button { context.send(viewAction: .accept) } label: {
Label(L10n.screenSessionVerificationTheyMatch, systemImage: "checkmark")
VStack(spacing: 32) {
Button(L10n.screenSessionVerificationTheyMatch) {
context.send(viewAction: .accept)
}
.buttonStyle(.compound(.primary))
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.acceptChallenge)
@@ -172,12 +164,12 @@ struct SessionVerificationScreen: View {
}
case .acceptingChallenge:
VStack(spacing: 30) {
VStack(spacing: 32) {
Button { context.send(viewAction: .accept) } label: {
HStack(spacing: 16) {
ProgressView()
.tint(.compound.textOnSolidPrimary)
Label(L10n.screenSessionVerificationTheyMatch, systemImage: "checkmark")
Text(L10n.screenSessionVerificationTheyMatch)
}
}
.buttonStyle(.compound(.primary))
@@ -197,16 +189,6 @@ struct SessionVerificationScreen: View {
}
}
@ToolbarContentBuilder
private var toolbarContent: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel) {
context.send(viewAction: .close)
}
.accessibilityIdentifier(A11yIdentifiers.sessionVerificationScreen.close)
}
}
struct EmojiView: View {
let emoji: SessionVerificationEmoji
@@ -244,7 +226,6 @@ struct SessionVerification_Previews: PreviewProvider, TestablePreview {
static func sessionVerificationScreen(state: SessionVerificationScreenStateMachine.State) -> some View {
let viewModel = SessionVerificationScreenViewModel(sessionVerificationControllerProxy: SessionVerificationControllerProxyMock.configureMock(),
recoveryState: .incomplete,
verificationState: state)
return SessionVerificationScreen(context: viewModel.context)
@@ -82,7 +82,7 @@ final class ReportContentScreenCoordinator: CoordinatorProtocol {
// MARK: - Private
private static let loadingIndicatorIdentifier = "ReportContentLoading"
private static let loadingIndicatorIdentifier = "\(ReportContentScreenCoordinator.self)-Loading"
private func startLoading() {
parameters.userIndicatorController.submitIndicator(
@@ -171,7 +171,7 @@ class RoomMemberDetailsScreenViewModel: RoomMemberDetailsScreenViewModelType, Ro
// MARK: Loading indicator
private static let loadingIndicatorIdentifier = "RoomMemberLoading"
private static let loadingIndicatorIdentifier = "\(RoomMemberDetailsScreenViewModel.self)-Loading"
private func showMemberLoadingIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -97,9 +97,8 @@ struct TimelineItemPlainStylerView<Content: View>: View {
HStack(spacing: 8) {
TimelineSenderAvatarView(timelineItem: timelineItem)
Text(timelineItem.sender.displayName ?? timelineItem.sender.id)
.font(.subheadline)
.font(.compound.bodyMDSemibold)
.foregroundColor(.compound.decorativeColor(for: timelineItem.sender.id).text)
.fontWeight(.semibold)
.lineLimit(1)
}
.onTapGesture {
@@ -1,68 +0,0 @@
//
// Copyright 2023 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
/// The item shown when all previous items are un-decryptable due to
/// key backup not yet being supported in the app.
struct EncryptedHistoryRoomTimelineView: View {
let timelineItem: EncryptedHistoryRoomTimelineItem
var body: some View {
Label {
Text(title)
.font(.compound.bodyMDSemibold)
.foregroundColor(.compound.textInfoPrimary)
} icon: {
CompoundIcon(\.infoSolid, size: .small, relativeTo: .compound.bodyMDSemibold)
.foregroundColor(.compound.iconInfoPrimary)
}
.labelStyle(EncryptedHistoryLabelStyle())
.padding(16)
.background {
RoundedRectangle(cornerRadius: 8)
.fill(Color.compound.bgInfoSubtle)
RoundedRectangle(cornerRadius: 8)
.stroke(Color.compound.borderInfoSubtle)
}
.frame(maxWidth: .infinity)
.padding(.horizontal, 8)
.padding(.vertical, 16)
}
private var title: String {
timelineItem.isSessionVerified ? L10n.screenRoomEncryptedHistoryBanner : L10n.screenRoomEncryptedHistoryBannerUnverified
}
}
private struct EncryptedHistoryLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
HStack(alignment: .top, spacing: 16) {
configuration.icon
configuration.title
}
}
}
struct EncryptedHistoryRoomTimelineView_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
VStack(spacing: 8) {
EncryptedHistoryRoomTimelineView(timelineItem: .init(id: .random, isSessionVerified: true))
EncryptedHistoryRoomTimelineView(timelineItem: .init(id: .random, isSessionVerified: false))
}
}
}
@@ -86,7 +86,7 @@ class SecureBackupKeyBackupScreenViewModel: SecureBackupKeyBackupScreenViewModel
}
}
private static let loadingIndicatorIdentifier = "SecureBackupKeyBackupScreenLoading"
private static let loadingIndicatorIdentifier = "\(SecureBackupKeyBackupScreenViewModel.self)-Loading"
private func showLoadingIndicator() {
userIndicatorController?.submitIndicator(.init(id: Self.loadingIndicatorIdentifier, type: .modal, title: L10n.commonLoading, persistent: true))
@@ -22,12 +22,21 @@ struct SecureBackupKeyBackupScreen: View {
@ObservedObject var context: SecureBackupKeyBackupScreenViewModel.Context
var body: some View {
mainContent
.padding()
.interactiveDismissDisabled()
.toolbar { toolbar }
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.alert(item: $context.alertInfo)
FullscreenDialog {
mainContent
} bottomContent: {
Button(role: .destructive) {
context.send(viewAction: .toggleBackup)
} label: {
Text(L10n.screenChatBackupKeyBackupActionDisable)
}
.buttonStyle(.compound(.primary))
}
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.interactiveDismissDisabled()
.toolbar { toolbar }
.alert(item: $context.alertInfo)
}
@ViewBuilder
@@ -71,15 +80,6 @@ struct SecureBackupKeyBackupScreen: View {
.foregroundColor(.compound.iconCriticalPrimary)
}
}
Spacer()
Button(role: .destructive) {
context.send(viewAction: .toggleBackup)
} label: {
Text(L10n.screenChatBackupKeyBackupActionDisable)
}
.buttonStyle(.compound(.primary))
}
}
@@ -22,26 +22,21 @@ struct SecureBackupLogoutConfirmationScreen: View {
@ObservedObject var context: SecureBackupLogoutConfirmationScreenViewModel.Context
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 16) {
header
content
}
.padding()
FullscreenDialog {
VStack(spacing: 16) {
HeroImage(icon: \.keyOffSolid)
content
}
.toolbar { toolbar }
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.safeAreaInset(edge: .bottom) { footer.padding() }
.alert(item: $context.alertInfo)
.padding()
} bottomContent: {
footer.padding()
}
.toolbar { toolbar }
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.alert(item: $context.alertInfo)
}
@ViewBuilder
private var header: some View {
HeroImage(icon: \.keyOffSolid)
}
@ViewBuilder
private var content: some View {
Text(title)
@@ -62,21 +57,23 @@ struct SecureBackupLogoutConfirmationScreen: View {
@ViewBuilder
private var footer: some View {
if context.viewState.mode == .saveRecoveryKey {
Button {
context.send(viewAction: .settings)
VStack(spacing: 16.0) {
if context.viewState.mode == .saveRecoveryKey {
Button {
context.send(viewAction: .settings)
} label: {
Text(L10n.commonSettings)
}
.buttonStyle(.compound(.primary))
}
Button(role: .destructive) {
context.send(viewAction: .logout)
} label: {
Text(L10n.commonSettings)
Text(L10n.actionSignout)
}
.buttonStyle(.compound(.primary))
}
Button(role: .destructive) {
context.send(viewAction: .logout)
} label: {
Text(L10n.actionSignout)
}
.buttonStyle(.compound(.primary))
}
@ToolbarContentBuilder
@@ -88,7 +85,7 @@ struct SecureBackupLogoutConfirmationScreen: View {
}
}
var title: String {
private var title: String {
switch context.viewState.mode {
case .saveRecoveryKey:
return L10n.screenSignoutSaveRecoveryKeyTitle
@@ -99,7 +96,7 @@ struct SecureBackupLogoutConfirmationScreen: View {
}
}
var subtitle: String {
private var subtitle: String {
switch context.viewState.mode {
case .saveRecoveryKey:
return L10n.screenSignoutSaveRecoveryKeySubtitle
@@ -20,6 +20,7 @@ import SwiftUI
struct SecureBackupRecoveryKeyScreenCoordinatorParameters {
let secureBackupController: SecureBackupControllerProtocol
let userIndicatorController: UserIndicatorControllerProtocol
let isModallyPresented: Bool
}
enum SecureBackupRecoveryKeyScreenCoordinatorAction {
@@ -40,7 +41,8 @@ final class SecureBackupRecoveryKeyScreenCoordinator: CoordinatorProtocol {
init(parameters: SecureBackupRecoveryKeyScreenCoordinatorParameters) {
viewModel = SecureBackupRecoveryKeyScreenViewModel(secureBackupController: parameters.secureBackupController,
userIndicatorController: parameters.userIndicatorController)
userIndicatorController: parameters.userIndicatorController,
isModallyPresented: parameters.isModallyPresented)
}
func start() {
@@ -28,6 +28,9 @@ enum SecureBackupRecoveryKeyScreenViewMode {
}
struct SecureBackupRecoveryKeyScreenViewState: BindableState {
/// Whether the screen is presented modally or within a navigation stack.
var isModallyPresented: Bool
let mode: SecureBackupRecoveryKeyScreenViewMode
var recoveryKey: String?
@@ -28,11 +28,15 @@ class SecureBackupRecoveryKeyScreenViewModel: SecureBackupRecoveryKeyScreenViewM
actionsSubject.eraseToAnyPublisher()
}
init(secureBackupController: SecureBackupControllerProtocol, userIndicatorController: UserIndicatorControllerProtocol) {
init(secureBackupController: SecureBackupControllerProtocol,
userIndicatorController: UserIndicatorControllerProtocol,
isModallyPresented: Bool) {
self.secureBackupController = secureBackupController
self.userIndicatorController = userIndicatorController
super.init(initialViewState: .init(mode: secureBackupController.recoveryState.value.viewMode, bindings: .init()))
super.init(initialViewState: .init(isModallyPresented: isModallyPresented,
mode: secureBackupController.recoveryState.value.viewMode,
bindings: .init()))
secureBackupController.recoveryState
.receive(on: DispatchQueue.main)
@@ -24,7 +24,7 @@ struct SecureBackupRecoveryKeyScreen: View {
private let textFieldIdentifier = "textFieldIdentifier"
var body: some View {
ScrollView {
FullscreenDialog {
ScrollViewReader { reader in
mainContent
.padding(16)
@@ -33,17 +33,14 @@ struct SecureBackupRecoveryKeyScreen: View {
reader.scrollTo(textFieldIdentifier)
}
}
}
.safeAreaInset(edge: .bottom) {
} bottomContent: {
footer
.padding([.horizontal, .bottom], 16)
.padding(.top, 8)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
}
.interactiveDismissDisabled()
.toolbar { toolbar }
.toolbar(.visible, for: .navigationBar)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.background()
.environment(\.backgroundStyle, AnyShapeStyle(Color.compound.bgCanvasDefault))
.interactiveDismissDisabled()
.alert(item: $context.alertInfo)
}
@@ -101,7 +98,7 @@ struct SecureBackupRecoveryKeyScreen: View {
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
if context.viewState.recoveryKey == nil {
if context.viewState.isModallyPresented == true, context.viewState.recoveryKey == nil {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
@@ -235,6 +232,8 @@ struct SecureBackupRecoveryKeyScreen_Previews: PreviewProvider, TestablePreview
let backupController = SecureBackupControllerMock()
backupController.underlyingRecoveryState = CurrentValueSubject<SecureBackupRecoveryState, Never>(recoveryState).asCurrentValuePublisher()
return SecureBackupRecoveryKeyScreenViewModel(secureBackupController: backupController, userIndicatorController: UserIndicatorControllerMock())
return SecureBackupRecoveryKeyScreenViewModel(secureBackupController: backupController,
userIndicatorController: UserIndicatorControllerMock(),
isModallyPresented: true)
}
}
@@ -46,7 +46,8 @@ final class SecureBackupScreenCoordinator: CoordinatorProtocol {
let navigationStackCoordinator = NavigationStackCoordinator()
let recoveryKeyCoordinator = SecureBackupRecoveryKeyScreenCoordinator(parameters: .init(secureBackupController: parameters.secureBackupController,
userIndicatorController: parameters.userIndicatorController))
userIndicatorController: parameters.userIndicatorController,
isModallyPresented: true))
recoveryKeyCoordinator.actions.sink { [weak self] action in
guard let self else { return }
@@ -33,7 +33,6 @@ enum SettingsScreenCoordinatorAction {
case bugReport
case about
case blockedUsers
case sessionVerification
case accountSessions
case notifications
case advancedSettings
@@ -77,8 +76,6 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
actionsSubject.send(.about)
case .blockedUsers:
actionsSubject.send(.blockedUsers)
case .sessionVerification:
actionsSubject.send(.sessionVerification)
case .secureBackup:
actionsSubject.send(.secureBackup)
case .accountSessionsList:
@@ -26,7 +26,6 @@ enum SettingsScreenViewModelAction {
case reportBug
case about
case blockedUsers
case sessionVerification
case secureBackup
case accountSessionsList
case notifications
@@ -37,7 +36,6 @@ enum SettingsScreenViewModelAction {
enum SettingsScreenSecuritySectionMode {
case none
case sessionVerification
case secureBackup
}
@@ -65,7 +63,6 @@ enum SettingsScreenViewAction {
case reportBug
case about
case blockedUsers
case sessionVerification
case secureBackup
case accountSessionsList
case notifications
@@ -50,9 +50,6 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
guard let self else { return }
switch (securityState.verificationState, securityState.recoveryState) {
case (.unverified, _):
state.showSecuritySectionBadge = true
state.securitySectionMode = .sessionVerification
case (.verified, .disabled):
state.showSecuritySectionBadge = true
state.securitySectionMode = .secureBackup
@@ -107,8 +104,6 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
actionsSubject.send(.blockedUsers)
case .logout:
actionsSubject.send(.logout)
case .sessionVerification:
actionsSubject.send(.sessionVerification)
case .secureBackup:
actionsSubject.send(.secureBackup)
case .notifications:
@@ -81,11 +81,6 @@ struct SettingsScreen: View {
private var accountSecuritySection: some View {
Section {
switch context.viewState.securitySectionMode {
case .sessionVerification:
ListRow(label: .default(title: L10n.actionCompleteVerification,
icon: \.checkCircle),
details: context.viewState.showSecuritySectionBadge ? .icon(securitySectionBadge) : nil,
kind: .button { context.send(viewAction: .sessionVerification) })
case .secureBackup:
ListRow(label: .default(title: L10n.commonChatBackup,
icon: \.key),
@@ -190,7 +190,7 @@ final class StartChatScreenCoordinator: CoordinatorProtocol {
// MARK: Loading indicator
private static let loadingIndicatorIdentifier = "StartChatCoordinatorLoading"
private static let loadingIndicatorIdentifier = "\(StartChatScreenCoordinator.self)-Loading"
private func showLoadingIndicator() {
parameters.userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -145,7 +145,7 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
// MARK: Loading indicator
private static let loadingIndicatorIdentifier = "StartChatLoading"
private static let loadingIndicatorIdentifier = "\(StartChatScreenViewModel.self)-Loading"
private func showLoadingIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: Self.loadingIndicatorIdentifier,
@@ -64,15 +64,8 @@ final class NotificationManager: NSObject, NotificationManagerProtocol {
self?.enableNotifications(newValue)
}
.store(in: &cancellables)
// Request authorization uppon UIApplication.didBecomeActiveNotification notification
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
.sink { [weak self] _ in
self?.requestAuthorization()
}
.store(in: &cancellables)
}
func requestAuthorization() {
guard appSettings.enableNotifications, !userSession.isNil else { return }
Task {
@@ -38,5 +38,6 @@ protocol NotificationManagerProtocol: AnyObject {
func registrationFailed(with error: Error)
func showLocalNotification(with title: String, subtitle: String?) async
func setUserSession(_ userSession: UserSessionProtocol?)
func requestAuthorization()
}
@@ -18,8 +18,7 @@ import Foundation
struct MockRoomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol {
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol {
timelineItemFactory: RoomTimelineItemFactoryProtocol) -> RoomTimelineControllerProtocol {
let timelineController = MockRoomTimelineController()
timelineController.timelineItems = RoomTimelineItemFixtures.largeChunk
return timelineController
@@ -24,7 +24,6 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
private let timelineProvider: RoomTimelineProviderProtocol
private let timelineItemFactory: RoomTimelineItemFactoryProtocol
private let appSettings: AppSettings
private let secureBackupController: SecureBackupControllerProtocol
private let serialDispatchQueue: DispatchQueue
private var cancellables = Set<AnyCancellable>()
@@ -39,13 +38,11 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
init(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
appSettings: AppSettings,
secureBackupController: SecureBackupControllerProtocol) {
appSettings: AppSettings) {
self.roomProxy = roomProxy
timelineProvider = roomProxy.timeline.timelineProvider
self.timelineItemFactory = timelineItemFactory
self.appSettings = appSettings
self.secureBackupController = secureBackupController
serialDispatchQueue = DispatchQueue(label: "io.element.elementx.roomtimelineprovider", qos: .utility)
timelineProvider
@@ -253,7 +250,6 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
var newTimelineItems = [RoomTimelineItemProtocol]()
var canBackPaginate = !roomProxy.timeline.timelineStartReached
var isBackPaginating = false
var lastEncryptedHistoryItemIndex: Int?
let collapsibleChunks = timelineProvider.itemProxies.groupBy { isItemCollapsible($0) }
@@ -264,10 +260,6 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
let timelineItem = buildTimelineItem(for: itemProxy)
if timelineItem is EncryptedHistoryRoomTimelineItem {
canBackPaginate = false
}
return timelineItem
}
@@ -282,35 +274,25 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
continue
}
if timelineItem is EncryptedHistoryRoomTimelineItem {
lastEncryptedHistoryItemIndex = newTimelineItems.endIndex
}
newTimelineItems.append(timelineItem)
} else {
newTimelineItems.append(CollapsibleTimelineItem(items: items))
}
}
if let lastEncryptedHistoryItemIndex {
// Remove everything up to the last encrypted history item.
// It only contains encrypted messages, state changes and date separators.
newTimelineItems.removeFirst(lastEncryptedHistoryItemIndex)
} else {
// Otherwise check if we need to add anything to the top of the timeline.
switch timelineProvider.backPaginationState {
case .timelineStartReached:
if !roomProxy.isEncryptedOneToOneRoom {
let timelineStart = TimelineStartRoomTimelineItem(name: roomProxy.name)
newTimelineItems.insert(timelineStart, at: 0)
}
canBackPaginate = false
case .paginating:
newTimelineItems.insert(PaginationIndicatorRoomTimelineItem(), at: 0)
isBackPaginating = true
case .idle:
break
// Check if we need to add anything to the top of the timeline.
switch timelineProvider.backPaginationState {
case .timelineStartReached:
if !roomProxy.isEncryptedOneToOneRoom {
let timelineStart = TimelineStartRoomTimelineItem(name: roomProxy.name)
newTimelineItems.insert(timelineStart, at: 0)
}
canBackPaginate = false
case .paginating:
newTimelineItems.insert(PaginationIndicatorRoomTimelineItem(), at: 0)
isBackPaginating = true
case .idle:
break
}
DispatchQueue.main.sync {
@@ -326,17 +308,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
switch itemProxy {
case .event(let eventTimelineItem):
let timelineItem = timelineItemFactory.buildTimelineItem(for: eventTimelineItem, isDM: roomProxy.isEncryptedOneToOneRoom)
// When backup is enabled just show the timeline items, they will most likely
// resolve eventually. If we don't know the backup state then we assume the session is not verified yet,
// otherwise we just treat it as fully disabled.
if secureBackupController.keyBackupState.value != .enabled {
if timelineItem is EncryptedRoomTimelineItem, isItemInEncryptionHistory(eventTimelineItem) {
return EncryptedHistoryRoomTimelineItem(id: eventTimelineItem.id,
isSessionVerified: secureBackupController.keyBackupState.value != .unknown)
}
}
if let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol {
// Avoid fetching this over and over again as it changes states if it keeps failing to load
// Errors will be handled again on appearance
@@ -358,14 +330,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
return nil
}
}
/// Whether or not a specific item is part of the room's history that can't be decrypted due
/// to the lack of key-backup. This is handled differently so we only show a single item.
private func isItemInEncryptionHistory(_ itemProxy: EventTimelineItemProxy) -> Bool {
guard roomProxy.isEncrypted, let lastLoginDate = appSettings.lastLoginDate else { return false }
return itemProxy.timestamp < lastLoginDate
}
private func isItemCollapsible(_ item: TimelineItemProxy) -> Bool {
if !appSettings.shouldCollapseRoomStateEvents {
return false
@@ -18,11 +18,9 @@ import Foundation
struct RoomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol {
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol {
timelineItemFactory: RoomTimelineItemFactoryProtocol) -> RoomTimelineControllerProtocol {
RoomTimelineController(roomProxy: roomProxy,
timelineItemFactory: timelineItemFactory,
appSettings: ServiceLocator.shared.settings,
secureBackupController: secureBackupController)
appSettings: ServiceLocator.shared.settings)
}
}
@@ -19,6 +19,5 @@ import Foundation
@MainActor
protocol RoomTimelineControllerFactoryProtocol {
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol
timelineItemFactory: RoomTimelineItemFactoryProtocol) -> RoomTimelineControllerProtocol
}
@@ -64,8 +64,6 @@ struct RoomTimelineItemView: View {
UnsupportedRoomTimelineView(timelineItem: item)
case .timelineStart(let item):
TimelineStartRoomTimelineView(timelineItem: item)
case .encryptedHistory(let item):
EncryptedHistoryRoomTimelineView(timelineItem: item)
case .state(let item):
StateRoomTimelineView(timelineItem: item)
case .group(let item):
@@ -60,7 +60,6 @@ enum RoomTimelineItemType: Equatable {
case sticker(StickerRoomTimelineItem)
case unsupported(UnsupportedRoomTimelineItem)
case timelineStart(TimelineStartRoomTimelineItem)
case encryptedHistory(EncryptedHistoryRoomTimelineItem)
case state(StateRoomTimelineItem)
case group(CollapsibleTimelineItem)
case location(LocationRoomTimelineItem)
@@ -100,8 +99,6 @@ enum RoomTimelineItemType: Equatable {
self = .unsupported(item)
case let item as TimelineStartRoomTimelineItem:
self = .timelineStart(item)
case let item as EncryptedHistoryRoomTimelineItem:
self = .encryptedHistory(item)
case let item as StateRoomTimelineItem:
self = .state(item)
case let item as CollapsibleTimelineItem:
@@ -136,7 +133,6 @@ enum RoomTimelineItemType: Equatable {
.sticker(let item as RoomTimelineItemProtocol),
.unsupported(let item as RoomTimelineItemProtocol),
.timelineStart(let item as RoomTimelineItemProtocol),
.encryptedHistory(let item as RoomTimelineItemProtocol),
.state(let item as RoomTimelineItemProtocol),
.group(let item as RoomTimelineItemProtocol),
.location(let item as RoomTimelineItemProtocol),
@@ -42,7 +42,7 @@ class UITestsAppCoordinator: AppCoordinatorProtocol, WindowManagerDelegate {
ServiceLocator.shared.register(userIndicatorController: UserIndicatorController())
AppSettings.configureWithSuiteName("io.element.elementx.uitests")
AppSettings.reset()
AppSettings.resetAllSettings()
ServiceLocator.shared.register(appSettings: AppSettings())
ServiceLocator.shared.register(bugReportService: BugReportServiceMock())
ServiceLocator.shared.register(analytics: AnalyticsService(client: AnalyticsClientMock(),
@@ -149,7 +149,6 @@ class MockScreen: Identifiable {
return navigationStackCoordinator
case .authenticationFlow:
let flowCoordinator = AuthenticationFlowCoordinator(authenticationService: MockAuthenticationServiceProxy(),
appLockService: AppLockServiceMock(),
bugReportService: BugReportServiceMock(),
navigationRootCoordinator: navigationRootCoordinator,
appSettings: ServiceLocator.shared.settings,
@@ -567,8 +566,7 @@ class MockScreen: Identifiable {
return navigationStackCoordinator
case .sessionVerification:
var sessionVerificationControllerProxy = SessionVerificationControllerProxyMock.configureMock(requestDelay: .seconds(5))
let parameters = SessionVerificationScreenCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationControllerProxy,
recoveryState: .unknown)
let parameters = SessionVerificationScreenCoordinatorParameters(sessionVerificationControllerProxy: sessionVerificationControllerProxy)
return SessionVerificationScreenCoordinator(parameters: parameters)
case .userSessionScreen, .userSessionScreenReply, .userSessionScreenRTE:
let appSettings: AppSettings = ServiceLocator.shared.settings
@@ -586,7 +584,9 @@ class MockScreen: Identifiable {
bugReportService: BugReportServiceMock(),
roomTimelineControllerFactory: MockRoomTimelineControllerFactory(),
appSettings: appSettings,
analytics: ServiceLocator.shared.analytics)
analytics: ServiceLocator.shared.analytics,
notificationManager: NotificationManagerMock(),
isNewLogin: false)
flowCoordinator.start()
@@ -24,7 +24,7 @@ class UnitTestsAppCoordinator: AppCoordinatorProtocol {
ServiceLocator.shared.register(userIndicatorController: UserIndicatorControllerMock.default)
AppSettings.configureWithSuiteName("io.element.elementx.unittests")
AppSettings.reset()
AppSettings.resetAllSettings()
ServiceLocator.shared.register(appSettings: AppSettings())
ServiceLocator.shared.register(bugReportService: BugReportServiceMock())
ServiceLocator.shared.register(analytics: AnalyticsService(client: AnalyticsClientMock(),