item-atlas/apps/ios/ItemAtlas/MyView.swift

263 lines
9.9 KiB
Swift

import SwiftUI
private struct AccountProfile: Decodable {
let username: String?
let nickname: String
let signature: String
let avatar: ProfileAvatar
var displayName: String { nickname.isEmpty ? (username ?? "我的账号") : nickname }
struct Update: Encodable {
var nickname: String
var signature: String
var avatar: ProfileAvatar
}
}
private enum ProfileAvatar: String, CaseIterable, Codable, Identifiable {
case person = "PERSON"
case cat = "CAT"
case leaf = "LEAF"
case moon = "MOON"
case mountain = "MOUNTAIN"
case spark = "SPARK"
var id: Self { self }
var symbol: String {
switch self {
case .person: "person.fill"
case .cat: "cat.fill"
case .leaf: "leaf.fill"
case .moon: "moon.stars.fill"
case .mountain: "mountain.2.fill"
case .spark: "sparkle"
}
}
var title: String {
switch self {
case .person: "默认"
case .cat: "小猫"
case .leaf: "叶子"
case .moon: "夜空"
case .mountain: "山丘"
case .spark: "星光"
}
}
var color: Color {
switch self {
case .person: .atlasBlue
case .cat: .orange
case .leaf: .green
case .moon: .purple
case .mountain: .teal
case .spark: .pink
}
}
}
private struct AvatarBadge: View {
let avatar: ProfileAvatar
let size: CGFloat
var body: some View {
Image(systemName: avatar.symbol)
.font(.system(size: size * 0.40, weight: .medium))
.symbolRenderingMode(.hierarchical)
.foregroundStyle(avatar.color)
.frame(width: size, height: size)
.background(avatar.color.opacity(0.12), in: Circle())
.accessibilityHidden(true)
}
}
struct MyView: View {
let account: AtlasAccount
var store: InventoryStore? = nil
let openSpaces: () -> Void
@State private var profile: AccountProfile?
@State private var profileError: String?
@State private var showingProfile = false
@State private var confirmingSignOut = false
var body: some View {
List {
Section {
if let profile {
Button { showingProfile = true } label: {
HStack(spacing: 13) {
AvatarBadge(avatar: profile.avatar, size: 52)
VStack(alignment: .leading, spacing: 4) {
Text(profile.displayName).font(.headline)
if !profile.nickname.isEmpty, let username = profile.username {
Text("账号 " + username).font(.caption).foregroundStyle(.secondary)
}
Text(profile.signature.isEmpty ? "添加签名" : profile.signature)
.font(.subheadline).foregroundStyle(.secondary).lineLimit(2)
}
.frame(maxWidth: .infinity, alignment: .leading)
Image(systemName: "pencil")
.foregroundStyle(Color.atlasBlue)
.accessibilityHidden(true)
}
.padding(.vertical, 5)
.foregroundStyle(.primary)
}
.buttonStyle(.plain)
.accessibilityHint("编辑头像、昵称和签名")
} else if profileError == nil {
ProgressView("正在加载资料")
}
if let profileError {
Text(profileError).font(.footnote).foregroundStyle(.secondary)
Button("重新加载资料") { Task { await loadProfile() } }
}
}
Section("空间") {
if let store {
NavigationLink {
SpaceSettings(store: store, openSpaces: openSpaces)
} label: {
Label {
VStack(alignment: .leading, spacing: 3) {
Text(store.space.name)
Text("空间设置").font(.caption).foregroundStyle(.secondary)
}
} icon: {
Image(systemName: "house")
}
}
Button(action: openSpaces) { Label("切换空间", systemImage: "arrow.left.arrow.right") }
} else {
Button(action: openSpaces) { Label("查看我的空间", systemImage: "house") }
}
}
if let store {
Section {
NavigationLink {
ItemListView(store: store, favoritesOnly: true)
} label: {
Label("我的收藏", systemImage: "star")
}
}
}
Section {
Button(role: .destructive) { confirmingSignOut = true } label: {
Label("退出登录", systemImage: "rectangle.portrait.and.arrow.right")
}
}
}
.navigationTitle("我的")
.navigationBarTitleDisplayMode(.inline)
.task { if profile == nil { await loadProfile() } }
.refreshable { await loadProfile() }
.sheet(isPresented: $showingProfile) {
if let profile {
ProfileEditor(account: account, profile: profile) { self.profile = $0 }
}
}
.confirmationDialog("退出当前账号?", isPresented: $confirmingSignOut, titleVisibility: .visible) {
Button("退出登录", role: .destructive) { Task { await account.signOut() } }
}
}
private func loadProfile() async {
do {
let data = try await account.request("/api/me/profile", timeout: 12)
try Task.checkCancellation()
profile = try JSONDecoder().decode(AccountProfile.self, from: data)
profileError = nil
} catch where !Task.isCancelled {
profileError = "暂时无法加载账号资料。"
} catch {}
}
}
private struct ProfileEditor: View {
let account: AtlasAccount
let saved: (AccountProfile) -> Void
@Environment(\.dismiss) private var dismiss
@FocusState private var typing: Bool
@State private var update: AccountProfile.Update
@State private var busy = false
@State private var error: String?
init(account: AtlasAccount, profile: AccountProfile, saved: @escaping (AccountProfile) -> Void) {
self.account = account
self.saved = saved
_update = State(initialValue: AccountProfile.Update(nickname: profile.nickname, signature: profile.signature,
avatar: profile.avatar))
}
var body: some View {
NavigationStack {
Form {
Section("头像") {
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 14) {
ForEach(ProfileAvatar.allCases) { avatar in
Button {
update.avatar = avatar
} label: {
VStack(spacing: 5) {
AvatarBadge(avatar: avatar, size: 48)
.padding(2)
.overlay {
Circle().strokeBorder(update.avatar == avatar ? Color.atlasBlue : .clear,
lineWidth: 2)
}
Text(avatar.title).font(.caption).foregroundStyle(.primary)
}
.frame(maxWidth: .infinity)
}
.buttonStyle(.plain)
.accessibilityAddTraits(update.avatar == avatar ? .isSelected : [])
}
}
.padding(.vertical, 7)
}
Section {
TextField("昵称", text: $update.nickname).focused($typing)
TextField("签名", text: $update.signature).focused($typing)
} header: {
Text("资料")
} footer: {
if update.nickname.utf16.count > 32 || update.signature.utf16.count > 100 {
Text("昵称最多 32 字符,签名最多 100 字符。")
}
}
if let error { Text(error).foregroundStyle(.red) }
}
.dismissibleKeyboard(active: typing) { typing = false }
.navigationTitle("编辑资料")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button("保存") { typing = false; Task { await save() } }
.disabled(busy || update.nickname.utf16.count > 32 || update.signature.utf16.count > 100)
}
}
}
.interactiveDismissDisabled(busy)
}
private func save() async {
guard !busy else { return }
busy = true
defer { busy = false }
error = nil
do {
let data = try await account.request("/api/me/profile", method: "PUT", data: JSONEncoder().encode(update), timeout: 12)
saved(try JSONDecoder().decode(AccountProfile.self, from: data))
dismiss()
} catch { self.error = error.localizedDescription }
}
}