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

100 lines
3.7 KiB
Swift

import SwiftUI
struct ReceivedSpaceInvitation: Decodable, Identifiable {
let id: UUID
let spaceName: String
let role: String
}
struct SpaceInvitationView: View {
let store: InventoryStore
@Environment(\.dismiss) private var dismiss
@FocusState private var editing: Bool
@State private var username = ""
@State private var role = "VIEWER"
@State private var sent: [SentInvitation] = []
@State private var busy = false
@State private var notice: String?
@State private var error: String?
private struct SentInvitation: Decodable, Identifiable {
let id: UUID
let username: String
let role: String
}
private var endpoint: String { store.root + "/direct-invitations" }
private var recipient: String { username.trimmingCharacters(in: .whitespacesAndNewlines) }
var body: some View {
NavigationStack {
Form {
Section {
TextField("对方的见物账号", text: $username)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($editing)
Picker("加入后的权限", selection: $role) {
Text("查看").tag("VIEWER")
Text("查看和整理").tag("EDITOR")
}
Button("发送邀请") { editing = false; Task { await send() } }
.disabled(recipient.isEmpty || recipient.count > 64 || busy)
if let notice { Text(notice).font(.footnote).foregroundStyle(.secondary) }
if let error { Text(error).font(.footnote).foregroundStyle(.red) }
}
if !sent.isEmpty {
Section("待对方接受") {
ForEach(sent) { invitation in
LabeledContent(invitation.username, value: invitation.role == "EDITOR" ? "可整理" : "可查看")
.swipeActions {
Button("撤销", role: .destructive) { Task { await revoke(invitation) } }
.disabled(busy)
}
}
}
}
}
.dismissibleKeyboard(active: editing) { editing = false }
.navigationTitle("邀请成员")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) { Button("完成") { dismiss() }.disabled(busy) }
}
.task { await load() }
}
}
private func load() async {
do { sent = try await store.get(endpoint) }
catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
private func send() async {
guard !busy else { return }
busy = true
defer { busy = false }
error = nil
notice = nil
do {
let body = try JSONEncoder().encode(["username": recipient, "role": role])
_ = try await store.account.request(endpoint, method: "POST", data: body)
username = ""
notice = "已提交。可接受的邀请会显示在对方的空间列表。"
await load()
} catch { self.error = error.localizedDescription }
}
private func revoke(_ invitation: SentInvitation) async {
guard !busy else { return }
busy = true
defer { busy = false }
error = nil
do {
_ = try await store.account.request(endpoint + "/" + invitation.id.uuidString, method: "DELETE")
await load()
} catch { self.error = error.localizedDescription }
}
}