adds schema view and schema generating command

This commit is contained in:
2026-11-03 09:35:41 +01:00
parent cc41decccb
commit 600d4874d2
62 changed files with 4416 additions and 105 deletions
@@ -421,7 +421,7 @@ final class PointerTracker: NSResponder {
}
extension EnvironmentValues {
/// The overlay host and the Git view set `.overlay`, so the regions inside them keep their pointer while the columns lose theirs.
/// The overlay host and the Git and Schema views set `.overlay`, so the regions inside them keep their pointer while the columns lose theirs.
@Entry var pointerLayer = PointerLayer.workspace
/// False under `disabledLook`, whose hit-testing switch SwiftUI does not expose.
@Entry var allowsPointerHand = true
+40 -22
View File
@@ -2,7 +2,6 @@ import AppKit
import HelderCore
import SwiftUI
/// The real git commands and their output, then a `$ git` input line. A click that selects nothing focuses the input.
/// The real git commands and their output, then a `$ git` input line. A click that selects nothing focuses the input.
struct GitConsolePanel: View {
let model: WorkspaceModel
@@ -14,13 +13,17 @@ struct GitConsolePanel: View {
header
VStack(alignment: .leading, spacing: 0) {
// First pick of the height: the log takes what its lines need, the input sits right under it.
ConsoleLogView(entries: store.lines, onPlainClick: { focusTick += 1 })
ConsoleLogView(entries: store.lines.map { ConsoleLogLine(id: $0.id, text: $0.line.text, color: Palette.console($0.line.kind)) },
onPlainClick: { focusTick += 1 })
.layoutPriority(1)
// An AppKit field has no text baseline for SwiftUI, so the row centres instead.
HStack(alignment: .center, spacing: 8) {
Text("$ git").typeRole(Typography.console).foregroundStyle(Palette.gitNew).lineLimit(1).fixedSize()
ConsoleInputField(
text: Binding(get: { store.consoleInput }, set: { store.consoleInput = $0 }),
placeholder: "status · add -A · commit -m \"…\" · push · pull · log",
role: Typography.console,
makeEditor: { GitConsoleFieldEditor() },
focusTick: focusTick,
onSubmit: { model.perform(.submitConsoleInput) },
onUp: { store.recallPreviousInput() }
@@ -79,11 +82,18 @@ private struct EraserButton: View {
// MARK: Log
/// One console line as the log draws it; the id stays put while older lines drop off the top.
struct ConsoleLogLine: Equatable {
let id: Int
let text: String
let color: Color
}
/// A read-only, selectable text view of the console lines; it follows the newest line.
/// Its height is measured in `sizeThatFits`, so the input row follows the last line in the same layout pass.
private struct ConsoleLogView: NSViewRepresentable {
let entries: [GitConsoleEntry]
let onPlainClick: () -> Void
struct ConsoleLogView: NSViewRepresentable {
let entries: [ConsoleLogLine]
var onPlainClick: () -> Void = {}
func makeCoordinator() -> Coordinator { Coordinator() }
@@ -144,7 +154,7 @@ private struct ConsoleLogView: NSViewRepresentable {
private var measured: (width: CGFloat, height: CGFloat)?
/// Rebuilt only when lines were added or dropped, since one console holds up to 400 of them.
func text(for entries: [GitConsoleEntry]) -> NSAttributedString {
func text(for entries: [ConsoleLogLine]) -> NSAttributedString {
let next = Signature(count: entries.count, first: entries.first?.id, last: entries.last?.id)
if next != signature {
signature = next
@@ -154,7 +164,7 @@ private struct ConsoleLogView: NSViewRepresentable {
return cached
}
func height(of entries: [GitConsoleEntry], width: CGFloat) -> CGFloat {
func height(of entries: [ConsoleLogLine], width: CGFloat) -> CGFloat {
let text = text(for: entries)
if let measured, measured.width == width { return measured.height }
let storage = NSTextStorage(attributedString: text)
@@ -169,7 +179,7 @@ private struct ConsoleLogView: NSViewRepresentable {
return height
}
private static func build(_ entries: [GitConsoleEntry]) -> NSAttributedString {
private static func build(_ entries: [ConsoleLogLine]) -> NSAttributedString {
let role = Typography.console
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = role.lineHeight ?? 19.2
@@ -181,9 +191,9 @@ private struct ConsoleLogView: NSViewRepresentable {
let spare = paragraph.maximumLineHeight - NSLayoutManager().defaultLineHeight(for: role.nsFont)
let out = NSMutableAttributedString()
for (index, entry) in entries.enumerated() {
let line = entry.line.text + (index == entries.count - 1 ? "" : "\n")
let line = entry.text + (index == entries.count - 1 ? "" : "\n")
out.append(NSAttributedString(string: line, attributes: [
.font: role.nsFont, .foregroundColor: NSColor(Palette.console(entry.line.kind)), .paragraphStyle: paragraph,
.font: role.nsFont, .foregroundColor: NSColor(entry.color), .paragraphStyle: paragraph,
.baselineOffset: max(0, spare / 2),
]))
}
@@ -193,7 +203,7 @@ private struct ConsoleLogView: NSViewRepresentable {
}
/// Grows with each new line; every resize lands on the newest line.
private final class ConsoleLogScrollView: NSScrollView {
final class ConsoleLogScrollView: NSScrollView {
override func setFrameSize(_ newSize: NSSize) {
let grew = newSize.height != frame.height
super.setFrameSize(newSize)
@@ -202,7 +212,7 @@ private final class ConsoleLogScrollView: NSScrollView {
}
/// A click that leaves no selection hands the keyboard to the input line.
private final class ConsoleLogTextView: PointerBoundTextView {
final class ConsoleLogTextView: PointerBoundTextView {
var onPlainClick: () -> Void = {}
override func mouseDown(with event: NSEvent) {
@@ -213,19 +223,26 @@ private final class ConsoleLogTextView: PointerBoundTextView {
// MARK: Input
/// The borderless input after `$ git`: ↵ runs it, ↑ recalls the last command. It never takes focus on its own.
private struct ConsoleInputField: NSViewRepresentable {
/// A borderless one-line input: the Git console's `$ git` line and the Schema table search.
/// ↵ submits and ↑ recalls; it takes focus only when `focusTick` moves.
struct ConsoleInputField: NSViewRepresentable {
@Binding var text: String
let focusTick: Int
let placeholder: String
let role: TypeRole
/// The field editor's class tells the key router which field holds the keyboard.
let makeEditor: () -> PointerBoundTextView
var focusTick = 0
let onSubmit: () -> Void
let onUp: () -> Void
var onUp: () -> Void = {}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> ConsoleFieldBox {
let font = Typography.console.nsFont
let font = role.nsFont
let field = NSTextField()
field.cell = ConsoleFieldCell(textCell: "")
let cell = ConsoleFieldCell(textCell: "")
cell.makeEditor = makeEditor
field.cell = cell
field.isBordered = false
field.isEditable = true
field.isSelectable = true
@@ -234,7 +251,7 @@ private struct ConsoleInputField: NSViewRepresentable {
field.font = font
field.textColor = NSColor(hex: 0xF4F5F4)
field.placeholderAttributedString = NSAttributedString(
string: "status · add -A · commit -m \"…\" · push · pull · log",
string: placeholder,
attributes: [.foregroundColor: NSColor(hex: 0x6C7783), .font: font]
)
field.stringValue = text
@@ -291,7 +308,7 @@ private struct ConsoleInputField: NSViewRepresentable {
}
/// The box around the console input: it takes the I-beam on the policy's terms and focuses the field on a click.
private final class ConsoleFieldBox: NSView, PointerTextTarget {
final class ConsoleFieldBox: NSView, PointerTextTarget {
let field: NSTextField
var pointerLayer = PointerLayer.overlay {
didSet { if pointerLayer != oldValue { PointerPolicy.setNeedsRefresh(in: window) } }
@@ -362,9 +379,10 @@ private final class ConsoleFieldCell: NSTextFieldCell {
var pointerLayer = PointerLayer.overlay {
didSet { editor.pointerLayer = pointerLayer }
}
var makeEditor: () -> PointerBoundTextView = { PointerBoundTextView() }
private lazy var editor: GitConsoleFieldEditor = {
let editor = GitConsoleFieldEditor()
private lazy var editor: PointerBoundTextView = {
let editor = makeEditor()
editor.isFieldEditor = true
editor.pointerLayer = pointerLayer
editor.insertionPointColor = NSColor(hex: 0xE8913A)
+30 -3
View File
@@ -1,14 +1,16 @@
import SwiftUI
/// The Git view's icons, drawn on Lucide's 24-unit grid at stroke 1.75; the flag is a plain pennant.
/// Icons with arcs Lucide draws as curves (cloud, eraser) use the nearest SF Symbol.
/// The Git and Schema views' icons, drawn on Lucide's 24-unit grid at stroke 1.75; the flag is a plain pennant.
/// Icons with arcs Lucide draws as curves (cloud, eraser, sparkle) use the nearest SF Symbol.
enum GitIcon {
case gitBranch, cloud, arrowDownToLine, arrowUpFromLine, minimize, chevronDown, chevronRight, eraser, check, flag
case database, terminal, search, minus, plus, x, sparkle
fileprivate var symbol: String? {
switch self {
case .cloud: "cloud"
case .eraser: "eraser"
case .sparkle: "sparkle"
default: nil
}
}
@@ -49,7 +51,32 @@ enum GitIcon {
case .flag:
line((5, 22), (5, 3))
line((5, 4), (19, 9), (5, 14))
case .cloud, .eraser:
case .database:
path.addEllipse(in: CGRect(x: 3 * k, y: 2 * k, width: 18 * k, height: 6 * k))
line((3, 5), (3, 19))
line((21, 5), (21, 19))
for y in [12.0, 19.0] {
// A lower half-ellipse, 9 wide and 3 deep each side, as two Bézier quarters.
let c = 0.5523
path.move(to: p(3, y))
path.addCurve(to: p(12, y + 3), control1: p(3, y + 3 * c), control2: p(12 - 9 * c, y + 3))
path.addCurve(to: p(21, y), control1: p(12 + 9 * c, y + 3), control2: p(21, y + 3 * c))
}
case .terminal:
line((4, 17), (10, 11), (4, 5))
line((12, 19), (20, 19))
case .search:
path.addEllipse(in: CGRect(x: 3 * k, y: 3 * k, width: 16 * k, height: 16 * k))
line((21, 21), (16.65, 16.65))
case .minus:
line((5, 12), (19, 12))
case .plus:
line((5, 12), (19, 12))
line((12, 5), (12, 19))
case .x:
line((18, 6), (6, 18))
line((6, 6), (18, 18))
case .cloud, .eraser, .sparkle:
break
}
return path
+1 -1
View File
@@ -31,7 +31,7 @@ struct GitTopBar: View {
}
/// A 28pt bordered button with an icon, a label and an amber mono count or key hint.
private struct GitBarButton: View {
struct GitBarButton: View {
let icon: GitIcon
let label: String
let trailing: String?
@@ -38,6 +38,10 @@ public enum ShortcutCatalog {
ShortcutRow(keys: ["⌘", "↵"], label: "Commit the staged files"),
ShortcutRow(keys: ["⌘", "P"], label: "Push the current branch"),
]),
ShortcutGroup(title: "Schema", rows: [
ShortcutRow(keys: ["⌘", "D"], label: "Open or close Schema (Laravel apps)"),
ShortcutRow(keys: ["↵"], label: "Table search: centre the first match"),
]),
ShortcutGroup(title: "File", rows: [
ShortcutRow(keys: ["⌘", "S"], label: "Save this file"),
ShortcutRow(keys: ["⌘", "M"], label: "Markdown: code or rendered preview"),
@@ -49,12 +53,12 @@ public enum ShortcutCatalog {
ShortcutRow(keys: ["⌘", "+"], label: "Zoom in"),
ShortcutRow(keys: ["⌘", "−"], label: "Zoom out"),
ShortcutRow(keys: ["⌘", "0"], label: "Actual size"),
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Git view"),
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Schema selection or view, then the Git view"),
]),
]
}
/// `?`: the keyboard reference, grouped NAVIGATE / AGENT / GIT / FILE.
/// `?`: the keyboard reference, grouped NAVIGATE / AGENT / GIT / SCHEMA / FILE.
struct ShortcutsOverlay: View {
var onClose: () -> Void
@@ -0,0 +1,282 @@
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
}
}
}
@@ -0,0 +1,27 @@
import HelderCore
import SwiftUI
/// `[ console ] artisan`: the last runs of `helder:schema`, following the newest line; the chevron hides it until the next run.
struct SchemaConsolePanel: View {
let store: SchemaStore
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 12) {
Text("[ console ] artisan").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
Spacer(minLength: 0)
SchemaIconButton(icon: .chevronDown, tip: "Hide console") { store.hideConsole() }
}
.padding(.leading, 16)
.padding(.trailing, 12)
.frame(height: SchemaViewMetrics.consoleHeader)
ConsoleLogView(entries: store.lines.map { ConsoleLogLine(id: $0.id, text: $0.line.text, color: Palette.artisan($0.line.kind)) })
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.padding(.horizontal, 16)
.padding(.bottom, 12)
}
.frame(height: SchemaViewMetrics.console)
.background(Palette.panel)
.hairline(.top)
}
}
@@ -0,0 +1,152 @@
import HelderCore
import SwiftUI
/// The 320pt panel for the selected table: its columns, what it belongs to and has many, and the footer actions.
struct SchemaDetailPanel: View {
let model: WorkspaceModel
let store: SchemaStore
let schema: SchemaModel
let table: SchemaTable
var body: some View {
let outgoing = schema.outgoing(from: table.name)
let incoming = schema.incoming(to: table.name)
VStack(spacing: 0) {
header
ScrollView {
VStack(alignment: .leading, spacing: 20) {
columns
if !outgoing.isEmpty {
relations("[ belongs to ]", arrow: "→", rows: outgoing.map { ($0.id, $0.to, $0.column) })
}
if !incoming.isEmpty {
relations("[ has many ]", arrow: "←", rows: incoming.map { ($0.id, $0.from, $0.column) })
}
if outgoing.isEmpty && incoming.isEmpty {
Text("— No foreign keys in or out.")
.typeRole(Typography.gitEmpty)
.foregroundStyle(Palette.textMuted)
.padding(.horizontal, 16)
}
}
.padding(.top, 14)
.padding(.bottom, 20)
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack(spacing: 8) {
SchemaOutlineButton(label: "Pass on to Claude", fills: true, padding: 8) { model.perform(.passSchemaTable(table.name)) }
SchemaOutlineButton(label: "Copy name", fills: true, padding: 8) { model.perform(.copySchemaTableName(table.name)) }
}
.padding(.horizontal, 16)
.padding(.vertical, 12)
.hairline(.top)
}
.background(Palette.panel)
.hairline(.leading)
}
private var header: some View {
HStack(spacing: 10) {
Text(table.name)
.typeRole(Typography.schemaDetailName)
.foregroundStyle(Palette.text1)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
if table.rows != nil {
Text(table.rowsLabel + " rows").typeRole(Typography.meta).foregroundStyle(Palette.textMuted).fixedSize()
}
SchemaIconButton(icon: .x, tip: "Close (Esc)") { store.clearSelection() }
}
.padding(.leading, 16)
.padding(.trailing, 10)
.frame(height: SchemaViewMetrics.detailHeader)
.hairline(.bottom)
}
private var columns: some View {
VStack(alignment: .leading, spacing: 0) {
sectionLabel("[ columns ] \(table.columns.count)")
ForEach(Array(table.columns.enumerated()), id: \.offset) { _, column in
VStack(alignment: .leading, spacing: 2) {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(column.name)
.typeRole(Typography.schemaDetailColumn)
.foregroundStyle(Palette.text2)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
Text(column.type).typeRole(Typography.schemaDetailMeta).foregroundStyle(Palette.textMuted).lineLimit(1).fixedSize()
}
Text(column.flags)
.typeRole(Typography.schemaDetailMeta)
.foregroundStyle(column.isPrimary || column.isForeign ? Palette.amberSoft : Palette.text4)
}
.padding(.horizontal, 16)
.padding(.vertical, 7)
.hairline(.top)
}
}
}
private func relations(_ label: String, arrow: String, rows: [(id: String, table: String, via: String)]) -> some View {
VStack(alignment: .leading, spacing: 0) {
sectionLabel(label)
ForEach(rows, id: \.id) { row in
SchemaRelationRow(arrow: arrow, table: row.table, via: row.via,
onHover: { inside in hover(row.table, inside) },
onClick: { store.centre(row.table) })
}
}
}
private func sectionLabel(_ text: String) -> some View {
Text(text)
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 16)
.padding(.bottom, 8)
}
private func hover(_ name: String, _ inside: Bool) {
if inside {
store.hover(name)
} else if store.hovered == name {
store.hover(nil)
}
}
}
/// `→ users … via user_id`: hover traces the table on the canvas, a click selects and centres it.
private struct SchemaRelationRow: View {
let arrow: String
let table: String
let via: String
let onHover: (Bool) -> Void
let onClick: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: onClick) {
HStack(spacing: 8) {
Text(arrow).foregroundStyle(Palette.amber)
Text(table).foregroundStyle(Palette.text1).lineLimit(1)
Spacer(minLength: 0)
Text("via " + via).foregroundStyle(Palette.textMuted).lineLimit(1)
}
.typeRole(Typography.path)
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(isHovered ? Palette.gitRowHover : .clear)
.hairline(.top)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.onHover { inside in
isHovered = inside
onHover(inside)
}
.animation(Metrics.colorTransition, value: isHovered)
}
}
@@ -0,0 +1,81 @@
import HelderCore
import SwiftUI
/// The command exists but has not written `database/helder/schema.json` yet.
struct SchemaEmptyState: View {
let model: WorkspaceModel
let store: SchemaStore
var body: some View {
SchemaStateBlock(label: "[ no dump yet ]",
message: Text("— Helder draws the schema from ") + schemaMono(SchemaPaths.dumpFile)
+ Text(". Run the command to write it.")) {
HStack(spacing: 14) {
SchemaPrimaryButton(label: store.runLabel) { model.perform(.runSchemaDump) }
Text("$ " + SchemaPaths.commandLine).typeRole(Typography.path).foregroundStyle(Palette.text4).lineLimit(1)
}
}
}
}
/// The project is a Laravel app without `HelderSchemaCommand.php`: the prompt that asks Claude to write it.
struct SchemaCommandMissing: View {
let model: WorkspaceModel
var body: some View {
SchemaStateBlock(label: "[ no command yet ]",
message: Text("— Helder draws the schema from ") + schemaMono(SchemaPaths.dumpFile)
+ Text(". The Artisan command ") + schemaMono(SchemaPaths.commandFile)
+ Text(" writes it, and this app does not have it yet.")) {
HStack(spacing: 14) {
SchemaPrimaryButton(label: "Generate command", icon: .sparkle) { model.perform(.generateSchemaCommand) }
SchemaOutlineButton(label: "Copy prompt", height: SchemaViewMetrics.primaryButton) { model.perform(.copySchemaPrompt) }
}
ScrollView {
Text(SchemaCommandPrompt.text)
.typeRole(Typography.console)
.foregroundStyle(Palette.textMuted)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(PointerTextRegion())
}
.frame(maxHeight: SchemaViewMetrics.promptPreview)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
}
}
}
/// A path inside the state copy: mono at the copy's size, in text-1.
private func schemaMono(_ text: String) -> Text {
Text(text).font(Typography.schemaBodyMono.font).foregroundColor(Palette.text1)
}
/// The centred block both states share: an amber label, Sans 15/1.6 copy, then the actions; at most 440 wide, 16 apart.
private struct SchemaStateBlock<Content: View>: View {
let label: String
let message: Text
@ViewBuilder let content: Content
init(label: String, message: Text, @ViewBuilder content: () -> Content) {
self.label = label
self.message = message
self.content = content()
}
var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text(label).typeRole(Typography.gitLabel).foregroundStyle(Palette.amber)
message
.typeRole(Typography.schemaBody)
.foregroundStyle(Palette.text3)
.fixedSize(horizontal: false, vertical: true)
content
}
.frame(maxWidth: SchemaViewMetrics.emptyStateWidth, alignment: .leading)
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
}
}
@@ -0,0 +1,75 @@
import HelderCore
import SwiftUI
/// One table on the canvas at 100%: a 33pt header, then a 22pt row per column. The line geometry depends on these sizes.
struct SchemaTableCard: View {
let table: SchemaTable
let highlight: SchemaHighlight
let isSelected: Bool
let onHoverColumn: (_ id: String, _ inside: Bool) -> Void
var body: some View {
let isFocus = highlight.focus == table.name
let lit = isFocus || isSelected
VStack(spacing: 0) {
HStack(spacing: 8) {
Text(table.name)
.typeRole(Typography.schemaCardName)
.foregroundStyle(lit ? Palette.text1 : Palette.text2)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
Text(table.rowsLabel).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
}
.padding(.horizontal, 10)
.frame(height: SchemaMetrics.headerHeight - Metrics.hairline)
.background(lit ? Palette.amberTint : Palette.panel)
Hairline()
ForEach(Array(table.columns.enumerated()), id: \.offset) { _, column in
row(column)
}
}
.padding(Metrics.hairline)
.frame(width: SchemaMetrics.cardWidth, height: table.cardHeight, alignment: .top)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(border(isFocus: isFocus), lineWidth: Metrics.hairline))
.opacity(highlight.opacity(of: table.name))
.animation(Metrics.colorTransition, value: highlight)
.animation(Metrics.colorTransition, value: isSelected)
}
private func row(_ column: SchemaColumn) -> some View {
let lit = highlight.isHighlighted(table: table.name, column: column.name)
let isKey = column.isPrimary || column.isForeign
return HStack(spacing: 6) {
Text(column.keyLabel)
.typeRole(Typography.schemaKey)
.foregroundStyle(lit ? Palette.amber : column.isPrimary ? Palette.amberSoft : Palette.textMuted)
.frame(width: 20, alignment: .leading)
Text(column.name)
.typeRole(Typography.path)
.foregroundStyle(lit ? Palette.text1 : isKey ? Palette.text2 : Palette.text3)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
Text(column.displayType).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
}
.padding(.horizontal, 10)
.frame(height: SchemaMetrics.rowHeight)
.background(lit ? Palette.amberTint : .clear)
.onHover { inside in
guard column.isForeign else { return }
onHoverColumn(SchemaColumnRef(table: table.name, column: column.name).id, inside)
}
}
/// Focus amber, a selection under another hover amber-deep, related text-4, a search match amber-soft.
private func border(isFocus: Bool) -> Color {
if isFocus { return Palette.amber }
if isSelected { return Palette.amberDeep }
if highlight.relatedTables.contains(table.name) { return Palette.text4 }
if highlight.searchMatches.contains(table.name) { return Palette.amberSoft }
return Palette.raised
}
}
@@ -0,0 +1,104 @@
import HelderCore
import SwiftUI
/// The 240pt list left of the canvas: the table search, `[ tables ] N`, and one row per matching table.
struct SchemaTableList: View {
let store: SchemaStore
let schema: SchemaModel
var body: some View {
let highlight = store.highlight
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 8) {
GitIconView(icon: .search, size: 14).foregroundStyle(Palette.textMuted)
ConsoleInputField(
text: Binding(get: { store.query }, set: { store.query = $0 }),
placeholder: "Find a table",
role: Typography.gitPath,
makeEditor: { SchemaSearchFieldEditor() },
onSubmit: { store.centreFirstMatch() }
)
.frame(maxWidth: .infinity)
.frame(height: 20)
}
.padding(.leading, 14)
.padding(.trailing, 12)
.frame(height: SchemaViewMetrics.searchRow)
.hairline(.bottom)
Text(SchemaSearch.listLabel(schema, query: store.query))
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.padding(.horizontal, 14)
.frame(height: SchemaViewMetrics.listLabelRow)
ScrollView {
LazyVStack(spacing: 0) {
ForEach(store.listedTables, id: \.name) { table in
SchemaTableRow(table: table,
isSelected: store.selected == table.name,
isFocus: highlight?.focus == table.name,
isRelated: highlight.map { $0.linesRecede && $0.relatedTables.contains(table.name) } ?? false,
onHover: { inside in hover(table.name, inside) },
onClick: { store.centre(table.name) })
}
}
.padding(.bottom, 12)
}
}
.background(Palette.panel)
.hairline(.trailing)
}
private func hover(_ name: String, _ inside: Bool) {
if inside {
store.hover(name)
} else if store.hovered == name {
store.hover(nil)
}
}
}
/// One table: its name and row count, the amber bar while selected.
private struct SchemaTableRow: View {
let table: SchemaTable
let isSelected: Bool
let isFocus: Bool
let isRelated: Bool
let onHover: (Bool) -> Void
let onClick: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: onClick) {
HStack(spacing: 8) {
Text(table.name)
.typeRole(Typography.path)
.foregroundStyle(isSelected || isFocus || isHovered ? Palette.text1 : isRelated ? Palette.text2 : Palette.text3)
.lineLimit(1)
.truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading)
Text(table.rowsLabel).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
}
.padding(.leading, 11)
.padding(.trailing, 14)
.frame(height: SchemaViewMetrics.listRow)
.background(background)
.overlay(alignment: .leading) {
Rectangle().fill(isSelected ? Palette.amber : .clear).frame(width: SchemaViewMetrics.accentBar)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.onHover { inside in
isHovered = inside
onHover(inside)
}
.animation(Metrics.colorTransition, value: isHovered)
}
private var background: Color {
if isSelected { return Palette.amberTint }
return isFocus || isHovered ? Palette.gitRowHover : .clear
}
}
@@ -0,0 +1,63 @@
import HelderCore
import SwiftUI
/// `[ schema ]`, the connection and the dump's meta, then the command path, Run and Close.
struct SchemaTopBar: View {
let model: WorkspaceModel
let store: SchemaStore
var body: some View {
HStack(spacing: 14) {
Text("[ schema ]").typeRole(Typography.gitLabel).foregroundStyle(Palette.textMuted).fixedSize()
if let schema = store.model {
HStack(spacing: 6) {
GitIconView(icon: .database, size: 13)
Text(schema.connectionLabel).typeRole(Typography.branch).lineLimit(1)
}
.foregroundStyle(Palette.amber)
.fixedSize()
}
Text(store.metaLabel)
.typeRole(Typography.path)
.foregroundStyle(Palette.textMuted)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 0)
if store.hasCommand {
CommandPathButton { model.perform(.openSchemaCommandFile) }
}
SchemaPrimaryButton(label: store.runLabel, icon: .terminal, height: SchemaViewMetrics.topButton,
role: Typography.commitButton, padding: 12) {
model.perform(.runSchemaDump)
}
.disabledLook(!store.hasCommand)
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘D") { model.perform(.closeSchemaView) }
}
.padding(.horizontal, 14)
.frame(height: SchemaViewMetrics.topBar)
.background(Palette.panel)
.hairline(.bottom)
}
}
/// `app/Console/Commands/HelderSchemaCommand.php` as a mono text button.
private struct CommandPathButton: View {
let action: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: action) {
Text(SchemaPaths.commandFile)
.typeRole(Typography.path)
.foregroundStyle(isHovered ? Palette.text1 : Palette.textMuted)
.lineLimit(1)
.padding(.vertical, 4)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.fixedSize()
.pointerHand()
.tracksHover($isHovered)
.tip("Open the command in the editor", edge: .trailing)
}
}
@@ -0,0 +1,147 @@
import HelderCore
import SwiftUI
/// ⌘D: the full-screen Schema view over the title bar, the columns and the status bar.
struct SchemaView: View {
let model: WorkspaceModel
let store: SchemaStore
var body: some View {
VStack(spacing: 0) {
SchemaTopBar(model: model, store: store)
HStack(spacing: 0) {
switch store.body {
case .diagram:
if let schema = store.model {
SchemaTableList(store: store, schema: schema)
.frame(width: SchemaViewMetrics.tableList)
SchemaCanvas(model: model, store: store, schema: schema)
if let table = store.selectedTable {
SchemaDetailPanel(model: model, store: store, schema: schema, table: table)
.frame(width: SchemaViewMetrics.detailPanel)
}
}
case .noDump:
SchemaEmptyState(model: model, store: store)
case .commandMissing:
SchemaCommandMissing(model: model)
case .loading:
Color.clear
}
}
.frame(maxHeight: .infinity)
if store.isConsoleOpen && !store.lines.isEmpty && store.body != .commandMissing {
SchemaConsolePanel(store: store)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
.contentShape(Rectangle())
}
}
/// The Schema view's fixed sizes, from the design handoff.
enum SchemaViewMetrics {
static let topBar: CGFloat = 44
static let topButton: CGFloat = 28
static let tableList: CGFloat = 240
static let searchRow: CGFloat = 44
static let listLabelRow: CGFloat = 34
static let listRow: CGFloat = 30
static let accentBar: CGFloat = 3
static let detailPanel: CGFloat = 320
static let detailHeader: CGFloat = 44
static let footerButton: CGFloat = 30
static let console: CGFloat = 150
static let consoleHeader: CGFloat = 32
static let primaryButton: CGFloat = 36
static let emptyStateWidth: CGFloat = 440
static let promptPreview: CGFloat = 240
static let zoomControl: CGFloat = 28
static let zoomButton: CGFloat = 30
static let zoomLabel: CGFloat = 52
static let canvasInset: CGFloat = 14
}
/// The amber primary of the empty and command-missing states: 36pt, Sans 600 13, amber-deep on hover.
struct SchemaPrimaryButton: View {
let label: String
var icon: GitIcon?
var height: CGFloat = SchemaViewMetrics.primaryButton
var role = Typography.gitCommitButton
var padding: CGFloat = 16
let action: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: action) {
HStack(spacing: 7) {
if let icon { GitIconView(icon: icon, size: 14) }
Text(label).typeRole(role).lineLimit(1)
}
.foregroundStyle(Palette.badgeText)
.padding(.horizontal, padding)
.frame(height: height)
.background(isHovered ? Palette.amberDeep : Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.fixedSize()
.pointerHand()
.tracksHover($isHovered)
}
}
/// The outline button of the detail footer and the command-missing state: text-5 border, raised fill on hover.
struct SchemaOutlineButton: View {
let label: String
var height: CGFloat = SchemaViewMetrics.footerButton
var fills = false
var padding: CGFloat = 16
let action: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: action) {
Text(label)
.typeRole(Typography.button)
.lineLimit(1)
.foregroundStyle(isHovered ? Palette.text1 : Palette.text3)
.padding(.horizontal, padding)
.frame(maxWidth: fills ? .infinity : nil)
.frame(height: height)
.background(isHovered ? Palette.raised : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall)
.strokeBorder(isHovered ? Palette.text4 : Palette.text5, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.fixedSize(horizontal: !fills, vertical: false)
.pointerHand()
.tracksHover($isHovered)
}
}
/// A borderless icon button: text-muted, text-1 on hover.
struct SchemaIconButton: View {
let icon: GitIcon
let tip: String
let action: () -> Void
@State private var isHovered = false
var body: some View {
Button(action: action) {
GitIconView(icon: icon, size: 14)
.foregroundStyle(isHovered ? Palette.text1 : Palette.textMuted)
.padding(4)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerHand()
.tracksHover($isHovered)
.tip(tip, edge: .trailing)
}
}
/// The table search's field editor; the key router tells it apart from the other fields by its class.
final class SchemaSearchFieldEditor: PointerBoundTextView {}
+21
View File
@@ -76,6 +76,10 @@ public enum Command: Equatable, Sendable {
case toggleGit
/// Esc with the Git view open and no overlay over it.
case closeGitView
/// ⌘D and the title bar's Schema button, in a Laravel app: opens or closes the full-screen Schema view.
case toggleSchemaView
/// Esc with nothing selected in the Schema view, and its Close button.
case closeSchemaView
/// ⌘1–⌘3 and the title-bar pane toggles: shows or hides one column.
case togglePane(Panel)
/// ⌘L
@@ -126,6 +130,23 @@ public enum Command: Equatable, Sendable {
/// ⌘C without a selection, outside a terminal: opens the Git view on its message field.
case focusCommitMessage
// MARK: Schema view
/// The Run button: `php artisan helder:schema`, then the dump is re-read.
case runSchemaDump
/// Closes the view and pastes the prompt that writes `HelderSchemaCommand.php` into the agent, unsent.
case generateSchemaCommand
case copySchemaPrompt
/// The detail panel's Pass on to Claude: `@schema:<table>` into the agent.
case passSchemaTable(String)
case copySchemaTableName(String)
/// The top bar's command path: closes the view and opens the command in the editor.
case openSchemaCommandFile
/// Esc with a table selected.
case clearSchemaSelection
/// Esc in the table search while it holds text.
case clearSchemaSearch
// MARK: Clean copy
/// The clean-copy popup's Copy and ⌘↩: copies its text and closes it.
+6 -1
View File
@@ -19,7 +19,7 @@ public struct HelderScene: Scene {
}
}
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘1–⌘3, ⌘L, ⌘.) are shown here too; the router
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘D, ⌘1–⌘3, ⌘L, ⌘.) are shown here too; the router
/// consumes them first, so the menu item fires only when a field or an overlay let the key through.
struct HelderCommands: Commands {
@FocusedValue(\.workspace) private var workspace
@@ -70,6 +70,11 @@ struct HelderCommands: Commands {
workspace?.perform(.toggleGit)
}
.keyboardShortcut("g", modifiers: .command)
Button(workspace?.layout.isSchemaViewOpen == true ? "Hide Schema" : "Show Schema") {
workspace?.perform(.toggleSchemaView)
}
.keyboardShortcut("d", modifiers: .command)
.disabled(workspace?.schema?.isLaravelApp != true)
Button(workspace?.layout.isVisible(.explorer) == false ? "Show Explorer" : "Hide Explorer") {
workspace?.perform(.togglePane(.explorer))
}
+41 -3
View File
@@ -59,11 +59,21 @@ public struct KeyContext: Equatable, Sendable {
public var gitViewOpen: Bool
/// The keyboard sits in the Git view's console input, where ⌘↵ must not commit.
public var inGitConsole: Bool
/// The project is a Laravel app, so ⌘D has a Schema view to toggle.
public var schemaAvailable: Bool
/// The full-screen Schema view covers the columns, like the Git view.
public var schemaViewOpen: Bool
/// A table is selected in the Schema view; Esc clears it first.
public var schemaHasSelection: Bool
/// The keyboard sits in the Schema table search and it holds text; Esc clears it before closing the view.
public var schemaSearchHasText: Bool
public init(hasProject: Bool = true, overlay: OverlayKind = .none, owner: KeyboardOwner = .workspace,
hasTextSelection: Bool = false, editorTextSelection: TextSelectionInfo? = nil,
hasEditorLineSelection: Bool = false, activePanel: Panel? = nil, focusZone: FocusZone = .neutral,
recentFileCount: Int = 0, searchSeed: String = "", gitViewOpen: Bool = false, inGitConsole: Bool = false) {
recentFileCount: Int = 0, searchSeed: String = "", gitViewOpen: Bool = false, inGitConsole: Bool = false,
schemaAvailable: Bool = false, schemaViewOpen: Bool = false, schemaHasSelection: Bool = false,
schemaSearchHasText: Bool = false) {
self.hasProject = hasProject
self.overlay = overlay
self.owner = owner
@@ -76,6 +86,10 @@ public struct KeyContext: Equatable, Sendable {
self.searchSeed = searchSeed
self.gitViewOpen = gitViewOpen
self.inGitConsole = inGitConsole
self.schemaAvailable = schemaAvailable
self.schemaViewOpen = schemaViewOpen
self.schemaHasSelection = schemaHasSelection
self.schemaSearchHasText = schemaSearchHasText
}
}
@@ -105,7 +119,8 @@ public enum KeyRoute: Equatable {
/// Maps a key press to a command. A key that a focused field or terminal needs is never taken:
/// arrows, ↵, `?`, ⌘A and ⌘C/⌘←/⌘→ go to the field; ⌘O, ⌘R and ⇧⌘N are left to the menu bar.
/// Esc closes the topmost layer: an overlay, then the Git view, else it reaches the terminal.
/// Esc closes the topmost layer: an overlay, then the Schema selection, search and view, then the Git view,
/// else it reaches the terminal.
public enum KeyRouter {
public static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
if press.control || press.option { return .pass }
@@ -116,7 +131,9 @@ public enum KeyRouter {
case .diff(busy: true): return .pass
case .none:
if press.key == .escape {
return context.gitViewOpen && !press.command ? .perform(.closeGitView) : .pass
guard !press.command else { return .pass }
if context.schemaViewOpen { return schemaEscape(context) }
return context.gitViewOpen ? .perform(.closeGitView) : .pass
}
default: if press.key == .escape && !press.command { return .perform(.dismissOverlay) }
}
@@ -127,6 +144,7 @@ public enum KeyRouter {
case .other: return .pass
}
if context.schemaViewOpen { return schemaViewKey(press, context) }
if context.gitViewOpen { return gitViewKey(press, context) }
return press.command ? commandKey(press, context) : plainKey(press, context)
}
@@ -145,6 +163,25 @@ public enum KeyRouter {
}
}
private static func schemaEscape(_ context: KeyContext) -> KeyRoute {
if context.schemaHasSelection { return .perform(.clearSchemaSelection) }
if context.schemaSearchHasText { return .perform(.clearSchemaSearch) }
return .perform(.closeSchemaView)
}
/// Over the Schema view the columns' keys rest as over the Git view; ⌘↵ and ⌘C have nothing to act on.
private static func schemaViewKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
guard press.command else {
return press.key == .character("?") && context.owner == .workspace ? .perform(.showShortcuts) : .pass
}
if press.shift { return commandKey(press, context) }
switch press.key {
case .character("a"), .character("c"): return .pass
case let .character(c): return commandCharacter(c, context)
default: return .pass
}
}
private static func launcherKey(_ press: KeyPress) -> KeyRoute {
guard !press.shift else { return .pass }
switch press.key {
@@ -198,6 +235,7 @@ public enum KeyRouter {
case "m": return .perform(.cycleMode)
case "w": return .perform(.closeFileOrWindow)
case "g": return .perform(.toggleGit)
case "d": return context.schemaAvailable ? .perform(.toggleSchemaView) : .pass
case "1": return .perform(.togglePane(.explorer))
case "2": return .perform(.togglePane(.editor))
case "3": return .perform(.togglePane(.terminal))
+14 -4
View File
@@ -130,16 +130,15 @@ private struct PaneToggles: View {
}
}
/// Git ⌘G · Search ⌘F · Fluid ⌘L · Hidden ⌘., then `?`. Search is an action; the others toggle.
/// While Helder reads aloud, a Stop toggle leads the group; switching it off stops the reading.
/// Git ⌘G · Schema ⌘D · Search ⌘F · Fluid ⌘L · Hidden ⌘., then `?`. Search is an action; the others toggle.
/// Schema shows only in a Laravel app. While Helder reads aloud, a Stop toggle leads the group.
private struct TitleToolbar: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
HStack(spacing: Metrics.toolbarIconGap) {
ButtonGroup(stop + [
git,
ButtonGroup(stop + [git] + schema + [
GroupItem("Search", keys: "⌘F", kind: .action,
tip: Text("Search the open file, the project and the file names.")) { model.perform(.showSearch(seed: "")) },
GroupItem("Fluid", keys: "⌘L", kind: .toggle(isOn: layout.fluid),
@@ -173,6 +172,17 @@ private struct TitleToolbar: View {
}
}
private var schema: [GroupItem] {
guard model.schema?.isLaravelApp == true else { return [] }
let open = model.layout.isSchemaViewOpen
let tip = open
? Tooltip.stated("Schema view: ", "open", ". Click to close it (⌘D).")
: Tooltip.stated("Schema view: ", "closed", ". Click to open the database diagram (⌘D).")
return [GroupItem("Schema", keys: "⌘D", kind: .toggle(isOn: open), tip: tip) {
model.perform(.toggleSchemaView)
}]
}
private var stop: [GroupItem] {
guard model.readAloud.isReading else { return [] }
return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) {
+17 -11
View File
@@ -8,7 +8,8 @@ struct WindowBridge: NSViewRepresentable {
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
let title: String
let hasProject: Bool
let gitViewOpen: Bool
/// The Git or the Schema view covers the columns.
let fullScreenViewOpen: Bool
func makeCoordinator() -> WindowCoordinator {
WindowCoordinator(model: model)
@@ -22,7 +23,7 @@ struct WindowBridge: NSViewRepresentable {
func updateNSView(_ view: BridgeView, context: Context) {
context.coordinator.updateTitle(title, hasProject: hasProject)
context.coordinator.updateGitView(open: gitViewOpen)
context.coordinator.updateFullScreenView(open: fullScreenViewOpen)
context.coordinator.guardClose()
}
@@ -50,7 +51,7 @@ final class WindowCoordinator: NSObject {
/// Set once the unsaved prompt said yes, so the second close goes through.
private var closeApproved = false
private var isAskingToClose = false
private var gitViewOpen = false
private var fullScreenViewOpen = false
init(model: WorkspaceModel) {
self.model = model
@@ -106,11 +107,11 @@ final class WindowCoordinator: NSObject {
AppName.set(hasProject ? title : AppName.standard)
}
/// Opening the Git view takes the keyboard from the column behind it at once; its message field
/// takes focus a run loop later, so typing never lands in a covered terminal.
func updateGitView(open: Bool) {
defer { gitViewOpen = open }
guard open, !gitViewOpen, let window else { return }
/// Opening the Git or Schema view takes the keyboard from the column behind it at once; the Git
/// message field takes focus a run loop later, so typing never lands in a covered terminal.
func updateFullScreenView(open: Bool) {
defer { fullScreenViewOpen = open }
guard open, !fullScreenViewOpen, let window else { return }
window.makeFirstResponder(nil)
}
@@ -221,7 +222,7 @@ final class WindowCoordinator: NSObject {
private func handleMouseDown(_ event: NSEvent) {
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented,
!model.layout.isGitViewOpen else { return }
!model.layout.isGitViewOpen, !model.layout.isSchemaViewOpen else { return }
let point = event.locationInWindow
let height = window.contentView?.bounds.height ?? window.frame.height
guard height - point.y > Metrics.titleBar, point.y > Metrics.statusBar else { return }
@@ -248,8 +249,9 @@ final class WindowCoordinator: NSObject {
var editorSelection: TextSelectionInfo?
var seed = ""
let gitViewOpen = model.layout.isGitViewOpen
let schemaViewOpen = model.layout.isSchemaViewOpen
if let text = responder as? NSTextView {
let column = gitViewOpen ? nil : column(of: text)
let column = gitViewOpen || schemaViewOpen ? nil : column(of: text)
owner = .text(in: column)
let range = text.selectedRange()
hasSelection = range.length > 0
@@ -285,7 +287,11 @@ final class WindowCoordinator: NSObject {
recentFileCount: editor?.history.count ?? 0,
searchSeed: seed,
gitViewOpen: gitViewOpen,
inGitConsole: responder is GitConsoleFieldEditor
inGitConsole: responder is GitConsoleFieldEditor,
schemaAvailable: model.schema?.isLaravelApp ?? false,
schemaViewOpen: schemaViewOpen,
schemaHasSelection: model.schema?.selected != nil,
schemaSearchHasText: responder is SchemaSearchFieldEditor && !(model.schema?.query.isEmpty ?? true)
)
}
+12 -4
View File
@@ -2,8 +2,8 @@ import AppKit
import HelderCore
import SwiftUI
/// The launcher without a project; with one, the title bar, three columns and status bar, then the Git view
/// over all of them, overlays above.
/// The launcher without a project; with one, the title bar, three columns and status bar, then the Git or
/// Schema view over all of them, overlays above.
struct WorkspaceView: View {
let model: WorkspaceModel
@@ -37,12 +37,19 @@ struct WorkspaceView: View {
.environment(\.pointerLayer, model.overlay.isPresented ? .workspace : .overlay)
}
}
.overlay {
if model.layout.isSchemaViewOpen, let schema = model.schema {
SchemaView(model: model, store: schema)
.environment(\.pointerLayer, model.overlay.isPresented ? .workspace : .overlay)
}
}
.overlay { OverlayHost(model: model) }
.overlay {
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model).environment(\.pointerLayer, .overlay) }
}
.background(PointerRefresher(trigger: PointerRefresher.Trigger(
overlay: model.overlay.current, gitViewOpen: model.layout.isGitViewOpen, activePath: model.editor?.activePath,
overlay: model.overlay.current, gitViewOpen: model.layout.isGitViewOpen,
schemaViewOpen: model.layout.isSchemaViewOpen, activePath: model.editor?.activePath,
visibility: model.layout.visibility, scale: model.layout.textScale)))
.onAppear { model.layout.windowResized(width: proxy.size.width) }
.onChange(of: proxy.size.width) { _, width in model.layout.windowResized(width: width) }
@@ -147,12 +154,13 @@ private struct HiddenPaneFocusGuard: NSViewRepresentable {
}
}
/// Re-reads the pointer when what lies under a still mouse changes: an overlay, the Git view, the open file,
/// Re-reads the pointer when what lies under a still mouse changes: an overlay, the Git or Schema view, the open file,
/// a column shown or hidden.
private struct PointerRefresher: NSViewRepresentable {
struct Trigger: Equatable {
var overlay: Overlay
var gitViewOpen: Bool
var schemaViewOpen: Bool
var activePath: String?
var visibility: ColumnVisibility
var scale: Double
+1 -1
View File
@@ -14,7 +14,7 @@ public struct WorkspaceWindow: View {
.frame(minWidth: Metrics.minimumWindow.width, minHeight: Metrics.minimumWindow.height)
.background(Palette.editor)
.background(WindowBridge(model: model, title: model.title, hasProject: model.root != nil,
gitViewOpen: model.layout.isGitViewOpen))
fullScreenViewOpen: model.layout.isGitViewOpen || model.layout.isSchemaViewOpen))
.preferredColorScheme(.dark)
.focusedSceneValue(\.workspace, model)
.task { await model.start() }
+14 -1
View File
@@ -92,6 +92,8 @@ public final class LayoutStore {
public private(set) var visibility = ColumnVisibility.all
/// ⌘G: the full-screen Git view over the whole window. Not persisted; the columns stay mounted under it.
public private(set) var isGitViewOpen = false
/// ⌘D: the full-screen Schema view, in Laravel apps. Not persisted; it and the Git view never show together.
public private(set) var isSchemaViewOpen = false
/// ⌘L: columns re-fit on resize and focus. A manual splitter drag turns this off.
public private(set) var fluid = true
/// ⌘.: dotfiles show in the tree and the search.
@@ -141,6 +143,7 @@ public final class LayoutStore {
activePanel = nil
focusZone = .neutral
isGitViewOpen = false
isSchemaViewOpen = false
let saved = persistence?.load(root: root)
visibility = saved?.visibility ?? .all
fluid = saved?.fluid ?? true
@@ -182,6 +185,7 @@ public final class LayoutStore {
public func openGitView() {
isGitViewOpen = true
isSchemaViewOpen = false
}
public func closeGitView() {
@@ -189,7 +193,16 @@ public final class LayoutStore {
}
public func toggleGitView() {
isGitViewOpen.toggle()
isGitViewOpen ? closeGitView() : openGitView()
}
public func openSchemaView() {
isSchemaViewOpen = true
isGitViewOpen = false
}
public func closeSchemaView() {
isSchemaViewOpen = false
}
public func toggleFluid() {
+308
View File
@@ -0,0 +1,308 @@
import Foundation
import HelderCore
import HelderServices
import Observation
/// One artisan console line with an id that stays put while older lines drop off the top.
public struct SchemaConsoleEntry: Identifiable, Sendable, Equatable {
public let id: Int
public var line: ArtisanConsoleLine
}
/// What the Schema view's body shows.
public enum SchemaViewBody: Equatable, Sendable {
/// The first check has not landed yet.
case loading
/// `HelderSchemaCommand.php` does not exist: the view offers the prompt that writes it.
case commandMissing
/// The command exists but `database/helder/schema.json` does not.
case noDump
case diagram
}
/// The Schema view's state for one Laravel project: the dump, the card positions, pan and zoom,
/// hover, selection, search and the artisan console.
@Observable
@MainActor
public final class SchemaStore {
public private(set) var isLaravelApp = false
public private(set) var hasCommand = false
public private(set) var hasChecked = false
public private(set) var model: SchemaModel?
public private(set) var positions: [String: SchemaPoint] = [:]
public private(set) var viewport = SchemaViewport()
public private(set) var hovered: String?
/// A hovered foreign key, `table.column`.
public private(set) var hoveredColumn: String?
public private(set) var selected: String?
public var query = ""
public private(set) var isBusy = false
/// When the shown dump was written: its `generated_at`, else the file's date.
public private(set) var lastDumpTime: Date?
public private(set) var lines: [SchemaConsoleEntry] = []
public private(set) var isConsoleOpen = false
/// The last read error of the dump, nil once a read succeeds.
public private(set) var loadError: String?
/// The canvas between the table list and the detail panel, as last laid out.
public private(set) var canvasSize = SchemaSize(width: 0, height: 0)
/// The card being dragged; hover stays put while it moves.
public private(set) var draggedTable: String?
public static let maxConsoleLines = 400
public static let detailPanelWidth = 320.0
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
@ObservationIgnored private let service: SchemaServicing
@ObservationIgnored private let layouts: SchemaLayoutPersisting
@ObservationIgnored private let root: String
/// The modification date of the dump last read, so a watcher event re-reads only a changed file.
@ObservationIgnored private var dumpDate: Date?
@ObservationIgnored private var hasReadDump = false
@ObservationIgnored private var needsFit = false
@ObservationIgnored private var hasFitted = false
@ObservationIgnored private var nextLineID = 0
public init(service: SchemaServicing, layouts: SchemaLayoutPersisting, root: String) {
self.service = service
self.layouts = layouts
self.root = root
}
// MARK: Derived
public var body: SchemaViewBody {
guard hasChecked else { return .loading }
if !hasCommand { return .commandMissing }
return model == nil ? .noDump : .diagram
}
/// What lights up for the current hover, selection and search; nil without a dump.
public var highlight: SchemaHighlight? {
model.map { SchemaHighlight(model: $0, hovered: hovered, selected: selected, hoveredColumn: hoveredColumn, query: query) }
}
/// `no command yet`, `no dump yet`, or `dumped 14:32 · 16 tables · 23 relations`.
public var metaLabel: String {
if hasChecked && !hasCommand { return "no command yet" }
guard let model else { return "no dump yet" }
let time = lastDumpTime.map { Self.timeFormatter.string(from: $0) } ?? "—"
return "dumped \(time) · \(model.tableCount) tables · \(model.relationCount) relations"
}
public var runLabel: String {
if isBusy { return "Dumping…" }
return model == nil ? "Run helder:schema" : "Re-run helder:schema"
}
/// The list rows: the tables matching the query, in name order.
public var listedTables: [SchemaTable] {
model.map { SchemaSearch.filter($0, query: query) } ?? []
}
public var selectedTable: SchemaTable? {
selected.flatMap { model?.table(named: $0) }
}
private static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
// MARK: Disk
/// Re-reads whether the project is a Laravel app and has the command.
public func check() async {
async let laravel = service.isLaravelApp()
async let command = service.hasCommand()
let (isLaravel, hasCommand) = await (laravel, command)
isLaravelApp = isLaravel
self.hasCommand = hasCommand
hasChecked = true
}
/// The view opened: checks the project and reads the dump when it changed since the last read.
public func opened() async {
await refresh(readingDump: true)
}
/// A watcher pass; the dump is only read while `readingDump` (the view is open) or one is already shown.
public func refresh(readingDump: Bool) async {
await check()
guard isLaravelApp, readingDump || model != nil else { return }
let date = await service.dumpModificationDate()
guard !hasReadDump || date != dumpDate else { return }
await reload()
}
/// Reads the dump, keeping the view and the positions of the tables that remain.
/// A corrupt dump logs its error to the console and toasts once per changed file.
public func reload() async {
dumpDate = await service.dumpModificationDate()
hasReadDump = true
do {
guard let next = try await service.readDump() else {
model = nil
loadError = nil
return
}
loadError = nil
apply(next)
} catch {
let message = (error as? LocalizedError)?.errorDescription ?? "\(error)"
loadError = message
log(message, .error)
isConsoleOpen = true
notify("Could not read the schema", SchemaPaths.dumpFile)
}
}
private func apply(_ next: SchemaModel) {
let saved = positions.isEmpty ? layouts.loadPositions(root: root) : positions
positions = SchemaLayout.positions(next, saved: saved)
model = next
lastDumpTime = next.generatedDate ?? dumpDate ?? Date()
let names = Set(next.tables.map(\.name))
if let selected, !names.contains(selected) { self.selected = nil }
if let hovered, !names.contains(hovered) { self.hovered = nil }
if let hoveredColumn, next.edges.allSatisfy({ $0.id != hoveredColumn }) { self.hoveredColumn = nil }
if !hasFitted {
needsFit = true
fitIfReady()
}
}
// MARK: Running helder:schema
/// Runs the command, streaming its output into the console; on exit 0 the dump is re-read.
/// A click while it runs is ignored.
public func run() async {
guard !isBusy, hasCommand else { return }
isBusy = true
isConsoleOpen = true
log(ArtisanOutputClassifier.commandEcho, .command)
let (stream, continuation) = AsyncStream<(String, Bool)>.makeStream()
let consumer = Task { [weak self] in
for await (line, isError) in stream {
let classified = ArtisanOutputClassifier.line(line, isError: isError)
self?.log(classified.text, classified.kind)
}
}
let code = await service.runDump { line, isError in continuation.yield((line, isError)) }
continuation.finish()
await consumer.value
isBusy = false
guard code == 0 else { return }
await reload()
if loadError == nil, let model { notify("Schema dumped · \(model.tableCount) tables", nil) }
}
public func hideConsole() {
isConsoleOpen = false
}
private func log(_ text: String, _ kind: ArtisanLineKind) {
lines.append(SchemaConsoleEntry(id: nextLineID, line: ArtisanConsoleLine(text: text, kind: kind)))
nextLineID += 1
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
}
// MARK: Pan and zoom
public func setCanvasSize(_ size: SchemaSize) {
guard size != canvasSize else { return }
canvasSize = size
fitIfReady()
}
/// Frames every card with a 48pt margin, at most 110%.
public func fit() {
guard let model, let bounds = SchemaGeometry.bounds(model, positions: positions), hasCanvas else { return }
viewport = SchemaGeometry.fit(bounds: bounds, in: canvasSize)
hasFitted = true
needsFit = false
}
/// Zooms around a canvas-view point, or around the centre for the `−` and `+` buttons.
public func zoom(by factor: Double, around anchor: SchemaPoint? = nil) {
guard model != nil else { return }
viewport = anchor.map { SchemaGeometry.zoom(viewport, by: factor, around: $0) }
?? SchemaGeometry.zoom(viewport, by: factor, in: canvasSize)
}
public func pan(dx: Double, dy: Double) {
guard model != nil else { return }
viewport.x += dx
viewport.y += dy
}
/// A background drag: the viewport it started from, moved by the drag.
public func setViewport(_ next: SchemaViewport) {
viewport = next
}
private var hasCanvas: Bool { canvasSize.width > 0 && canvasSize.height > 0 }
private func fitIfReady() {
guard needsFit, hasCanvas, model != nil else { return }
fit()
}
// MARK: Cards
public func moveTable(_ name: String, to point: SchemaPoint) {
guard positions[name] != nil else { return }
draggedTable = name
positions[name] = point
}
/// A card drag ended: the positions are saved for this project.
public func endDrag() {
guard draggedTable != nil else { return }
draggedTable = nil
layouts.savePositions(positions, root: root)
}
public func hover(_ table: String?) {
guard draggedTable == nil else { return }
hovered = table
if table == nil { hoveredColumn = nil }
}
/// Only foreign-key rows narrow the highlight; nil leaves it to the hovered table.
public func hoverColumn(_ id: String?) {
guard draggedTable == nil else { return }
hoveredColumn = id
}
/// A click on a card: selects it, or deselects it when it already was.
public func toggleSelection(_ table: String) {
selected = selected == table ? nil : table
}
public func clearSelection() {
selected = nil
}
/// Selects the table and pans it to the middle; the detail panel's width is left out when it is about to open.
public func centre(_ name: String) {
guard let model, let table = model.table(named: name), let position = positions[name] else { return }
let width = canvasSize.width - (selected == nil ? Self.detailPanelWidth : 0)
viewport = SchemaGeometry.centre(table, at: position, in: SchemaSize(width: width, height: canvasSize.height), view: viewport)
selected = name
hovered = nil
hoveredColumn = nil
}
/// ↵ in the table search.
public func centreFirstMatch() {
guard !query.trimmingCharacters(in: .whitespaces).isEmpty, let first = listedTables.first else { return }
centre(first.name)
}
public func clearSearch() {
query = ""
}
}
@@ -93,6 +93,28 @@ extension WorkspaceModel {
if panel == .editor { editor?.requestTextFocus() }
}
// MARK: Schema view
/// Opens the Schema view in a Laravel app and reads the command and dump; anywhere else it does nothing.
func openSchemaView() {
guard let schema, schema.isLaravelApp, !layout.isSchemaViewOpen else { return }
layout.openSchemaView()
focusRequest = nil
track { await schema.opened() }
}
/// Hands the keyboard back to the column that had it before the view opened.
func closeSchemaView() {
guard layout.isSchemaViewOpen else { return }
layout.closeSchemaView()
guard let panel = layout.activePanel else {
focusRequest = nil
return
}
focusRequest = FocusRequest(.panel(panel))
if panel == .editor { editor?.requestTextFocus() }
}
// MARK: Focus and the row cursor
func focus(_ panel: Panel) {
@@ -67,6 +67,9 @@ extension WorkspaceModel {
self.editor = editor
cleanCopy = CleanCopyStore(files: services.files)
let schema = SchemaStore(service: services.schema, layouts: app.schemaLayouts, root: root.path)
schema.notify = notify
self.schema = schema
terminal = TerminalStore(projectRoot: root.path)
wireTerminal()
launcher = LauncherList(recents: recentProjects, excluding: root.path)
@@ -98,11 +101,12 @@ extension WorkspaceModel {
recentProjects = await app.recentProjects.list()
guard generation == current else { return }
launcher = LauncherList(recents: recentProjects, excluding: root.path)
let sourceControl = sourceControl, explorer = explorer, editor = editor, cleanCopy = cleanCopy
let sourceControl = sourceControl, explorer = explorer, editor = editor, cleanCopy = cleanCopy, schema = schema
async let git: Void = sourceControl?.refresh() ?? ()
async let tree: Void = explorer?.reload() ?? ()
async let baseline: Void = cleanCopy?.loadBaseline() ?? ()
_ = await (git, tree, baseline)
async let laravel: Void = schema?.check() ?? ()
_ = await (git, tree, baseline, laravel)
await editor?.restore(restoreSession: config.session.restoreOnLaunch)
guard generation == current else { return }
startWatcher(root)
@@ -7,7 +7,7 @@ extension WorkspaceModel {
public func refresh() async {
refreshTick += 1
let editor = editor
async let reread: Void = run([.git, .tree])
async let reread: Void = run([.git, .tree, .schema])
async let active: Void = editor?.reloadActiveFromDisk() ?? ()
_ = await (reread, active)
}
@@ -15,7 +15,7 @@ extension WorkspaceModel {
/// Reacts to a disk change from the watcher: project and git events gather into one debounced refresh.
public func handle(_ event: WatchEvent) async {
switch event {
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles])
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .schema])
case .git: scheduleRefresh(.git)
case .config: await reloadConfig()
case .cleanCopy: await cleanCopyChanged()
@@ -61,7 +61,8 @@ extension WorkspaceModel {
/// Reads the stores once up front, so a pass that outlives a project switch only touches the old project.
func run(_ scope: RefreshScope) async {
let sourceControl = sourceControl, explorer = explorer, editor = editor
let sourceControl = sourceControl, explorer = explorer, editor = editor, schema = schema
let readsDump = layout.isSchemaViewOpen
let current = generation
if scope.contains(.symbols) {
await services?.symbols.invalidate()
@@ -70,7 +71,8 @@ extension WorkspaceModel {
async let git: Void = scope.contains(.git) ? (sourceControl?.refresh() ?? ()) : ()
async let tree: Void = scope.contains(.tree) ? (explorer?.reload() ?? ()) : ()
async let files: Void = scope.contains(.openFiles) ? (editor?.filesChanged(nil) ?? ()) : ()
_ = await (git, tree, files)
async let dump: Void = scope.contains(.schema) ? (schema?.refresh(readingDump: readsDump) ?? ()) : ()
_ = await (git, tree, files, dump)
}
/// Restarts the countdown on every change, so a burst of writes loads the class list once.
@@ -41,6 +41,8 @@ public struct RefreshScope: OptionSet, Sendable {
public static let symbols = RefreshScope(rawValue: 4)
/// The open file and every unsaved buffer pick up the disk text; unsaved edits are kept.
public static let openFiles = RefreshScope(rawValue: 8)
/// The Schema view's command file and dump.
public static let schema = RefreshScope(rawValue: 16)
}
/// A list row whose on-screen frame the ⌘→ menu anchors to.
@@ -81,6 +83,7 @@ public final class WorkspaceModel {
public internal(set) var editor: EditorStore?
public internal(set) var terminal: TerminalStore
public internal(set) var cleanCopy: CleanCopyStore?
public internal(set) var schema: SchemaStore?
@ObservationIgnored public let app: AppServices
@ObservationIgnored public internal(set) var services: WorkspaceServices?
@@ -148,6 +151,8 @@ public final class WorkspaceModel {
case .toggleGit: layout.isGitViewOpen ? closeGitView() : openGitView()
case .closeGitView: closeGitView()
case .toggleSchemaView: layout.isSchemaViewOpen ? closeSchemaView() : openSchemaView()
case .closeSchemaView: closeSchemaView()
case let .togglePane(panel): layout.togglePane(panel)
case .toggleAutoFit: layout.toggleFluid()
case .toggleHidden: layout.toggleHidden()
@@ -204,6 +209,27 @@ public final class WorkspaceModel {
}
case .focusCommitMessage: openGitView()
case .runSchemaDump:
guard let schema else { return }
track { await schema.run() }
case .generateSchemaCommand:
closeSchemaView()
passToAgent(SchemaCommandPrompt.text, toast: "Command prompt")
case .copySchemaPrompt:
app.system.copy(SchemaCommandPrompt.text)
toasts.show("Copied prompt")
case let .passSchemaTable(name):
closeSchemaView()
passToAgent("@schema:\(name)", toast: "@schema:\(name)")
case let .copySchemaTableName(name):
app.system.copy(name)
toasts.show("Copied table name", detail: name)
case .openSchemaCommandFile:
closeSchemaView()
open(SchemaPaths.commandFile)
case .clearSchemaSelection: schema?.clearSelection()
case .clearSchemaSearch: schema?.clearSearch()
case .copyCleanCopy: copyCleanCopy()
case .stopReading: readAloud.stop()
+12 -4
View File
@@ -10,15 +10,18 @@ public struct WorkspaceServices {
public var symbols: SymbolServicing
public var config: ConfigServicing
public var recentFiles: RecentFilesStoring
/// The Schema view's dump reading and `helder:schema` runs.
public var schema: SchemaServicing
public init(git: GitServicing, files: FileServicing, search: SearchServicing, symbols: SymbolServicing,
config: ConfigServicing, recentFiles: RecentFilesStoring) {
config: ConfigServicing, recentFiles: RecentFilesStoring, schema: SchemaServicing) {
self.git = git
self.files = files
self.search = search
self.symbols = symbols
self.config = config
self.recentFiles = recentFiles
self.schema = schema
}
public static func live(root: URL) -> WorkspaceServices {
@@ -30,7 +33,8 @@ public struct WorkspaceServices {
search: search,
symbols: SymbolService(root: root, config: config),
config: config,
recentFiles: RecentFilesStore(root: root)
recentFiles: RecentFilesStore(root: root),
schema: SchemaService(root: root)
)
}
}
@@ -41,6 +45,8 @@ public struct AppServices {
public var session: SessionStoring
/// Column widths and toggles, per project.
public var layouts: LayoutPersisting
/// Schema card positions, per project.
public var schemaLayouts: SchemaLayoutPersisting
/// Dialogs, pasteboard, Finder.
public var system: SystemActing
public var speech: SpeechServicing
@@ -49,11 +55,12 @@ public struct AppServices {
public var makeWatcher: () -> FileWatching
/// Every store is passed in, so a test can never reach the user's real recents, sessions or layouts.
public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting, system: SystemActing,
speech: SpeechServicing, makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting,
schemaLayouts: SchemaLayoutPersisting, system: SystemActing, speech: SpeechServicing, makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
self.recentProjects = recentProjects
self.session = session
self.layouts = layouts
self.schemaLayouts = schemaLayouts
self.system = system
self.speech = speech
self.makeWorkspace = makeWorkspace
@@ -64,6 +71,7 @@ public struct AppServices {
recentProjects: RecentProjectsStore(),
session: SessionStore(),
layouts: UserDefaultsLayoutStore(),
schemaLayouts: UserDefaultsSchemaLayoutStore(),
system: LiveSystemActions(),
speech: SpeechService(),
makeWorkspace: WorkspaceServices.live(root:),
+10
View File
@@ -150,6 +150,16 @@ public enum Palette {
public static let inlineAddedHighlight = Color(hex: 0x8FBFB4, alpha: 0.36)
public static let inlineFiller = Color(hex: 0x232C39, alpha: 0.35)
/// The colour of an artisan console line in the Schema view.
public static func artisan(_ kind: ArtisanLineKind) -> Color {
switch kind {
case .command: text1
case .output: text3
case .error: amber
case .success: gitNew
}
}
/// The colour of a console line.
public static func console(_ kind: GitLineKind) -> Color {
switch kind {
+14
View File
@@ -110,6 +110,20 @@ public enum Typography {
public static let gitEmpty = TypeRole(.sansRegular, 13, lineHeight: 20.8)
public static let console = TypeRole(.monoRegular, 12, lineHeight: 19.2)
public static let branchCurrent = TypeRole(.monoSemiBold, 12)
// MARK: Schema view
/// The empty and command-missing copy: Sans 15/1.6, with paths in mono at the same size.
public static let schemaBody = TypeRole(.sansRegular, 15, lineHeight: 24)
public static let schemaBodyMono = TypeRole(.monoRegular, 15, lineHeight: 24)
/// A card's table name.
public static let schemaCardName = TypeRole(.monoBold, 12)
/// `PK`, `FK`, `UQ` on a card row.
public static let schemaKey = TypeRole(.monoBold, 9, trackingEm: 0.06)
public static let schemaZoom = TypeRole(.monoMedium, 11)
public static let schemaDetailName = TypeRole(.monoBold, 13)
public static let schemaDetailColumn = TypeRole(.monoMedium, 12, lineHeight: 16.8)
public static let schemaDetailMeta = TypeRole(.monoRegular, 11, lineHeight: 15.4)
}
extension View {