import InventoryCore import SwiftUI struct ItemEditor: View { let store: InventoryStore var initialLocation: UUID? = nil @Environment(\.dismiss) private var dismiss @State private var name = "" @State private var aliases = "" @State private var quantity = 1 @State private var notes = "" @State private var locationID: UUID? @State private var errorMessage: String? var body: some View { NavigationStack { Form { Section("物品") { TextField("名称", text: $name) TextField("别名,用逗号隔开", text: $aliases) Stepper("数量:\(quantity)", value: $quantity, in: 1...9999) TextField("备注", text: $notes, axis: .vertical) } Section("放在哪") { LocationPicker(inventory: store.inventory, selection: $locationID) if store.inventory.locations.isEmpty { Text("先在「位置」里建一个位置。").font(.footnote).foregroundStyle(.secondary) } } if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } } .navigationTitle("记一件") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("保存") { save() } .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || locationID == nil) } } } .onAppear { if locationID == nil { locationID = initialLocation } } } private func save() { guard let locationID else { return } do { let aliasList = aliases.split(whereSeparator: { ",,、".contains($0) }).map(String.init) try store.update { try $0.addItem(name: name, aliases: aliasList, quantity: quantity, notes: notes, locationID: locationID) } dismiss() } catch { errorMessage = error.localizedDescription } } } struct MoveEditor: View { let store: InventoryStore let item: Item @Environment(\.dismiss) private var dismiss @State private var locationID: UUID? @State private var errorMessage: String? var body: some View { NavigationStack { Form { Section("原位置") { Text(store.inventory.path(to: item.locationID)) } Section("新位置") { LocationPicker(inventory: store.inventory, selection: $locationID) } if let errorMessage { Section { Text(errorMessage).foregroundStyle(.red) } } } .navigationTitle("移位") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("确认移位") { guard let locationID else { return } do { try store.update { try $0.moveItem(id: item.id, to: locationID) } dismiss() } catch { errorMessage = error.localizedDescription } } .disabled(locationID == nil || locationID == item.locationID) } } } } } private struct LocationPicker: View { let inventory: Inventory @Binding var selection: UUID? var body: some View { Picker("位置", selection: $selection) { Text("请选择").tag(nil as UUID?) ForEach(inventory.locations) { location in Text(inventory.path(to: location.id)).tag(Optional(location.id)) } } .pickerStyle(.navigationLink) } }