mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-04 19:44:05 +00:00
Move search users into a dedicated service (#789)
* add users provider with test * add ui test for search users * add changelog * Update ElementX/Sources/Services/Users/UsersProvider.swift Co-authored-by: Alfonso Grillo <alfogrillo@gmail.com> * add error handling in usersprovider * remove empty section * add search in invite users * add CancellableTask, add setup App Settings in UnitTest, screenshots * rename of UserDiscoveryService * Update ElementX/Sources/Other/Extensions/Publisher.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * new error management for User Discovery Service * Update ElementX/Sources/Other/CancellableTask.swift Co-authored-by: Alfonso Grillo <alfogrillo@gmail.com> * Update ElementX/Sources/Services/Users/UserDiscoveryService.swift Co-authored-by: Alfonso Grillo <alfogrillo@gmail.com> * fix invite users and start chat errors * use only one task to fetch user profile --------- Co-authored-by: Alfonso Grillo <alfogrillo@gmail.com> Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com>
This commit is contained in:
@@ -19,6 +19,7 @@ import SwiftUI
|
||||
|
||||
struct InviteUsersCoordinatorParameters {
|
||||
let userSession: UserSessionProtocol
|
||||
let userDiscoveryService: UserDiscoveryServiceProtocol
|
||||
}
|
||||
|
||||
enum InviteUsersCoordinatorAction {
|
||||
@@ -38,7 +39,7 @@ final class InviteUsersCoordinator: CoordinatorProtocol {
|
||||
init(parameters: InviteUsersCoordinatorParameters) {
|
||||
self.parameters = parameters
|
||||
|
||||
viewModel = InviteUsersViewModel(userSession: parameters.userSession)
|
||||
viewModel = InviteUsersViewModel(userSession: parameters.userSession, userDiscoveryService: parameters.userDiscoveryService)
|
||||
}
|
||||
|
||||
func start() {
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
enum InviteUsersErrorType: Error {
|
||||
case unknown
|
||||
}
|
||||
|
||||
enum InviteUsersViewModelAction {
|
||||
case close
|
||||
}
|
||||
@@ -23,7 +27,7 @@ enum InviteUsersViewModelAction {
|
||||
struct InviteUsersViewState: BindableState {
|
||||
var bindings = InviteUsersViewStateBindings()
|
||||
|
||||
var usersSection: SearchUsersSection = .init(type: .empty, users: [])
|
||||
var usersSection: UserDiscoverySection = .init(type: .suggestions, users: [])
|
||||
var selectedUsers: [UserProfile] = []
|
||||
|
||||
var isSearching: Bool {
|
||||
@@ -45,7 +49,7 @@ struct InviteUsersViewStateBindings {
|
||||
var searchQuery = ""
|
||||
|
||||
/// Information describing the currently displayed alert.
|
||||
var alertInfo: AlertInfo<ClientProxyError>?
|
||||
var alertInfo: AlertInfo<InviteUsersErrorType>?
|
||||
}
|
||||
|
||||
enum InviteUsersViewAction {
|
||||
|
||||
@@ -21,17 +21,19 @@ typealias InviteUsersViewModelType = StateStoreViewModel<InviteUsersViewState, I
|
||||
|
||||
class InviteUsersViewModel: InviteUsersViewModelType, InviteUsersViewModelProtocol {
|
||||
private let userSession: UserSessionProtocol
|
||||
private let userDiscoveryService: UserDiscoveryServiceProtocol
|
||||
private let actionsSubject: PassthroughSubject<InviteUsersViewModelAction, Never> = .init()
|
||||
|
||||
var actions: AnyPublisher<InviteUsersViewModelAction, Never> {
|
||||
actionsSubject.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
init(userSession: UserSessionProtocol) {
|
||||
init(userSession: UserSessionProtocol, userDiscoveryService: UserDiscoveryServiceProtocol) {
|
||||
self.userSession = userSession
|
||||
self.userDiscoveryService = userDiscoveryService
|
||||
super.init(initialViewState: InviteUsersViewState(), imageProvider: userSession.mediaProvider)
|
||||
|
||||
fetchSuggestions()
|
||||
setupSubscriptions()
|
||||
}
|
||||
|
||||
// MARK: - Public
|
||||
@@ -65,11 +67,53 @@ class InviteUsersViewModel: InviteUsersViewModelType, InviteUsersViewModelProtoc
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func fetchSuggestions() {
|
||||
guard ServiceLocator.shared.settings.startChatUserSuggestionsEnabled else {
|
||||
state.usersSection = .init(type: .empty, users: [])
|
||||
private func setupSubscriptions() {
|
||||
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
|
||||
}
|
||||
state.usersSection = .init(type: .suggestions, users: [.mockAlice, .mockBob, .mockCharlie])
|
||||
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 var searchQuery: String {
|
||||
context.searchQuery
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +44,10 @@ struct InviteUsersScreen: View {
|
||||
/// 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 {
|
||||
Form {
|
||||
Form {
|
||||
if context.viewState.hasEmptySearchResults {
|
||||
noResultsContent
|
||||
} else {
|
||||
usersSection
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ struct InviteUsersScreen: View {
|
||||
.buttonStyle(FormButtonStyle(accessory: .selection(isSelected: context.viewState.isUserSelected(user))))
|
||||
}
|
||||
} header: {
|
||||
if let title = context.viewState.usersSection.type.title {
|
||||
if let title = context.viewState.usersSection.title {
|
||||
Text(title)
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,10 @@ struct InviteUsersScreen_Previews: PreviewProvider {
|
||||
static let viewModel = {
|
||||
let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"),
|
||||
mediaProvider: MockMediaProvider())
|
||||
return InviteUsersViewModel(userSession: userSession)
|
||||
let userDiscoveryService = UserDiscoveryServiceMock()
|
||||
userDiscoveryService.fetchSuggestionsReturnValue = .success([.mockAlice])
|
||||
userDiscoveryService.searchProfilesWithReturnValue = .success([.mockAlice])
|
||||
return InviteUsersViewModel(userSession: userSession, userDiscoveryService: userDiscoveryService)
|
||||
}()
|
||||
|
||||
static var previews: some View {
|
||||
|
||||
@@ -21,6 +21,7 @@ struct StartChatCoordinatorParameters {
|
||||
let userSession: UserSessionProtocol
|
||||
weak var userIndicatorController: UserIndicatorControllerProtocol?
|
||||
let navigationStackCoordinator: NavigationStackCoordinator?
|
||||
let userDiscoveryService: UserDiscoveryServiceProtocol
|
||||
}
|
||||
|
||||
enum StartChatCoordinatorAction {
|
||||
@@ -41,7 +42,7 @@ final class StartChatCoordinator: CoordinatorProtocol {
|
||||
init(parameters: StartChatCoordinatorParameters) {
|
||||
self.parameters = parameters
|
||||
|
||||
viewModel = StartChatViewModel(userSession: parameters.userSession, userIndicatorController: parameters.userIndicatorController)
|
||||
viewModel = StartChatViewModel(userSession: parameters.userSession, userIndicatorController: parameters.userIndicatorController, userDiscoveryService: parameters.userDiscoveryService)
|
||||
}
|
||||
|
||||
func start() {
|
||||
@@ -69,7 +70,7 @@ final class StartChatCoordinator: CoordinatorProtocol {
|
||||
// MARK: - Private
|
||||
|
||||
private func presentInviteUsersScreen() {
|
||||
let inviteParameters = InviteUsersCoordinatorParameters(userSession: parameters.userSession)
|
||||
let inviteParameters = InviteUsersCoordinatorParameters(userSession: parameters.userSession, userDiscoveryService: parameters.userDiscoveryService)
|
||||
let coordinator = InviteUsersCoordinator(parameters: inviteParameters)
|
||||
coordinator.actions.sink { [weak self] result in
|
||||
switch result {
|
||||
|
||||
@@ -16,6 +16,11 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
enum StartChatErrorType: Error {
|
||||
case failedCreatingRoom
|
||||
case unknown
|
||||
}
|
||||
|
||||
enum StartChatViewModelAction {
|
||||
case close
|
||||
case createRoom
|
||||
@@ -24,7 +29,7 @@ enum StartChatViewModelAction {
|
||||
|
||||
struct StartChatViewState: BindableState {
|
||||
var bindings = StartChatScreenViewStateBindings()
|
||||
var usersSection: SearchUsersSection = .init(type: .empty, users: [])
|
||||
var usersSection: UserDiscoverySection = .init(type: .suggestions, users: [])
|
||||
|
||||
var isSearching: Bool {
|
||||
!bindings.searchQuery.isEmpty
|
||||
@@ -39,7 +44,7 @@ struct StartChatScreenViewStateBindings {
|
||||
var searchQuery = ""
|
||||
|
||||
/// Information describing the currently displayed alert.
|
||||
var alertInfo: AlertInfo<ClientProxyError>?
|
||||
var alertInfo: AlertInfo<StartChatErrorType>?
|
||||
}
|
||||
|
||||
enum StartChatViewAction {
|
||||
|
||||
@@ -22,6 +22,7 @@ typealias StartChatViewModelType = StateStoreViewModel<StartChatViewState, Start
|
||||
class StartChatViewModel: StartChatViewModelType, StartChatViewModelProtocol {
|
||||
private let userSession: UserSessionProtocol
|
||||
private let actionsSubject: PassthroughSubject<StartChatViewModelAction, Never> = .init()
|
||||
private let userDiscoveryService: UserDiscoveryServiceProtocol
|
||||
|
||||
var actions: AnyPublisher<StartChatViewModelAction, Never> {
|
||||
actionsSubject.eraseToAnyPublisher()
|
||||
@@ -29,13 +30,13 @@ class StartChatViewModel: StartChatViewModelType, StartChatViewModelProtocol {
|
||||
|
||||
weak var userIndicatorController: UserIndicatorControllerProtocol?
|
||||
|
||||
init(userSession: UserSessionProtocol, userIndicatorController: UserIndicatorControllerProtocol?) {
|
||||
init(userSession: UserSessionProtocol, userIndicatorController: UserIndicatorControllerProtocol?, userDiscoveryService: UserDiscoveryServiceProtocol) {
|
||||
self.userSession = userSession
|
||||
self.userIndicatorController = userIndicatorController
|
||||
self.userDiscoveryService = userDiscoveryService
|
||||
super.init(initialViewState: StartChatViewState(), imageProvider: userSession.mediaProvider)
|
||||
|
||||
setupBindings()
|
||||
fetchSuggestions()
|
||||
}
|
||||
|
||||
// MARK: - Public
|
||||
@@ -70,87 +71,61 @@ class StartChatViewModel: StartChatViewModelType, StartChatViewModelProtocol {
|
||||
|
||||
private func displayError(_ type: ClientProxyError) {
|
||||
switch type {
|
||||
case .failedRetrievingDirectRoom:
|
||||
state.bindings.alertInfo = AlertInfo(id: type,
|
||||
title: L10n.commonError,
|
||||
message: L10n.screenStartChatErrorStartingChat)
|
||||
case .failedCreatingRoom:
|
||||
state.bindings.alertInfo = AlertInfo(id: 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:
|
||||
state.bindings.alertInfo = AlertInfo(id: type)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func setupBindings() {
|
||||
context.$viewState
|
||||
.map(\.bindings.searchQuery)
|
||||
.map { query in
|
||||
// debounce search queries but make sure clearing the search updates immediately
|
||||
let milliseconds = query.isEmpty ? 0 : 500
|
||||
return Just(query).delay(for: .milliseconds(milliseconds), scheduler: DispatchQueue.main)
|
||||
}
|
||||
.switchToLatest()
|
||||
.removeDuplicates()
|
||||
.debounceAndRemoveDuplicates()
|
||||
.sink { [weak self] _ in
|
||||
self?.fetchData()
|
||||
self?.fetchUsers()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
private func fetchData() {
|
||||
@CancellableTask
|
||||
private var fetchUsersTask: Task<Void, Never>?
|
||||
|
||||
private func fetchUsers() {
|
||||
guard searchQuery.count >= 3 else {
|
||||
fetchSuggestions()
|
||||
return
|
||||
}
|
||||
|
||||
Task {
|
||||
await searchProfiles()
|
||||
fetchUsersTask = Task {
|
||||
let result = await userDiscoveryService.searchProfiles(with: searchQuery)
|
||||
guard !Task.isCancelled else { return }
|
||||
handleResult(for: .searchResult, result: result)
|
||||
}
|
||||
}
|
||||
|
||||
private func searchProfiles() async {
|
||||
// copies the current query to check later if fetched data must be shown or not
|
||||
let committedQuery = searchQuery
|
||||
|
||||
async let queriedProfile = getProfileIfPossible()
|
||||
async let searchedUsers = clientProxy.searchUsers(searchTerm: committedQuery, limit: 5)
|
||||
|
||||
await updateState(committedQuery: committedQuery,
|
||||
queriedProfile: queriedProfile,
|
||||
searchResults: try? searchedUsers.get())
|
||||
}
|
||||
|
||||
private func updateState(committedQuery: String, queriedProfile: UserProfile?, searchResults: SearchUsersResults?) {
|
||||
guard committedQuery == searchQuery else {
|
||||
return
|
||||
}
|
||||
|
||||
let localProfile = queriedProfile ?? UserProfile(searchQuery: searchQuery)
|
||||
let allResults = merge(localProfile: localProfile, searchResults: searchResults?.results)
|
||||
|
||||
state.usersSection = .init(type: .searchResult, users: allResults)
|
||||
}
|
||||
|
||||
private func merge(localProfile: UserProfile?, searchResults: [UserProfile]?) -> [UserProfile] {
|
||||
guard let localProfile else {
|
||||
return searchResults ?? []
|
||||
}
|
||||
|
||||
let filteredSearchResult = searchResults?.filter {
|
||||
$0.userID != localProfile.userID
|
||||
} ?? []
|
||||
|
||||
return [localProfile] + filteredSearchResult
|
||||
}
|
||||
|
||||
private func fetchSuggestions() {
|
||||
guard ServiceLocator.shared.settings.startChatUserSuggestionsEnabled else {
|
||||
state.usersSection = .init(type: .empty, users: [])
|
||||
state.usersSection = .init(type: .suggestions, users: [])
|
||||
return
|
||||
}
|
||||
state.usersSection = .init(type: .suggestions, users: [.mockAlice, .mockBob, .mockCharlie])
|
||||
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 {
|
||||
@@ -165,14 +140,6 @@ class StartChatViewModel: StartChatViewModelType, StartChatViewModelProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
private func getProfileIfPossible() async -> UserProfile? {
|
||||
guard searchQuery.isMatrixIdentifier else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return try? await clientProxy.getProfile(for: searchQuery).get()
|
||||
}
|
||||
|
||||
private var clientProxy: ClientProxyProtocol {
|
||||
userSession.clientProxy
|
||||
}
|
||||
@@ -196,18 +163,3 @@ class StartChatViewModel: StartChatViewModelType, StartChatViewModelProtocol {
|
||||
userIndicatorController?.retractIndicatorWithId(Self.loadingIndicatorIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
private extension String {
|
||||
var isMatrixIdentifier: Bool {
|
||||
MatrixEntityRegex.isMatrixUserIdentifier(self)
|
||||
}
|
||||
}
|
||||
|
||||
private extension UserProfile {
|
||||
init?(searchQuery: String) {
|
||||
guard searchQuery.isMatrixIdentifier else {
|
||||
return nil
|
||||
}
|
||||
self.init(userID: searchQuery)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ struct StartChatScreen: View {
|
||||
.buttonStyle(FormButtonStyle())
|
||||
}
|
||||
} header: {
|
||||
if let title = context.viewState.usersSection.type.title {
|
||||
if let title = context.viewState.usersSection.title {
|
||||
Text(title)
|
||||
}
|
||||
}
|
||||
@@ -131,12 +131,19 @@ struct StartChatScreen: View {
|
||||
// MARK: - Previews
|
||||
|
||||
struct StartChat_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
static let viewModel = {
|
||||
let userSession = MockUserSession(clientProxy: MockClientProxy(userID: "@userid:example.com"),
|
||||
mediaProvider: MockMediaProvider())
|
||||
let regularViewModel = StartChatViewModel(userSession: userSession, userIndicatorController: nil)
|
||||
let userDiscoveryService = UserDiscoveryServiceMock()
|
||||
userDiscoveryService.fetchSuggestionsReturnValue = .success([.mockAlice])
|
||||
userDiscoveryService.searchProfilesWithReturnValue = .success([.mockAlice])
|
||||
let viewModel = StartChatViewModel(userSession: userSession, userIndicatorController: nil, userDiscoveryService: userDiscoveryService)
|
||||
return viewModel
|
||||
}()
|
||||
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
StartChatScreen(context: regularViewModel.context)
|
||||
StartChatScreen(context: viewModel.context)
|
||||
.tint(.element.accent)
|
||||
}
|
||||
}
|
||||
|
||||
+10
-11
@@ -16,22 +16,21 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
struct SearchUsersSection {
|
||||
let type: SearchUserSectionType
|
||||
struct UserDiscoverySection {
|
||||
let type: UserDiscoverySectionType
|
||||
let users: [UserProfile]
|
||||
}
|
||||
|
||||
enum SearchUserSectionType: Equatable {
|
||||
case searchResult
|
||||
case suggestions
|
||||
case empty
|
||||
|
||||
var title: String? {
|
||||
switch self {
|
||||
case .searchResult, .empty:
|
||||
switch type {
|
||||
case .searchResult:
|
||||
return nil
|
||||
case .suggestions:
|
||||
return L10n.commonSuggestions
|
||||
return users.isEmpty ? nil : L10n.commonSuggestions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum UserDiscoverySectionType: Equatable {
|
||||
case searchResult
|
||||
case suggestions
|
||||
}
|
||||
Reference in New Issue
Block a user