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

471 lines
20 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
struct InventoryView: View {
let store: InventoryStore
let switcher: SpaceMenu.Actions
let onIntake: () -> Void
var body: some View {
NavigationStack {
ItemListView(store: store, onIntake: onIntake)
.toolbar {
if #available(iOS 26.0, *) {
ToolbarItem(placement: .topBarTrailing) {
SpaceMenu(current: store.space, actions: switcher)
}
.sharedBackgroundVisibility(.hidden)
} else {
ToolbarItem(placement: .topBarTrailing) {
SpaceMenu(current: store.space, actions: switcher)
}
}
}
}
}
}
struct SpaceMenu: View {
struct Actions {
let spaces: [Space]
let select: (Space) -> Void
let manage: () -> Void
}
let current: Space
let actions: Actions
var body: some View {
Menu {
Section("切换空间") {
ForEach(actions.spaces) { space in
Button {
if space.id != current.id { actions.select(space) }
} label: {
if space.id == current.id {
Label(space.name, systemImage: "checkmark")
} else {
Text(space.name)
}
}
}
}
Button(action: actions.manage) {
Label("我的空间", systemImage: "house")
}
} label: {
HStack(spacing: 4) {
Text(current.name)
.font(.subheadline.weight(.medium))
.lineLimit(1)
.frame(maxWidth: 94, alignment: .trailing)
Image(systemName: "chevron.down")
.font(.caption2.weight(.semibold))
.accessibilityHidden(true)
}
.foregroundStyle(Color.atlasBlue)
}
.accessibilityLabel("切换空间")
.accessibilityValue(current.name)
}
}
struct ItemListView: View {
let store: InventoryStore
let favoritesOnly: Bool
let onIntake: (() -> Void)?
@Environment(\.colorScheme) private var colorScheme
@State private var results: ItemListResults
@State private var query = ""
@FocusState private var searching: Bool
init(store: InventoryStore, favoritesOnly: Bool = false, onIntake: (() -> Void)? = nil) {
self.store = store
self.favoritesOnly = favoritesOnly
self.onIntake = onIntake
_results = State(initialValue: ItemListResults(firstPage: store.cachedItems(favorites: favoritesOnly)))
}
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, onIntake: {
searching = false
onIntake?()
})
}
.listStyle(.plain).scrollDismissesKeyboard(.interactively)
}
.navigationTitle(favoritesOnly ? "我的收藏" : "找物")
.navigationBarTitleDisplayMode(.inline)
.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, refresh: true) }
}
}
@MainActor
@Observable
final class ItemListResults {
struct LoadID: Hashable {
let query: String
let revision: 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(set) var displayedQuery: String?
private var displayedRevision: Int?
private var activeRequest: UUID?
init(firstPage: [Item]?) {
if let firstPage { showFirstPage(firstPage, query: "") }
}
private func showFirstPage(_ page: [Item], query: String) {
rows = page
more = page.count == 50
displayedQuery = query
loading = false
}
func loadID(query: String, revision: Int) -> LoadID {
LoadID(query: query.trimmingCharacters(in: .whitespacesAndNewlines), revision: revision)
}
func load(store: InventoryStore, query: String = "", favorites: Bool = false,
location: UUID? = nil, append: Bool = false, refresh: 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
if displayedQuery != input, input.isEmpty, let cache = store.cachedItems(favorites: favorites, location: location) {
showFirstPage(cache, query: input)
}
loading = 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, refresh: refresh)
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) }
more = page.count == 50 && rows.count <= 10000
} else if !refresh, displayedRevision == revision, displayedQuery == input,
rows.count > page.count, page.count == 50,
rows.prefix(page.count).map(\.id) == page.map(\.id) {
rows.replaceSubrange(0..<page.count, with: page)
} else {
showFirstPage(page, query: input)
}
displayedRevision = revision
} catch is CancellationError {
} catch where !Task.isCancelled && activeRequest == request {
if (error as? AtlasError)?.resourceUnavailable == true {
rows = []
more = false
displayedQuery = nil
}
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
var onIntake: (() -> Void)? = nil
private var input: String { query.trimmingCharacters(in: .whitespacesAndNewlines) }
var body: some View {
Section {
if location != nil, let onIntake, store.canWrite {
Button(action: onIntake) {
Label("在这里录入", systemImage: "plus.circle.fill")
.font(.subheadline.weight(.semibold))
.foregroundStyle(Color.atlasBlue)
}
}
if results.error == nil && (results.loading || results.displayedQuery != input) { ProgressView("加载中") }
else if results.rows.isEmpty && results.error == nil {
if location != nil {
Label("这个位置还没有物品", systemImage: "shippingbox")
.font(.subheadline).foregroundStyle(.secondary)
} else {
ContentUnavailableView(emptyTitle, systemImage: favorites ? "star" : "archivebox",
description: Text(emptyDescription))
}
}
ForEach(results.displayedQuery == input ? results.rows : []) { item in
NavigationLink { ItemDetailView(store: store, itemID: item.id, summary: item) } label: {
HStack(spacing: 12) {
PhotoImage(store: store, target: .item(item.id), photo: item.coverPhotoId, thumbnail: true,
placeholderSymbol: InventorySymbol.item(item.icon).image)
.frame(width: 46, height: 46).clipShape(.rect(cornerRadius: 8)).accessibilityHidden(true)
VStack(alignment: .leading, spacing: 3) {
Text(item.name).font(.headline)
Text(item.locationLabel).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 && results.displayedQuery == input {
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("重试") {
Task { await results.load(store: store, query: query, favorites: favorites, location: location, refresh: true) }
}
}
if let onIntake, !favorites, store.canWrite, input.isEmpty, location == nil,
results.displayedQuery == input, results.rows.isEmpty, results.error == nil {
Button(action: onIntake) { Label("添加物品", systemImage: "plus") }
}
} header: {
if location != nil { Text("这里的物品") }
}
}
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 summary: Item?
@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
init(store: InventoryStore, itemID: UUID, summary: Item? = nil) {
self.store = store
self.itemID = itemID
_summary = State(initialValue: summary)
_detail = State(initialValue: store.account.cached(store.itemPath(itemID)))
}
var body: some View {
Group {
if let item = detail?.item ?? summary {
List {
Section("当前位置") {
Label(item.locationLabel, systemImage: "location.fill").foregroundStyle(Color.atlasBlue)
if item.locationId != nil {
NavigationLink {
ItemLocationPlanView(store: store, item: item)
} label: {
Label("在平面图中查看", systemImage: "map")
}
}
if store.canWrite && detail != nil { Button(item.locationId == nil ? "设置位置" : "移位") { showingMove = true } }
}
Section("物品信息") {
LabeledContent("数量", value: "\(item.quantity)")
if let price = item.priceCents {
LabeledContent("购入单价", value: PurchasePrice.display(price))
}
if !item.aliases.isEmpty { LabeledContent("别名", value: item.aliases.joined(separator: "、")) }
if !item.notes.isEmpty { Text(item.notes) }
}
PhotoGallery(store: store, target: .item(itemID))
if let detail {
CommunityPublicationSection(store: store, item: item)
Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) }
}
if let detail, !detail.relations.isEmpty {
Section("关联物品") {
ForEach(detail.relations) { relation in
NavigationLink { ItemDetailView(store: store, itemID: relation.itemId) } label: {
LabeledContent(relation.name, value: relation.locationPath.isEmpty ? "未设置位置" : relation.locationPath)
}
}
}
}
if let detail, !detail.moves.isEmpty {
Section("移位历史") {
ForEach(Array(detail.moves.enumerated()), id: \.offset) { _, move in
VStack(alignment: .leading, spacing: 4) {
Text("\(move.fromPath.isEmpty ? "未设置位置" : move.fromPath) → \(move.toPath.isEmpty ? "未设置位置" : move.toPath)")
Text(move.movedAt.prefix(10)).font(.caption).foregroundStyle(.secondary)
}
}
}
}
if store.canWrite && detail != nil { Button("删除物品", role: .destructive) { confirmingDelete = true }.disabled(busy) }
if let error { Text(error).foregroundStyle(.red); Button("刷新") { Task { await load(refresh: true) } } }
}
.refreshable { await load(refresh: true) }
.navigationTitle(item.name)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
if store.canWrite && detail != nil { Button("编辑") { showingEdit = true }.disabled(busy) }
}
}
.sheet(isPresented: $showingMove) { MoveEditor(store: store, item: item) }
.sheet(isPresented: $showingEdit) { ItemEditor(store: store, existing: item) }
.confirmationDialog("删除「\(item.name)」?", isPresented: $confirmingDelete, titleVisibility: .visible) {
Button("删除物品和图片", role: .destructive) { Task { await archive(item) } }
} message: {
if item.published == true { Text("社区分享及其评论、评分也会删除。") }
}
} else if let error {
ContentUnavailableView { Label("加载失败", systemImage: "exclamationmark.circle") }
description: { Text(error) } actions: { Button("重试") { Task { await load(refresh: true) } } }
} else { ProgressView("正在加载物品") }
}
.navigationBarTitleDisplayMode(.inline)
.toolbar(.visible, for: .navigationBar)
.task(id: store.revision) { await load() }
}
private func load(refresh: Bool = false) async {
do {
detail = try await store.account.read(store.itemPath(itemID), refresh: refresh)
error = nil
} catch is CancellationError {
} catch where !Task.isCancelled {
if (error as? AtlasError)?.resourceUnavailable == true {
detail = nil
summary = nil
}
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)", affectsCommunity: item.published == true, changesItemCount: true)
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
@State private var note: String
init(store: InventoryStore, detail: ItemDetail, saved: @escaping (ItemDetail) -> Void) {
self.store = store
self.detail = detail
self.saved = saved
_note = State(initialValue: detail.preference.note)
}
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)
TextField("写下自己的使用感受", text: $note, axis: .vertical)
.lineLimit(2...4)
.disabled(busy)
.onChange(of: detail.preference.note) { _, updated in note = updated }
if note.trimmingCharacters(in: .whitespacesAndNewlines) != detail.preference.note {
Button("保存个人短评") {
var preference = detail.preference
preference.note = note
Task { await save(preference) }
}
.disabled(busy || note.utf16.count > 500)
}
if note.utf16.count > 500 {
Text("短评最多 500 字。").font(.footnote).foregroundStyle(.secondary)
}
if let error { Text(error).foregroundStyle(.red) }
}
private func save(_ preference: ItemDetail.Preference) async {
guard !busy else { return }
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 }
}
}