Renaming screens returns (#829)

* Rename: StartChat -> StartChatScreen

* Rename: Login -> LoginScreen

* Rename: ServerSelection -> ServerSelectionScreen

* Rename: SoftLogout -> SoftLogoutScreen
This commit is contained in:
Stefan Ceriu
2023-04-25 12:13:03 +03:00
committed by GitHub
parent 24572c6582
commit b726cd149a
31 changed files with 286 additions and 286 deletions
@@ -0,0 +1,84 @@
//
// 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
struct StartChatScreenCoordinatorParameters {
let userSession: UserSessionProtocol
weak var userIndicatorController: UserIndicatorControllerProtocol?
let navigationStackCoordinator: NavigationStackCoordinator?
let userDiscoveryService: UserDiscoveryServiceProtocol
}
enum StartChatScreenCoordinatorAction {
case close
case openRoom(withIdentifier: String)
}
final class StartChatScreenCoordinator: CoordinatorProtocol {
private let parameters: StartChatScreenCoordinatorParameters
private var viewModel: StartChatScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<StartChatScreenCoordinatorAction, Never> = .init()
private var cancellables: Set<AnyCancellable> = .init()
var actions: AnyPublisher<StartChatScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: StartChatScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = StartChatScreenViewModel(userSession: parameters.userSession, userIndicatorController: parameters.userIndicatorController, userDiscoveryService: parameters.userDiscoveryService)
}
func start() {
viewModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .close:
self.actionsSubject.send(.close)
case .createRoom:
// before creating a room we select the users we would like to invite in that room
self.presentInviteUsersScreen()
case .openRoom(let identifier):
self.actionsSubject.send(.openRoom(withIdentifier: identifier))
}
}
.store(in: &cancellables)
}
// MARK: - Public
func toPresentable() -> AnyView {
AnyView(StartChatScreen(context: viewModel.context))
}
// MARK: - Private
private func presentInviteUsersScreen() {
let inviteParameters = InviteUsersScreenCoordinatorParameters(userSession: parameters.userSession, userDiscoveryService: parameters.userDiscoveryService)
let coordinator = InviteUsersScreenCoordinator(parameters: inviteParameters)
coordinator.actions.sink { [weak self] result in
switch result {
case .close:
self?.parameters.navigationStackCoordinator?.pop()
}
}
.store(in: &cancellables)
parameters.navigationStackCoordinator?.push(coordinator)
}
}
@@ -0,0 +1,55 @@
//
// 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 StartChatScreenErrorType: Error {
case failedCreatingRoom
case unknown
}
enum StartChatScreenViewModelAction {
case close
case createRoom
case openRoom(withIdentifier: String)
}
struct StartChatScreenViewState: BindableState {
var bindings = StartChatScreenViewStateBindings()
var usersSection: UserDiscoverySection = .init(type: .suggestions, users: [])
var isSearching: Bool {
!bindings.searchQuery.isEmpty
}
var hasEmptySearchResults: Bool {
isSearching && usersSection.type == .searchResult && usersSection.users.isEmpty
}
}
struct StartChatScreenViewStateBindings {
var searchQuery = ""
/// Information describing the currently displayed alert.
var alertInfo: AlertInfo<StartChatScreenErrorType>?
}
enum StartChatScreenViewAction {
case close
case createRoom
case inviteFriends
case selectUser(UserProfile)
}
@@ -0,0 +1,165 @@
//
// 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 StartChatScreenViewModelType = StateStoreViewModel<StartChatScreenViewState, StartChatScreenViewAction>
class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenViewModelProtocol {
private let userSession: UserSessionProtocol
private let actionsSubject: PassthroughSubject<StartChatScreenViewModelAction, Never> = .init()
private let userDiscoveryService: UserDiscoveryServiceProtocol
var actions: AnyPublisher<StartChatScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
weak var userIndicatorController: UserIndicatorControllerProtocol?
init(userSession: UserSessionProtocol, userIndicatorController: UserIndicatorControllerProtocol?, userDiscoveryService: UserDiscoveryServiceProtocol) {
self.userSession = userSession
self.userIndicatorController = userIndicatorController
self.userDiscoveryService = userDiscoveryService
super.init(initialViewState: StartChatScreenViewState(), imageProvider: userSession.mediaProvider)
setupBindings()
}
// MARK: - Public
override func process(viewAction: StartChatScreenViewAction) {
switch viewAction {
case .close:
actionsSubject.send(.close)
case .createRoom:
actionsSubject.send(.createRoom)
case .inviteFriends:
break
case .selectUser(let user):
showLoadingIndicator()
Task {
let currentDirectRoom = await clientProxy.directRoomForUserID(user.userID)
switch currentDirectRoom {
case .success(.some(let roomId)):
self.hideLoadingIndicator()
self.actionsSubject.send(.openRoom(withIdentifier: roomId))
case .success(nil):
await self.createDirectRoom(with: user)
case .failure(let failure):
self.hideLoadingIndicator()
self.displayError(failure)
}
}
}
}
// MARK: - Private
private func displayError(_ type: ClientProxyError) {
switch type {
case .failedCreatingRoom, .failedRetrievingDirectRoom:
state.bindings.alertInfo = AlertInfo(id: .failedCreatingRoom,
title: L10n.commonError,
message: L10n.screenStartChatErrorStartingChat)
case .failedSearchingUsers:
state.bindings.alertInfo = AlertInfo(id: .unknown)
default:
break
}
}
private func setupBindings() {
context.$viewState
.map(\.bindings.searchQuery)
.debounceAndRemoveDuplicates()
.sink { [weak self] _ in
self?.fetchUsers()
}
.store(in: &cancellables)
}
@CancellableTask
private var fetchUsersTask: Task<Void, Never>?
private func fetchUsers() {
guard searchQuery.count >= 3 else {
fetchSuggestions()
return
}
fetchUsersTask = Task {
let result = await userDiscoveryService.searchProfiles(with: searchQuery)
guard !Task.isCancelled else { return }
handleResult(for: .searchResult, result: result)
}
}
private func fetchSuggestions() {
guard ServiceLocator.shared.settings.startChatUserSuggestionsEnabled else {
state.usersSection = .init(type: .suggestions, users: [])
return
}
fetchUsersTask = Task {
let result = await userDiscoveryService.fetchSuggestions()
guard !Task.isCancelled else { return }
handleResult(for: .suggestions, result: result)
}
}
private func handleResult(for sectionType: UserDiscoverySectionType, result: Result<[UserProfile], UserDiscoveryErrorType>) {
switch result {
case .success(let users):
state.usersSection = .init(type: sectionType, users: users)
case .failure:
break
}
}
private func createDirectRoom(with user: UserProfile) async {
showLoadingIndicator()
let result = await clientProxy.createDirectRoom(with: user.userID)
hideLoadingIndicator()
switch result {
case .success(let roomId):
actionsSubject.send(.openRoom(withIdentifier: roomId))
case .failure(let failure):
displayError(failure)
}
}
private var clientProxy: ClientProxyProtocol {
userSession.clientProxy
}
private var searchQuery: String {
context.searchQuery
}
// MARK: Loading indicator
static let loadingIndicatorIdentifier = "StartChatLoading"
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 StartChatScreenViewModelProtocol {
var actions: AnyPublisher<StartChatScreenViewModelAction, Never> { get }
var context: StartChatScreenViewModelType.Context { get }
}
@@ -0,0 +1,150 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct StartChatScreen: View {
@ObservedObject var context: StartChatScreenViewModel.Context
var body: some View {
Form {
if !context.viewState.isSearching {
mainContent
} else {
searchContent
}
}
.scrollContentBackground(.hidden)
.background(Color.element.formBackground.ignoresSafeArea())
.navigationTitle(L10n.actionStartChat)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
closeButton
}
}
.searchable(text: $context.searchQuery, placement: .navigationBarDrawer(displayMode: .always), prompt: L10n.commonSearchForSomeone)
.alert(item: $context.alertInfo) { $0.alert }
}
// MARK: - Private
/// The content shown in the form when the search query is empty.
@ViewBuilder
private var mainContent: some View {
createRoomSection
inviteFriendsSection
usersSection
}
/// The content shown in the form when a search query has been entered.
@ViewBuilder
private var searchContent: some View {
if context.viewState.hasEmptySearchResults {
noResultsContent
} else {
usersSection
}
}
private var createRoomSection: some View {
Section {
Button(action: createRoom) {
Label(L10n.actionCreateARoom, systemImage: "person.3")
}
.buttonStyle(FormButtonStyle(accessory: .navigationLink))
}
.formSectionStyle()
}
private var inviteFriendsSection: some View {
Section {
Button(action: inviteFriends) {
Label(L10n.actionInviteFriendsToApp(InfoPlistReader.main.bundleDisplayName), systemImage: "square.and.arrow.up")
}
.buttonStyle(FormButtonStyle())
.accessibilityIdentifier(A11yIdentifiers.startChatScreen.inviteFriends)
}
.formSectionStyle()
}
@ViewBuilder
private var usersSection: some View {
if !context.viewState.usersSection.users.isEmpty {
Section {
ForEach(context.viewState.usersSection.users, id: \.userID) { user in
Button { context.send(viewAction: .selectUser(user)) } label: {
UserProfileCell(user: user, imageProvider: context.imageProvider)
}
.buttonStyle(FormButtonStyle())
}
} header: {
if let title = context.viewState.usersSection.title {
Text(title)
}
}
.listRowSeparator(.automatic)
.formSectionStyle()
}
}
private var noResultsContent: some View {
Text(L10n.commonNoResults)
.font(.element.body)
.foregroundColor(.element.tertiaryContent)
.frame(maxWidth: .infinity)
.listRowBackground(Color.clear)
.accessibilityIdentifier(A11yIdentifiers.startChatScreen.searchNoResults)
}
private var closeButton: some View {
Button(L10n.actionCancel, action: close)
.accessibilityIdentifier(A11yIdentifiers.startChatScreen.closeStartChat)
}
private func createRoom() {
context.send(viewAction: .createRoom)
}
private func inviteFriends() {
context.send(viewAction: .inviteFriends)
}
private func close() {
context.send(viewAction: .close)
}
}
// MARK: - Previews
struct StartChatScreen_Previews: PreviewProvider {
static let viewModel = {
let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"),
mediaProvider: MockMediaProvider())
let userDiscoveryService = UserDiscoveryServiceMock()
userDiscoveryService.fetchSuggestionsReturnValue = .success([.mockAlice])
userDiscoveryService.searchProfilesWithReturnValue = .success([.mockAlice])
let viewModel = StartChatScreenViewModel(userSession: userSession, userIndicatorController: nil, userDiscoveryService: userDiscoveryService)
return viewModel
}()
static var previews: some View {
NavigationView {
StartChatScreen(context: viewModel.context)
.tint(.element.accent)
}
}
}