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
+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:),