diff --git a/Sources/HelderCore/Schema/ArtisanConsole.swift b/Sources/HelderCore/Schema/ArtisanConsole.swift new file mode 100644 index 0000000..8fe7b63 --- /dev/null +++ b/Sources/HelderCore/Schema/ArtisanConsole.swift @@ -0,0 +1,41 @@ +import Foundation + +/// How a line in the Schema view's artisan console is painted. +public enum ArtisanLineKind: String, Sendable, Equatable { + case command + case output + case error + case success +} + +public struct ArtisanConsoleLine: Sendable, Equatable { + public var text: String + public var kind: ArtisanLineKind + + public init(text: String, kind: ArtisanLineKind) { + self.text = text + self.kind = kind + } +} + +public enum ArtisanOutputClassifier { + /// `$ php artisan helder:schema`, the echo before a run. + public static let commandEcho = "$ " + SchemaPaths.commandLine + + /// Stderr and `ERROR`/`Exception` lines are errors; Laravel's `INFO`/`DONE` blocks and `Wrote …` are successes. + /// + /// PHP writes warnings to stderr too, but there they still mean the run went wrong for the user. + public static func classify(_ line: String, isError: Bool) -> ArtisanLineKind { + if isError { return .error } + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.hasPrefix("ERROR") || trimmed.hasPrefix("FAIL") || line.contains("Exception") { return .error } + if trimmed.hasPrefix("INFO") || trimmed.hasPrefix("DONE") || trimmed.hasPrefix("Wrote ") || trimmed.hasPrefix("Schema dumped") { + return .success + } + return .output + } + + public static func line(_ text: String, isError: Bool) -> ArtisanConsoleLine { + ArtisanConsoleLine(text: text, kind: classify(text, isError: isError)) + } +} diff --git a/Sources/HelderCore/Schema/SchemaCommandPrompt.swift b/Sources/HelderCore/Schema/SchemaCommandPrompt.swift new file mode 100644 index 0000000..f9d323c --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaCommandPrompt.swift @@ -0,0 +1,214 @@ +import Foundation + +/// The prompt that asks an agent to write `HelderSchemaCommand` in a Laravel project. +public enum SchemaCommandPrompt { + /// The JSON contract in this text is what `SchemaDump` decodes; change both together. + public static let text = #""" + Build an Artisan command that dumps this app's database schema for Helder, the IDE that draws it as a diagram. + + File: app/Console/Commands/HelderSchemaCommand.php + Class: App\Console\Commands\HelderSchemaCommand, extends Illuminate\Console\Command + Signature: helder:schema {--connection= : Database connection to read (default: the default connection)} + Description: Dump the database schema for Helder to visualise. + + What the command does: + 1. Read the structure with Laravel's schema builder only: Schema::connection($connection)->getTables(), getColumns($table), getIndexes($table) and getForeignKeys($table). Write no raw SQL for the structure. If this Laravel version has no Schema::getTables(), stop and tell me. + 2. Skip these tables: migrations, jobs, job_batches, failed_jobs, cache, cache_locks, sessions, password_reset_tokens. + 3. Count the rows of each table with DB::connection($connection)->table($table)->count(). When one count fails, write null for that table and go on. + 4. Write the JSON below to database/helder/schema.json. Create database/helder when it is missing. Write to a temporary file in that folder first, then rename it, so Helder never reads a half-written file. + 5. Make sure database/helder/.gitignore exists with the two lines `*` and `!.gitignore`, so the dump stays out of git. + 6. Print the counts with $this->components->twoColumnDetail(): Connection (` · `), Tables, Columns, Foreign keys. Then print `Wrote database/helder/schema.json ( KB)` with $this->components->info() and return self::SUCCESS. On an error, print it with $this->components->error() and return self::FAILURE. + + The JSON contract. Helder reads exactly these keys. Keep the arrays from the schema builder as they come, unchanged: + + { + "version": 1, + "connection": "", + "driver": "getDriverName()>", + "database": "getDatabaseName()>", + "generated_at": "toIso8601String()>", + "tables": [ + { + "name": "", + "rows": , + "columns": [ ], + "indexes": [ ], + "foreign_keys": [ ] + } + ] + } + + Sort the tables by name. Encode with JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR. + + Follow the code style of this project. Add no migration, no route and no package. When the command is done, run `php artisan helder:schema` once and show me the output. + + A working example follows. Use it as the starting point and adapt it to this project's conventions. Schema::getCurrentSchemaListing() keeps MySQL to this connection's own database; if this Laravel version does not have that method, filter the result of getTables() by the connection's database instead. + + ```php + option('connection') ?: config('database.default')); + $payload = $this->buildPayload($connection); + $path = $this->writeAtomically($payload); + + $tables = Arr::get($payload, 'tables', []); + + $this->components->twoColumnDetail('Connection', $connection.' · '.Arr::get($payload, 'database')); + $this->components->twoColumnDetail('Tables', (string) count($tables)); + $this->components->twoColumnDetail('Columns', (string) $this->countOf($tables, 'columns')); + $this->components->twoColumnDetail('Foreign keys', (string) $this->countOf($tables, 'foreign_keys')); + + $size = number_format(filesize($path) / 1024, 1); + $this->components->info("Wrote database/helder/schema.json ({$size} KB)"); + + return self::SUCCESS; + } catch (Throwable $exception) { + $this->components->error($exception->getMessage()); + + return self::FAILURE; + } + } + + /** + * Build the schema payload for one connection. + * + * @return array + */ + private function buildPayload(string $connection): array + { + $schema = Schema::connection($connection); + + // On MySQL, getTables() without an argument lists the tables of every database on the server; the listing limits it to this connection's database. + $names = Arr::pluck($schema->getTables($schema->getCurrentSchemaListing()), 'name'); + $names = array_values(array_diff($names, self::SKIPPED_TABLES)); + sort($names); + + $tables = []; + + foreach ($names as $name) { + $tables[] = [ + 'name' => $name, + 'rows' => $this->countRows($connection, $name), + 'columns' => $schema->getColumns($name), + 'indexes' => $schema->getIndexes($name), + 'foreign_keys' => $schema->getForeignKeys($name), + ]; + } + + return [ + 'version' => 1, + 'connection' => $connection, + 'driver' => DB::connection($connection)->getDriverName(), + 'database' => DB::connection($connection)->getDatabaseName(), + 'generated_at' => now()->toIso8601String(), + 'tables' => $tables, + ]; + } + + /** + * Count the rows of a table, or return null when the count fails. + */ + private function countRows(string $connection, string $table): ?int + { + try { + return DB::connection($connection)->table($table)->count(); + } catch (Throwable) { + return null; + } + } + + /** + * Sum the size of one list key over all tables. + * + * @param array> $tables + */ + private function countOf(array $tables, string $key): int + { + return array_sum(array_map(fn (array $table): int => count(Arr::get($table, $key, [])), $tables)); + } + + /** + * Write the payload to schema.json through a temp file and a rename, and return the path. + * + * @param array $payload + */ + private function writeAtomically(array $payload): string + { + $directory = database_path('helder'); + $target = $directory.'/schema.json'; + $gitignore = $directory.'/.gitignore'; + + File::ensureDirectoryExists($directory); + + if (! File::exists($gitignore)) { + File::put($gitignore, "*\n!.gitignore\n"); + } + + $json = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + $temporary = tempnam($directory, 'schema.json.'); + + try { + File::put($temporary, $json); + File::chmod($temporary, 0644); + + if (! rename($temporary, $target)) { + throw new RuntimeException('Could not move the temp file onto schema.json.'); + } + } catch (Throwable $exception) { + File::delete($temporary); + + throw $exception; + } + + return $target; + } + } + ``` + """# +} diff --git a/Sources/HelderCore/Schema/SchemaDump.swift b/Sources/HelderCore/Schema/SchemaDump.swift new file mode 100644 index 0000000..53526c7 --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaDump.swift @@ -0,0 +1,277 @@ +import Foundation + +public enum SchemaDumpError: Error, Equatable, LocalizedError { + /// The file is not a JSON object; `reason` is the decoder's message. + case corrupt(reason: String) + + public var errorDescription: String? { + switch self { + case let .corrupt(reason): "\(SchemaPaths.dumpFile) is not a valid schema dump: \(reason)" + } + } +} + +/// `database/helder/schema.json` as the `helder:schema` command writes it (contract version 1). +/// +/// Decoding is tolerant: a missing or mistyped key gets its default and a table without a name is skipped, +/// so the older prototype dump (no version, driver, database or rows) still loads. +public struct SchemaDump: Sendable, Equatable, Decodable { + public var version: Int? + public var connection: String? + public var driver: String? + public var database: String? + public var generatedAt: String? + public var tables: [Table] + + public init(version: Int? = 1, connection: String? = nil, driver: String? = nil, database: String? = nil, + generatedAt: String? = nil, tables: [Table] = []) { + self.version = version + self.connection = connection + self.driver = driver + self.database = database + self.generatedAt = generatedAt + self.tables = tables + } + + /// Throws `SchemaDumpError.corrupt` when the data is not a JSON object. + public static func decode(_ data: Data) throws -> SchemaDump { + do { + return try JSONDecoder().decode(SchemaDump.self, from: data) + } catch let error as DecodingError { + throw SchemaDumpError.corrupt(reason: Self.describe(error)) + } catch { + throw SchemaDumpError.corrupt(reason: error.localizedDescription) + } + } + + private static func describe(_ error: DecodingError) -> String { + switch error { + case let .dataCorrupted(context): + let underlying = (context.underlyingError as NSError?)?.userInfo[NSDebugDescriptionErrorKey] as? String + return underlying ?? context.debugDescription + case let .typeMismatch(_, context), let .valueNotFound(_, context), let .keyNotFound(_, context): + return context.debugDescription + @unknown default: + return "\(error)" + } + } + + private enum CodingKeys: String, CodingKey { + case version, connection, driver, database, generatedAt = "generated_at", tables + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + version = c.lenientInt(.version) + connection = c.lenientString(.connection) + driver = c.lenientString(.driver) + database = c.lenientString(.database) + generatedAt = c.lenientString(.generatedAt) + tables = c.lenientList(Table.self, .tables) + } + + public struct Table: Sendable, Equatable, Decodable { + public var name: String + public var rows: Int? + public var columns: [Column] + public var indexes: [Index] + public var foreignKeys: [ForeignKey] + + public init(name: String, rows: Int? = nil, columns: [Column] = [], indexes: [Index] = [], foreignKeys: [ForeignKey] = []) { + self.name = name + self.rows = rows + self.columns = columns + self.indexes = indexes + self.foreignKeys = foreignKeys + } + + private enum CodingKeys: String, CodingKey { + case name, rows, columns, indexes, foreignKeys = "foreign_keys" + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + guard let name = c.lenientString(.name), !name.isEmpty else { + throw DecodingError.keyNotFound(CodingKeys.name, .init(codingPath: decoder.codingPath, debugDescription: "table without a name")) + } + self.name = name + rows = c.lenientInt(.rows) + columns = c.lenientList(Column.self, .columns) + indexes = c.lenientList(Index.self, .indexes) + foreignKeys = c.lenientList(ForeignKey.self, .foreignKeys) + } + } + + /// One item of Laravel's `Schema::getColumns()`. + public struct Column: Sendable, Equatable, Decodable { + public var name: String + public var typeName: String? + /// The full type, such as `varchar(255)`. + public var type: String? + public var nullable: Bool + /// Numbers and booleans are kept as their text. + public var defaultValue: String? + public var autoIncrement: Bool + public var comment: String? + + public init(name: String, typeName: String? = nil, type: String? = nil, nullable: Bool = false, + defaultValue: String? = nil, autoIncrement: Bool = false, comment: String? = nil) { + self.name = name + self.typeName = typeName + self.type = type + self.nullable = nullable + self.defaultValue = defaultValue + self.autoIncrement = autoIncrement + self.comment = comment + } + + private enum CodingKeys: String, CodingKey { + case name, typeName = "type_name", type, nullable, defaultValue = "default", autoIncrement = "auto_increment", comment + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + guard let name = c.lenientString(.name), !name.isEmpty else { + throw DecodingError.keyNotFound(CodingKeys.name, .init(codingPath: decoder.codingPath, debugDescription: "column without a name")) + } + self.name = name + typeName = c.lenientString(.typeName) + type = c.lenientString(.type) + nullable = c.lenientBool(.nullable) ?? false + defaultValue = c.lenientString(.defaultValue) + autoIncrement = c.lenientBool(.autoIncrement) ?? false + comment = c.lenientString(.comment) + } + } + + /// One item of Laravel's `Schema::getIndexes()`. + public struct Index: Sendable, Equatable, Decodable { + public var name: String? + public var columns: [String] + public var type: String? + public var unique: Bool + public var primary: Bool + + public init(name: String? = nil, columns: [String], type: String? = nil, unique: Bool = false, primary: Bool = false) { + self.name = name + self.columns = columns + self.type = type + self.unique = unique + self.primary = primary + } + + private enum CodingKeys: String, CodingKey { + case name, columns, type, unique, primary + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + name = c.lenientString(.name) + columns = c.lenientStrings(.columns) + type = c.lenientString(.type) + primary = c.lenientBool(.primary) ?? false + unique = c.lenientBool(.unique) ?? primary + } + } + + /// One item of Laravel's `Schema::getForeignKeys()`. + public struct ForeignKey: Sendable, Equatable, Decodable { + public var name: String? + public var columns: [String] + public var foreignSchema: String? + public var foreignTable: String + public var foreignColumns: [String] + public var onUpdate: String? + public var onDelete: String? + + public init(name: String? = nil, columns: [String], foreignSchema: String? = nil, foreignTable: String, + foreignColumns: [String] = [], onUpdate: String? = nil, onDelete: String? = nil) { + self.name = name + self.columns = columns + self.foreignSchema = foreignSchema + self.foreignTable = foreignTable + self.foreignColumns = foreignColumns + self.onUpdate = onUpdate + self.onDelete = onDelete + } + + private enum CodingKeys: String, CodingKey { + case name, columns, foreignSchema = "foreign_schema", foreignTable = "foreign_table", + foreignColumns = "foreign_columns", onUpdate = "on_update", onDelete = "on_delete" + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + guard let table = c.lenientString(.foreignTable), !table.isEmpty else { + throw DecodingError.keyNotFound(CodingKeys.foreignTable, .init(codingPath: decoder.codingPath, debugDescription: "foreign key without a table")) + } + name = c.lenientString(.name) + columns = c.lenientStrings(.columns) + foreignSchema = c.lenientString(.foreignSchema) + foreignTable = table + foreignColumns = c.lenientStrings(.foreignColumns) + onUpdate = c.lenientString(.onUpdate) + onDelete = c.lenientString(.onDelete) + } + } +} + +/// Reads that never throw: a missing or mistyped value is nil, and a list keeps only the items that decode. +private extension KeyedDecodingContainer { + func lenientString(_ key: Key) -> String? { + if let value = try? decodeIfPresent(String.self, forKey: key) { return value } + if let value = try? decodeIfPresent(Int.self, forKey: key) { return String(value) } + if let value = try? decodeIfPresent(Double.self, forKey: key) { return String(value) } + if let value = try? decodeIfPresent(Bool.self, forKey: key) { return value ? "true" : "false" } + return nil + } + + func lenientInt(_ key: Key) -> Int? { + if let value = try? decodeIfPresent(Int.self, forKey: key) { return value } + if let value = try? decodeIfPresent(Double.self, forKey: key), value.isFinite { return Int(value) } + if let value = try? decodeIfPresent(String.self, forKey: key) { return Int(value) } + return nil + } + + /// PDO drivers may hand booleans over as 0/1 or "1". + func lenientBool(_ key: Key) -> Bool? { + if let value = try? decodeIfPresent(Bool.self, forKey: key) { return value } + if let value = try? decodeIfPresent(Int.self, forKey: key) { return value != 0 } + if let value = try? decodeIfPresent(String.self, forKey: key) { + return ["1", "true", "yes"].contains(value.lowercased()) + } + return nil + } + + func lenientStrings(_ key: Key) -> [String] { + lenientList(LenientString.self, key).compactMap(\.value) + } + + func lenientList(_ type: T.Type, _ key: Key) -> [T] { + guard let items = try? decodeIfPresent([Failable].self, forKey: key) else { return [] } + return items.compactMap(\.value) + } +} + +private struct Failable: Decodable { + let value: T? + + init(from decoder: Decoder) throws { + value = try? T(from: decoder) + } +} + +private struct LenientString: Decodable { + let value: String? + + init(from decoder: Decoder) throws { + let c = try decoder.singleValueContainer() + if let text = try? c.decode(String.self) { + value = text + } else if let number = try? c.decode(Int.self) { + value = String(number) + } else { + value = nil + } + } +} diff --git a/Sources/HelderCore/Schema/SchemaGeometry.swift b/Sources/HelderCore/Schema/SchemaGeometry.swift new file mode 100644 index 0000000..c9bee6a --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaGeometry.swift @@ -0,0 +1,213 @@ +import Foundation + +/// A point on the schema canvas, in canvas units (before pan and zoom). +public struct SchemaPoint: Sendable, Hashable, Codable { + public var x: Double + public var y: Double + + public init(x: Double, y: Double) { + self.x = x + self.y = y + } +} + +public struct SchemaSize: Sendable, Hashable { + public var width: Double + public var height: Double + + public init(width: Double, height: Double) { + self.width = width + self.height = height + } +} + +public struct SchemaRect: Sendable, Hashable { + public var x: Double + public var y: Double + public var width: Double + public var height: Double + + public init(x: Double, y: Double, width: Double, height: Double) { + self.x = x + self.y = y + self.width = width + self.height = height + } + + public var maxX: Double { x + width } + public var maxY: Double { y + height } +} + +/// Pan and zoom: a canvas point `p` shows at `p * scale + (x, y)` in the viewport. +public struct SchemaViewport: Sendable, Hashable { + public var x: Double + public var y: Double + public var scale: Double + + public init(x: Double = 0, y: Double = 0, scale: Double = 1) { + self.x = x + self.y = y + self.scale = scale + } + + /// `100%` style label for the zoom control. + public var percentLabel: String { "\(Int((scale * 100).rounded()))%" } +} + +/// The fixed sizes of the Schema canvas; the line geometry depends on the card sizes. +public enum SchemaMetrics { + public static let cardWidth = 240.0 + /// The header, including its bottom border. + public static let headerHeight = 33.0 + public static let rowHeight = 22.0 + /// Card top to the centre of column 0: 1px border + 33 header + half a row. + public static let firstRowCentre = 45.0 + /// Header plus the card's top and bottom border. + public static let cardChrome = 35.0 + public static let laneSpacing = 340.0 + public static let cardGap = 48.0 + /// Where the default layout starts. + public static let layoutOrigin = SchemaPoint(x: 40, y: 40) + public static let fitMargin = 48.0 + public static let fitMaxScale = 1.1 + /// Room right of the rightmost card for same-lane loops, as the prototype's fit. + public static let fitExtraWidth = 60.0 + public static let minScale = 0.3 + public static let maxScale = 2.0 + public static let zoomStep = 1.2 + /// Card centres closer than this count as one lane: the line loops out on the right. + public static let sameLaneDistance = 240.0 + public static let loopBase = 46.0 + public static let loopFactor = 0.12 + public static let minCurve = 40.0 + public static let endRadius = 3.0 +} + +/// A cubic Bézier with horizontal tangents, from the foreign-key row to the referenced row. +public struct SchemaEdgePath: Sendable, Hashable { + public var start: SchemaPoint + public var control1: SchemaPoint + public var control2: SchemaPoint + public var end: SchemaPoint + + public init(start: SchemaPoint, control1: SchemaPoint, control2: SchemaPoint, end: SchemaPoint) { + self.start = start + self.control1 = control1 + self.control2 = control2 + self.end = end + } +} + +public enum SchemaGeometry { + public static func cardHeight(columns: Int) -> Double { + SchemaMetrics.cardChrome + Double(columns) * SchemaMetrics.rowHeight + } + + /// The vertical centre of column `index` in a card whose top is `top`. + public static func columnCentreY(top: Double, index: Int) -> Double { + top + SchemaMetrics.firstRowCentre + Double(index) * SchemaMetrics.rowHeight + } + + /// Right edge to left edge when the target is right, the mirror when left, a loop off the right edges in one lane. + public static func edgePath(from source: SchemaPoint, columnIndex: Int, to target: SchemaPoint, targetColumnIndex: Int) -> SchemaEdgePath { + let width = SchemaMetrics.cardWidth + let y1 = columnCentreY(top: source.y, index: columnIndex) + let y2 = columnCentreY(top: target.y, index: targetColumnIndex) + let sourceCentre = source.x + width / 2 + let targetCentre = target.x + width / 2 + let x1: Double, x2: Double, c1: Double, c2: Double + if abs(sourceCentre - targetCentre) < SchemaMetrics.sameLaneDistance { + x1 = source.x + width + x2 = target.x + width + let loop = SchemaMetrics.loopBase + abs(y2 - y1) * SchemaMetrics.loopFactor + c1 = x1 + loop + c2 = x2 + loop + } else if targetCentre > sourceCentre { + x1 = source.x + width + x2 = target.x + let d = max(SchemaMetrics.minCurve, (x2 - x1) / 2) + c1 = x1 + d + c2 = x2 - d + } else { + x1 = source.x + x2 = target.x + width + let d = max(SchemaMetrics.minCurve, (x1 - x2) / 2) + c1 = x1 - d + c2 = x2 + d + } + return SchemaEdgePath(start: SchemaPoint(x: x1, y: y1), control1: SchemaPoint(x: c1, y: y1), + control2: SchemaPoint(x: c2, y: y2), end: SchemaPoint(x: x2, y: y2)) + } + + /// Nil when either table has no position. + public static func edgePath(_ edge: SchemaEdge, positions: [String: SchemaPoint]) -> SchemaEdgePath? { + guard let source = positions[edge.from], let target = positions[edge.to] else { return nil } + return edgePath(from: source, columnIndex: edge.columnIndex, to: target, targetColumnIndex: edge.targetColumnIndex) + } + + public static func cardRect(_ table: SchemaTable, at position: SchemaPoint) -> SchemaRect { + SchemaRect(x: position.x, y: position.y, width: SchemaMetrics.cardWidth, height: table.cardHeight) + } + + /// The box around every placed card; nil when none is placed. + public static func bounds(_ model: SchemaModel, positions: [String: SchemaPoint]) -> SchemaRect? { + var x0 = Double.infinity, y0 = Double.infinity, x1 = -Double.infinity, y1 = -Double.infinity + for table in model.tables { + guard let p = positions[table.name] else { continue } + let rect = cardRect(table, at: p) + x0 = min(x0, rect.x) + y0 = min(y0, rect.y) + x1 = max(x1, rect.maxX) + y1 = max(y1, rect.maxY) + } + guard x0.isFinite else { return nil } + return SchemaRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0) + } + + public static func clampScale(_ scale: Double) -> Double { + min(SchemaMetrics.maxScale, max(SchemaMetrics.minScale, scale)) + } + + /// Frames `bounds` in `viewport` with a 48px margin, never above 110% nor below 30%. + public static func fit(bounds: SchemaRect, in viewport: SchemaSize) -> SchemaViewport { + let margin = SchemaMetrics.fitMargin * 2 + let width = bounds.width + SchemaMetrics.fitExtraWidth + let height = bounds.height + let fitting = min((viewport.width - margin) / max(width, 1), (viewport.height - margin) / max(height, 1)) + let scale = min(SchemaMetrics.fitMaxScale, max(SchemaMetrics.minScale, fitting)) + return SchemaViewport(x: (viewport.width - width * scale) / 2 - bounds.x * scale, + y: (viewport.height - height * scale) / 2 - bounds.y * scale, + scale: scale) + } + + /// Scales by `factor` (clamped to 30–200%) keeping the canvas point under `anchor` (viewport coordinates) in place. + public static func zoom(_ view: SchemaViewport, by factor: Double, around anchor: SchemaPoint) -> SchemaViewport { + let scale = clampScale(view.scale * factor) + let ratio = scale / view.scale + return SchemaViewport(x: anchor.x - (anchor.x - view.x) * ratio, + y: anchor.y - (anchor.y - view.y) * ratio, + scale: scale) + } + + /// Zooms around the viewport's centre, as the `−` and `+` buttons do. + public static func zoom(_ view: SchemaViewport, by factor: Double, in viewport: SchemaSize) -> SchemaViewport { + zoom(view, by: factor, around: SchemaPoint(x: viewport.width / 2, y: viewport.height / 2)) + } + + /// Pans so the card sits in the middle of `viewport`, keeping the scale; values are rounded to whole points. + /// + /// Pass the width left of the detail panel when it is about to open, as the prototype does. + public static func centre(_ table: SchemaTable, at position: SchemaPoint, in viewport: SchemaSize, view: SchemaViewport) -> SchemaViewport { + let k = view.scale + let midX = position.x + SchemaMetrics.cardWidth / 2 + let midY = position.y + table.cardHeight / 2 + return SchemaViewport(x: (viewport.width / 2 - midX * k).rounded(), + y: (viewport.height / 2 - midY * k).rounded(), + scale: k) + } + + /// The canvas point under a viewport point. + public static func canvasPoint(_ point: SchemaPoint, in view: SchemaViewport) -> SchemaPoint { + SchemaPoint(x: (point.x - view.x) / view.scale, y: (point.y - view.y) / view.scale) + } +} diff --git a/Sources/HelderCore/Schema/SchemaHighlight.swift b/Sources/HelderCore/Schema/SchemaHighlight.swift new file mode 100644 index 0000000..859d452 --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaHighlight.swift @@ -0,0 +1,95 @@ +import Foundation + +/// Which lines, cards and rows light up for the current hover, selection and search. +public struct SchemaHighlight: Sendable, Equatable { + /// The hovered table, else the selected one. + public var focus: String? + /// Ids (`table.column`) of the edges drawn in amber. + public var activeEdges: Set + /// Both ends of every active edge, plus the focus. + public var relatedTables: Set + /// Cards drawn at 30% opacity. + public var dimmedTables: Set + /// Cards whose name holds the search query; empty without a query. + public var searchMatches: Set + /// The foreign-key rows and the rows they reference, of every active edge. + public var highlightedColumns: Set + /// True when inactive lines take the receded colour (a focus, a hovered key, or a query). + public var linesRecede: Bool + + /// A hovered foreign key (`table.column`) narrows the highlight to its one edge and wins over the focus. + /// + /// The search only dims cards while nothing is focused. + public init(model: SchemaModel, hovered: String?, selected: String?, hoveredColumn: String?, query: String) { + let focus = hovered ?? selected + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let active = model.edges.filter { edge in + if let hoveredColumn { return edge.id == hoveredColumn } + guard let focus else { return false } + return edge.from == focus || edge.to == focus + } + var related = Set(active.flatMap { [$0.from, $0.to] }) + if let focus { related.insert(focus) } + + var columns = Set() + for edge in active { + columns.insert(SchemaColumnRef(table: edge.from, column: edge.column)) + if let target = model.table(named: edge.to), edge.targetColumnIndex < target.columns.count { + columns.insert(SchemaColumnRef(table: edge.to, column: target.columns[edge.targetColumnIndex].name)) + } + } + + let names = model.tables.map(\.name) + let matches = needle.isEmpty ? Set() : Set(names.filter { $0.lowercased().contains(needle) }) + let dimsAll = focus != nil || hoveredColumn != nil + let dimmed: Set = if dimsAll { + Set(names.filter { !related.contains($0) }) + } else if !needle.isEmpty { + Set(names.filter { !matches.contains($0) }) + } else { + [] + } + + self.focus = focus + activeEdges = Set(active.map(\.id)) + relatedTables = related + dimmedTables = dimmed + searchMatches = matches + highlightedColumns = columns + linesRecede = dimsAll || !needle.isEmpty + } + + public func isActive(_ edge: SchemaEdge) -> Bool { + activeEdges.contains(edge.id) + } + + public func isHighlighted(table: String, column: String) -> Bool { + highlightedColumns.contains(SchemaColumnRef(table: table, column: column)) + } + + /// 1 or 0.3. + public func opacity(of table: String) -> Double { + dimmedTables.contains(table) ? 0.3 : 1 + } + + /// The edges in drawing order: inactive first, so active lines sit on top. + public func drawingOrder(_ edges: [SchemaEdge]) -> [SchemaEdge] { + edges.filter { !isActive($0) } + edges.filter(isActive) + } +} + +public enum SchemaSearch { + /// The tables whose name holds `query` (case-insensitive), in name order; all of them for an empty query. + public static func filter(_ model: SchemaModel, query: String) -> [SchemaTable] { + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !needle.isEmpty else { return model.tables } + return model.tables.filter { $0.name.lowercased().contains(needle) } + } + + /// `[ TABLES ] 16`, or `[ TABLES ] 3 of 16` while filtering. + public static func listLabel(_ model: SchemaModel, query: String) -> String { + let total = model.tables.count + let isFiltering = !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + return isFiltering ? "[ TABLES ] \(filter(model, query: query).count) of \(total)" : "[ TABLES ] \(total)" + } +} diff --git a/Sources/HelderCore/Schema/SchemaLayout.swift b/Sources/HelderCore/Schema/SchemaLayout.swift new file mode 100644 index 0000000..c02c7aa --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaLayout.swift @@ -0,0 +1,96 @@ +import Foundation + +/// The default placement of the cards: lanes by foreign-key depth, left to right. +public enum SchemaLayout { + /// Lane 0 holds tables that point at nothing; every other table sits one lane right of the deepest table it points at. + /// + /// Self-references are ignored and a cycle is broken at the edge that closes it, visiting tables by name, so the result is deterministic. + public static func lanes(_ model: SchemaModel) -> [String: Int] { + var targets: [String: [String]] = [:] + for edge in model.edges where edge.from != edge.to { + targets[edge.from, default: []].append(edge.to) + } + var lane: [String: Int] = [:] + var visiting = Set() + + func visit(_ name: String) -> Int? { + if let known = lane[name] { return known } + guard visiting.insert(name).inserted else { return nil } + var deepest = -1 + for target in Set(targets[name] ?? []).sorted() { + if let value = visit(target) { deepest = max(deepest, value) } + } + visiting.remove(name) + lane[name] = deepest + 1 + return deepest + 1 + } + + for table in model.tables.map(\.name).sorted() { _ = visit(table) } + return lane + } + + /// Lanes 340px apart, cards 48px apart, each lane centred against the tallest. + /// + /// Lane 0 is in name order; later lanes follow the average height of the tables they point at, to limit crossings. + public static func defaultPositions(_ model: SchemaModel) -> [String: SchemaPoint] { + let lanes = lanes(model) + let tables = Dictionary(uniqueKeysWithValues: model.tables.map { ($0.name, $0) }) + let laneCount = (lanes.values.max() ?? -1) + 1 + var members = Array(repeating: [String](), count: laneCount) + for (name, lane) in lanes { members[lane].append(name) } + + var offset: [String: Double] = [:] + var laneHeight = Array(repeating: 0.0, count: laneCount) + // Card centre as a share of its lane's height, which compares across lanes of different heights. + var relative: [String: Double] = [:] + + for lane in 0.. 0 ? centre / y : 0.5 } + } + + let tallest = laneHeight.max() ?? 0 + let origin = SchemaMetrics.layoutOrigin + var positions: [String: SchemaPoint] = [:] + for (name, lane) in lanes { + let shift = ((tallest - laneHeight[lane]) / 2).rounded() + positions[name] = SchemaPoint(x: origin.x + Double(lane) * SchemaMetrics.laneSpacing, + y: origin.y + shift + (offset[name] ?? 0)) + } + return positions + } + + /// Saved positions for the tables that still exist, default ones for the rest. + public static func positions(_ model: SchemaModel, saved: [String: SchemaPoint]) -> [String: SchemaPoint] { + var result = defaultPositions(model) + for table in model.tables { + if let point = saved[table.name] { result[table.name] = point } + } + return result + } + + /// The UserDefaults key that holds a project's card positions. + public static func defaultsKey(root: String) -> String { "helder.schemaLayout:" + root } +} diff --git a/Sources/HelderCore/Schema/SchemaModel.swift b/Sources/HelderCore/Schema/SchemaModel.swift new file mode 100644 index 0000000..b76f863 --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaModel.swift @@ -0,0 +1,228 @@ +import Foundation + +/// A column another column points at. +public struct SchemaColumnRef: Sendable, Hashable, Codable { + public var table: String + public var column: String + + public init(table: String, column: String) { + self.table = table + self.column = column + } + + /// `table.column`, the form the view uses for a hovered foreign key. + public var id: String { table + "." + column } +} + +public struct SchemaColumn: Sendable, Equatable { + public var name: String + /// The full type such as `varchar(255)`, else the bare type name. + public var type: String + public var isPrimary: Bool + public var isForeign: Bool + /// Alone in a unique index that is not the primary key. + public var isUnique: Bool + public var isNullable: Bool + public var foreignTarget: SchemaColumnRef? + + public init(name: String, type: String, isPrimary: Bool = false, isForeign: Bool = false, isUnique: Bool = false, + isNullable: Bool = false, foreignTarget: SchemaColumnRef? = nil) { + self.name = name + self.type = type + self.isPrimary = isPrimary + self.isForeign = isForeign + self.isUnique = isUnique + self.isNullable = isNullable + self.foreignTarget = foreignTarget + } + + /// `PK`, `FK`, `UQ` or empty, in that order of precedence. + public var keyLabel: String { + isPrimary ? "PK" : isForeign ? "FK" : isUnique ? "UQ" : "" + } + + /// The type with `?` for a nullable column, as the card shows it. + public var displayType: String { + isNullable ? type + "?" : type + } + + /// The detail panel's flags line, such as `FK → users.id · NULL`. + public var flags: String { + var parts: [String] = [] + if isPrimary { parts.append("PRIMARY") } + if isForeign { parts.append("FK → " + (foreignTarget?.id ?? "?")) } + if isUnique { parts.append("UNIQUE") } + parts.append(isNullable ? "NULL" : "NOT NULL") + return parts.joined(separator: " · ") + } +} + +public struct SchemaTable: Sendable, Equatable { + public var name: String + public var rows: Int? + public var columns: [SchemaColumn] + + public init(name: String, rows: Int? = nil, columns: [SchemaColumn]) { + self.name = name + self.rows = rows + self.columns = columns + } + + /// The row count with en-US thousands separators, or empty when unknown. + public var rowsLabel: String { + SchemaFormat.count(rows) + } + + public var cardHeight: Double { + SchemaGeometry.cardHeight(columns: columns.count) + } +} + +/// One relationship line: from a foreign-key column to the column it references. +public struct SchemaEdge: Sendable, Hashable { + public var from: String + public var column: String + public var columnIndex: Int + public var to: String + public var targetColumnIndex: Int + + public init(from: String, column: String, columnIndex: Int, to: String, targetColumnIndex: Int) { + self.from = from + self.column = column + self.columnIndex = columnIndex + self.to = to + self.targetColumnIndex = targetColumnIndex + } + + /// `table.column` of the foreign-key end; unique within a model. + public var id: String { from + "." + column } +} + +/// What the Schema view draws, derived from a dump. +public struct SchemaModel: Sendable, Equatable { + /// `mysql · odynt`: the driver (else the connection name) and the database. + public var connectionLabel: String + /// The dump's `generated_at` as written. + public var generatedAt: String? + /// Sorted by name. + public var tables: [SchemaTable] + public var edges: [SchemaEdge] + + public init(connectionLabel: String, generatedAt: String? = nil, tables: [SchemaTable], edges: [SchemaEdge]) { + self.connectionLabel = connectionLabel + self.generatedAt = generatedAt + self.tables = tables + self.edges = edges + } + + /// Edges whose target table is not in the dump are dropped; a multi-column key draws one line from its first column. + public init(dump: SchemaDump) { + let sortedTables = dump.tables.sorted { $0.name < $1.name } + var seen = Set() + let unique = sortedTables.filter { seen.insert($0.name).inserted } + let raw = Dictionary(uniqueKeysWithValues: unique.map { ($0.name, $0) }) + let tables = unique.map(Self.table) + let byName = Dictionary(uniqueKeysWithValues: tables.map { ($0.name, $0) }) + + var edges: [SchemaEdge] = [] + var edgeIDs = Set() + for table in tables { + for key in raw[table.name]?.foreignKeys ?? [] { + guard let first = key.columns.first, + let columnIndex = table.columns.firstIndex(where: { $0.name == first }), + let target = byName[key.foreignTable] else { continue } + let edge = SchemaEdge(from: table.name, column: first, columnIndex: columnIndex, to: target.name, + targetColumnIndex: Self.targetIndex(in: target, column: key.foreignColumns.first)) + if edgeIDs.insert(edge.id).inserted { edges.append(edge) } + } + } + + self.init(connectionLabel: Self.connectionLabel(dump), generatedAt: dump.generatedAt, tables: tables, edges: edges) + } + + public var tableCount: Int { tables.count } + public var columnCount: Int { tables.reduce(0) { $0 + $1.columns.count } } + public var relationCount: Int { edges.count } + + public func table(named name: String) -> SchemaTable? { + tables.first { $0.name == name } + } + + /// Belongs to: the edges leaving `table`. + public func outgoing(from table: String) -> [SchemaEdge] { + edges.filter { $0.from == table } + } + + /// Has many: the edges arriving at `table`. + public func incoming(to table: String) -> [SchemaEdge] { + edges.filter { $0.to == table } + } + + /// `generatedAt` parsed as ISO 8601, with or without fractional seconds. + public var generatedDate: Date? { + guard let generatedAt else { return nil } + let plain = ISO8601DateFormatter() + if let date = plain.date(from: generatedAt) { return date } + let fractional = ISO8601DateFormatter() + fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return fractional.date(from: generatedAt) + } + + private static func connectionLabel(_ dump: SchemaDump) -> String { + let engine = nonEmpty(dump.driver) ?? nonEmpty(dump.connection) + switch (engine, nonEmpty(dump.database)) { + case let (engine?, database?): return engine + " · " + database + case let (engine?, nil): return engine + case let (nil, database?): return database + case (nil, nil): return "database" + } + } + + private static func nonEmpty(_ text: String?) -> String? { + guard let text, !text.isEmpty else { return nil } + return text + } + + private static func table(_ raw: SchemaDump.Table) -> SchemaTable { + var primary = Set(raw.indexes.filter(\.primary).flatMap(\.columns)) + if primary.isEmpty, let auto = raw.columns.first(where: \.autoIncrement) { primary.insert(auto.name) } + let unique = Set(raw.indexes.filter { $0.unique && !$0.primary && $0.columns.count == 1 }.flatMap(\.columns)) + var targets: [String: SchemaColumnRef] = [:] + for key in raw.foreignKeys { + for (offset, column) in key.columns.enumerated() where targets[column] == nil { + let foreign = offset < key.foreignColumns.count ? key.foreignColumns[offset] : (key.foreignColumns.first ?? "id") + targets[column] = SchemaColumnRef(table: key.foreignTable, column: foreign) + } + } + let columns = raw.columns.map { column in + let isPrimary = primary.contains(column.name) + return SchemaColumn( + name: column.name, + type: nonEmpty(column.type) ?? nonEmpty(column.typeName) ?? "", + isPrimary: isPrimary, + isForeign: targets[column.name] != nil, + isUnique: !isPrimary && unique.contains(column.name), + isNullable: column.nullable, + foreignTarget: targets[column.name] + ) + } + return SchemaTable(name: raw.name, rows: raw.rows, columns: columns) + } + + /// The referenced column, else the first primary column, else the first row. + private static func targetIndex(in table: SchemaTable, column: String?) -> Int { + if let column, let index = table.columns.firstIndex(where: { $0.name == column }) { return index } + return table.columns.firstIndex(where: \.isPrimary) ?? 0 + } +} + +public enum SchemaFormat { + /// `214,330`; empty for nil. + public static func count(_ value: Int?) -> String { + guard let value else { return "" } + let formatter = NumberFormatter() + formatter.locale = Locale(identifier: "en_US") + formatter.numberStyle = .decimal + return formatter.string(from: NSNumber(value: value)) ?? String(value) + } +} diff --git a/Sources/HelderCore/Schema/SchemaPaths.swift b/Sources/HelderCore/Schema/SchemaPaths.swift new file mode 100644 index 0000000..3c636f0 --- /dev/null +++ b/Sources/HelderCore/Schema/SchemaPaths.swift @@ -0,0 +1,11 @@ +import Foundation + +/// Where the Schema view looks in a Laravel project, relative to the project root. +public enum SchemaPaths { + /// The command whose presence turns the Schema view on. + public static let commandFile = "app/Console/Commands/HelderSchemaCommand.php" + public static let dumpFile = "database/helder/schema.json" + public static let artisanFile = "artisan" + /// What the console echoes before a run. + public static let commandLine = "php artisan helder:schema" +} diff --git a/Sources/HelderServices/Schema/SchemaService.swift b/Sources/HelderServices/Schema/SchemaService.swift new file mode 100644 index 0000000..78415da --- /dev/null +++ b/Sources/HelderServices/Schema/SchemaService.swift @@ -0,0 +1,145 @@ +import Foundation +import HelderCore + +/// Finds the php binary: Laravel Herd's first, then the search path. +public struct PHPLocator: Sendable { + public var herdPath: String + public var locator: ExecutableLocator + + public init(herdPath: String = PHPLocator.defaultHerdPath, locator: ExecutableLocator = .standard) { + self.herdPath = herdPath + self.locator = locator + } + + public static var defaultHerdPath: String { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/Herd/bin/php").path + } + + public func locate() -> URL? { + if FileManager.default.isExecutableFile(atPath: herdPath) { return URL(fileURLWithPath: herdPath) } + return locator.locate("php") + } +} + +public struct SchemaService: SchemaServicing { + public let root: URL + private let runner: ProcessRunning + private let php: PHPLocator + private let timeout: TimeInterval + + public static let notFoundMessage = "php not found. Install Laravel Herd or put php on PATH." + public static let arguments = ["artisan", "helder:schema", "--no-ansi", "--no-interaction"] + + public init(root: URL, runner: ProcessRunning = ProcessRunner(), php: PHPLocator = PHPLocator(), timeout: TimeInterval = 120) { + self.root = root + self.runner = runner + self.php = php + self.timeout = timeout + } + + public func isLaravelApp() async -> Bool { + isFile(SchemaPaths.artisanFile) + } + + public func hasCommand() async -> Bool { + isFile(SchemaPaths.commandFile) + } + + public func readDump() async throws -> SchemaModel? { + let url = root.appendingPathComponent(SchemaPaths.dumpFile) + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + let data: Data + do { + data = try Data(contentsOf: url) + } catch { + throw SchemaDumpError.corrupt(reason: error.localizedDescription) + } + return SchemaModel(dump: try SchemaDump.decode(data)) + } + + public func dumpModificationDate() async -> Date? { + let path = root.appendingPathComponent(SchemaPaths.dumpFile).path + return (try? FileManager.default.attributesOfItem(atPath: path))?[.modificationDate] as? Date + } + + /// The found php's folder goes first on the child's PATH, so `php` called from the app's own scripts is the same one. + public func runDump(onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async -> Int32 { + guard let binary = php.locate() else { + onLine(Self.notFoundMessage, true) + return -1 + } + var environment = ProcessInfo.processInfo.environment + let folder = binary.deletingLastPathComponent().path + environment["PATH"] = [folder, environment["PATH"]].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ":") + let runner = self.runner, root = self.root, timeout = self.timeout + + let outcome = await withTaskGroup(of: Outcome?.self) { group -> Outcome? in + group.addTask { + do { + let result = try await runner.stream(binary.path, arguments: Self.arguments, in: root, + environment: environment, onLine: onLine) + return .finished(result.exitCode) + } catch is CancellationError { + return nil + } catch let ProcessRunnerError.executableNotFound(name) { + return .failed("\(name) not found") + } catch let ProcessRunnerError.launchFailed(reason) { + return .failed(reason) + } catch { + return .failed("\(error)") + } + } + group.addTask { + try? await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000)) + return Task.isCancelled ? nil : .failed("timed out after \(Self.seconds(timeout))s") + } + let first = await group.next() ?? nil + group.cancelAll() + return first + } + switch outcome { + case let .finished(code): + return code + case let .failed(reason): + onLine(reason, true) + return -1 + case nil: + return -1 + } + } + + private enum Outcome: Sendable { + case finished(Int32) + case failed(String) + } + + private func isFile(_ relative: String) -> Bool { + var isDirectory: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: root.appendingPathComponent(relative).path, isDirectory: &isDirectory) + return exists && !isDirectory.boolValue + } + + /// "5" for whole seconds, "0.5" otherwise. + private static func seconds(_ value: TimeInterval) -> String { + value == value.rounded() ? String(Int(value)) : String(value) + } +} + +/// Never throws: positions that cannot be read are empty, ones that cannot be written are skipped. +public struct UserDefaultsSchemaLayoutStore: SchemaLayoutPersisting, @unchecked Sendable { + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + public func loadPositions(root: String) -> [String: SchemaPoint] { + defaults.data(forKey: SchemaLayout.defaultsKey(root: root)) + .flatMap { try? JSONDecoder().decode([String: SchemaPoint].self, from: $0) } ?? [:] + } + + public func savePositions(_ positions: [String: SchemaPoint], root: String) { + if let data = try? JSONEncoder().encode(positions) { defaults.set(data, forKey: SchemaLayout.defaultsKey(root: root)) } + } +} diff --git a/Sources/HelderServices/Schema/SchemaServicing.swift b/Sources/HelderServices/Schema/SchemaServicing.swift new file mode 100644 index 0000000..e51c183 --- /dev/null +++ b/Sources/HelderServices/Schema/SchemaServicing.swift @@ -0,0 +1,25 @@ +import Foundation +import HelderCore + +/// The Schema view's disk and process work for one project. +public protocol SchemaServicing: Sendable { + /// True when the project root holds an `artisan` file. + func isLaravelApp() async -> Bool + /// True when `app/Console/Commands/HelderSchemaCommand.php` exists. + func hasCommand() async -> Bool + /// The model from `database/helder/schema.json`, nil when the file is missing; throws `SchemaDumpError` when it is corrupt. + func readDump() async throws -> SchemaModel? + /// When the dump was last written, nil when it is missing. + func dumpModificationDate() async -> Date? + /// Runs `php artisan helder:schema` in the project and streams each line (`isError` for stderr); returns the exit code. + /// + /// Never throws and never waits on input: a missing php, a launch failure or the timeout becomes one error line and code -1. + func runDump(onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async -> Int32 +} + +/// Card positions per project, kept in Helder's own settings rather than in the project folder. +public protocol SchemaLayoutPersisting: Sendable { + /// Empty when nothing was saved for `root`. + func loadPositions(root: String) -> [String: SchemaPoint] + func savePositions(_ positions: [String: SchemaPoint], root: String) +} diff --git a/Sources/HelderUI/Components/PointerPolicy.swift b/Sources/HelderUI/Components/PointerPolicy.swift index f1dc00f..235ab73 100644 --- a/Sources/HelderUI/Components/PointerPolicy.swift +++ b/Sources/HelderUI/Components/PointerPolicy.swift @@ -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 diff --git a/Sources/HelderUI/GitView/GitConsolePanel.swift b/Sources/HelderUI/GitView/GitConsolePanel.swift index 67b1883..27f520d 100644 --- a/Sources/HelderUI/GitView/GitConsolePanel.swift +++ b/Sources/HelderUI/GitView/GitConsolePanel.swift @@ -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) diff --git a/Sources/HelderUI/GitView/GitIcon.swift b/Sources/HelderUI/GitView/GitIcon.swift index 9f22786..8db6fa7 100644 --- a/Sources/HelderUI/GitView/GitIcon.swift +++ b/Sources/HelderUI/GitView/GitIcon.swift @@ -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 diff --git a/Sources/HelderUI/GitView/GitTopBar.swift b/Sources/HelderUI/GitView/GitTopBar.swift index 53315bc..f99f35b 100644 --- a/Sources/HelderUI/GitView/GitTopBar.swift +++ b/Sources/HelderUI/GitView/GitTopBar.swift @@ -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? diff --git a/Sources/HelderUI/Overlays/ShortcutsOverlay.swift b/Sources/HelderUI/Overlays/ShortcutsOverlay.swift index 527076a..9f01943 100644 --- a/Sources/HelderUI/Overlays/ShortcutsOverlay.swift +++ b/Sources/HelderUI/Overlays/ShortcutsOverlay.swift @@ -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 diff --git a/Sources/HelderUI/SchemaView/SchemaCanvas.swift b/Sources/HelderUI/SchemaView/SchemaCanvas.swift new file mode 100644 index 0000000..deac821 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaCanvas.swift @@ -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: 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 + } + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaConsolePanel.swift b/Sources/HelderUI/SchemaView/SchemaConsolePanel.swift new file mode 100644 index 0000000..0e507e5 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaConsolePanel.swift @@ -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) + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaDetailPanel.swift b/Sources/HelderUI/SchemaView/SchemaDetailPanel.swift new file mode 100644 index 0000000..8e55075 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaDetailPanel.swift @@ -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) + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaEmptyState.swift b/Sources/HelderUI/SchemaView/SchemaEmptyState.swift new file mode 100644 index 0000000..c650086 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaEmptyState.swift @@ -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: 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) + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaTableCard.swift b/Sources/HelderUI/SchemaView/SchemaTableCard.swift new file mode 100644 index 0000000..f1ba713 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaTableCard.swift @@ -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 + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaTableList.swift b/Sources/HelderUI/SchemaView/SchemaTableList.swift new file mode 100644 index 0000000..d875c8c --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaTableList.swift @@ -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 + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaTopBar.swift b/Sources/HelderUI/SchemaView/SchemaTopBar.swift new file mode 100644 index 0000000..b6259c8 --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaTopBar.swift @@ -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) + } +} diff --git a/Sources/HelderUI/SchemaView/SchemaView.swift b/Sources/HelderUI/SchemaView/SchemaView.swift new file mode 100644 index 0000000..85c9b7c --- /dev/null +++ b/Sources/HelderUI/SchemaView/SchemaView.swift @@ -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 {} diff --git a/Sources/HelderUI/Shell/Command.swift b/Sources/HelderUI/Shell/Command.swift index 23524bd..054f5d4 100644 --- a/Sources/HelderUI/Shell/Command.swift +++ b/Sources/HelderUI/Shell/Command.swift @@ -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:
` 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. diff --git a/Sources/HelderUI/Shell/HelderScene.swift b/Sources/HelderUI/Shell/HelderScene.swift index ab2dbd1..b09e0cb 100644 --- a/Sources/HelderUI/Shell/HelderScene.swift +++ b/Sources/HelderUI/Shell/HelderScene.swift @@ -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)) } diff --git a/Sources/HelderUI/Shell/KeyRouter.swift b/Sources/HelderUI/Shell/KeyRouter.swift index 1696b6c..641084d 100644 --- a/Sources/HelderUI/Shell/KeyRouter.swift +++ b/Sources/HelderUI/Shell/KeyRouter.swift @@ -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)) diff --git a/Sources/HelderUI/Shell/TitleBarView.swift b/Sources/HelderUI/Shell/TitleBarView.swift index aaddd1c..839f16d 100644 --- a/Sources/HelderUI/Shell/TitleBarView.swift +++ b/Sources/HelderUI/Shell/TitleBarView.swift @@ -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.")) { diff --git a/Sources/HelderUI/Shell/WindowBridge.swift b/Sources/HelderUI/Shell/WindowBridge.swift index aede177..78b4e77 100644 --- a/Sources/HelderUI/Shell/WindowBridge.swift +++ b/Sources/HelderUI/Shell/WindowBridge.swift @@ -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) ) } diff --git a/Sources/HelderUI/Shell/WorkspaceView.swift b/Sources/HelderUI/Shell/WorkspaceView.swift index 8efc133..2171984 100644 --- a/Sources/HelderUI/Shell/WorkspaceView.swift +++ b/Sources/HelderUI/Shell/WorkspaceView.swift @@ -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 diff --git a/Sources/HelderUI/Shell/WorkspaceWindow.swift b/Sources/HelderUI/Shell/WorkspaceWindow.swift index b1a1704..52a835d 100644 --- a/Sources/HelderUI/Shell/WorkspaceWindow.swift +++ b/Sources/HelderUI/Shell/WorkspaceWindow.swift @@ -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() } diff --git a/Sources/HelderUI/State/LayoutStore.swift b/Sources/HelderUI/State/LayoutStore.swift index 8012c65..734561e 100644 --- a/Sources/HelderUI/State/LayoutStore.swift +++ b/Sources/HelderUI/State/LayoutStore.swift @@ -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() { diff --git a/Sources/HelderUI/State/SchemaStore.swift b/Sources/HelderUI/State/SchemaStore.swift new file mode 100644 index 0000000..dbd3df3 --- /dev/null +++ b/Sources/HelderUI/State/SchemaStore.swift @@ -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 = "" + } +} diff --git a/Sources/HelderUI/State/WorkspaceModel+Commands.swift b/Sources/HelderUI/State/WorkspaceModel+Commands.swift index e897665..8ae83f2 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Commands.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Commands.swift @@ -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) { diff --git a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift index 7337caa..646f1fe 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Lifecycle.swift @@ -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) diff --git a/Sources/HelderUI/State/WorkspaceModel+Refresh.swift b/Sources/HelderUI/State/WorkspaceModel+Refresh.swift index 0522b46..3fe153d 100644 --- a/Sources/HelderUI/State/WorkspaceModel+Refresh.swift +++ b/Sources/HelderUI/State/WorkspaceModel+Refresh.swift @@ -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. diff --git a/Sources/HelderUI/State/WorkspaceModel.swift b/Sources/HelderUI/State/WorkspaceModel.swift index 3c5c06d..ddfcc27 100644 --- a/Sources/HelderUI/State/WorkspaceModel.swift +++ b/Sources/HelderUI/State/WorkspaceModel.swift @@ -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() diff --git a/Sources/HelderUI/State/WorkspaceServices.swift b/Sources/HelderUI/State/WorkspaceServices.swift index 9dc44fe..ba2f025 100644 --- a/Sources/HelderUI/State/WorkspaceServices.swift +++ b/Sources/HelderUI/State/WorkspaceServices.swift @@ -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:), diff --git a/Sources/HelderUI/Theme/Palette.swift b/Sources/HelderUI/Theme/Palette.swift index 571103d..3b208ad 100644 --- a/Sources/HelderUI/Theme/Palette.swift +++ b/Sources/HelderUI/Theme/Palette.swift @@ -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 { diff --git a/Sources/HelderUI/Theme/Typography.swift b/Sources/HelderUI/Theme/Typography.swift index 1e42e93..f8909ac 100644 --- a/Sources/HelderUI/Theme/Typography.swift +++ b/Sources/HelderUI/Theme/Typography.swift @@ -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 { diff --git a/Tests/HelderCoreTests/Schema/ArtisanConsoleTests.swift b/Tests/HelderCoreTests/Schema/ArtisanConsoleTests.swift new file mode 100644 index 0000000..ce63fd7 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/ArtisanConsoleTests.swift @@ -0,0 +1,42 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct ArtisanConsoleTests { + @Test("stdout lines are classified", arguments: [ + (" Connection ............................ mysql · odynt", ArtisanLineKind.output), + (" Tables ................................ 16", .output), + (" INFO Wrote database/helder/schema.json (18.4 KB).", .success), + (" Wrote database/helder/schema.json (18.4 KB)", .success), + (" DONE Schema dumped in 0.41s.", .success), + (" ERROR SQLSTATE[HY000] [2002] Connection refused.", .error), + (" Illuminate\\Database\\QueryException", .error), + ("", .output), + ]) + func classify(line: String, expected: ArtisanLineKind) { + #expect(ArtisanOutputClassifier.classify(line, isError: false) == expected) + } + + @Test func everyStderrLineIsAnError() { + #expect(ArtisanOutputClassifier.classify("PHP Warning: something", isError: true) == .error) + #expect(ArtisanOutputClassifier.line(" DONE x", isError: true) == ArtisanConsoleLine(text: " DONE x", kind: .error)) + } + + @Test func theEchoAndPathsMatchTheCommand() { + #expect(ArtisanOutputClassifier.commandEcho == "$ php artisan helder:schema") + #expect(SchemaPaths.commandFile == "app/Console/Commands/HelderSchemaCommand.php") + #expect(SchemaPaths.dumpFile == "database/helder/schema.json") + #expect(SchemaPaths.artisanFile == "artisan") + } + + @Test func thePromptNamesTheFileTheContractAndTheIgnoreFile() { + let text = SchemaCommandPrompt.text + #expect(text.hasPrefix("Build an Artisan command that dumps this app's database schema for Helder")) + #expect(text.contains("Class: App\\Console\\Commands\\HelderSchemaCommand, extends Illuminate\\Console\\Command")) + #expect(text.contains("File: " + SchemaPaths.commandFile)) + #expect(text.contains("\"foreign_keys\": [ ]")) + #expect(text.contains("`*` and `!.gitignore`")) + #expect(text.hasSuffix("run `php artisan helder:schema` once and show me the output.")) + #expect(text.contains("\n{\n \"version\": 1,\n")) + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaDumpTests.swift b/Tests/HelderCoreTests/Schema/SchemaDumpTests.swift new file mode 100644 index 0000000..9dff807 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaDumpTests.swift @@ -0,0 +1,85 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SchemaDumpTests { + private func decode(_ json: String) throws -> SchemaDump { + try SchemaDump.decode(Data(json.utf8)) + } + + // MARK: decoding + + @Test func theFullContractDecodes() throws { + let dump = try decode(SchemaFixtures.contract) + #expect(dump.version == 1) + #expect(dump.connection == "mysql") + #expect(dump.driver == "mysql") + #expect(dump.database == "odynt") + #expect(dump.generatedAt == "2026-11-02T14:32:05+01:00") + #expect(dump.tables.map(\.name) == ["users", "messages", "conversations"]) + + let users = try #require(dump.tables.first) + #expect(users.rows == 1284) + #expect(users.columns[0] == SchemaDump.Column(name: "id", typeName: "bigint", type: "bigint unsigned", autoIncrement: true)) + #expect(users.indexes[1] == SchemaDump.Index(name: "users_email_unique", columns: ["email"], type: "btree", unique: true)) + + let messages = dump.tables[1] + #expect(messages.columns[2].comment == "the body") + #expect(messages.foreignKeys == [SchemaDump.ForeignKey( + name: "messages_conversation_id_foreign", columns: ["conversation_id"], foreignSchema: "odynt", + foreignTable: "conversations", foreignColumns: ["id"], onUpdate: "no action", onDelete: "cascade")]) + + #expect(dump.tables[2].rows == nil) + #expect(dump.tables[2].columns[2].defaultValue == "0") + } + + @Test func theOlderPrototypeShapeDecodes() throws { + let dump = try decode(""" + {"connection": "mysql", "generated_at": "2026-10-01T09:00:00+00:00", + "tables": [{"name": "users", "columns": [{"name": "id", "type_name": "bigint", "type": "bigint", "nullable": false}], + "indexes": [{"name": "primary", "columns": ["id"], "unique": true, "primary": true}], "foreign_keys": []}]} + """) + #expect(dump.version == nil) + #expect(dump.driver == nil) + #expect(dump.database == nil) + #expect(dump.tables.count == 1) + #expect(dump.tables[0].rows == nil) + #expect(SchemaModel(dump: dump).connectionLabel == "mysql") + } + + @Test func missingKeysGetTheirDefaults() throws { + let dump = try decode(#"{"tables": [{"name": "t", "columns": [{"name": "a"}], "indexes": [{"columns": ["a"], "primary": true}]}]}"#) + let table = try #require(dump.tables.first) + #expect(table.foreignKeys == []) + #expect(table.columns == [SchemaDump.Column(name: "a")]) + #expect(table.indexes[0].unique) + #expect(try decode("{}") == SchemaDump(version: nil)) + } + + @Test func unknownKeysAndBrokenItemsAreSkipped() throws { + let dump = try decode(""" + {"version": "1", "extra": {"x": 1}, "tables": [ + {"columns": []}, + "not a table", + {"name": "t", "rows": "12", "columns": [{"type": "int"}, {"name": "a", "nullable": 1, "default": 5, "auto_increment": "1"}], + "foreign_keys": [{"columns": ["a"]}, {"columns": ["a"], "foreign_table": "u"}]} + ]} + """) + #expect(dump.version == 1) + #expect(dump.tables.map(\.name) == ["t"]) + let table = dump.tables[0] + #expect(table.rows == 12) + #expect(table.columns == [SchemaDump.Column(name: "a", nullable: true, defaultValue: "5", autoIncrement: true)]) + #expect(table.foreignKeys == [SchemaDump.ForeignKey(columns: ["a"], foreignTable: "u")]) + } + + @Test("corrupt data throws a readable error", arguments: ["", "{\"tables\": [", "[1, 2]", "not json"]) + func corrupt(json: String) { + #expect { + try decode(json) + } throws: { error in + guard let error = error as? SchemaDumpError, case .corrupt = error else { return false } + return error.localizedDescription.hasPrefix("database/helder/schema.json is not a valid schema dump:") + } + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaFixtures.swift b/Tests/HelderCoreTests/Schema/SchemaFixtures.swift new file mode 100644 index 0000000..44ad543 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaFixtures.swift @@ -0,0 +1,80 @@ +import Foundation +import HelderCore + +enum SchemaFixtures { + /// A version 1 dump as the command writes it: users ← conversations ← messages, plus a unique email. + static let contract = #""" + { + "version": 1, + "connection": "mysql", + "driver": "mysql", + "database": "odynt", + "generated_at": "2026-11-02T14:32:05+01:00", + "tables": [ + { + "name": "users", + "rows": 1284, + "columns": [ + {"name": "id", "type_name": "bigint", "type": "bigint unsigned", "collation": null, "nullable": false, "default": null, "auto_increment": true, "comment": null, "generation": null}, + {"name": "email", "type_name": "varchar", "type": "varchar(255)", "nullable": false, "default": null, "auto_increment": false, "comment": null}, + {"name": "email_verified_at", "type_name": "timestamp", "type": "timestamp", "nullable": true, "default": null, "auto_increment": false, "comment": null} + ], + "indexes": [ + {"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true}, + {"name": "users_email_unique", "columns": ["email"], "type": "btree", "unique": true, "primary": false} + ], + "foreign_keys": [] + }, + { + "name": "messages", + "rows": 214330, + "columns": [ + {"name": "id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": true, "comment": null}, + {"name": "conversation_id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": false, "comment": null}, + {"name": "content", "type_name": "longtext", "type": "longtext", "nullable": false, "default": null, "auto_increment": false, "comment": "the body"} + ], + "indexes": [ + {"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true} + ], + "foreign_keys": [ + {"name": "messages_conversation_id_foreign", "columns": ["conversation_id"], "foreign_schema": "odynt", "foreign_table": "conversations", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "cascade"} + ] + }, + { + "name": "conversations", + "rows": null, + "columns": [ + {"name": "id", "type_name": "bigint", "type": "bigint unsigned", "nullable": false, "default": null, "auto_increment": true, "comment": null}, + {"name": "user_id", "type_name": "bigint", "type": "bigint unsigned", "nullable": true, "default": null, "auto_increment": false, "comment": null}, + {"name": "archived", "type_name": "tinyint", "type": "tinyint(1)", "nullable": false, "default": "0", "auto_increment": false, "comment": null}, + {"name": "ghost_id", "type_name": "bigint", "type": "bigint", "nullable": true, "default": null, "auto_increment": false, "comment": null} + ], + "indexes": [ + {"name": "primary", "columns": ["id"], "type": "btree", "unique": true, "primary": true} + ], + "foreign_keys": [ + {"name": "conversations_user_id_foreign", "columns": ["user_id"], "foreign_schema": "odynt", "foreign_table": "users", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "set null"}, + {"name": "conversations_ghost_id_foreign", "columns": ["ghost_id"], "foreign_schema": "odynt", "foreign_table": "ghosts", "foreign_columns": ["id"], "on_update": "no action", "on_delete": "cascade"} + ] + } + ] + } + """# + + static var contractModel: SchemaModel { + SchemaModel(dump: try! SchemaDump.decode(Data(contract.utf8))) + } + + /// A table with `count` plain columns, the first one primary. + static func table(_ name: String, columns count: Int = 2) -> SchemaTable { + SchemaTable(name: name, columns: (0.. SchemaEdge { + SchemaEdge(from: from, column: column, columnIndex: index, to: to, targetColumnIndex: 0) + } + + static func model(_ names: [String], edges: [SchemaEdge], columns: Int = 2) -> SchemaModel { + SchemaModel(connectionLabel: "test", tables: names.sorted().map { table($0, columns: columns) }, edges: edges) + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaGeometryTests.swift b/Tests/HelderCoreTests/Schema/SchemaGeometryTests.swift new file mode 100644 index 0000000..26f1c1a --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaGeometryTests.swift @@ -0,0 +1,95 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SchemaGeometryTests { + private func p(_ x: Double, _ y: Double) -> SchemaPoint { SchemaPoint(x: x, y: y) } + + @Test func cardSizesMatchTheCard() { + #expect(SchemaGeometry.cardHeight(columns: 0) == 35) + #expect(SchemaGeometry.cardHeight(columns: 3) == 101) + #expect(SchemaGeometry.columnCentreY(top: 100, index: 0) == 145) + #expect(SchemaGeometry.columnCentreY(top: 100, index: 2) == 189) + } + + @Test func aTargetToTheRightLeavesTheRightEdgeAndEntersTheLeft() { + let path = SchemaGeometry.edgePath(from: p(40, 40), columnIndex: 1, to: p(380, 40), targetColumnIndex: 0) + #expect(path == SchemaEdgePath(start: p(280, 107), control1: p(330, 107), control2: p(330, 85), end: p(380, 85))) + } + + @Test func aTargetToTheLeftIsTheMirror() { + let path = SchemaGeometry.edgePath(from: p(380, 40), columnIndex: 0, to: p(40, 100), targetColumnIndex: 0) + #expect(path == SchemaEdgePath(start: p(380, 85), control1: p(330, 85), control2: p(330, 145), end: p(280, 145))) + } + + @Test func aNearTargetStillCurvesAtLeastFortyPoints() { + let path = SchemaGeometry.edgePath(from: p(0, 0), columnIndex: 0, to: p(250, 0), targetColumnIndex: 0) + #expect(path.control1.x == 280) + #expect(path.control2.x == 210) + } + + @Test func theSameLaneLoopsOutOnTheRight() { + let path = SchemaGeometry.edgePath(from: p(40, 40), columnIndex: 2, to: p(100, 300), targetColumnIndex: 0) + let loop = 46 + 216 * 0.12 + #expect(path == SchemaEdgePath(start: p(280, 129), control1: p(280 + loop, 129), control2: p(340 + loop, 345), end: p(340, 345))) + } + + @Test func centresExactlyOneCardApartAreNotTheSameLane() { + let path = SchemaGeometry.edgePath(from: p(0, 0), columnIndex: 0, to: p(240, 0), targetColumnIndex: 0) + #expect(path.end.x == 240) + } + + @Test func anEdgeWithAnUnplacedTableHasNoPath() { + let edge = SchemaFixtures.edge("a", "b") + #expect(SchemaGeometry.edgePath(edge, positions: ["a": p(0, 0)]) == nil) + #expect(SchemaGeometry.edgePath(edge, positions: ["a": p(0, 0), "b": p(400, 0)])?.start == p(240, 67)) + } + + @Test func boundsHoldEveryPlacedCard() { + let model = SchemaFixtures.model(["a", "b", "c"], edges: []) + let bounds = SchemaGeometry.bounds(model, positions: ["a": p(40, 40), "b": p(400, 10)]) + #expect(bounds == SchemaRect(x: 40, y: 10, width: 600, height: 109)) + #expect(SchemaGeometry.bounds(model, positions: [:]) == nil) + } + + @Test func fitCentresAndCapsTheScale() { + let view = SchemaGeometry.fit(bounds: SchemaRect(x: 40, y: 40, width: 240, height: 200), in: SchemaSize(width: 1000, height: 800)) + #expect(view == SchemaViewport(x: 291, y: 246, scale: 1.1)) + } + + @Test func fitNeverGoesBelowThirtyPercent() { + let view = SchemaGeometry.fit(bounds: SchemaRect(x: 0, y: 0, width: 5000, height: 5000), in: SchemaSize(width: 200, height: 200)) + #expect(view.scale == 0.3) + } + + @Test func fitShrinksToTheTighterSide() { + let view = SchemaGeometry.fit(bounds: SchemaRect(x: 0, y: 0, width: 1940, height: 400), in: SchemaSize(width: 1096, height: 800)) + #expect(view.scale == 0.5) + #expect(view.x == 48) + } + + @Test func zoomKeepsThePointUnderTheAnchor() { + let view = SchemaViewport(x: 30, y: -20, scale: 0.8) + let anchor = p(300, 200) + let before = SchemaGeometry.canvasPoint(anchor, in: view) + let zoomed = SchemaGeometry.zoom(view, by: 1.2, around: anchor) + let after = SchemaGeometry.canvasPoint(anchor, in: zoomed) + #expect(abs(zoomed.scale - 0.96) < 1e-9) + #expect(abs(before.x - after.x) < 1e-9) + #expect(abs(before.y - after.y) < 1e-9) + } + + @Test func zoomIsClampedBetweenThirtyAndTwoHundredPercent() { + let view = SchemaViewport(x: 0, y: 0, scale: 1) + #expect(SchemaGeometry.zoom(view, by: 10, around: p(0, 0)).scale == 2) + #expect(SchemaGeometry.zoom(view, by: 0.01, around: p(0, 0)).scale == 0.3) + #expect(SchemaGeometry.zoom(view, by: 2, in: SchemaSize(width: 200, height: 200)) == SchemaViewport(x: -100, y: -100, scale: 2)) + #expect(SchemaViewport(scale: 0.96).percentLabel == "96%") + } + + @Test func centreKeepsTheScaleAndRounds() { + let table = SchemaFixtures.table("a") + let view = SchemaGeometry.centre(table, at: p(100, 200), in: SchemaSize(width: 800, height: 600), view: SchemaViewport(x: 5, y: 5, scale: 1)) + #expect(view == SchemaViewport(x: 180, y: 61, scale: 1)) + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaHighlightTests.swift b/Tests/HelderCoreTests/Schema/SchemaHighlightTests.swift new file mode 100644 index 0000000..a1b7379 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaHighlightTests.swift @@ -0,0 +1,90 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SchemaHighlightTests { + private let model = SchemaFixtures.contractModel + + private func highlight(hovered: String? = nil, selected: String? = nil, column: String? = nil, query: String = "") -> SchemaHighlight { + SchemaHighlight(model: model, hovered: hovered, selected: selected, hoveredColumn: column, query: query) + } + + private func ref(_ table: String, _ column: String) -> SchemaColumnRef { + SchemaColumnRef(table: table, column: column) + } + + @Test func nothingFocusedHighlightsNothing() { + let h = highlight() + #expect(h.focus == nil) + #expect(h.activeEdges.isEmpty) + #expect(h.relatedTables.isEmpty) + #expect(h.dimmedTables.isEmpty) + #expect(h.highlightedColumns.isEmpty) + #expect(!h.linesRecede) + #expect(h.opacity(of: "users") == 1) + } + + @Test func hoveringATableLightsEveryLineInAndOut() { + let h = highlight(hovered: "conversations") + #expect(h.activeEdges == ["conversations.user_id", "messages.conversation_id"]) + #expect(h.relatedTables == ["conversations", "users", "messages"]) + #expect(h.dimmedTables.isEmpty) + #expect(h.highlightedColumns == [ref("conversations", "user_id"), ref("users", "id"), + ref("messages", "conversation_id"), ref("conversations", "id")]) + #expect(h.linesRecede) + } + + @Test func unrelatedTablesDim() { + let h = highlight(hovered: "users") + #expect(h.activeEdges == ["conversations.user_id"]) + #expect(h.relatedTables == ["users", "conversations"]) + #expect(h.dimmedTables == ["messages"]) + #expect(h.opacity(of: "messages") == 0.3) + #expect(h.isHighlighted(table: "users", column: "id")) + #expect(!h.isHighlighted(table: "conversations", column: "id")) + } + + @Test func aHoveredKeyNarrowsToItsOneRelationship() { + let h = highlight(hovered: "conversations", column: "conversations.user_id") + #expect(h.activeEdges == ["conversations.user_id"]) + #expect(h.relatedTables == ["conversations", "users"]) + #expect(h.dimmedTables == ["messages"]) + } + + @Test func theHoverWinsOverTheSelection() { + #expect(highlight(selected: "users").focus == "users") + let h = highlight(hovered: "messages", selected: "users") + #expect(h.focus == "messages") + #expect(h.dimmedTables == ["users"]) + } + + @Test func aTableWithoutLinesKeepsOnlyItself() { + let lonely = SchemaFixtures.model(["a", "b"], edges: []) + let h = SchemaHighlight(model: lonely, hovered: "a", selected: nil, hoveredColumn: nil, query: "") + #expect(h.relatedTables == ["a"]) + #expect(h.dimmedTables == ["b"]) + } + + @Test func searchDimsTheRestOnlyWithoutFocus() { + let h = highlight(query: " CON ") + #expect(h.searchMatches == ["conversations"]) + #expect(h.dimmedTables == ["messages", "users"]) + #expect(h.linesRecede) + let focused = highlight(hovered: "users", query: "con") + #expect(focused.searchMatches == ["conversations"]) + #expect(focused.dimmedTables == ["messages"]) + } + + @Test func activeLinesAreDrawnLast() { + let h = highlight(hovered: "users") + #expect(h.drawingOrder(model.edges).map(\.id) == ["messages.conversation_id", "conversations.user_id"]) + } + + @Test func theTableListFiltersBySubstring() { + #expect(SchemaSearch.filter(model, query: "S").map(\.name) == ["conversations", "messages", "users"]) + #expect(SchemaSearch.filter(model, query: "mess").map(\.name) == ["messages"]) + #expect(SchemaSearch.filter(model, query: " ").count == 3) + #expect(SchemaSearch.listLabel(model, query: "") == "[ TABLES ] 3") + #expect(SchemaSearch.listLabel(model, query: "user") == "[ TABLES ] 1 of 3") + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaLayoutTests.swift b/Tests/HelderCoreTests/Schema/SchemaLayoutTests.swift new file mode 100644 index 0000000..1d5c4b9 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaLayoutTests.swift @@ -0,0 +1,71 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SchemaLayoutTests { + private typealias F = SchemaFixtures + + @Test func lanesFollowTheForeignKeyDepth() { + #expect(SchemaLayout.lanes(F.contractModel) == ["users": 0, "conversations": 1, "messages": 2]) + } + + @Test func aTableTakesTheLaneAfterItsDeepestTarget() { + let model = F.model(["a", "b", "c"], edges: [F.edge("c", "a"), F.edge("c", "b", column: "c0", index: 0), F.edge("b", "a")]) + #expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1, "c": 2]) + } + + @Test func aSelfReferenceIsIgnored() { + let model = F.model(["a", "b"], edges: [F.edge("a", "a"), F.edge("b", "a", column: "c0", index: 0)]) + #expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1]) + } + + @Test func aCycleIsBrokenWhereItCloses() { + let model = F.model(["a", "b", "c"], edges: [F.edge("a", "b"), F.edge("b", "c"), F.edge("c", "a")]) + #expect(SchemaLayout.lanes(model) == ["c": 0, "b": 1, "a": 2]) + } + + @Test func lanesAreSpacedAndCentredAgainstTheTallest() { + let model = F.model(["a", "b", "x"], edges: [F.edge("x", "a")]) + let positions = SchemaLayout.defaultPositions(model) + // Cards of two columns are 79 tall: lane 0 holds two (254 with gaps), lane 1 one (127). + #expect(positions["a"] == SchemaPoint(x: 40, y: 40)) + #expect(positions["b"] == SchemaPoint(x: 40, y: 167)) + #expect(positions["x"] == SchemaPoint(x: 380, y: 104)) + } + + @Test func aLaneIsOrderedByTheHeightOfItsTargets() { + let model = F.model(["a", "b", "x", "y"], edges: [F.edge("x", "b"), F.edge("y", "a")]) + let positions = SchemaLayout.defaultPositions(model) + #expect(positions["y"]!.y < positions["x"]!.y) + } + + @Test func cardsInALaneDoNotOverlap() { + let model = F.model(["a", "b", "c", "d"], edges: [], columns: 5) + let ys = SchemaLayout.defaultPositions(model).values.map(\.y).sorted() + for (upper, lower) in zip(ys, ys.dropFirst()) { + #expect(lower - upper == SchemaGeometry.cardHeight(columns: 5) + SchemaMetrics.cardGap) + } + } + + @Test func theLayoutIsDeterministic() { + let edges = [F.edge("a", "b"), F.edge("b", "a"), F.edge("c", "a"), F.edge("d", "c"), F.edge("e", "e")] + let model = F.model(["a", "b", "c", "d", "e"], edges: edges) + let reversed = SchemaModel(connectionLabel: "test", tables: model.tables.reversed(), edges: edges.reversed()) + let first = SchemaLayout.defaultPositions(model) + #expect(first.count == 5) + #expect(SchemaLayout.defaultPositions(model) == first) + #expect(SchemaLayout.defaultPositions(reversed) == first) + } + + @Test func anEmptyModelHasNoPositions() { + #expect(SchemaLayout.defaultPositions(F.model([], edges: [])).isEmpty) + } + + @Test func savedPositionsWinForTablesThatStillExist() { + let model = F.model(["a", "b"], edges: []) + let positions = SchemaLayout.positions(model, saved: ["a": SchemaPoint(x: 1, y: 2), "gone": SchemaPoint(x: 9, y: 9)]) + #expect(positions["a"] == SchemaPoint(x: 1, y: 2)) + #expect(positions["b"] == SchemaLayout.defaultPositions(model)["b"]) + #expect(positions["gone"] == nil) + } +} diff --git a/Tests/HelderCoreTests/Schema/SchemaModelTests.swift b/Tests/HelderCoreTests/Schema/SchemaModelTests.swift new file mode 100644 index 0000000..91344c2 --- /dev/null +++ b/Tests/HelderCoreTests/Schema/SchemaModelTests.swift @@ -0,0 +1,96 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SchemaModelTests { + @Test func tablesAreSortedAndCounted() { + let model = SchemaFixtures.contractModel + #expect(model.tables.map(\.name) == ["conversations", "messages", "users"]) + #expect(model.connectionLabel == "mysql · odynt") + #expect(model.tableCount == 3) + #expect(model.columnCount == 10) + #expect(model.relationCount == 2) + #expect(model.generatedDate == ISO8601DateFormatter().date(from: "2026-11-02T13:32:05Z")) + } + + @Test func columnsCarryTheirKeys() throws { + let model = SchemaFixtures.contractModel + let users = try #require(model.table(named: "users")) + #expect(users.columns[0] == SchemaColumn(name: "id", type: "bigint unsigned", isPrimary: true)) + #expect(users.columns[1].isUnique) + #expect(users.columns[1].keyLabel == "UQ") + #expect(users.columns[2].displayType == "timestamp?") + #expect(users.rowsLabel == "1,284") + + let conversations = try #require(model.table(named: "conversations")) + let userID = conversations.columns[1] + #expect(userID.isForeign) + #expect(userID.foreignTarget == SchemaColumnRef(table: "users", column: "id")) + #expect(userID.keyLabel == "FK") + #expect(userID.flags == "FK → users.id · NULL") + #expect(conversations.columns[0].flags == "PRIMARY · NOT NULL") + #expect(users.columns[1].flags == "UNIQUE · NOT NULL") + #expect(conversations.rowsLabel == "") + #expect(model.table(named: "messages")?.rowsLabel == "214,330") + } + + @Test func edgesPointAtTheReferencedRowAndSkipMissingTables() { + let model = SchemaFixtures.contractModel + #expect(model.edges == [ + SchemaEdge(from: "conversations", column: "user_id", columnIndex: 1, to: "users", targetColumnIndex: 0), + SchemaEdge(from: "messages", column: "conversation_id", columnIndex: 1, to: "conversations", targetColumnIndex: 0), + ]) + #expect(model.outgoing(from: "conversations").map(\.to) == ["users"]) + #expect(model.incoming(to: "conversations").map(\.from) == ["messages"]) + // The ghost_id key points at a table that is not in the dump: still a FK column, but no line. + #expect(model.table(named: "conversations")?.columns[3].isForeign == true) + } + + @Test func theTargetRowFallsBackToThePrimaryKeyThenTheFirstRow() { + let dump = SchemaDump(tables: [ + .init(name: "a", columns: [.init(name: "code"), .init(name: "uuid")], + indexes: [.init(columns: ["uuid"], primary: true)]), + .init(name: "b", columns: [.init(name: "x")]), + .init(name: "c", columns: [.init(name: "id"), .init(name: "a_ref"), .init(name: "b_ref")], + foreignKeys: [.init(columns: ["a_ref"], foreignTable: "a", foreignColumns: ["missing"]), + .init(columns: ["b_ref"], foreignTable: "b")]), + ]) + let edges = SchemaModel(dump: dump).edges + #expect(edges.map(\.targetColumnIndex) == [1, 0]) + } + + @Test func aKeyOnAColumnThatIsNotListedDrawsNoLine() { + let dump = SchemaDump(tables: [ + .init(name: "a", columns: [.init(name: "id")]), + .init(name: "b", columns: [.init(name: "id")], foreignKeys: [.init(columns: ["a_id"], foreignTable: "a")]), + ]) + #expect(SchemaModel(dump: dump).edges.isEmpty) + } + + @Test func theTypeFallsBackToTheTypeName() { + let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "a", typeName: "int"), .init(name: "b")])]) + #expect(SchemaModel(dump: dump).tables[0].columns.map(\.type) == ["int", ""]) + } + + @Test func anAutoIncrementColumnIsPrimaryWhenNoIndexSaysSo() { + let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "id", autoIncrement: true), .init(name: "a")])]) + #expect(SchemaModel(dump: dump).tables[0].columns.map(\.isPrimary) == [true, false]) + } + + @Test func aCompositeUniqueIndexDoesNotMarkItsColumns() { + let dump = SchemaDump(tables: [.init(name: "t", columns: [.init(name: "a"), .init(name: "b")], + indexes: [.init(columns: ["a", "b"], unique: true)])]) + #expect(SchemaModel(dump: dump).tables[0].columns.map(\.isUnique) == [false, false]) + } + + @Test("the connection label falls back", arguments: [ + (SchemaDump(connection: "main", driver: "pgsql", database: "shop"), "pgsql · shop"), + (SchemaDump(connection: "main", database: "shop"), "main · shop"), + (SchemaDump(connection: "main", driver: ""), "main"), + (SchemaDump(database: "shop"), "shop"), + (SchemaDump(), "database"), + ]) + func connectionLabel(dump: SchemaDump, expected: String) { + #expect(SchemaModel(dump: dump).connectionLabel == expected) + } +} diff --git a/Tests/HelderServicesTests/Schema/SchemaServiceTests.swift b/Tests/HelderServicesTests/Schema/SchemaServiceTests.swift new file mode 100644 index 0000000..d91dcc7 --- /dev/null +++ b/Tests/HelderServicesTests/Schema/SchemaServiceTests.swift @@ -0,0 +1,173 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +@Suite struct SchemaServiceTests { + /// A Laravel-looking project plus a `bin` folder holding a fake `php` with the given shell body. + private func project(php body: String? = nil) throws -> (dir: TempDirectory, bin: URL) { + let dir = try TempDirectory() + try dir.write("project/artisan", " SchemaService { + let php = PHPLocator(herdPath: herd ?? dir.url("no-herd/php").path, locator: ExecutableLocator(directories: [bin.path])) + return SchemaService(root: dir.url("project"), php: php, timeout: timeout) + } + + // MARK: files + + @Test func detectsArtisanAndTheCommand() async throws { + let (dir, bin) = try project() + let schema = service(dir, bin: bin) + #expect(await schema.isLaravelApp()) + #expect(!(await schema.hasCommand())) + try dir.write("project/" + SchemaPaths.commandFile, "&2 + echo " Wrote database/helder/schema.json (1.0 KB)" + """) + let log = LineLog() + let code = await service(dir, bin: bin).runDump(onLine: log.append) + #expect(code == 0) + let outputs = log.outputs + #expect(outputs.count == 3) + #expect(outputs.first == "args: artisan helder:schema --no-ansi --no-interaction") + // pwd -P resolves /var to /private/var, so compare the tail only. + #expect(outputs.dropFirst().first?.hasSuffix("/" + dir.root.lastPathComponent + "/project") == true) + #expect(outputs.last == " Wrote database/helder/schema.json (1.0 KB)") + #expect(log.errors == ["oops"]) + } + + @Test func theExitCodeComesBack() async throws { + let (dir, bin) = try project(php: "echo ' ERROR Connection refused.'\nexit 1") + let log = LineLog() + #expect(await service(dir, bin: bin).runDump(onLine: log.append) == 1) + #expect(log.outputs == [" ERROR Connection refused."]) + } + + @Test func herdsPhpWinsAndItsFolderLeadsThePath() async throws { + let (dir, bin) = try project(php: "echo path-php") + try script(in: dir, "herd/bin/php", "echo herd\necho \"${PATH%%:*}\"") + let log = LineLog() + let code = await service(dir, bin: bin, herd: dir.url("herd/bin/php").path).runDump(onLine: log.append) + #expect(code == 0) + #expect(log.outputs == ["herd", dir.url("herd/bin").path]) + } + + @Test func thePhpOnThePathIsTheFallback() async throws { + let (dir, bin) = try project(php: "echo \"${PATH%%:*}\"") + let log = LineLog() + #expect(await service(dir, bin: bin).runDump(onLine: log.append) == 0) + #expect(log.outputs == [bin.path]) + } + + @Test func noPhpIsOneClearErrorLine() async throws { + let (dir, bin) = try project() + let log = LineLog() + let code = await service(dir, bin: bin).runDump(onLine: log.append) + #expect(code != 0) + #expect(log.errors == ["php not found. Install Laravel Herd or put php on PATH."]) + #expect(log.outputs.isEmpty) + } + + @Test func theRunNeverWaitsOnInput() async throws { + let (dir, bin) = try project(php: "read answer\necho \"read: [$answer]\"") + let log = LineLog() + #expect(await service(dir, bin: bin, timeout: 10).runDump(onLine: log.append) == 0) + #expect(log.outputs == ["read: []"]) + } + + @Test func aHungRunTimesOut() async throws { + let (dir, bin) = try project(php: "echo started\nexec sleep 30") + let log = LineLog() + let start = Date() + let code = await service(dir, bin: bin, timeout: 0.5).runDump(onLine: log.append) + #expect(code == -1) + #expect(log.errors == ["timed out after 0.5s"]) + #expect(Date().timeIntervalSince(start) < 10) + } +} + +@Suite struct SchemaLayoutStoreTests { + private func withDefaults(_ body: (UserDefaults) throws -> Void) rethrows { + let suite = "helder-test-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + try body(defaults) + } + + @Test func positionsRoundTripPerProject() { + withDefaults { defaults in + let store = UserDefaultsSchemaLayoutStore(defaults: defaults) + #expect(store.loadPositions(root: "/a").isEmpty) + store.savePositions(["users": SchemaPoint(x: 40, y: 104.5)], root: "/a") + #expect(store.loadPositions(root: "/a") == ["users": SchemaPoint(x: 40, y: 104.5)]) + #expect(store.loadPositions(root: "/b").isEmpty) + #expect(defaults.data(forKey: "helder.schemaLayout:/a") != nil) + } + } + + @Test func unreadablePositionsAreEmpty() { + withDefaults { defaults in + defaults.set(Data("nope".utf8), forKey: SchemaLayout.defaultsKey(root: "/a")) + #expect(UserDefaultsSchemaLayoutStore(defaults: defaults).loadPositions(root: "/a").isEmpty) + } + } +} diff --git a/Tests/HelderUITests/Overlays/OverlayListTests.swift b/Tests/HelderUITests/Overlays/OverlayListTests.swift index f4ca9c1..954ffab 100644 --- a/Tests/HelderUITests/Overlays/OverlayListTests.swift +++ b/Tests/HelderUITests/Overlays/OverlayListTests.swift @@ -5,14 +5,14 @@ import HelderCore import Testing @Suite struct ShortcutCatalogTests { - @Test func theGroupsAreNavigateAgentGitFileInThatOrder() { - #expect(ShortcutCatalog.groups.map(\.title) == ["Navigate", "Agent", "Git", "File"]) + @Test func theGroupsAreNavigateAgentGitSchemaFileInThatOrder() { + #expect(ShortcutCatalog.groups.map(\.title) == ["Navigate", "Agent", "Git", "Schema", "File"]) } @Test func everyShortcutTheAppHandlesIsListed() { let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() }) let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘P", - "⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc", + "⌘C", "⌘↵", "⌘G", "⌘D", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc", "⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−", "⌘1", "⌘2", "⌘3"] #expect(Set(handled).subtracting(listed).isEmpty) } diff --git a/Tests/HelderUITests/Schema/SchemaViewTests.swift b/Tests/HelderUITests/Schema/SchemaViewTests.swift new file mode 100644 index 0000000..3ccef9c --- /dev/null +++ b/Tests/HelderUITests/Schema/SchemaViewTests.swift @@ -0,0 +1,346 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI +import Testing + +/// `users` plus tables that each point at it through `user_id`, in name order. +func schemaSample(_ names: [String] = ["posts", "users"]) -> SchemaModel { + let tables = names.sorted().map { name in + SchemaTable(name: name, rows: 3, columns: [ + SchemaColumn(name: "id", type: "bigint", isPrimary: true), + SchemaColumn(name: "user_id", type: "bigint", isForeign: name != "users", + foreignTarget: name == "users" ? nil : SchemaColumnRef(table: "users", column: "id")), + ]) + } + let edges = names.sorted().filter { $0 != "users" }.map { + SchemaEdge(from: $0, column: "user_id", columnIndex: 1, to: "users", targetColumnIndex: 0) + } + return SchemaModel(connectionLabel: "mysql · shop", tables: tables, edges: edges) +} + +@MainActor +@Suite struct SchemaViewAvailabilityTests { + @Test func aProjectWithoutArtisanHasNoSchemaView() async { + let harness = WorkspaceHarness() + harness.schema.setLaravelApp(false) + await harness.start() + await harness.perform(.toggleSchemaView) + #expect(!harness.model.layout.isSchemaViewOpen) + #expect(harness.model.schema?.isLaravelApp == false) + } + + @Test func aLaravelAppWithoutTheCommandOpensOnTheCommandPrompt() async throws { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + #expect(harness.model.layout.isSchemaViewOpen) + #expect(schema.body == .commandMissing) + #expect(schema.metaLabel == "no command yet") + await harness.perform(.toggleSchemaView) + #expect(!harness.model.layout.isSchemaViewOpen) + } + + @Test func anExistingDumpLoadsWhenTheViewOpens() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setDump(schemaSample()) + await harness.start() + #expect(harness.schema.reads == 0) + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + #expect(schema.body == .diagram) + #expect(schema.metaLabel.hasPrefix("dumped ")) + #expect(schema.metaLabel.hasSuffix(" · 2 tables · 1 relations")) + #expect(schema.runLabel == "Re-run helder:schema") + } + + @Test func theGitAndSchemaViewsNeverShowTogether() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + await harness.perform(.toggleGit) + #expect(harness.model.layout.isGitViewOpen) + #expect(!harness.model.layout.isSchemaViewOpen) + await harness.perform(.toggleSchemaView) + #expect(harness.model.layout.isSchemaViewOpen) + #expect(!harness.model.layout.isGitViewOpen) + } + + @Test func closingGivesTheKeyboardBackToTheColumn() async { + let harness = WorkspaceHarness() + await harness.start() + harness.model.perform(.focus(.terminal)) + await harness.perform(.toggleSchemaView) + #expect(harness.model.focusRequest == nil) + await harness.perform(.closeSchemaView) + #expect(harness.model.focusRequest?.target == .panel(.terminal)) + } +} + +@MainActor +@Suite struct SchemaCommandPromptTests { + @Test func generateCommandPastesThePromptUnsentAndClosesTheView() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + await harness.perform(.generateSchemaCommand) + #expect(!harness.model.layout.isSchemaViewOpen) + #expect(harness.agent.sent == [BracketedPaste.wrap(SchemaCommandPrompt.text, composerHasText: false)]) + #expect(harness.agent.sent.allSatisfy { !$0.hasSuffix("\r") }) + #expect(harness.model.toasts.toasts.last?.title == "Passed to agent") + #expect(harness.model.toasts.toasts.last?.detail == "Command prompt") + } + + @Test func copyPromptCopiesAndToasts() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + await harness.perform(.copySchemaPrompt) + #expect(harness.system.copied == [SchemaCommandPrompt.text]) + #expect(harness.toastTitles == ["Copied prompt"]) + #expect(harness.model.layout.isSchemaViewOpen) + } +} + +@MainActor +@Suite struct SchemaRunTests { + @Test func aSuccessfulRunStreamsReloadsAndToasts() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setRun(FakeSchemaRun(lines: [(" Tables ........ 2", false), (" Wrote database/helder/schema.json (1 KB)", false)], + writes: schemaSample())) + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + #expect(schema.body == .noDump) + #expect(schema.runLabel == "Run helder:schema") + await harness.perform(.runSchemaDump) + #expect(schema.body == .diagram) + #expect(schema.lines.map(\.line.text) == ["$ php artisan helder:schema", " Tables ........ 2", + " Wrote database/helder/schema.json (1 KB)"]) + #expect(schema.lines.map(\.line.kind) == [.command, .output, .success]) + #expect(schema.isConsoleOpen) + #expect(!schema.isBusy) + #expect(harness.toastTitles == ["Schema dumped · 2 tables"]) + } + + @Test func aFailedRunKeepsTheConsoleOpenAndToastsNothing() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setRun(FakeSchemaRun(exitCode: 1, lines: [(" ERROR Connection refused.", false), ("trace", true)])) + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + schema.hideConsole() + await harness.perform(.runSchemaDump) + #expect(schema.isConsoleOpen) + #expect(schema.model == nil) + #expect(schema.lines.last?.line.kind == .error) + #expect(harness.toastTitles.isEmpty) + } + + @Test func aClickWhileItRunsIsIgnored() async { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setRun(FakeSchemaRun(writes: schemaSample(), delay: .milliseconds(150))) + await harness.start() + await harness.perform(.toggleSchemaView) + harness.model.perform(.runSchemaDump) + #expect(await eventually { harness.model.schema?.isBusy == true }) + #expect(harness.model.schema?.runLabel == "Dumping…") + harness.model.perform(.runSchemaDump) + await harness.model.settle() + #expect(harness.schema.runs == 1) + } + + @Test func withoutTheCommandRunDoesNothing() async { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + await harness.perform(.runSchemaDump) + #expect(harness.schema.runs == 0) + } + + @Test func aCorruptDumpShowsItsErrorInTheConsoleAndAToast() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setDump(schemaSample()) + harness.schema.setReadError(SchemaDumpError.corrupt(reason: "Unexpected character")) + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + #expect(schema.model == nil) + #expect(schema.loadError?.contains("Unexpected character") == true) + #expect(schema.lines.last?.line.kind == .error) + #expect(schema.isConsoleOpen) + #expect(harness.toastTitles == ["Could not read the schema"]) + } +} + +@MainActor +@Suite struct SchemaLiveTests { + @Test func theViewFlipsWhenTheCommandAndItsDumpAppear() async throws { + let harness = WorkspaceHarness() + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + #expect(schema.body == .commandMissing) + + harness.schema.setHasCommand(true) + try #require(harness.watchers.last).emit(.project) + #expect(await eventually { schema.body == .noDump }) + + harness.schema.setDump(schemaSample()) + try #require(harness.watchers.last).emit(.project) + #expect(await eventually { schema.body == .diagram }) + } + + @Test func aChangedDumpReloadsKeepingTheViewAndPositions() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setDump(schemaSample(), date: Date(timeIntervalSince1970: 1000)) + await harness.start() + await harness.perform(.toggleSchemaView) + let schema = try #require(harness.model.schema) + let view = SchemaViewport(x: 120, y: -40, scale: 0.8) + schema.setViewport(view) + let moved = SchemaPoint(x: 900, y: 700) + schema.moveTable("users", to: moved) + schema.endDrag() + + let grown = schemaSample(["comments", "posts", "users"]) + harness.schema.setDump(grown, date: Date(timeIntervalSince1970: 2000)) + try #require(harness.watchers.last).emit(.project) + #expect(await eventually { schema.model?.tableCount == 3 }) + #expect(schema.viewport == view) + #expect(schema.positions["users"] == moved) + #expect(schema.positions["comments"] == SchemaLayout.defaultPositions(grown)["comments"]) + } + + @Test func anUnchangedDumpIsNotReadAgain() async throws { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setDump(schemaSample(), date: Date(timeIntervalSince1970: 1000)) + await harness.start() + await harness.perform(.toggleSchemaView) + #expect(harness.schema.reads == 1) + try #require(harness.watchers.last).emit(.project) + #expect(await eventually { harness.git.loads >= 2 }) + await harness.model.settle() + #expect(harness.schema.reads == 1) + } +} + +@MainActor +@Suite struct SchemaCanvasStateTests { + private func opened(saved: [String: SchemaPoint]? = nil) async throws -> (WorkspaceHarness, SchemaStore) { + let harness = WorkspaceHarness() + harness.schema.setHasCommand(true) + harness.schema.setDump(schemaSample()) + if let saved { harness.schemaLayouts.saved = [harness.root.path: saved] } + await harness.start() + await harness.perform(.toggleSchemaView) + return (harness, try #require(harness.model.schema)) + } + + @Test func positionsAreSavedWhenADragEndsAndComeBackNextTime() async throws { + let (harness, schema) = try await opened() + let point = SchemaPoint(x: 512, y: 64) + schema.moveTable("posts", to: point) + #expect(harness.schemaLayouts.saved.isEmpty) + schema.endDrag() + #expect(harness.schemaLayouts.saved[harness.root.path]?["posts"] == point) + + let (_, again) = try await opened(saved: ["posts": point]) + #expect(again.positions["posts"] == point) + #expect(again.positions["users"] == SchemaLayout.defaultPositions(schemaSample())["users"]) + } + + @Test func theFirstDumpFitsOnceTheCanvasHasASize() async throws { + let (_, schema) = try await opened() + #expect(schema.viewport == SchemaViewport()) + schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) + let bounds = try #require(SchemaGeometry.bounds(schemaSample(), positions: schema.positions)) + #expect(schema.viewport == SchemaGeometry.fit(bounds: bounds, in: SchemaSize(width: 1000, height: 600))) + schema.setViewport(SchemaViewport(x: 5, y: 5, scale: 1)) + schema.setCanvasSize(SchemaSize(width: 1200, height: 600)) + #expect(schema.viewport == SchemaViewport(x: 5, y: 5, scale: 1)) + } + + @Test func centringLeavesRoomForTheDetailPanelThatOpens() async throws { + let (_, schema) = try await opened() + schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) + let before = schema.viewport + let users = try #require(schemaSample().table(named: "users")) + schema.centre("users") + #expect(schema.selected == "users") + #expect(schema.viewport == SchemaGeometry.centre(users, at: schema.positions["users"]!, + in: SchemaSize(width: 680, height: 600), view: before)) + let posts = try #require(schemaSample().table(named: "posts")) + let open = schema.viewport + schema.centre("posts") + #expect(schema.viewport == SchemaGeometry.centre(posts, at: schema.positions["posts"]!, + in: SchemaSize(width: 1000, height: 600), view: open)) + } + + @Test func enterInTheSearchCentresTheFirstMatch() async throws { + let (_, schema) = try await opened() + schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) + schema.query = "us" + schema.centreFirstMatch() + #expect(schema.selected == "users") + schema.query = "nothing" + schema.clearSelection() + schema.centreFirstMatch() + #expect(schema.selected == nil) + } + + @Test func aClickSelectsAndASecondClickDeselects() async throws { + let (harness, schema) = try await opened() + schema.toggleSelection("users") + #expect(schema.selectedTable?.name == "users") + schema.toggleSelection("users") + #expect(schema.selected == nil) + schema.toggleSelection("posts") + await harness.perform(.clearSchemaSelection) + #expect(schema.selected == nil) + schema.query = "po" + await harness.perform(.clearSchemaSearch) + #expect(schema.query.isEmpty) + } + + @Test func hoverWaitsWhileACardIsDragged() async throws { + let (_, schema) = try await opened() + schema.moveTable("posts", to: SchemaPoint(x: 1, y: 1)) + schema.hover("users") + #expect(schema.hovered == nil) + schema.endDrag() + schema.hover("users") + schema.hoverColumn("posts.user_id") + #expect(schema.highlight?.activeEdges == ["posts.user_id"]) + schema.hover(nil) + #expect(schema.hoveredColumn == nil) + } + + @Test func passOnAndCopyNameUseTheTable() async throws { + let (harness, _) = try await opened() + await harness.perform(.copySchemaTableName("users")) + #expect(harness.system.copied == ["users"]) + #expect(harness.toastTitles == ["Copied table name"]) + await harness.perform(.passSchemaTable("users")) + #expect(!harness.model.layout.isSchemaViewOpen) + #expect(harness.agent.sent == [BracketedPaste.wrap("@schema:users", composerHasText: false)]) + } + + @Test func theCommandPathOpensTheCommandInTheEditor() async { + let harness = WorkspaceHarness(contents: [SchemaPaths.commandFile: " + + init(hasCommand: Bool = false, dump: SchemaModel? = nil) { + state = Locked(State(hasCommand: hasCommand, dump: dump, dumpDate: dump == nil ? nil : Date())) + } + + var runs: Int { state.current.runs } + var reads: Int { state.current.reads } + + func setLaravelApp(_ value: Bool) { state.mutate { $0.isLaravelApp = value } } + func setHasCommand(_ value: Bool) { state.mutate { $0.hasCommand = value } } + func setDump(_ model: SchemaModel?, date: Date? = Date()) { state.mutate { $0.dump = model; $0.dumpDate = model == nil ? nil : date } } + /// Makes every `readDump` throw this error, or read normally again with nil. + func setReadError(_ error: Error?) { state.mutate { $0.readError = error } } + func setRun(_ run: FakeSchemaRun) { state.mutate { $0.run = run } } + + func isLaravelApp() async -> Bool { state.current.isLaravelApp } + func hasCommand() async -> Bool { state.current.hasCommand } + + func readDump() async throws -> SchemaModel? { + let (dump, error) = state.mutate { state in + state.reads += 1 + return (state.dump, state.readError) + } + if let error { throw error } + return dump + } + + func dumpModificationDate() async -> Date? { state.current.dumpDate } + + func runDump(onLine: @escaping @Sendable (String, Bool) -> Void) async -> Int32 { + let run = state.mutate { state in + state.runs += 1 + return state.run + } + for line in run.lines { onLine(line.text, line.isError) } + if run.delay > .zero { try? await Task.sleep(for: run.delay) } + if let written = run.writes { + state.mutate { $0.dump = written; $0.dumpDate = Date() } + } + return run.exitCode + } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSchemaLayouts.swift b/Tests/HelderUITests/Support/Fakes/FakeSchemaLayouts.swift new file mode 100644 index 0000000..481edb2 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSchemaLayouts.swift @@ -0,0 +1,16 @@ +import Foundation +import HelderCore +import HelderServices + +/// Schema card positions per project, in memory instead of UserDefaults. +final class FakeSchemaLayouts: SchemaLayoutPersisting, @unchecked Sendable { + private let state = Locked([String: [String: SchemaPoint]]()) + + var saved: [String: [String: SchemaPoint]] { + get { state.current } + set { state.mutate { $0 = newValue } } + } + + func loadPositions(root: String) -> [String: SchemaPoint] { state.current[root] ?? [:] } + func savePositions(_ positions: [String: SchemaPoint], root: String) { state.mutate { $0[root] = positions } } +} diff --git a/Tests/HelderUITests/Support/WorkspaceHarness.swift b/Tests/HelderUITests/Support/WorkspaceHarness.swift index 5b15e60..447540c 100644 --- a/Tests/HelderUITests/Support/WorkspaceHarness.swift +++ b/Tests/HelderUITests/Support/WorkspaceHarness.swift @@ -18,6 +18,8 @@ struct WorkspaceHarness { let layouts: FakeLayouts let system: FakeSystem let speech: FakeSpeech + let schema: FakeSchema + let schemaLayouts: FakeSchemaLayouts let watchers: WatcherBox let agent = FakeTerminal() @@ -38,12 +40,15 @@ struct WorkspaceHarness { let layouts = FakeLayouts() let system = FakeSystem() let speech = FakeSpeech() + let schema = FakeSchema() + let schemaLayouts = FakeSchemaLayouts() let watchers = WatcherBox() let app = AppServices( - recentProjects: recentStore, session: session, layouts: layouts, system: system, speech: speech, + recentProjects: recentStore, session: session, layouts: layouts, schemaLayouts: schemaLayouts, + system: system, speech: speech, makeWorkspace: { _ in WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols, - config: config, recentFiles: recentFiles) + config: config, recentFiles: recentFiles, schema: schema) }, makeWatcher: { let watcher = FakeWatcher() @@ -63,6 +68,8 @@ struct WorkspaceHarness { self.layouts = layouts self.system = system self.speech = speech + self.schema = schema + self.schemaLayouts = schemaLayouts self.watchers = watchers model.terminal.attach(agent, as: .agent) } diff --git a/docs/architecture.md b/docs/architecture.md index a32194c..499ce13 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -Swift package at the repo root, macOS 14+, one project per window and one window per process. The behaviour spec is [behaviour.md](behaviour.md), the visual system [design/README.md](design/README.md). +Swift package at the repo root, macOS 14+, one project per window and one window per process. The behaviour spec is [behaviour.md](behaviour.md), the visual system [design/README.md](../design/README.md). ## Layers @@ -18,7 +18,7 @@ Helder (executable) → HelderUI → HelderServices → HelderCore ## How a window works -- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `CleanCopyStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`, `ReadAloudStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. +- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `CleanCopyStore`, `SchemaStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`, `ReadAloudStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. - **One entry point.** Views, the menu bar and the key router all call `WorkspaceModel.perform(Command)` (`Shell/Command.swift`). Context-menu items arrive as `.context(ContextAction)`; the model asks `SourceControlStore.confirmation(for:)` / `ExplorerStore.confirmation(for:)` first and shows the confirm overlay, and `.confirmPending` runs the action. The name prompt submits with `.submitName`, the pass-on prompt with `.passToAgent`. - **Overlays never stack.** `OverlayStore.current` is one `Overlay` enum; only the model presents or dismisses it. `OverlayStore.onChange` lets the model run closing behaviour however an overlay went away (the Diff gives back the mode it covered). `OverlayHost` draws the current overlay. `.launcher` is the ⇧⌘O "Open recent project" list; the bare window's launcher is part of the shell, not an overlay. The key router only sees `OverlayKind` (`none`, `diff(busy:)`, `other`): over the Diff the workspace keys keep working unless its own menu or prompt is open (`busy`). Toasts (`ToastStore`) may sit on top. The Diff draws its own right-click menu and pass-on prompt inside itself, so it stays open. - **Read aloud.** `.readAloudFile` reads the open file's buffer (unsaved edits included) or the file from disk, turns it into prose with `MarkdownSpeech`, and hands it to `ReadAloudStore`; `.readAloudText` speaks the selection (selected Markdown as prose). `ReadAloudStore` lives as long as the window, like `ToastStore`; its `isReading` shows the title bar's Stop, which runs `.stopReading`. `closeProject()` stops the reading. @@ -26,7 +26,8 @@ Helder (executable) → HelderUI → HelderServices → HelderCore - **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the session and ends the terminals. - **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the session, stops the watcher and polling, and ends both terminals. - **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live. -- **Git view.** ⌘G toggles `LayoutStore.isGitViewOpen` (never persisted, reset on a project switch). `WorkspaceView` draws `GitView` as an overlay over title bar, columns and status bar, under `OverlayHost`, so every overlay and toast sits above it; the columns stay mounted. `KeyContext.gitViewOpen` sends keys to `KeyRouter.gitViewKey` (column keys rest, ⌘↵ commits) and makes a bare Esc `.closeGitView` once no overlay is open; `inGitConsole` (first responder is a `GitConsoleFieldEditor`) keeps ⌘↵ from committing out of the console. `openGitView()` / `closeGitView()` in `+Commands` move the focus request (commit message in, previous `activePanel` out). Design source: `docs/design_handoff_helder_app_v2/README.md`. +- **Git view.** ⌘G toggles `LayoutStore.isGitViewOpen` (never persisted, reset on a project switch). `WorkspaceView` draws `GitView` as an overlay over title bar, columns and status bar, under `OverlayHost`, so every overlay and toast sits above it; the columns stay mounted. `KeyContext.gitViewOpen` sends keys to `KeyRouter.gitViewKey` (column keys rest, ⌘↵ commits) and makes a bare Esc `.closeGitView` once no overlay is open; `inGitConsole` (first responder is a `GitConsoleFieldEditor`) keeps ⌘↵ from committing out of the console. `openGitView()` / `closeGitView()` in `+Commands` move the focus request (commit message in, previous `activePanel` out). Design source: `design/README.md`. +- **Schema view.** ⌘D toggles `LayoutStore.isSchemaViewOpen` (never persisted, reset on a project switch); `openGitView`/`openSchemaView` close each other. It exists only when `SchemaStore.isLaravelApp` (an `artisan` file): the title-bar toggle, `KeyContext.schemaAvailable` for ⌘D and the View menu item follow it. `WorkspaceView` draws `SchemaView` like `GitView`. `SchemaStore.body` picks the command-missing prompt, the no-dump state or the diagram. The watcher's `.project` events and ⌘R carry `RefreshScope.schema`: `refresh(readingDump:)` re-checks the command and re-reads the dump only when its modification date moved, keeping viewport and positions (`SchemaLayout.positions(_:saved:)`). Card positions go to `AppServices.schemaLayouts` when a drag ends; the first dump in a store fits once the canvas has a size. `run()` streams `SchemaServicing.runDump` like the Git console and toasts through `notify`. Esc over the view: selection (`.clearSchemaSelection`), then the search text while `SchemaSearchFieldEditor` has the keyboard (`.clearSchemaSearch`), then `.closeSchemaView`. The canvas lays each card out at 100% and scales it into its on-screen frame, so the click and `.pointerHand()` area stay unscaled; scroll and pinch arrive through a local event monitor (`SchemaScrollCatcher`), since the cards would take them otherwise. Contract: [schema.md](schema.md). - **Git commands.** Every git write and every typed console command goes through `SourceControlStore.run`, which chains onto `commandTail` so two commands never race for `.git/index.lock`, logs `$ git …` and streams lines via `GitServicing.execute` → `ProcessRunning.stream` into the console (`GitOutputClassifier`, one per run). `execute` never throws and switches off prompts, editors and pagers (`GIT_TERMINAL_PROMPT=0`, `GIT_EDITOR=true`, `GIT_PAGER=cat`), so a run can never wait on input. Typed commands run without literal pathspecs (globs work); buttons always pass explicit paths, never `add -A`. Push/pull/fetch and typed commands get `remoteTimeout` (120 s). Commit always runs git, even when `canCommitNow` is false, so git's refusal is the error the user sees. Branch switching is refused in the store while `isDirty`, without asking git. The status read (`load`) stays on `ProcessRunning.run`. - **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`. - **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject `, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window. @@ -43,6 +44,8 @@ Sources/HelderCore/ Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus) Git/ GitStatus/Change/GitSnapshot, Porcelain parsing (incl. behind/upstream), GitDerivation (rows, commit text), GitSections (the four sections, InlineDiff), GitConsole (echo, input parsing, line classifier), GitBranches + Schema/ SchemaDump (tolerant schema.json decoding), SchemaModel, SchemaLayout (default lanes), SchemaGeometry + (lines, fit, zoom, centre), SchemaHighlight + SchemaSearch, ArtisanConsole, SchemaCommandPrompt, SchemaPaths Highlight/ SyntaxHighlighter and one grammar per language Markdown/ block/inline tree and parser, MarkdownSpeech (the prose Read aloud speaks) Search/ result models, Fuzzy, InFileSearch, rg --json parsing @@ -54,6 +57,7 @@ Sources/HelderServices/ Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log) Process/ ProcessRunner (`run`, and `stream` for line-by-line output), ExecutableLocator, ChildReaper, InstanceLauncher Project/ ConfigService, RecentStores, SessionStore, ProjectLocator + Schema/ SchemaServicing + SchemaService (`php artisan helder:schema` via PHPLocator, the dump), SchemaLayoutPersisting Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk) Speech/ SpeechServicing + SpeechService (AVSpeechSynthesizer, the system voice), shared by the window Symbols/ SymbolService @@ -64,7 +68,10 @@ Sources/HelderUI/ Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator, Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter, ButtonGroup (pane toggles, toolbar), Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink - GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches + GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches; + GitIcon and the console log/input the Schema view reuses + SchemaView/ the full-screen Schema view (⌘D): top bar, table list, canvas with cards and lines, detail panel, + artisan console, the no-dump and command-missing states Explorer/ the file tree column and the row glyphs Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup Terminal/ agent + shell panes over SwiftTerm @@ -76,7 +83,7 @@ Tests/HelderUITests/Support/ WorkspaceHarness, StoreHarnesses (EditorHarness, Tests/HelderUITests/Support/Fakes/ one fake per service protocol (FakeGit, FakeFiles, FakeSystem, …) assets/icon.png the app icon; bundle.sh turns it into Helder.icns vendor/ripgrep/rg ripgrep 15 for Apple silicon, from the @vscode/ripgrep build (its LICENSE beside it), bundled as Contents/Helpers/rg -docs/design/ design tokens, the design canvas and reference screenshots +design/ the design handoff (README.md) and the HTML prototype ``` ## Commands diff --git a/docs/behaviour.md b/docs/behaviour.md index b526022..8826d05 100644 --- a/docs/behaviour.md +++ b/docs/behaviour.md @@ -20,7 +20,7 @@ The three columns of the body, left to right, are: 2. **Editor** (one file and its code) 3. **Agent and Terminal**, a single column split into two stacked panes: the Claude agent pane on top and a shell terminal below it. -Git is not a column: the full-screen **Git view** (section 3) covers all three regions while it is open. +Git is not a column: the full-screen **Git view** (section 3) covers all three regions while it is open. In a Laravel app the full-screen **Schema view** (section 4) does the same; the two never show together. Every boundary between panes is a draggable splitter. The vertical splitters between the three columns adjust their widths. The horizontal splitter between the agent pane and the terminal pane adjusts their heights. Splitter positions persist across launches. Panes have sensible minimum widths and heights so they cannot be collapsed to nothing by dragging. @@ -34,8 +34,8 @@ The top bar contains, left to right: - The Helder wordmark. - A breadcrumb showing the path to the active file, for example `console / src / Http / Controller / UserController.php`. The breadcrumb is **display only** for now. It is not clickable and does not navigate. -- Centred on the window, the **pane toggles**: Explorer · File · Claude. Each shows or hides one column, all on by default (see Pane toggles in section 9). The breadcrumb truncates before it reaches them. -- On the right, the toolbar: **`Git N`** (`Cmd+G`) toggles the Git view (section 3); N counts the changed files, a file both staged and unstaged once, and the count is left out when there are none. **Search** (`Cmd+F`) is an action; **Fluid** (`Cmd+L`) and **Hidden** (`Cmd+.`) are toggles. Then `?` for the keyboard shortcuts. +- Centred on the window, the **pane toggles**: Explorer · File · Claude. Each shows or hides one column, all on by default (see Pane toggles in section 10). The breadcrumb truncates before it reaches them. +- On the right, the toolbar: **`Git N`** (`Cmd+G`) toggles the Git view (section 3); N counts the changed files, a file both staged and unstaged once, and the count is left out when there are none. In a Laravel app (an `artisan` file in the root) **Schema** (`Cmd+D`) follows it and toggles the Schema view (section 4); elsewhere it is left out. **Search** (`Cmd+F`) is an action; **Fluid** (`Cmd+L`) and **Hidden** (`Cmd+.`) are toggles. Then `?` for the keyboard shortcuts. - While Helder reads aloud, a **Stop** toggle appears left of **Git**, in the same style and switched on. A click switches it off and stops the reading; the button then goes away. It also goes away when the reading reaches the end, and a project switch or window close stops the reading. --- @@ -98,7 +98,51 @@ The bottom-right panel: **local** branches, then **remote · origin**. The curre --- -## 4. Explorer panel +## 4. Schema view + +A full-screen view, drawn like the Git view, that shows the database of a Laravel app as a diagram of tables and foreign-key lines. It exists only in a Laravel app: a project with an `artisan` file in its root. Elsewhere there is no **Schema** button, `Cmd+D` does nothing and View › Show Schema is disabled. `Cmd+D`, the **Schema** toggle and View › Show Schema open it; `Cmd+D`, `Esc` and its **Close** button close it. Opening it closes the Git view, and opening the Git view closes it. Dialogs, menus, search and toasts sit above it, and the columns stay mounted under it. It is not persisted: a project always opens with it closed. + +Helder reads the diagram from `database/helder/schema.json`, which the app's own Artisan command `app/Console/Commands/HelderSchemaCommand.php` (`php artisan helder:schema`) writes. The file's contract is in [schema.md](schema.md). + +While it is open, the columns' row, focus and editor keys rest, as over the Git view; `Cmd+Return` and `Cmd+C` do nothing. `Esc` closes the topmost layer: an overlay first, then the table selection, then the table search's text (only while the search has the keyboard), then the view. + +### States + +- **No command yet**: the app has no `HelderSchemaCommand.php`. The body shows `[ NO COMMAND YET ]`, a line that names the dump and the command, **Generate command** and **Copy prompt**, and a scrollable, selectable preview of the prompt. **Generate command** closes the view and pastes the prompt into the Claude prompt without sending it (toast `Passed to agent` · `Command prompt`). **Copy prompt** copies it (toast `Copied prompt`). The top bar reads `no command yet`, its Run button is disabled and the command path is hidden. +- **No dump yet**: the command exists, the dump does not. `[ NO DUMP YET ]`, a line about `database/helder/schema.json`, the Run button and `$ php artisan helder:schema`. +- **Diagram**: the table list, the canvas, and the detail panel while a table is selected. + +The view flips between these states by itself: the watcher re-checks the command and re-reads the dump when its modification date changes, so a command that Claude writes and runs in the terminal shows its diagram without a click. A re-read keeps the pan, the zoom and the card positions; new tables get a default place. + +### Top bar + +`[ schema ]`, then (with a dump) the database icon and `driver · database` in amber, then `no command yet`, `no dump yet` or `dumped 14:32 · 16 tables · 23 relations`. On the right: the command path as a text button (it closes the view and opens the command in the editor), the amber Run button (`Run helder:schema`, `Re-run helder:schema` once a dump exists, `Dumping…` while it runs; clicks are ignored then) and **Close** (`⌘D`). + +### Running the command + +Run executes `php artisan helder:schema` in the project root with Herd's php, else the `php` on `PATH`. The console opens and shows `$ php artisan helder:schema`, then each output line as it arrives: errors in amber, `INFO`/`DONE`/`Wrote …` lines in teal. Exit code 0 re-reads the dump and toasts `Schema dumped · N tables`; any other code keeps the console open and toasts nothing more. A run stops after 120 seconds. A dump that is not valid JSON shows its error in the console and toasts `Could not read the schema`. + +### Table list + +240pt, left. A search field (`Find a table`) filters by substring; `Return` selects and centres the first match. `[ TABLES ] 16`, or `[ TABLES ] 3 of 16` while filtering. One row per table in name order with its row count. Hovering a row lights the table on the canvas as hovering the card does; a click selects and centres it. + +### Canvas + +Cards (240pt wide; a 33pt header with the name and row count, then a 22pt row per column with `PK`/`FK`/`UQ`, the name and the type, `?` for nullable) and one cubic line per foreign key, from the key's row to the referenced row: hollow end at the key, filled end at the target. Drag the background or scroll to pan; `Cmd`/`Ctrl` + scroll and pinch zoom around the pointer, 30–200%. The control bottom right zooms out, shows the percentage, zooms in (×1.2) and fits all cards (48pt margin, at most 110%). The first dump fits itself. Drag a card to move it (a press that moves less than 4pt is a click); its position is saved per project in Helder's settings when the drag ends. + +Hovering a table lights every line in or out of it in amber, outlines related tables and dims the rest to 30%; hovering a foreign-key row narrows that to one relationship. A click selects a table (click it again or the empty canvas to deselect). Without a focus, the search outlines matching cards and dims the rest. Only colour and opacity change, over 160ms; nothing moves. + +### Detail panel + +320pt, right, while a table is selected: the name, the row count and a close button; `[ COLUMNS ] N` with each column's type and flags (`PRIMARY · NOT NULL`, `FK → users.id · NULL`, `UNIQUE · NOT NULL`); `[ BELONGS TO ]` (outgoing keys) and `[ HAS MANY ]` (incoming keys), whose rows light the other table on hover and select and centre it on click; or `— No foreign keys in or out.`. Footer: **Pass on to Claude** closes the view and inserts `@schema:
` into the Claude prompt; **Copy name** copies it (toast `Copied table name`). + +### Console + +150pt, at the bottom, from the first run: `[ CONSOLE ] ARTISAN` and the run output, kept at the newest line, at most 400 lines. The chevron hides it until the next run. + +--- + +## 5. Explorer panel The second column. A standard project file tree. @@ -112,7 +156,7 @@ The second column. A standard project file tree. --- -## 5. Editor +## 6. Editor The third and widest column. It shows exactly one file: a bar on top and the code below. Opening another file replaces it. Opening a file always reads it fresh from disk. Edits are written only with `Cmd+S` (or by `editor.autoSave`). Opening a file, the same one included, while the open file has unsaved edits asks **Save**, **Don't Save** or **Cancel**: Save writes and then opens, Don't Save drops the edits and opens, Cancel keeps the current file, its edits and the Explorer selection. A failed save keeps the file open. With `editor.autoSave` on, the file saves silently instead of asking. @@ -144,7 +188,7 @@ Shared rules: teal is what the file holds now, amber-deep is what it held before ### Editing behavior - A file with no changes opens directly in a normal editable view with no Diff button, since there is nothing to diff. -- Editing follows the editor settings: indentation, indent width, trim trailing whitespace, insert final newline, word wrap, indent guides, whitespace rendering, and active-line highlight, all read from configuration (section 10). +- Editing follows the editor settings: indentation, indent width, trim trailing whitespace, insert final newline, word wrap, indent guides, whitespace rendering, and active-line highlight, all read from configuration (section 11). - **Word wrap** follows `editor.wordWrap`: `markdown` (default), `on`, or `off`. When it is on, a line too wide for the pane folds onto the next row instead of scrolling sideways. Only the first row of a folded line carries a line number; the rows below it stay blank. Diff never wraps, because its two panes align row by row. ### Right-click in code @@ -168,7 +212,7 @@ On a marked line of the live file (any marked line, blank lines and the space af --- -## 6. Agent pane +## 7. Agent pane The top pane of the fourth column. @@ -190,7 +234,7 @@ The agent hands the user text to copy through one file, `.clean-copy` in the pro --- -## 7. Terminal pane +## 8. Terminal pane The bottom pane of the fourth column. @@ -211,7 +255,7 @@ Right-clicking in the agent pane or the terminal pane shows a menu without a hea --- -## 8. Status bar +## 9. Status bar A bar across the bottom of the window. All items are **display only** for now; none are clickable. @@ -220,7 +264,7 @@ A bar across the bottom of the window. All items are **display only** for now; n --- -## 9. Global interactions +## 10. Global interactions ### Go to File (`Cmd+P`) @@ -246,11 +290,11 @@ Inside the overlay: The pointer shows what a left click does at that spot. It depends only on what lies under the mouse. -- **Pointing hand** only where a left click runs an action: buttons (title-bar toggles and tools, `?`, Preview, Diff, the Git view's buttons and section headers, dialog buttons, Collapse, search chips), clickable rows (Git view file rows and switchable branches, Explorer rows, search results, recent files and projects, launcher rows, symbol popup rows, context-menu items) and the project name in the title bar. Never on a view that only reacts to a right-click, a tooltip or hover. +- **Pointing hand** only where a left click runs an action: buttons (title-bar toggles and tools, `?`, Preview, Diff, the Git view's buttons and section headers, dialog buttons, Collapse, search chips), clickable rows (Git view file rows and switchable branches, Schema table rows, cards and relation rows, Explorer rows, search results, recent files and projects, launcher rows, symbol popup rows, context-menu items) and the project name in the title bar. Never on a view that only reacts to a right-click, a tooltip or hover. - **I-beam** where a click places a caret or starts a selection: the code (also below the last line), the Markdown preview, both terminals, the commit message, the Git console and every overlay input. - **Arrow** everywhere else: labels, headers, folder labels, the gutter, the status bar, scrims, toasts, empty states, and a disabled button such as Commit with nothing staged. - With an overlay open, every column behind it, and the Git view, shows the arrow; the overlay's own buttons, rows and inputs keep theirs. -- A splitter shows a resize arrow; `Cmd` over a known PHP class name in the code shows the hand. No other pointers are used. +- A splitter shows a resize arrow; `Cmd` over a known PHP class name in the code shows the hand. No other pointers are used: the Schema canvas pans with the arrow, without a grab hand. ### Pane resizing @@ -266,7 +310,7 @@ When `session.restoreOnLaunch` is on (default), reopening a project restores the --- -## 10. Configuration +## 11. Configuration Settings are project-scoped and live in a `.helder` folder in the project root. @@ -279,12 +323,12 @@ Settings that affect behavior described above include indentation and editor dis --- -## 11. States and edge cases summary +## 12. States and edge cases summary - **No project open**: the window shows an empty state inviting the user to open a project folder. - **Clean working tree**: the Git view shows its clean message; the Explorer still shows the full tree. - **Unchanged file open**: normal editable view, no Diff button. -- **Added or deleted file**: views behave as described in section 5. +- **Added or deleted file**: views behave as described in section 6. - **Binary or unsupported file**: placeholder, no Preview or Diff button. - **Search with no matches**: per-column no-results messages. - **Agent command not available**: the agent pane is a terminal, so a missing or failing command surfaces as ordinary terminal output in that pane. diff --git a/docs/guide/index.md b/docs/guide/index.md index 32564e1..0aeecf1 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -23,7 +23,7 @@ This guide explains Helder from the user's side: what each part of the window sh ``` 1. [Title bar](title-bar.md): breadcrumb, pane toggles and toolbar. -2. [Git](git.md): the full-screen Git view (`Cmd+G`), with the [commit form](git-commit-form.md), a console and the branches. +2. [Git](git.md): the full-screen Git view (`Cmd+G`), with the [commit form](git-commit-form.md), a console and the branches. In a Laravel app, [Schema](schema.md) (`Cmd+D`) draws the database the same way. 3. [Explorer](explorer.md): the project's file tree. 4. [File view](file-view.md): one open file, with [Markdown preview](file-view-markdown.md) and [Diff](file-view-diff.md). 5. [Claude Code](claude-code.md): the agent session. @@ -41,10 +41,11 @@ This guide explains Helder from the user's side: what each part of the window sh - [Recent projects](recent-projects.md): switch to or open another project. - [Notifications](notifications.md): the short messages that confirm or warn. -### Git and files +### Git, schema and files - [Git](git.md): the full-screen Git view: changes, inline diffs, pull, push, console and branches. - [Git commit form](git-commit-form.md): write a message, commit, or commit and push. +- [Schema](schema.md): the full-screen database diagram of a Laravel app (`Cmd+D`). - [Explorer](explorer.md): browse, create, rename and delete files. ### The file view diff --git a/docs/guide/keyboard-shortcuts.md b/docs/guide/keyboard-shortcuts.md index 0b3d900..ad4104d 100644 --- a/docs/guide/keyboard-shortcuts.md +++ b/docs/guide/keyboard-shortcuts.md @@ -20,6 +20,8 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m | | ... | | | | GIT | | | | ... | | +| | SCHEMA | | +| | ... | | | | FILE | | | | ... | | | +----------------------------------------------+ | @@ -28,7 +30,7 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m ``` 1. **Header**: a question-mark icon, the title and an `esc` chip. -2. **Group label**: NAVIGATE, AGENT, GIT and FILE. +2. **Group label**: NAVIGATE, AGENT, GIT, SCHEMA and FILE. 3. **Row**: the keys as keycaps, then what they do. ## Features @@ -37,10 +39,11 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m - Open it with `?` when no text field, code view or terminal has the keyboard. You can also click the `?` button in the [title bar](title-bar.md), or choose View > Keyboard Shortcuts or Help > Keyboard Shortcuts. - Close it with `Esc`, or by clicking the dimmed backdrop. - It scrolls only when the window is too short to show all of it. -- It holds the main shortcuts, in four groups: +- It holds the main shortcuts, in five groups: - **Navigate**: search, list movement, column movement, the Explorer row cursor, the column toggles `Cmd+1` to `Cmd+3`, recent projects, open folder, new window, PHP class lookup, and this list. - **Agent**: pass the selection to the agent. - **Git**: open or close the Git view, focus the commit message, commit, push. + - **Schema**: open or close the Schema view (Laravel apps), and `Return` in its table search. - **File**: save, Markdown preview, close, refresh, hidden files, select all, Fluid columns, zoom, and `Esc`. - The full reference is below. @@ -48,8 +51,8 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m - A text field, the code, or a terminal keeps the keys it needs. Arrows, `Return`, `?`, `Cmd+A` and `Cmd+C` with a selection go to the field, not to Helder. - Keys with `Ctrl` or `Opt` always go to the field or terminal, except the menu shortcuts that use them. - While an overlay is open, it owns the keys. `Esc` closes it. The Diff is the exception: the workspace shortcuts keep working over it. -- `Esc` closes the topmost layer: a right-click menu, a dialog, search or the Diff first, then the [Git](git.md) view. With none of those open, `Esc` goes to the terminal. -- While the Git view is open, the column keys rest: arrows, `Return` and `Cmd+Left` / `Cmd+Right` do nothing in the columns under it. +- `Esc` closes the topmost layer: a right-click menu, a dialog, search or the Diff first, then the [Schema](schema.md) view's selection, its search text and the view itself, or the [Git](git.md) view. With none of those open, `Esc` goes to the terminal. +- While the Git or Schema view is open, the column keys rest: arrows, `Return` and `Cmd+Left` / `Cmd+Right` do nothing in the columns under it. ## Keyboard @@ -104,6 +107,15 @@ See [Git](git.md) and [Git commit form](git-commit-form.md). | `Return` | Run the command in the console input | | `Up` | Recall the previous console command | +### Schema view +See [Schema](schema.md). Only in a Laravel app: a project with an `artisan` file. + +| Keys | Action | +|---|---| +| `Cmd+D` | Open or close the Schema view | +| `Return` | In the table search: select and centre the first match | +| `Esc` | Deselect the table, then clear the search (while it has the keyboard), then close the view | + ### Explorer See [Explorer](explorer.md). diff --git a/docs/guide/schema.md b/docs/guide/schema.md new file mode 100644 index 0000000..7c29cde --- /dev/null +++ b/docs/guide/schema.md @@ -0,0 +1,131 @@ +# Schema + +The Schema view is a full-screen diagram of a Laravel app's database: every table as a card, every foreign key as a line. Hover a table to trace what it points at and what points at it, click it to read its columns, and hand a table to Claude. Open it with `Cmd+D`. + +[Guide index](index.md) · Related: [Git](git.md), [Title bar](title-bar.md), [Claude Code](claude-code.md), [Notifications](notifications.md) + +## At a glance + +```text ++----------------------------------------------------------------------------+ +| (1) [ schema ] = mysql . shop dumped 14:32 . 16 tables . 23 relations | +| app/Console/.../HelderSchemaCommand.php [>_ Re-run] [x] | +|----------------------------------------------------------------------------| +| (2) Q Find a table | (3) | (5) users x | +| [ TABLES ] 16 | +-----------------+ | [ COLUMNS ] 8 | +| |users 1,284 | | posts 312 | +-------+ | id bigint | +| posts 312 | | PK id bigint | | users | | PRIMARY . NOT.. | +| comments 9,812 | | FK user_id ----+--->| PK id | | [ HAS MANY ] | +| | +-----------------+ +-------+ | <- posts via .. | +| | (4) drag to pan ... [- 80% + Fit] | [Pass on][Copy] | +|----------------------------------------------------------------------------| +| (6) [ console ] artisan v | +| $ php artisan helder:schema | +| Wrote database/helder/schema.json (18.4 KB) | ++----------------------------------------------------------------------------+ +``` + +1. **Top bar**: the database, when the dump was made, the command path, the Run button and Close. +2. **Table list**: a search field and every table with its row count. +3. **Canvas**: the table cards and the relationship lines. +4. **Hint and zoom control**: how to move around, and zoom out, the zoom level, zoom in and Fit. +5. **Detail panel**: the selected table's columns and relations, while a table is selected. +6. **Console**: the output of `php artisan helder:schema`. + +## Features + +### When the view exists +- Only in a Laravel app: a project with an `artisan` file in its root. Anywhere else there is no **Schema** button and `Cmd+D` does nothing. +- The diagram comes from `database/helder/schema.json`. The app's own Artisan command `app/Console/Commands/HelderSchemaCommand.php` writes that file. See [the schema.json contract](../schema.md). + +### Open and close the view +- `Cmd+D`, the **Schema** toggle in the [Title bar](title-bar.md), or View > Show Schema opens it. The toggle's dot is amber while the view is open. +- The view covers the whole window. The columns stay as they were under it, and terminals keep running. +- Close it with `Cmd+D`, `Esc`, or the **Close** button. The keyboard goes back to the column that had it. +- The Git view and the Schema view never show together: opening one closes the other. +- The view is not remembered: a project always opens with it closed. + +### No command yet +A Laravel app without `HelderSchemaCommand.php` opens the view on `[ NO COMMAND YET ]`: + +```text ++--------------------------------------------------+ +| [ NO COMMAND YET ] | +| - Helder draws the schema from | +| database/helder/schema.json. The Artisan command| +| app/Console/Commands/HelderSchemaCommand.php | +| writes it, and this app does not have it yet. | +| [* Generate command] [Copy prompt] | +| +----------------------------------------------+ | +| | Build an Artisan command that dumps ... | | +| +----------------------------------------------+ | ++--------------------------------------------------+ +``` + +- **Generate command** closes the view and puts a prompt in the Claude prompt. It does not send it: read it, then press `Return` yourself. +- **Copy prompt** copies the same prompt, for another agent or a ticket. +- The box below shows the whole prompt, so you know what Claude gets. +- When Claude writes the command and runs it in the terminal, the view switches to the diagram by itself. + +### No dump yet +With the command but no `database/helder/schema.json`, the view shows `[ NO DUMP YET ]` and a **Run helder:schema** button. A dump that already exists loads as soon as the view opens. + +### Run the command +- **Run helder:schema** (or **Re-run helder:schema** once there is a dump) runs `php artisan helder:schema` in the project folder. Helder uses Laravel Herd's `php` when it is installed, else the `php` on your `PATH`. +- While it runs, the button reads `Dumping…` and more clicks do nothing. A run stops after 120 seconds. +- The console shows each line as it arrives: errors in amber, the `Wrote …` and `DONE` lines in teal. +- When it succeeds, the diagram reloads and a [notification](notifications.md) reads `Schema dumped · 16 tables`. +- When it fails, the console stays open with the error. +- A `schema.json` that is not valid JSON shows its error in the console and the notification `Could not read the schema`. + +### Table list +- Type in **Find a table** to filter the list. `Return` selects and centres the first match. `Esc` clears the search, while the search has the keyboard. +- The label reads `[ TABLES ] 16`, or `[ TABLES ] 3 of 16` while filtering. +- Hover a row to trace that table on the canvas. Click a row to select it and move it to the middle. + +### Move around the canvas +- Drag the empty background, or scroll, to pan. +- `Cmd` + scroll, `Ctrl` + scroll, or pinch to zoom around the pointer, from 30% to 200%. +- The control at the bottom right: `−` and `+` zoom around the middle; **Fit** shows every table. +- The first dump fits itself to the window. After that, a new dump keeps your view. + +### Arrange the tables +- Drag a card to move it. A press that hardly moves is a click. +- Helder remembers where you put the cards, per project. A new dump keeps them; new tables get a default place. +- The default places put tables that point at nothing on the left, and each other table one lane right of the deepest table it points at. + +### Trace a relation +- Hover a table: its lines turn amber, related tables get a grey outline and the rest fade. +- Hover a foreign-key row (`FK`) to trace only that one relation. +- With a search and nothing hovered or selected, matching cards get an amber outline and the rest fade. + +### Inspect a table +- Click a card to select it; the detail panel opens on the right. Click it again, or the empty canvas, to close it. +- **[ COLUMNS ]** lists every column with its type and flags, such as `FK → users.id · NULL`. +- **[ BELONGS TO ]** lists the tables this one points at; **[ HAS MANY ]** the tables that point at it. Hover a row to trace that table; click it to select it and move to it. +- **Pass on to Claude** closes the view and puts `@schema:
` in the Claude prompt. +- **Copy name** copies the table name. + +### Console +- It opens on the first run, at the bottom, and keeps the last 400 lines. +- The chevron hides it until the next run. + +### How the view stays up to date +You do not need to refresh by hand. Helder watches the project folder: when the command file appears or goes, or `database/helder/schema.json` changes, the view follows. `Cmd+R` checks again too. + +## Keyboard + +| Keys | Action | +|---|---| +| `Cmd+D` | Open or close the Schema view (Laravel apps) | +| `Return` | In the table search: select and centre the first match | +| `Esc` | Deselect the table, then clear the search (while it has the keyboard), then close the view | +| `Cmd+G` | Switch to the Git view | + +## Related + +- [Git](git.md): the other full-screen view. +- [Title bar](title-bar.md): the **Schema** toggle. +- [Claude Code](claude-code.md): where the prompt and `@schema:
` land. +- [The schema.json contract](../schema.md): the file the command writes. +- [Keyboard shortcuts](keyboard-shortcuts.md): every shortcut in one list. diff --git a/docs/guide/title-bar.md b/docs/guide/title-bar.md index ddcf737..38f1899 100644 --- a/docs/guide/title-bar.md +++ b/docs/guide/title-bar.md @@ -1,6 +1,6 @@ # Title bar -The title bar is the 44-point strip across the top of a project window. It tells you which project, branch and file you are on, and holds the column toggles, the Git toggle and the main tools. +The title bar is the 44-point strip across the top of a project window. It tells you which project, branch and file you are on, and holds the column toggles, the Git and Schema toggles and the main tools. [Guide index](index.md) · Related: [Window layout](layout.md), [Search](search.md), [Keyboard shortcuts](keyboard-shortcuts.md) @@ -11,8 +11,8 @@ The title bar is the 44-point strip across the top of a project window. It tells | o o o Helder. shop . main app > Http > User.php * | | (1) (2) (3) (4) (5) (6) | | | -| [.Explorer|.File|.Claude] [Git 3 |Search |.Fluid |.Hidden] [?] | -| (7) (8) (9) (10) (10) (11) | +| [.Explorer|.File|.Claude] [Git 3 |.Schema |Search |.Fluid |.Hidden] [?] | +| (7) (8) (9) (10) (11) (11) (12) | +----------------------------------------------------------------------------+ ``` @@ -21,7 +21,7 @@ The bar is one row in the app. It is drawn on two rows here to fit the page. While Helder reads aloud, a **Stop** button leads the toolbar: ```text -| [.Stop |Git 3 |Search |.Fluid |.Hidden] [?] | +| [.Stop |Git 3 |.Schema |Search |.Fluid |.Hidden] [?] | ``` 1. **Window buttons**: the macOS close, minimize and zoom buttons. @@ -32,9 +32,10 @@ While Helder reads aloud, a **Stop** button leads the toolbar: 6. **Unsaved dot**: an amber dot when the open file has unsaved edits. 7. **Pane toggles**: each shows or hides one column. 8. **Git N**: opens and closes the Git view. -9. **Search**: a button that opens an overlay. -10. **Fluid** and **Hidden**: on/off toggles. -11. **`?`**: opens the keyboard shortcuts. +9. **Schema**: opens and closes the Schema view, in a Laravel app only. +10. **Search**: a button that opens an overlay. +11. **Fluid** and **Hidden**: on/off toggles. +12. **`?`**: opens the keyboard shortcuts. ## Features @@ -63,12 +64,13 @@ While Helder reads aloud, a **Stop** button leads the toolbar: The toolbar sits on the right. Each button shows its shortcut next to its label. - **Git N** (`Cmd+G`): opens the full-screen [Git](git.md) view. N counts the changed files; a file that is both staged and unstaged counts once. With no changes it reads **Git**. The view covers the title bar, so close it with `Cmd+G`, `Esc` or its own **Close** button. +- **Schema** (`Cmd+D`): opens the full-screen [Schema](schema.md) view, the database diagram. It shows only in a Laravel app: a project with an `artisan` file in its root. Opening it closes the Git view, and the other way round. - **Search** (`Cmd+F`): opens search over the open file, the project contents and the file names. See [Search](search.md). - **Fluid** (`Cmd+L`): when on, the columns re-fit on resize and when focus moves. When off, they keep their size. See [Window layout](layout.md). - **Hidden** (`Cmd+.`): when on, dotfiles appear in the Explorer and in search. - **`?`**: opens the keyboard shortcuts list. See [Keyboard shortcuts](keyboard-shortcuts.md). -Git, Fluid and Hidden carry a state dot like the pane toggles; Git's dot is on while the view is open. Search has no dot, because it is an action. Hover any button for a tooltip that explains its current state. +Git, Schema, Fluid and Hidden carry a state dot like the pane toggles; the Git and Schema dots are on while their view is open. Search has no dot, because it is an action. Hover any button for a tooltip that explains its current state. ### Read aloud - **Stop** shows only while Helder reads a file or a selection aloud. Start the reading from the [right-click menu](right-click-menu.md): **Read aloud** on a Markdown file, **Read aloud selection** in the code. @@ -87,6 +89,7 @@ Drag an empty part of the title bar to move the window, as in any macOS app. | `Cmd+L` | Fluid column widths on or off | | `Cmd+.` | Hidden files on or off | | `Cmd+G` | Open or close the Git view | +| `Cmd+D` | Open or close the Schema view (Laravel apps) | | `Cmd+1` / `Cmd+2` / `Cmd+3` | Explorer, File or Claude column on or off | | `?` | Keyboard shortcuts (when no text field has focus) | | `Cmd+O` | Open a folder (same as clicking the project name) | @@ -95,6 +98,7 @@ Drag an empty part of the title bar to move the window, as in any macOS app. - [Window layout](layout.md): what the pane toggles, Fluid and Hidden do to the columns. - [Git](git.md): the view the Git toggle opens. +- [Schema](schema.md): the view the Schema toggle opens. - [Search](search.md): the overlay the Search button opens. - [Keyboard shortcuts](keyboard-shortcuts.md): the overlay the `?` button opens. - [Recent projects](recent-projects.md): opening another folder. diff --git a/docs/index.md b/docs/index.md index 46e4b28..6a425fc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,7 +2,7 @@ - [User guide](guide/index.md): every area of the app at user level, one page each, with ASCII sketches. - [Architecture](architecture.md): layers, folder map, commands, file ownership, gotchas. -- [Design tokens](design/README.md): the visual source of truth (colours, type, geometry, screens). +- [Design](../design/README.md): the visual source of truth (colours, type, geometry, screens), including the full-screen Git view (⌘G) and Schema view (⌘D). - [Behaviour spec](behaviour.md): every panel and interaction. -- [Design handoff v2](design_handoff_helder_app_v2/README.md): the design source of the full-screen Git view (⌘G). +- [schema.json contract](schema.md): the file `helder:schema` writes and the Schema view (⌘D) reads. - [Plak URL scheme](plak.md): the `plak://` contract that the right-click Plak item relies on. diff --git a/docs/schema.md b/docs/schema.md new file mode 100644 index 0000000..2b2ff79 --- /dev/null +++ b/docs/schema.md @@ -0,0 +1,58 @@ +# schema.json contract + +The [Schema view](guide/schema.md) draws a Laravel app's database from `database/helder/schema.json`. The app's own Artisan command, `app/Console/Commands/HelderSchemaCommand.php` (`php artisan helder:schema`), writes that file. Helder does not ship the command: **Generate command** in the view asks Claude to write it from the prompt in `SchemaCommandPrompt.text` (`Sources/HelderCore/Schema/SchemaCommandPrompt.swift`). + +[Docs index](index.md) · Related: [Schema view guide](guide/schema.md), [Behaviour § 4](behaviour.md#4-schema-view) + +## Paths + +| What | Path, relative to the project root | +|---|---| +| Turns the view on | `artisan` (a Laravel app) | +| The command | `app/Console/Commands/HelderSchemaCommand.php` | +| The dump | `database/helder/schema.json` | +| How Helder runs it | `php artisan helder:schema --no-ansi --no-interaction`, with Herd's `php` first, else `php` on `PATH`, 120 s timeout | + +## The file (version 1) + +```json +{ + "version": 1, + "connection": "", + "driver": "getDriverName()>", + "database": "getDatabaseName()>", + "generated_at": "toIso8601String()>", + "tables": [ + { + "name": "
", + "rows": , + "columns": [ ], + "indexes": [ ], + "foreign_keys": [ ] + } + ] +} +``` + +What the command must do besides the JSON: + +- Read the structure only with Laravel's schema builder: `Schema::getTables()`, `getColumns`, `getIndexes`, `getForeignKeys`. +- Skip `migrations`, `jobs`, `job_batches`, `failed_jobs`, `cache`, `cache_locks`, `sessions` and `password_reset_tokens`. +- Count rows with `DB::table($table)->count()`; a failed count is `null`. +- Sort the tables by name, and encode with `JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR`. +- Write a temporary file in `database/helder/` and rename it, so Helder never reads half a file. +- Keep `database/helder/.gitignore` with `*` and `!.gitignore`. +- Print the counts with `twoColumnDetail`, then `Wrote database/helder/schema.json ( KB)`, and return `SUCCESS`; on an error print it with `error()` and return `FAILURE`. + +## How Helder reads it + +`SchemaDump` (`Sources/HelderCore/Schema/SchemaDump.swift`) decodes the file; `SchemaModel` turns it into cards and lines. + +- Decoding is tolerant. A missing or mistyped key gets its default; a table, column or key without a name is skipped. Booleans may come as `true`, `1` or `"1"`. The older prototype shape (no `version`, `driver`, `database` or `rows`) still loads. +- A file that is not a JSON object is an error: the console shows it and a toast reads `Could not read the schema`. +- The connection label is `driver · database`, else the connection name. +- Primary keys come from the primary index, else the auto-increment column. `UQ` marks a column alone in a unique index that is not the primary key. +- One line per foreign key, from its first column to the referenced column (else the target's primary key, else its first row). A key to a table that is not in the dump draws no line. +- The view re-reads the file when its modification date changes, so rewrite it in place; Helder keeps the user's pan, zoom and card positions across a re-read. + +Change the prompt and `SchemaDump` together: the prompt is the only place the contract is written for the agent.