Change user display name and avatar (#1718)

* Fixes #1715, #1716 - Add new user profile editing screen

* Bump SDK, adopt new `client.removeAvatar()` method

* Address PR review comments
This commit is contained in:
Stefan Ceriu
2023-09-15 16:20:33 +03:00
committed by GitHub
parent b3a0680d64
commit fe711a9a40
20 changed files with 700 additions and 69 deletions
@@ -0,0 +1,86 @@
//
// 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 UserDetailsEditScreenCoordinatorParameters {
let clientProxy: ClientProxyProtocol
let mediaProvider: MediaProviderProtocol
weak var navigationStackCoordinator: NavigationStackCoordinator?
weak var userIndicatorController: UserIndicatorControllerProtocol?
}
enum UserDetailsEditScreenCoordinatorAction { }
final class UserDetailsEditScreenCoordinator: CoordinatorProtocol {
private let parameters: UserDetailsEditScreenCoordinatorParameters
private var viewModel: UserDetailsEditScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<UserDetailsEditScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<UserDetailsEditScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: UserDetailsEditScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = UserDetailsEditScreenViewModel(clientProxy: parameters.clientProxy,
mediaProvider: parameters.mediaProvider,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actions
.sink { [weak self] action in
switch action {
case .displayCameraPicker:
self?.displayMediaPickerWithSource(.camera)
case .displayMediaPicker:
self?.displayMediaPickerWithSource(.photoLibrary)
case .displayFilePicker:
self?.displayMediaPickerWithSource(.documents)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(UserDetailsEditScreen(context: viewModel.context))
}
// MARK: Private
private func displayMediaPickerWithSource(_ source: MediaPickerScreenSource) {
let stackCoordinator = NavigationStackCoordinator()
let userIndicatorController = UserIndicatorController(rootCoordinator: stackCoordinator)
let mediaPickerCoordinator = MediaPickerScreenCoordinator(userIndicatorController: userIndicatorController, source: source) { [weak self] action in
guard let self else { return }
switch action {
case .cancel:
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
case .selectMediaAtURL(let url):
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
viewModel.didSelectMediaURL(url: url)
}
}
stackCoordinator.setRootCoordinator(mediaPickerCoordinator)
parameters.navigationStackCoordinator?.setSheetCoordinator(userIndicatorController)
}
}
@@ -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.
//
import Foundation
enum UserDetailsEditScreenViewModelAction {
case displayCameraPicker
case displayMediaPicker
case displayFilePicker
}
struct UserDetailsEditScreenViewState: BindableState {
let userID: String
var currentAvatarURL: URL?
var selectedAvatarURL: URL?
var currentDisplayName: String?
var localMedia: MediaInfo?
var bindings: UserDetailsEditScreenViewStateBindings
var nameDidChange: Bool {
bindings.name != currentDisplayName
}
/// The string shown for the room's name when it can't be edited.
var nameRowTitle: String {
bindings.name.isEmpty ? L10n.screenEditProfileDisplayName : bindings.name
}
var avatarDidChange: Bool {
localMedia != nil || selectedAvatarURL != currentAvatarURL
}
var canSave: Bool {
!bindings.name.isEmpty && (avatarDidChange || nameDidChange)
}
var showDeleteImageAction: Bool {
localMedia != nil || selectedAvatarURL != nil
}
}
struct UserDetailsEditScreenViewStateBindings {
var name = ""
var showMediaSheet = false
}
enum UserDetailsEditScreenViewAction {
case save
case presentMediaSource
case displayCameraPicker
case displayMediaPicker
case removeImage
}
@@ -0,0 +1,151 @@
//
// 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 UserDetailsEditScreenViewModelType = StateStoreViewModel<UserDetailsEditScreenViewState, UserDetailsEditScreenViewAction>
class UserDetailsEditScreenViewModel: UserDetailsEditScreenViewModelType, UserDetailsEditScreenViewModelProtocol {
private let actionsSubject: PassthroughSubject<UserDetailsEditScreenViewModelAction, Never> = .init()
private let clientProxy: ClientProxyProtocol
private weak var userIndicatorController: UserIndicatorControllerProtocol?
private let mediaPreprocessor: MediaUploadingPreprocessor = .init()
var actions: AnyPublisher<UserDetailsEditScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(clientProxy: ClientProxyProtocol,
mediaProvider: MediaProviderProtocol,
userIndicatorController: UserIndicatorControllerProtocol?) {
self.clientProxy = clientProxy
self.userIndicatorController = userIndicatorController
super.init(initialViewState: UserDetailsEditScreenViewState(userID: clientProxy.userID,
bindings: .init()), imageProvider: mediaProvider)
clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.currentAvatarURL, on: self)
.store(in: &cancellables)
clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.selectedAvatarURL, on: self)
.store(in: &cancellables)
clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.currentDisplayName, on: self)
.store(in: &cancellables)
clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.sink { [weak self] displayName in
guard let self else { return }
state.bindings.name = displayName ?? ""
}
.store(in: &cancellables)
Task {
await self.clientProxy.loadUserAvatarURL()
await self.clientProxy.loadUserDisplayName()
}
}
// MARK: - Public
override func process(viewAction: UserDetailsEditScreenViewAction) {
switch viewAction {
case .save:
saveUserDetails()
case .presentMediaSource:
state.bindings.showMediaSheet = true
case .displayCameraPicker:
actionsSubject.send(.displayCameraPicker)
case .displayMediaPicker:
actionsSubject.send(.displayMediaPicker)
case .removeImage:
state.localMedia = nil
state.selectedAvatarURL = nil
}
}
func didSelectMediaURL(url: URL) {
Task {
let userIndicatorID = UUID().uuidString
defer {
userIndicatorController?.retractIndicatorWithId(userIndicatorID)
}
userIndicatorController?.submitIndicator(UserIndicator(id: userIndicatorID,
type: .modal(progress: .indeterminate, interactiveDismissDisabled: true, allowsInteraction: false),
title: L10n.commonLoading,
persistent: true))
let mediaResult = await mediaPreprocessor.processMedia(at: url)
switch mediaResult {
case .success(.image):
state.localMedia = try? mediaResult.get()
case .failure, .success:
userIndicatorController?.alertInfo = .init(id: .init(), title: L10n.commonError, message: L10n.errorUnknown)
}
}
}
// MARK: - Private
private func saveUserDetails() {
Task {
let userIndicatorID = UUID().uuidString
defer {
userIndicatorController?.retractIndicatorWithId(userIndicatorID)
}
userIndicatorController?.submitIndicator(UserIndicator(id: userIndicatorID,
type: .modal(progress: .indeterminate, interactiveDismissDisabled: true, allowsInteraction: false),
title: L10n.screenEditProfileUpdatingDetails,
persistent: true))
do {
try await withThrowingTaskGroup(of: Void.self) { group in
if state.avatarDidChange {
group.addTask {
if let localMedia = await self.state.localMedia {
try await self.clientProxy.setUserAvatar(media: localMedia).get()
} else if await self.state.selectedAvatarURL == nil {
try await self.clientProxy.removeUserAvatar().get()
}
}
}
if state.nameDidChange {
group.addTask {
try await self.clientProxy.setUserDisplayName(self.state.bindings.name).get()
}
}
try await group.waitForAll()
}
} catch {
userIndicatorController?.alertInfo = .init(id: .init(),
title: L10n.screenEditProfileErrorTitle,
message: L10n.screenEditProfileError)
}
}
}
}
@@ -0,0 +1,26 @@
//
// 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 Foundation
@MainActor
protocol UserDetailsEditScreenViewModelProtocol {
var actions: AnyPublisher<UserDetailsEditScreenViewModelAction, Never> { get }
var context: UserDetailsEditScreenViewModelType.Context { get }
func didSelectMediaURL(url: URL)
}
@@ -0,0 +1,129 @@
//
// 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 UserDetailsEditScreen: View {
@ObservedObject var context: UserDetailsEditScreenViewModel.Context
@FocusState private var focus: Bool
var body: some View {
Form {
avatar
nameSection
}
.compoundList()
.scrollDismissesKeyboard(.immediately)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
}
// MARK: - Private
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionSave) {
context.send(viewAction: .save)
focus = false
}
.disabled(!context.viewState.canSave)
}
}
private var avatar: some View {
Button {
context.send(viewAction: .presentMediaSource)
} label: {
OverridableAvatarImage(overrideURL: context.viewState.localMedia?.thumbnailURL,
url: context.viewState.selectedAvatarURL,
name: context.viewState.currentDisplayName,
contentID: context.viewState.userID,
avatarSize: .user(on: .memberDetails),
imageProvider: context.imageProvider)
.overlay(alignment: .bottomTrailing) {
avatarOverlayIcon
}
.confirmationDialog("", isPresented: $context.showMediaSheet) {
mediaActionSheet
}
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .center)
.listRowBackground(Color.clear)
}
private var nameSection: some View {
Section {
ListRow(label: .plain(title: L10n.screenEditProfileDisplayNamePlaceholder),
kind: .textField(text: $context.name, axis: .horizontal))
.focused($focus)
} header: {
Text(L10n.screenEditProfileDisplayName)
.compoundListSectionHeader()
}
}
private var avatarOverlayIcon: some View {
Image(systemName: "camera")
.font(.system(size: 14, weight: .semibold))
.padding(3)
.imageScale(.small)
.foregroundColor(.white)
.background {
Circle()
.foregroundColor(.black)
.aspectRatio(1, contentMode: .fill)
}
}
@ViewBuilder
private var mediaActionSheet: some View {
Button {
context.send(viewAction: .displayCameraPicker)
} label: {
Text(L10n.actionTakePhoto)
}
Button {
context.send(viewAction: .displayMediaPicker)
} label: {
Text(L10n.actionChoosePhoto)
}
if context.viewState.showDeleteImageAction {
Button(role: .destructive) {
context.send(viewAction: .removeImage)
} label: {
Text(L10n.actionRemove)
}
}
}
}
// MARK: - Previews
struct UserDetailsEditScreen_Previews: PreviewProvider {
static let viewModel = UserDetailsEditScreenViewModel(clientProxy: MockClientProxy(userID: "@stefan:matrix.org"),
mediaProvider: MockMediaProvider(),
userIndicatorController: UserIndicatorControllerMock.default)
static var previews: some View {
NavigationStack {
UserDetailsEditScreen(context: viewModel.context)
}
}
}