Files

283 lines
12 KiB
Swift
Raw Permalink 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 AppKit
import HelderCore
import SwiftUI
/// The diagram: relationship lines under the cards, panned and zoomed by the store's viewport.
/// Each card is laid out at 100% and scaled into its on-screen frame, so its click and pointer area stay unscaled.
struct SchemaCanvas: View {
let model: WorkspaceModel
let store: SchemaStore
let schema: SchemaModel
/// Where a background drag started; nil between drags.
@State private var pan: (start: SchemaViewport, moved: Bool)?
/// The card being pressed and where it stood.
@State private var press: (name: String, origin: SchemaPoint, moved: Bool)?
private static let space = "schemaCanvas"
/// A press that moves less than this is a click.
private static let dragThreshold = 4.0
var body: some View {
let highlight = store.highlight ?? SchemaHighlight(model: schema, hovered: nil, selected: nil, hoveredColumn: nil, query: "")
let view = store.viewport
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
Palette.editor
.contentShape(Rectangle())
.gesture(backgroundDrag)
SchemaEdges(schema: schema, positions: store.positions, viewport: view, highlight: highlight)
.allowsHitTesting(false)
ForEach(schema.tables, id: \.name) { table in
if let position = store.positions[table.name] {
card(table, at: position, view: view, highlight: highlight)
}
}
Text("drag to pan · ⌘ scroll to zoom · hover a table or a key to trace it · click to inspect")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.allowsHitTesting(false)
.padding(SchemaViewMetrics.canvasInset)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
SchemaZoomControl(store: store)
.padding(SchemaViewMetrics.canvasInset)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}
.coordinateSpace(name: Self.space)
.clipped()
.background(SchemaScrollCatcher(
isActive: !model.overlay.isPresented,
onPan: { dx, dy in store.pan(dx: dx, dy: dy) },
onZoom: { factor, point in store.zoom(by: factor, around: SchemaPoint(x: point.x, y: point.y)) }
))
.onAppear { store.setCanvasSize(SchemaSize(width: proxy.size.width, height: proxy.size.height)) }
.onChange(of: proxy.size) { _, size in store.setCanvasSize(SchemaSize(width: size.width, height: size.height)) }
}
}
private func card(_ table: SchemaTable, at position: SchemaPoint, view: SchemaViewport, highlight: SchemaHighlight) -> some View {
let k = view.scale
let width = SchemaMetrics.cardWidth * k
let height = table.cardHeight * k
return SchemaTableCard(table: table, highlight: highlight, isSelected: store.selected == table.name) { id, inside in
if inside {
store.hoverColumn(id)
} else if store.hoveredColumn == id {
store.hoverColumn(nil)
}
}
.scaleEffect(k, anchor: .topLeading)
.frame(width: width, height: height, alignment: .topLeading)
.contentShape(Rectangle())
.pointerHand()
.onHover { inside in
if inside {
store.hover(table.name)
} else if store.hovered == table.name {
store.hover(nil)
}
}
.gesture(cardDrag(table.name, origin: position, scale: k))
.position(x: position.x * k + view.x + width / 2, y: position.y * k + view.y + height / 2)
}
/// Drags the card past a 4pt threshold; a shorter press selects it, or deselects it when it already was.
private func cardDrag(_ name: String, origin: SchemaPoint, scale: Double) -> some Gesture {
DragGesture(minimumDistance: 0, coordinateSpace: .named(Self.space))
.onChanged { value in
var current = press.flatMap { $0.name == name ? $0 : nil } ?? (name: name, origin: origin, moved: false)
let dx = value.translation.width, dy = value.translation.height
if !current.moved && abs(dx) + abs(dy) < Self.dragThreshold {
press = current
return
}
current.moved = true
press = current
store.moveTable(name, to: SchemaPoint(x: (current.origin.x + dx / scale).rounded(),
y: (current.origin.y + dy / scale).rounded()))
}
.onEnded { _ in
let moved = press?.moved ?? false
press = nil
if moved { store.endDrag() } else { store.toggleSelection(name) }
}
}
/// Pans past a 4pt threshold; a click on the empty canvas deselects.
private var backgroundDrag: some Gesture {
DragGesture(minimumDistance: 0, coordinateSpace: .named(Self.space))
.onChanged { value in
var current = pan ?? (start: store.viewport, moved: false)
let dx = value.translation.width, dy = value.translation.height
if !current.moved && abs(dx) + abs(dy) < Self.dragThreshold {
pan = current
return
}
current.moved = true
pan = current
var next = current.start
next.x += dx
next.y += dy
store.setViewport(next)
}
.onEnded { _ in
let moved = pan?.moved ?? false
pan = nil
if !moved { store.clearSelection() }
}
}
}
/// One cubic line per foreign key, hollow at the key end and filled at the referenced end; active lines on top.
private struct SchemaEdges: View {
let schema: SchemaModel
let positions: [String: SchemaPoint]
let viewport: SchemaViewport
let highlight: SchemaHighlight
var body: some View {
Canvas { context, _ in
let k = viewport.scale
func screen(_ p: SchemaPoint) -> CGPoint { CGPoint(x: p.x * k + viewport.x, y: p.y * k + viewport.y) }
for edge in highlight.drawingOrder(schema.edges) {
guard let geometry = SchemaGeometry.edgePath(edge, positions: positions) else { continue }
let active = highlight.isActive(edge)
let color = active ? Palette.amber : highlight.linesRecede ? Palette.raised : Palette.text5
let start = screen(geometry.start), end = screen(geometry.end)
var line = Path()
line.move(to: start)
line.addCurve(to: end, control1: screen(geometry.control1), control2: screen(geometry.control2))
context.stroke(line, with: .color(color), lineWidth: (active ? 1.75 : 1.25) * k)
let r = SchemaMetrics.endRadius * k
let hollow = Path(ellipseIn: CGRect(x: start.x - r, y: start.y - r, width: r * 2, height: r * 2))
context.fill(hollow, with: .color(Palette.editor))
context.stroke(hollow, with: .color(color), lineWidth: 1.5 * k)
context.fill(Path(ellipseIn: CGRect(x: end.x - r, y: end.y - r, width: r * 2, height: r * 2)), with: .color(color))
}
}
}
}
/// `−` · zoom % · `+` · Fit, bottom right of the canvas.
private struct SchemaZoomControl: View {
let store: SchemaStore
var body: some View {
HStack(spacing: 0) {
ZoomButton(tip: "Zoom out") { store.zoom(by: 1 / SchemaMetrics.zoomStep) } label: {
GitIconView(icon: .minus, size: 14).frame(width: SchemaViewMetrics.zoomButton)
}
Text(store.viewport.percentLabel)
.typeRole(Typography.schemaZoom)
.foregroundStyle(Palette.textMuted)
.frame(width: SchemaViewMetrics.zoomLabel, height: SchemaViewMetrics.zoomControl)
.hairline(.leading)
.hairline(.trailing)
ZoomButton(tip: "Zoom in") { store.zoom(by: SchemaMetrics.zoomStep) } label: {
GitIconView(icon: .plus, size: 14).frame(width: SchemaViewMetrics.zoomButton)
}
ZoomButton(tip: "Fit the whole schema") { store.fit() } label: {
Text("Fit").typeRole(Typography.button).padding(.horizontal, 11)
}
.hairline(.leading)
}
.fixedSize()
.background(Palette.panel)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
}
}
private struct ZoomButton<Label: View>: View {
let tip: String
let action: () -> Void
@ViewBuilder let label: Label
@State private var isHovered = false
var body: some View {
Button(action: action) {
label
.foregroundStyle(isHovered ? Palette.text1 : Palette.text3)
.frame(height: SchemaViewMetrics.zoomControl)
.background(isHovered ? Palette.raised : .clear)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($isHovered)
.tip(tip, edge: .trailing)
}
}
/// Turns scroll and pinch over the canvas into pan and zoom: plain scroll pans, ⌘ or Ctrl scroll and pinch zoom
/// around the pointer. A local monitor, because the cards on top would otherwise receive the events.
private struct SchemaScrollCatcher: NSViewRepresentable {
let isActive: Bool
let onPan: (_ dx: Double, _ dy: Double) -> Void
let onZoom: (_ factor: Double, _ at: CGPoint) -> Void
func makeNSView(context: Context) -> CatcherView {
CatcherView()
}
func updateNSView(_ view: CatcherView, context: Context) {
view.isActive = isActive
view.onPan = onPan
view.onZoom = onZoom
}
static func dismantleNSView(_ view: CatcherView, coordinator: ()) {
view.removeMonitor()
}
final class CatcherView: NSView {
var isActive = true
var onPan: (Double, Double) -> Void = { _, _ in }
var onZoom: (Double, CGPoint) -> Void = { _, _ in }
private var monitor: Any?
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil {
removeMonitor()
} else if monitor == nil {
monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .magnify]) { [weak self] event in
MainActor.assumeIsolated { self?.handle(event) ?? false } ? nil : event
}
}
}
func removeMonitor() {
if let monitor { NSEvent.removeMonitor(monitor) }
monitor = nil
}
/// True when the event was over the canvas and moved it.
private func handle(_ event: NSEvent) -> Bool {
guard isActive, let window, event.window === window else { return false }
let point = convert(event.locationInWindow, from: nil)
guard bounds.contains(point) else { return false }
switch event.type {
case .magnify:
onZoom(1 + event.magnification, point)
case .scrollWheel:
// A mouse wheel reports lines, a trackpad points; both feel alike after this.
let unit = event.hasPreciseScrollingDeltas ? 1.0 : 10.0
let dx = event.scrollingDeltaX * unit, dy = event.scrollingDeltaY * unit
if event.modifierFlags.contains(.command) || event.modifierFlags.contains(.control) {
onZoom(exp(dy * 0.01), point)
} else {
onPan(dx, dy)
}
default:
return false
}
return true
}
}
}