Join room by address (#3840)

* Implemented join room by address

* improved the text field typing

* some improvements to how the text is edited

* remove navigation link

* moved room directory search to the start chat flow

* updated preview tests

* added unit tests and improved the code

* updated strings

* some pr suggestions:

- moving the file
- changing the name of the action
- reintroduce the debounce text queries
- add comments

* renamed the auth text field style to Element

updated tests
This commit is contained in:
Mauro
2025-02-28 13:35:15 +01:00
committed by GitHub
parent 2b58f57483
commit 7f6ea1c2ae
54 changed files with 611 additions and 340 deletions
@@ -20,6 +20,7 @@ struct StartChatScreenCoordinatorParameters {
enum StartChatScreenCoordinatorAction {
case close
case openRoom(withIdentifier: String)
case openRoomDirectorySearch
}
final class StartChatScreenCoordinator: CoordinatorProtocol {
@@ -48,7 +49,8 @@ final class StartChatScreenCoordinator: CoordinatorProtocol {
viewModel = StartChatScreenViewModel(userSession: parameters.userSession,
analytics: ServiceLocator.shared.analytics,
userIndicatorController: parameters.userIndicatorController,
userDiscoveryService: parameters.userDiscoveryService)
userDiscoveryService: parameters.userDiscoveryService,
appSettings: ServiceLocator.shared.settings)
}
func start() {
@@ -60,8 +62,10 @@ final class StartChatScreenCoordinator: CoordinatorProtocol {
case .createRoom:
// before creating a room we select the users we would like to invite in that room
presentInviteUsersScreen()
case .openRoom(let identifier):
case .showRoom(let identifier):
actionsSubject.send(.openRoom(withIdentifier: identifier))
case .openRoomDirectorySearch:
actionsSubject.send(.openRoomDirectorySearch)
}
}
.store(in: &cancellables)
@@ -12,16 +12,18 @@ enum StartChatScreenErrorType: Error {
case unknown
}
enum StartChatScreenViewModelAction {
enum StartChatScreenViewModelAction: Equatable {
case close
case createRoom
case openRoom(withIdentifier: String)
case showRoom(withIdentifier: String)
case openRoomDirectorySearch
}
struct StartChatScreenViewState: BindableState {
let userID: String
var bindings = StartChatScreenViewStateBindings()
var usersSection: UserDiscoverySection = .init(type: .suggestions, users: [])
var isRoomDirectoryEnabled = false
var isSearching: Bool {
!bindings.searchQuery.isEmpty
@@ -30,15 +32,19 @@ struct StartChatScreenViewState: BindableState {
var hasEmptySearchResults: Bool {
isSearching && usersSection.type == .searchResult && usersSection.users.isEmpty
}
var joinByAddressState: JoinByAddressState = .example
}
struct StartChatScreenViewStateBindings {
var searchQuery = ""
var roomAddress = ""
/// Information describing the currently displayed alert.
var alertInfo: AlertInfo<StartChatScreenErrorType>?
var selectedUserToInvite: UserProfileProxy?
var isJoinRoomByAddressSheetPresented = false
}
enum StartChatScreenViewAction {
@@ -46,4 +52,13 @@ enum StartChatScreenViewAction {
case createRoom
case createDM(user: UserProfileProxy)
case selectUser(UserProfileProxy)
case joinRoomByAddress
case openRoomDirectorySearch
}
enum JoinByAddressState: Equatable {
case example
case invalidAddress
case addressNotFound
case addressFound(address: String, roomID: String)
}
@@ -6,6 +6,7 @@
//
import Combine
import MatrixRustSDK
import SwiftUI
typealias StartChatScreenViewModelType = StateStoreViewModel<StartChatScreenViewState, StartChatScreenViewAction>
@@ -15,6 +16,7 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
private let analytics: AnalyticsService
private let userIndicatorController: UserIndicatorControllerProtocol
private let userDiscoveryService: UserDiscoveryServiceProtocol
private let appSettings: AppSettings
private var suggestedUsers = [UserProfileProxy]()
@@ -26,11 +28,13 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
init(userSession: UserSessionProtocol,
analytics: AnalyticsService,
userIndicatorController: UserIndicatorControllerProtocol,
userDiscoveryService: UserDiscoveryServiceProtocol) {
userDiscoveryService: UserDiscoveryServiceProtocol,
appSettings: AppSettings) {
self.userSession = userSession
self.analytics = analytics
self.userIndicatorController = userIndicatorController
self.userDiscoveryService = userDiscoveryService
self.appSettings = appSettings
super.init(initialViewState: StartChatScreenViewState(userID: userSession.clientProxy.userID), mediaProvider: userSession.mediaProvider)
@@ -60,7 +64,7 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
switch currentDirectRoom {
case .success(.some(let roomId)):
hideLoadingIndicator()
actionsSubject.send(.openRoom(withIdentifier: roomId))
actionsSubject.send(.showRoom(withIdentifier: roomId))
case .success:
hideLoadingIndicator()
state.bindings.selectedUserToInvite = user
@@ -71,12 +75,24 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
}
case .createDM(let user):
Task { await createDirectRoom(user: user) }
case .joinRoomByAddress:
joinRoomByAddress()
case .openRoomDirectorySearch:
actionsSubject.send(.openRoomDirectorySearch)
}
}
// MARK: - Private
// periphery:ignore - auto cancels when reassigned
@CancellableTask private var resolveAliasTask: Task<Void, Never>?
private var internalRoomAddressState: JoinByAddressState = .example
private func setupBindings() {
appSettings.$publicSearchEnabled
.weakAssign(to: \.state.isRoomDirectoryEnabled, on: self)
.store(in: &cancellables)
context.$viewState
.map(\.bindings.searchQuery)
.debounceTextQueriesAndRemoveDuplicates()
@@ -84,6 +100,62 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
self?.fetchUsers()
}
.store(in: &cancellables)
context.$viewState
.map(\.bindings.roomAddress)
.removeDuplicates()
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self else {
return
}
state.joinByAddressState = .example
internalRoomAddressState = .example
}
.store(in: &cancellables)
context.$viewState
.map(\.bindings.roomAddress)
.debounceTextQueriesAndRemoveDuplicates()
.sink { [weak self] roomAddress in
guard let self else {
return
}
resolveRoomAddress(roomAddress)
}
.store(in: &cancellables)
}
private func resolveRoomAddress(_ roomAddress: String) {
guard !roomAddress.isEmpty,
isRoomAliasFormatValid(alias: roomAddress) else {
internalRoomAddressState = .invalidAddress
resolveAliasTask = nil
return
}
resolveAliasTask = Task { [weak self] in
guard let self else {
return
}
defer { resolveAliasTask = nil }
guard case let .success(resolved) = await userSession.clientProxy.resolveRoomAlias(roomAddress) else {
if Task.isCancelled {
return
}
internalRoomAddressState = .addressNotFound
return
}
guard !Task.isCancelled else {
return
}
let result = JoinByAddressState.addressFound(address: roomAddress, roomID: resolved.roomId)
internalRoomAddressState = result
state.joinByAddressState = result
}
}
// periphery:ignore - auto cancels when reassigned
@@ -118,7 +190,7 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
switch await userSession.clientProxy.createDirectRoom(with: user.userID, expectedRoomName: user.displayName) {
case .success(let roomId):
analytics.trackCreatedRoom(isDM: true)
actionsSubject.send(.openRoom(withIdentifier: roomId))
actionsSubject.send(.showRoom(withIdentifier: roomId))
case .failure:
displayError()
}
@@ -129,6 +201,28 @@ class StartChatScreenViewModel: StartChatScreenViewModelType, StartChatScreenVie
title: L10n.commonError,
message: L10n.screenStartChatErrorStartingChat)
}
private func joinRoomByAddress() {
if case let .addressFound(lastTestedAddress, roomID) = internalRoomAddressState,
lastTestedAddress == state.bindings.roomAddress {
actionsSubject.send(.showRoom(withIdentifier: roomID))
} else if let resolveAliasTask {
// If the task is still running we wait for it to complete and we check the state again
showLoadingIndicator(delay: .milliseconds(250))
Task {
await resolveAliasTask.value
hideLoadingIndicator()
joinRoomByAddress()
}
} else if internalRoomAddressState == .example {
// If we are in the example state internally, this means that the task has not started yet so we start it, and the check the state again
resolveRoomAddress(state.bindings.roomAddress)
joinRoomByAddress()
} else {
// In any other case we just use the internal state
state.joinByAddressState = internalRoomAddressState
}
}
// MARK: Loading indicator
@@ -0,0 +1,95 @@
//
// Copyright 2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
struct JoinRoomByAddressView: View {
@ObservedObject var context: StartChatScreenViewModel.Context
@Environment(\.dismiss) private var dismiss
@State private var sheetHeight: CGFloat = .zero
@FocusState private var textFieldFocus
private let topPadding: CGFloat = 22
private var footerText: String {
switch context.viewState.joinByAddressState {
case .example:
L10n.screenStartChatJoinRoomByAddressSupportingText
case .addressNotFound:
L10n.screenStartChatJoinRoomByAddressRoomNotFound
case .addressFound:
L10n.screenStartChatJoinRoomByAddressRoomFound
case .invalidAddress:
L10n.screenStartChatJoinRoomByAddressInvalidAddress
}
}
private var textFieldState: ElementTextFieldStyle.State {
switch context.viewState.joinByAddressState {
case .addressFound:
.success
case .example:
.default
case .addressNotFound, .invalidAddress:
.error
}
}
var body: some View {
ScrollView {
VStack(spacing: 24) {
TextField(L10n.screenStartChatJoinRoomByAddressPlaceholder,
text: $context.roomAddress)
.textFieldStyle(.element(labelText: L10n.screenStartChatJoinRoomByAddressAction,
footerText: footerText,
state: textFieldState))
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.textContentType(.URL)
.focused($textFieldFocus)
.onChange(of: context.roomAddress) { _, newValue in
context.roomAddress = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
}
Button(L10n.actionContinue) {
context.send(viewAction: .joinRoomByAddress)
}
.buttonStyle(.compound(.primary))
}
.padding(.horizontal, 16)
.readHeight($sheetHeight)
}
.scrollBounceBehavior(.basedOnSize)
.padding(.top, topPadding) // For the drag indicator
.presentationDetents([.height(sheetHeight + topPadding)])
.presentationDragIndicator(.visible)
.presentationBackground(.compound.bgCanvasDefault)
.onAppear {
textFieldFocus = true
}
}
}
struct JoinRoomByAddressView_Previews: PreviewProvider, TestablePreview {
static let viewModel = {
let userSession = UserSessionMock(.init(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com"))))
let userDiscoveryService = UserDiscoveryServiceMock()
userDiscoveryService.searchProfilesWithReturnValue = .success([.mockAlice])
let viewModel = StartChatScreenViewModel(userSession: userSession,
analytics: ServiceLocator.shared.analytics,
userIndicatorController: UserIndicatorControllerMock(),
userDiscoveryService: userDiscoveryService,
appSettings: ServiceLocator.shared.settings)
return viewModel
}()
static var previews: some View {
JoinRoomByAddressView(context: viewModel.context)
}
}
@@ -36,6 +36,11 @@ struct StartChatScreen: View {
context.send(viewAction: .createDM(user: user))
}
}
.sheet(isPresented: $context.isJoinRoomByAddressSheetPresented) {
context.roomAddress = ""
} content: {
JoinRoomByAddressView(context: context)
}
}
// MARK: - Private
@@ -44,10 +49,34 @@ struct StartChatScreen: View {
@ViewBuilder
private var mainContent: some View {
createRoomSection
if context.viewState.isRoomDirectoryEnabled {
roomDirectorySearch
}
inviteFriendsSection
joinRoomByAddressSection
usersSection
}
private var joinRoomByAddressSection: some View {
Section {
ListRow(label: .default(title: L10n.screenStartChatJoinRoomByAddressAction,
icon: \.room),
kind: .button {
context.isJoinRoomByAddressSheetPresented = true
})
}
}
private var roomDirectorySearch: some View {
Section {
ListRow(label: .default(title: L10n.screenRoomDirectorySearchTitle,
icon: \.listBulleted),
kind: .navigationLink {
context.send(viewAction: .openRoomDirectorySearch)
})
}
}
/// The content shown in the form when a search query has been entered.
@ViewBuilder
private var searchContent: some View {
@@ -125,13 +154,16 @@ struct StartChatScreen: View {
struct StartChatScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = {
let appSettings = AppSettings()
appSettings.publicSearchEnabled = true
let userSession = UserSessionMock(.init(clientProxy: ClientProxyMock(.init(userID: "@userid:example.com"))))
let userDiscoveryService = UserDiscoveryServiceMock()
userDiscoveryService.searchProfilesWithReturnValue = .success([.mockAlice])
let viewModel = StartChatScreenViewModel(userSession: userSession,
analytics: ServiceLocator.shared.analytics,
userIndicatorController: UserIndicatorControllerMock(),
userDiscoveryService: userDiscoveryService)
userDiscoveryService: userDiscoveryService,
appSettings: appSettings)
return viewModel
}()