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

479 lines
21 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 IntakeView: View {
let store: InventoryStore
var initialLocation: Place? = nil
var onReturnToChooser: (() -> Void)? = nil
@Environment(\.scenePhase) private var scenePhase
@Environment(\.dismiss) private var dismiss
@AppStorage("atlas.voice.recording-mode") private var recordingMode: RecordingMode = .tap
@FocusState private var typing: Bool
@State private var voice = VoiceCapture()
@State private var text = ""
@State private var draft: Draft?
@State private var selections: [Int: UUID] = [:]
@State private var operation: Operation?
@State private var busy = false
@State private var supplementing = false
@State private var showingAdd = false
@State private var error: String?
@State private var showingHelp = false
private enum RecordingMode: String {
case tap, hold
}
private struct Draft: Decodable {
let id: UUID
let originalText: String
let candidates: [Candidate]
let status: String
let version: Int
}
private struct Candidate: Decodable {
let name: String
let quantity: Int?
let action: String
let location: String?
}
private struct Operation: Decodable { let id: UUID; let status: String }
private struct Confirm: Encodable { let version: Int; let items: [ItemInput] }
private var canParse: Bool {
!busy && voice.phase == .idle && operation == nil && text.utf16.count <= 4000 &&
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private var canReview: Bool { draft?.candidates.contains { $0.action != "SKIP" } == true }
var body: some View {
if let onReturnToChooser {
if showingAdd {
ItemEditor(store: store, initialLocation: initialLocation?.id, onClose: { saved in
showingAdd = false
if saved { onReturnToChooser() }
})
} else {
intake
}
} else {
intake.sheet(isPresented: $showingAdd) {
ItemEditor(store: store, initialLocation: initialLocation?.id)
}
}
}
private var intake: some View {
ScrollViewReader { scroll in
ScrollView {
VStack(alignment: .leading, spacing: 14) {
if let initialLocation {
Label(initialLocation.path, systemImage: "mappin")
.font(.subheadline).foregroundStyle(.secondary)
.accessibilityLabel("默认位置," + initialLocation.path)
}
if operation == nil {
inputCard.id("intake.original")
if let draft, !supplementing, voice.phase == .idle {
reviewCard(draft).id(draft.id)
}
if voice.phase == .idle && !supplementing { manualEntry }
}
if let operation { operationCard(operation) }
if let error { Text(error).font(.callout).foregroundStyle(.red) }
}
.frame(maxWidth: 560)
.padding(16)
.frame(maxWidth: .infinity)
}
.onChange(of: draft?.id) { _, id in
if let id { withAnimation { scroll.scrollTo(id) } }
}
.onChange(of: supplementing) { _, active in
if active { withAnimation { scroll.scrollTo("intake.original", anchor: .top) } }
}
}
.background(Color(uiColor: .systemGroupedBackground))
.safeAreaInset(edge: .bottom, spacing: 0) {
if !typing && operation == nil { bottomBar }
}
.dismissibleKeyboard(active: typing) { typing = false }
.navigationTitle("录入物品")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button(onReturnToChooser == nil ? "关闭" : "返回选择") {
if let onReturnToChooser { onReturnToChooser() }
else { dismiss() }
}
.disabled(busy || voice.phase != .idle)
}
ToolbarItemGroup(placement: .topBarTrailing) {
Menu {
Picker("录音方式", selection: $recordingMode) {
Text("点按开始,再点结束").tag(RecordingMode.tap)
Text("按住说,松手结束").tag(RecordingMode.hold)
}
} label: {
Label("录音设置", systemImage: "slider.horizontal.3")
}
.disabled(voice.phase != .idle)
Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") }
.disabled(voice.phase != .idle)
}
}
.interactiveDismissDisabled(busy || voice.phase != .idle)
.sensoryFeedback(.start, trigger: voice.phase) { _, phase in phase == .recording }
.onDisappear { voice.cancel() }
.onChange(of: scenePhase) { _, phase in
if phase == .background { voice.cancel() }
}
.onChange(of: text) { _, updated in
if operation == nil && draft?.originalText != updated {
draft = nil
selections = [:]
supplementing = false
}
}
.sheet(isPresented: $showingHelp) { help }
}
private var bottomBar: some View {
VStack(spacing: 8) {
if voice.phase == .recording || voice.phase == .finishing {
ProgressView(value: Double(voice.elapsedSeconds), total: Double(VoiceCapture.maximumDuration)) {
Text("\(voice.elapsedSeconds) / \(VoiceCapture.maximumDuration) 秒")
.font(.caption.monospacedDigit())
}
}
if let draft, canReview, !supplementing, voice.phase == .idle {
Button { Task { await submit(draft) } } label: {
primaryLabel(busy ? "正在保存" : "保存物品", symbol: "checkmark",
color: .atlasBlue, enabled: !busy)
}
.buttonStyle(.plain)
.disabled(busy)
} else {
voiceButton
}
}
.frame(maxWidth: 560)
.padding(.horizontal, 16)
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(.bar)
.overlay(alignment: .top) { Divider() }
}
private var manualEntry: some View {
Button { showingAdd = true } label: {
HStack(spacing: 13) {
Image(systemName: "square.and.pencil")
.font(.headline)
.foregroundStyle(Color.atlasBlue)
.frame(width: 36, height: 36)
.background(Color.atlasBlue.opacity(0.10), in: .rect(cornerRadius: 10))
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 3) {
Text("手动添加").font(.headline).foregroundStyle(.primary)
Text("填写名称、照片和备注").font(.subheadline).foregroundStyle(.secondary)
}
Spacer()
Image(systemName: "chevron.right").font(.footnote.weight(.semibold))
.foregroundStyle(.tertiary).accessibilityHidden(true)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(14)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16))
.contentShape(.rect(cornerRadius: 16))
}
.buttonStyle(.plain)
.accessibilityIdentifier("intake.manual")
.disabled(voice.phase != .idle || busy)
}
private var inputCard: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("物品描述").font(.headline).accessibilityAddTraits(.isHeader)
Spacer()
if supplementing {
Button("取消补录") { supplementing = false }
.disabled(voice.phase != .idle)
} else if draft != nil {
Button("再说一句", action: supplement)
.disabled(busy || typing)
}
}
.font(.subheadline)
if voice.phase == .idle {
TextField("例如:把两根数据线放在书房抽屉", text: $text, axis: .vertical)
.lineLimit(3...7)
.focused($typing)
.accessibilityLabel("物品描述")
.disabled(busy)
} else {
let original = [text, voice.transcript].filter { !$0.isEmpty }.joined(separator: "\n")
Text(original.isEmpty ? "听到的文字会显示在这里。" : original)
.foregroundStyle(original.isEmpty ? Color.secondary : Color.primary)
.lineLimit(3...)
.frame(maxWidth: .infinity, alignment: .leading)
}
if text.utf16.count > 4000 {
Text("最多 4,000 字,可以分开整理。").font(.footnote).foregroundStyle(.secondary)
}
if !text.isEmpty && draft == nil && !supplementing && voice.phase == .idle {
Button("整理成物品草稿") { typing = false; Task { await parse() } }.disabled(!canParse)
}
if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) }
if busy && !canReview { ProgressView("正在整理") }
}
.padding(16)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16))
}
private func reviewCard(_ draft: Draft) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text("核对物品").font(.headline).accessibilityAddTraits(.isHeader)
if draft.candidates.isEmpty {
Text(draft.status == "MODEL_UNAVAILABLE"
? "AI 暂不可用,可以重试或手动添加。"
: "这段话还没整理出物品,可以修改原话或用 AI 整理。")
.font(.callout).foregroundStyle(.secondary)
Button("用 AI 整理") { typing = false; Task { await parse(source: "MODEL") } }
.disabled(!canParse)
}
ForEach(draft.candidates.indices, id: \.self) { index in
let candidate = draft.candidates[index]
if candidate.action == "SKIP" {
Text("\(candidate.name) · 跳过").font(.callout).foregroundStyle(.secondary)
} else {
VStack(alignment: .leading, spacing: 4) {
Text("\(candidate.name) ×\(candidate.quantity ?? 1)").font(.subheadline.weight(.semibold))
if let hint = candidate.location, !hint.isEmpty, selections[index] == nil {
Text("原话位置 · " + hint).font(.footnote).foregroundStyle(.secondary)
}
LocationPicker(store: store,
selection: Binding(get: { selections[index] }, set: { selections[index] = $0 }),
title: "存放位置", allowsClearing: true)
}
.padding(12)
.background(Color(uiColor: .systemGroupedBackground), in: .rect(cornerRadius: 12))
}
}
}
.padding(16)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16))
}
private func operationCard(_ operation: Operation) -> some View {
VStack(alignment: .leading, spacing: 10) {
Text(statusText(operation.status)).font(.headline)
if busy {
ProgressView()
} else if operation.status == "COMPLETED" {
Button("继续录入") { reset(clearText: true) }
} else if ["FAILED", "REJECTED"].contains(operation.status) {
Button("返回核对") { reset(clearText: false) }
} else if operation.status == "NEEDS_REVIEW" {
Button("重试交付") { Task { await retry(operation) } }
} else {
Button("刷新进度") { Task { await poll(operation) } }
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(16)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 16))
}
private var help: some View {
NavigationStack {
List {
Section("智能录入") {
Text("1. 在屏幕底部开始录音。右上角可以切换录音方式。")
Text("2. 看到录音状态再说。一次最多 25 秒,可以停顿。")
Text("3. 说完松手或再次点按。可以修改转写,也可以直接打字。")
Text("4. 可以再说一句,也可以核对物品后在底部保存。位置可以调整、清除或留空。")
}
Section("手动添加") {
Text("填写名称就能录入单件物品。需要时再加位置、照片或备注。")
}
}
.navigationTitle("怎么录入")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } }
}
}
}
private var voiceEnabled: Bool { !busy && operation == nil && voice.phase != .finishing }
@ViewBuilder
private var voiceButton: some View {
if recordingMode == .tap {
Button(action: toggleRecording) { recordingLabel }
.buttonStyle(.plain)
.disabled(!voiceEnabled)
} else {
recordingLabel
.accessibilityHidden(true)
.overlay {
HoldRecordingControl(label: recordingTitle, enabled: voiceEnabled,
onPress: beginRecording, onRelease: { voice.stop() },
onAccessibilityActivate: toggleRecording)
}
}
}
private var recordingTitle: String {
switch voice.phase {
case .idle:
if recordingMode == .hold { "按住说" }
else { supplementing ? "开始补录" : "开始录音" }
case .preparing: "麦克风准备中"
case .recording: recordingMode == .hold ? "松手结束" : "结束录音"
case .finishing: "正在转写"
}
}
private var recordingLabel: some View {
primaryLabel(recordingTitle, symbol: voice.phase == .recording ? "waveform" : "mic.fill",
color: voice.phase == .recording ? .atlasNavy : .atlasBlue, enabled: voiceEnabled)
}
private func primaryLabel(_ title: String, symbol: String, color: Color, enabled: Bool) -> some View {
Label(title, systemImage: symbol)
.font(.headline)
.frame(maxWidth: .infinity, minHeight: 54)
.foregroundStyle(.white)
.background(color, in: .rect(cornerRadius: 14))
.opacity(enabled ? 1 : 0.55)
.contentShape(Rectangle())
}
private func toggleRecording() {
if voice.phase == .idle { beginRecording() } else { voice.stop() }
}
private func supplement() {
supplementing = true
if recordingMode == .tap { beginRecording() }
}
private func beginRecording() {
guard voiceEnabled, voice.phase == .idle else { return }
typing = false
voice.start(context: store.locations.map(\.name)) { phrase, complete in
text = transcript(appending: phrase)
supplementing = false
if complete { Task { await parse() } }
}
}
private func transcript(appending phrase: String) -> String {
let previous = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !previous.isEmpty else { return phrase }
guard !phrase.isEmpty else { return previous }
if supplementing, let draft, draft.candidates.count <= 1, draft.candidates.first?.location == nil,
let verb = ["放在", "放到", "放进", "收进", "放"].first(where: { phrase.hasPrefix($0) }) {
let hint = String(phrase.dropFirst(verb.count)).trimmingCharacters(in: .whitespacesAndNewlines)
let subject = previous.trimmingCharacters(in: CharacterSet(charactersIn: "。.!!"))
// Keep a standalone location with its item so it can still use the single-sentence parser.
if !subject.isEmpty && !hint.isEmpty &&
(verb != "放" || IntakeLocationMatcher.match(hint, locations: store.locations,
defaultID: initialLocation?.id) != nil) {
return subject + (verb == "放" ? "放在" : verb) + hint
}
}
return previous + "\n" + phrase
}
private func parse(source: String = "VOICE") async {
guard canParse else { return }
let original = text
busy = true
defer { busy = false }
error = nil
do {
try await store.refreshLocations()
let result: Draft = try await store.send(store.root + "/drafts", ["text": original, "source": source])
guard text == original else { return }
draft = result
selections = Dictionary(uniqueKeysWithValues: result.candidates.enumerated().compactMap { index, candidate in
guard candidate.action != "SKIP",
let place = IntakeLocationMatcher.match(candidate.location, locations: store.locations,
defaultID: initialLocation?.id) else { return nil }
return (index, place)
})
} catch { self.error = error.localizedDescription }
}
private func submit(_ draft: Draft) async {
guard draft.originalText == text, !busy, operation == nil, voice.phase == .idle else { return }
let items = draft.candidates.enumerated().compactMap { index, candidate -> ItemInput? in
guard candidate.action != "SKIP" else { return nil }
return ItemInput(name: candidate.name, quantity: candidate.quantity ?? 1, notes: "",
locationId: selections[index], aliases: [])
}
guard !items.isEmpty else { return }
busy = true
defer { busy = false }
do {
let accepted: Operation = try await store.send(store.root + "/drafts/\(draft.id)/confirm",
Confirm(version: draft.version, items: items))
operation = accepted
await poll(accepted)
} catch { self.error = error.localizedDescription }
}
private func reset(clearText: Bool) {
if clearText { text = "" }
draft = nil
selections = [:]
operation = nil
error = nil
}
private func retry(_ operation: Operation) async {
busy = true
defer { busy = false }
do {
let path = store.root + "/operations/\(operation.id)/retry"
let bytes = try await store.account.request(path, method: "POST")
let accepted = try JSONDecoder().decode(Operation.self, from: bytes)
self.operation = accepted
await poll(accepted)
} catch { self.error = error.localizedDescription }
}
private func poll(_ current: Operation) async {
busy = true
defer { busy = false }
error = nil
do {
for _ in 0..<12 {
let status: Operation = try await store.get(store.root + "/operations/\(current.id)")
operation = status
if status.status == "COMPLETED" {
store.changed(inventorySummaryChanged: true)
onReturnToChooser?()
return
}
if ["FAILED", "REJECTED", "NEEDS_REVIEW"].contains(status.status) { return }
try await Task.sleep(for: .seconds(1))
}
} catch { self.error = error.localizedDescription }
}
private func statusText(_ status: String) -> String {
switch status {
case "COMPLETED": "物品已录入"
case "FAILED", "REJECTED": "录入失败,请核对空间权限与位置"
case "NEEDS_REVIEW": "录入结果待核对,可以重试交付"
default: "正在录入"
}
}
}