356 lines
17 KiB
Swift
356 lines
17 KiB
Swift
import SwiftUI
|
||
|
||
struct IntakeView: View {
|
||
let store: InventoryStore
|
||
@Environment(\.scenePhase) private var scenePhase
|
||
@AppStorage("atlas.voice.recording-mode") private var recordingMode: RecordingMode = .tap
|
||
@GestureState private var holdingMicrophone = false
|
||
@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 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
|
||
}
|
||
|
||
var body: some View {
|
||
NavigationStack {
|
||
if store.canWrite {
|
||
Form {
|
||
Section {
|
||
Button { showingAdd = true } label: { Label("手动添加物品", systemImage: "plus") }
|
||
.disabled(voice.phase != .idle)
|
||
}
|
||
Section("录音录入") {
|
||
voiceButton
|
||
if voice.phase == .recording || voice.phase == .finishing {
|
||
recordingProgress
|
||
}
|
||
if !voice.transcript.isEmpty {
|
||
Text(voice.transcript).foregroundStyle(.secondary)
|
||
}
|
||
if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) }
|
||
DisclosureGroup("录音设置") {
|
||
Picker("录音方式", selection: $recordingMode) {
|
||
Text("点按开始,再点结束").tag(RecordingMode.tap)
|
||
Text("按住录音,松手结束").tag(RecordingMode.hold)
|
||
}.disabled(voice.phase != .idle)
|
||
}
|
||
}
|
||
if voice.phase == .idle {
|
||
Section("录入文字") {
|
||
TextEditor(text: $text)
|
||
.frame(minHeight: 88)
|
||
.focused($typing)
|
||
.accessibilityLabel("录入文字")
|
||
.disabled(busy || operation != nil)
|
||
.overlay(alignment: .topLeading) {
|
||
if text.isEmpty {
|
||
Text("录音转写会显示在这里,也可以直接输入。")
|
||
.foregroundStyle(.secondary)
|
||
.padding(.horizontal, 5)
|
||
.padding(.vertical, 8)
|
||
.allowsHitTesting(false)
|
||
.accessibilityHidden(true)
|
||
}
|
||
}
|
||
if text.utf16.count > 4000 {
|
||
Text("录入文字达到长度上限,请分开整理。").font(.footnote).foregroundStyle(.secondary)
|
||
}
|
||
if !text.isEmpty && draft == nil {
|
||
Button("生成物品草稿") { typing = false; Task { await parse() } }
|
||
.disabled(!canParse)
|
||
}
|
||
}
|
||
}
|
||
if voice.phase == .idle, let draft {
|
||
Section("核对物品和位置") {
|
||
if draft.candidates.isEmpty {
|
||
Text(draft.status == "MODEL_UNAVAILABLE"
|
||
? "AI 暂不可用。你可以再试一次,或手动添加物品。"
|
||
: "还没整理出物品。可以修改原话,或让 AI 整理较长的描述。")
|
||
.font(.footnote).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) · 跳过").foregroundStyle(.secondary)
|
||
} else {
|
||
VStack(alignment: .leading) {
|
||
Text("\(candidate.name) ×\(candidate.quantity ?? 1)")
|
||
if let hint = candidate.location, !hint.isEmpty {
|
||
Text("原话位置:\(hint)").font(.footnote).foregroundStyle(.secondary)
|
||
}
|
||
Picker("存放位置", selection: Binding(get: { selections[index] }, set: { selections[index] = $0 })) {
|
||
Text("未选择").tag(nil as UUID?)
|
||
ForEach(store.locations) { place in Text(place.path).tag(Optional(place.id)) }
|
||
}
|
||
}.disabled(operation != nil)
|
||
}
|
||
}
|
||
if !draft.candidates.isEmpty {
|
||
Button("保存物品") { typing = false; Task { await submit(draft) } }
|
||
.disabled(busy || selections.isEmpty || operation != nil || voice.phase != .idle)
|
||
if selections.isEmpty {
|
||
Text("选好存放位置后就可以保存。").font(.footnote).foregroundStyle(.secondary)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if let operation {
|
||
Section {
|
||
Text(statusText(operation.status))
|
||
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) } }.disabled(busy)
|
||
} else {
|
||
Button("刷新进度") { Task { await poll(operation) } }.disabled(busy)
|
||
}
|
||
}
|
||
}
|
||
if busy { ProgressView() }
|
||
if let error { Text(error).foregroundStyle(.red) }
|
||
}
|
||
.dismissibleKeyboard(active: typing) { typing = false }
|
||
.navigationTitle("录入")
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
.toolbar {
|
||
ToolbarItem(placement: .topBarTrailing) {
|
||
Button { showingHelp = true } label: { Label("录入说明", systemImage: "questionmark.circle") }
|
||
.disabled(voice.phase != .idle)
|
||
}
|
||
}
|
||
.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 = [:]
|
||
}
|
||
}
|
||
.sheet(isPresented: $showingHelp) {
|
||
NavigationStack {
|
||
List {
|
||
Section("录音录入") {
|
||
Text("1. 点「开始录音」。也可以在设置里切换为按住说。")
|
||
Text("2. 说完点结束或松手。每次最多 25 秒,中间可以停顿。")
|
||
Text("3. 查看转写和草稿。可以修改文字,或点「用 AI 整理」。")
|
||
Text("4. 核对物品和存放位置,再点「保存物品」。")
|
||
}
|
||
Section("手动添加") {
|
||
Text("点「手动添加物品」,填写名称,选好存放位置再保存。")
|
||
}
|
||
}
|
||
.navigationTitle("怎么录入")
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
.toolbar {
|
||
ToolbarItem(placement: .confirmationAction) { Button("完成") { showingHelp = false } }
|
||
}
|
||
}
|
||
}
|
||
.sheet(isPresented: $showingAdd) { ItemEditor(store: store) }
|
||
} else {
|
||
ContentUnavailableView("当前空间只有查看权限", systemImage: "lock")
|
||
.navigationTitle("录入").navigationBarTitleDisplayMode(.inline)
|
||
}
|
||
}
|
||
}
|
||
|
||
@ViewBuilder
|
||
private var voiceButton: some View {
|
||
if recordingMode == .tap {
|
||
Button(action: toggleRecording) { recordingLabel }
|
||
.disabled(busy || operation != nil || voice.phase == .finishing)
|
||
} else {
|
||
recordingLabel
|
||
.foregroundStyle(Color.accentColor)
|
||
.gesture(DragGesture(minimumDistance: 0).updating($holdingMicrophone) { _, active, _ in
|
||
active = true
|
||
})
|
||
.onChange(of: holdingMicrophone) { _, active in
|
||
if active { beginRecording(whileHeld: true) } else { voice.stop() }
|
||
}
|
||
.accessibilityAddTraits(.isButton)
|
||
.accessibilityAction { toggleRecording() }
|
||
.accessibilityHint("使用旁白时,轻点两下开始,再轻点两下结束。")
|
||
.allowsHitTesting(!busy && operation == nil && voice.phase != .finishing)
|
||
}
|
||
}
|
||
|
||
private var recordingLabel: some View {
|
||
Group {
|
||
switch voice.phase {
|
||
case .idle: Label(recordingMode == .hold ? "按住录音" : "开始录音", systemImage: "mic.fill")
|
||
case .preparing: Label("准备麦克风…", systemImage: "mic")
|
||
case .recording: Label(recordingMode == .hold ? "松手结束" : "结束录音", systemImage: "stop.circle.fill")
|
||
case .finishing: Label("正在转写…", systemImage: "waveform")
|
||
}
|
||
}
|
||
.frame(maxWidth: .infinity, minHeight: 32, alignment: .leading)
|
||
.contentShape(Rectangle())
|
||
}
|
||
|
||
private var recordingProgress: some View {
|
||
VStack(alignment: .leading, spacing: 8) {
|
||
HStack {
|
||
Label(voice.phase == .finishing ? "完成转写中" : "录音中", systemImage: "waveform")
|
||
Spacer()
|
||
Text("\(voice.elapsedSeconds) / \(VoiceCapture.maximumDuration) 秒").monospacedDigit()
|
||
}
|
||
.font(.footnote)
|
||
ProgressView(value: Double(voice.elapsedSeconds), total: Double(VoiceCapture.maximumDuration))
|
||
.accessibilityHidden(true)
|
||
}
|
||
}
|
||
|
||
private func toggleRecording() {
|
||
if voice.phase == .idle { beginRecording() } else { voice.stop() }
|
||
}
|
||
|
||
private func beginRecording(whileHeld: Bool = false) {
|
||
guard !busy, operation == nil else { return }
|
||
typing = false
|
||
Task {
|
||
if whileHeld && !holdingMicrophone { return }
|
||
await voice.start(context: store.locations.map(\.name)) { phrase, complete in
|
||
let previous = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
text = previous.isEmpty ? phrase : previous + "\n" + phrase
|
||
if complete { Task { await parse() } }
|
||
}
|
||
}
|
||
}
|
||
|
||
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 = suggestedPlace(candidate.location) else { return nil }
|
||
return (index, place.id)
|
||
})
|
||
} catch { self.error = error.localizedDescription }
|
||
}
|
||
|
||
private func suggestedPlace(_ original: String?) -> Place? {
|
||
guard let original else { return nil }
|
||
func key(_ value: String) -> String {
|
||
value.folding(options: [.caseInsensitive, .widthInsensitive], locale: Locale(identifier: "zh-CN"))
|
||
.filter { !$0.isWhitespace && $0 != "/" }
|
||
}
|
||
let hint = key(original)
|
||
guard !hint.isEmpty else { return nil }
|
||
let spoken = hint.hasSuffix("了") ? String(hint.dropLast()) : hint
|
||
let exact = store.locations.filter { key($0.path) == hint }
|
||
let matches = exact.isEmpty ? store.locations.filter { key($0.path) == spoken } : exact
|
||
if !matches.isEmpty { return matches.count == 1 ? matches.first : nil }
|
||
let names = store.locations.filter { key($0.name) == hint || key($0.name) == spoken }
|
||
return names.count == 1 ? names.first : nil
|
||
}
|
||
|
||
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 let location = selections[index], candidate.action != "SKIP" else { return nil }
|
||
return ItemInput(name: candidate.name, quantity: candidate.quantity ?? 1, notes: "", locationId: location, 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()
|
||
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: "正在录入"
|
||
}
|
||
}
|
||
}
|