import InventoryCore import SwiftUI struct LocationView: View { let store: InventoryStore var body: some View { NavigationStack { LocationContents(store: store, location: nil) } } } private struct LocationContents: View { let store: InventoryStore let location: Location? @State private var editingLocation = false @State private var addingItem = false @State private var newName = "" @State private var errorMessage: String? var body: some View { List { if let location { Section { Text(store.inventory.path(to: location.id)).foregroundStyle(.secondary) } } Section(location == nil ? "房间和区域" : "子位置") { ForEach(store.inventory.children(of: location?.id)) { child in NavigationLink { LocationContents(store: store, location: child) } label: { Label(child.name, systemImage: "folder") } } Button { newName = "" editingLocation = true } label: { Label(location == nil ? "新建位置" : "新建子位置", systemImage: "plus") } } if let location { Section("这里的物品") { ForEach(store.inventory.search("").filter { $0.locationID == location.id }) { item in NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: { Text(item.name) } } Button("记一件") { addingItem = true } } } if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } } .navigationTitle(location?.name ?? "位置") .alert("新建位置", isPresented: $editingLocation) { TextField("名称", text: $newName) Button("取消", role: .cancel) {} Button("保存") { do { try store.update { try $0.addLocation(name: newName, parentID: location?.id) } errorMessage = nil } catch { errorMessage = error.localizedDescription } } } .sheet(isPresented: $addingItem) { ItemEditor(store: store, initialLocation: location?.id) } } }