503 lines
21 KiB
Swift
503 lines
21 KiB
Swift
import SwiftUI
|
|
|
|
enum LocationTemplate: String, CaseIterable, Codable, Identifiable {
|
|
case livingRoom = "LIVING_ROOM", bedroom = "BEDROOM", study = "STUDY", kitchen = "KITCHEN"
|
|
case bathroom = "BATHROOM", room = "ROOM", entry = "ENTRY", balcony = "BALCONY", area = "AREA"
|
|
case sofa = "SOFA", bed = "BED", desk = "DESK", tvStand = "TV_STAND", wardrobe = "WARDROBE"
|
|
case bookcase = "BOOKCASE", shelf = "SHELF", table = "TABLE", storageBox = "STORAGE_BOX"
|
|
|
|
var id: String { rawValue }
|
|
|
|
var name: String {
|
|
switch self {
|
|
case .livingRoom: "客厅"
|
|
case .bedroom: "卧室"
|
|
case .study: "书房"
|
|
case .kitchen: "厨房"
|
|
case .bathroom: "卫生间"
|
|
case .room: "房间"
|
|
case .entry: "玄关"
|
|
case .balcony: "阳台"
|
|
case .area: "开放区域"
|
|
case .sofa: "转角沙发"
|
|
case .bed: "床"
|
|
case .desk: "书桌"
|
|
case .tvStand: "电视柜"
|
|
case .wardrobe: "衣柜"
|
|
case .bookcase: "书架"
|
|
case .shelf: "层架"
|
|
case .table: "边几"
|
|
case .storageBox: "收纳箱"
|
|
}
|
|
}
|
|
|
|
enum Kind { case room, area, furniture }
|
|
|
|
var kind: Kind {
|
|
switch self {
|
|
case .livingRoom, .bedroom, .study, .kitchen, .bathroom, .room: .room
|
|
case .entry, .balcony, .area: .area
|
|
default: .furniture
|
|
}
|
|
}
|
|
|
|
var dimensions: (width: Int, depth: Int) {
|
|
switch self {
|
|
case .livingRoom: (4000, 3400)
|
|
case .bedroom, .study, .room: (3000, 2800)
|
|
case .kitchen: (2600, 2400)
|
|
case .bathroom: (2100, 1900)
|
|
case .entry, .balcony, .area: (2200, 1500)
|
|
case .sofa: (2300, 1400)
|
|
case .bed: (1600, 2100)
|
|
case .desk, .tvStand: (1400, 620)
|
|
case .wardrobe: (1600, 650)
|
|
case .bookcase, .shelf: (1100, 450)
|
|
case .table: (600, 600)
|
|
case .storageBox: (500, 450)
|
|
}
|
|
}
|
|
|
|
static func suggested(for slot: LayoutLocation, isRoot: Bool) -> Self {
|
|
if slot.name.contains("沙发") { return .sofa }
|
|
if let known = LocationTemplate(rawValue: slot.icon), isRoot || known.kind != .room { return known }
|
|
return isRoot ? .room : .storageBox
|
|
}
|
|
}
|
|
|
|
struct LocationGeometry: Codable, Equatable {
|
|
var template: LocationTemplate
|
|
var xMm: Int
|
|
var yMm: Int
|
|
var widthMm: Int
|
|
var depthMm: Int
|
|
var rotation = 0
|
|
|
|
var right: Int { xMm + widthMm }
|
|
var bottom: Int { yMm + depthMm }
|
|
|
|
func overlaps(_ other: Self) -> Bool {
|
|
xMm < other.right && other.xMm < right && yMm < other.bottom && other.yMm < bottom
|
|
}
|
|
}
|
|
|
|
struct LayoutLocation: Decodable, Identifiable, Equatable {
|
|
let id: UUID
|
|
let name: String
|
|
let icon: String
|
|
var geometry: LocationGeometry?
|
|
}
|
|
|
|
struct LocationLayoutSnapshot: Decodable {
|
|
let version: UUID
|
|
let widthMm: Int
|
|
let depthMm: Int
|
|
let locations: [LayoutLocation]
|
|
}
|
|
|
|
struct LocationPlacement: Encodable {
|
|
let id: UUID
|
|
let newName: String?
|
|
let geometry: LocationGeometry
|
|
}
|
|
|
|
extension InventoryStore {
|
|
func locationLayout(parent: UUID?, refresh: Bool = false) async throws -> LocationLayoutSnapshot {
|
|
let query = parent.map { "?parentId=\($0)" } ?? ""
|
|
return try await account.read(root + "/location-layout" + query, refresh: refresh)
|
|
}
|
|
|
|
func saveLocationLayout(parent: UUID?, version: UUID, placements: [LocationPlacement]) async throws -> LocationLayoutSnapshot {
|
|
struct Input: Encodable {
|
|
let parentId: UUID?
|
|
let version: UUID
|
|
let placements: [LocationPlacement]
|
|
}
|
|
let snapshot: LocationLayoutSnapshot = try await send(root + "/location-layout", method: "PUT",
|
|
Input(parentId: parent, version: version, placements: placements))
|
|
changed()
|
|
return snapshot
|
|
}
|
|
}
|
|
|
|
struct LocationPlanSection: View {
|
|
let store: InventoryStore
|
|
let parent: Place?
|
|
let open: (UUID) -> Void
|
|
@State private var snapshot: LocationLayoutSnapshot?
|
|
@State private var error: String?
|
|
@State private var editing = false
|
|
|
|
var body: some View {
|
|
Section {
|
|
if let snapshot {
|
|
let placed = snapshot.locations.filter { $0.geometry != nil }
|
|
if placed.isEmpty {
|
|
ContentUnavailableView("还没有摆放位置", systemImage: "square.dashed",
|
|
description: Text(store.canWrite ? "可以摆放已有位置,或用模板新建。" : "空间成员摆放后会显示在这里。"))
|
|
} else {
|
|
LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed,
|
|
selected: nil, editing: false, open: open)
|
|
DisclosureGroup("图上的位置") {
|
|
ForEach(placed) { place in
|
|
Button(place.name) { open(place.id) }.buttonStyle(.borderless)
|
|
}
|
|
}
|
|
}
|
|
let unplaced = snapshot.locations.filter { $0.geometry == nil }
|
|
if !unplaced.isEmpty {
|
|
DisclosureGroup("未摆放 \(unplaced.count) 处") {
|
|
ForEach(unplaced) { place in
|
|
Button(place.name) { open(place.id) }.buttonStyle(.borderless)
|
|
}
|
|
}
|
|
}
|
|
if store.canWrite {
|
|
Button { editing = true } label: { Label("编辑布局", systemImage: "square.and.pencil") }
|
|
}
|
|
} else if error == nil {
|
|
ProgressView("正在读取俯视图")
|
|
}
|
|
if let error {
|
|
Text(error).font(.footnote).foregroundStyle(.secondary)
|
|
Button("重新读取") { Task { await load(refresh: true) } }
|
|
}
|
|
} header: {
|
|
LocationLevelHeading(level: parent == nil ? .room : .furniture)
|
|
}
|
|
.task(id: store.revision) { await load() }
|
|
.sheet(isPresented: $editing) {
|
|
if let snapshot {
|
|
LocationPlanEditor(store: store, parent: parent, snapshot: snapshot) { saved in
|
|
self.snapshot = saved
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func load(refresh: Bool = false) async {
|
|
do {
|
|
snapshot = try await store.locationLayout(parent: parent?.id, refresh: refresh)
|
|
error = nil
|
|
} catch where !Task.isCancelled {
|
|
if (error as? AtlasError)?.resourceUnavailable == true { snapshot = nil }
|
|
self.error = error.localizedDescription
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
private struct LocationPlanEditor: View {
|
|
let store: InventoryStore
|
|
let parent: Place?
|
|
let onSave: (LocationLayoutSnapshot) -> Void
|
|
@Environment(\.dismiss) private var dismiss
|
|
@State private var snapshot: LocationLayoutSnapshot
|
|
@State private var locations: [LayoutLocation]
|
|
@State private var selection: UUID?
|
|
@State private var choosingTemplate = false
|
|
@State private var saving = false
|
|
@State private var error: String?
|
|
@State private var conflicted = false
|
|
@State private var confirmingReload = false
|
|
@FocusState private var dimensionField: String?
|
|
|
|
init(store: InventoryStore, parent: Place?, snapshot: LocationLayoutSnapshot,
|
|
onSave: @escaping (LocationLayoutSnapshot) -> Void) {
|
|
self.store = store
|
|
self.parent = parent
|
|
self.onSave = onSave
|
|
_snapshot = State(initialValue: snapshot)
|
|
_locations = State(initialValue: snapshot.locations)
|
|
}
|
|
|
|
private var placed: [LayoutLocation] { locations.filter { $0.geometry != nil } }
|
|
private var unplaced: [LayoutLocation] { locations.filter { $0.geometry == nil } }
|
|
|
|
var body: some View {
|
|
NavigationStack {
|
|
ScrollView {
|
|
VStack(alignment: .leading, spacing: 16) {
|
|
if let parent { Text(parent.path).font(.subheadline).foregroundStyle(.secondary) }
|
|
LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed,
|
|
selected: selection, editing: true, open: { selection = $0 }, change: change)
|
|
if let selection, let place = locations.first(where: { $0.id == selection }), let geometry = place.geometry {
|
|
controls(for: place, geometry: geometry)
|
|
}
|
|
HStack {
|
|
if !unplaced.isEmpty {
|
|
Menu {
|
|
ForEach(unplaced) { place in
|
|
Button(place.name) { placeExisting(place) }
|
|
}
|
|
} label: { Label("摆放已有位置", systemImage: "square.dashed") }
|
|
}
|
|
Button { choosingTemplate = true } label: {
|
|
Label("添加模板", systemImage: "plus")
|
|
}
|
|
}
|
|
.buttonStyle(.bordered)
|
|
if let error {
|
|
Text(error).font(.footnote).foregroundStyle(.red).accessibilityAddTraits(.updatesFrequently)
|
|
if conflicted { Button("加载最新布局") { confirmingReload = true } }
|
|
}
|
|
}
|
|
.padding(16)
|
|
.frame(maxWidth: 600)
|
|
.frame(maxWidth: .infinity)
|
|
}
|
|
.background(Color(uiColor: .systemGroupedBackground))
|
|
.dismissibleKeyboard(active: dimensionField != nil) { dimensionField = nil }
|
|
.disabled(saving)
|
|
.navigationTitle("编辑布局")
|
|
.navigationBarTitleDisplayMode(.inline)
|
|
.toolbar {
|
|
ToolbarItem(placement: .cancellationAction) {
|
|
Button("取消") { dismiss() }.disabled(saving)
|
|
}
|
|
ToolbarItem(placement: .confirmationAction) {
|
|
Button("保存") {
|
|
dimensionField = nil
|
|
Task { await save() }
|
|
}
|
|
.disabled(saving || locations == snapshot.locations)
|
|
}
|
|
}
|
|
.sheet(isPresented: $choosingTemplate) {
|
|
LocationTemplatePicker(isRoot: parent == nil, names: Set(locations.map(\.name)), add: add)
|
|
}
|
|
.confirmationDialog("重新加载最新布局?", isPresented: $confirmingReload, titleVisibility: .visible) {
|
|
Button("重新加载", role: .destructive) { Task { await reload() } }
|
|
} message: { Text("重新加载会舍弃本次未保存的调整。") }
|
|
}
|
|
.interactiveDismissDisabled(saving || locations != snapshot.locations)
|
|
}
|
|
|
|
private func controls(for place: LayoutLocation, geometry: LocationGeometry) -> some View {
|
|
VStack(alignment: .leading, spacing: 10) {
|
|
HStack(alignment: .firstTextBaseline) {
|
|
Text(place.name).font(.headline)
|
|
Spacer()
|
|
Menu {
|
|
ForEach(LocationTemplate.allCases.filter { parent == nil || $0.kind != .room }) { template in
|
|
Button(template.name) {
|
|
var updated = geometry
|
|
updated.template = template
|
|
change(place.id, updated)
|
|
}
|
|
}
|
|
} label: {
|
|
Label(geometry.template.name, systemImage: "chevron.down")
|
|
.font(.subheadline)
|
|
}
|
|
.accessibilityLabel("更换模板,当前为" + geometry.template.name)
|
|
}
|
|
Grid(horizontalSpacing: 10, verticalSpacing: 6) {
|
|
GridRow {
|
|
measurement("宽度", at: \.widthMm, in: place.id, value: geometry.widthMm)
|
|
measurement("深度", at: \.depthMm, in: place.id, value: geometry.depthMm)
|
|
}
|
|
GridRow {
|
|
measurement("横向位置", at: \.xMm, in: place.id, value: geometry.xMm)
|
|
measurement("纵向位置", at: \.yMm, in: place.id, value: geometry.yMm)
|
|
}
|
|
}
|
|
HStack {
|
|
Button("旋转 90°", systemImage: "rotate.right") {
|
|
var turned = geometry
|
|
turned.widthMm = geometry.depthMm
|
|
turned.depthMm = geometry.widthMm
|
|
turned.rotation = (geometry.rotation + 90) % 360
|
|
guard turned.widthMm <= snapshot.widthMm && turned.depthMm <= snapshot.depthMm else {
|
|
error = "旋转后超出画布。请先缩小尺寸。"
|
|
return
|
|
}
|
|
change(place.id, turned)
|
|
}
|
|
Spacer()
|
|
Button("移出俯视图", role: .destructive) { remove(place.id) }
|
|
}
|
|
.font(.subheadline)
|
|
}
|
|
.padding(14)
|
|
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 14))
|
|
}
|
|
|
|
private func measurement(_ label: String, at key: WritableKeyPath<LocationGeometry, Int>,
|
|
in id: UUID, value: Int) -> some View {
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
Text(label + "(厘米)").font(.caption).foregroundStyle(.secondary)
|
|
TextField(label, value: Binding(get: { value / 10 }, set: { number in
|
|
guard let current = locations.first(where: { $0.id == id })?.geometry else { return }
|
|
var updated = current
|
|
updated[keyPath: key] = min(2400, max(0, number)) * 10
|
|
change(id, updated)
|
|
}), format: .number.grouping(.never))
|
|
.keyboardType(.numberPad)
|
|
.textFieldStyle(.roundedBorder)
|
|
.focused($dimensionField, equals: label)
|
|
.accessibilityLabel(label + ",厘米")
|
|
}
|
|
}
|
|
|
|
private func change(_ id: UUID, _ proposed: LocationGeometry) {
|
|
guard let index = locations.firstIndex(where: { $0.id == id }) else { return }
|
|
var geometry = proposed
|
|
geometry.widthMm = min(snapshot.widthMm, max(100, geometry.widthMm))
|
|
geometry.depthMm = min(snapshot.depthMm, max(100, geometry.depthMm))
|
|
geometry.xMm = min(snapshot.widthMm - geometry.widthMm, max(0, geometry.xMm))
|
|
geometry.yMm = min(snapshot.depthMm - geometry.depthMm, max(0, geometry.yMm))
|
|
locations[index].geometry = geometry
|
|
selection = id
|
|
if !conflicted { error = nil }
|
|
}
|
|
|
|
private func placeExisting(_ place: LayoutLocation) {
|
|
let template = LocationTemplate.suggested(for: place, isRoot: parent == nil)
|
|
if let geometry = suggestedPlacement(template) { change(place.id, geometry) }
|
|
}
|
|
|
|
private func add(_ template: LocationTemplate, _ name: String) {
|
|
guard let geometry = suggestedPlacement(template) else { return }
|
|
let id = UUID()
|
|
locations.append(.init(id: id, name: name, icon: template.rawValue, geometry: geometry))
|
|
selection = id
|
|
}
|
|
|
|
private func suggestedPlacement(_ template: LocationTemplate) -> LocationGeometry? {
|
|
let preferred = template.dimensions
|
|
let geometries = placed.compactMap(\.geometry)
|
|
let occupied = geometries.filter { geometry in
|
|
template.kind == .room ? geometry.template.kind == .room : geometry.template.kind == template.kind
|
|
}
|
|
for divisor in [1, 2] {
|
|
let width = min(snapshot.widthMm, max(100, preferred.width / divisor))
|
|
let depth = min(snapshot.depthMm, max(100, preferred.depth / divisor))
|
|
for y in stride(from: 0, through: snapshot.depthMm - depth, by: 200) {
|
|
for x in stride(from: 0, through: snapshot.widthMm - width, by: 200) {
|
|
let geometry = LocationGeometry(template: template, xMm: x, yMm: y, widthMm: width, depthMm: depth)
|
|
if !occupied.contains(where: { geometry.overlaps($0) }) { return geometry }
|
|
}
|
|
}
|
|
}
|
|
error = "画布没有足够空位。请先调整已有的位置。"
|
|
return nil
|
|
}
|
|
|
|
private func remove(_ id: UUID) {
|
|
guard let index = locations.firstIndex(where: { $0.id == id }) else { return }
|
|
if snapshot.locations.contains(where: { $0.id == id }) { locations[index].geometry = nil }
|
|
else { locations.remove(at: index) }
|
|
selection = nil
|
|
}
|
|
|
|
private func save() async {
|
|
guard !saving else { return }
|
|
saving = true
|
|
error = nil
|
|
defer { saving = false }
|
|
let existing = Set(snapshot.locations.map(\.id))
|
|
let request = locations.compactMap { place in
|
|
place.geometry.map { LocationPlacement(id: place.id, newName: existing.contains(place.id) ? nil : place.name, geometry: $0) }
|
|
}
|
|
do {
|
|
let updated = try await store.saveLocationLayout(parent: parent?.id, version: snapshot.version, placements: request)
|
|
onSave(updated)
|
|
dismiss()
|
|
} catch {
|
|
self.error = error.localizedDescription
|
|
conflicted = (error as? AtlasError)?.status == 409
|
|
}
|
|
}
|
|
|
|
private func reload() async {
|
|
do {
|
|
let updated = try await store.locationLayout(parent: parent?.id, refresh: true)
|
|
snapshot = updated
|
|
locations = updated.locations
|
|
selection = nil
|
|
error = nil
|
|
conflicted = false
|
|
} catch { self.error = error.localizedDescription }
|
|
}
|
|
}
|
|
|
|
private struct LocationTemplatePicker: View {
|
|
let isRoot: Bool
|
|
let names: Set<String>
|
|
let add: (LocationTemplate, String) -> Void
|
|
@Environment(\.dismiss) private var dismiss
|
|
@State private var template: LocationTemplate?
|
|
@State private var name = ""
|
|
@FocusState private var focused: Bool
|
|
|
|
private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
private var available: [LocationTemplate] {
|
|
LocationTemplate.allCases.filter { isRoot || $0.kind != .room }
|
|
}
|
|
|
|
var body: some View {
|
|
NavigationStack {
|
|
ScrollView {
|
|
VStack(alignment: .leading, spacing: 14) {
|
|
if template != nil {
|
|
TextField("位置名称", text: $name)
|
|
.textFieldStyle(.roundedBorder)
|
|
.focused($focused)
|
|
if names.contains(trimmed) {
|
|
Text("当前层级已有同名位置。").font(.footnote).foregroundStyle(.secondary)
|
|
}
|
|
}
|
|
LazyVGrid(columns: [GridItem(.adaptive(minimum: 88), spacing: 8)], spacing: 8) {
|
|
ForEach(available) { choice in
|
|
Button {
|
|
focused = false
|
|
template = choice
|
|
name = availableName(choice.name)
|
|
} label: {
|
|
VStack(spacing: 5) {
|
|
LocationFloorArt(template: choice, rotation: 0)
|
|
.frame(width: 57, height: 40)
|
|
.accessibilityHidden(true)
|
|
Text(choice.name).font(.subheadline).foregroundStyle(.primary)
|
|
}
|
|
.padding(8)
|
|
.frame(maxWidth: .infinity, minHeight: 79)
|
|
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 10))
|
|
.overlay {
|
|
if choice == template { RoundedRectangle(cornerRadius: 10).stroke(Color.atlasBlue, lineWidth: 2) }
|
|
}
|
|
}
|
|
.buttonStyle(.plain)
|
|
.accessibilityAddTraits(choice == template ? .isSelected : [])
|
|
}
|
|
}
|
|
}
|
|
.padding(16)
|
|
}
|
|
.background(Color(uiColor: .systemGroupedBackground))
|
|
.dismissibleKeyboard(active: focused) { focused = false }
|
|
.navigationTitle("添加模板")
|
|
.navigationBarTitleDisplayMode(.inline)
|
|
.toolbar {
|
|
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } }
|
|
ToolbarItem(placement: .confirmationAction) {
|
|
Button("摆放") {
|
|
if let template { add(template, trimmed); dismiss() }
|
|
}
|
|
.disabled(template == nil || trimmed.isEmpty || trimmed.utf16.count > 100 || names.contains(trimmed))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func availableName(_ title: String) -> String {
|
|
var unique = title
|
|
var suffix = 2
|
|
while names.contains(unique) {
|
|
unique = "\(title) \(suffix)"
|
|
suffix += 1
|
|
}
|
|
return unique
|
|
}
|
|
}
|