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

282 lines
12 KiB
Swift

import SwiftUI
@main
struct ItemAtlasApp: App {
@State private var account = AtlasAccount()
var body: some Scene {
WindowGroup {
Group {
if account.signedIn {
SpacesView(account: account)
} else {
NavigationStack {
WelcomeView(account: account)
}
}
}
.tint(.atlasBlue)
}
}
}
private struct SpacesView: View {
let account: AtlasAccount
@State private var spaces: [Space]
@State private var selected: Space?
@State private var showingCreate = false
@State private var showingJoin = false
@State private var showingMyProfile = false
@State private var showingCommunity = false
@State private var loaded: Bool
@State private var error: String?
@State private var invitations: [ReceivedSpaceInvitation] = []
@State private var updatingInvitation = false
@State private var choseInitialSpace = false
init(account: AtlasAccount) {
self.account = account
let preview: [Space]? = account.cached("/api/households")
_spaces = State(initialValue: preview ?? [])
_loaded = State(initialValue: preview != nil)
}
var body: some View {
Group {
if let selected {
SpaceTabs(account: account, space: selected, spaces: spaces, selectSpace: select,
openSpaces: { self.selected = nil })
.id(selected)
} else {
NavigationStack {
List {
if !loaded && error == nil { ProgressView("正在加载空间") }
if loaded && spaces.isEmpty && invitations.isEmpty {
ContentUnavailableView("还没有空间", systemImage: "house", description: Text("建一个自己的空间,或等家人邀请你。"))
}
if let error { Text(error).foregroundStyle(.red) }
if !invitations.isEmpty {
Section("待接受的邀请") {
ForEach(invitations) { invitation in
VStack(alignment: .leading, spacing: 8) {
Text(invitation.spaceName).font(.headline)
Text(invitation.role == "EDITOR" ? "可查看和整理物品" : "可查看物品")
.font(.subheadline).foregroundStyle(.secondary)
HStack(spacing: 18) {
Button("接受") { Task { await update(invitation, accepting: true) } }
Button("忽略") { Task { await update(invitation, accepting: false) } }
.foregroundStyle(.secondary)
}
.buttonStyle(.borderless)
.disabled(updatingInvitation)
}
}
}
}
ForEach(spaces) { space in
Button { select(space) } label: { Label(space.name, systemImage: "house") }
}
Button("新建空间") { showingCreate = true }.disabled(!loaded)
}
.task { await load() }
.refreshable { await load(refresh: true) }
.navigationTitle("我的空间")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button { showingCommunity = true } label: {
Label("社区", systemImage: "bubble.left.and.bubble.right")
}
}
ToolbarItemGroup(placement: .topBarTrailing) {
Button { showingJoin = true } label: { Label("使用邀请码", systemImage: "person.badge.plus") }
Button { showingMyProfile = true } label: { Label("我的", systemImage: "person.crop.circle") }
}
}
.sheet(isPresented: $showingCommunity) {
NavigationStack { CommunityFeedView(account: account) }
}
.sheet(isPresented: $showingMyProfile) {
NavigationStack { MyView(account: account, openSpaces: { showingMyProfile = false }) }
}
.sheet(isPresented: $showingCreate) {
SpaceEditor(account: account, joining: false, saved: select)
}
.sheet(isPresented: $showingJoin) {
SpaceEditor(account: account, joining: true, saved: select)
}
}
}
}
.task { await CommunityFeedView.warm(account: account) }
}
private func select(_ space: Space) {
choseInitialSpace = true
if let index = spaces.firstIndex(where: { $0.id == space.id }) {
spaces[index] = space
} else {
spaces.append(space)
}
selected = space
}
private func load(refresh: Bool = false) async {
do {
async let inbox = account.request("/api/households/direct-invitations")
let current: [Space] = try await account.read("/api/households", refresh: refresh)
try Task.checkCancellation()
spaces = current
loaded = true
error = nil
let received = try await JSONDecoder().decode([ReceivedSpaceInvitation].self, from: inbox)
try Task.checkCancellation()
invitations = received
if !choseInitialSpace && spaces.count == 1 && invitations.isEmpty { select(spaces[0]) }
choseInitialSpace = true
} catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
private func update(_ invitation: ReceivedSpaceInvitation, accepting: Bool) async {
guard !updatingInvitation else { return }
updatingInvitation = true
defer { updatingInvitation = false }
error = nil
let path = "/api/households/direct-invitations/" + invitation.id.uuidString
do {
if accepting {
let response = try await account.request(path + "/accept", method: "POST")
let space = try JSONDecoder().decode(Space.self, from: response)
account.invalidateReads("/api/households")
select(space)
} else {
_ = try await account.request(path, method: "DELETE")
}
invitations.removeAll { $0.id == invitation.id }
} catch { self.error = error.localizedDescription }
}
}
private struct SpaceTabs: View {
@State private var store: InventoryStore
let switcher: SpaceMenu.Actions
let openSpaces: () -> Void
init(account: AtlasAccount, space: Space, spaces: [Space], selectSpace: @escaping (Space) -> Void,
openSpaces: @escaping () -> Void) {
_store = State(initialValue: InventoryStore(account: account, space: space))
switcher = SpaceMenu.Actions(spaces: spaces, select: selectSpace, manage: openSpaces)
self.openSpaces = openSpaces
}
var body: some View {
TabView {
InventoryView(store: store, switcher: switcher).tabItem { Label("找物", systemImage: "magnifyingglass") }
LocationView(store: store).tabItem { Label("位置", systemImage: "square.stack") }
NavigationStack {
CommunityFeedView(account: store.account, source: store)
}.tabItem { Label("社区", systemImage: "bubble.left.and.bubble.right") }
NavigationStack {
MyView(account: store.account, store: store, openSpaces: openSpaces)
}.tabItem { Label("我的", systemImage: "person.crop.circle") }
}
.task { await store.warm() }
}
}
private struct SpaceEditor: View {
let account: AtlasAccount
let joining: Bool
let saved: (Space) -> Void
@Environment(\.dismiss) private var dismiss
@FocusState private var focused: Field?
private enum Field { case name, displayName }
@State private var name = ""
@State private var displayName = ""
@State private var busy = false
@State private var error: String?
var body: some View {
NavigationStack {
Form {
TextField(joining ? "邀请码" : "空间名称", text: $name).focused($focused, equals: .name)
.textInputAutocapitalization(.never)
TextField("我在空间里的称呼", text: $displayName).focused($focused, equals: .displayName)
if let error { Text(error).foregroundStyle(.red) }
}
.dismissibleKeyboard(active: focused != nil) { focused = nil }
.navigationTitle(joining ? "加入空间" : "新建空间")
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button(joining ? "加入" : "新建") { Task { await save() } }
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || (joining && displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || busy)
}
}
}
.interactiveDismissDisabled(busy)
}
private func save() async {
busy = true
defer { busy = false }
let entry = name.trimmingCharacters(in: .whitespacesAndNewlines)
let fields = [joining ? "code" : "name": entry, "displayName": displayName.trimmingCharacters(in: .whitespacesAndNewlines)]
do {
let bytes = try await account.request(joining ? "/api/households/invitations/redeem" : "/api/households",
method: "POST", data: JSONEncoder().encode(fields))
let space = try JSONDecoder().decode(Space.self, from: bytes)
account.invalidateReads("/api/households")
dismiss()
saved(space)
} catch { self.error = error.localizedDescription }
}
}
struct SpaceSettings: View {
let store: InventoryStore
let openSpaces: () -> Void
@State private var confirming = false
@State private var showingInvite = false
@State private var busy = false
@State private var error: String?
var body: some View {
List {
LabeledContent("当前空间", value: store.space.name)
if store.space.role == "OWNER" {
Section("成员") {
Button { showingInvite = true } label: {
Label("邀请成员", systemImage: "person.badge.plus")
}
}
Section {
Button("删除空间", role: .destructive) { confirming = true }.disabled(busy)
}
}
if let error { Text(error).foregroundStyle(.red) }
}
.navigationTitle("空间设置")
.navigationBarTitleDisplayMode(.inline)
.sheet(isPresented: $showingInvite) { SpaceInvitationView(store: store) }
.confirmationDialog("删除「\(store.space.name)」?", isPresented: $confirming, titleVisibility: .visible) {
Button("删除空间和图片", role: .destructive) {
Task {
busy = true
defer { busy = false }
do { try await store.delete(store.root); openSpaces() }
catch { self.error = error.localizedDescription }
}
}
} message: {
Text("此空间里的物品、位置和图片都会删除,空间成员会失去访问权限。")
}
}
}
extension Color {
static let atlasNavy = Color(red: 0.09, green: 0.15, blue: 0.28)
static let atlasBlue = Color(red: 0.19, green: 0.32, blue: 0.81)
}