Files
helder/Sources/HelderUI/State/SchemaStore.swift
T

309 lines
12 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 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 = ""
}
}