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

265 lines
11 KiB
Swift

import PhotosUI
import SwiftUI
struct ItemEditor: View {
let store: InventoryStore
var initialLocation: UUID? = nil
var existing: Item? = nil
@Environment(\.dismiss) private var dismiss
@FocusState private var focus: Field?
@State private var name = ""
@State private var aliases = ""
@State private var quantity = 1
@State private var notes = ""
@State private var price = ""
@State private var icon = "BOX"
@State private var locationID: UUID?
@State private var showingAddLocation = false
@State private var loadingLocations = true
@State private var initialized = false
@State private var error: String?
@State private var busy = false
@State private var photoSelection: PhotosPickerItem?
@State private var loadingPhoto = false
@State private var crop: CropSource?
@State private var photo: Data?
@State private var photoKey = UUID()
@State private var createKey = UUID()
@State private var savedItem: Item?
private enum Field { case name, aliases, price, notes }
private var canSave: Bool {
!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && validPrice &&
!busy && !loadingPhoto
}
private var validPrice: Bool {
price.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || PurchasePrice.cents(from: price) != nil
}
var body: some View {
NavigationStack {
Form {
if savedItem != nil {
Section {
Text("物品已保存,照片可以重试上传。")
Button("稍后添加照片") { dismiss() }.disabled(busy)
}
}
Section("物品") {
TextField("名称", text: $name).focused($focus, equals: .name)
TextField("别名,用逗号隔开", text: $aliases).focused($focus, equals: .aliases)
Stepper("数量:\(quantity)", value: $quantity, in: 1...9999)
TextField("购入单价(元,可选)", text: $price).keyboardType(.decimalPad)
.focused($focus, equals: .price)
if !validPrice {
Text("单价允许 0 到 999 亿元,最多两位小数。")
.font(.footnote).foregroundStyle(.secondary)
}
TextField("备注", text: $notes, axis: .vertical).focused($focus, equals: .notes)
}
.disabled(busy || savedItem != nil)
photoSection
Section("图标") {
SymbolPicker(symbols: InventorySymbol.items, color: .teal, selection: $icon)
}
.disabled(busy || savedItem != nil)
if existing == nil {
Section("存放位置(可选)") {
LocationPicker(store: store, selection: $locationID, allowsClearing: true)
if !loadingLocations && store.locations.isEmpty {
Button("新建位置") { focus = nil; showingAddLocation = true }
}
}
.disabled(busy || savedItem != nil)
}
if let error { Text(error).foregroundStyle(.red) }
}
.dismissibleKeyboard(active: focus != nil) { focus = nil }
.navigationTitle(existing == nil ? "添加物品" : "编辑物品")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button(savedItem == nil ? "取消" : "关闭") { dismiss() }.disabled(busy)
}
ToolbarItem(placement: .confirmationAction) {
Button(savedItem == nil ? "保存" : "重试上传") { focus = nil; Task { await save() } }
.disabled(!canSave)
}
}
.sheet(isPresented: $showingAddLocation) {
PlaceEditor(store: store) { locationID = $0 }
}
.sheet(item: $crop) { source in
CropEditor(source: source, actionTitle: "使用照片") { jpeg in
photo = jpeg
photoKey = UUID()
}
}
}
.interactiveDismissDisabled(busy)
.task {
guard !initialized else { return }
initialized = true
name = existing?.name ?? ""
aliases = existing?.aliases.joined(separator: "、") ?? ""
quantity = existing?.quantity ?? 1
notes = existing?.notes ?? ""
price = existing?.priceCents.map(PurchasePrice.input) ?? ""
icon = InventorySymbol.item(existing?.icon).id
locationID = existing?.locationId ?? initialLocation
do { if existing == nil { try await store.refreshLocations() } }
catch { self.error = error.localizedDescription }
loadingLocations = false
}
.task(id: photoSelection) {
guard let selection = photoSelection else { return }
loadingPhoto = true
defer {
if photoSelection == selection {
loadingPhoto = false
photoSelection = nil
}
}
do {
guard let source = try await selection.loadTransferable(type: CropSource.self) else {
throw AtlasError("这张照片无法打开,请重新选择。")
}
try Task.checkCancellation()
focus = nil
error = nil
crop = source
} catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
}
private var photoSection: some View {
let pickerTitle = photo == nil ? "选择照片" : "更换待上传照片"
return Section("照片") {
if let photo, let preview = UIImage(data: photo) {
Image(uiImage: preview)
.resizable().scaledToFit()
.frame(maxHeight: 130)
.clipShape(.rect(cornerRadius: 10))
.accessibilityLabel("待上传照片")
if savedItem == nil {
Button("移除待上传照片", role: .destructive) { self.photo = nil }.disabled(busy)
}
} else if let existing, let cover = existing.coverPhotoId {
PhotoImage(store: store, target: .item(existing.id), photo: cover, thumbnail: true)
.frame(width: 82, height: 82).clipShape(.rect(cornerRadius: 10))
}
if savedItem == nil {
PhotosPicker(selection: $photoSelection, matching: .images, preferredItemEncoding: .current) {
Label(pickerTitle, systemImage: "photo.badge.plus")
}
.disabled(busy || loadingPhoto)
}
if busy && photo != nil { ProgressView("正在保存") }
if loadingPhoto { ProgressView("读取照片") }
}
}
private func save() async {
guard canSave else { return }
busy = true
error = nil
defer { busy = false }
do {
let item: Item
if let savedItem {
item = savedItem
} else {
let aliasList = aliases.split(whereSeparator: { ",,、".contains($0) })
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
let input = ItemInput(name: name, quantity: quantity, notes: notes, locationId: locationID,
aliases: aliasList, version: existing?.version,
appearance: .init(icon: icon, priceCents: PurchasePrice.cents(from: price)))
item = try await store.save(input, id: existing?.id, idempotencyKey: existing == nil ? createKey : nil)
savedItem = item
}
if let photo { try await store.upload(photo, target: .item(item.id), idempotencyKey: photoKey) }
dismiss()
} catch { self.error = error.localizedDescription }
}
}
struct MoveEditor: View {
let store: InventoryStore
let item: Item
@Environment(\.dismiss) private var dismiss
@State private var locationID: UUID?
@State private var error: String?
@State private var busy = false
init(store: InventoryStore, item: Item) {
self.store = store
self.item = item
_locationID = State(initialValue: item.locationId)
}
var body: some View {
NavigationStack {
Form {
Section("原位置") { Text(item.locationLabel) }
Section("新位置") { LocationPicker(store: store, selection: $locationID, allowsClearing: true) }
if let error { Text(error).foregroundStyle(.red) }
}
.navigationTitle("移位")
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button("确认移位") { Task { await save() } }.disabled(locationID == item.locationId || busy)
}
}
}
.interactiveDismissDisabled(busy)
.task {
do { try await store.refreshLocations() }
catch { self.error = error.localizedDescription }
}
}
private func save() async {
guard locationID != item.locationId, !busy else { return }
struct Move: Encodable {
let locationId: UUID?
let version: Int
enum CodingKeys: CodingKey { case locationId, version }
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(locationId, forKey: .locationId)
try container.encode(version, forKey: .version)
}
}
busy = true
defer { busy = false }
do {
let _: Item = try await store.send(store.itemPath(item.id) + "/moves", Move(locationId: locationID, version: item.version))
store.changed()
dismiss()
} catch { self.error = error.localizedDescription }
}
}
extension View {
func dismissibleKeyboard(active: Bool, action: @escaping () -> Void) -> some View {
scrollDismissesKeyboard(.interactively)
.safeAreaInset(edge: .bottom, spacing: 0) {
if active {
HStack {
Spacer()
Button(action: action) { Label("收起键盘", systemImage: "keyboard.chevron.compact.down") }
}
.padding(.horizontal).padding(.vertical, 8)
.background(.bar)
}
}
}
}