SPB Git

Repository Public

AccountPanes.swift 20.3 KB 363 lines swift

1import MCCCore2import SwiftUI3import UserNotifications45struct ProfilePane: View {6    @Environment(AppModel.self) private var app7    @Environment(\.mccTheme) private var theme8    @State private var name = ""9    @State private var deviceLabel = DeviceInfo.storedLabel()10    @State private var savedLabel = false1112    var body: some View {13        @Bindable var app = app14        SettingsPaneContainer(pane: .profile) {15            DetailSection(title: tr("settings.profile.identity")) {16                if let user = app.session.user {17                    KeyValueRow(tr("settings.profile.handle"), user.handle, monospaced: true)18                    KeyValueRow(tr("settings.profile.role"), user.role.label)19                    HStack {20                        TextField(tr("settings.profile.display_name"), text: $name)21                            .textFieldStyle(.roundedBorder)22                            .accessibilityIdentifier("profile-name")23                        Button(tr("action.save")) {24                            Task { await app.perform { try await app.session.account.updateProfile(displayName: name.trimmingCharacters(in: .whitespaces)) } }25                        }26                        .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || name == user.displayName)27                        .mutation(app)28                    }29                }30            }31            DetailSection(title: tr("settings.profile.interface")) {32                Picker(tr("settings.profile.language"), selection: Binding(get: { Localization.shared.language }, set: { setLanguage($0) })) {33                    ForEach(AppLanguage.allCases) { Text($0.endonym).tag($0) }34                }35                .pickerStyle(.segmented)36                .fixedSize()37                .accessibilityIdentifier("language-picker")38                Text(tr("settings.profile.language.help")).font(.caption).foregroundStyle(theme.textTertiary)39                Picker(tr("settings.profile.appearance"), selection: $app.appearance) {40                    ForEach(AppearancePreference.allCases) { Text($0.title).tag($0) }41                }42                .pickerStyle(.segmented)43                .fixedSize()44                .accessibilityIdentifier("appearance-picker")45            }46            DetailSection(title: tr("settings.profile.device")) {47                HStack {48                    TextField(tr("settings.profile.device_label"), text: $deviceLabel)49                        .textFieldStyle(.roundedBorder)50                    Button(tr("action.save")) {51                        DeviceInfo.setStoredLabel(deviceLabel)52                        deviceLabel = DeviceInfo.storedLabel()53                        savedLabel = true54                    }55                    .disabled(deviceLabel.trimmingCharacters(in: .whitespaces).isEmpty)56                }57                Text(savedLabel ? tr("settings.profile.device_label.saved") : tr("settings.profile.device_label.help"))58                    .font(.caption).foregroundStyle(theme.textTertiary)59            }60            DetailSection(title: tr("settings.profile.permissions")) {61                Text(tr("settings.profile.permissions.help")).font(.caption).foregroundStyle(theme.textTertiary)62                let perms = app.session.permissions.sorted()63                if perms.isEmpty {64                    Text(tr("settings.profile.permissions.none")).font(.callout).foregroundStyle(theme.textSecondary)65                } else {66                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 190), alignment: .leading)], alignment: .leading, spacing: Tokens.Space.s2) {67                        ForEach(perms, id: \.self) { Text($0).font(.callout.monospaced()).foregroundStyle(theme.textPrimary) }68                    }69                    .accessibilityElement(children: .combine)70                    .accessibilityLabel(tr("settings.profile.permissions"))71                    .accessibilityValue(perms.joined(separator: ", "))72                }73            }74        }75        .onAppear { name = app.session.user?.displayName ?? "" }76    }7778    private func setLanguage(_ language: AppLanguage) {79        Localization.shared.select(language)      // live: every view reading tr(...) re-renders80        guard app.session.canMutate else { return }81        Task { _ = try? await app.session.account.updateProfile(locale: language) }82    }83}8485struct PasskeysPane: View {86    @Environment(AppModel.self) private var app87    @Environment(\.mccTheme) private var theme88    @State private var newLabel = DeviceInfo.storedLabel()89    @State private var working = false90    @State private var renaming: API.Passkey?91    @State private var renameText = ""92    @State private var deleting: API.Passkey?9394    var body: some View {95        let account = app.session.account96        SettingsPaneContainer(pane: .passkeys, subtitle: tr("settings.passkeys.subtitle")) {97            DetailSection(title: tr("settings.passkeys.add.title")) {98                HStack {99                    TextField(tr("settings.passkeys.label"), text: $newLabel).textFieldStyle(.roundedBorder)100                    Button {101                        Task {102                            working = true103                            await app.perform { _ = try await account.addPasskey(label: newLabel.trimmingCharacters(in: .whitespaces).isEmpty ? nil : newLabel) }104                            working = false105                        }106                    } label: { Label(tr("settings.passkeys.add"), systemImage: "plus") }107                        .disabled(working)108                        .mutation(app)109                        .accessibilityIdentifier("passkey-add")110                    if working { ProgressView().controlSize(.small) }111                }112                Text(tr("settings.passkeys.add.help")).font(.caption).foregroundStyle(theme.textTertiary)113            }114            ResourceView(account.passkeys) { keys in115                VStack(spacing: Tokens.Space.s3) {116                    ForEach(keys, id: \.id) { key in row(key) }117                }118            }119        }120        .task { await account.passkeys.load() }121        .alert(tr("settings.passkeys.rename"), isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), presenting: renaming) { key in122            TextField(tr("settings.passkeys.label"), text: $renameText)123            Button(tr("action.save")) {124                let label = renameText.trimmingCharacters(in: .whitespaces)125                guard !label.isEmpty else { return }126                Task { await app.perform { try await account.renamePasskey(id: key.id, label: label) } }127            }128            Button(tr("action.cancel"), role: .cancel) {}129        }130        .confirmationDialog(tr("settings.passkeys.delete.title"), isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), presenting: deleting) { key in131            Button(tr("settings.passkeys.delete.confirm"), role: .destructive) {132                Task { await app.perform { try await account.deletePasskey(id: key.id) } }133            }134            Button(tr("action.cancel"), role: .cancel) {}135        } message: { key in136            Text(tr("settings.passkeys.delete.message", key.label))137        }138    }139140    private func row(_ key: API.Passkey) -> some View {141        Card {142            HStack(alignment: .top, spacing: Tokens.Space.s4) {143                Image(systemName: "key.fill").foregroundStyle(theme.textSecondary).accessibilityHidden(true)144                VStack(alignment: .leading, spacing: Tokens.Space.s1) {145                    HStack(spacing: Tokens.Space.s3) {146                        Text(key.label.isEmpty ? tr("settings.passkeys.unnamed") : key.label).font(.headline).foregroundStyle(theme.textPrimary)147                        if key.revokedAt != nil { StatusBadge(tr("settings.revoked"), tone: .offline, compact: true) }148                        if key.backupEligible {149                            StatusBadge(key.backupState ? tr("settings.passkeys.synced") : tr("settings.passkeys.syncable"), tone: key.backupState ? .info : .neutral, compact: true)150                        } else {151                            StatusBadge(tr("settings.passkeys.device_bound"), tone: .neutral, compact: true)152                        }153                    }154                    Text(tr("settings.passkeys.created", settingsDate(key.createdAt)) + " · "155                         + (key.lastUsedAt.map { tr("settings.passkeys.last_used", Format.relative($0)) } ?? tr("settings.passkeys.never_used")))156                        .font(.caption).foregroundStyle(theme.textSecondary)157                    if !key.transports.isEmpty {158                        Text(tr("settings.passkeys.transports", key.transports.joined(separator: ", "))).font(.caption).foregroundStyle(theme.textTertiary)159                    }160                }161                Spacer()162                if key.revokedAt == nil {163                    Button(tr("settings.passkeys.rename")) { renameText = key.label; renaming = key }.mutation(app)164                    Button(tr("action.delete"), role: .destructive) { deleting = key }.mutation(app)165                }166            }167        }168        .accessibilityElement(children: .contain)169    }170}171172struct SessionsDevicesPane: View {173    @Environment(AppModel.self) private var app174    @Environment(\.mccTheme) private var theme175    @State private var revokingSession: API.Session?176    @State private var revokingDevice: API.Device?177    @State private var notificationStatus: UNAuthorizationStatus?178179    var body: some View {180        let account = app.session.account181        SettingsPaneContainer(pane: .sessions, subtitle: tr("settings.sessions.subtitle")) {182            DetailSection(title: tr("settings.sessions.title")) {183                ResourceView(account.sessions) { sessions in184                    VStack(spacing: Tokens.Space.s3) {185                        ForEach(sessions, id: \.id) { s in sessionRow(s); if s.id != sessions.last?.id { Divider() } }186                    }187                }188            }189            DetailSection(title: tr("settings.devices.title")) {190                ResourceView(account.devices) { devices in191                    VStack(spacing: Tokens.Space.s3) {192                        ForEach(devices, id: \.id) { d in deviceRow(d); if d.id != devices.last?.id { Divider() } }193                    }194                }195            }196            DetailSection(title: tr("settings.push.title")) {197                KeyValueRow(tr("settings.push.entitlement"), Entitlements.apsEnvironment.map { tr("settings.push.entitlement.present", $0) } ?? tr("settings.push.entitlement.absent"))198                KeyValueRow(tr("settings.push.authorization"), notificationLabel)199                InfoBanner(tone: .info, title: tr("settings.push.server.title"), message: tr("settings.push.server.message"))200            }201        }202        .task {203            await account.sessions.load()204            await account.devices.load()205            notificationStatus = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus206        }207        .confirmationDialog(tr("settings.sessions.revoke.title"), isPresented: Binding(get: { revokingSession != nil }, set: { if !$0 { revokingSession = nil } }), presenting: revokingSession) { s in208            Button(tr("settings.revoke"), role: .destructive) { Task { await app.perform { try await account.revokeSession(id: s.id) } } }209            Button(tr("action.cancel"), role: .cancel) {}210        } message: { s in211            Text(s.current ? tr("settings.sessions.revoke.current") : tr("settings.sessions.revoke.message"))212        }213        .confirmationDialog(tr("settings.devices.revoke.title"), isPresented: Binding(get: { revokingDevice != nil }, set: { if !$0 { revokingDevice = nil } }), presenting: revokingDevice) { d in214            Button(tr("settings.revoke"), role: .destructive) { Task { await app.perform { try await account.revokeDevice(id: d.id) } } }215            Button(tr("action.cancel"), role: .cancel) {}216        } message: { d in217            Text(d.current ? tr("settings.devices.revoke.current") : tr("settings.devices.revoke.message", d.label))218        }219    }220221    private var notificationLabel: String {222        switch notificationStatus {223        case .authorized?, .provisional?: tr("settings.push.authorization.granted")224        case .denied?: tr("settings.push.authorization.denied")225        case .notDetermined?: tr("settings.push.authorization.not_asked")226        default: tr("settings.push.authorization.unknown")227        }228    }229230    private func sessionRow(_ s: API.Session) -> some View {231        HStack(alignment: .top, spacing: Tokens.Space.s4) {232            VStack(alignment: .leading, spacing: Tokens.Space.s1) {233                HStack(spacing: Tokens.Space.s3) {234                    Text(s.deviceLabel ?? tr("settings.sessions.unknown_device")).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)235                    StatusBadge(s.kind == .bearer ? tr("settings.sessions.kind.app") : tr("settings.sessions.kind.web"), tone: .neutral, compact: true)236                    if s.current { StatusBadge(tr("settings.current"), tone: .ok, compact: true) }237                }238                Text(tr("settings.sessions.times", settingsDate(s.createdAt), Format.relative(s.lastSeenAt))).font(.caption).foregroundStyle(theme.textSecondary)239                Text(s.stepUpValidUntil > Date() ? tr("settings.sessions.stepup.valid", Format.time(s.stepUpValidUntil)) : tr("settings.sessions.stepup.expired"))240                    .font(.caption).foregroundStyle(theme.textTertiary)241                if let ip = s.ip { Text(tr("settings.sessions.ip", ip)).font(.caption.monospaced()).foregroundStyle(theme.textTertiary).textSelection(.enabled) }242                if let ua = s.userAgent, !ua.isEmpty { Text(ua).font(.caption).foregroundStyle(theme.textTertiary).lineLimit(2).textSelection(.enabled) }243            }244            Spacer()245            Button(tr("settings.revoke"), role: .destructive) { revokingSession = s }.mutation(app)246        }247        .accessibilityElement(children: .contain)248    }249250    private func deviceRow(_ d: API.Device) -> some View {251        HStack(alignment: .top, spacing: Tokens.Space.s4) {252            Image(systemName: d.kind == .ios ? "iphone" : d.kind == .macos ? "desktopcomputer" : "globe").foregroundStyle(theme.textSecondary).accessibilityHidden(true)253            VStack(alignment: .leading, spacing: Tokens.Space.s1) {254                HStack(spacing: Tokens.Space.s3) {255                    Text(d.label).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)256                    StatusBadge(d.kind.rawValue, tone: .neutral, compact: true)257                    if d.current { StatusBadge(tr("settings.current"), tone: .ok, compact: true) }258                    if d.revokedAt != nil { StatusBadge(tr("settings.revoked"), tone: .offline, compact: true) }259                }260                Text([d.model, d.osVersion, d.appVersion].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(theme.textSecondary)261                Text(tr("settings.devices.times", settingsDate(d.createdAt), d.lastSeenAt.map { Format.relative($0) } ?? "—")).font(.caption).foregroundStyle(theme.textTertiary)262                Text(d.pushEnabled ? tr("settings.devices.push.on", d.pushEnv?.rawValue ?? "—") : tr("settings.devices.push.off")).font(.caption).foregroundStyle(theme.textTertiary)263            }264            Spacer()265            if d.revokedAt == nil { Button(tr("settings.revoke"), role: .destructive) { revokingDevice = d }.mutation(app) }266        }267        .accessibilityElement(children: .contain)268    }269}270271struct SecurityPane: View {272    @Environment(AppModel.self) private var app273    @Environment(\.mccTheme) private var theme274275    var body: some View {276        @Bindable var lock = app.lock277        SettingsPaneContainer(pane: .security) {278            DetailSection(title: tr("settings.lock.title")) {279                Toggle(tr("settings.lock.enable"), isOn: $lock.isEnabled)280                    .disabled(!lock.isAvailable)281                    .accessibilityIdentifier("lock-toggle")282                if !lock.isAvailable { Text(tr("settings.lock.unavailable")).font(.caption).foregroundStyle(theme.textSecondary) }283                Picker(tr("settings.lock.idle"), selection: $lock.idleMinutes) {284                    ForEach([1, 5, 10, 15, 30, 60], id: \.self) { Text(Format.duration(seconds: Double($0 * 60))).tag($0) }285                }286                .fixedSize()287                .disabled(!lock.isEnabled)288                InfoBanner(tone: .info, title: tr("settings.lock.local.title"), message: tr("settings.lock.local.message"))289                Button(tr("settings.lock.now")) { lock.lockNow() }.disabled(!lock.isEnabled)290            }291            DetailSection(title: tr("settings.session.title")) {292                if let s = app.session.me?.session {293                    KeyValueRow(tr("settings.session.authenticated"), settingsDate(s.authenticatedAt))294                    KeyValueRow(tr("settings.session.expires"), settingsDate(s.absoluteExpiresAt))295                }296                Button(tr("menu.sign_out"), role: .destructive) { Task { await app.signOut() } }297                    .accessibilityIdentifier("settings-sign-out")298            }299        }300    }301}302303struct ShortcutsPane: View {304    @Environment(\.mccTheme) private var theme305    var body: some View {306        SettingsPaneContainer(pane: .shortcuts) {307            Card {308                Grid(alignment: .leading, horizontalSpacing: Tokens.Space.s7, verticalSpacing: Tokens.Space.s3) {309                    ForEach(Array(ShortcutsHelp.entries.enumerated()), id: \.offset) { _, e in310                        GridRow {311                            Text(e.keys).font(.callout.monospaced()).foregroundStyle(theme.textPrimary)312                            Text(e.title).font(.callout).foregroundStyle(theme.textSecondary)313                        }314                        .accessibilityElement(children: .combine)315                    }316                }317            }318        }319    }320}321322struct AboutPane: View {323    @Environment(AppModel.self) private var app324    @Environment(\.mccTheme) private var theme325326    private var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "—" }327    private var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—" }328329    var body: some View {330        let version = app.session.admin.version331        SettingsPaneContainer(pane: .about) {332            DetailSection(title: tr("settings.about.app")) {333                KeyValueRow(tr("settings.about.version"), "\(appVersion) (\(build))")334                KeyValueRow(tr("settings.about.bundle"), Bundle.main.bundleIdentifier ?? "—", monospaced: true)335                KeyValueRow(tr("settings.about.origin"), app.environment.origin.absoluteString, monospaced: true)336                KeyValueRow(tr("settings.about.associated_domains"),337                            Entitlements.associatedDomains.isEmpty ? tr("settings.about.associated_domains.absent") : Entitlements.associatedDomains.joined(separator: ", "))338                KeyValueRow(tr("settings.about.keychain"), Entitlements.keychainAccessGroup ?? tr("settings.about.keychain.login"))339                if Entitlements.associatedDomains.isEmpty {340                    InfoBanner(tone: .warning, title: tr("settings.about.no_domains.title"), message: tr("settings.about.no_domains.message"))341                }342            }343            DetailSection(title: tr("settings.about.server")) {344                ResourceView(version) { v in345                    VStack(spacing: Tokens.Space.s2) {346                        KeyValueRow(tr("settings.about.server_version"), v.version)347                        KeyValueRow(tr("settings.about.api_version"), v.apiVersion)348                        if let c = v.commit, !c.isEmpty { KeyValueRow(tr("settings.about.commit"), c, monospaced: true) }349                        if let b = v.builtAt { KeyValueRow(tr("settings.about.built"), Format.dateTime(b)) }350                        if let m = v.minAppVersion, !m.isEmpty {351                            KeyValueRow(tr("settings.about.min_app"), m)352                            if SettingsLogic.isOlder(app: appVersion, than: m) {353                                InfoBanner(tone: .warning, title: tr("settings.about.outdated.title"), message: tr("settings.about.outdated.message", appVersion, m))354                            }355                        }356                    }357                }358            }359        }360        .task { await version.load() }361    }362}363
Files main
Menu

Theme