Let members edit their profile and invite others (#12)

* Add HealthChat API and extended profile services

Expose OpenID tokens and homeserver credentials from the client proxy, and
add fork-only services for the HealthChat member directory backend
(api.healthchat.ch) plus a service that reads MSC4133 extended profile
fields directly from the homeserver. Groundwork for the members tab and
the profile screens.

Claude-Session: https://claude.ai/code/session_013qdTbAWsZj2quQzEkagXaS

* Show extended profile details on the profile screens

Add a UserProfileScreenHook that lets the fork inject an extra Form
section below the header of the user profile and room member details
screens. The HealthChat implementation loads the MSC4133 extended
profile fields and renders them with tappable phone/email/website
links, hiding the section entirely for profiles without any fields.

Strings live in a new fork-only HealthChat.strings table (de/en/fr,
generated as HealthChatL10n via SwiftGen) since Untranslated.strings
pins the English bundle.

Claude-Session: https://claude.ai/code/session_013qdTbAWsZj2quQzEkagXaS

* Add a member directory tab

Add a HomeTabsHook that lets the fork append an extra tab to the home
tab bar, and a HealthChat members flow behind it: a directory of all
approved members from the HealthChat API with server-side search,
pending-approval and error states, chat shortcuts and pushed member
profiles. Chats and calls are handed back to the session flow via the
hook's actions publisher.

Claude-Session: https://claude.ai/code/session_013qdTbAWsZj2quQzEkagXaS

* Let members edit their profile and invite others

Add a native profile editor for the HealthChat extended profile fields
(13 fields plus avatar, saved as a partial diff through the HealthChat
API so displayname derivation and Zitadel sync stay server-side), an
invitation sheet (email plus personal note) and a profile-completeness
hint on the member directory.

A new UserDetailsEditScreenHook lets the fork substitute the profile
editor behind the settings user row — the stock display-name editor
would let users edit a value the next profile update derives away.

Claude-Session: https://claude.ai/code/session_013qdTbAWsZj2quQzEkagXaS
This commit is contained in:
2026-09-22 17:04:37 +02:00
parent 93149f1cbd
commit b475cc7e9a
47 changed files with 1595 additions and 17 deletions
@@ -0,0 +1,88 @@
//
// Copyright 2026 Novaloop AG
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import SwiftUI
struct HealthChatProfileEditScreenCoordinatorParameters {
let orientationManager: OrientationManagerProtocol
let userSession: UserSessionProtocol
let apiService: HealthChatAPIServiceProtocol
let mediaUploadingPreprocessor: MediaUploadingPreprocessor
weak var navigationStackCoordinator: NavigationStackCoordinator?
let userIndicatorController: UserIndicatorControllerProtocol
}
final class HealthChatProfileEditScreenCoordinator: CoordinatorProtocol, UserDetailsEditCoordinatorProtocol {
private let parameters: HealthChatProfileEditScreenCoordinatorParameters
private let viewModel: HealthChatProfileEditScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<RoomDetailsEditScreenCoordinatorAction, Never> = .init()
var actions: AnyPublisher<RoomDetailsEditScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: HealthChatProfileEditScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = HealthChatProfileEditScreenViewModel(userSession: parameters.userSession,
apiService: parameters.apiService,
mediaUploadingPreprocessor: parameters.mediaUploadingPreprocessor,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actionsPublisher
.sink { [weak self] action in
guard let self else { return }
switch action {
case .dismiss:
actionsSubject.send(.dismiss)
case .displayCameraPicker:
displayMediaPickerWithMode(.init(source: .camera, selectionType: .single))
case .displayMediaPicker:
displayMediaPickerWithMode(.init(source: .photoLibrary, selectionType: .single))
case .displayFilePicker:
displayMediaPickerWithMode(.init(source: .documents(types: [.image]), selectionType: .single))
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(HealthChatProfileEditScreen(context: viewModel.context))
}
// MARK: Private
private func displayMediaPickerWithMode(_ mode: MediaPickerScreenMode) {
let stackCoordinator = NavigationStackCoordinator()
let mediaPickerCoordinator = MediaPickerScreenCoordinator(mode: mode,
userIndicatorController: parameters.userIndicatorController,
orientationManager: parameters.orientationManager) { [weak self] action in
guard let self else { return }
switch action {
case .cancel:
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
case .selectedMediaAtURLs(let urls):
guard urls.count == 1,
let url = urls.first else {
fatalError("Received an invalid number of URLs")
}
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
viewModel.didSelectMediaURL(url: url)
}
}
stackCoordinator.setRootCoordinator(mediaPickerCoordinator)
parameters.navigationStackCoordinator?.setSheetCoordinator(stackCoordinator)
}
}
@@ -0,0 +1,116 @@
//
// Copyright 2026 Novaloop AG
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Foundation
enum HealthChatProfileEditScreenViewModelAction {
case dismiss
case displayCameraPicker
case displayMediaPicker
case displayFilePicker
}
struct HealthChatProfileEditScreenViewState: BindableState {
var initialProfile: HealthChatMember?
var loadFailed = false
var canEditAvatar = false
var selectedAvatarURL: URL?
var localMedia: MediaInfo?
var bindings = HealthChatProfileEditScreenViewStateBindings()
var avatarDidChange: Bool {
localMedia != nil || selectedAvatarURL != initialProfile?.avatarURL
}
/// The changed text fields as a partial update, nil when nothing changed.
var fieldsUpdate: HealthChatProfileUpdate? {
guard let initialProfile else { return nil }
var update = HealthChatProfileUpdate()
// nil leaves a field unchanged server-side, an empty string clears it.
func diff(_ binding: String, _ initialValue: String?) -> String? {
let value = binding.trimmingCharacters(in: .whitespacesAndNewlines)
return value == (initialValue ?? "") ? nil : value
}
update.title = diff(bindings.title, initialProfile.title)
update.firstName = diff(bindings.firstName, initialProfile.firstName)
update.lastName = diff(bindings.lastName, initialProfile.lastName)
update.specialty = diff(bindings.specialty, initialProfile.specialty)
update.practiceName = diff(bindings.practiceName, initialProfile.practiceName)
update.businessCity = diff(bindings.businessCity, initialProfile.businessCity)
update.businessEmail = diff(bindings.businessEmail, initialProfile.businessEmail)
update.businessTel = diff(bindings.businessTel, initialProfile.businessTel)
update.furtherInfo = diff(bindings.furtherInfo, initialProfile.furtherInfo)
update.street = diff(bindings.street, initialProfile.street)
update.houseNumber = diff(bindings.houseNumber, initialProfile.houseNumber)
update.postalCode = diff(bindings.postalCode, initialProfile.postalCode)
update.website = diff(bindings.website, initialProfile.website)
return update == HealthChatProfileUpdate() ? nil : update
}
/// First name, last name, speciality, practice and city are required (web client parity).
var requiredFieldsAreValid: Bool {
let requiredFields = [bindings.firstName, bindings.lastName, bindings.specialty,
bindings.practiceName, bindings.businessCity]
guard requiredFields.allSatisfy({ !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) else {
return false
}
let website = bindings.website.trimmingCharacters(in: .whitespacesAndNewlines)
return website.isEmpty || URL(string: website) != nil
}
var canSave: Bool {
initialProfile != nil && requiredFieldsAreValid && (avatarDidChange || fieldsUpdate != nil)
}
var showDeleteImageAction: Bool {
localMedia != nil || selectedAvatarURL != nil
}
}
struct HealthChatProfileEditScreenViewStateBindings {
var title = ""
var firstName = ""
var lastName = ""
var specialty = ""
var practiceName = ""
var businessCity = ""
var businessEmail = ""
var businessTel = ""
var furtherInfo = ""
var street = ""
var houseNumber = ""
var postalCode = ""
var website = ""
var showMediaSheet = false
var alertInfo: AlertInfo<HealthChatProfileEditScreenAlertType>?
}
enum HealthChatProfileEditScreenAlertType {
case failedProcessingMedia
case unsavedChanges
case saveError
case unknown
}
enum HealthChatProfileEditScreenViewAction {
case cancel
case save
case retry
case presentMediaSource
case displayCameraPicker
case displayMediaPicker
case displayFilePicker
case removeImage
}
@@ -0,0 +1,158 @@
//
// Copyright 2026 Novaloop AG
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import SwiftUI
typealias HealthChatProfileEditScreenViewModelType = StateStoreViewModelV2<HealthChatProfileEditScreenViewState, HealthChatProfileEditScreenViewAction>
class HealthChatProfileEditScreenViewModel: HealthChatProfileEditScreenViewModelType, HealthChatProfileEditScreenViewModelProtocol {
private let clientProxy: ClientProxyProtocol
private let apiService: HealthChatAPIServiceProtocol
private let mediaUploadingPreprocessor: MediaUploadingPreprocessor
private let userIndicatorController: UserIndicatorControllerProtocol
private let actionsSubject: PassthroughSubject<HealthChatProfileEditScreenViewModelAction, Never> = .init()
var actionsPublisher: AnyPublisher<HealthChatProfileEditScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(userSession: UserSessionProtocol,
apiService: HealthChatAPIServiceProtocol,
mediaUploadingPreprocessor: MediaUploadingPreprocessor,
userIndicatorController: UserIndicatorControllerProtocol) {
clientProxy = userSession.clientProxy
self.apiService = apiService
self.mediaUploadingPreprocessor = mediaUploadingPreprocessor
self.userIndicatorController = userIndicatorController
super.init(initialViewState: HealthChatProfileEditScreenViewState(), mediaProvider: userSession.mediaProvider)
Task { await loadProfile() }
}
// MARK: - Public
override func process(viewAction: HealthChatProfileEditScreenViewAction) {
switch viewAction {
case .cancel:
showUnsavedChangesAlert() // The cancel button is only shown when there are unsaved changes.
case .save:
Task { await saveProfile() }
case .retry:
Task { await loadProfile() }
case .presentMediaSource:
state.bindings.showMediaSheet = true
case .displayCameraPicker:
actionsSubject.send(.displayCameraPicker)
case .displayMediaPicker:
actionsSubject.send(.displayMediaPicker)
case .displayFilePicker:
actionsSubject.send(.displayFilePicker)
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))
guard case let .success(maxUploadSize) = await clientProxy.maxMediaUploadSize else {
MXLog.error("Failed to get max upload size")
state.bindings.alertInfo = .init(id: .unknown)
return
}
let mediaResult = await mediaUploadingPreprocessor.processMedia(at: url, maxUploadSize: maxUploadSize)
switch mediaResult {
case .success(.image):
state.localMedia = try? mediaResult.get()
case .failure, .success:
state.bindings.alertInfo = .init(id: .failedProcessingMedia)
}
}
}
// MARK: - Private
private func loadProfile() async {
state.loadFailed = false
state.canEditAvatar = await clientProxy.capabilities.canChangeAvatar()
switch await apiService.ownProfile() {
case .success(let profile):
state.selectedAvatarURL = profile.avatarURL
state.bindings.title = profile.title ?? ""
state.bindings.firstName = profile.firstName ?? ""
state.bindings.lastName = profile.lastName ?? ""
state.bindings.specialty = profile.specialty ?? ""
state.bindings.practiceName = profile.practiceName ?? ""
state.bindings.businessCity = profile.businessCity ?? ""
state.bindings.businessEmail = profile.businessEmail ?? ""
state.bindings.businessTel = profile.businessTel ?? ""
state.bindings.furtherInfo = profile.furtherInfo ?? ""
state.bindings.street = profile.street ?? ""
state.bindings.houseNumber = profile.houseNumber ?? ""
state.bindings.postalCode = profile.postalCode ?? ""
state.bindings.website = profile.website ?? ""
state.initialProfile = profile
case .failure:
state.loadFailed = true
}
}
private func showUnsavedChangesAlert() {
state.bindings.alertInfo = .init(id: .unsavedChanges,
title: L10n.dialogUnsavedChangesTitle,
message: L10n.dialogUnsavedChangesDescription,
primaryButton: .init(title: L10n.actionSave) { Task { await self.saveProfile() } },
secondaryButton: .init(title: L10n.actionDiscard, role: .cancel) { self.actionsSubject.send(.dismiss) })
}
private func saveProfile() async {
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 {
if state.avatarDidChange {
try await saveAvatar()
}
// The fields go second so the derived display name reflects the latest names.
if let update = state.fieldsUpdate {
try await apiService.updateOwnProfile(update).get()
}
actionsSubject.send(.dismiss)
} catch {
MXLog.error("Failed saving the HealthChat profile with error: \(error)")
state.bindings.alertInfo = .init(id: .saveError,
title: L10n.screenEditProfileErrorTitle,
message: L10n.screenEditProfileError)
}
}
private func saveAvatar() async throws {
if let localMedia = state.localMedia {
try await clientProxy.setUserAvatar(media: localMedia).get()
} else if state.selectedAvatarURL == nil {
try await clientProxy.removeUserAvatar().get()
}
}
}
@@ -0,0 +1,17 @@
//
// Copyright 2026 Novaloop AG
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import Foundation
@MainActor
protocol HealthChatProfileEditScreenViewModelProtocol {
var actionsPublisher: AnyPublisher<HealthChatProfileEditScreenViewModelAction, Never> { get }
var context: HealthChatProfileEditScreenViewModelType.Context { get }
func didSelectMediaURL(url: URL)
}
@@ -0,0 +1,220 @@
//
// Copyright 2026 Novaloop AG
//
// 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 HealthChatProfileEditScreen: View {
@Bindable var context: HealthChatProfileEditScreenViewModel.Context
var body: some View {
content
.navigationTitle(L10n.screenEditProfileTitle)
.navigationBarTitleDisplayMode(.inline)
.navigationBarBackButtonHidden(context.viewState.canSave)
.toolbar { toolbar }
.alert(item: $context.alertInfo)
}
// MARK: - Private
@ViewBuilder
private var content: some View {
if context.viewState.loadFailed {
failureView
} else {
form
}
}
private var form: some View {
Form {
Section {
avatar
}
Section {
textFieldRow(HealthChatL10n.commonAcademicTitle, text: $context.title)
textFieldRow(requiredLabel(HealthChatL10n.commonFirstName), text: $context.firstName)
textFieldRow(requiredLabel(HealthChatL10n.commonLastName), text: $context.lastName)
} header: {
Text(HealthChatL10n.screenProfileEditSectionPersonal)
.compoundListSectionHeader()
}
Section {
textFieldRow(requiredLabel(HealthChatL10n.commonSpecialty), text: $context.specialty)
textFieldRow(requiredLabel(HealthChatL10n.commonPracticeName), text: $context.practiceName)
textFieldRow(requiredLabel(HealthChatL10n.commonCity), text: $context.businessCity)
textFieldRow(HealthChatL10n.commonFurtherInfo, text: $context.furtherInfo, axis: .vertical)
} header: {
Text(HealthChatL10n.screenProfileEditSectionProfessional)
.compoundListSectionHeader()
}
Section {
textFieldRow(HealthChatL10n.commonBusinessEmail, text: $context.businessEmail)
textFieldRow(HealthChatL10n.commonBusinessTel, text: $context.businessTel)
} header: {
Text(HealthChatL10n.screenProfileEditSectionContact)
.compoundListSectionHeader()
}
Section {
textFieldRow(HealthChatL10n.commonStreet, text: $context.street)
textFieldRow(HealthChatL10n.commonHouseNumber, text: $context.houseNumber)
textFieldRow(HealthChatL10n.commonPostalCode, text: $context.postalCode)
textFieldRow(HealthChatL10n.commonWebsite, text: $context.website)
} header: {
Text(HealthChatL10n.screenProfileEditSectionAddress)
.compoundListSectionHeader()
}
}
.compoundList()
.scrollDismissesKeyboard(.immediately)
.disabled(context.viewState.initialProfile == nil)
}
private var failureView: some View {
VStack(spacing: 16) {
BigIcon(icon: \.error)
Text(L10n.commonSomethingWentWrong)
.font(.compound.bodyLG)
.foregroundColor(.compound.textSecondary)
.multilineTextAlignment(.center)
Button(L10n.actionRetry) {
context.send(viewAction: .retry)
}
.buttonStyle(.compound(.secondary, size: .medium))
.fixedSize()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(16)
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
if context.viewState.canSave {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
}
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionSave) {
context.send(viewAction: .save)
}
.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.initialProfile?.displayName,
contentID: context.viewState.initialProfile?.userID ?? "",
shape: .circle,
avatarSize: .user(on: .editUserDetails),
mediaProvider: context.mediaProvider)
.confirmationDialog("", isPresented: $context.showMediaSheet) {
mediaActionSheet
}
}
.buttonStyle(EditAvatarButtonStyle())
.disabled(!context.viewState.canEditAvatar)
.frame(maxWidth: .infinity, alignment: .center)
.listRowBackground(Color.clear)
}
private func textFieldRow(_ label: String, text: Binding<String>, axis: Axis = .horizontal) -> some View {
ListRow(label: .plain(title: label),
kind: .textField(text: text, axis: axis))
}
private func requiredLabel(_ label: String) -> String {
"\(label) *"
}
@ViewBuilder
private var mediaActionSheet: some View {
Button {
context.send(viewAction: .displayCameraPicker)
} label: {
Text(L10n.actionTakePhoto)
}
Button {
context.send(viewAction: .displayMediaPicker)
} label: {
Text(L10n.actionChoosePhoto)
}
Button {
context.send(viewAction: .displayFilePicker)
} label: {
Text(L10n.actionChooseFile)
}
if context.viewState.showDeleteImageAction {
Button(role: .destructive) {
context.send(viewAction: .removeImage)
} label: {
Text(L10n.actionRemove)
}
}
}
}
// MARK: - Previews
struct HealthChatProfileEditScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = makeViewModel()
static var previews: some View {
ElementNavigationStack {
HealthChatProfileEditScreen(context: viewModel.context)
}
.snapshotPreferences(expect: viewModel.context.observe(\.viewState.initialProfile).map { $0 != nil })
.previewDisplayName("Profile")
}
static func makeViewModel() -> HealthChatProfileEditScreenViewModel {
let apiService = HealthChatAPIServiceMock()
let member = try? JSONDecoder().decode(HealthChatMember.self, from: Data("""
{
"userId": "@alice:healthchat.ch",
"displayName": "Dr. Alice Alpha",
"title": "Dr. med.",
"firstName": "Alice",
"lastName": "Alpha",
"specialty": "Physiotherapie",
"practiceName": "Praxis Alpha",
"businessCity": "Zürich",
"businessEmail": "praxis@example.ch",
"businessTel": "+41 44 123 45 67",
"street": "Friedaustrasse",
"houseNumber": "17",
"postalCode": "8003",
"website": "https://example.ch"
}
""".utf8))
if let member {
apiService.ownProfileReturnValue = .success(member)
}
return HealthChatProfileEditScreenViewModel(userSession: UserSessionMock(.init(clientProxy: ClientProxyMock(.init()))),
apiService: apiService,
mediaUploadingPreprocessor: MediaUploadingPreprocessor(appSettings: .volatile()),
userIndicatorController: UserIndicatorControllerMock())
}
}