adds schema view and schema generating command
This commit is contained in:
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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 (`<connection> · <database>`), Tables, Columns, Foreign keys. Then print `Wrote database/helder/schema.json (<size> 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": "<connection name>",
|
||||
"driver": "<DB::connection($connection)->getDriverName()>",
|
||||
"database": "<DB::connection($connection)->getDatabaseName()>",
|
||||
"generated_at": "<now()->toIso8601String()>",
|
||||
"tables": [
|
||||
{
|
||||
"name": "<table name>",
|
||||
"rows": <int or null>,
|
||||
"columns": [ <Schema::getColumns($table), unchanged> ],
|
||||
"indexes": [ <Schema::getIndexes($table), unchanged> ],
|
||||
"foreign_keys": [ <Schema::getForeignKeys($table), unchanged> ]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
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
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class HelderSchemaCommand extends Command
|
||||
{
|
||||
private const SKIPPED_TABLES = [
|
||||
'migrations',
|
||||
'jobs',
|
||||
'job_batches',
|
||||
'failed_jobs',
|
||||
'cache',
|
||||
'cache_locks',
|
||||
'sessions',
|
||||
'password_reset_tokens',
|
||||
];
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'helder:schema
|
||||
{--connection= : Database connection to read (default: the default connection)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Dump the database schema for Helder to visualise.';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$connection = (string) ($this->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<string, mixed>
|
||||
*/
|
||||
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<int, array<string, mixed>> $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<string, mixed> $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;
|
||||
}
|
||||
}
|
||||
```
|
||||
"""#
|
||||
}
|
||||
@@ -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<T: Decodable>(_ type: T.Type, _ key: Key) -> [T] {
|
||||
guard let items = try? decodeIfPresent([Failable<T>].self, forKey: key) else { return [] }
|
||||
return items.compactMap(\.value)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Failable<T: Decodable>: 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<String>
|
||||
/// Both ends of every active edge, plus the focus.
|
||||
public var relatedTables: Set<String>
|
||||
/// Cards drawn at 30% opacity.
|
||||
public var dimmedTables: Set<String>
|
||||
/// Cards whose name holds the search query; empty without a query.
|
||||
public var searchMatches: Set<String>
|
||||
/// The foreign-key rows and the rows they reference, of every active edge.
|
||||
public var highlightedColumns: Set<SchemaColumnRef>
|
||||
/// 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<SchemaColumnRef>()
|
||||
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<String>() : Set(names.filter { $0.lowercased().contains(needle) })
|
||||
let dimsAll = focus != nil || hoveredColumn != nil
|
||||
let dimmed: Set<String> = 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)"
|
||||
}
|
||||
}
|
||||
@@ -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<String>()
|
||||
|
||||
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..<laneCount {
|
||||
let ordered: [String]
|
||||
if lane == 0 {
|
||||
ordered = members[lane].sorted()
|
||||
} else {
|
||||
let keys = Dictionary(uniqueKeysWithValues: members[lane].map { name in
|
||||
let shares = model.edges
|
||||
.filter { $0.from == name && $0.to != name && (lanes[$0.to] ?? lane) < lane }
|
||||
.compactMap { relative[$0.to] }
|
||||
return (name, shares.isEmpty ? 0.5 : shares.reduce(0, +) / Double(shares.count))
|
||||
})
|
||||
ordered = members[lane].sorted { a, b in
|
||||
keys[a]! == keys[b]! ? a < b : keys[a]! < keys[b]!
|
||||
}
|
||||
}
|
||||
var y = 0.0
|
||||
var centres: [(String, Double)] = []
|
||||
for name in ordered {
|
||||
let height = tables[name]?.cardHeight ?? SchemaGeometry.cardHeight(columns: 0)
|
||||
offset[name] = y
|
||||
centres.append((name, y + height / 2))
|
||||
y += height + SchemaMetrics.cardGap
|
||||
}
|
||||
laneHeight[lane] = y
|
||||
for (name, centre) in centres { relative[name] = y > 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 }
|
||||
}
|
||||
@@ -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<String>()
|
||||
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<String>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)) }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -31,7 +31,7 @@ struct GitTopBar: View {
|
||||
}
|
||||
|
||||
/// A 28pt bordered button with an icon, a label and an amber mono count or key hint.
|
||||
private struct GitBarButton: View {
|
||||
struct GitBarButton: View {
|
||||
let icon: GitIcon
|
||||
let label: String
|
||||
let trailing: String?
|
||||
|
||||
@@ -38,6 +38,10 @@ public enum ShortcutCatalog {
|
||||
ShortcutRow(keys: ["⌘", "↵"], label: "Commit the staged files"),
|
||||
ShortcutRow(keys: ["⌘", "P"], label: "Push the current branch"),
|
||||
]),
|
||||
ShortcutGroup(title: "Schema", rows: [
|
||||
ShortcutRow(keys: ["⌘", "D"], label: "Open or close Schema (Laravel apps)"),
|
||||
ShortcutRow(keys: ["↵"], label: "Table search: centre the first match"),
|
||||
]),
|
||||
ShortcutGroup(title: "File", rows: [
|
||||
ShortcutRow(keys: ["⌘", "S"], label: "Save this file"),
|
||||
ShortcutRow(keys: ["⌘", "M"], label: "Markdown: code or rendered preview"),
|
||||
@@ -49,12 +53,12 @@ public enum ShortcutCatalog {
|
||||
ShortcutRow(keys: ["⌘", "+"], label: "Zoom in"),
|
||||
ShortcutRow(keys: ["⌘", "−"], label: "Zoom out"),
|
||||
ShortcutRow(keys: ["⌘", "0"], label: "Actual size"),
|
||||
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Git view"),
|
||||
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Schema selection or view, then the Git view"),
|
||||
]),
|
||||
]
|
||||
}
|
||||
|
||||
/// `?`: the keyboard reference, grouped NAVIGATE / AGENT / GIT / FILE.
|
||||
/// `?`: the keyboard reference, grouped NAVIGATE / AGENT / GIT / SCHEMA / FILE.
|
||||
struct ShortcutsOverlay: View {
|
||||
var onClose: () -> Void
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import AppKit
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The diagram: relationship lines under the cards, panned and zoomed by the store's viewport.
|
||||
/// Each card is laid out at 100% and scaled into its on-screen frame, so its click and pointer area stay unscaled.
|
||||
struct SchemaCanvas: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SchemaStore
|
||||
let schema: SchemaModel
|
||||
|
||||
/// Where a background drag started; nil between drags.
|
||||
@State private var pan: (start: SchemaViewport, moved: Bool)?
|
||||
/// The card being pressed and where it stood.
|
||||
@State private var press: (name: String, origin: SchemaPoint, moved: Bool)?
|
||||
|
||||
private static let space = "schemaCanvas"
|
||||
/// A press that moves less than this is a click.
|
||||
private static let dragThreshold = 4.0
|
||||
|
||||
var body: some View {
|
||||
let highlight = store.highlight ?? SchemaHighlight(model: schema, hovered: nil, selected: nil, hoveredColumn: nil, query: "")
|
||||
let view = store.viewport
|
||||
GeometryReader { proxy in
|
||||
ZStack(alignment: .topLeading) {
|
||||
Palette.editor
|
||||
.contentShape(Rectangle())
|
||||
.gesture(backgroundDrag)
|
||||
SchemaEdges(schema: schema, positions: store.positions, viewport: view, highlight: highlight)
|
||||
.allowsHitTesting(false)
|
||||
ForEach(schema.tables, id: \.name) { table in
|
||||
if let position = store.positions[table.name] {
|
||||
card(table, at: position, view: view, highlight: highlight)
|
||||
}
|
||||
}
|
||||
Text("drag to pan · ⌘ scroll to zoom · hover a table or a key to trace it · click to inspect")
|
||||
.typeRole(Typography.meta)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.lineLimit(1)
|
||||
.allowsHitTesting(false)
|
||||
.padding(SchemaViewMetrics.canvasInset)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
|
||||
SchemaZoomControl(store: store)
|
||||
.padding(SchemaViewMetrics.canvasInset)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
|
||||
}
|
||||
.coordinateSpace(name: Self.space)
|
||||
.clipped()
|
||||
.background(SchemaScrollCatcher(
|
||||
isActive: !model.overlay.isPresented,
|
||||
onPan: { dx, dy in store.pan(dx: dx, dy: dy) },
|
||||
onZoom: { factor, point in store.zoom(by: factor, around: SchemaPoint(x: point.x, y: point.y)) }
|
||||
))
|
||||
.onAppear { store.setCanvasSize(SchemaSize(width: proxy.size.width, height: proxy.size.height)) }
|
||||
.onChange(of: proxy.size) { _, size in store.setCanvasSize(SchemaSize(width: size.width, height: size.height)) }
|
||||
}
|
||||
}
|
||||
|
||||
private func card(_ table: SchemaTable, at position: SchemaPoint, view: SchemaViewport, highlight: SchemaHighlight) -> some View {
|
||||
let k = view.scale
|
||||
let width = SchemaMetrics.cardWidth * k
|
||||
let height = table.cardHeight * k
|
||||
return SchemaTableCard(table: table, highlight: highlight, isSelected: store.selected == table.name) { id, inside in
|
||||
if inside {
|
||||
store.hoverColumn(id)
|
||||
} else if store.hoveredColumn == id {
|
||||
store.hoverColumn(nil)
|
||||
}
|
||||
}
|
||||
.scaleEffect(k, anchor: .topLeading)
|
||||
.frame(width: width, height: height, alignment: .topLeading)
|
||||
.contentShape(Rectangle())
|
||||
.pointerHand()
|
||||
.onHover { inside in
|
||||
if inside {
|
||||
store.hover(table.name)
|
||||
} else if store.hovered == table.name {
|
||||
store.hover(nil)
|
||||
}
|
||||
}
|
||||
.gesture(cardDrag(table.name, origin: position, scale: k))
|
||||
.position(x: position.x * k + view.x + width / 2, y: position.y * k + view.y + height / 2)
|
||||
}
|
||||
|
||||
/// Drags the card past a 4pt threshold; a shorter press selects it, or deselects it when it already was.
|
||||
private func cardDrag(_ name: String, origin: SchemaPoint, scale: Double) -> some Gesture {
|
||||
DragGesture(minimumDistance: 0, coordinateSpace: .named(Self.space))
|
||||
.onChanged { value in
|
||||
var current = press.flatMap { $0.name == name ? $0 : nil } ?? (name: name, origin: origin, moved: false)
|
||||
let dx = value.translation.width, dy = value.translation.height
|
||||
if !current.moved && abs(dx) + abs(dy) < Self.dragThreshold {
|
||||
press = current
|
||||
return
|
||||
}
|
||||
current.moved = true
|
||||
press = current
|
||||
store.moveTable(name, to: SchemaPoint(x: (current.origin.x + dx / scale).rounded(),
|
||||
y: (current.origin.y + dy / scale).rounded()))
|
||||
}
|
||||
.onEnded { _ in
|
||||
let moved = press?.moved ?? false
|
||||
press = nil
|
||||
if moved { store.endDrag() } else { store.toggleSelection(name) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Pans past a 4pt threshold; a click on the empty canvas deselects.
|
||||
private var backgroundDrag: some Gesture {
|
||||
DragGesture(minimumDistance: 0, coordinateSpace: .named(Self.space))
|
||||
.onChanged { value in
|
||||
var current = pan ?? (start: store.viewport, moved: false)
|
||||
let dx = value.translation.width, dy = value.translation.height
|
||||
if !current.moved && abs(dx) + abs(dy) < Self.dragThreshold {
|
||||
pan = current
|
||||
return
|
||||
}
|
||||
current.moved = true
|
||||
pan = current
|
||||
var next = current.start
|
||||
next.x += dx
|
||||
next.y += dy
|
||||
store.setViewport(next)
|
||||
}
|
||||
.onEnded { _ in
|
||||
let moved = pan?.moved ?? false
|
||||
pan = nil
|
||||
if !moved { store.clearSelection() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One cubic line per foreign key, hollow at the key end and filled at the referenced end; active lines on top.
|
||||
private struct SchemaEdges: View {
|
||||
let schema: SchemaModel
|
||||
let positions: [String: SchemaPoint]
|
||||
let viewport: SchemaViewport
|
||||
let highlight: SchemaHighlight
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, _ in
|
||||
let k = viewport.scale
|
||||
func screen(_ p: SchemaPoint) -> CGPoint { CGPoint(x: p.x * k + viewport.x, y: p.y * k + viewport.y) }
|
||||
for edge in highlight.drawingOrder(schema.edges) {
|
||||
guard let geometry = SchemaGeometry.edgePath(edge, positions: positions) else { continue }
|
||||
let active = highlight.isActive(edge)
|
||||
let color = active ? Palette.amber : highlight.linesRecede ? Palette.raised : Palette.text5
|
||||
let start = screen(geometry.start), end = screen(geometry.end)
|
||||
var line = Path()
|
||||
line.move(to: start)
|
||||
line.addCurve(to: end, control1: screen(geometry.control1), control2: screen(geometry.control2))
|
||||
context.stroke(line, with: .color(color), lineWidth: (active ? 1.75 : 1.25) * k)
|
||||
let r = SchemaMetrics.endRadius * k
|
||||
let hollow = Path(ellipseIn: CGRect(x: start.x - r, y: start.y - r, width: r * 2, height: r * 2))
|
||||
context.fill(hollow, with: .color(Palette.editor))
|
||||
context.stroke(hollow, with: .color(color), lineWidth: 1.5 * k)
|
||||
context.fill(Path(ellipseIn: CGRect(x: end.x - r, y: end.y - r, width: r * 2, height: r * 2)), with: .color(color))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `−` · zoom % · `+` · Fit, bottom right of the canvas.
|
||||
private struct SchemaZoomControl: View {
|
||||
let store: SchemaStore
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
ZoomButton(tip: "Zoom out") { store.zoom(by: 1 / SchemaMetrics.zoomStep) } label: {
|
||||
GitIconView(icon: .minus, size: 14).frame(width: SchemaViewMetrics.zoomButton)
|
||||
}
|
||||
Text(store.viewport.percentLabel)
|
||||
.typeRole(Typography.schemaZoom)
|
||||
.foregroundStyle(Palette.textMuted)
|
||||
.frame(width: SchemaViewMetrics.zoomLabel, height: SchemaViewMetrics.zoomControl)
|
||||
.hairline(.leading)
|
||||
.hairline(.trailing)
|
||||
ZoomButton(tip: "Zoom in") { store.zoom(by: SchemaMetrics.zoomStep) } label: {
|
||||
GitIconView(icon: .plus, size: 14).frame(width: SchemaViewMetrics.zoomButton)
|
||||
}
|
||||
ZoomButton(tip: "Fit the whole schema") { store.fit() } label: {
|
||||
Text("Fit").typeRole(Typography.button).padding(.horizontal, 11)
|
||||
}
|
||||
.hairline(.leading)
|
||||
}
|
||||
.fixedSize()
|
||||
.background(Palette.panel)
|
||||
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
|
||||
}
|
||||
}
|
||||
|
||||
private struct ZoomButton<Label: View>: View {
|
||||
let tip: String
|
||||
let action: () -> Void
|
||||
@ViewBuilder let label: Label
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
label
|
||||
.foregroundStyle(isHovered ? Palette.text1 : Palette.text3)
|
||||
.frame(height: SchemaViewMetrics.zoomControl)
|
||||
.background(isHovered ? Palette.raised : .clear)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
.tip(tip, edge: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns scroll and pinch over the canvas into pan and zoom: plain scroll pans, ⌘ or Ctrl scroll and pinch zoom
|
||||
/// around the pointer. A local monitor, because the cards on top would otherwise receive the events.
|
||||
private struct SchemaScrollCatcher: NSViewRepresentable {
|
||||
let isActive: Bool
|
||||
let onPan: (_ dx: Double, _ dy: Double) -> Void
|
||||
let onZoom: (_ factor: Double, _ at: CGPoint) -> Void
|
||||
|
||||
func makeNSView(context: Context) -> CatcherView {
|
||||
CatcherView()
|
||||
}
|
||||
|
||||
func updateNSView(_ view: CatcherView, context: Context) {
|
||||
view.isActive = isActive
|
||||
view.onPan = onPan
|
||||
view.onZoom = onZoom
|
||||
}
|
||||
|
||||
static func dismantleNSView(_ view: CatcherView, coordinator: ()) {
|
||||
view.removeMonitor()
|
||||
}
|
||||
|
||||
final class CatcherView: NSView {
|
||||
var isActive = true
|
||||
var onPan: (Double, Double) -> Void = { _, _ in }
|
||||
var onZoom: (Double, CGPoint) -> Void = { _, _ in }
|
||||
private var monitor: Any?
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
if window == nil {
|
||||
removeMonitor()
|
||||
} else if monitor == nil {
|
||||
monitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .magnify]) { [weak self] event in
|
||||
MainActor.assumeIsolated { self?.handle(event) ?? false } ? nil : event
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func removeMonitor() {
|
||||
if let monitor { NSEvent.removeMonitor(monitor) }
|
||||
monitor = nil
|
||||
}
|
||||
|
||||
/// True when the event was over the canvas and moved it.
|
||||
private func handle(_ event: NSEvent) -> Bool {
|
||||
guard isActive, let window, event.window === window else { return false }
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
guard bounds.contains(point) else { return false }
|
||||
switch event.type {
|
||||
case .magnify:
|
||||
onZoom(1 + event.magnification, point)
|
||||
case .scrollWheel:
|
||||
// A mouse wheel reports lines, a trackpad points; both feel alike after this.
|
||||
let unit = event.hasPreciseScrollingDeltas ? 1.0 : 10.0
|
||||
let dx = event.scrollingDeltaX * unit, dy = event.scrollingDeltaY * unit
|
||||
if event.modifierFlags.contains(.command) || event.modifierFlags.contains(.control) {
|
||||
onZoom(exp(dy * 0.01), point)
|
||||
} else {
|
||||
onPan(dx, dy)
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// `[ console ] artisan`: the last runs of `helder:schema`, following the newest line; the chevron hides it until the next run.
|
||||
struct SchemaConsolePanel: View {
|
||||
let store: SchemaStore
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 12) {
|
||||
Text("[ console ] artisan").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
|
||||
Spacer(minLength: 0)
|
||||
SchemaIconButton(icon: .chevronDown, tip: "Hide console") { store.hideConsole() }
|
||||
}
|
||||
.padding(.leading, 16)
|
||||
.padding(.trailing, 12)
|
||||
.frame(height: SchemaViewMetrics.consoleHeader)
|
||||
ConsoleLogView(entries: store.lines.map { ConsoleLogLine(id: $0.id, text: $0.line.text, color: Palette.artisan($0.line.kind)) })
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
.frame(height: SchemaViewMetrics.console)
|
||||
.background(Palette.panel)
|
||||
.hairline(.top)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The 320pt panel for the selected table: its columns, what it belongs to and has many, and the footer actions.
|
||||
struct SchemaDetailPanel: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SchemaStore
|
||||
let schema: SchemaModel
|
||||
let table: SchemaTable
|
||||
|
||||
var body: some View {
|
||||
let outgoing = schema.outgoing(from: table.name)
|
||||
let incoming = schema.incoming(to: table.name)
|
||||
VStack(spacing: 0) {
|
||||
header
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
columns
|
||||
if !outgoing.isEmpty {
|
||||
relations("[ belongs to ]", arrow: "→", rows: outgoing.map { ($0.id, $0.to, $0.column) })
|
||||
}
|
||||
if !incoming.isEmpty {
|
||||
relations("[ has many ]", arrow: "←", rows: incoming.map { ($0.id, $0.from, $0.column) })
|
||||
}
|
||||
if outgoing.isEmpty && incoming.isEmpty {
|
||||
Text("— No foreign keys in or out.")
|
||||
.typeRole(Typography.gitEmpty)
|
||||
.foregroundStyle(Palette.textMuted)
|
||||
.padding(.horizontal, 16)
|
||||
}
|
||||
}
|
||||
.padding(.top, 14)
|
||||
.padding(.bottom, 20)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
HStack(spacing: 8) {
|
||||
SchemaOutlineButton(label: "Pass on to Claude", fills: true, padding: 8) { model.perform(.passSchemaTable(table.name)) }
|
||||
SchemaOutlineButton(label: "Copy name", fills: true, padding: 8) { model.perform(.copySchemaTableName(table.name)) }
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 12)
|
||||
.hairline(.top)
|
||||
}
|
||||
.background(Palette.panel)
|
||||
.hairline(.leading)
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 10) {
|
||||
Text(table.name)
|
||||
.typeRole(Typography.schemaDetailName)
|
||||
.foregroundStyle(Palette.text1)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
if table.rows != nil {
|
||||
Text(table.rowsLabel + " rows").typeRole(Typography.meta).foregroundStyle(Palette.textMuted).fixedSize()
|
||||
}
|
||||
SchemaIconButton(icon: .x, tip: "Close (Esc)") { store.clearSelection() }
|
||||
}
|
||||
.padding(.leading, 16)
|
||||
.padding(.trailing, 10)
|
||||
.frame(height: SchemaViewMetrics.detailHeader)
|
||||
.hairline(.bottom)
|
||||
}
|
||||
|
||||
private var columns: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
sectionLabel("[ columns ] \(table.columns.count)")
|
||||
ForEach(Array(table.columns.enumerated()), id: \.offset) { _, column in
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 10) {
|
||||
Text(column.name)
|
||||
.typeRole(Typography.schemaDetailColumn)
|
||||
.foregroundStyle(Palette.text2)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(column.type).typeRole(Typography.schemaDetailMeta).foregroundStyle(Palette.textMuted).lineLimit(1).fixedSize()
|
||||
}
|
||||
Text(column.flags)
|
||||
.typeRole(Typography.schemaDetailMeta)
|
||||
.foregroundStyle(column.isPrimary || column.isForeign ? Palette.amberSoft : Palette.text4)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 7)
|
||||
.hairline(.top)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func relations(_ label: String, arrow: String, rows: [(id: String, table: String, via: String)]) -> some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
sectionLabel(label)
|
||||
ForEach(rows, id: \.id) { row in
|
||||
SchemaRelationRow(arrow: arrow, table: row.table, via: row.via,
|
||||
onHover: { inside in hover(row.table, inside) },
|
||||
onClick: { store.centre(row.table) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func sectionLabel(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.typeRole(Typography.panelLabel)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.bottom, 8)
|
||||
}
|
||||
|
||||
private func hover(_ name: String, _ inside: Bool) {
|
||||
if inside {
|
||||
store.hover(name)
|
||||
} else if store.hovered == name {
|
||||
store.hover(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `→ users … via user_id`: hover traces the table on the canvas, a click selects and centres it.
|
||||
private struct SchemaRelationRow: View {
|
||||
let arrow: String
|
||||
let table: String
|
||||
let via: String
|
||||
let onHover: (Bool) -> Void
|
||||
let onClick: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: onClick) {
|
||||
HStack(spacing: 8) {
|
||||
Text(arrow).foregroundStyle(Palette.amber)
|
||||
Text(table).foregroundStyle(Palette.text1).lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
Text("via " + via).foregroundStyle(Palette.textMuted).lineLimit(1)
|
||||
}
|
||||
.typeRole(Typography.path)
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
.background(isHovered ? Palette.gitRowHover : .clear)
|
||||
.hairline(.top)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.onHover { inside in
|
||||
isHovered = inside
|
||||
onHover(inside)
|
||||
}
|
||||
.animation(Metrics.colorTransition, value: isHovered)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The command exists but has not written `database/helder/schema.json` yet.
|
||||
struct SchemaEmptyState: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SchemaStore
|
||||
|
||||
var body: some View {
|
||||
SchemaStateBlock(label: "[ no dump yet ]",
|
||||
message: Text("— Helder draws the schema from ") + schemaMono(SchemaPaths.dumpFile)
|
||||
+ Text(". Run the command to write it.")) {
|
||||
HStack(spacing: 14) {
|
||||
SchemaPrimaryButton(label: store.runLabel) { model.perform(.runSchemaDump) }
|
||||
Text("$ " + SchemaPaths.commandLine).typeRole(Typography.path).foregroundStyle(Palette.text4).lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project is a Laravel app without `HelderSchemaCommand.php`: the prompt that asks Claude to write it.
|
||||
struct SchemaCommandMissing: View {
|
||||
let model: WorkspaceModel
|
||||
|
||||
var body: some View {
|
||||
SchemaStateBlock(label: "[ no command yet ]",
|
||||
message: Text("— Helder draws the schema from ") + schemaMono(SchemaPaths.dumpFile)
|
||||
+ Text(". The Artisan command ") + schemaMono(SchemaPaths.commandFile)
|
||||
+ Text(" writes it, and this app does not have it yet.")) {
|
||||
HStack(spacing: 14) {
|
||||
SchemaPrimaryButton(label: "Generate command", icon: .sparkle) { model.perform(.generateSchemaCommand) }
|
||||
SchemaOutlineButton(label: "Copy prompt", height: SchemaViewMetrics.primaryButton) { model.perform(.copySchemaPrompt) }
|
||||
}
|
||||
ScrollView {
|
||||
Text(SchemaCommandPrompt.text)
|
||||
.typeRole(Typography.console)
|
||||
.foregroundStyle(Palette.textMuted)
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(12)
|
||||
.background(PointerTextRegion())
|
||||
}
|
||||
.frame(maxHeight: SchemaViewMetrics.promptPreview)
|
||||
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A path inside the state copy: mono at the copy's size, in text-1.
|
||||
private func schemaMono(_ text: String) -> Text {
|
||||
Text(text).font(Typography.schemaBodyMono.font).foregroundColor(Palette.text1)
|
||||
}
|
||||
|
||||
/// The centred block both states share: an amber label, Sans 15/1.6 copy, then the actions; at most 440 wide, 16 apart.
|
||||
private struct SchemaStateBlock<Content: View>: View {
|
||||
let label: String
|
||||
let message: Text
|
||||
@ViewBuilder let content: Content
|
||||
|
||||
init(label: String, message: Text, @ViewBuilder content: () -> Content) {
|
||||
self.label = label
|
||||
self.message = message
|
||||
self.content = content()
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text(label).typeRole(Typography.gitLabel).foregroundStyle(Palette.amber)
|
||||
message
|
||||
.typeRole(Typography.schemaBody)
|
||||
.foregroundStyle(Palette.text3)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
content
|
||||
}
|
||||
.frame(maxWidth: SchemaViewMetrics.emptyStateWidth, alignment: .leading)
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Palette.editor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// One table on the canvas at 100%: a 33pt header, then a 22pt row per column. The line geometry depends on these sizes.
|
||||
struct SchemaTableCard: View {
|
||||
let table: SchemaTable
|
||||
let highlight: SchemaHighlight
|
||||
let isSelected: Bool
|
||||
let onHoverColumn: (_ id: String, _ inside: Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
let isFocus = highlight.focus == table.name
|
||||
let lit = isFocus || isSelected
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 8) {
|
||||
Text(table.name)
|
||||
.typeRole(Typography.schemaCardName)
|
||||
.foregroundStyle(lit ? Palette.text1 : Palette.text2)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(table.rowsLabel).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.frame(height: SchemaMetrics.headerHeight - Metrics.hairline)
|
||||
.background(lit ? Palette.amberTint : Palette.panel)
|
||||
Hairline()
|
||||
ForEach(Array(table.columns.enumerated()), id: \.offset) { _, column in
|
||||
row(column)
|
||||
}
|
||||
}
|
||||
.padding(Metrics.hairline)
|
||||
.frame(width: SchemaMetrics.cardWidth, height: table.cardHeight, alignment: .top)
|
||||
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
|
||||
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusMedium))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(border(isFocus: isFocus), lineWidth: Metrics.hairline))
|
||||
.opacity(highlight.opacity(of: table.name))
|
||||
.animation(Metrics.colorTransition, value: highlight)
|
||||
.animation(Metrics.colorTransition, value: isSelected)
|
||||
}
|
||||
|
||||
private func row(_ column: SchemaColumn) -> some View {
|
||||
let lit = highlight.isHighlighted(table: table.name, column: column.name)
|
||||
let isKey = column.isPrimary || column.isForeign
|
||||
return HStack(spacing: 6) {
|
||||
Text(column.keyLabel)
|
||||
.typeRole(Typography.schemaKey)
|
||||
.foregroundStyle(lit ? Palette.amber : column.isPrimary ? Palette.amberSoft : Palette.textMuted)
|
||||
.frame(width: 20, alignment: .leading)
|
||||
Text(column.name)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(lit ? Palette.text1 : isKey ? Palette.text2 : Palette.text3)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(column.displayType).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.frame(height: SchemaMetrics.rowHeight)
|
||||
.background(lit ? Palette.amberTint : .clear)
|
||||
.onHover { inside in
|
||||
guard column.isForeign else { return }
|
||||
onHoverColumn(SchemaColumnRef(table: table.name, column: column.name).id, inside)
|
||||
}
|
||||
}
|
||||
|
||||
/// Focus amber, a selection under another hover amber-deep, related text-4, a search match amber-soft.
|
||||
private func border(isFocus: Bool) -> Color {
|
||||
if isFocus { return Palette.amber }
|
||||
if isSelected { return Palette.amberDeep }
|
||||
if highlight.relatedTables.contains(table.name) { return Palette.text4 }
|
||||
if highlight.searchMatches.contains(table.name) { return Palette.amberSoft }
|
||||
return Palette.raised
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The 240pt list left of the canvas: the table search, `[ tables ] N`, and one row per matching table.
|
||||
struct SchemaTableList: View {
|
||||
let store: SchemaStore
|
||||
let schema: SchemaModel
|
||||
|
||||
var body: some View {
|
||||
let highlight = store.highlight
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack(spacing: 8) {
|
||||
GitIconView(icon: .search, size: 14).foregroundStyle(Palette.textMuted)
|
||||
ConsoleInputField(
|
||||
text: Binding(get: { store.query }, set: { store.query = $0 }),
|
||||
placeholder: "Find a table",
|
||||
role: Typography.gitPath,
|
||||
makeEditor: { SchemaSearchFieldEditor() },
|
||||
onSubmit: { store.centreFirstMatch() }
|
||||
)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(height: 20)
|
||||
}
|
||||
.padding(.leading, 14)
|
||||
.padding(.trailing, 12)
|
||||
.frame(height: SchemaViewMetrics.searchRow)
|
||||
.hairline(.bottom)
|
||||
Text(SchemaSearch.listLabel(schema, query: store.query))
|
||||
.typeRole(Typography.panelLabel)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.lineLimit(1)
|
||||
.padding(.horizontal, 14)
|
||||
.frame(height: SchemaViewMetrics.listLabelRow)
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 0) {
|
||||
ForEach(store.listedTables, id: \.name) { table in
|
||||
SchemaTableRow(table: table,
|
||||
isSelected: store.selected == table.name,
|
||||
isFocus: highlight?.focus == table.name,
|
||||
isRelated: highlight.map { $0.linesRecede && $0.relatedTables.contains(table.name) } ?? false,
|
||||
onHover: { inside in hover(table.name, inside) },
|
||||
onClick: { store.centre(table.name) })
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
}
|
||||
.background(Palette.panel)
|
||||
.hairline(.trailing)
|
||||
}
|
||||
|
||||
private func hover(_ name: String, _ inside: Bool) {
|
||||
if inside {
|
||||
store.hover(name)
|
||||
} else if store.hovered == name {
|
||||
store.hover(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One table: its name and row count, the amber bar while selected.
|
||||
private struct SchemaTableRow: View {
|
||||
let table: SchemaTable
|
||||
let isSelected: Bool
|
||||
let isFocus: Bool
|
||||
let isRelated: Bool
|
||||
let onHover: (Bool) -> Void
|
||||
let onClick: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: onClick) {
|
||||
HStack(spacing: 8) {
|
||||
Text(table.name)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(isSelected || isFocus || isHovered ? Palette.text1 : isRelated ? Palette.text2 : Palette.text3)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(table.rowsLabel).typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).fixedSize()
|
||||
}
|
||||
.padding(.leading, 11)
|
||||
.padding(.trailing, 14)
|
||||
.frame(height: SchemaViewMetrics.listRow)
|
||||
.background(background)
|
||||
.overlay(alignment: .leading) {
|
||||
Rectangle().fill(isSelected ? Palette.amber : .clear).frame(width: SchemaViewMetrics.accentBar)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.onHover { inside in
|
||||
isHovered = inside
|
||||
onHover(inside)
|
||||
}
|
||||
.animation(Metrics.colorTransition, value: isHovered)
|
||||
}
|
||||
|
||||
private var background: Color {
|
||||
if isSelected { return Palette.amberTint }
|
||||
return isFocus || isHovered ? Palette.gitRowHover : .clear
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// `[ schema ]`, the connection and the dump's meta, then the command path, Run and Close.
|
||||
struct SchemaTopBar: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SchemaStore
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 14) {
|
||||
Text("[ schema ]").typeRole(Typography.gitLabel).foregroundStyle(Palette.textMuted).fixedSize()
|
||||
if let schema = store.model {
|
||||
HStack(spacing: 6) {
|
||||
GitIconView(icon: .database, size: 13)
|
||||
Text(schema.connectionLabel).typeRole(Typography.branch).lineLimit(1)
|
||||
}
|
||||
.foregroundStyle(Palette.amber)
|
||||
.fixedSize()
|
||||
}
|
||||
Text(store.metaLabel)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(Palette.textMuted)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
Spacer(minLength: 0)
|
||||
if store.hasCommand {
|
||||
CommandPathButton { model.perform(.openSchemaCommandFile) }
|
||||
}
|
||||
SchemaPrimaryButton(label: store.runLabel, icon: .terminal, height: SchemaViewMetrics.topButton,
|
||||
role: Typography.commitButton, padding: 12) {
|
||||
model.perform(.runSchemaDump)
|
||||
}
|
||||
.disabledLook(!store.hasCommand)
|
||||
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘D") { model.perform(.closeSchemaView) }
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.frame(height: SchemaViewMetrics.topBar)
|
||||
.background(Palette.panel)
|
||||
.hairline(.bottom)
|
||||
}
|
||||
}
|
||||
|
||||
/// `app/Console/Commands/HelderSchemaCommand.php` as a mono text button.
|
||||
private struct CommandPathButton: View {
|
||||
let action: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
Text(SchemaPaths.commandFile)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(isHovered ? Palette.text1 : Palette.textMuted)
|
||||
.lineLimit(1)
|
||||
.padding(.vertical, 4)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.fixedSize()
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
.tip("Open the command in the editor", edge: .trailing)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// ⌘D: the full-screen Schema view over the title bar, the columns and the status bar.
|
||||
struct SchemaView: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SchemaStore
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
SchemaTopBar(model: model, store: store)
|
||||
HStack(spacing: 0) {
|
||||
switch store.body {
|
||||
case .diagram:
|
||||
if let schema = store.model {
|
||||
SchemaTableList(store: store, schema: schema)
|
||||
.frame(width: SchemaViewMetrics.tableList)
|
||||
SchemaCanvas(model: model, store: store, schema: schema)
|
||||
if let table = store.selectedTable {
|
||||
SchemaDetailPanel(model: model, store: store, schema: schema, table: table)
|
||||
.frame(width: SchemaViewMetrics.detailPanel)
|
||||
}
|
||||
}
|
||||
case .noDump:
|
||||
SchemaEmptyState(model: model, store: store)
|
||||
case .commandMissing:
|
||||
SchemaCommandMissing(model: model)
|
||||
case .loading:
|
||||
Color.clear
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity)
|
||||
if store.isConsoleOpen && !store.lines.isEmpty && store.body != .commandMissing {
|
||||
SchemaConsolePanel(store: store)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Palette.editor)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
}
|
||||
|
||||
/// The Schema view's fixed sizes, from the design handoff.
|
||||
enum SchemaViewMetrics {
|
||||
static let topBar: CGFloat = 44
|
||||
static let topButton: CGFloat = 28
|
||||
static let tableList: CGFloat = 240
|
||||
static let searchRow: CGFloat = 44
|
||||
static let listLabelRow: CGFloat = 34
|
||||
static let listRow: CGFloat = 30
|
||||
static let accentBar: CGFloat = 3
|
||||
static let detailPanel: CGFloat = 320
|
||||
static let detailHeader: CGFloat = 44
|
||||
static let footerButton: CGFloat = 30
|
||||
static let console: CGFloat = 150
|
||||
static let consoleHeader: CGFloat = 32
|
||||
static let primaryButton: CGFloat = 36
|
||||
static let emptyStateWidth: CGFloat = 440
|
||||
static let promptPreview: CGFloat = 240
|
||||
static let zoomControl: CGFloat = 28
|
||||
static let zoomButton: CGFloat = 30
|
||||
static let zoomLabel: CGFloat = 52
|
||||
static let canvasInset: CGFloat = 14
|
||||
}
|
||||
|
||||
/// The amber primary of the empty and command-missing states: 36pt, Sans 600 13, amber-deep on hover.
|
||||
struct SchemaPrimaryButton: View {
|
||||
let label: String
|
||||
var icon: GitIcon?
|
||||
var height: CGFloat = SchemaViewMetrics.primaryButton
|
||||
var role = Typography.gitCommitButton
|
||||
var padding: CGFloat = 16
|
||||
let action: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
HStack(spacing: 7) {
|
||||
if let icon { GitIconView(icon: icon, size: 14) }
|
||||
Text(label).typeRole(role).lineLimit(1)
|
||||
}
|
||||
.foregroundStyle(Palette.badgeText)
|
||||
.padding(.horizontal, padding)
|
||||
.frame(height: height)
|
||||
.background(isHovered ? Palette.amberDeep : Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.fixedSize()
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline button of the detail footer and the command-missing state: text-5 border, raised fill on hover.
|
||||
struct SchemaOutlineButton: View {
|
||||
let label: String
|
||||
var height: CGFloat = SchemaViewMetrics.footerButton
|
||||
var fills = false
|
||||
var padding: CGFloat = 16
|
||||
let action: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
Text(label)
|
||||
.typeRole(Typography.button)
|
||||
.lineLimit(1)
|
||||
.foregroundStyle(isHovered ? Palette.text1 : Palette.text3)
|
||||
.padding(.horizontal, padding)
|
||||
.frame(maxWidth: fills ? .infinity : nil)
|
||||
.frame(height: height)
|
||||
.background(isHovered ? Palette.raised : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall)
|
||||
.strokeBorder(isHovered ? Palette.text4 : Palette.text5, lineWidth: Metrics.hairline))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.fixedSize(horizontal: !fills, vertical: false)
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
}
|
||||
}
|
||||
|
||||
/// A borderless icon button: text-muted, text-1 on hover.
|
||||
struct SchemaIconButton: View {
|
||||
let icon: GitIcon
|
||||
let tip: String
|
||||
let action: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
GitIconView(icon: icon, size: 14)
|
||||
.foregroundStyle(isHovered ? Palette.text1 : Palette.textMuted)
|
||||
.padding(4)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
.tip(tip, edge: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
/// The table search's field editor; the key router tells it apart from the other fields by its class.
|
||||
final class SchemaSearchFieldEditor: PointerBoundTextView {}
|
||||
@@ -76,6 +76,10 @@ public enum Command: Equatable, Sendable {
|
||||
case toggleGit
|
||||
/// Esc with the Git view open and no overlay over it.
|
||||
case closeGitView
|
||||
/// ⌘D and the title bar's Schema button, in a Laravel app: opens or closes the full-screen Schema view.
|
||||
case toggleSchemaView
|
||||
/// Esc with nothing selected in the Schema view, and its Close button.
|
||||
case closeSchemaView
|
||||
/// ⌘1–⌘3 and the title-bar pane toggles: shows or hides one column.
|
||||
case togglePane(Panel)
|
||||
/// ⌘L
|
||||
@@ -126,6 +130,23 @@ public enum Command: Equatable, Sendable {
|
||||
/// ⌘C without a selection, outside a terminal: opens the Git view on its message field.
|
||||
case focusCommitMessage
|
||||
|
||||
// MARK: Schema view
|
||||
|
||||
/// The Run button: `php artisan helder:schema`, then the dump is re-read.
|
||||
case runSchemaDump
|
||||
/// Closes the view and pastes the prompt that writes `HelderSchemaCommand.php` into the agent, unsent.
|
||||
case generateSchemaCommand
|
||||
case copySchemaPrompt
|
||||
/// The detail panel's Pass on to Claude: `@schema:<table>` into the agent.
|
||||
case passSchemaTable(String)
|
||||
case copySchemaTableName(String)
|
||||
/// The top bar's command path: closes the view and opens the command in the editor.
|
||||
case openSchemaCommandFile
|
||||
/// Esc with a table selected.
|
||||
case clearSchemaSelection
|
||||
/// Esc in the table search while it holds text.
|
||||
case clearSchemaSearch
|
||||
|
||||
// MARK: Clean copy
|
||||
|
||||
/// The clean-copy popup's Copy and ⌘↩: copies its text and closes it.
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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.")) {
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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() }
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
/// One artisan console line with an id that stays put while older lines drop off the top.
|
||||
public struct SchemaConsoleEntry: Identifiable, Sendable, Equatable {
|
||||
public let id: Int
|
||||
public var line: ArtisanConsoleLine
|
||||
}
|
||||
|
||||
/// What the Schema view's body shows.
|
||||
public enum SchemaViewBody: Equatable, Sendable {
|
||||
/// The first check has not landed yet.
|
||||
case loading
|
||||
/// `HelderSchemaCommand.php` does not exist: the view offers the prompt that writes it.
|
||||
case commandMissing
|
||||
/// The command exists but `database/helder/schema.json` does not.
|
||||
case noDump
|
||||
case diagram
|
||||
}
|
||||
|
||||
/// The Schema view's state for one Laravel project: the dump, the card positions, pan and zoom,
|
||||
/// hover, selection, search and the artisan console.
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class SchemaStore {
|
||||
public private(set) var isLaravelApp = false
|
||||
public private(set) var hasCommand = false
|
||||
public private(set) var hasChecked = false
|
||||
public private(set) var model: SchemaModel?
|
||||
public private(set) var positions: [String: SchemaPoint] = [:]
|
||||
public private(set) var viewport = SchemaViewport()
|
||||
public private(set) var hovered: String?
|
||||
/// A hovered foreign key, `table.column`.
|
||||
public private(set) var hoveredColumn: String?
|
||||
public private(set) var selected: String?
|
||||
public var query = ""
|
||||
public private(set) var isBusy = false
|
||||
/// When the shown dump was written: its `generated_at`, else the file's date.
|
||||
public private(set) var lastDumpTime: Date?
|
||||
public private(set) var lines: [SchemaConsoleEntry] = []
|
||||
public private(set) var isConsoleOpen = false
|
||||
/// The last read error of the dump, nil once a read succeeds.
|
||||
public private(set) var loadError: String?
|
||||
/// The canvas between the table list and the detail panel, as last laid out.
|
||||
public private(set) var canvasSize = SchemaSize(width: 0, height: 0)
|
||||
/// The card being dragged; hover stays put while it moves.
|
||||
public private(set) var draggedTable: String?
|
||||
|
||||
public static let maxConsoleLines = 400
|
||||
public static let detailPanelWidth = 320.0
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
|
||||
@ObservationIgnored private let service: SchemaServicing
|
||||
@ObservationIgnored private let layouts: SchemaLayoutPersisting
|
||||
@ObservationIgnored private let root: String
|
||||
/// The modification date of the dump last read, so a watcher event re-reads only a changed file.
|
||||
@ObservationIgnored private var dumpDate: Date?
|
||||
@ObservationIgnored private var hasReadDump = false
|
||||
@ObservationIgnored private var needsFit = false
|
||||
@ObservationIgnored private var hasFitted = false
|
||||
@ObservationIgnored private var nextLineID = 0
|
||||
|
||||
public init(service: SchemaServicing, layouts: SchemaLayoutPersisting, root: String) {
|
||||
self.service = service
|
||||
self.layouts = layouts
|
||||
self.root = root
|
||||
}
|
||||
|
||||
// MARK: Derived
|
||||
|
||||
public var body: SchemaViewBody {
|
||||
guard hasChecked else { return .loading }
|
||||
if !hasCommand { return .commandMissing }
|
||||
return model == nil ? .noDump : .diagram
|
||||
}
|
||||
|
||||
/// What lights up for the current hover, selection and search; nil without a dump.
|
||||
public var highlight: SchemaHighlight? {
|
||||
model.map { SchemaHighlight(model: $0, hovered: hovered, selected: selected, hoveredColumn: hoveredColumn, query: query) }
|
||||
}
|
||||
|
||||
/// `no command yet`, `no dump yet`, or `dumped 14:32 · 16 tables · 23 relations`.
|
||||
public var metaLabel: String {
|
||||
if hasChecked && !hasCommand { return "no command yet" }
|
||||
guard let model else { return "no dump yet" }
|
||||
let time = lastDumpTime.map { Self.timeFormatter.string(from: $0) } ?? "—"
|
||||
return "dumped \(time) · \(model.tableCount) tables · \(model.relationCount) relations"
|
||||
}
|
||||
|
||||
public var runLabel: String {
|
||||
if isBusy { return "Dumping…" }
|
||||
return model == nil ? "Run helder:schema" : "Re-run helder:schema"
|
||||
}
|
||||
|
||||
/// The list rows: the tables matching the query, in name order.
|
||||
public var listedTables: [SchemaTable] {
|
||||
model.map { SchemaSearch.filter($0, query: query) } ?? []
|
||||
}
|
||||
|
||||
public var selectedTable: SchemaTable? {
|
||||
selected.flatMap { model?.table(named: $0) }
|
||||
}
|
||||
|
||||
private static let timeFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "HH:mm"
|
||||
return formatter
|
||||
}()
|
||||
|
||||
// MARK: Disk
|
||||
|
||||
/// Re-reads whether the project is a Laravel app and has the command.
|
||||
public func check() async {
|
||||
async let laravel = service.isLaravelApp()
|
||||
async let command = service.hasCommand()
|
||||
let (isLaravel, hasCommand) = await (laravel, command)
|
||||
isLaravelApp = isLaravel
|
||||
self.hasCommand = hasCommand
|
||||
hasChecked = true
|
||||
}
|
||||
|
||||
/// The view opened: checks the project and reads the dump when it changed since the last read.
|
||||
public func opened() async {
|
||||
await refresh(readingDump: true)
|
||||
}
|
||||
|
||||
/// A watcher pass; the dump is only read while `readingDump` (the view is open) or one is already shown.
|
||||
public func refresh(readingDump: Bool) async {
|
||||
await check()
|
||||
guard isLaravelApp, readingDump || model != nil else { return }
|
||||
let date = await service.dumpModificationDate()
|
||||
guard !hasReadDump || date != dumpDate else { return }
|
||||
await reload()
|
||||
}
|
||||
|
||||
/// Reads the dump, keeping the view and the positions of the tables that remain.
|
||||
/// A corrupt dump logs its error to the console and toasts once per changed file.
|
||||
public func reload() async {
|
||||
dumpDate = await service.dumpModificationDate()
|
||||
hasReadDump = true
|
||||
do {
|
||||
guard let next = try await service.readDump() else {
|
||||
model = nil
|
||||
loadError = nil
|
||||
return
|
||||
}
|
||||
loadError = nil
|
||||
apply(next)
|
||||
} catch {
|
||||
let message = (error as? LocalizedError)?.errorDescription ?? "\(error)"
|
||||
loadError = message
|
||||
log(message, .error)
|
||||
isConsoleOpen = true
|
||||
notify("Could not read the schema", SchemaPaths.dumpFile)
|
||||
}
|
||||
}
|
||||
|
||||
private func apply(_ next: SchemaModel) {
|
||||
let saved = positions.isEmpty ? layouts.loadPositions(root: root) : positions
|
||||
positions = SchemaLayout.positions(next, saved: saved)
|
||||
model = next
|
||||
lastDumpTime = next.generatedDate ?? dumpDate ?? Date()
|
||||
let names = Set(next.tables.map(\.name))
|
||||
if let selected, !names.contains(selected) { self.selected = nil }
|
||||
if let hovered, !names.contains(hovered) { self.hovered = nil }
|
||||
if let hoveredColumn, next.edges.allSatisfy({ $0.id != hoveredColumn }) { self.hoveredColumn = nil }
|
||||
if !hasFitted {
|
||||
needsFit = true
|
||||
fitIfReady()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Running helder:schema
|
||||
|
||||
/// Runs the command, streaming its output into the console; on exit 0 the dump is re-read.
|
||||
/// A click while it runs is ignored.
|
||||
public func run() async {
|
||||
guard !isBusy, hasCommand else { return }
|
||||
isBusy = true
|
||||
isConsoleOpen = true
|
||||
log(ArtisanOutputClassifier.commandEcho, .command)
|
||||
let (stream, continuation) = AsyncStream<(String, Bool)>.makeStream()
|
||||
let consumer = Task { [weak self] in
|
||||
for await (line, isError) in stream {
|
||||
let classified = ArtisanOutputClassifier.line(line, isError: isError)
|
||||
self?.log(classified.text, classified.kind)
|
||||
}
|
||||
}
|
||||
let code = await service.runDump { line, isError in continuation.yield((line, isError)) }
|
||||
continuation.finish()
|
||||
await consumer.value
|
||||
isBusy = false
|
||||
guard code == 0 else { return }
|
||||
await reload()
|
||||
if loadError == nil, let model { notify("Schema dumped · \(model.tableCount) tables", nil) }
|
||||
}
|
||||
|
||||
public func hideConsole() {
|
||||
isConsoleOpen = false
|
||||
}
|
||||
|
||||
private func log(_ text: String, _ kind: ArtisanLineKind) {
|
||||
lines.append(SchemaConsoleEntry(id: nextLineID, line: ArtisanConsoleLine(text: text, kind: kind)))
|
||||
nextLineID += 1
|
||||
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
|
||||
}
|
||||
|
||||
// MARK: Pan and zoom
|
||||
|
||||
public func setCanvasSize(_ size: SchemaSize) {
|
||||
guard size != canvasSize else { return }
|
||||
canvasSize = size
|
||||
fitIfReady()
|
||||
}
|
||||
|
||||
/// Frames every card with a 48pt margin, at most 110%.
|
||||
public func fit() {
|
||||
guard let model, let bounds = SchemaGeometry.bounds(model, positions: positions), hasCanvas else { return }
|
||||
viewport = SchemaGeometry.fit(bounds: bounds, in: canvasSize)
|
||||
hasFitted = true
|
||||
needsFit = false
|
||||
}
|
||||
|
||||
/// Zooms around a canvas-view point, or around the centre for the `−` and `+` buttons.
|
||||
public func zoom(by factor: Double, around anchor: SchemaPoint? = nil) {
|
||||
guard model != nil else { return }
|
||||
viewport = anchor.map { SchemaGeometry.zoom(viewport, by: factor, around: $0) }
|
||||
?? SchemaGeometry.zoom(viewport, by: factor, in: canvasSize)
|
||||
}
|
||||
|
||||
public func pan(dx: Double, dy: Double) {
|
||||
guard model != nil else { return }
|
||||
viewport.x += dx
|
||||
viewport.y += dy
|
||||
}
|
||||
|
||||
/// A background drag: the viewport it started from, moved by the drag.
|
||||
public func setViewport(_ next: SchemaViewport) {
|
||||
viewport = next
|
||||
}
|
||||
|
||||
private var hasCanvas: Bool { canvasSize.width > 0 && canvasSize.height > 0 }
|
||||
|
||||
private func fitIfReady() {
|
||||
guard needsFit, hasCanvas, model != nil else { return }
|
||||
fit()
|
||||
}
|
||||
|
||||
// MARK: Cards
|
||||
|
||||
public func moveTable(_ name: String, to point: SchemaPoint) {
|
||||
guard positions[name] != nil else { return }
|
||||
draggedTable = name
|
||||
positions[name] = point
|
||||
}
|
||||
|
||||
/// A card drag ended: the positions are saved for this project.
|
||||
public func endDrag() {
|
||||
guard draggedTable != nil else { return }
|
||||
draggedTable = nil
|
||||
layouts.savePositions(positions, root: root)
|
||||
}
|
||||
|
||||
public func hover(_ table: String?) {
|
||||
guard draggedTable == nil else { return }
|
||||
hovered = table
|
||||
if table == nil { hoveredColumn = nil }
|
||||
}
|
||||
|
||||
/// Only foreign-key rows narrow the highlight; nil leaves it to the hovered table.
|
||||
public func hoverColumn(_ id: String?) {
|
||||
guard draggedTable == nil else { return }
|
||||
hoveredColumn = id
|
||||
}
|
||||
|
||||
/// A click on a card: selects it, or deselects it when it already was.
|
||||
public func toggleSelection(_ table: String) {
|
||||
selected = selected == table ? nil : table
|
||||
}
|
||||
|
||||
public func clearSelection() {
|
||||
selected = nil
|
||||
}
|
||||
|
||||
/// Selects the table and pans it to the middle; the detail panel's width is left out when it is about to open.
|
||||
public func centre(_ name: String) {
|
||||
guard let model, let table = model.table(named: name), let position = positions[name] else { return }
|
||||
let width = canvasSize.width - (selected == nil ? Self.detailPanelWidth : 0)
|
||||
viewport = SchemaGeometry.centre(table, at: position, in: SchemaSize(width: width, height: canvasSize.height), view: viewport)
|
||||
selected = name
|
||||
hovered = nil
|
||||
hoveredColumn = nil
|
||||
}
|
||||
|
||||
/// ↵ in the table search.
|
||||
public func centreFirstMatch() {
|
||||
guard !query.trimmingCharacters(in: .whitespaces).isEmpty, let first = listedTables.first else { return }
|
||||
centre(first.name)
|
||||
}
|
||||
|
||||
public func clearSearch() {
|
||||
query = ""
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,28 @@ extension WorkspaceModel {
|
||||
if panel == .editor { editor?.requestTextFocus() }
|
||||
}
|
||||
|
||||
// MARK: Schema view
|
||||
|
||||
/// Opens the Schema view in a Laravel app and reads the command and dump; anywhere else it does nothing.
|
||||
func openSchemaView() {
|
||||
guard let schema, schema.isLaravelApp, !layout.isSchemaViewOpen else { return }
|
||||
layout.openSchemaView()
|
||||
focusRequest = nil
|
||||
track { await schema.opened() }
|
||||
}
|
||||
|
||||
/// Hands the keyboard back to the column that had it before the view opened.
|
||||
func closeSchemaView() {
|
||||
guard layout.isSchemaViewOpen else { return }
|
||||
layout.closeSchemaView()
|
||||
guard let panel = layout.activePanel else {
|
||||
focusRequest = nil
|
||||
return
|
||||
}
|
||||
focusRequest = FocusRequest(.panel(panel))
|
||||
if panel == .editor { editor?.requestTextFocus() }
|
||||
}
|
||||
|
||||
// MARK: Focus and the row cursor
|
||||
|
||||
func focus(_ panel: Panel) {
|
||||
|
||||
@@ -67,6 +67,9 @@ extension WorkspaceModel {
|
||||
self.editor = editor
|
||||
|
||||
cleanCopy = CleanCopyStore(files: services.files)
|
||||
let schema = SchemaStore(service: services.schema, layouts: app.schemaLayouts, root: root.path)
|
||||
schema.notify = notify
|
||||
self.schema = schema
|
||||
terminal = TerminalStore(projectRoot: root.path)
|
||||
wireTerminal()
|
||||
launcher = LauncherList(recents: recentProjects, excluding: root.path)
|
||||
@@ -98,11 +101,12 @@ extension WorkspaceModel {
|
||||
recentProjects = await app.recentProjects.list()
|
||||
guard generation == current else { return }
|
||||
launcher = LauncherList(recents: recentProjects, excluding: root.path)
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor, cleanCopy = cleanCopy
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor, cleanCopy = cleanCopy, schema = schema
|
||||
async let git: Void = sourceControl?.refresh() ?? ()
|
||||
async let tree: Void = explorer?.reload() ?? ()
|
||||
async let baseline: Void = cleanCopy?.loadBaseline() ?? ()
|
||||
_ = await (git, tree, baseline)
|
||||
async let laravel: Void = schema?.check() ?? ()
|
||||
_ = await (git, tree, baseline, laravel)
|
||||
await editor?.restore(restoreSession: config.session.restoreOnLaunch)
|
||||
guard generation == current else { return }
|
||||
startWatcher(root)
|
||||
|
||||
@@ -7,7 +7,7 @@ extension WorkspaceModel {
|
||||
public func refresh() async {
|
||||
refreshTick += 1
|
||||
let editor = editor
|
||||
async let reread: Void = run([.git, .tree])
|
||||
async let reread: Void = run([.git, .tree, .schema])
|
||||
async let active: Void = editor?.reloadActiveFromDisk() ?? ()
|
||||
_ = await (reread, active)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ extension WorkspaceModel {
|
||||
/// Reacts to a disk change from the watcher: project and git events gather into one debounced refresh.
|
||||
public func handle(_ event: WatchEvent) async {
|
||||
switch event {
|
||||
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles])
|
||||
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .schema])
|
||||
case .git: scheduleRefresh(.git)
|
||||
case .config: await reloadConfig()
|
||||
case .cleanCopy: await cleanCopyChanged()
|
||||
@@ -61,7 +61,8 @@ extension WorkspaceModel {
|
||||
|
||||
/// Reads the stores once up front, so a pass that outlives a project switch only touches the old project.
|
||||
func run(_ scope: RefreshScope) async {
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor, schema = schema
|
||||
let readsDump = layout.isSchemaViewOpen
|
||||
let current = generation
|
||||
if scope.contains(.symbols) {
|
||||
await services?.symbols.invalidate()
|
||||
@@ -70,7 +71,8 @@ extension WorkspaceModel {
|
||||
async let git: Void = scope.contains(.git) ? (sourceControl?.refresh() ?? ()) : ()
|
||||
async let tree: Void = scope.contains(.tree) ? (explorer?.reload() ?? ()) : ()
|
||||
async let files: Void = scope.contains(.openFiles) ? (editor?.filesChanged(nil) ?? ()) : ()
|
||||
_ = await (git, tree, files)
|
||||
async let dump: Void = scope.contains(.schema) ? (schema?.refresh(readingDump: readsDump) ?? ()) : ()
|
||||
_ = await (git, tree, files, dump)
|
||||
}
|
||||
|
||||
/// Restarts the countdown on every change, so a burst of writes loads the class list once.
|
||||
|
||||
@@ -41,6 +41,8 @@ public struct RefreshScope: OptionSet, Sendable {
|
||||
public static let symbols = RefreshScope(rawValue: 4)
|
||||
/// The open file and every unsaved buffer pick up the disk text; unsaved edits are kept.
|
||||
public static let openFiles = RefreshScope(rawValue: 8)
|
||||
/// The Schema view's command file and dump.
|
||||
public static let schema = RefreshScope(rawValue: 16)
|
||||
}
|
||||
|
||||
/// A list row whose on-screen frame the ⌘→ menu anchors to.
|
||||
@@ -81,6 +83,7 @@ public final class WorkspaceModel {
|
||||
public internal(set) var editor: EditorStore?
|
||||
public internal(set) var terminal: TerminalStore
|
||||
public internal(set) var cleanCopy: CleanCopyStore?
|
||||
public internal(set) var schema: SchemaStore?
|
||||
|
||||
@ObservationIgnored public let app: AppServices
|
||||
@ObservationIgnored public internal(set) var services: WorkspaceServices?
|
||||
@@ -148,6 +151,8 @@ public final class WorkspaceModel {
|
||||
|
||||
case .toggleGit: layout.isGitViewOpen ? closeGitView() : openGitView()
|
||||
case .closeGitView: closeGitView()
|
||||
case .toggleSchemaView: layout.isSchemaViewOpen ? closeSchemaView() : openSchemaView()
|
||||
case .closeSchemaView: closeSchemaView()
|
||||
case let .togglePane(panel): layout.togglePane(panel)
|
||||
case .toggleAutoFit: layout.toggleFluid()
|
||||
case .toggleHidden: layout.toggleHidden()
|
||||
@@ -204,6 +209,27 @@ public final class WorkspaceModel {
|
||||
}
|
||||
case .focusCommitMessage: openGitView()
|
||||
|
||||
case .runSchemaDump:
|
||||
guard let schema else { return }
|
||||
track { await schema.run() }
|
||||
case .generateSchemaCommand:
|
||||
closeSchemaView()
|
||||
passToAgent(SchemaCommandPrompt.text, toast: "Command prompt")
|
||||
case .copySchemaPrompt:
|
||||
app.system.copy(SchemaCommandPrompt.text)
|
||||
toasts.show("Copied prompt")
|
||||
case let .passSchemaTable(name):
|
||||
closeSchemaView()
|
||||
passToAgent("@schema:\(name)", toast: "@schema:\(name)")
|
||||
case let .copySchemaTableName(name):
|
||||
app.system.copy(name)
|
||||
toasts.show("Copied table name", detail: name)
|
||||
case .openSchemaCommandFile:
|
||||
closeSchemaView()
|
||||
open(SchemaPaths.commandFile)
|
||||
case .clearSchemaSelection: schema?.clearSelection()
|
||||
case .clearSchemaSearch: schema?.clearSearch()
|
||||
|
||||
case .copyCleanCopy: copyCleanCopy()
|
||||
|
||||
case .stopReading: readAloud.stop()
|
||||
|
||||
@@ -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:),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user