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

422 lines
17 KiB
Swift

import SwiftUI
import UIKit
@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 {
private enum Page: Hashable {
case inventory, locations, community, profile
var title: String {
switch self {
case .inventory: "找物"
case .locations: "位置"
case .community: "社区"
case .profile: "我的"
}
}
var symbol: String {
switch self {
case .inventory: "magnifyingglass"
case .locations: "square.stack"
case .community: "bubble.left.and.bubble.right"
case .profile: "person.crop.circle"
}
}
}
private struct IntakeRequest: Identifiable {
let id = UUID()
let location: Place?
}
@State private var store: InventoryStore
@State private var page = Page.inventory
@State private var intake: IntakeRequest?
@State private var keyboardVisible = false
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 {
VStack(spacing: 0) {
tabs
.frame(maxWidth: .infinity, maxHeight: .infinity)
if !keyboardVisible { navigationBar }
}
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
keyboardVisible = true
}
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
keyboardVisible = false
}
.sheet(item: $intake) { request in
NavigationStack { IntakeView(store: store, initialLocation: request.location) }
.presentationDragIndicator(.visible)
}
.task { await store.warm() }
}
private var tabs: some View {
TabView(selection: $page) {
InventoryView(store: store, switcher: switcher, onIntake: { openIntake() })
.toolbar(.hidden, for: .tabBar)
.tabItem { Label(Page.inventory.title, systemImage: Page.inventory.symbol) }
.tag(Page.inventory)
LocationView(store: store, onIntake: openIntake)
.toolbar(.hidden, for: .tabBar)
.tabItem { Label(Page.locations.title, systemImage: Page.locations.symbol) }
.tag(Page.locations)
NavigationStack {
CommunityFeedView(account: store.account, source: store)
}
.toolbar(.hidden, for: .tabBar)
.tabItem { Label(Page.community.title, systemImage: Page.community.symbol) }
.tag(Page.community)
NavigationStack {
MyView(account: store.account, store: store, openSpaces: openSpaces)
}
.toolbar(.hidden, for: .tabBar)
.tabItem { Label(Page.profile.title, systemImage: Page.profile.symbol) }
.tag(Page.profile)
}
.toolbar(.hidden, for: .tabBar)
}
private var navigationBar: some View {
HStack(spacing: 0) {
tabButton(.inventory)
tabButton(.locations)
if store.canWrite {
Button { openIntake() } label: {
Image(systemName: "plus")
.font(.system(size: 27, weight: .semibold))
.foregroundStyle(.white)
.frame(width: 60, height: 60)
.background(Color.atlasBlue, in: Circle())
}
.buttonStyle(.plain)
.accessibilityLabel("录入物品")
.accessibilityIdentifier("intake.add")
.frame(maxWidth: .infinity)
}
tabButton(.community)
tabButton(.profile)
}
.frame(maxWidth: 600)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.frame(maxWidth: .infinity)
.background(.regularMaterial)
.overlay(alignment: .top) { Divider() }
}
private func tabButton(_ destination: Page) -> some View {
Button { page = destination } label: {
VStack(spacing: 4) {
tabGlyph(destination, selected: page == destination)
.frame(width: 28, height: 26)
.accessibilityHidden(true)
Text(destination.title).font(.caption2.weight(page == destination ? .semibold : .medium))
}
.foregroundStyle(page == destination ? Color.atlasBlue : Color.secondary)
.frame(maxWidth: .infinity, minHeight: 48)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityAddTraits(page == destination ? .isSelected : [])
}
@ViewBuilder
private func tabGlyph(_ destination: Page, selected: Bool) -> some View {
if destination == .inventory {
SearchTabGlyph(selected: selected).frame(width: 24, height: 24)
} else {
Image(systemName: selected ? destination.symbol + ".fill" : destination.symbol)
.font(.system(size: destination == .profile ? 24 : 21, weight: .medium))
}
}
private func openIntake(_ location: Place? = nil) {
guard store.canWrite else { return }
intake = IntakeRequest(location: location)
}
}
private struct SearchTabGlyph: View {
let selected: Bool
var body: some View {
Canvas { context, size in
let scale = size.width / 24
let lens = Path(ellipseIn: CGRect(x: 2.5 * scale, y: 2.5 * scale, width: 14 * scale, height: 14 * scale))
let stroke = StrokeStyle(lineWidth: 2 * scale, lineCap: .round)
let color = GraphicsContext.Shading.foreground
var handle = Path()
handle.move(to: CGPoint(x: 14.8 * scale, y: 14.8 * scale))
handle.addLine(to: CGPoint(x: 21 * scale, y: 21 * scale))
if selected { context.fill(lens, with: color) }
context.stroke(lens, with: color, style: stroke)
context.stroke(handle, with: color, style: stroke)
}
}
}
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)
}