307 lines
13 KiB
Swift
307 lines
13 KiB
Swift
import SwiftUI
|
||
|
||
struct InventoryView: View {
|
||
let store: InventoryStore
|
||
|
||
var body: some View {
|
||
NavigationStack { ItemListView(store: store) }
|
||
}
|
||
}
|
||
|
||
struct ItemListView: View {
|
||
let store: InventoryStore
|
||
var favoritesOnly = false
|
||
@Environment(\.colorScheme) private var colorScheme
|
||
@State private var results = ItemListResults()
|
||
@State private var query = ""
|
||
@FocusState private var searching: Bool
|
||
|
||
var body: some View {
|
||
VStack(spacing: 0) {
|
||
HStack(spacing: 10) {
|
||
Image(systemName: "magnifyingglass").foregroundStyle(.secondary).accessibilityHidden(true)
|
||
TextField("搜物品、别名或位置", text: $query)
|
||
.focused($searching).submitLabel(.search).onSubmit { searching = false }
|
||
.textInputAutocapitalization(.never)
|
||
if !query.isEmpty {
|
||
Button { query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) }
|
||
.accessibilityLabel("清除搜索")
|
||
}
|
||
if searching {
|
||
Button { searching = false } label: { Image(systemName: "keyboard.chevron.compact.down") }
|
||
.accessibilityLabel("收起键盘")
|
||
}
|
||
}
|
||
.padding(.horizontal, 12)
|
||
.frame(minHeight: 44)
|
||
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 13))
|
||
.padding(.horizontal, 16)
|
||
.padding(.vertical, 8)
|
||
.background(Color.entryBackground(for: colorScheme))
|
||
List { ItemsSection(store: store, results: results, query: query, favorites: favoritesOnly) }
|
||
.listStyle(.plain).scrollDismissesKeyboard(.interactively)
|
||
}
|
||
.navigationTitle(favoritesOnly ? "我的收藏" : "找物")
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
.toolbar {
|
||
ToolbarItem(placement: .topBarTrailing) {
|
||
Text(store.space.name).font(.caption).foregroundStyle(.secondary)
|
||
.lineLimit(1).frame(maxWidth: 108, alignment: .trailing)
|
||
.accessibilityLabel("当前空间:\(store.space.name)")
|
||
}
|
||
}
|
||
.task(id: results.loadID(query: query, revision: store.revision)) {
|
||
await results.load(store: store, query: query, favorites: favoritesOnly)
|
||
}
|
||
.refreshable { await results.load(store: store, query: query, favorites: favoritesOnly) }
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
@Observable
|
||
final class ItemListResults {
|
||
struct LoadID: Hashable {
|
||
let query: String
|
||
let revision: Int
|
||
let retry: Int
|
||
}
|
||
|
||
private(set) var rows: [Item] = []
|
||
private(set) var loading = true
|
||
private(set) var loadingMore = false
|
||
private(set) var more = false
|
||
private(set) var error: String?
|
||
private var retryCount = 0
|
||
private var displayedQuery = ""
|
||
private var activeRequest: UUID?
|
||
|
||
func loadID(query: String, revision: Int) -> LoadID {
|
||
LoadID(query: query.trimmingCharacters(in: .whitespacesAndNewlines), revision: revision, retry: retryCount)
|
||
}
|
||
|
||
func retry() { retryCount += 1 }
|
||
|
||
func load(store: InventoryStore, query: String = "", favorites: Bool = false,
|
||
location: UUID? = nil, append: Bool = false) async {
|
||
let input = query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
guard !append || (more && !loading && !loadingMore && input == displayedQuery) else { return }
|
||
let request = UUID()
|
||
activeRequest = request
|
||
let revision = store.revision
|
||
error = nil
|
||
if append {
|
||
loadingMore = true
|
||
} else {
|
||
loadingMore = false
|
||
loading = rows.isEmpty || displayedQuery != input
|
||
if loading { rows = []; more = false }
|
||
}
|
||
defer {
|
||
if activeRequest == request {
|
||
loading = false
|
||
loadingMore = false
|
||
}
|
||
}
|
||
do {
|
||
if !append && !input.isEmpty { try await Task.sleep(for: .milliseconds(240)) }
|
||
let page = try await store.search(input, favorites: favorites, location: location,
|
||
offset: append ? rows.count : 0)
|
||
try Task.checkCancellation()
|
||
guard activeRequest == request, store.revision == revision else { return }
|
||
if append {
|
||
let existing = Set(rows.map(\.id))
|
||
rows += page.filter { !existing.contains($0.id) }
|
||
} else {
|
||
rows = page
|
||
displayedQuery = input
|
||
}
|
||
more = page.count == 50 && rows.count <= 10000
|
||
} catch where !Task.isCancelled && activeRequest == request {
|
||
if let urlError = error as? URLError, urlError.code == .timedOut {
|
||
self.error = "请求超时,请重试。"
|
||
} else {
|
||
self.error = error.localizedDescription
|
||
}
|
||
} catch {}
|
||
}
|
||
}
|
||
|
||
struct ItemsSection: View {
|
||
let store: InventoryStore
|
||
let results: ItemListResults
|
||
var query = ""
|
||
var favorites = false
|
||
var location: UUID? = nil
|
||
@State private var showingAdd = false
|
||
|
||
private var input: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||
|
||
var body: some View {
|
||
Section {
|
||
if results.loading { ProgressView("加载中") }
|
||
else if results.rows.isEmpty && results.error == nil {
|
||
ContentUnavailableView(emptyTitle, systemImage: favorites ? "star" : "archivebox",
|
||
description: Text(emptyDescription))
|
||
}
|
||
ForEach(results.rows) { item in
|
||
NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: {
|
||
HStack(spacing: 12) {
|
||
PhotoImage(store: store, item: item.id, photo: item.coverPhotoId, thumbnail: true)
|
||
.frame(width: 46, height: 46).clipShape(.rect(cornerRadius: 8)).accessibilityHidden(true)
|
||
VStack(alignment: .leading, spacing: 3) {
|
||
Text(item.name).font(.headline)
|
||
Text(item.locationPath).font(.subheadline).foregroundStyle(.secondary)
|
||
}
|
||
Spacer()
|
||
if item.quantity > 1 { Text("×\(item.quantity)").font(.caption).foregroundStyle(.secondary) }
|
||
}
|
||
.padding(.vertical, 4)
|
||
}
|
||
}
|
||
if results.more && results.error == nil {
|
||
Button(results.loadingMore ? "加载中" : "加载更多") {
|
||
Task { await results.load(store: store, query: query, favorites: favorites, location: location, append: true) }
|
||
}.disabled(results.loadingMore)
|
||
}
|
||
if let error = results.error {
|
||
Text(error).foregroundStyle(.red)
|
||
Button("重试") { results.retry() }
|
||
}
|
||
if !favorites && store.canWrite && input.isEmpty {
|
||
Button { showingAdd = true } label: { Label("添加物品", systemImage: "plus") }
|
||
}
|
||
}
|
||
.sheet(isPresented: $showingAdd) { ItemEditor(store: store, initialLocation: location) }
|
||
}
|
||
|
||
private var emptyTitle: String {
|
||
if !input.isEmpty { return "没找到物品" }
|
||
return favorites ? "还没有收藏" : "还没有物品"
|
||
}
|
||
|
||
private var emptyDescription: String {
|
||
if !input.isEmpty { return "试试别名、房间或收纳盒名称。" }
|
||
if favorites { return "在当前空间的物品详情里点收藏,就会出现在这里。" }
|
||
return store.canWrite ? "从手边的一件东西开始。" : "空间成员添加物品后会显示在这里。"
|
||
}
|
||
}
|
||
|
||
struct ItemDetailView: View {
|
||
let store: InventoryStore
|
||
let itemID: UUID
|
||
@Environment(\.dismiss) private var dismiss
|
||
@State private var detail: ItemDetail?
|
||
@State private var showingMove = false
|
||
@State private var showingEdit = false
|
||
@State private var confirmingDelete = false
|
||
@State private var error: String?
|
||
@State private var busy = false
|
||
|
||
var body: some View {
|
||
Group {
|
||
if let detail {
|
||
List {
|
||
Section("当前位置") {
|
||
Label(detail.item.locationPath, systemImage: "location.fill").foregroundStyle(Color.atlasBlue)
|
||
if store.canWrite { Button("移位") { showingMove = true } }
|
||
}
|
||
Section("物品信息") {
|
||
LabeledContent("数量", value: "\(detail.item.quantity)")
|
||
if !detail.item.aliases.isEmpty { LabeledContent("别名", value: detail.item.aliases.joined(separator: "、")) }
|
||
if !detail.item.notes.isEmpty { Text(detail.item.notes) }
|
||
}
|
||
ItemPhotos(store: store, item: itemID)
|
||
Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) }
|
||
if !detail.relations.isEmpty {
|
||
Section("关联物品") {
|
||
ForEach(detail.relations) { relation in
|
||
NavigationLink { ItemDetailView(store: store, itemID: relation.itemId) } label: {
|
||
LabeledContent(relation.name, value: relation.locationPath)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if !detail.moves.isEmpty {
|
||
Section("移位历史") {
|
||
ForEach(Array(detail.moves.enumerated()), id: \.offset) { _, move in
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
Text("\(move.fromPath) → \(move.toPath)")
|
||
Text(move.movedAt.prefix(10)).font(.caption).foregroundStyle(.secondary)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if store.canWrite { Button("删除物品", role: .destructive) { confirmingDelete = true }.disabled(busy) }
|
||
if let error { Text(error).foregroundStyle(.red); Button("刷新") { Task { await load() } } }
|
||
}
|
||
.navigationTitle(detail.item.name)
|
||
.toolbar {
|
||
ToolbarItem(placement: .topBarTrailing) {
|
||
if store.canWrite { Button("编辑") { showingEdit = true }.disabled(busy) }
|
||
}
|
||
}
|
||
.sheet(isPresented: $showingMove) { MoveEditor(store: store, item: detail.item) }
|
||
.sheet(isPresented: $showingEdit) { ItemEditor(store: store, existing: detail.item) }
|
||
.confirmationDialog("删除「\(detail.item.name)」?", isPresented: $confirmingDelete, titleVisibility: .visible) {
|
||
Button("删除物品和图片", role: .destructive) { Task { await archive(detail.item) } }
|
||
}
|
||
} else if let error {
|
||
ContentUnavailableView { Label("加载失败", systemImage: "exclamationmark.circle") }
|
||
description: { Text(error) } actions: { Button("重试") { Task { await load() } } }
|
||
} else { ProgressView("正在加载物品") }
|
||
}
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
.toolbar(.visible, for: .navigationBar)
|
||
.task(id: store.revision) { await load() }
|
||
}
|
||
|
||
private func load() async {
|
||
do { detail = try await store.get(store.itemPath(itemID)); error = nil }
|
||
catch where !Task.isCancelled { self.error = error.localizedDescription }
|
||
catch {}
|
||
}
|
||
|
||
private func archive(_ item: Item) async {
|
||
busy = true
|
||
defer { busy = false }
|
||
do { try await store.delete(store.itemPath(item.id) + "?version=\(item.version)"); dismiss() }
|
||
catch { self.error = error.localizedDescription }
|
||
}
|
||
}
|
||
|
||
private struct PreferenceEditor: View {
|
||
let store: InventoryStore
|
||
let detail: ItemDetail
|
||
let saved: (ItemDetail) -> Void
|
||
@State private var error: String?
|
||
@State private var busy = false
|
||
|
||
var body: some View {
|
||
Toggle("收藏", isOn: Binding(get: { detail.preference.favorite }, set: { value in
|
||
var preference = detail.preference
|
||
preference.favorite = value
|
||
Task { await save(preference) }
|
||
})).disabled(busy)
|
||
Picker("评分", selection: Binding(get: { detail.preference.rating ?? 0 }, set: { value in
|
||
var preference = detail.preference
|
||
preference.rating = value == 0 ? nil : value
|
||
Task { await save(preference) }
|
||
})) {
|
||
Text("未评分").tag(0)
|
||
ForEach(1...5, id: \.self) { Text("\($0) 分").tag($0) }
|
||
}.disabled(busy)
|
||
if let error { Text(error).foregroundStyle(.red) }
|
||
}
|
||
|
||
private func save(_ preference: ItemDetail.Preference) async {
|
||
busy = true
|
||
defer { busy = false }
|
||
do {
|
||
let result: ItemDetail.Preference = try await store.send(store.itemPath(detail.item.id) + "/preference", method: "PUT", preference)
|
||
saved(ItemDetail(item: detail.item, moves: detail.moves, relations: detail.relations, preference: result))
|
||
store.changed()
|
||
error = nil
|
||
} catch { self.error = error.localizedDescription }
|
||
}
|
||
}
|