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

226 lines
9.5 KiB
Swift

import SwiftUI
private struct PlanSuggestion: Decodable {
let locationId: UUID?
let name: String
let geometry: LocationGeometry?
let note: String?
}
struct LocationPlanAssistant: View {
private struct Row: Identifiable {
let id: UUID
let suggestion: PlanSuggestion
let existing: Bool
}
let store: InventoryStore
let parent: Place?
let snapshot: LocationLayoutSnapshot
let locations: [LayoutLocation]
let apply: ([LayoutLocation]) -> Void
@Environment(\.dismiss) private var dismiss
@Environment(\.scenePhase) private var scenePhase
@FocusState private var typing: Bool
@State private var voice = VoiceCapture()
@State private var text = ""
@State private var rows: [Row] = []
@State private var included: Set<UUID> = []
@State private var request: UUID?
@State private var generating = false
@State private var error: String?
private var description: String { text.trimmingCharacters(in: .whitespacesAndNewlines) }
private var example: String {
parent == nil ? "例如:客厅在左边,右边是书房,沙发靠客厅上侧。"
: "例如:电视柜靠上边,书架靠右,左下角放一个收纳箱。"
}
private var merged: [LayoutLocation] {
var result = locations
for row in rows where included.contains(row.id) {
guard let geometry = row.suggestion.geometry else { continue }
if let index = result.firstIndex(where: { $0.id == row.id }) {
result[index].geometry = geometry
} else {
result.append(.init(id: row.id, name: row.suggestion.name,
icon: geometry.template.rawValue, geometry: geometry))
}
}
return result
}
private var roomOverlap: Bool {
let rooms = merged.compactMap(\.geometry).filter { $0.template.kind == .room }
return rooms.indices.contains { index in
rooms.dropFirst(index + 1).contains(where: rooms[index].overlaps)
}
}
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 14) {
Text(parent?.path ?? "整个空间").font(.subheadline).foregroundStyle(.secondary)
Text(example).font(.subheadline).foregroundStyle(.secondary)
descriptionInput
HStack {
Button(action: record) {
Label(voiceLabel, systemImage: voice.phase == .idle ? "mic" : "waveform")
}
.buttonStyle(.bordered)
.disabled(generating || voice.phase == .finishing)
Spacer()
Button("生成草稿") {
typing = false
request = UUID()
}
.buttonStyle(.borderedProminent)
.disabled(generating || voice.phase != .idle || description.isEmpty || description.utf16.count > 1600)
}
if generating { ProgressView("正在用本地模型生成平面图") }
if let error = voice.error { Text(error).font(.footnote).foregroundStyle(.secondary) }
if let error { Text(error).font(.footnote).foregroundStyle(.red) }
if !rows.isEmpty { review }
}
.padding(16)
.frame(maxWidth: 600)
.frame(maxWidth: .infinity)
}
.scrollDismissesKeyboard(.interactively)
.dismissibleKeyboard(active: typing) { typing = false }
.background(Color(uiColor: .systemGroupedBackground))
.navigationTitle("AI 建模")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
Button("应用草稿") { apply(merged); dismiss() }
.disabled(included.isEmpty || generating || roomOverlap || voice.phase != .idle)
}
}
}
.task(id: request) { if request != nil { await generate() } }
.onChange(of: text) {
rows = []
included = []
}
.onChange(of: scenePhase) { _, phase in if phase == .background { voice.cancel() } }
.onDisappear { voice.cancel() }
.interactiveDismissDisabled(voice.phase != .idle)
}
@ViewBuilder
private var descriptionInput: some View {
Group {
if voice.phase == .idle {
TextEditor(text: $text)
.frame(minHeight: 112)
.scrollContentBackground(.hidden)
.focused($typing)
.disabled(generating)
.accessibilityLabel("空间描述")
} else {
VStack(alignment: .leading, spacing: 8) {
Text([text, voice.transcript].filter { !$0.isEmpty }.joined(separator: "\n"))
.frame(maxWidth: .infinity, minHeight: 70, alignment: .topLeading)
ProgressView(value: Double(voice.elapsedSeconds), total: Double(VoiceCapture.maximumDuration)) {
Text("\(voice.elapsedSeconds) / \(VoiceCapture.maximumDuration) 秒").font(.caption)
}
}
}
}
.padding(10)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 12))
if text.utf16.count > 1600 {
Text("最多输入 1,600 字,可以分次生成。").font(.footnote).foregroundStyle(.secondary)
}
}
private var review: some View {
VStack(alignment: .leading, spacing: 10) {
Text("草稿预览").font(.headline)
LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: merged,
selected: nil, editing: false, open: { _ in }, highlighted: included)
.allowsHitTesting(false)
if roomOverlap {
Text("勾选的位置与当前编辑中的房间重叠,请先取消勾选其中一项。")
.font(.footnote).foregroundStyle(.red)
}
ForEach(rows) { row in
if row.suggestion.geometry != nil {
Toggle(isOn: Binding(get: { included.contains(row.id) }, set: { on in
if on { included.insert(row.id) } else { included.remove(row.id) }
})) {
rowLabel(row)
}
} else {
rowLabel(row).foregroundStyle(.secondary)
}
}
}
}
private func rowLabel(_ row: Row) -> some View {
VStack(alignment: .leading, spacing: 3) {
Text(row.suggestion.name).font(.subheadline.weight(.medium))
Text(([row.suggestion.geometry == nil ? "待确认" : (row.existing ? "调整位置" : "新增位置")] +
[row.suggestion.note].compactMap { $0 }).joined(separator: " · "))
.font(.caption).foregroundStyle(.secondary)
}
}
private var voiceLabel: String {
switch voice.phase {
case .idle: "语音描述"
case .preparing: "准备麦克风"
case .recording: "结束录音"
case .finishing: "正在转写"
}
}
private func record() {
if voice.phase == .idle {
typing = false
voice.start(context: locations.map(\.name)) { phrase, _ in
text = [description, phrase].filter { !$0.isEmpty }.joined(separator: "\n")
}
} else {
voice.stop()
}
}
private func generate() async {
struct Input: Encodable {
let parentId: UUID?
let version: UUID
let description: String
}
struct Output: Decodable { let changes: [PlanSuggestion] }
guard !generating else { return }
generating = true
error = nil
defer { generating = false }
do {
let payload = try JSONEncoder().encode(Input(parentId: parent?.id, version: snapshot.version, description: description))
let result = try await store.account.request(store.root + "/location-layout-drafts", method: "POST",
data: payload, timeout: 70)
let suggestions = try JSONDecoder().decode(Output.self, from: result)
try Task.checkCancellation()
var used = Set<UUID>()
rows = suggestions.changes.compactMap { suggestion in
let match = locations.first { place in
place.id == suggestion.locationId || place.name.caseInsensitiveCompare(suggestion.name) == .orderedSame
}
let id = match?.id ?? UUID()
guard used.insert(id).inserted else { return nil }
return Row(id: id, suggestion: suggestion, existing: match != nil)
}
included = Set(rows.filter { $0.suggestion.geometry != nil }.map(\.id))
if rows.isEmpty { error = "这段描述没有可摆放的位置。可以补充一个房间、区域或家具。" }
} catch where !Task.isCancelled {
self.error = error.localizedDescription
} catch {}
}
}