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

374 lines
17 KiB
Swift

import SwiftUI
struct LocationPlanCanvas: View {
let width: Int
let depth: Int
let locations: [LayoutLocation]
let selected: UUID?
let editing: Bool
let open: (UUID) -> Void
var change: ((UUID, LocationGeometry) -> Void)? = nil
var expanded = false
var snapping = true
var highlighted: Set<UUID> = []
@State private var zoom = CGFloat(1)
@State private var pan = CGSize.zero
@State private var guides = LocationPlanGuides()
@GestureState private var pinch = CGFloat(1)
@GestureState private var panning = CGSize.zero
var body: some View {
GeometryReader { proxy in
let size = proxy.size
let fit = max(0.001, min((size.width - 14) / CGFloat(width), (size.height - 14) / CGFloat(depth)))
let scale = fit * min(4, max(1, zoom * pinch))
let board = CGSize(width: CGFloat(width) * scale, height: CGFloat(depth) * scale)
let shapes = Dictionary(uniqueKeysWithValues: locations.compactMap { place in
place.geometry.map { (place.id, $0) }
})
let visibleOffset = clamped(offset: CGSize(width: pan.width + panning.width, height: pan.height + panning.height),
board: board, viewport: size)
ZStack {
RoundedRectangle(cornerRadius: 10).fill(Color(uiColor: .secondarySystemGroupedBackground))
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 3)
.updating($panning) { value, state, _ in
if zoom > 1 { state = value.translation }
}
.onEnded { value in
if zoom > 1 {
pan = clamped(offset: CGSize(width: pan.width + value.translation.width,
height: pan.height + value.translation.height),
board: board, viewport: size)
}
})
ZStack(alignment: .topLeading) {
PlanGrid(spacing: max(1, 100 * scale))
ForEach(locations) { place in
if let geometry = place.geometry {
PlanTile(place: place, geometry: geometry, scale: scale,
selected: selected == place.id || highlighted.contains(place.id),
editing: editing, canvasWidth: width, canvasDepth: depth,
shapes: shapes, snapping: snapping,
open: { open(place.id) }, change: { change?(place.id, $0) },
report: { guides = $0 })
.zIndex(geometry.template.kind == .furniture ? (selected == place.id ? 3 : 2) : (selected == place.id ? 1 : 0))
}
}
if guides.x != nil || guides.y != nil {
PlanGuides(guides: guides, scale: scale).zIndex(5)
}
}
.frame(width: board.width, height: board.height)
.overlay { Rectangle().strokeBorder(.secondary.opacity(0.35), lineWidth: 1).allowsHitTesting(false) }
.offset(visibleOffset)
if locations.isEmpty {
Text("摆放位置后会显示在这里")
.font(.footnote).foregroundStyle(.secondary).allowsHitTesting(false)
}
}
.clipped()
.simultaneousGesture(MagnifyGesture()
.updating($pinch) { value, state, _ in state = value.magnification }
.onEnded { value in
setZoom(zoom * value.magnification, fit: fit, viewport: size)
})
.overlay(alignment: .bottomTrailing) {
if expanded {
HStack(spacing: 2) {
zoomButton("缩小", icon: "minus.magnifyingglass", disabled: zoom <= 1) {
setZoom(zoom / 1.35, fit: fit, viewport: size)
}
zoomButton("适应屏幕", icon: "arrow.up.left.and.arrow.down.right", disabled: false) {
setZoom(1, fit: fit, viewport: size)
}
zoomButton("放大", icon: "plus.magnifyingglass", disabled: zoom >= 4) {
setZoom(zoom * 1.35, fit: fit, viewport: size)
}
}
.background(.regularMaterial, in: .rect(cornerRadius: 10))
.padding(8)
}
}
}
.frame(height: expanded ? nil : 275)
.frame(maxHeight: expanded ? .infinity : nil)
.accessibilityElement(children: .contain)
.accessibilityLabel("位置平面图")
.accessibilityIdentifier("location.floor.canvas")
}
private func zoomButton(_ label: String, icon: String, disabled: Bool, action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: icon).frame(width: 41, height: 40).contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(disabled)
.foregroundStyle(disabled ? Color.secondary : Color.atlasBlue)
.accessibilityLabel(label)
}
private func setZoom(_ value: CGFloat, fit: CGFloat, viewport: CGSize) {
zoom = min(4, max(1, value))
let board = CGSize(width: CGFloat(width) * fit * zoom, height: CGFloat(depth) * fit * zoom)
pan = clamped(offset: pan, board: board, viewport: viewport)
}
private func clamped(offset: CGSize, board: CGSize, viewport: CGSize) -> CGSize {
let x = max(0, (board.width - viewport.width) / 2 + 7)
let y = max(0, (board.height - viewport.height) / 2 + 7)
return CGSize(width: min(x, max(-x, offset.width)), height: min(y, max(-y, offset.height)))
}
}
private struct PlanGrid: View {
let spacing: CGFloat
var body: some View {
Canvas { context, size in
var major = Path()
var minor = Path()
for index in 0...Int(size.width / spacing) {
let x = CGFloat(index) * spacing
if index.isMultiple(of: 5) {
major.move(to: CGPoint(x: x, y: 0)); major.addLine(to: CGPoint(x: x, y: size.height))
} else if spacing >= 6 {
minor.move(to: CGPoint(x: x, y: 0)); minor.addLine(to: CGPoint(x: x, y: size.height))
}
}
for index in 0...Int(size.height / spacing) {
let y = CGFloat(index) * spacing
if index.isMultiple(of: 5) {
major.move(to: CGPoint(x: 0, y: y)); major.addLine(to: CGPoint(x: size.width, y: y))
} else if spacing >= 6 {
minor.move(to: CGPoint(x: 0, y: y)); minor.addLine(to: CGPoint(x: size.width, y: y))
}
}
context.stroke(minor, with: .color(.secondary.opacity(0.1)), lineWidth: 0.5)
context.stroke(major, with: .color(.secondary.opacity(0.21)), lineWidth: 0.7)
}
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
private struct PlanGuides: View {
let guides: LocationPlanGuides
let scale: CGFloat
var body: some View {
Canvas { context, size in
var line = Path()
if let x = guides.x {
let horizontal = CGFloat(x) * scale
line.move(to: CGPoint(x: horizontal, y: 0))
line.addLine(to: CGPoint(x: horizontal, y: size.height))
}
if let y = guides.y {
let vertical = CGFloat(y) * scale
line.move(to: CGPoint(x: 0, y: vertical))
line.addLine(to: CGPoint(x: size.width, y: vertical))
}
context.stroke(line, with: .color(.atlasBlue), style: StrokeStyle(lineWidth: 1.4, dash: [4, 3]))
}
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
private struct PlanTile: View {
struct Drag: Equatable {
let delta: CGSize
let resizing: Bool
}
let place: LayoutLocation
let geometry: LocationGeometry
let scale: CGFloat
let selected: Bool
let editing: Bool
let canvasWidth: Int
let canvasDepth: Int
let shapes: [UUID: LocationGeometry]
let snapping: Bool
let open: () -> Void
let change: (LocationGeometry) -> Void
let report: (LocationPlanGuides) -> Void
@GestureState private var drag: Drag?
var body: some View {
let preview = drag.map { result($0) }
let frame = preview?.geometry ?? geometry
let overlapping = editing && (selected || drag != nil) && frame.template.kind == .room &&
shapes.contains { id, other in id != place.id && other.template.kind == .room && other.overlaps(frame) }
let width = CGFloat(frame.widthMm) * scale, depth = CGFloat(frame.depthMm) * scale
ZStack(alignment: .topLeading) {
let tile = LocationFloorArt(template: frame.template, rotation: frame.rotation)
.overlay(alignment: frame.template.kind == .room ? .topLeading : .bottom) {
if width > 29 && depth > 17 {
Text(place.name)
.font(.caption2.weight(.semibold))
.lineLimit(1)
.padding(.horizontal, 4).padding(.vertical, 2)
.background(.regularMaterial, in: .rect(cornerRadius: 4))
.padding(2)
.allowsHitTesting(false)
}
}
.frame(width: width, height: depth)
.overlay {
if selected || drag != nil || overlapping {
RoundedRectangle(cornerRadius: 4).stroke(overlapping ? Color.red : .atlasBlue, lineWidth: 2)
}
}
.contentShape(Rectangle())
if editing {
tile
.onTapGesture(perform: open)
.highPriorityGesture(gesture(resizing: false))
.accessibilityAddTraits(.isButton)
.accessibilityAction { open() }
} else {
Button(action: open) { tile }.buttonStyle(.plain)
}
if selected && editing {
Circle()
.fill(Color.atlasBlue)
.overlay { Circle().strokeBorder(.white, lineWidth: 2) }
.frame(width: 16, height: 16)
.frame(width: 44, height: 44)
.contentShape(Rectangle())
.highPriorityGesture(gesture(resizing: true))
.position(x: max(0, width - 4), y: max(0, depth - 4))
.accessibilityHidden(true)
}
}
.frame(width: width, height: depth, alignment: .topLeading)
.position(x: CGFloat(frame.xMm) * scale + width / 2, y: CGFloat(frame.yMm) * scale + depth / 2)
.accessibilityLabel(place.name)
.onChange(of: preview?.guides) { _, current in report(current ?? .init()) }
}
private func gesture(resizing: Bool) -> some Gesture {
DragGesture(minimumDistance: 4, coordinateSpace: .global)
.updating($drag) { value, state, _ in state = Drag(delta: value.translation, resizing: resizing) }
.onEnded { value in
change(result(Drag(delta: value.translation, resizing: resizing)).geometry)
report(.init())
}
}
private func result(_ drag: Drag) -> LocationPlanSnap.Result {
let dx = Int((drag.delta.width / scale).rounded()), dy = Int((drag.delta.height / scale).rounded())
let neighbors = shapes.compactMap { $0.key == place.id ? nil : $0.value }
let snap = LocationPlanSnap(width: canvasWidth, depth: canvasDepth, neighbors: neighbors,
threshold: Int(min(300, max(50, 7 / scale))), enabled: snapping)
return drag.resizing ? snap.resize(geometry, dx: dx, dy: dy) : snap.move(geometry, dx: dx, dy: dy)
}
}
struct LocationFloorArt: View {
let template: LocationTemplate
let rotation: Int
@Environment(\.colorScheme) private var scheme
private struct Piece {
let x: CGFloat
let y: CGFloat
let w: CGFloat
let h: CGFloat
let color: Color
let radius: CGFloat
init(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ color: Color, _ radius: CGFloat = 5) {
self.x = x; self.y = y; self.w = w; self.h = h
self.color = color; self.radius = radius
}
}
private let sage = Color(red: 0.55, green: 0.66, blue: 0.54)
private let pale = Color(red: 0.77, green: 0.82, blue: 0.64)
private let tan = Color(red: 0.85, green: 0.69, blue: 0.53)
private let cream = Color(red: 0.97, green: 0.91, blue: 0.78)
private let wood = Color(red: 0.65, green: 0.43, blue: 0.34)
private let slate = Color(red: 0.33, green: 0.40, blue: 0.47)
var body: some View {
if template.kind == .furniture {
GeometryReader { proxy in
let sideways = rotation % 180 != 0
let width = sideways ? proxy.size.height : proxy.size.width
let height = sideways ? proxy.size.width : proxy.size.height
furnishing.frame(width: width, height: height)
.rotationEffect(.degrees(Double(rotation)))
.position(x: proxy.size.width / 2, y: proxy.size.height / 2)
}
} else {
room
}
}
private var room: some View {
let tint = template == .bathroom || template == .kitchen || template == .balcony ? Color.teal : Color.brown
return RoundedRectangle(cornerRadius: 4)
.fill(tint.opacity(scheme == .dark ? 0.26 : 0.16))
.overlay {
RoundedRectangle(cornerRadius: 4)
.strokeBorder(tint.opacity(0.76), style: StrokeStyle(lineWidth: template.kind == .room ? 1.6 : 1, dash: template.kind == .area ? [4, 3] : []))
}
}
private var furnishing: some View {
Canvas { context, size in
let shapes = pieces
let left = (shapes.map(\.x).min() ?? 0) - 2
let top = (shapes.map(\.y).min() ?? 0) - 2
let right = (shapes.map { $0.x + $0.w }.max() ?? 100) + 2
let bottom = (shapes.map { $0.y + $0.h }.max() ?? 70) + 2
let sx = size.width / (right - left), sy = size.height / (bottom - top)
for part in shapes {
let rect = CGRect(x: (part.x - left) * sx, y: (part.y - top) * sy,
width: part.w * sx, height: part.h * sy)
let path = Path(roundedRect: rect, cornerRadius: part.radius * min(sx, sy))
context.fill(path, with: .color(part.color))
context.stroke(path, with: .color(.black.opacity(0.4)), lineWidth: min(1.3, max(0.45, min(sx, sy))))
}
}
.allowsHitTesting(false)
}
private var pieces: [Piece] {
switch template {
case .sofa:
[.init(4,6,105,39,sage,10), .init(74,30,35,38,sage,9),
.init(15,16,25,20,pale), .init(41,16,25,20,pale), .init(67,16,25,20,pale),
.init(80,37,22,23,pale), .init(97,13,12,48,sage)]
case .bed:
[.init(17,4,74,86,tan,8), .init(21,9,66,12,wood),
.init(24,16,28,17,cream), .init(56,16,28,17,cream),
.init(22,35,64,49,cream,7), .init(22,65,64,19,sage)]
case .tvStand:
[.init(5,12,106,47,tan,7), .init(32,22,51,9,slate), .init(11,11,94,14,slate),
.init(12,39,28,13,cream), .init(44,39,28,13,cream), .init(76,39,27,13,cream)]
case .wardrobe:
[.init(5,10,104,48,wood), .init(10,15,22,38,tan), .init(34,15,22,38,tan),
.init(58,15,22,38,tan), .init(82,15,22,38,tan),
.init(26,29,3,10,slate), .init(39,29,3,10,slate), .init(74,29,3,10,slate), .init(86,29,3,10,slate)]
case .bookcase:
[.init(6,7,102,49,wood), .init(13,13,88,36,cream), .init(41,13,4,36,wood,2),
.init(71,13,4,36,wood,2), .init(19,23,8,23,sage), .init(28,26,9,20,slate),
.init(49,17,8,29,wood), .init(58,23,8,23,sage), .init(82,22,13,24,slate)]
case .shelf:
[.init(5,12,107,46,sage), .init(12,18,21,34,pale), .init(36,18,21,34,pale),
.init(60,18,21,34,pale), .init(84,18,21,34,pale)]
case .desk:
[.init(5,10,106,55,wood,7), .init(10,14,96,44,tan),
.init(25,22,22,24,cream), .init(62,22,31,20,slate), .init(72,42,11,7,slate)]
case .table:
[.init(3,3,58,58,wood,29), .init(6,5,52,52,tan,26)]
default:
[.init(20,7,66,60,tan,9), .init(22,9,62,20,cream,7), .init(43,45,20,8,wood,4)]
}
}
}