adds nice git interface
This commit is contained in:
@@ -15,9 +15,9 @@ Always use the scripts: they select the toolchain this machine needs. Search use
|
|||||||
|
|
||||||
## What it does
|
## What it does
|
||||||
|
|
||||||
One project per window, four columns:
|
One project per window, three columns, and a full-screen Git view over them:
|
||||||
|
|
||||||
- **Source Control**: staged and unstaged changes grouped by folder, stage/unstage/discard, the commit box and push at the foot.
|
- **Git view** (⌘G): staged, changed, new and deleted files with inline diffs; stage, unstage, discard, delete, restore; commit, commit and push, pull; a console with every git command; branch switching.
|
||||||
- **Explorer**: the file tree with change letters; new file/folder, rename, delete, Show in Finder, copy or pass on a reference.
|
- **Explorer**: the file tree with change letters; new file/folder, rename, delete, Show in Finder, copy or pass on a reference.
|
||||||
- **Editor**: one open file under a bar with its path, unsaved dot and change counts; changed lines marked in the live code, Diff opens a full-screen side-by-side view; Preview renders Markdown; ⌘-click on a PHP class shows its definition and uses.
|
- **Editor**: one open file under a bar with its path, unsaved dot and change counts; changed lines marked in the live code, Diff opens a full-screen side-by-side view; Preview renders Markdown; ⌘-click on a PHP class shows its definition and uses.
|
||||||
- **Agent**: Claude Code over a plain shell. "Pass on" pastes a reference (and the selected code) into the agent's composer without sending it.
|
- **Agent**: Claude Code over a plain shell. "Pass on" pastes a reference (and the selected code) into the agent's composer without sending it.
|
||||||
@@ -32,20 +32,22 @@ Plus ⌘F search (this file, the project, file names), recent files and recent p
|
|||||||
| ⌘O | Open a folder |
|
| ⌘O | Open a folder |
|
||||||
| ⇧⌘O | Open recent project: the list of recent projects |
|
| ⇧⌘O | Open recent project: the list of recent projects |
|
||||||
| ⇧⌘N | New window |
|
| ⇧⌘N | New window |
|
||||||
| ⌘← ⌘→ | Column left or right; in Git or Explorer ⌘→ opens the row's menu |
|
| ⌘← ⌘→ | Column left or right; in the Explorer ⌘→ opens the row's menu |
|
||||||
| ↑ ↓ ↵ | Git or Explorer: move the row cursor, open the row |
|
| ↑ ↓ ↵ | Explorer: move the row cursor, open the row |
|
||||||
| ⌘↑ ⌘↓ | Recent files, from the editor |
|
| ⌘↑ ⌘↓ | Recent files, from the editor |
|
||||||
| ⌘→ (selection) | Pass the selection to the agent |
|
| ⌘→ (selection) | Pass the selection to the agent |
|
||||||
| ⌘M | Markdown: code or rendered preview |
|
| ⌘M | Markdown: code or rendered preview |
|
||||||
| ⌘S / ⌘W | Save / close the open file (asks about unsaved edits) |
|
| ⌘S / ⌘W | Save / close the open file (asks about unsaved edits) |
|
||||||
| ⌘C | Focus the commit message (copies when something is selected) |
|
| ⌘C | Open the Git view on the commit message (copies when something is selected) |
|
||||||
| ⌘↵ / ⇧↵ in the message | Commit the staged files |
|
| ⌘↵ | Commit the staged files, while the Git view is open |
|
||||||
| ⌘P | Push |
|
| ⌘P | Push |
|
||||||
| ⌘R | Re-read git, the tree and the open file from disk |
|
| ⌘R | Re-read git, the tree and the open file from disk |
|
||||||
| ⌘G / ⌘L / ⌘. | Source Control column / fluid columns / hidden files |
|
| ⌘G | Open or close the Git view |
|
||||||
|
| ⌘1 / ⌘2 / ⌘3 | Explorer / File / Claude column on or off |
|
||||||
|
| ⌘L / ⌘. | Fluid columns / hidden files |
|
||||||
| ⌘A | Select all in the focused pane; in the code pane, the whole file |
|
| ⌘A | Select all in the focused pane; in the code pane, the whole file |
|
||||||
| ⌘0 / ⌘+ / ⌘− | Zoom: editor, Diff and terminal text |
|
| ⌘0 / ⌘+ / ⌘− | Zoom: editor, Diff and terminal text |
|
||||||
| Esc | Close the overlay |
|
| Esc | Close the overlay, then the Git view |
|
||||||
| ? | Keyboard shortcuts |
|
| ? | Keyboard shortcuts |
|
||||||
|
|
||||||
Closing a window, switching project or quitting (⌘Q) first asks about every unsaved file; a cancel keeps everything open. Then the session is written and both terminals end. A terminal whose process exited restarts on the next key press; right-click in a terminal gives Copy (with a selection) and Paste.
|
Closing a window, switching project or quitting (⌘Q) first asks about every unsaved file; a cancel keeps everything open. Then the session is written and both terminals end. A terminal whose process exited restarts on the next key press; right-click in a terminal gives Copy (with a selection) and Paste.
|
||||||
|
|||||||
@@ -71,8 +71,6 @@ public struct HelderConfig: Codable, Sendable, Equatable {
|
|||||||
|
|
||||||
public struct Git: Codable, Sendable, Equatable {
|
public struct Git: Codable, Sendable, Equatable {
|
||||||
public var confirmDiscard = true
|
public var confirmDiscard = true
|
||||||
public var confirmStage = false
|
|
||||||
public var confirmUnstage = false
|
|
||||||
public var defaultDiffMode = DefaultDiffMode.updated
|
public var defaultDiffMode = DefaultDiffMode.updated
|
||||||
/// Milliseconds between git status polls; 0 disables the poll.
|
/// Milliseconds between git status polls; 0 disables the poll.
|
||||||
public var refreshInterval = 10_000
|
public var refreshInterval = 10_000
|
||||||
@@ -182,15 +180,13 @@ extension HelderConfig.Editor {
|
|||||||
|
|
||||||
extension HelderConfig.Git {
|
extension HelderConfig.Git {
|
||||||
private enum CodingKeys: String, CodingKey {
|
private enum CodingKeys: String, CodingKey {
|
||||||
case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval
|
case confirmDiscard, defaultDiffMode, refreshInterval
|
||||||
}
|
}
|
||||||
|
|
||||||
public init(from decoder: Decoder) throws {
|
public init(from decoder: Decoder) throws {
|
||||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
let d = Self()
|
let d = Self()
|
||||||
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
|
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
|
||||||
confirmStage = c.value(.confirmStage, d.confirmStage)
|
|
||||||
confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage)
|
|
||||||
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
|
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
|
||||||
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
|
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ public enum ContextTarget: Sendable, Equatable {
|
|||||||
case editor(reference: AgentReference, code: String?, showDiffLine: Int? = nil)
|
case editor(reference: AgentReference, code: String?, showDiffLine: Int? = nil)
|
||||||
case file(path: String)
|
case file(path: String)
|
||||||
case directory(path: String)
|
case directory(path: String)
|
||||||
/// A git row; the row carries its own half, since one file can have two rows.
|
/// A file row in the Git view; a deleted file has nothing to open.
|
||||||
case gitRow(path: String, staged: Bool)
|
case gitRow(path: String, isDeleted: Bool)
|
||||||
|
/// The caret beside the Git view's Commit button.
|
||||||
|
case commitMenu
|
||||||
/// The empty space under the tree: the project folder itself.
|
/// The empty space under the tree: the project folder itself.
|
||||||
case projectRoot
|
case projectRoot
|
||||||
case terminal(TerminalKind, hasSelection: Bool)
|
case terminal(TerminalKind, hasSelection: Bool)
|
||||||
@@ -17,7 +19,7 @@ public enum ContextTarget: Sendable, Equatable {
|
|||||||
switch self {
|
switch self {
|
||||||
case let .editor(reference, _, _): reference.path
|
case let .editor(reference, _, _): reference.path
|
||||||
case let .file(path), let .directory(path), let .gitRow(path, _): path
|
case let .file(path), let .directory(path), let .gitRow(path, _): path
|
||||||
case .projectRoot, .terminal: ""
|
case .projectRoot, .terminal, .commitMenu: ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,12 +32,13 @@ public enum ContextAction: Sendable, Equatable {
|
|||||||
case copyFileName(String)
|
case copyFileName(String)
|
||||||
case newFile(inDirectory: String)
|
case newFile(inDirectory: String)
|
||||||
case newFolder(inDirectory: String)
|
case newFolder(inDirectory: String)
|
||||||
case stage(String)
|
/// Opens a file from the Git view, which closes first.
|
||||||
case unstage(String)
|
case openFile(String)
|
||||||
case openDiff(String)
|
/// Reverts unstaged changes: modified and deleted files come back from the index, new files are removed.
|
||||||
|
case gitDiscard([String])
|
||||||
|
case commit(andPush: Bool)
|
||||||
/// Opens the Diff of the open file at this line.
|
/// Opens the Diff of the open file at this line.
|
||||||
case showDiff(String, line: Int)
|
case showDiff(String, line: Int)
|
||||||
case discard(String)
|
|
||||||
case rename(String, isDirectory: Bool)
|
case rename(String, isDirectory: Bool)
|
||||||
case revealInFinder(String)
|
case revealInFinder(String)
|
||||||
case delete(String, isDirectory: Bool)
|
case delete(String, isDirectory: Bool)
|
||||||
@@ -58,7 +61,15 @@ public enum ContextAction: Sendable, Equatable {
|
|||||||
/// Destructive items read in amber-deep.
|
/// Destructive items read in amber-deep.
|
||||||
public var isDestructive: Bool {
|
public var isDestructive: Bool {
|
||||||
switch self {
|
switch self {
|
||||||
case .discard, .delete: true
|
case .gitDiscard, .delete: true
|
||||||
|
default: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menu's main item, set in bold.
|
||||||
|
public var isEmphasized: Bool {
|
||||||
|
switch self {
|
||||||
|
case .openFile, .commit(andPush: true): true
|
||||||
default: false
|
default: false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,7 +87,7 @@ public enum ContextActions {
|
|||||||
switch target {
|
switch target {
|
||||||
case let .file(path), let .gitRow(path, _): path
|
case let .file(path), let .gitRow(path, _): path
|
||||||
case .projectRoot: projectName + "/"
|
case .projectRoot: projectName + "/"
|
||||||
case .editor, .directory, .terminal: ""
|
case .editor, .directory, .terminal, .commitMenu: ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,12 +138,16 @@ public enum ContextActions {
|
|||||||
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
|
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
|
||||||
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
|
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
|
||||||
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
|
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
|
||||||
case let .gitRow(path, staged):
|
case let .gitRow(path, isDeleted):
|
||||||
return fileHead(path) + readAloudFile(path) + [
|
let open: [ContextMenuEntry] = isDeleted ? [] : [.action(.openFile(path), label: "Open in editor"), .separator]
|
||||||
.separator,
|
return open + [
|
||||||
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
|
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
|
||||||
.action(.openDiff(path), label: "Open diff"),
|
.action(.copyReference(path), label: "Copy reference"),
|
||||||
.action(.discard(path), label: "Discard changes"),
|
]
|
||||||
|
case .commitMenu:
|
||||||
|
return [
|
||||||
|
.action(.commit(andPush: false), label: "Commit"),
|
||||||
|
.action(.commit(andPush: true), label: "Commit and push"),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// The branches a checkout can pick from: local ones and the ones on "origin".
|
||||||
|
public struct GitBranchList: Sendable, Equatable {
|
||||||
|
/// Sorted local branch names.
|
||||||
|
public var local: [String]
|
||||||
|
/// Sorted "origin/x" names; "origin/HEAD" is left out.
|
||||||
|
public var remote: [String]
|
||||||
|
|
||||||
|
public init(local: [String] = [], remote: [String] = []) {
|
||||||
|
self.local = local
|
||||||
|
self.remote = remote
|
||||||
|
}
|
||||||
|
|
||||||
|
public static let empty = GitBranchList()
|
||||||
|
|
||||||
|
/// True when `remote` ("origin/x") already has a local branch "x".
|
||||||
|
public func isTracked(_ remote: String) -> Bool {
|
||||||
|
local.contains(Self.localName(ofRemote: remote))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The local name a remote branch checks out as: "origin/feature/a" → "feature/a".
|
||||||
|
public static func localName(ofRemote remote: String) -> String {
|
||||||
|
guard let slash = remote.firstIndex(of: "/") else { return remote }
|
||||||
|
return String(remote[remote.index(after: slash)...])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum GitBranchParsing {
|
||||||
|
public static let arguments = ["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes/origin"]
|
||||||
|
|
||||||
|
/// Reads one full ref name per line, as `arguments` prints them.
|
||||||
|
public static func parse(_ raw: String) -> GitBranchList {
|
||||||
|
var list = GitBranchList()
|
||||||
|
for line in raw.split(whereSeparator: \.isNewline) {
|
||||||
|
let ref = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if ref.hasPrefix("refs/heads/") {
|
||||||
|
list.local.append(String(ref.dropFirst("refs/heads/".count)))
|
||||||
|
} else if ref.hasPrefix("refs/remotes/origin/") {
|
||||||
|
let name = String(ref.dropFirst("refs/remotes/".count))
|
||||||
|
if name != "origin/HEAD" { list.remote.append(name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list.local.sort()
|
||||||
|
list.remote.sort()
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// How a line in the git console is painted.
|
||||||
|
public enum GitLineKind: String, Sendable, Equatable {
|
||||||
|
case command
|
||||||
|
case output
|
||||||
|
case error
|
||||||
|
case hint
|
||||||
|
case staged
|
||||||
|
case unstaged
|
||||||
|
case success
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct GitConsoleLine: Sendable, Equatable {
|
||||||
|
public var text: String
|
||||||
|
public var kind: GitLineKind
|
||||||
|
|
||||||
|
public init(text: String, kind: GitLineKind) {
|
||||||
|
self.text = text
|
||||||
|
self.kind = kind
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum GitConsoleText {
|
||||||
|
/// The echo of a run, such as `$ git commit -m "fix the bar"`.
|
||||||
|
public static func commandLine(_ arguments: [String]) -> String {
|
||||||
|
(["$ git"] + arguments.map(quoted)).joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func quoted(_ argument: String) -> String {
|
||||||
|
let needsQuotes = argument.isEmpty || argument.contains { $0.isWhitespace || $0 == "\"" || $0 == "'" }
|
||||||
|
guard needsQuotes else { return argument }
|
||||||
|
return "\"" + argument.replacingOccurrences(of: "\"", with: "\\\"") + "\""
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits what the user typed into git arguments; a leading `git` is dropped and nil means nothing is left.
|
||||||
|
///
|
||||||
|
/// Quoting follows the shell: '…' is literal, "…" honours `\"` and `\\`, and an unclosed quote ends at the end.
|
||||||
|
public static func parseInput(_ input: String) -> [String]? {
|
||||||
|
var arguments: [String] = []
|
||||||
|
var current = ""
|
||||||
|
var hasToken = false
|
||||||
|
var quote: Character?
|
||||||
|
var escaping = false
|
||||||
|
for char in input {
|
||||||
|
if escaping {
|
||||||
|
if quote == "\"" && char != "\"" && char != "\\" { current.append("\\") }
|
||||||
|
current.append(char)
|
||||||
|
escaping = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch (quote, char) {
|
||||||
|
case ("'", "'"), ("\"", "\""):
|
||||||
|
quote = nil
|
||||||
|
case ("'", _):
|
||||||
|
current.append(char)
|
||||||
|
case (_, "\\"):
|
||||||
|
escaping = true
|
||||||
|
hasToken = true
|
||||||
|
case (nil, "'"), (nil, "\""):
|
||||||
|
quote = char
|
||||||
|
hasToken = true
|
||||||
|
case (nil, _) where char.isWhitespace:
|
||||||
|
if hasToken { arguments.append(current) }
|
||||||
|
current = ""
|
||||||
|
hasToken = false
|
||||||
|
default:
|
||||||
|
current.append(char)
|
||||||
|
hasToken = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if escaping { current.append("\\") }
|
||||||
|
if hasToken { arguments.append(current) }
|
||||||
|
if arguments.first == "git" { arguments.removeFirst() }
|
||||||
|
return arguments.isEmpty ? nil : arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The branch's place against its upstream, such as `1 ahead · 2 behind origin`.
|
||||||
|
public static func syncLabel(ahead: Int, behind: Int, upstream: String?) -> String {
|
||||||
|
guard let upstream else { return "no upstream" }
|
||||||
|
let remote = upstream.split(separator: "/", maxSplits: 1).first.map(String.init) ?? upstream
|
||||||
|
switch (ahead > 0, behind > 0) {
|
||||||
|
case (true, true): return "\(ahead) ahead · \(behind) behind \(remote)"
|
||||||
|
case (false, true): return "\(behind) behind \(remote)"
|
||||||
|
case (true, false): return "\(ahead) ahead of \(remote)"
|
||||||
|
case (false, false): return "in sync with \(remote)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paints the output lines of one git command. Keep one per run: `status` sections carry over between lines.
|
||||||
|
///
|
||||||
|
/// Git writes progress to stderr, so a stderr line alone is not an error.
|
||||||
|
public struct GitOutputClassifier: Sendable {
|
||||||
|
private enum StatusSection {
|
||||||
|
case staged
|
||||||
|
case unstaged
|
||||||
|
case other
|
||||||
|
}
|
||||||
|
|
||||||
|
private let subcommand: String?
|
||||||
|
private var section = StatusSection.other
|
||||||
|
|
||||||
|
public init(arguments: [String]) {
|
||||||
|
subcommand = Self.subcommand(of: arguments)
|
||||||
|
}
|
||||||
|
|
||||||
|
public mutating func classify(_ line: String, isError: Bool) -> GitLineKind {
|
||||||
|
let trimmed = line.drop { $0 == " " || $0 == "\t" }
|
||||||
|
if trimmed.hasPrefix("hint:") { return .hint }
|
||||||
|
if Self.errorPrefixes.contains(where: { trimmed.hasPrefix($0) }) { return .error }
|
||||||
|
switch subcommand {
|
||||||
|
case "push":
|
||||||
|
if Self.isRefUpdate(trimmed) { return .success }
|
||||||
|
case "status":
|
||||||
|
if let next = Self.sections[String(trimmed)] {
|
||||||
|
section = next
|
||||||
|
return .output
|
||||||
|
}
|
||||||
|
if line.hasPrefix("\t") {
|
||||||
|
switch section {
|
||||||
|
case .staged: return .staged
|
||||||
|
case .unstaged: return .unstaged
|
||||||
|
case .other: break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return .output
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let errorPrefixes = [
|
||||||
|
"error:", "fatal:", "! [rejected]", "! [remote rejected]", "Aborting", "Please commit your changes",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// `a1b2c3d..e4f5a6b main -> main`, a forced `+ a...b`, or `* [new branch] x -> x`.
|
||||||
|
private static func isRefUpdate(_ line: Substring) -> Bool {
|
||||||
|
line.contains(" -> ")
|
||||||
|
&& line.wholeMatch(of: /(?:\+\s*)?(?:[0-9a-f]+\.\.\.?[0-9a-f]+|\*\s+\[new [a-z ]+\])\s+.+ -> .+/) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let sections: [String: StatusSection] = [
|
||||||
|
"Changes to be committed:": .staged,
|
||||||
|
"Changes not staged for commit:": .unstaged,
|
||||||
|
"Untracked files:": .unstaged,
|
||||||
|
"Unmerged paths:": .other,
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The first argument that is not an option; `-c` and `-C` take a value.
|
||||||
|
private static func subcommand(of arguments: [String]) -> String? {
|
||||||
|
var skipNext = false
|
||||||
|
for argument in arguments {
|
||||||
|
if skipNext {
|
||||||
|
skipNext = false
|
||||||
|
} else if argument == "-c" || argument == "-C" {
|
||||||
|
skipNext = true
|
||||||
|
} else if !argument.hasPrefix("-") {
|
||||||
|
return argument
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,8 @@ public enum GitDerivation {
|
|||||||
/// so a file staged as modified but deleted on disk reads as deleted.
|
/// so a file staged as modified but deleted on disk reads as deleted.
|
||||||
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
|
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
|
||||||
guard let snapshot else { return .empty }
|
guard let snapshot else { return .empty }
|
||||||
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true)
|
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
|
||||||
|
behind: snapshot.behind, upstream: snapshot.upstream, isRepository: true)
|
||||||
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
|
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
|
||||||
var tooBig = Set<String>()
|
var tooBig = Set<String>()
|
||||||
for change in snapshot.changes {
|
for change in snapshot.changes {
|
||||||
@@ -39,55 +40,9 @@ public enum GitDerivation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rows of one folder in the Source Control list.
|
|
||||||
public struct ChangeGroup: Sendable, Equatable {
|
|
||||||
/// Folder path; "" is the project root.
|
|
||||||
public var dir: String
|
|
||||||
public var rows: [Change]
|
|
||||||
|
|
||||||
public init(dir: String, rows: [Change]) {
|
|
||||||
self.dir = dir
|
|
||||||
self.rows = rows
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum SourceControlText {
|
public enum SourceControlText {
|
||||||
/// Groups rows by folder in order of first appearance; keyboard navigation walks this same order.
|
|
||||||
public static func groupByDir(_ list: [Change]) -> [ChangeGroup] {
|
|
||||||
var groups: [ChangeGroup] = []
|
|
||||||
var indexByDir: [String: Int] = [:]
|
|
||||||
for change in list {
|
|
||||||
let dir = PathUtils.dirname(change.path)
|
|
||||||
if let index = indexByDir[dir] {
|
|
||||||
groups[index].rows.append(change)
|
|
||||||
} else {
|
|
||||||
indexByDir[dir] = groups.count
|
|
||||||
groups.append(ChangeGroup(dir: dir, rows: [change]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return groups
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The row order of the list: staged groups first, then unstaged, each folder by folder.
|
|
||||||
public static func navigationOrder(_ changes: [Change]) -> [Change] {
|
|
||||||
let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows)
|
|
||||||
let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows)
|
|
||||||
return staged + unstaged
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
|
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
|
||||||
public static func normalizeCommitMessage(_ value: String) -> String {
|
public static func normalizeCommitMessage(_ value: String) -> String {
|
||||||
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
|
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
|
||||||
}
|
}
|
||||||
|
|
||||||
public static func pushTooltip(canPush: Bool, ahead: Int) -> String {
|
|
||||||
if !canPush { return "Nothing to push (⌘P)" }
|
|
||||||
if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" }
|
|
||||||
return "Push the branch to remote (⌘P)"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Git rows under `tests/` or `cypress/` render dimmed.
|
|
||||||
public static func isTestFile(_ path: String) -> Bool {
|
|
||||||
path.hasPrefix("tests/") || path.hasPrefix("cypress/")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,12 +41,18 @@ public struct GitSnapshot: Sendable, Equatable {
|
|||||||
public var ahead: Int
|
public var ahead: Int
|
||||||
/// True when a push would send something, including a branch without an upstream.
|
/// True when a push would send something, including a branch without an upstream.
|
||||||
public var canPush: Bool
|
public var canPush: Bool
|
||||||
|
/// Commits the remote has that the branch does not; 0 when unknown.
|
||||||
|
public var behind: Int
|
||||||
|
/// The tracked branch, such as "origin/main"; nil without one.
|
||||||
|
public var upstream: String?
|
||||||
public var changes: [GitFileChange]
|
public var changes: [GitFileChange]
|
||||||
|
|
||||||
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
|
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, changes: [GitFileChange]) {
|
||||||
self.branch = branch
|
self.branch = branch
|
||||||
self.ahead = ahead
|
self.ahead = ahead
|
||||||
self.canPush = canPush
|
self.canPush = canPush
|
||||||
|
self.behind = behind
|
||||||
|
self.upstream = upstream
|
||||||
self.changes = changes
|
self.changes = changes
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -86,6 +92,10 @@ public struct GitWorkingState: Sendable, Equatable {
|
|||||||
public var branch: String
|
public var branch: String
|
||||||
public var ahead: Int
|
public var ahead: Int
|
||||||
public var canPush: Bool
|
public var canPush: Bool
|
||||||
|
/// Commits the remote has that the branch does not; 0 when unknown.
|
||||||
|
public var behind: Int
|
||||||
|
/// The tracked branch, such as "origin/main"; nil without one.
|
||||||
|
public var upstream: String?
|
||||||
public var changes: [Change]
|
public var changes: [Change]
|
||||||
/// Per path: HEAD vs disk. Drives the Actual view.
|
/// Per path: HEAD vs disk. Drives the Actual view.
|
||||||
public var fileDiffs: [String: Diff]
|
public var fileDiffs: [String: Diff]
|
||||||
@@ -97,13 +107,16 @@ public struct GitWorkingState: Sendable, Equatable {
|
|||||||
public var isRepository: Bool
|
public var isRepository: Bool
|
||||||
|
|
||||||
public init(
|
public init(
|
||||||
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
|
branch: String = "—", ahead: Int = 0, canPush: Bool = false, behind: Int = 0, upstream: String? = nil,
|
||||||
|
changes: [Change] = [],
|
||||||
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
|
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
|
||||||
stagedPaths: Set<String> = [], isRepository: Bool = false
|
stagedPaths: Set<String> = [], isRepository: Bool = false
|
||||||
) {
|
) {
|
||||||
self.branch = branch
|
self.branch = branch
|
||||||
self.ahead = ahead
|
self.ahead = ahead
|
||||||
self.canPush = canPush
|
self.canPush = canPush
|
||||||
|
self.behind = behind
|
||||||
|
self.upstream = upstream
|
||||||
self.changes = changes
|
self.changes = changes
|
||||||
self.fileDiffs = fileDiffs
|
self.fileDiffs = fileDiffs
|
||||||
self.rowDiffs = rowDiffs
|
self.rowDiffs = rowDiffs
|
||||||
@@ -127,14 +140,3 @@ public struct GitWorkingState: Sendable, Equatable {
|
|||||||
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
|
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The outcome of a push, shown in a toast.
|
|
||||||
public struct PushResult: Sendable, Equatable {
|
|
||||||
public var ok: Bool
|
|
||||||
public var message: String
|
|
||||||
|
|
||||||
public init(ok: Bool, message: String) {
|
|
||||||
self.ok = ok
|
|
||||||
self.message = message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A group in the Git view's change list, in the order the list shows them.
|
||||||
|
public enum GitSectionKind: String, CaseIterable, Sendable {
|
||||||
|
case staged
|
||||||
|
case changed
|
||||||
|
case untracked
|
||||||
|
case deleted
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct GitSection: Sendable, Equatable, Identifiable {
|
||||||
|
public var kind: GitSectionKind
|
||||||
|
public var rows: [Change]
|
||||||
|
|
||||||
|
public init(kind: GitSectionKind, rows: [Change]) {
|
||||||
|
self.kind = kind
|
||||||
|
self.rows = rows
|
||||||
|
}
|
||||||
|
|
||||||
|
public var id: String { kind.rawValue }
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum GitSections {
|
||||||
|
/// Sorts rows into their sections; only non-empty sections come back and rows keep their order.
|
||||||
|
///
|
||||||
|
/// Every staged row is staged, whatever its status; an unstaged rename or conflict counts as changed.
|
||||||
|
public static func build(_ changes: [Change]) -> [GitSection] {
|
||||||
|
var byKind: [GitSectionKind: [Change]] = [:]
|
||||||
|
for change in changes {
|
||||||
|
byKind[kind(of: change), default: []].append(change)
|
||||||
|
}
|
||||||
|
return GitSectionKind.allCases.compactMap { kind in
|
||||||
|
byKind[kind].map { GitSection(kind: kind, rows: $0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Distinct paths of the rows, in order.
|
||||||
|
public static func uniquePaths(_ rows: [Change]) -> [String] {
|
||||||
|
var seen = Set<String>()
|
||||||
|
return rows.compactMap { seen.insert($0.path).inserted ? $0.path : nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func kind(of change: Change) -> GitSectionKind {
|
||||||
|
if change.staged { return .staged }
|
||||||
|
switch change.status {
|
||||||
|
case .added: return .untracked
|
||||||
|
case .deleted: return .deleted
|
||||||
|
case .modified, .renamed, .unmerged: return .changed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One side of an inline diff line.
|
||||||
|
public struct InlineDiffCell: Sendable, Equatable {
|
||||||
|
public var number: Int
|
||||||
|
public var text: String
|
||||||
|
public var mark: LineMark?
|
||||||
|
/// Character offsets of the part that differs from the other side; nil when the whole line counts.
|
||||||
|
public var highlight: Range<Int>?
|
||||||
|
|
||||||
|
public init(number: Int, text: String, mark: LineMark? = nil, highlight: Range<Int>? = nil) {
|
||||||
|
self.number = number
|
||||||
|
self.text = text
|
||||||
|
self.mark = mark
|
||||||
|
self.highlight = highlight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum InlineDiffRow: Sendable, Equatable {
|
||||||
|
case line(left: InlineDiffCell?, right: InlineDiffCell?)
|
||||||
|
/// A run of unchanged rows folded away.
|
||||||
|
case gap(Int)
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum InlineDiff {
|
||||||
|
/// The rows of `diff.split` with `context` unchanged rows kept around each change; other unchanged runs fold into a gap.
|
||||||
|
public static func rows(from diff: Diff, context: Int = 3) -> [InlineDiffRow] {
|
||||||
|
let split = diff.split
|
||||||
|
let changed = split.map { $0.left?.mark != nil || $0.right?.mark != nil }
|
||||||
|
guard changed.contains(true) else { return [] }
|
||||||
|
var keep = [Bool](repeating: false, count: split.count)
|
||||||
|
for (index, isChanged) in changed.enumerated() where isChanged {
|
||||||
|
let low = max(0, index - context), high = min(split.count - 1, index + context)
|
||||||
|
for kept in low...high { keep[kept] = true }
|
||||||
|
}
|
||||||
|
var rows: [InlineDiffRow] = []
|
||||||
|
var folded = 0
|
||||||
|
for (index, row) in split.enumerated() {
|
||||||
|
guard keep[index] else {
|
||||||
|
folded += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if folded > 0 { rows.append(.gap(folded)) }
|
||||||
|
folded = 0
|
||||||
|
rows.append(line(row))
|
||||||
|
}
|
||||||
|
if folded > 0 { rows.append(.gap(folded)) }
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func line(_ row: SplitRow) -> InlineDiffRow {
|
||||||
|
var left = row.left.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
|
||||||
|
var right = row.right.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
|
||||||
|
if let old = left, let new = right, old.mark == .removed, new.mark == .added {
|
||||||
|
let ranges = highlights(old.text, new.text)
|
||||||
|
left?.highlight = ranges.left
|
||||||
|
right?.highlight = ranges.right
|
||||||
|
}
|
||||||
|
return .line(left: left, right: right)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The middle between the common prefix and the common suffix, per side; nil when nothing is shared or a middle is empty.
|
||||||
|
static func highlights(_ old: String, _ new: String) -> (left: Range<Int>?, right: Range<Int>?) {
|
||||||
|
let a = Array(old), b = Array(new)
|
||||||
|
var prefix = 0
|
||||||
|
while prefix < a.count && prefix < b.count && a[prefix] == b[prefix] { prefix += 1 }
|
||||||
|
var suffix = 0
|
||||||
|
while suffix < a.count - prefix && suffix < b.count - prefix && a[a.count - 1 - suffix] == b[b.count - 1 - suffix] {
|
||||||
|
suffix += 1
|
||||||
|
}
|
||||||
|
guard prefix > 0 || suffix > 0 else { return (nil, nil) }
|
||||||
|
let left = prefix..<(a.count - suffix)
|
||||||
|
let right = prefix..<(b.count - suffix)
|
||||||
|
return (left.isEmpty ? nil : left, right.isEmpty ? nil : right)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,12 +25,16 @@ public struct ParsedStatus: Sendable, Equatable {
|
|||||||
public var branch: String
|
public var branch: String
|
||||||
public var ahead: Int
|
public var ahead: Int
|
||||||
public var canPush: Bool
|
public var canPush: Bool
|
||||||
|
public var behind: Int
|
||||||
|
public var upstream: String?
|
||||||
public var entries: [StatusEntry]
|
public var entries: [StatusEntry]
|
||||||
|
|
||||||
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
|
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, entries: [StatusEntry]) {
|
||||||
self.branch = branch
|
self.branch = branch
|
||||||
self.ahead = ahead
|
self.ahead = ahead
|
||||||
self.canPush = canPush
|
self.canPush = canPush
|
||||||
|
self.behind = behind
|
||||||
|
self.upstream = upstream
|
||||||
self.entries = entries
|
self.entries = entries
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -69,6 +73,8 @@ public enum Porcelain {
|
|||||||
let header = String(part.dropFirst(3))
|
let header = String(part.dropFirst(3))
|
||||||
result.branch = parseBranch(header: header)
|
result.branch = parseBranch(header: header)
|
||||||
(result.ahead, result.canPush) = parseAhead(header: header)
|
(result.ahead, result.canPush) = parseAhead(header: header)
|
||||||
|
result.behind = parseBehind(header: header)
|
||||||
|
result.upstream = parseUpstream(header: header)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
let chars = Array(part.prefix(2))
|
let chars = Array(part.prefix(2))
|
||||||
@@ -101,6 +107,20 @@ public enum Porcelain {
|
|||||||
return (0, !header.contains("..."))
|
return (0, !header.contains("..."))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The `[behind N]` count of a header; 0 without one.
|
||||||
|
public static func parseBehind(header: String) -> Int {
|
||||||
|
guard let match = header.firstMatch(of: /\[[^\]]*\bbehind (\d+)/) else { return 0 }
|
||||||
|
return Int(match.1) ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tracked branch after `...` in a header (`main...origin/main [ahead 1]` → "origin/main"); nil without one.
|
||||||
|
public static func parseUpstream(header: String) -> String? {
|
||||||
|
if header.hasPrefix("HEAD ") { return nil }
|
||||||
|
guard let range = header.range(of: "...") else { return nil }
|
||||||
|
let name = header[range.upperBound...].split(separator: " ").first.map(String.init) ?? ""
|
||||||
|
return name.isEmpty ? nil : name
|
||||||
|
}
|
||||||
|
|
||||||
/// Maps one porcelain column letter to the letter the row shows.
|
/// Maps one porcelain column letter to the letter the row shows.
|
||||||
public static func status(for code: Character) -> GitStatus {
|
public static func status(for code: Character) -> GitStatus {
|
||||||
switch code {
|
switch code {
|
||||||
@@ -125,20 +145,6 @@ public enum Porcelain {
|
|||||||
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
|
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The toast line for a push: git reports on stderr, so the summary is pulled from there.
|
|
||||||
public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult {
|
|
||||||
let source = stderr.isEmpty ? stdout : stderr
|
|
||||||
var lines = source.split(whereSeparator: \.isNewline)
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") }
|
|
||||||
let summary = lines.first { line in
|
|
||||||
line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date")
|
|
||||||
|| line.localizedCaseInsensitiveContains("new branch")
|
|
||||||
}
|
|
||||||
return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True when a failed `git push` only needs `-u origin <branch>`.
|
/// True when a failed `git push` only needs `-u origin <branch>`.
|
||||||
public static func needsUpstream(stderr: String) -> Bool {
|
public static func needsUpstream(stderr: String) -> Bool {
|
||||||
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
|
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
|
||||||
|
|||||||
@@ -7,14 +7,12 @@ public enum FocusZone: String, Sendable, Equatable {
|
|||||||
case terminal
|
case terminal
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pixel widths of the three fixed columns; the editor takes the remainder.
|
/// Pixel widths of the two fixed columns; the editor takes the remainder.
|
||||||
public struct ColumnWidths: Sendable, Equatable {
|
public struct ColumnWidths: Sendable, Equatable {
|
||||||
public var sourceControl: Double
|
|
||||||
public var explorer: Double
|
public var explorer: Double
|
||||||
public var agent: Double
|
public var agent: Double
|
||||||
|
|
||||||
public init(sourceControl: Double, explorer: Double, agent: Double) {
|
public init(explorer: Double, agent: Double) {
|
||||||
self.sourceControl = sourceControl
|
|
||||||
self.explorer = explorer
|
self.explorer = explorer
|
||||||
self.agent = agent
|
self.agent = agent
|
||||||
}
|
}
|
||||||
@@ -25,18 +23,17 @@ public enum ColumnLayout {
|
|||||||
public static let roomyWidth = 1600.0
|
public static let roomyWidth = 1600.0
|
||||||
public static let minEditorWidth = 280.0
|
public static let minEditorWidth = 280.0
|
||||||
public static let splitterWidth = 1.0
|
public static let splitterWidth = 1.0
|
||||||
public static let sourceControlRange = 160.0...460.0
|
|
||||||
public static let explorerRange = 160.0...520.0
|
public static let explorerRange = 160.0...520.0
|
||||||
|
|
||||||
/// Fluid widths for a window. Roomy: 13.4% · 16.4% · flex · 27.3% (the design's
|
/// Fluid widths for a window. Roomy: 16.4% · flex · 27.3% (the design's 288 · flex · 480
|
||||||
/// 236 · 288 · flex · 480 on a 1760 frame). Tight: 15% · 15%, and the agent column
|
/// on a 1760 frame). Tight: 15%, and the agent column takes 30%, or 20% with the editor
|
||||||
/// takes 30%, or 20% with the editor focused, or 50% with a terminal focused.
|
/// focused, or 50% with a terminal focused.
|
||||||
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
|
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
|
||||||
if w >= roomyWidth {
|
if w >= roomyWidth {
|
||||||
return ColumnWidths(sourceControl: (w * 0.134).rounded(), explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
|
return ColumnWidths(explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
|
||||||
}
|
}
|
||||||
let agentShare = focus == .terminal ? 0.5 : focus == .editor ? 0.2 : 0.3
|
let agentShare = focus == .terminal ? 0.5 : focus == .editor ? 0.2 : 0.3
|
||||||
return ColumnWidths(sourceControl: (w * 0.15).rounded(), explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
|
return ColumnWidths(explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Scales the fixed columns down so the flex column keeps `minEditorWidth`; unchanged when they fit.
|
/// Scales the fixed columns down so the flex column keeps `minEditorWidth`; unchanged when they fit.
|
||||||
@@ -45,12 +42,10 @@ public enum ColumnLayout {
|
|||||||
let agentIsFixed = visible.agent && visible.editor
|
let agentIsFixed = visible.agent && visible.editor
|
||||||
let flexMinimum = visible.editor || visible.agent ? minEditorWidth : 0
|
let flexMinimum = visible.editor || visible.agent ? minEditorWidth : 0
|
||||||
let budget = windowWidth - Double(visible.splitterCount) * splitterWidth - flexMinimum
|
let budget = windowWidth - Double(visible.splitterCount) * splitterWidth - flexMinimum
|
||||||
let total = (visible.sourceControl ? widths.sourceControl : 0) + (visible.explorer ? widths.explorer : 0)
|
let total = (visible.explorer ? widths.explorer : 0) + (agentIsFixed ? widths.agent : 0)
|
||||||
+ (agentIsFixed ? widths.agent : 0)
|
|
||||||
guard total > budget, total > 0 else { return widths }
|
guard total > budget, total > 0 else { return widths }
|
||||||
let k = max(0, budget) / total
|
let k = max(0, budget) / total
|
||||||
return ColumnWidths(
|
return ColumnWidths(
|
||||||
sourceControl: visible.sourceControl ? (widths.sourceControl * k).rounded(.down) : widths.sourceControl,
|
|
||||||
explorer: visible.explorer ? (widths.explorer * k).rounded(.down) : widths.explorer,
|
explorer: visible.explorer ? (widths.explorer * k).rounded(.down) : widths.explorer,
|
||||||
agent: agentIsFixed ? (widths.agent * k).rounded(.down) : widths.agent
|
agent: agentIsFixed ? (widths.agent * k).rounded(.down) : widths.agent
|
||||||
)
|
)
|
||||||
@@ -58,20 +53,18 @@ public enum ColumnLayout {
|
|||||||
|
|
||||||
/// The widest the agent column may be dragged: until the editor would drop below its minimum.
|
/// The widest the agent column may be dragged: until the editor would drop below its minimum.
|
||||||
public static func maxAgentWidth(windowWidth: Double, widths: ColumnWidths, visible: ColumnVisibility) -> Double {
|
public static func maxAgentWidth(windowWidth: Double, widths: ColumnWidths, visible: ColumnVisibility) -> Double {
|
||||||
let others = (visible.sourceControl ? widths.sourceControl : 0) + (visible.explorer ? widths.explorer : 0)
|
let others = visible.explorer ? widths.explorer : 0
|
||||||
return max(minEditorWidth, windowWidth - Double(visible.splitterCount) * splitterWidth - others - minEditorWidth)
|
return max(minEditorWidth, windowWidth - Double(visible.splitterCount) * splitterWidth - others - minEditorWidth)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Which of the four columns are shown. A hidden column keeps its width and its contents.
|
/// Which of the three columns are shown. A hidden column keeps its width and its contents.
|
||||||
public struct ColumnVisibility: Sendable, Equatable {
|
public struct ColumnVisibility: Sendable, Equatable {
|
||||||
public var sourceControl: Bool
|
|
||||||
public var explorer: Bool
|
public var explorer: Bool
|
||||||
public var editor: Bool
|
public var editor: Bool
|
||||||
public var agent: Bool
|
public var agent: Bool
|
||||||
|
|
||||||
public init(sourceControl: Bool = true, explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
|
public init(explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
|
||||||
self.sourceControl = sourceControl
|
|
||||||
self.explorer = explorer
|
self.explorer = explorer
|
||||||
self.editor = editor
|
self.editor = editor
|
||||||
self.agent = agent
|
self.agent = agent
|
||||||
@@ -81,6 +74,6 @@ public struct ColumnVisibility: Sendable, Equatable {
|
|||||||
|
|
||||||
/// One splitter between each pair of neighbouring visible columns.
|
/// One splitter between each pair of neighbouring visible columns.
|
||||||
public var splitterCount: Int {
|
public var splitterCount: Int {
|
||||||
max(0, [sourceControl, explorer, editor, agent].filter { $0 }.count - 1)
|
max(0, [explorer, editor, agent].filter { $0 }.count - 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ public actor GitService: GitServicing {
|
|||||||
private let runner: ProcessRunning
|
private let runner: ProcessRunning
|
||||||
private let statusAttempts: Int
|
private let statusAttempts: Int
|
||||||
private let statusRetryDelay: TimeInterval
|
private let statusRetryDelay: TimeInterval
|
||||||
private let pushTimeout: TimeInterval
|
|
||||||
private let maxDiffBytes: Int
|
private let maxDiffBytes: Int
|
||||||
|
|
||||||
/// Enough overlapping `git show`s to hide process start-up, well under macOS's open-file limit.
|
/// Enough overlapping `git show`s to hide process start-up, well under macOS's open-file limit.
|
||||||
@@ -19,13 +18,12 @@ public actor GitService: GitServicing {
|
|||||||
|
|
||||||
/// `statusAttempts` and `statusRetryDelay` ride out an external tool holding `.git/index.lock`.
|
/// `statusAttempts` and `statusRetryDelay` ride out an external tool holding `.git/index.lock`.
|
||||||
public init(root: URL, runner: ProcessRunning = ProcessRunner(), statusAttempts: Int = 6,
|
public init(root: URL, runner: ProcessRunning = ProcessRunner(), statusAttempts: Int = 6,
|
||||||
statusRetryDelay: TimeInterval = 0.12, pushTimeout: TimeInterval = 120,
|
statusRetryDelay: TimeInterval = 0.12,
|
||||||
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
|
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
|
||||||
self.root = root
|
self.root = root
|
||||||
self.runner = runner
|
self.runner = runner
|
||||||
self.statusAttempts = statusAttempts
|
self.statusAttempts = statusAttempts
|
||||||
self.statusRetryDelay = statusRetryDelay
|
self.statusRetryDelay = statusRetryDelay
|
||||||
self.pushTimeout = pushTimeout
|
|
||||||
self.maxDiffBytes = maxDiffBytes
|
self.maxDiffBytes = maxDiffBytes
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,11 +48,6 @@ public actor GitService: GitServicing {
|
|||||||
return try await startRead()
|
return try await startRead()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The text of `path` in HEAD or in the index; "" when that side has no such file or it is binary.
|
|
||||||
public func contents(of path: String, at revision: GitRevision) async -> String {
|
|
||||||
await Self.blob(revision.prefix + path, root: root, runner: runner, maxBytes: .max).text
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True inside a work tree; falls back to a `.git` on disk so a branch switch mid-probe does not blank the column.
|
/// True inside a work tree; falls back to a `.git` on disk so a branch switch mid-probe does not blank the column.
|
||||||
public func isRepository() async -> Bool {
|
public func isRepository() async -> Bool {
|
||||||
if let result = try? await Self.run(["rev-parse", "--is-inside-work-tree"], root: root, runner: runner),
|
if let result = try? await Self.run(["rev-parse", "--is-inside-work-tree"], root: root, runner: runner),
|
||||||
@@ -64,86 +57,79 @@ public actor GitService: GitServicing {
|
|||||||
return FileManager.default.fileExists(atPath: root.appendingPathComponent(".git").path)
|
return FileManager.default.fileExists(atPath: root.appendingPathComponent(".git").path)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func stage(_ paths: [String]) async throws {
|
/// Prompts, editors and pagers are switched off, so a run can never wait on input: a commit without `-m` aborts.
|
||||||
guard !paths.isEmpty else { return }
|
public func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
|
||||||
try await git(["add", "--"] + paths)
|
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult {
|
||||||
}
|
var environment = ProcessInfo.processInfo.environment.merging(Self.consoleEnvironment) { _, new in new }
|
||||||
|
environment["GIT_LITERAL_PATHSPECS"] = literalPathspecs ? "1" : nil
|
||||||
public func unstage(_ paths: [String]) async throws {
|
|
||||||
guard !paths.isEmpty else { return }
|
|
||||||
let reset = try await Self.run(["reset", "--"] + paths, root: root, runner: runner)
|
|
||||||
if !reset.succeeded {
|
|
||||||
// A repository without commits has no HEAD to reset to.
|
|
||||||
try await git(["rm", "--cached", "-r", "--"] + paths)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func commit(message: String) async throws {
|
|
||||||
try await git(["commit", "-m", message])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pushes; retries once with `-u origin <branch>` when the branch has no upstream.
|
|
||||||
/// Credential prompts are switched off and the whole push gives up after `pushTimeout`.
|
|
||||||
public func push() async -> PushResult {
|
|
||||||
let environment = Self.environment(adding: ["GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"])
|
|
||||||
let runner = self.runner, root = self.root
|
let runner = self.runner, root = self.root
|
||||||
let attempt = Task { () async throws -> ProcessResult in
|
let outcome = await withTaskGroup(of: ExecuteOutcome?.self) { group -> ExecuteOutcome? in
|
||||||
var result = try await runner.run("git", arguments: ["push"], in: root, environment: environment)
|
group.addTask {
|
||||||
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) {
|
do {
|
||||||
let head = try await runner.run("git", arguments: ["rev-parse", "--abbrev-ref", "HEAD"], in: root, environment: environment)
|
return .finished(try await runner.stream("git", arguments: arguments, in: root, environment: environment, onLine: onLine))
|
||||||
let branch = head.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
} catch is CancellationError {
|
||||||
if !branch.isEmpty && branch != "HEAD" {
|
return nil
|
||||||
result = try await runner.run("git", arguments: ["push", "-u", "origin", branch], in: root, environment: environment)
|
} catch let ProcessRunnerError.executableNotFound(name) {
|
||||||
|
return .failed("\(name) not found")
|
||||||
|
} catch let ProcessRunnerError.launchFailed(reason) {
|
||||||
|
return .failed(reason)
|
||||||
|
} catch {
|
||||||
|
return .failed("\(error)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result
|
if let timeout {
|
||||||
|
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
|
||||||
}
|
}
|
||||||
let timeout = Task {
|
switch outcome {
|
||||||
try await Task.sleep(nanoseconds: UInt64(pushTimeout * 1_000_000_000))
|
case let .finished(result):
|
||||||
attempt.cancel()
|
return GitCommandResult(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
|
||||||
}
|
case let .failed(reason):
|
||||||
defer { timeout.cancel() }
|
onLine(reason, true)
|
||||||
do {
|
return GitCommandResult(exitCode: -1, stdout: "", stderr: reason)
|
||||||
let result = try await attempt.value
|
case nil:
|
||||||
return Porcelain.pushSummary(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
|
return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled")
|
||||||
} catch is CancellationError {
|
|
||||||
return PushResult(ok: false, message: "push timed out")
|
|
||||||
} catch {
|
|
||||||
return PushResult(ok: false, message: "\(error)")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A path HEAD has is checked out from HEAD (index and disk); any other path is unstaged
|
public func branches() async -> GitBranchList {
|
||||||
/// and its file deleted. A staged rename also gets its source back. Folders are never deleted.
|
guard let result = try? await Self.run(GitBranchParsing.arguments, root: root, runner: runner), result.succeeded else {
|
||||||
public func discard(_ paths: [String]) async throws {
|
return .empty
|
||||||
let renames = paths.isEmpty ? [:] : try await stagedRenameSources()
|
|
||||||
for path in paths {
|
|
||||||
if let source = renames[path] {
|
|
||||||
_ = try await Self.run(["reset", "-q", "HEAD", "--", source, path], root: root, runner: runner)
|
|
||||||
try await git(["checkout", "HEAD", "--", source])
|
|
||||||
}
|
|
||||||
let known = try await Self.run(["cat-file", "-e", "HEAD:" + path], root: root, runner: runner)
|
|
||||||
if known.succeeded {
|
|
||||||
try await git(["checkout", "HEAD", "--", path])
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
_ = try await Self.run(["reset", "-q", "HEAD", "--", path], root: root, runner: runner)
|
|
||||||
guard let url = fileURL(path) else { continue }
|
|
||||||
var isDirectory: ObjCBool = false
|
|
||||||
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue {
|
|
||||||
try FileManager.default.removeItem(at: url)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return GitBranchParsing.parse(result.stdout)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rename target → source for every rename in the index.
|
/// The name alone when no email is set.
|
||||||
private func stagedRenameSources() async throws -> [String: String] {
|
public func author() async -> String? {
|
||||||
let parsed = Porcelain.parseStatus(try await statusWithRetry())
|
guard let name = await configValue("user.name") else { return nil }
|
||||||
var sources: [String: String] = [:]
|
guard let email = await configValue("user.email") else { return name }
|
||||||
for entry in parsed.entries where entry.isStagedRename {
|
return "\(name) <\(email)>"
|
||||||
sources[entry.path] = entry.originalPath
|
}
|
||||||
}
|
|
||||||
return sources
|
private func configValue(_ key: String) async -> String? {
|
||||||
|
guard let result = try? await Self.run(["config", "--get", key], root: root, runner: runner), result.succeeded else { return nil }
|
||||||
|
let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return value.isEmpty ? nil : value
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum ExecuteOutcome: Sendable {
|
||||||
|
case finished(ProcessResult)
|
||||||
|
case failed(String)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let consoleEnvironment = [
|
||||||
|
"GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never", "GIT_EDITOR": "true", "GIT_PAGER": "cat", "PAGER": "cat",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// "5" for whole seconds, "0.5" otherwise.
|
||||||
|
private static func seconds(_ value: TimeInterval) -> String {
|
||||||
|
value == value.rounded() ? String(Int(value)) : String(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - load
|
// MARK: - load
|
||||||
@@ -166,7 +152,8 @@ public actor GitService: GitServicing {
|
|||||||
let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in
|
let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in
|
||||||
await Self.changes(for: entry, root: root, runner: runner, maxBytes: maxBytes)
|
await Self.changes(for: entry, root: root, runner: runner, maxBytes: maxBytes)
|
||||||
}
|
}
|
||||||
return GitSnapshot(branch: parsed.branch, ahead: parsed.ahead, canPush: parsed.canPush, changes: perEntry.flatMap { $0 })
|
return GitSnapshot(branch: parsed.branch, ahead: parsed.ahead, canPush: parsed.canPush, behind: parsed.behind,
|
||||||
|
upstream: parsed.upstream, changes: perEntry.flatMap { $0 })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An external checkout briefly holds `.git/index.lock`; a status landing then fails, so retry.
|
/// An external checkout briefly holds `.git/index.lock`; a status landing then fails, so retry.
|
||||||
@@ -279,27 +266,10 @@ public actor GitService: GitServicing {
|
|||||||
adding extra: [String: String] = [:]) async throws -> ProcessResult {
|
adding extra: [String: String] = [:]) async throws -> ProcessResult {
|
||||||
try await runner.run("git", arguments: arguments, in: root, environment: environment(adding: extra))
|
try await runner.run("git", arguments: arguments, in: root, environment: environment(adding: extra))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The file for a repository path, or nil for the root itself or a path that escapes it.
|
|
||||||
private func fileURL(_ path: String) -> URL? {
|
|
||||||
let base = root.standardizedFileURL.path
|
|
||||||
let url = root.appendingPathComponent(path).standardizedFileURL
|
|
||||||
return url.path.hasPrefix(base + "/") ? url : nil
|
|
||||||
}
|
|
||||||
|
|
||||||
@discardableResult
|
|
||||||
private func git(_ arguments: [String]) async throws -> String {
|
|
||||||
let result = try await Self.run(arguments, root: root, runner: runner)
|
|
||||||
guard result.succeeded else {
|
|
||||||
throw GitError.commandFailed(arguments: arguments, exitCode: result.exitCode,
|
|
||||||
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
|
|
||||||
}
|
|
||||||
return result.stdout
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Which stored copy of a file `GitService.contents(of:at:)` reads.
|
/// Which stored copy of a file a blob read takes.
|
||||||
public enum GitRevision: Sendable {
|
enum GitRevision: Sendable {
|
||||||
case head
|
case head
|
||||||
case index
|
case index
|
||||||
|
|
||||||
|
|||||||
@@ -6,15 +6,36 @@ public enum GitError: Error, Equatable {
|
|||||||
case commandFailed(arguments: [String], exitCode: Int32, stderr: String)
|
case commandFailed(arguments: [String], exitCode: Int32, stderr: String)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What one `execute` run of git ended with.
|
||||||
|
public struct GitCommandResult: Sendable, Equatable {
|
||||||
|
public var exitCode: Int32
|
||||||
|
public var stdout: String
|
||||||
|
public var stderr: String
|
||||||
|
|
||||||
|
public init(exitCode: Int32, stdout: String, stderr: String) {
|
||||||
|
self.exitCode = exitCode
|
||||||
|
self.stdout = stdout
|
||||||
|
self.stderr = stderr
|
||||||
|
}
|
||||||
|
|
||||||
|
public var succeeded: Bool { exitCode == 0 }
|
||||||
|
}
|
||||||
|
|
||||||
public protocol GitServicing: Sendable {
|
public protocol GitServicing: Sendable {
|
||||||
/// The working state, or nil when the project is not a git repository.
|
/// The working state, or nil when the project is not a git repository.
|
||||||
func load() async throws -> GitSnapshot?
|
func load() async throws -> GitSnapshot?
|
||||||
/// Stages modifications, additions and deletions of the paths.
|
/// Runs `git <arguments>` in the project and streams every output line; never throws (a launch failure is exit code -1 with the reason on stderr).
|
||||||
func stage(_ paths: [String]) async throws
|
func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
|
||||||
func unstage(_ paths: [String]) async throws
|
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult
|
||||||
func commit(message: String) async throws
|
/// Local and origin branches.
|
||||||
/// Never throws: a failed push is a toast, not an error.
|
func branches() async -> GitBranchList
|
||||||
func push() async -> PushResult
|
/// `user.name <user.email>` from git config, nil when unset.
|
||||||
/// Reverts each path to HEAD; a file HEAD does not have is unstaged and deleted, and a staged rename gets its source back.
|
func author() async -> String?
|
||||||
func discard(_ paths: [String]) async throws
|
}
|
||||||
|
|
||||||
|
extension GitServicing {
|
||||||
|
/// Runs with literal pathspecs and no timeout.
|
||||||
|
public func execute(_ arguments: [String], onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult {
|
||||||
|
await execute(arguments, literalPathspecs: true, timeout: nil, onLine: onLine)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import Darwin
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
public struct ProcessResult: Sendable, Equatable {
|
public struct ProcessResult: Sendable, Equatable {
|
||||||
@@ -24,9 +25,21 @@ public protocol ProcessRunning: Sendable {
|
|||||||
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
|
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
|
||||||
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
|
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
|
||||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
|
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
|
||||||
|
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
|
||||||
|
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||||
|
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ProcessRunning {
|
extension ProcessRunning {
|
||||||
|
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
|
||||||
|
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||||
|
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||||
|
let result = try await run(executable, arguments: arguments, in: directory, environment: environment)
|
||||||
|
for line in OutputLines.split(result.stdout) { onLine(line, false) }
|
||||||
|
for line in OutputLines.split(result.stderr) { onLine(line, true) }
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
|
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
|
||||||
try await run(executable, arguments: arguments, in: directory, environment: nil)
|
try await run(executable, arguments: arguments, in: directory, environment: nil)
|
||||||
}
|
}
|
||||||
@@ -40,8 +53,18 @@ public struct ProcessRunner: ProcessRunning {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||||
|
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||||
|
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||||
|
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||||
|
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
|
||||||
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
|
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
|
||||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment)
|
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
|
||||||
return try await withTaskCancellationHandler {
|
return try await withTaskCancellationHandler {
|
||||||
try await withCheckedThrowingContinuation { continuation in
|
try await withCheckedThrowingContinuation { continuation in
|
||||||
job.start(continuation)
|
job.start(continuation)
|
||||||
@@ -52,14 +75,55 @@ public struct ProcessRunner: ProcessRunning {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Splits output into lines on "\n" and "\r", so a progress update ends a line too; empty lines are dropped.
|
||||||
|
enum OutputLines {
|
||||||
|
static func split(_ text: String) -> [String] {
|
||||||
|
text.split(omittingEmptySubsequences: true) { $0 == "\n" || $0 == "\r" || $0 == "\r\n" }.map(String.init)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collects one pipe's bytes and, when streaming, cuts them into lines as they arrive.
|
||||||
|
private final class LineBuffer {
|
||||||
|
private(set) var all = Data()
|
||||||
|
private var pending = Data()
|
||||||
|
|
||||||
|
/// Appends a chunk and returns the lines it completed.
|
||||||
|
func append(_ chunk: Data) -> [String] {
|
||||||
|
all.append(chunk)
|
||||||
|
pending.append(chunk)
|
||||||
|
var lines: [String] = []
|
||||||
|
while let end = pending.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
|
||||||
|
let line = pending[pending.startIndex..<end]
|
||||||
|
if !line.isEmpty { lines.append(String(decoding: line, as: UTF8.self)) }
|
||||||
|
pending.removeSubrange(pending.startIndex...end)
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last line when the output did not end with a line break.
|
||||||
|
func finish() -> String? {
|
||||||
|
defer { pending.removeAll() }
|
||||||
|
return pending.isEmpty ? nil : String(decoding: pending, as: UTF8.self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One child process. Both pipes are drained on their own threads, because a child that
|
/// One child process. Both pipes are drained on their own threads, because a child that
|
||||||
/// fills one pipe while we wait on the other would deadlock.
|
/// fills one pipe while we wait on the other would deadlock.
|
||||||
|
///
|
||||||
|
/// A cancel resumes at once and signals the child and every descendant: a grandchild such as
|
||||||
|
/// `ssh` can hold a pipe open long after the child is gone, so waiting for EOF could hang.
|
||||||
private final class Job: @unchecked Sendable {
|
private final class Job: @unchecked Sendable {
|
||||||
private let process = Process()
|
private let process = Process()
|
||||||
private let lock = NSLock()
|
private let lock = NSLock()
|
||||||
private var cancelled = false
|
private var cancelled = false
|
||||||
|
private var continuation: CheckedContinuation<ProcessResult, Error>?
|
||||||
|
private let onLine: (@Sendable (String, Bool) -> Void)?
|
||||||
|
/// Keeps `onLine` to one call at a time, though both pipes feed it.
|
||||||
|
private let emitLock = NSLock()
|
||||||
|
|
||||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
|
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
|
||||||
|
onLine: (@Sendable (String, Bool) -> Void)?) {
|
||||||
|
self.onLine = onLine
|
||||||
process.executableURL = url
|
process.executableURL = url
|
||||||
process.arguments = arguments
|
process.arguments = arguments
|
||||||
if let directory { process.currentDirectoryURL = directory }
|
if let directory { process.currentDirectoryURL = directory }
|
||||||
@@ -80,53 +144,102 @@ private final class Job: @unchecked Sendable {
|
|||||||
process.terminationHandler = { _ in group.leave() }
|
process.terminationHandler = { _ in group.leave() }
|
||||||
|
|
||||||
lock.lock()
|
lock.lock()
|
||||||
let alreadyCancelled = cancelled
|
if cancelled {
|
||||||
|
lock.unlock()
|
||||||
|
continuation.resume(throwing: CancellationError())
|
||||||
|
return
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
if !alreadyCancelled { try process.run() }
|
try process.run()
|
||||||
} catch {
|
} catch {
|
||||||
lock.unlock()
|
lock.unlock()
|
||||||
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
|
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
self.continuation = continuation
|
||||||
lock.unlock()
|
lock.unlock()
|
||||||
if alreadyCancelled {
|
|
||||||
continuation.resume(throwing: CancellationError())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
group.enter()
|
group.enter()
|
||||||
DispatchQueue.global().async {
|
DispatchQueue.global().async { [self] in
|
||||||
outData = out.fileHandleForReading.readDataToEndOfFile()
|
outData = drain(out.fileHandleForReading, isError: false)
|
||||||
group.leave()
|
group.leave()
|
||||||
}
|
}
|
||||||
group.enter()
|
group.enter()
|
||||||
DispatchQueue.global().async {
|
DispatchQueue.global().async { [self] in
|
||||||
errData = err.fileHandleForReading.readDataToEndOfFile()
|
errData = drain(err.fileHandleForReading, isError: true)
|
||||||
group.leave()
|
group.leave()
|
||||||
}
|
}
|
||||||
group.notify(queue: .global()) { [self, process] in
|
group.notify(queue: .global()) { [self, process] in
|
||||||
if wasCancelled {
|
resume(with: .success(ProcessResult(
|
||||||
continuation.resume(throwing: CancellationError())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
continuation.resume(returning: ProcessResult(
|
|
||||||
exitCode: process.terminationStatus,
|
exitCode: process.terminationStatus,
|
||||||
stdout: String(decoding: outData, as: UTF8.self),
|
stdout: String(decoding: outData, as: UTF8.self),
|
||||||
stderr: String(decoding: errData, as: UTF8.self)
|
stderr: String(decoding: errData, as: UTF8.self)
|
||||||
))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var wasCancelled: Bool {
|
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
|
||||||
|
private func resume(with result: Result<ProcessResult, Error>) {
|
||||||
lock.lock()
|
lock.lock()
|
||||||
defer { lock.unlock() }
|
let pending = continuation
|
||||||
return cancelled
|
continuation = nil
|
||||||
|
lock.unlock()
|
||||||
|
pending?.resume(with: result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a pipe to its end, emitting each line on the way when streaming.
|
||||||
|
private func drain(_ handle: FileHandle, isError: Bool) -> Data {
|
||||||
|
guard let onLine else { return handle.readDataToEndOfFile() }
|
||||||
|
let buffer = LineBuffer()
|
||||||
|
// `read(upToCount:)` waits for the full count; `availableData` returns each chunk as it lands.
|
||||||
|
while true {
|
||||||
|
let chunk = handle.availableData
|
||||||
|
if chunk.isEmpty { break }
|
||||||
|
emit(buffer.append(chunk), isError: isError, onLine)
|
||||||
|
}
|
||||||
|
if let last = buffer.finish() { emit([last], isError: isError, onLine) }
|
||||||
|
return buffer.all
|
||||||
|
}
|
||||||
|
|
||||||
|
private func emit(_ lines: [String], isError: Bool, _ onLine: @Sendable (String, Bool) -> Void) {
|
||||||
|
guard !lines.isEmpty else { return }
|
||||||
|
emitLock.lock()
|
||||||
|
defer { emitLock.unlock() }
|
||||||
|
for line in lines { onLine(line, isError) }
|
||||||
}
|
}
|
||||||
|
|
||||||
func cancel() {
|
func cancel() {
|
||||||
lock.lock()
|
lock.lock()
|
||||||
defer { lock.unlock() }
|
|
||||||
cancelled = true
|
cancelled = true
|
||||||
if process.isRunning { process.terminate() }
|
if process.isRunning {
|
||||||
|
let pid = process.processIdentifier
|
||||||
|
// Descendants first: once the child is gone its children are reparented and out of reach.
|
||||||
|
for descendant in ProcessTree.descendants(of: pid).reversed() { kill(descendant, SIGTERM) }
|
||||||
|
kill(pid, SIGTERM)
|
||||||
|
}
|
||||||
|
lock.unlock()
|
||||||
|
resume(with: .failure(CancellationError()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The process tree below a pid, read through libproc.
|
||||||
|
enum ProcessTree {
|
||||||
|
/// Children before grandchildren.
|
||||||
|
static func descendants(of pid: pid_t) -> [pid_t] {
|
||||||
|
var out: [pid_t] = []
|
||||||
|
var queue = [pid]
|
||||||
|
while !queue.isEmpty {
|
||||||
|
let children = Self.children(of: queue.removeFirst())
|
||||||
|
out += children
|
||||||
|
queue += children
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func children(of pid: pid_t) -> [pid_t] {
|
||||||
|
var buffer = [pid_t](repeating: 0, count: 64)
|
||||||
|
let bytes = proc_listchildpids(pid, &buffer, Int32(buffer.count * MemoryLayout<pid_t>.size))
|
||||||
|
guard bytes > 0 else { return [] }
|
||||||
|
return buffer.filter { $0 > 0 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,16 @@ public struct GroupItem {
|
|||||||
case toggle(isOn: Bool)
|
case toggle(isOn: Bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keeps a button's identity while its label changes, as `Git 3` does.
|
||||||
|
var id: String
|
||||||
var label: String
|
var label: String
|
||||||
var keys: String?
|
var keys: String?
|
||||||
var kind: Kind
|
var kind: Kind
|
||||||
var tip: Text
|
var tip: Text
|
||||||
var action: () -> Void
|
var action: () -> Void
|
||||||
|
|
||||||
public init(_ label: String, keys: String? = nil, kind: Kind, tip: Text, action: @escaping () -> Void) {
|
public init(_ label: String, id: String? = nil, keys: String? = nil, kind: Kind, tip: Text, action: @escaping () -> Void) {
|
||||||
|
self.id = id ?? label
|
||||||
self.label = label
|
self.label = label
|
||||||
self.keys = keys
|
self.keys = keys
|
||||||
self.kind = kind
|
self.kind = kind
|
||||||
@@ -34,7 +37,7 @@ public struct ButtonGroup: View {
|
|||||||
|
|
||||||
public var body: some View {
|
public var body: some View {
|
||||||
HStack(spacing: 0) {
|
HStack(spacing: 0) {
|
||||||
ForEach(Array(items.enumerated()), id: \.element.label) { index, item in
|
ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
|
||||||
GroupButton(item: item, isFirst: index == 0, isLast: index == items.count - 1)
|
GroupButton(item: item, isFirst: index == 0, isLast: index == items.count - 1)
|
||||||
.tip(item.tip, edge: tipEdge)
|
.tip(item.tip, edge: tipEdge)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,15 +50,17 @@ public struct ContextMenuRow: View {
|
|||||||
var shortcut: String?
|
var shortcut: String?
|
||||||
var isHighlighted: Bool
|
var isHighlighted: Bool
|
||||||
var isDestructive: Bool
|
var isDestructive: Bool
|
||||||
|
var isEmphasized: Bool
|
||||||
|
|
||||||
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
|
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
|
||||||
isHighlighted: Bool, isDestructive: Bool = false) {
|
isHighlighted: Bool, isDestructive: Bool = false, isEmphasized: Bool = false) {
|
||||||
self.label = label
|
self.label = label
|
||||||
self.systemImage = systemImage
|
self.systemImage = systemImage
|
||||||
self.iconTint = iconTint
|
self.iconTint = iconTint
|
||||||
self.shortcut = shortcut
|
self.shortcut = shortcut
|
||||||
self.isHighlighted = isHighlighted
|
self.isHighlighted = isHighlighted
|
||||||
self.isDestructive = isDestructive
|
self.isDestructive = isDestructive
|
||||||
|
self.isEmphasized = isEmphasized
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
|
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
|
||||||
@@ -77,7 +79,7 @@ public struct ContextMenuRow: View {
|
|||||||
.foregroundStyle(iconColor)
|
.foregroundStyle(iconColor)
|
||||||
.frame(width: 15)
|
.frame(width: 15)
|
||||||
}
|
}
|
||||||
Text(label).typeRole(isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem)
|
Text(label).typeRole(labelRole)
|
||||||
.foregroundStyle(labelColor)
|
.foregroundStyle(labelColor)
|
||||||
Spacer(minLength: 8)
|
Spacer(minLength: 8)
|
||||||
if let shortcut {
|
if let shortcut {
|
||||||
@@ -95,6 +97,11 @@ public struct ContextMenuRow: View {
|
|||||||
.pointerHand()
|
.pointerHand()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var labelRole: TypeRole {
|
||||||
|
if isEmphasized { return Typography.menuItemEmphasized }
|
||||||
|
return isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem
|
||||||
|
}
|
||||||
|
|
||||||
private var labelColor: Color {
|
private var labelColor: Color {
|
||||||
if isDestructive { return Palette.removedText }
|
if isDestructive { return Palette.removedText }
|
||||||
return isHighlighted ? Palette.text1 : Palette.text3
|
return isHighlighted ? Palette.text1 : Palette.text3
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
/// The frame every overlay sits in: a flat ink scrim (no blur) and a `panel` card with a hairline border,
|
/// The frame every overlay sits in. `.sized` puts a top-aligned `panel` card on a flat ink scrim, and a click
|
||||||
/// radius 8 and the overlay shadow. `.inset` fills the window minus 34pt, up to 1200pt wide; `.sized` centres a fixed-width card
|
/// on the scrim calls `onDismiss`; `.fullScreen` fills the window edge to edge on the slate page, like the Git view.
|
||||||
/// at the top. A click on the scrim calls `onDismiss`.
|
|
||||||
public struct OverlayShell<Content: View>: View {
|
public struct OverlayShell<Content: View>: View {
|
||||||
public enum Placement {
|
public enum Placement {
|
||||||
/// Search, Diff: the whole window minus the 34pt inset, at most `insetOverlayMaxWidth` wide.
|
/// Search: the whole window, title bar and status bar included, with no scrim to click.
|
||||||
case inset
|
case fullScreen
|
||||||
/// A card of this width, top-aligned inside the inset.
|
/// A card of this width, top-aligned inside the inset.
|
||||||
case sized(width: CGFloat)
|
case sized(width: CGFloat)
|
||||||
}
|
}
|
||||||
@@ -15,31 +14,28 @@ public struct OverlayShell<Content: View>: View {
|
|||||||
var onDismiss: () -> Void
|
var onDismiss: () -> Void
|
||||||
var content: Content
|
var content: Content
|
||||||
|
|
||||||
public init(_ placement: Placement = .inset, onDismiss: @escaping () -> Void, @ViewBuilder content: () -> Content) {
|
public init(_ placement: Placement, onDismiss: @escaping () -> Void, @ViewBuilder content: () -> Content) {
|
||||||
self.placement = placement
|
self.placement = placement
|
||||||
self.onDismiss = onDismiss
|
self.onDismiss = onDismiss
|
||||||
self.content = content()
|
self.content = content()
|
||||||
}
|
}
|
||||||
|
|
||||||
public var body: some View {
|
public var body: some View {
|
||||||
ZStack(alignment: .top) {
|
|
||||||
Palette.scrim
|
|
||||||
.contentShape(Rectangle())
|
|
||||||
.onTapGesture(perform: onDismiss)
|
|
||||||
card
|
|
||||||
.padding(Metrics.overlayInset)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ViewBuilder
|
|
||||||
private var card: some View {
|
|
||||||
switch placement {
|
switch placement {
|
||||||
case .inset:
|
case .fullScreen:
|
||||||
OverlayCard { content }
|
content
|
||||||
.frame(maxWidth: Metrics.insetOverlayMaxWidth, maxHeight: .infinity)
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
.background(Palette.editor)
|
||||||
|
.contentShape(Rectangle())
|
||||||
case let .sized(width):
|
case let .sized(width):
|
||||||
OverlayCard { content }
|
ZStack(alignment: .top) {
|
||||||
.frame(width: width)
|
Palette.scrim
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture(perform: onDismiss)
|
||||||
|
OverlayCard { content }
|
||||||
|
.frame(width: width)
|
||||||
|
.padding(Metrics.overlayInset)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ public struct PanelLabel: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A column's header bar: the panel label left, optional trailing content, hairline below.
|
/// A column's header bar: the panel label left, optional trailing content, hairline below.
|
||||||
/// Use it at the top of Explorer, Source Control groups and code panels.
|
/// Use it at the top of Explorer and code panels.
|
||||||
public struct PanelHeader<Trailing: View>: View {
|
public struct PanelHeader<Trailing: View>: View {
|
||||||
var title: String
|
var title: String
|
||||||
var height: CGFloat
|
var height: CGFloat
|
||||||
|
|||||||
@@ -196,9 +196,10 @@ extension PointerPolicy {
|
|||||||
scheduleUpdate(in: window)
|
scheduleUpdate(in: window)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Git view counts as an overlay: it covers every column and its own views sit on the overlay layer.
|
||||||
static func isOverlayOpen(in window: NSWindow?) -> Bool {
|
static func isOverlayOpen(in window: NSWindow?) -> Bool {
|
||||||
guard let window else { return false }
|
guard let window, let model = WorkspaceRegistry.model(for: window) else { return false }
|
||||||
return WorkspaceRegistry.model(for: window)?.overlay.isPresented ?? false
|
return model.overlay.isPresented || model.layout.isGitViewOpen
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-reads the pointer for a mouse that has not moved, once SwiftUI has applied the change that asked for it.
|
/// Re-reads the pointer for a mouse that has not moved, once SwiftUI has applied the change that asked for it.
|
||||||
@@ -420,7 +421,7 @@ final class PointerTracker: NSResponder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension EnvironmentValues {
|
extension EnvironmentValues {
|
||||||
/// The overlay host sets `.overlay`, so the regions inside it keep their pointer while the columns lose theirs.
|
/// The overlay host and the Git view set `.overlay`, so the regions inside them keep their pointer while the columns lose theirs.
|
||||||
@Entry var pointerLayer = PointerLayer.workspace
|
@Entry var pointerLayer = PointerLayer.workspace
|
||||||
/// False under `disabledLook`, whose hit-testing switch SwiftUI does not expose.
|
/// False under `disabledLook`, whose hit-testing switch SwiftUI does not expose.
|
||||||
@Entry var allowsPointerHand = true
|
@Entry var allowsPointerHand = true
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// Pieces shared by the Source Control and Explorer rows.
|
// Pieces of the Explorer rows.
|
||||||
import AppKit
|
import AppKit
|
||||||
import HelderCore
|
import HelderCore
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import AppKit
|
||||||
|
import HelderCore
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Local and origin branches; a click switches, but only while the working tree is clean.
|
||||||
|
struct GitBranchesPanel: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
header
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 0) {
|
||||||
|
group("local")
|
||||||
|
ForEach(store.branches.local, id: \.self) { name in
|
||||||
|
BranchRow(model: model, item: item(name, remote: false))
|
||||||
|
}
|
||||||
|
group("remote · origin")
|
||||||
|
ForEach(store.branches.remote, id: \.self) { name in
|
||||||
|
BranchRow(model: model, item: item(name, remote: true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.bottom, 12)
|
||||||
|
.background(OverlayScrollers())
|
||||||
|
}
|
||||||
|
.scrollIndicators(.automatic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
let count = store.changedPathCount
|
||||||
|
return HStack(spacing: 12) {
|
||||||
|
Text("[ branches ]").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
Text(store.isDirty ? "— \(count) uncommitted file\(count == 1 ? "" : "s") · switching locked" : "clean · click to switch")
|
||||||
|
.typeRole(Typography.path)
|
||||||
|
.foregroundStyle(store.isDirty ? Palette.amberSoft : Palette.textMuted)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
.frame(height: GitMetrics.stripHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func group(_ label: String) -> some View {
|
||||||
|
Text(label)
|
||||||
|
.typeRole(Typography.panelLabel)
|
||||||
|
.foregroundStyle(Palette.text4)
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.top, 8)
|
||||||
|
.padding(.bottom, 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func item(_ name: String, remote: Bool) -> BranchItem {
|
||||||
|
let current = !remote && name == store.state.branch
|
||||||
|
let tracked = remote && store.branches.isTracked(name)
|
||||||
|
let isCurrentUpstream = remote && GitBranchList.localName(ofRemote: name) == store.state.branch
|
||||||
|
let canSwitch = !current && !isCurrentUpstream && !store.isDirty
|
||||||
|
return BranchItem(
|
||||||
|
name: name, remote: remote, current: current, locked: !current && store.isDirty,
|
||||||
|
meta: current ? "current" : (tracked ? "tracked" : ""),
|
||||||
|
action: canSwitch ? (remote && !tracked ? "checkout →" : "switch →") : "",
|
||||||
|
clickable: !current && !isCurrentUpstream
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct BranchItem {
|
||||||
|
let name: String
|
||||||
|
let remote: Bool
|
||||||
|
let current: Bool
|
||||||
|
/// Another branch while the tree is dirty: dimmed, and a click only explains why.
|
||||||
|
let locked: Bool
|
||||||
|
let meta: String
|
||||||
|
let action: String
|
||||||
|
let clickable: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct BranchRow: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let item: BranchItem
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
GitIconView(icon: item.remote ? .cloud : .gitBranch, size: 13)
|
||||||
|
.foregroundStyle(item.current ? Palette.amber : Palette.text4)
|
||||||
|
Text(item.name)
|
||||||
|
.typeRole(item.current ? Typography.branchCurrent : Typography.path)
|
||||||
|
.foregroundStyle(item.current ? Palette.text1 : Palette.text3)
|
||||||
|
.lineLimit(1)
|
||||||
|
.truncationMode(.tail)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
if !item.meta.isEmpty {
|
||||||
|
Text(item.meta).typeRole(Typography.meta).foregroundStyle(Palette.text4).fixedSize()
|
||||||
|
}
|
||||||
|
if !item.action.isEmpty {
|
||||||
|
Text(item.action).typeRole(Typography.gitCount).foregroundStyle(Palette.amber).fixedSize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.leading, 16)
|
||||||
|
.padding(.trailing, 16)
|
||||||
|
.frame(height: GitMetrics.branchRow)
|
||||||
|
.background(isHovered ? Palette.raised : (item.current ? Palette.gitCurrentBranch : .clear))
|
||||||
|
.overlay(alignment: .leading) {
|
||||||
|
Rectangle().fill(item.current ? Palette.amber : .clear).frame(width: GitMetrics.accentBar)
|
||||||
|
}
|
||||||
|
.opacity(item.locked ? 0.4 : 1)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture {
|
||||||
|
guard item.clickable else { return }
|
||||||
|
model.perform(.switchBranch(item.name, remote: item.remote))
|
||||||
|
}
|
||||||
|
.pointerHand(item.clickable && !item.locked)
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
.modifier(LockedTip(isLocked: item.locked))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct LockedTip: ViewModifier {
|
||||||
|
let isLocked: Bool
|
||||||
|
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if isLocked {
|
||||||
|
content.tip("Commit or discard your changes first")
|
||||||
|
} else {
|
||||||
|
content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the enclosing scroll view's scrollers over the content, so rows keep their 16px right padding.
|
||||||
|
/// A legacy scroller would take its width from the rows whenever the list overflows.
|
||||||
|
private struct OverlayScrollers: NSViewRepresentable {
|
||||||
|
func makeNSView(context: Context) -> OverlayScrollersProbe { OverlayScrollersProbe() }
|
||||||
|
func updateNSView(_ view: OverlayScrollersProbe, context: Context) { view.apply() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class OverlayScrollersProbe: NSView {
|
||||||
|
private var observer: NSObjectProtocol?
|
||||||
|
|
||||||
|
override func viewDidMoveToWindow() {
|
||||||
|
super.viewDidMoveToWindow()
|
||||||
|
apply()
|
||||||
|
guard observer == nil, window != nil else { return }
|
||||||
|
observer = NotificationCenter.default.addObserver(
|
||||||
|
forName: NSScroller.preferredScrollerStyleDidChangeNotification, object: nil, queue: .main
|
||||||
|
) { [weak self] _ in
|
||||||
|
MainActor.assumeIsolated { self?.apply() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
if let observer { NotificationCenter.default.removeObserver(observer) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||||
|
|
||||||
|
func apply() {
|
||||||
|
guard let scroll = enclosingScrollView, scroll.scrollerStyle != .overlay else { return }
|
||||||
|
scroll.scrollerStyle = .overlay
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import AppKit
|
||||||
|
import HelderCore
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The message field over the author, the ⌘↵ hint and the Commit split button.
|
||||||
|
struct GitCommitBlock: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
@State private var isFocused = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
GitMessageField(
|
||||||
|
text: store.commitMessage,
|
||||||
|
focusToken: model.focusRequest?.target == .commitMessage ? model.focusRequest?.id : nil,
|
||||||
|
onChange: { store.setCommitMessage($0) },
|
||||||
|
onFocusChange: focusChanged
|
||||||
|
)
|
||||||
|
.background(Palette.editor)
|
||||||
|
.overlay(alignment: .bottom) {
|
||||||
|
Rectangle().fill(isFocused ? Palette.amber : Palette.raised).frame(height: Metrics.hairline)
|
||||||
|
}
|
||||||
|
.animation(Metrics.colorTransition, value: isFocused)
|
||||||
|
HStack(spacing: 16) {
|
||||||
|
if let author = store.author {
|
||||||
|
Text(author).typeRole(Typography.path).foregroundStyle(Palette.textMuted).lineLimit(1)
|
||||||
|
}
|
||||||
|
Text("⌘↵ commits").typeRole(Typography.path).foregroundStyle(Palette.text4).fixedSize()
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
CommitSplitButton(model: model, store: store)
|
||||||
|
}
|
||||||
|
.padding(.leading, 16)
|
||||||
|
.padding(.trailing, 14)
|
||||||
|
.frame(height: GitMetrics.commitFooter)
|
||||||
|
}
|
||||||
|
.background(Palette.panel)
|
||||||
|
.hairline(.bottom)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func focusChanged(_ focused: Bool) {
|
||||||
|
isFocused = focused
|
||||||
|
if focused { model.focusTaken(.commitMessage) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Commit N files` plus a caret that opens Commit / Commit and push. Amber only when git would accept it,
|
||||||
|
/// but both parts always run, so git's own refusal shows in the console.
|
||||||
|
private struct CommitSplitButton: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
@State private var mainHovered = false
|
||||||
|
@State private var caretHovered = false
|
||||||
|
@State private var caretFrame = CGRect.zero
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
let ready = store.canCommitNow
|
||||||
|
let count = store.stagedPathCount
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
Button { model.perform(.commit) } label: {
|
||||||
|
Text(count > 0 ? "Commit \(count) file\(count == 1 ? "" : "s")" : "Nothing staged")
|
||||||
|
.typeRole(Typography.gitCommitButton)
|
||||||
|
.padding(.horizontal, 18)
|
||||||
|
.frame(minWidth: GitMetrics.commitButtonMinWidth)
|
||||||
|
.frame(height: GitMetrics.commitButton)
|
||||||
|
.background(fill(ready: ready, hovered: mainHovered))
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($mainHovered)
|
||||||
|
Button(action: openMenu) {
|
||||||
|
GitIconView(icon: .chevronDown, size: 14)
|
||||||
|
.frame(width: GitMetrics.commitButton, height: GitMetrics.commitButton)
|
||||||
|
.background(fill(ready: ready, hovered: caretHovered))
|
||||||
|
.overlay(alignment: .leading) { Rectangle().fill(Palette.editor).frame(width: Metrics.hairline) }
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($caretHovered)
|
||||||
|
.background(GlobalFrameReader(frame: $caretFrame))
|
||||||
|
}
|
||||||
|
.foregroundStyle(ready ? Palette.badgeText : Palette.textMuted)
|
||||||
|
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||||
|
.fixedSize()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func fill(ready: Bool, hovered: Bool) -> Color {
|
||||||
|
if ready { return hovered ? Palette.amberDeep : Palette.amber }
|
||||||
|
return hovered ? Palette.commitIdleHover : Palette.raised
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menu hangs under the caret, right-aligned to it.
|
||||||
|
private func openMenu() {
|
||||||
|
let anchor = CGPoint(x: caretFrame.maxX - Metrics.contextMenuWidth, y: caretFrame.maxY + 4)
|
||||||
|
model.perform(.showContextMenu(.commitMenu, anchor: anchor))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plex Mono 14/1.6 message field that grows with its wrapped text from 56 to 180pt, measured in `sizeThatFits`.
|
||||||
|
struct GitMessageField: NSViewRepresentable {
|
||||||
|
let text: String
|
||||||
|
/// A new value takes first responder once, a run loop later: opening the view clears first responder first.
|
||||||
|
let focusToken: UUID?
|
||||||
|
let onChange: (String) -> Void
|
||||||
|
let onFocusChange: (Bool) -> Void
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
|
let scroll = NSScrollView()
|
||||||
|
scroll.drawsBackground = false
|
||||||
|
scroll.hasVerticalScroller = true
|
||||||
|
scroll.autohidesScrollers = true
|
||||||
|
scroll.borderType = .noBorder
|
||||||
|
|
||||||
|
let role = Typography.commitMessage
|
||||||
|
let textView = MessageTextView()
|
||||||
|
textView.delegate = context.coordinator
|
||||||
|
textView.drawsBackground = false
|
||||||
|
textView.isRichText = false
|
||||||
|
textView.allowsUndo = true
|
||||||
|
textView.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
|
textView.isAutomaticDashSubstitutionEnabled = false
|
||||||
|
textView.isAutomaticSpellingCorrectionEnabled = false
|
||||||
|
textView.isContinuousSpellCheckingEnabled = false
|
||||||
|
textView.font = role.nsFont
|
||||||
|
textView.textColor = NSColor(hex: 0xF4F5F4)
|
||||||
|
textView.insertionPointColor = NSColor(hex: 0xE8913A)
|
||||||
|
let padding = textView.textContainer?.lineFragmentPadding ?? 5
|
||||||
|
textView.textContainerInset = NSSize(width: GitMetrics.messageInset.width - padding, height: GitMetrics.messageInset.height)
|
||||||
|
textView.isVerticallyResizable = true
|
||||||
|
textView.isHorizontallyResizable = false
|
||||||
|
textView.autoresizingMask = [.width]
|
||||||
|
textView.textContainer?.widthTracksTextView = true
|
||||||
|
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||||
|
textView.fillsClipView = true
|
||||||
|
let paragraph = NSMutableParagraphStyle()
|
||||||
|
paragraph.minimumLineHeight = role.lineHeight ?? 22.4
|
||||||
|
paragraph.maximumLineHeight = role.lineHeight ?? 22.4
|
||||||
|
textView.defaultParagraphStyle = paragraph
|
||||||
|
textView.typingAttributes = [.font: role.nsFont, .foregroundColor: NSColor(hex: 0xF4F5F4), .paragraphStyle: paragraph]
|
||||||
|
textView.placeholder = "Commit message"
|
||||||
|
textView.string = text
|
||||||
|
scroll.documentView = textView
|
||||||
|
context.coordinator.textView = textView
|
||||||
|
return scroll
|
||||||
|
}
|
||||||
|
|
||||||
|
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSScrollView, context: Context) -> CGSize? {
|
||||||
|
let width = proposal.width ?? nsView.frame.width
|
||||||
|
return CGSize(width: width, height: context.coordinator.height(of: text, width: width))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The field height for `text` at `width`: the wrapped lines plus the insets, kept within 56...180pt.
|
||||||
|
static func height(of text: String, width: CGFloat) -> CGFloat {
|
||||||
|
let role = Typography.commitMessage
|
||||||
|
let paragraph = NSMutableParagraphStyle()
|
||||||
|
paragraph.minimumLineHeight = role.lineHeight ?? 22.4
|
||||||
|
paragraph.maximumLineHeight = role.lineHeight ?? 22.4
|
||||||
|
let storage = NSTextStorage(string: text, attributes: [.font: role.nsFont, .paragraphStyle: paragraph])
|
||||||
|
let layout = NSLayoutManager()
|
||||||
|
let textWidth = max(1, width - 2 * GitMetrics.messageInset.width)
|
||||||
|
let container = NSTextContainer(size: NSSize(width: textWidth, height: .greatestFiniteMagnitude))
|
||||||
|
container.lineFragmentPadding = 0
|
||||||
|
layout.addTextContainer(container)
|
||||||
|
storage.addLayoutManager(layout)
|
||||||
|
layout.ensureLayout(for: container)
|
||||||
|
let needed = ceil(layout.usedRect(for: container).height + 2 * GitMetrics.messageInset.height)
|
||||||
|
return min(max(needed, GitMetrics.messageMin), GitMetrics.messageMax)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||||
|
let coordinator = context.coordinator
|
||||||
|
coordinator.parent = self
|
||||||
|
guard let textView = coordinator.textView else { return }
|
||||||
|
textView.pointerLayer = context.environment.pointerLayer
|
||||||
|
textView.onFocusChange = onFocusChange
|
||||||
|
if textView.string != text {
|
||||||
|
textView.string = text
|
||||||
|
}
|
||||||
|
if let focusToken, coordinator.lastFocusToken != focusToken {
|
||||||
|
coordinator.lastFocusToken = focusToken
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
guard let window = textView.window, window.makeFirstResponder(textView) else { return }
|
||||||
|
textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
|
var parent: GitMessageField?
|
||||||
|
weak var textView: MessageTextView?
|
||||||
|
var lastFocusToken: UUID?
|
||||||
|
private var measured: (text: String, width: CGFloat, height: CGFloat)?
|
||||||
|
|
||||||
|
func height(of text: String, width: CGFloat) -> CGFloat {
|
||||||
|
if let measured, measured.text == text, measured.width == width { return measured.height }
|
||||||
|
let height = GitMessageField.height(of: text, width: width)
|
||||||
|
measured = (text, width, height)
|
||||||
|
return height
|
||||||
|
}
|
||||||
|
|
||||||
|
func textDidChange(_ notification: Notification) {
|
||||||
|
guard let textView else { return }
|
||||||
|
let normalized = SourceControlText.normalizeCommitMessage(textView.string)
|
||||||
|
if normalized != textView.string {
|
||||||
|
let caret = textView.selectedRange()
|
||||||
|
textView.string = normalized
|
||||||
|
textView.setSelectedRange(NSRange(location: min(caret.location, (normalized as NSString).length), length: 0))
|
||||||
|
}
|
||||||
|
parent?.onChange(normalized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Draws the placeholder and reports focus.
|
||||||
|
final class MessageTextView: PointerBoundTextView {
|
||||||
|
var placeholder = ""
|
||||||
|
var onFocusChange: ((Bool) -> Void)?
|
||||||
|
|
||||||
|
override func becomeFirstResponder() -> Bool {
|
||||||
|
let accepted = super.becomeFirstResponder()
|
||||||
|
if accepted { onFocusChange?(true) }
|
||||||
|
return accepted
|
||||||
|
}
|
||||||
|
|
||||||
|
override func resignFirstResponder() -> Bool {
|
||||||
|
let accepted = super.resignFirstResponder()
|
||||||
|
if accepted { onFocusChange?(false) }
|
||||||
|
return accepted
|
||||||
|
}
|
||||||
|
|
||||||
|
override func draw(_ dirtyRect: NSRect) {
|
||||||
|
super.draw(dirtyRect)
|
||||||
|
guard string.isEmpty, !placeholder.isEmpty else { return }
|
||||||
|
let attributes: [NSAttributedString.Key: Any] = [
|
||||||
|
.font: font ?? Typography.commitMessage.nsFont, .foregroundColor: NSColor(hex: 0x6C7783),
|
||||||
|
.paragraphStyle: defaultParagraphStyle ?? NSParagraphStyle.default,
|
||||||
|
]
|
||||||
|
let origin = NSPoint(x: textContainerInset.width + (textContainer?.lineFragmentPadding ?? 0), y: textContainerInset.height)
|
||||||
|
(placeholder as NSString).draw(at: origin, withAttributes: attributes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
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
|
||||||
|
let store: SourceControlStore
|
||||||
|
@State private var focusTick = 0
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
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 })
|
||||||
|
.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 }),
|
||||||
|
focusTick: focusTick,
|
||||||
|
onSubmit: { model.perform(.submitConsoleInput) },
|
||||||
|
onUp: { store.recallPreviousInput() }
|
||||||
|
)
|
||||||
|
.frame(maxWidth: .infinity)
|
||||||
|
}
|
||||||
|
.frame(height: Self.inputHeight)
|
||||||
|
Color.clear
|
||||||
|
.frame(maxWidth: .infinity, minHeight: 12, maxHeight: .infinity)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture { focusTick += 1 }
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let inputHeight: CGFloat = 19.2
|
||||||
|
|
||||||
|
private var header: some View {
|
||||||
|
HStack(spacing: 12) {
|
||||||
|
Text("[ console ] git").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
|
||||||
|
if let busy = store.busy {
|
||||||
|
Text(busy == .push ? "→ pushing to origin…" : "→ pulling from origin…")
|
||||||
|
.typeRole(Typography.path)
|
||||||
|
.foregroundStyle(Palette.amber)
|
||||||
|
.lineLimit(1)
|
||||||
|
}
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
EraserButton { store.clearConsole() }
|
||||||
|
}
|
||||||
|
.padding(.leading, 16)
|
||||||
|
.padding(.trailing, 12)
|
||||||
|
.frame(height: GitMetrics.stripHeader)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture { focusTick += 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct EraserButton: View {
|
||||||
|
let action: () -> Void
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: action) {
|
||||||
|
GitIconView(icon: .eraser, size: 14)
|
||||||
|
.foregroundStyle(isHovered ? Palette.text1 : Palette.textMuted)
|
||||||
|
.padding(4)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
.tip("Clear", edge: .trailing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Log
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> ConsoleLogScrollView {
|
||||||
|
let scroll = ConsoleLogScrollView()
|
||||||
|
scroll.drawsBackground = false
|
||||||
|
scroll.hasVerticalScroller = true
|
||||||
|
scroll.autohidesScrollers = true
|
||||||
|
scroll.borderType = .noBorder
|
||||||
|
let textView = ConsoleLogTextView(frame: NSRect(x: 0, y: 0, width: 100, height: 0))
|
||||||
|
textView.isEditable = false
|
||||||
|
textView.isSelectable = true
|
||||||
|
textView.drawsBackground = false
|
||||||
|
textView.isRichText = true
|
||||||
|
textView.textContainerInset = .zero
|
||||||
|
textView.textContainer?.lineFragmentPadding = 0
|
||||||
|
textView.isVerticallyResizable = true
|
||||||
|
textView.isHorizontallyResizable = false
|
||||||
|
textView.autoresizingMask = [.width]
|
||||||
|
textView.textContainer?.widthTracksTextView = true
|
||||||
|
// The container starts as tall as the zero-height frame, which lays out no line at all.
|
||||||
|
textView.textContainer?.containerSize = NSSize(width: 100, height: CGFloat.greatestFiniteMagnitude)
|
||||||
|
textView.minSize = .zero
|
||||||
|
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||||
|
textView.selectedTextAttributes = [.backgroundColor: NSColor(hex: 0x3A424C)]
|
||||||
|
scroll.documentView = textView
|
||||||
|
return scroll
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ scroll: ConsoleLogScrollView, context: Context) {
|
||||||
|
guard let textView = scroll.documentView as? ConsoleLogTextView else { return }
|
||||||
|
textView.pointerLayer = context.environment.pointerLayer
|
||||||
|
textView.onPlainClick = onPlainClick
|
||||||
|
let coordinator = context.coordinator
|
||||||
|
let text = coordinator.text(for: entries)
|
||||||
|
guard coordinator.applied !== text else { return }
|
||||||
|
coordinator.applied = text
|
||||||
|
textView.textStorage?.setAttributedString(text)
|
||||||
|
textView.scrollToEndOfDocument(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sizeThatFits(_ proposal: ProposedViewSize, nsView: ConsoleLogScrollView, context: Context) -> CGSize? {
|
||||||
|
let width = proposal.width ?? nsView.frame.width
|
||||||
|
let height = entries.isEmpty ? 0 : context.coordinator.height(of: entries, width: width)
|
||||||
|
return CGSize(width: width, height: min(height, proposal.height ?? height))
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator {
|
||||||
|
private struct Signature: Equatable {
|
||||||
|
var count: Int
|
||||||
|
var first: Int?
|
||||||
|
var last: Int?
|
||||||
|
}
|
||||||
|
|
||||||
|
var applied: NSAttributedString?
|
||||||
|
private var signature: Signature?
|
||||||
|
private var cached = NSAttributedString()
|
||||||
|
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 {
|
||||||
|
let next = Signature(count: entries.count, first: entries.first?.id, last: entries.last?.id)
|
||||||
|
if next != signature {
|
||||||
|
signature = next
|
||||||
|
cached = Self.build(entries)
|
||||||
|
measured = nil
|
||||||
|
}
|
||||||
|
return cached
|
||||||
|
}
|
||||||
|
|
||||||
|
func height(of entries: [GitConsoleEntry], width: CGFloat) -> CGFloat {
|
||||||
|
let text = text(for: entries)
|
||||||
|
if let measured, measured.width == width { return measured.height }
|
||||||
|
let storage = NSTextStorage(attributedString: text)
|
||||||
|
let layout = NSLayoutManager()
|
||||||
|
let container = NSTextContainer(size: NSSize(width: max(width, 1), height: .greatestFiniteMagnitude))
|
||||||
|
container.lineFragmentPadding = 0
|
||||||
|
layout.addTextContainer(container)
|
||||||
|
storage.addLayoutManager(layout)
|
||||||
|
layout.ensureLayout(for: container)
|
||||||
|
let height = ceil(layout.usedRect(for: container).height)
|
||||||
|
measured = (width, height)
|
||||||
|
return height
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func build(_ entries: [GitConsoleEntry]) -> NSAttributedString {
|
||||||
|
let role = Typography.console
|
||||||
|
let paragraph = NSMutableParagraphStyle()
|
||||||
|
paragraph.minimumLineHeight = role.lineHeight ?? 19.2
|
||||||
|
paragraph.maximumLineHeight = role.lineHeight ?? 19.2
|
||||||
|
paragraph.lineBreakMode = .byCharWrapping
|
||||||
|
paragraph.tabStops = []
|
||||||
|
paragraph.defaultTabInterval = 4 * (" " as NSString).size(withAttributes: [.font: role.nsFont]).width
|
||||||
|
// AppKit puts a fixed line's spare height above the glyphs; this centres them like the `$ git` row.
|
||||||
|
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")
|
||||||
|
out.append(NSAttributedString(string: line, attributes: [
|
||||||
|
.font: role.nsFont, .foregroundColor: NSColor(Palette.console(entry.line.kind)), .paragraphStyle: paragraph,
|
||||||
|
.baselineOffset: max(0, spare / 2),
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Grows with each new line; every resize lands on the newest line.
|
||||||
|
private final class ConsoleLogScrollView: NSScrollView {
|
||||||
|
override func setFrameSize(_ newSize: NSSize) {
|
||||||
|
let grew = newSize.height != frame.height
|
||||||
|
super.setFrameSize(newSize)
|
||||||
|
if grew { documentView?.scrollToEndOfDocument(nil) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A click that leaves no selection hands the keyboard to the input line.
|
||||||
|
private final class ConsoleLogTextView: PointerBoundTextView {
|
||||||
|
var onPlainClick: () -> Void = {}
|
||||||
|
|
||||||
|
override func mouseDown(with event: NSEvent) {
|
||||||
|
super.mouseDown(with: event)
|
||||||
|
if selectedRange().length == 0 { onPlainClick() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Input
|
||||||
|
|
||||||
|
/// The borderless input after `$ git`: ↵ runs it, ↑ recalls the last command. It never takes focus on its own.
|
||||||
|
private struct ConsoleInputField: NSViewRepresentable {
|
||||||
|
@Binding var text: String
|
||||||
|
let focusTick: Int
|
||||||
|
let onSubmit: () -> Void
|
||||||
|
let onUp: () -> Void
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> ConsoleFieldBox {
|
||||||
|
let font = Typography.console.nsFont
|
||||||
|
let field = NSTextField()
|
||||||
|
field.cell = ConsoleFieldCell(textCell: "")
|
||||||
|
field.isBordered = false
|
||||||
|
field.isEditable = true
|
||||||
|
field.isSelectable = true
|
||||||
|
field.drawsBackground = false
|
||||||
|
field.focusRingType = .none
|
||||||
|
field.font = font
|
||||||
|
field.textColor = NSColor(hex: 0xF4F5F4)
|
||||||
|
field.placeholderAttributedString = NSAttributedString(
|
||||||
|
string: "status · add -A · commit -m \"…\" · push · pull · log",
|
||||||
|
attributes: [.foregroundColor: NSColor(hex: 0x6C7783), .font: font]
|
||||||
|
)
|
||||||
|
field.stringValue = text
|
||||||
|
field.delegate = context.coordinator
|
||||||
|
field.cell?.isScrollable = true
|
||||||
|
field.cell?.wraps = false
|
||||||
|
context.coordinator.lastFocusTick = focusTick
|
||||||
|
return ConsoleFieldBox(field: field)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ box: ConsoleFieldBox, context: Context) {
|
||||||
|
let coordinator = context.coordinator
|
||||||
|
coordinator.parent = self
|
||||||
|
box.pointerLayer = context.environment.pointerLayer
|
||||||
|
(box.field.cell as? ConsoleFieldCell)?.pointerLayer = context.environment.pointerLayer
|
||||||
|
if box.field.stringValue != text {
|
||||||
|
box.field.stringValue = text
|
||||||
|
if let editor = box.field.currentEditor() {
|
||||||
|
editor.selectedRange = NSRange(location: (text as NSString).length, length: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if coordinator.lastFocusTick != focusTick {
|
||||||
|
coordinator.lastFocusTick = focusTick
|
||||||
|
DispatchQueue.main.async { box.focus() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTextFieldDelegate {
|
||||||
|
var parent: ConsoleInputField
|
||||||
|
var lastFocusTick = 0
|
||||||
|
|
||||||
|
init(_ parent: ConsoleInputField) {
|
||||||
|
self.parent = parent
|
||||||
|
}
|
||||||
|
|
||||||
|
func controlTextDidChange(_ note: Notification) {
|
||||||
|
guard let field = note.object as? NSTextField else { return }
|
||||||
|
parent.text = field.stringValue
|
||||||
|
}
|
||||||
|
|
||||||
|
func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
|
||||||
|
switch selector {
|
||||||
|
case #selector(NSResponder.insertNewline(_:)):
|
||||||
|
parent.onSubmit()
|
||||||
|
return true
|
||||||
|
case #selector(NSResponder.moveUp(_:)):
|
||||||
|
parent.onUp()
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 {
|
||||||
|
let field: NSTextField
|
||||||
|
var pointerLayer = PointerLayer.overlay {
|
||||||
|
didSet { if pointerLayer != oldValue { PointerPolicy.setNeedsRefresh(in: window) } }
|
||||||
|
}
|
||||||
|
private lazy var pointerTracker = PointerTracker(view: self)
|
||||||
|
|
||||||
|
init(field: NSTextField) {
|
||||||
|
self.field = field
|
||||||
|
super.init(frame: .zero)
|
||||||
|
addSubview(field)
|
||||||
|
}
|
||||||
|
|
||||||
|
required init?(coder: NSCoder) {
|
||||||
|
fatalError("ConsoleFieldBox is built in code")
|
||||||
|
}
|
||||||
|
|
||||||
|
func focus() {
|
||||||
|
guard let window, field.currentEditor() == nil else { return }
|
||||||
|
window.makeFirstResponder(field)
|
||||||
|
field.currentEditor()?.selectedRange = NSRange(location: (field.stringValue as NSString).length, length: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func layout() {
|
||||||
|
super.layout()
|
||||||
|
let height = min(field.intrinsicContentSize.height, bounds.height)
|
||||||
|
field.frame = NSRect(x: 0, y: ((bounds.height - height) / 2).rounded(), width: bounds.width, height: height)
|
||||||
|
}
|
||||||
|
|
||||||
|
var acceptsPointerText: Bool { field.isEnabled }
|
||||||
|
|
||||||
|
func isPointerOverText(atWindowPoint point: NSPoint) -> Bool {
|
||||||
|
isTopmost(atWindowPoint: point)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||||
|
|
||||||
|
override func resetCursorRects() {
|
||||||
|
addPointerCursorRect(bounds)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func updateTrackingAreas() {
|
||||||
|
super.updateTrackingAreas()
|
||||||
|
pointerTracker.update()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setFrameOrigin(_ newOrigin: NSPoint) {
|
||||||
|
super.setFrameOrigin(newOrigin)
|
||||||
|
pointerTracker.update()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setFrameSize(_ newSize: NSSize) {
|
||||||
|
super.setFrameSize(newSize)
|
||||||
|
pointerTracker.update()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewDidMoveToWindow() {
|
||||||
|
super.viewDidMoveToWindow()
|
||||||
|
pointerTracker.update()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func mouseDown(with event: NSEvent) {
|
||||||
|
focus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edits through a PointerBoundTextView with the amber caret, instead of the window's shared field editor.
|
||||||
|
private final class ConsoleFieldCell: NSTextFieldCell {
|
||||||
|
var pointerLayer = PointerLayer.overlay {
|
||||||
|
didSet { editor.pointerLayer = pointerLayer }
|
||||||
|
}
|
||||||
|
|
||||||
|
private lazy var editor: GitConsoleFieldEditor = {
|
||||||
|
let editor = GitConsoleFieldEditor()
|
||||||
|
editor.isFieldEditor = true
|
||||||
|
editor.pointerLayer = pointerLayer
|
||||||
|
editor.insertionPointColor = NSColor(hex: 0xE8913A)
|
||||||
|
return editor
|
||||||
|
}()
|
||||||
|
|
||||||
|
override func fieldEditor(for controlView: NSView) -> NSTextView? {
|
||||||
|
editor
|
||||||
|
}
|
||||||
|
|
||||||
|
override func setUpFieldEditorAttributes(_ textObj: NSText) -> NSText {
|
||||||
|
let text = super.setUpFieldEditorAttributes(textObj)
|
||||||
|
(text as? NSTextView)?.insertionPointColor = NSColor(hex: 0xE8913A)
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The console input's field editor; the key router tells the console apart from the message field by it.
|
||||||
|
final class GitConsoleFieldEditor: PointerBoundTextView {}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The Git view's Lucide icons, drawn on Lucide's 24-unit grid at stroke 1.75.
|
||||||
|
/// Icons with arcs Lucide draws as curves (cloud, eraser) use the nearest SF Symbol.
|
||||||
|
enum GitIcon {
|
||||||
|
case gitBranch, cloud, arrowDownToLine, arrowUpFromLine, minimize, chevronDown, chevronRight, eraser, check
|
||||||
|
|
||||||
|
fileprivate var symbol: String? {
|
||||||
|
switch self {
|
||||||
|
case .cloud: "cloud"
|
||||||
|
case .eraser: "eraser"
|
||||||
|
default: nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fileprivate func path(_ k: CGFloat) -> Path {
|
||||||
|
func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: x * k, y: y * k) }
|
||||||
|
var path = Path()
|
||||||
|
func line(_ points: (CGFloat, CGFloat)...) {
|
||||||
|
path.move(to: p(points[0].0, points[0].1))
|
||||||
|
for point in points.dropFirst() { path.addLine(to: p(point.0, point.1)) }
|
||||||
|
}
|
||||||
|
switch self {
|
||||||
|
case .gitBranch:
|
||||||
|
line((6, 3), (6, 15))
|
||||||
|
path.addEllipse(in: CGRect(x: 15 * k, y: 3 * k, width: 6 * k, height: 6 * k))
|
||||||
|
path.addEllipse(in: CGRect(x: 3 * k, y: 15 * k, width: 6 * k, height: 6 * k))
|
||||||
|
path.move(to: p(18, 9))
|
||||||
|
path.addQuadCurve(to: p(9, 18), control: p(18, 18))
|
||||||
|
case .arrowDownToLine:
|
||||||
|
line((12, 17), (12, 3))
|
||||||
|
line((6, 11), (12, 17), (18, 11))
|
||||||
|
line((19, 21), (5, 21))
|
||||||
|
case .arrowUpFromLine:
|
||||||
|
line((18, 9), (12, 3), (6, 9))
|
||||||
|
line((12, 3), (12, 17))
|
||||||
|
line((5, 21), (19, 21))
|
||||||
|
case .minimize:
|
||||||
|
line((14, 10), (21, 3))
|
||||||
|
line((20, 10), (14, 10), (14, 4))
|
||||||
|
line((3, 21), (10, 14))
|
||||||
|
line((4, 14), (10, 14), (10, 20))
|
||||||
|
case .chevronDown:
|
||||||
|
line((6, 9), (12, 15), (18, 9))
|
||||||
|
case .chevronRight:
|
||||||
|
line((9, 18), (15, 12), (9, 6))
|
||||||
|
case .check:
|
||||||
|
line((20, 6), (9, 17), (4, 12))
|
||||||
|
case .cloud, .eraser:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GitIconView: View {
|
||||||
|
let icon: GitIcon
|
||||||
|
var size: CGFloat = 14
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
if let symbol = icon.symbol {
|
||||||
|
Image(systemName: symbol)
|
||||||
|
.font(.system(size: size * 0.82, weight: .light))
|
||||||
|
.frame(width: size, height: size)
|
||||||
|
} else {
|
||||||
|
icon.path(size / 24)
|
||||||
|
.stroke(style: StrokeStyle(lineWidth: 1.75 * size / 24, lineCap: .round, lineJoin: .round))
|
||||||
|
.frame(width: size, height: size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,400 @@
|
|||||||
|
import HelderCore
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The four colour-coded sections, Staged on top. Rows and inline diff lines are one flat lazy list,
|
||||||
|
/// so a long expanded file only builds the lines on screen.
|
||||||
|
struct GitSectionsList: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ScrollView {
|
||||||
|
LazyVStack(alignment: .leading, spacing: 0) {
|
||||||
|
ForEach(items) { item in
|
||||||
|
switch item.kind {
|
||||||
|
case let .message(text):
|
||||||
|
Text(text)
|
||||||
|
.typeRole(Typography.gitEmpty)
|
||||||
|
.foregroundStyle(Palette.textMuted)
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.vertical, 24)
|
||||||
|
case let .header(section, separated):
|
||||||
|
GitSectionHeader(model: model, store: store, section: section)
|
||||||
|
.padding(.top, separated ? GitMetrics.sectionGap : 0)
|
||||||
|
.overlay(alignment: .top) { if separated { Hairline() } }
|
||||||
|
case let .row(kind, row):
|
||||||
|
GitFileRow(model: model, store: store, kind: kind, row: row)
|
||||||
|
case let .diffLine(row):
|
||||||
|
InlineDiffLine(row: row)
|
||||||
|
case let .diffNote(text):
|
||||||
|
Text(text)
|
||||||
|
.typeRole(Typography.meta)
|
||||||
|
.foregroundStyle(Palette.text4)
|
||||||
|
.padding(.leading, 64)
|
||||||
|
.frame(maxWidth: .infinity, minHeight: GitMetrics.diffLine, alignment: .leading)
|
||||||
|
case .diffTop:
|
||||||
|
Color.clear.frame(height: 8)
|
||||||
|
case .diffBottom:
|
||||||
|
Color.clear.frame(height: 12).hairline(.bottom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(.bottom, 24)
|
||||||
|
}
|
||||||
|
.scrollIndicators(.automatic)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var items: [GitListItem] {
|
||||||
|
if store.hasLoaded && !store.state.isRepository { return [GitListItem(id: "empty", kind: .message("— Not a git repository."))] }
|
||||||
|
if store.sections.isEmpty {
|
||||||
|
return store.hasLoaded ? [GitListItem(id: "empty", kind: .message("— No changes. The working tree is clean."))] : []
|
||||||
|
}
|
||||||
|
var items: [GitListItem] = []
|
||||||
|
for (index, section) in store.sections.enumerated() {
|
||||||
|
let separated = index == 1 && store.sections[0].kind == .staged
|
||||||
|
items.append(GitListItem(id: "h:" + section.id, kind: .header(section, separated: separated)))
|
||||||
|
guard !store.isCollapsed(section.kind) else { continue }
|
||||||
|
for row in section.rows {
|
||||||
|
let key = SourceControlStore.rowKey(section.kind, row)
|
||||||
|
items.append(GitListItem(id: "r:" + key, kind: .row(section.kind, row)))
|
||||||
|
guard store.isExpanded(section.kind, row) else { continue }
|
||||||
|
items.append(GitListItem(id: "t:" + key, kind: .diffTop))
|
||||||
|
switch store.detail(for: row) {
|
||||||
|
case .tooBig:
|
||||||
|
items.append(GitListItem(id: "n:" + key, kind: .diffNote("Too big.")))
|
||||||
|
case let .rows(lines) where lines.isEmpty:
|
||||||
|
items.append(GitListItem(id: "n:" + key, kind: .diffNote("— No line changes.")))
|
||||||
|
case let .rows(lines):
|
||||||
|
for (offset, line) in lines.enumerated() {
|
||||||
|
items.append(GitListItem(id: "d:\(key):\(offset)", kind: .diffLine(line)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items.append(GitListItem(id: "b:" + key, kind: .diffBottom))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct GitListItem: Identifiable {
|
||||||
|
enum Kind {
|
||||||
|
case message(String)
|
||||||
|
case header(GitSection, separated: Bool)
|
||||||
|
case row(GitSectionKind, Change)
|
||||||
|
case diffTop
|
||||||
|
case diffLine(InlineDiffRow)
|
||||||
|
case diffNote(String)
|
||||||
|
case diffBottom
|
||||||
|
}
|
||||||
|
|
||||||
|
let id: String
|
||||||
|
let kind: Kind
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Section look
|
||||||
|
|
||||||
|
/// What a section is called, how it is coloured, and which bulk and row actions it offers.
|
||||||
|
private struct SectionStyle {
|
||||||
|
let label: String
|
||||||
|
let color: Color
|
||||||
|
let tint: Color
|
||||||
|
|
||||||
|
init(_ kind: GitSectionKind) {
|
||||||
|
switch kind {
|
||||||
|
case .staged: (label, color, tint) = ("staged", Palette.amber, Palette.gitStagedTint)
|
||||||
|
case .changed: (label, color, tint) = ("changed", Palette.gitModified, Palette.gitModifiedTint)
|
||||||
|
case .untracked: (label, color, tint) = ("new · untracked", Palette.gitNew, Palette.gitNewTint)
|
||||||
|
case .deleted: (label, color, tint) = ("deleted", Palette.gitDeleted, Palette.gitDeletedTint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct GitAction {
|
||||||
|
let label: String
|
||||||
|
let isDestructive: Bool
|
||||||
|
let command: Command
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Left then right; a lone action, such as `Unstage`, always lands in the right column.
|
||||||
|
/// Conflicted rows get no Discard: staging them is how a resolution is marked.
|
||||||
|
private func actions(_ kind: GitSectionKind, rows: [Change], bulk: Bool) -> [GitAction] {
|
||||||
|
let all = bulk ? " all" : ""
|
||||||
|
let paths = GitSections.uniquePaths(rows)
|
||||||
|
let stage = GitAction(label: "Stage" + all, isDestructive: false, command: .stage(paths))
|
||||||
|
switch kind {
|
||||||
|
case .staged: return [GitAction(label: "Unstage" + all, isDestructive: false, command: .unstage(paths))]
|
||||||
|
case .changed:
|
||||||
|
let discardable = GitSections.uniquePaths(rows.filter { $0.status != .unmerged })
|
||||||
|
guard !discardable.isEmpty else { return [stage] }
|
||||||
|
return [GitAction(label: "Discard" + all, isDestructive: true, command: .context(.gitDiscard(discardable))), stage]
|
||||||
|
case .untracked: return [GitAction(label: "Delete" + all, isDestructive: true, command: .context(.gitDiscard(paths))), stage]
|
||||||
|
case .deleted: return [GitAction(label: "Restore" + all, isDestructive: false, command: .context(.gitDiscard(paths))), stage]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two 100pt columns, identical in headers and rows so the buttons line up.
|
||||||
|
private struct ActionsTable: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let actions: [GitAction]
|
||||||
|
let isHeader: Bool
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: GitMetrics.actionGap) {
|
||||||
|
if actions.count < 2 { Color.clear.frame(width: GitMetrics.actionWidth, height: 1) }
|
||||||
|
ForEach(Array(actions.enumerated()), id: \.offset) { _, action in
|
||||||
|
GitActionButton(action: action, isHeader: isHeader) { model.perform(action.command) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct GitActionButton: View {
|
||||||
|
let action: GitAction
|
||||||
|
let isHeader: Bool
|
||||||
|
let perform: () -> Void
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: perform) {
|
||||||
|
Text(action.label)
|
||||||
|
.typeRole(Typography.button)
|
||||||
|
.foregroundStyle(textColor)
|
||||||
|
.frame(width: GitMetrics.actionWidth, height: isHeader ? GitMetrics.headerAction : GitMetrics.rowAction)
|
||||||
|
.background(isHovered ? Palette.raised : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||||
|
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(borderColor, lineWidth: Metrics.hairline))
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var textColor: Color {
|
||||||
|
if !isHeader && isHovered { return Palette.text1 }
|
||||||
|
return action.isDestructive ? Palette.amberSoft : Palette.text3
|
||||||
|
}
|
||||||
|
|
||||||
|
private var borderColor: Color {
|
||||||
|
if isHeader { return isHovered ? Palette.text4 : Palette.text5 }
|
||||||
|
return isHovered ? Palette.text5 : .clear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Header
|
||||||
|
|
||||||
|
private struct GitSectionHeader: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
let section: GitSection
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
let style = SectionStyle(section.kind)
|
||||||
|
let open = !store.isCollapsed(section.kind)
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
GitIconView(icon: open ? .chevronDown : .chevronRight, size: 14)
|
||||||
|
.foregroundStyle(open ? Palette.amber : Palette.text4)
|
||||||
|
Text(style.label).typeRole(Typography.gitLabel).foregroundStyle(style.color).lineLimit(1).fixedSize()
|
||||||
|
Text("\(section.rows.count)")
|
||||||
|
.typeRole(Typography.gitCount)
|
||||||
|
.foregroundStyle(Palette.badgeText)
|
||||||
|
.padding(.horizontal, 6)
|
||||||
|
.padding(.vertical, 3)
|
||||||
|
.background(style.color, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
ActionsTable(model: model, actions: actions(section.kind, rows: section.rows, bulk: true),
|
||||||
|
isHeader: true)
|
||||||
|
}
|
||||||
|
.padding(.leading, 14)
|
||||||
|
.padding(.trailing, 14)
|
||||||
|
.frame(height: GitMetrics.sectionHeader)
|
||||||
|
.background(isHovered ? Palette.panel : style.tint)
|
||||||
|
.overlay(alignment: .leading) { Rectangle().fill(style.color).frame(width: GitMetrics.accentBar) }
|
||||||
|
.hairline(.bottom)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture { store.toggleSection(section.kind) }
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: File row
|
||||||
|
|
||||||
|
private struct GitFileRow: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
let kind: GitSectionKind
|
||||||
|
let row: Change
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
let expanded = store.isExpanded(kind, row)
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
GitIconView(icon: expanded ? .chevronDown : .chevronRight, size: 13)
|
||||||
|
.foregroundStyle(expanded ? Palette.amber : Palette.text4)
|
||||||
|
StatusBadge(status: row.status)
|
||||||
|
path
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
Text("+\(row.added)").foregroundStyle(Palette.gitNew)
|
||||||
|
.frame(width: GitMetrics.statWidth, alignment: .trailing)
|
||||||
|
Text("\u{2212}\(row.removed)").foregroundStyle(Palette.gitModified)
|
||||||
|
.frame(width: GitMetrics.statWidth - 8, alignment: .trailing)
|
||||||
|
.padding(.trailing, 8)
|
||||||
|
}
|
||||||
|
.typeRole(Typography.gitStats)
|
||||||
|
.lineLimit(1)
|
||||||
|
ActionsTable(model: model, actions: actions(kind, rows: [row], bulk: false), isHeader: false)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 14)
|
||||||
|
.frame(height: GitMetrics.fileRow)
|
||||||
|
.background(expanded ? Palette.panel : (isHovered ? Palette.gitRowHover : .clear))
|
||||||
|
.overlay(alignment: .leading) {
|
||||||
|
Rectangle().fill(kind == .staged ? Palette.amber : .clear).frame(width: GitMetrics.accentBar)
|
||||||
|
}
|
||||||
|
.hairline(.bottom)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
.onTapGesture { store.toggleRow(kind, row) }
|
||||||
|
.pointerHand()
|
||||||
|
.overlay(RightClickArea { point in
|
||||||
|
model.perform(.showContextMenu(.gitRow(path: row.path, isDeleted: row.isDeleted), anchor: point))
|
||||||
|
})
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The folder and slash muted, the name bright; a deleted file is struck through with a muted name.
|
||||||
|
private var path: some View {
|
||||||
|
let dir = PathUtils.dirname(row.path)
|
||||||
|
let name = PathUtils.basename(row.path)
|
||||||
|
let dirText = Text(dir.isEmpty ? "" : dir + "/").foregroundColor(Palette.textMuted)
|
||||||
|
let nameText = Text(name).foregroundColor(row.isDeleted ? Palette.textMuted : Palette.text1)
|
||||||
|
return (dirText + nameText)
|
||||||
|
.strikethrough(row.isDeleted, color: Palette.textMuted)
|
||||||
|
.typeRole(Typography.gitPath)
|
||||||
|
.lineLimit(1)
|
||||||
|
.truncationMode(.tail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct StatusBadge: View {
|
||||||
|
let status: GitStatus
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Text(status.rawValue)
|
||||||
|
.typeRole(Typography.gitStatusLetter)
|
||||||
|
.foregroundStyle(Palette.badgeText)
|
||||||
|
.frame(width: GitMetrics.statusBadge, height: GitMetrics.statusBadge)
|
||||||
|
.background(color, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||||
|
.tip(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var color: Color {
|
||||||
|
switch status {
|
||||||
|
case .added: Palette.gitNew
|
||||||
|
case .deleted: Palette.gitDeleted
|
||||||
|
case .modified, .renamed, .unmerged: Palette.gitModified
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var name: String {
|
||||||
|
switch status {
|
||||||
|
case .added: "New file"
|
||||||
|
case .deleted: "Deleted"
|
||||||
|
case .modified: "Modified"
|
||||||
|
case .renamed: "Renamed"
|
||||||
|
case .unmerged: "Conflict"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Inline diff
|
||||||
|
|
||||||
|
/// One side-by-side line, last commit left and working tree right, or a folded run of unchanged lines.
|
||||||
|
private struct InlineDiffLine: View {
|
||||||
|
let row: InlineDiffRow
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
switch row {
|
||||||
|
case let .gap(count):
|
||||||
|
Text("⋯ \(count) unchanged line\(count == 1 ? "" : "s")")
|
||||||
|
.typeRole(Typography.meta)
|
||||||
|
.foregroundStyle(Palette.text4)
|
||||||
|
.padding(.leading, 64)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.frame(height: GitMetrics.diffGap)
|
||||||
|
.background(Palette.panel)
|
||||||
|
.padding(.vertical, 6)
|
||||||
|
case let .line(left, right):
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
InlineDiffCellView(cell: left, side: .left)
|
||||||
|
Hairline(.vertical)
|
||||||
|
InlineDiffCellView(cell: right, side: .right)
|
||||||
|
}
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum DiffSide {
|
||||||
|
case left, right
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct InlineDiffCellView: View {
|
||||||
|
let cell: InlineDiffCell?
|
||||||
|
let side: DiffSide
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(alignment: .top, spacing: 0) {
|
||||||
|
Text(cell.map { String($0.number) } ?? "")
|
||||||
|
.foregroundStyle(numberColor)
|
||||||
|
.frame(width: GitMetrics.diffGutter - 12, alignment: .trailing)
|
||||||
|
.padding(.trailing, 12)
|
||||||
|
Text(code)
|
||||||
|
.foregroundStyle(Palette.text2)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.padding(.trailing, 16)
|
||||||
|
}
|
||||||
|
.typeRole(Typography.inlineDiff)
|
||||||
|
.padding(.vertical, Self.verticalPad)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||||
|
.background(fill)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Centres a single line in its 22pt box; `typeRole` only spaces the lines after the first.
|
||||||
|
private static let verticalPad: CGFloat = {
|
||||||
|
let font = Typography.inlineDiff.nsFont
|
||||||
|
return max(0, (GitMetrics.diffLine - (font.ascender - font.descender + font.leading)) / 2)
|
||||||
|
}()
|
||||||
|
|
||||||
|
private var fill: Color {
|
||||||
|
guard let cell else { return Palette.inlineFiller }
|
||||||
|
switch cell.mark {
|
||||||
|
case .removed: return Palette.inlineRemovedFill
|
||||||
|
case .added: return Palette.inlineAddedFill
|
||||||
|
case nil: return .clear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var numberColor: Color {
|
||||||
|
switch cell?.mark {
|
||||||
|
case .removed: Palette.gitModified
|
||||||
|
case .added: Palette.gitNew
|
||||||
|
case nil: Palette.text5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tabs show four wide; the differing middle of a paired line gets its highlight.
|
||||||
|
private var code: AttributedString {
|
||||||
|
guard let cell else { return AttributedString() }
|
||||||
|
let characters = Array(cell.text)
|
||||||
|
func piece(_ range: Range<Int>) -> AttributedString {
|
||||||
|
AttributedString(String(characters[range]).replacingOccurrences(of: "\t", with: " "))
|
||||||
|
}
|
||||||
|
guard let highlight = cell.highlight, highlight.upperBound <= characters.count else {
|
||||||
|
return piece(0..<characters.count)
|
||||||
|
}
|
||||||
|
var middle = piece(highlight)
|
||||||
|
middle.backgroundColor = side == .left ? Palette.inlineRemovedHighlight : Palette.inlineAddedHighlight
|
||||||
|
return piece(0..<highlight.lowerBound) + middle + piece(highlight.upperBound..<characters.count)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import HelderCore
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// `[ git ]`, the branch and its place against origin, then Pull, Push and Close.
|
||||||
|
struct GitTopBar: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
let state = store.state
|
||||||
|
HStack(spacing: 14) {
|
||||||
|
Text("[ git ]").typeRole(Typography.gitLabel).foregroundStyle(Palette.textMuted).fixedSize()
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
GitIconView(icon: .gitBranch, size: 13)
|
||||||
|
Text(state.branch).typeRole(Typography.branch).lineLimit(1).truncationMode(.tail)
|
||||||
|
}
|
||||||
|
.foregroundStyle(Palette.amber)
|
||||||
|
Text(store.syncLabel).typeRole(Typography.path).foregroundStyle(Palette.textMuted).lineLimit(1).fixedSize()
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
GitBarButton(icon: .arrowDownToLine, label: store.busy == .pull ? "Pulling…" : "Pull",
|
||||||
|
trailing: state.behind > 0 ? "↓\(state.behind)" : nil) { model.perform(.pull) }
|
||||||
|
GitBarButton(icon: .arrowUpFromLine, label: store.busy == .push ? "Pushing…" : "Push",
|
||||||
|
trailing: state.ahead > 0 ? "↑\(state.ahead)" : nil) { model.perform(.push) }
|
||||||
|
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘G") { model.perform(.closeGitView) }
|
||||||
|
}
|
||||||
|
.padding(.horizontal, 14)
|
||||||
|
.frame(height: GitMetrics.topBar)
|
||||||
|
.background(Palette.panel)
|
||||||
|
.hairline(.bottom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 28pt bordered button with an icon, a label and an amber mono count or key hint.
|
||||||
|
private struct GitBarButton: View {
|
||||||
|
let icon: GitIcon
|
||||||
|
let label: String
|
||||||
|
let trailing: String?
|
||||||
|
let action: () -> Void
|
||||||
|
@State private var isHovered = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: action) {
|
||||||
|
HStack(spacing: 7) {
|
||||||
|
GitIconView(icon: icon, size: 14)
|
||||||
|
Text(label).typeRole(Typography.button)
|
||||||
|
if let trailing {
|
||||||
|
Text(trailing).typeRole(Typography.gitCount).foregroundStyle(Palette.amber)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.foregroundStyle(isHovered ? Palette.text1 : Palette.text3)
|
||||||
|
.padding(.horizontal, 11)
|
||||||
|
.frame(height: GitMetrics.topButton)
|
||||||
|
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall)
|
||||||
|
.strokeBorder(isHovered ? Palette.text5 : Palette.raised, lineWidth: Metrics.hairline))
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.fixedSize()
|
||||||
|
.pointerHand()
|
||||||
|
.tracksHover($isHovered)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import HelderCore
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// ⌘G: the full-screen Git view over the title bar, the columns and the status bar.
|
||||||
|
struct GitView: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Group {
|
||||||
|
if let store = model.sourceControl {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
GitTopBar(model: model, store: store)
|
||||||
|
GitCommitBlock(model: model, store: store)
|
||||||
|
GitSectionsList(model: model, store: store)
|
||||||
|
.frame(maxHeight: .infinity)
|
||||||
|
GitBottomStrip(model: model, store: store)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Color.clear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
.background(Palette.editor)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The console left, the branches right, 230pt tall.
|
||||||
|
private struct GitBottomStrip: View {
|
||||||
|
let model: WorkspaceModel
|
||||||
|
let store: SourceControlStore
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
GitConsolePanel(model: model, store: store)
|
||||||
|
.frame(maxWidth: .infinity)
|
||||||
|
Hairline(.vertical)
|
||||||
|
GitBranchesPanel(model: model, store: store)
|
||||||
|
.frame(maxWidth: .infinity)
|
||||||
|
}
|
||||||
|
.frame(height: GitMetrics.bottomStrip)
|
||||||
|
.background(Palette.panel)
|
||||||
|
.hairline(.top)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Git view's fixed sizes, from the design handoff.
|
||||||
|
enum GitMetrics {
|
||||||
|
static let topBar: CGFloat = 44
|
||||||
|
static let topButton: CGFloat = 28
|
||||||
|
static let messageMin: CGFloat = 56
|
||||||
|
static let messageMax: CGFloat = 180
|
||||||
|
static let messageInset = CGSize(width: 16, height: 14)
|
||||||
|
static let commitFooter: CGFloat = 52
|
||||||
|
static let commitButton: CGFloat = 32
|
||||||
|
static let commitButtonMinWidth: CGFloat = 160
|
||||||
|
static let sectionHeader: CGFloat = 46
|
||||||
|
static let sectionGap: CGFloat = 28
|
||||||
|
static let fileRow: CGFloat = 36
|
||||||
|
static let accentBar: CGFloat = 3
|
||||||
|
static let actionWidth: CGFloat = 100
|
||||||
|
static let headerAction: CGFloat = 28
|
||||||
|
static let rowAction: CGFloat = 26
|
||||||
|
static let actionGap: CGFloat = 6
|
||||||
|
static let statusBadge: CGFloat = 18
|
||||||
|
static let statWidth: CGFloat = 52
|
||||||
|
static let diffLine: CGFloat = 22
|
||||||
|
static let diffGutter: CGFloat = 52
|
||||||
|
static let diffGap: CGFloat = 28
|
||||||
|
static let bottomStrip: CGFloat = 230
|
||||||
|
static let stripHeader: CGFloat = 32
|
||||||
|
static let branchRow: CGFloat = 28
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A colour transition on hover, the only motion the view has.
|
||||||
|
struct HoverState: ViewModifier {
|
||||||
|
@Binding var isHovered: Bool
|
||||||
|
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
content
|
||||||
|
.onHover { isHovered = $0 }
|
||||||
|
.animation(Metrics.colorTransition, value: isHovered)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension View {
|
||||||
|
func tracksHover(_ isHovered: Binding<Bool>) -> some View {
|
||||||
|
modifier(HoverState(isHovered: isHovered))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -78,7 +78,8 @@ struct ContextMenuOverlay: View {
|
|||||||
ContextMenuSeparator()
|
ContextMenuSeparator()
|
||||||
case let .action(action, label):
|
case let .action(action, label):
|
||||||
ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color,
|
ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color,
|
||||||
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
|
isHighlighted: highlighted == index, isDestructive: action.isDestructive,
|
||||||
|
isEmphasized: action.isEmphasized)
|
||||||
.onHover { inside in if inside { highlighted = index } }
|
.onHover { inside in if inside { highlighted = index } }
|
||||||
.onTapGesture { onPerform(action) }
|
.onTapGesture { onPerform(action) }
|
||||||
}
|
}
|
||||||
@@ -109,11 +110,11 @@ struct ContextMenuOverlay: View {
|
|||||||
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
|
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
|
||||||
switch action {
|
switch action {
|
||||||
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText, .readAloudTerminalSelection,
|
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText, .readAloudTerminalSelection,
|
||||||
.plak, .plakTerminalSelection: .plain
|
.plak, .plakTerminalSelection, .openFile, .commit: .plain
|
||||||
case .newFile, .newFolder, .stage: .add
|
case .newFile, .newFolder: .add
|
||||||
case .copyFileName, .unstage, .revealInFinder: .modify
|
case .copyFileName, .revealInFinder: .modify
|
||||||
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .openDiff, .showDiff, .rename: .rename
|
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .showDiff, .rename: .rename
|
||||||
case .discard, .delete: .danger
|
case .gitDiscard, .delete: .danger
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,13 +126,14 @@ struct ContextMenuOverlay: View {
|
|||||||
case .readAloudFile, .readAloudText, .readAloudTerminalSelection: "speaker.wave.2"
|
case .readAloudFile, .readAloudText, .readAloudTerminalSelection: "speaker.wave.2"
|
||||||
case .plak, .plakTerminalSelection: "note.text.badge.plus"
|
case .plak, .plakTerminalSelection: "note.text.badge.plus"
|
||||||
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
|
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
|
||||||
|
case .openFile: "doc.text"
|
||||||
|
case .commit(andPush: false): "checkmark"
|
||||||
|
case .commit(andPush: true): "arrow.up.to.line"
|
||||||
case .pasteIntoTerminal: "doc.on.clipboard"
|
case .pasteIntoTerminal: "doc.on.clipboard"
|
||||||
case .newFile: "doc.badge.plus"
|
case .newFile: "doc.badge.plus"
|
||||||
case .newFolder: "folder.badge.plus"
|
case .newFolder: "folder.badge.plus"
|
||||||
case .stage: "plus"
|
case .showDiff: "arrow.left.arrow.right"
|
||||||
case .unstage: "minus"
|
case .gitDiscard: "arrow.uturn.backward"
|
||||||
case .openDiff, .showDiff: "arrow.left.arrow.right"
|
|
||||||
case .discard: "arrow.uturn.backward"
|
|
||||||
case .rename: "pencil"
|
case .rename: "pencil"
|
||||||
case .revealInFinder: "folder"
|
case .revealInFinder: "folder"
|
||||||
case .delete: "trash"
|
case .delete: "trash"
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ public struct OverlayHost: View {
|
|||||||
activeText: path.map { model.editor?.text(for: $0) ?? "" } ?? "",
|
activeText: path.map { model.editor?.text(for: $0) ?? "" } ?? "",
|
||||||
showHidden: model.layout.showHidden),
|
showHidden: model.layout.showHidden),
|
||||||
changedPaths: model.changedPaths,
|
changedPaths: model.changedPaths,
|
||||||
|
isFullScreen: model.layout.isFullScreen,
|
||||||
onOpen: { model.perform(.open($0.path, OpenOptions(line: $0.line))) },
|
onOpen: { model.perform(.open($0.path, OpenOptions(line: $0.line))) },
|
||||||
onClose: dismiss
|
onClose: dismiss
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -290,20 +290,16 @@ public final class SearchModel {
|
|||||||
|
|
||||||
// MARK: Layout
|
// MARK: Layout
|
||||||
|
|
||||||
/// Column widths: the focused column takes 70%; at rest this file is 230, files 250,
|
/// Fixed column widths that never follow the focus: 30 · 45 · 25 with this file, else 65 · 35.
|
||||||
/// and a side column never drops below 180.
|
public static func widths(total: CGFloat, columns: [Column]) -> [Column: CGFloat] {
|
||||||
public static func widths(total: CGFloat, columns: [Column], focused: Column) -> [Column: CGFloat] {
|
|
||||||
let restingSide: [Column: CGFloat] = [.thisFile: 230, .files: 250]
|
|
||||||
let minimumSide: CGFloat = 180
|
|
||||||
var widths: [Column: CGFloat] = [:]
|
var widths: [Column: CGFloat] = [:]
|
||||||
if focused == .project {
|
if columns.contains(.thisFile) {
|
||||||
for side in columns where side != .project { widths[side] = restingSide[side] }
|
widths[.thisFile] = (total * 0.30).rounded()
|
||||||
|
widths[.files] = (total * 0.25).rounded()
|
||||||
} else {
|
} else {
|
||||||
widths[focused] = (total * 0.7).rounded()
|
widths[.files] = (total * 0.35).rounded()
|
||||||
for side in columns where side != .project && side != focused { widths[side] = minimumSide }
|
|
||||||
}
|
}
|
||||||
let used = widths.values.reduce(0, +)
|
widths[.project] = max(0, total - widths.values.reduce(0, +))
|
||||||
widths[.project] = max(0, total - used)
|
|
||||||
return widths
|
return widths
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ struct SearchOverlay: View {
|
|||||||
@State private var model: SearchModel
|
@State private var model: SearchModel
|
||||||
/// Paths with a git change get a dot in the files column.
|
/// Paths with a git change get a dot in the files column.
|
||||||
var changedPaths: Set<String>
|
var changedPaths: Set<String>
|
||||||
|
/// Full screen hides the traffic lights, so the query bar reclaims their inset.
|
||||||
|
var isFullScreen: Bool
|
||||||
var onOpen: (SearchModel.Target) -> Void
|
var onOpen: (SearchModel.Target) -> Void
|
||||||
var onClose: () -> Void
|
var onClose: () -> Void
|
||||||
|
|
||||||
@@ -14,15 +16,17 @@ struct SearchOverlay: View {
|
|||||||
@State private var parkedPointer: CGPoint?
|
@State private var parkedPointer: CGPoint?
|
||||||
@State private var hoveredGroup: String?
|
@State private var hoveredGroup: String?
|
||||||
|
|
||||||
init(model: SearchModel, changedPaths: Set<String>, onOpen: @escaping (SearchModel.Target) -> Void, onClose: @escaping () -> Void) {
|
init(model: SearchModel, changedPaths: Set<String>, isFullScreen: Bool,
|
||||||
|
onOpen: @escaping (SearchModel.Target) -> Void, onClose: @escaping () -> Void) {
|
||||||
_model = State(initialValue: model)
|
_model = State(initialValue: model)
|
||||||
self.changedPaths = changedPaths
|
self.changedPaths = changedPaths
|
||||||
|
self.isFullScreen = isFullScreen
|
||||||
self.onOpen = onOpen
|
self.onOpen = onOpen
|
||||||
self.onClose = onClose
|
self.onClose = onClose
|
||||||
}
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
OverlayShell(.inset, onDismiss: onClose) {
|
OverlayShell(.fullScreen, onDismiss: onClose) {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
queryBar.zIndex(1)
|
queryBar.zIndex(1)
|
||||||
columns
|
columns
|
||||||
@@ -54,7 +58,8 @@ struct SearchOverlay: View {
|
|||||||
.padding(.leading, 12)
|
.padding(.leading, 12)
|
||||||
.hairline(.leading)
|
.hairline(.leading)
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 18)
|
.padding(.leading, isFullScreen ? 18 : Metrics.trafficLightInset)
|
||||||
|
.padding(.trailing, 18)
|
||||||
.frame(height: Metrics.searchQueryBar)
|
.frame(height: Metrics.searchQueryBar)
|
||||||
.hairline(.bottom)
|
.hairline(.bottom)
|
||||||
}
|
}
|
||||||
@@ -85,7 +90,7 @@ struct SearchOverlay: View {
|
|||||||
|
|
||||||
private var columns: some View {
|
private var columns: some View {
|
||||||
GeometryReader { proxy in
|
GeometryReader { proxy in
|
||||||
let widths = SearchModel.widths(total: proxy.size.width, columns: model.columns, focused: model.column)
|
let widths = SearchModel.widths(total: proxy.size.width, columns: model.columns)
|
||||||
HStack(spacing: 0) {
|
HStack(spacing: 0) {
|
||||||
if model.columns.contains(.thisFile) {
|
if model.columns.contains(.thisFile) {
|
||||||
thisFileColumn.frame(width: widths[.thisFile])
|
thisFileColumn.frame(width: widths[.thisFile])
|
||||||
@@ -95,7 +100,6 @@ struct SearchOverlay: View {
|
|||||||
divider
|
divider
|
||||||
filesColumn.frame(width: widths[.files])
|
filesColumn.frame(width: widths[.files])
|
||||||
}
|
}
|
||||||
.animation(Metrics.colorTransition, value: model.column)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +267,7 @@ struct SearchOverlay: View {
|
|||||||
TypeBadge(path: match.path)
|
TypeBadge(path: match.path)
|
||||||
VStack(alignment: .leading, spacing: 1) {
|
VStack(alignment: .leading, spacing: 1) {
|
||||||
Text(SearchHighlight.name(PathUtils.basename(match.path), indices: match.nameIndices, selected: selected))
|
Text(SearchHighlight.name(PathUtils.basename(match.path), indices: match.nameIndices, selected: selected))
|
||||||
.typeRole(selected ? Typography.rowSelected : Typography.sourceControlRow)
|
.typeRole(selected ? Typography.rowSelected : Typography.rowSmall)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
if !directory.isEmpty {
|
if !directory.isEmpty {
|
||||||
Text(directory + "/").typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).truncationMode(.head)
|
Text(directory + "/").typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).truncationMode(.head)
|
||||||
|
|||||||
@@ -19,7 +19,10 @@ public enum ShortcutCatalog {
|
|||||||
ShortcutRow(keys: ["⌘", "↑↓"], label: "Move through a list"),
|
ShortcutRow(keys: ["⌘", "↑↓"], label: "Move through a list"),
|
||||||
ShortcutRow(keys: ["↵"], label: "Open the selected item"),
|
ShortcutRow(keys: ["↵"], label: "Open the selected item"),
|
||||||
ShortcutRow(keys: ["⌘", "←→"], label: "Column left or right"),
|
ShortcutRow(keys: ["⌘", "←→"], label: "Column left or right"),
|
||||||
ShortcutRow(keys: ["↑↓"], label: "Git or Explorer: move the row cursor"),
|
ShortcutRow(keys: ["↑↓"], label: "Explorer: move the row cursor"),
|
||||||
|
ShortcutRow(keys: ["⌘", "1"], label: "Explorer column on or off"),
|
||||||
|
ShortcutRow(keys: ["⌘", "2"], label: "File column on or off"),
|
||||||
|
ShortcutRow(keys: ["⌘", "3"], label: "Claude column on or off"),
|
||||||
ShortcutRow(keys: ["⇧", "⌘", "O"], label: "Open a recent project"),
|
ShortcutRow(keys: ["⇧", "⌘", "O"], label: "Open a recent project"),
|
||||||
ShortcutRow(keys: ["⌘", "O"], label: "Open a project folder"),
|
ShortcutRow(keys: ["⌘", "O"], label: "Open a project folder"),
|
||||||
ShortcutRow(keys: ["⇧", "⌘", "N"], label: "Open a new window"),
|
ShortcutRow(keys: ["⇧", "⌘", "N"], label: "Open a new window"),
|
||||||
@@ -30,9 +33,9 @@ public enum ShortcutCatalog {
|
|||||||
ShortcutRow(keys: ["⌘", "→"], label: "Pass the selection to the agent"),
|
ShortcutRow(keys: ["⌘", "→"], label: "Pass the selection to the agent"),
|
||||||
]),
|
]),
|
||||||
ShortcutGroup(title: "Git", rows: [
|
ShortcutGroup(title: "Git", rows: [
|
||||||
|
ShortcutRow(keys: ["⌘", "G"], label: "Open or close the Git view"),
|
||||||
ShortcutRow(keys: ["⌘", "C"], label: "Focus the commit message"),
|
ShortcutRow(keys: ["⌘", "C"], label: "Focus the commit message"),
|
||||||
ShortcutRow(keys: ["⌘", "↵"], label: "Commit the staged files"),
|
ShortcutRow(keys: ["⌘", "↵"], label: "Commit the staged files"),
|
||||||
ShortcutRow(keys: ["⌘", "G"], label: "Source Control column on or off"),
|
|
||||||
ShortcutRow(keys: ["⌘", "P"], label: "Push the current branch"),
|
ShortcutRow(keys: ["⌘", "P"], label: "Push the current branch"),
|
||||||
]),
|
]),
|
||||||
ShortcutGroup(title: "File", rows: [
|
ShortcutGroup(title: "File", rows: [
|
||||||
@@ -46,7 +49,7 @@ public enum ShortcutCatalog {
|
|||||||
ShortcutRow(keys: ["⌘", "+"], label: "Zoom in"),
|
ShortcutRow(keys: ["⌘", "+"], label: "Zoom in"),
|
||||||
ShortcutRow(keys: ["⌘", "−"], label: "Zoom out"),
|
ShortcutRow(keys: ["⌘", "−"], label: "Zoom out"),
|
||||||
ShortcutRow(keys: ["⌘", "0"], label: "Actual size"),
|
ShortcutRow(keys: ["⌘", "0"], label: "Actual size"),
|
||||||
ShortcutRow(keys: ["Esc"], label: "Close an overlay or a split view"),
|
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Git view"),
|
||||||
]),
|
]),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import HelderCore
|
|||||||
/// first responder when it names them.
|
/// first responder when it names them.
|
||||||
public enum FocusTarget: Equatable, Sendable {
|
public enum FocusTarget: Equatable, Sendable {
|
||||||
case panel(Panel)
|
case panel(Panel)
|
||||||
/// ⌘C without a selection, outside a terminal: the commit message field.
|
/// The Git view's commit message field; ⌘G and ⌘C without a selection ask for it.
|
||||||
case commitMessage
|
case commitMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,9 +72,11 @@ public enum Command: Equatable, Sendable {
|
|||||||
|
|
||||||
// MARK: Layout and focus
|
// MARK: Layout and focus
|
||||||
|
|
||||||
/// ⌘G: the Source Control pane toggle.
|
/// ⌘G and the title bar's Git button: opens or closes the full-screen Git view.
|
||||||
case toggleGit
|
case toggleGit
|
||||||
/// A title-bar pane toggle: shows or hides one column.
|
/// Esc with the Git view open and no overlay over it.
|
||||||
|
case closeGitView
|
||||||
|
/// ⌘1–⌘3 and the title-bar pane toggles: shows or hides one column.
|
||||||
case togglePane(Panel)
|
case togglePane(Panel)
|
||||||
/// ⌘L
|
/// ⌘L
|
||||||
case toggleAutoFit
|
case toggleAutoFit
|
||||||
@@ -85,11 +87,11 @@ public enum Command: Equatable, Sendable {
|
|||||||
/// ⌘←/⌘→ outside a text field.
|
/// ⌘←/⌘→ outside a text field.
|
||||||
case focusNeighbour(step: Int)
|
case focusNeighbour(step: Int)
|
||||||
|
|
||||||
// MARK: Row cursor in Source Control and Explorer
|
// MARK: Row cursor in the Explorer
|
||||||
|
|
||||||
/// ↑/↓
|
/// ↑/↓
|
||||||
case moveRowCursor(Int)
|
case moveRowCursor(Int)
|
||||||
/// ↵: git row opens its half, a file opens, a folder toggles.
|
/// ↵: a file opens, a folder toggles.
|
||||||
case openSelectedRow
|
case openSelectedRow
|
||||||
/// ⌘→ on a row: its context menu, anchored to the column's right edge.
|
/// ⌘→ on a row: its context menu, anchored to the column's right edge.
|
||||||
case openRowMenu
|
case openRowMenu
|
||||||
@@ -110,11 +112,18 @@ public enum Command: Equatable, Sendable {
|
|||||||
|
|
||||||
// MARK: Git
|
// MARK: Git
|
||||||
|
|
||||||
/// ⌘↵
|
/// ⌘↵ and the Commit button: always runs git, so its refusal shows in the console.
|
||||||
case commit
|
case commit
|
||||||
/// ⌘P
|
/// ⌘P
|
||||||
case push
|
case push
|
||||||
/// ⌘C without a selection, outside a terminal
|
case pull
|
||||||
|
case stage([String])
|
||||||
|
case unstage([String])
|
||||||
|
/// A branch row in the Git view; a remote one switches by its local name.
|
||||||
|
case switchBranch(String, remote: Bool)
|
||||||
|
/// ↵ in the Git console.
|
||||||
|
case submitConsoleInput
|
||||||
|
/// ⌘C without a selection, outside a terminal: opens the Git view on its message field.
|
||||||
case focusCommitMessage
|
case focusCommitMessage
|
||||||
|
|
||||||
// MARK: Clean copy
|
// MARK: Clean copy
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ public struct HelderScene: Scene {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘L, ⌘.) are shown here too; the router
|
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘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.
|
/// consumes them first, so the menu item fires only when a field or an overlay let the key through.
|
||||||
struct HelderCommands: Commands {
|
struct HelderCommands: Commands {
|
||||||
@FocusedValue(\.workspace) private var workspace
|
@FocusedValue(\.workspace) private var workspace
|
||||||
@@ -66,19 +66,22 @@ struct HelderCommands: Commands {
|
|||||||
.keyboardShortcut("r", modifiers: .command)
|
.keyboardShortcut("r", modifiers: .command)
|
||||||
.disabled(workspace?.root == nil)
|
.disabled(workspace?.root == nil)
|
||||||
Divider()
|
Divider()
|
||||||
Button(workspace?.layout.isVisible(.sourceControl) == false ? "Show Source Control" : "Hide Source Control") {
|
Button(workspace?.layout.isGitViewOpen == true ? "Hide Git" : "Show Git") {
|
||||||
workspace?.perform(.toggleGit)
|
workspace?.perform(.toggleGit)
|
||||||
}
|
}
|
||||||
.keyboardShortcut("g", modifiers: .command)
|
.keyboardShortcut("g", modifiers: .command)
|
||||||
Button(workspace?.layout.isVisible(.explorer) == false ? "Show Explorer" : "Hide Explorer") {
|
Button(workspace?.layout.isVisible(.explorer) == false ? "Show Explorer" : "Hide Explorer") {
|
||||||
workspace?.perform(.togglePane(.explorer))
|
workspace?.perform(.togglePane(.explorer))
|
||||||
}
|
}
|
||||||
|
.keyboardShortcut("1", modifiers: .command)
|
||||||
Button(workspace?.layout.isVisible(.editor) == false ? "Show File" : "Hide File") {
|
Button(workspace?.layout.isVisible(.editor) == false ? "Show File" : "Hide File") {
|
||||||
workspace?.perform(.togglePane(.editor))
|
workspace?.perform(.togglePane(.editor))
|
||||||
}
|
}
|
||||||
|
.keyboardShortcut("2", modifiers: .command)
|
||||||
Button(workspace?.layout.isVisible(.terminal) == false ? "Show Claude" : "Hide Claude") {
|
Button(workspace?.layout.isVisible(.terminal) == false ? "Show Claude" : "Hide Claude") {
|
||||||
workspace?.perform(.togglePane(.terminal))
|
workspace?.perform(.togglePane(.terminal))
|
||||||
}
|
}
|
||||||
|
.keyboardShortcut("3", modifiers: .command)
|
||||||
Button(workspace?.layout.fluid == false ? "Fluid Column Widths" : "Lock Column Widths") {
|
Button(workspace?.layout.fluid == false ? "Fluid Column Widths" : "Lock Column Widths") {
|
||||||
workspace?.perform(.toggleAutoFit)
|
workspace?.perform(.toggleAutoFit)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,11 +55,15 @@ public struct KeyContext: Equatable, Sendable {
|
|||||||
public var recentFileCount: Int
|
public var recentFileCount: Int
|
||||||
/// The seed ⌘F uses: the first line of the current selection.
|
/// The seed ⌘F uses: the first line of the current selection.
|
||||||
public var searchSeed: String
|
public var searchSeed: String
|
||||||
|
/// The full-screen Git view covers the columns, so their list and focus keys rest.
|
||||||
|
public var gitViewOpen: Bool
|
||||||
|
/// The keyboard sits in the Git view's console input, where ⌘↵ must not commit.
|
||||||
|
public var inGitConsole: Bool
|
||||||
|
|
||||||
public init(hasProject: Bool = true, overlay: OverlayKind = .none, owner: KeyboardOwner = .workspace,
|
public init(hasProject: Bool = true, overlay: OverlayKind = .none, owner: KeyboardOwner = .workspace,
|
||||||
hasTextSelection: Bool = false, editorTextSelection: TextSelectionInfo? = nil,
|
hasTextSelection: Bool = false, editorTextSelection: TextSelectionInfo? = nil,
|
||||||
hasEditorLineSelection: Bool = false, activePanel: Panel? = nil, focusZone: FocusZone = .neutral,
|
hasEditorLineSelection: Bool = false, activePanel: Panel? = nil, focusZone: FocusZone = .neutral,
|
||||||
recentFileCount: Int = 0, searchSeed: String = "") {
|
recentFileCount: Int = 0, searchSeed: String = "", gitViewOpen: Bool = false, inGitConsole: Bool = false) {
|
||||||
self.hasProject = hasProject
|
self.hasProject = hasProject
|
||||||
self.overlay = overlay
|
self.overlay = overlay
|
||||||
self.owner = owner
|
self.owner = owner
|
||||||
@@ -70,6 +74,8 @@ public struct KeyContext: Equatable, Sendable {
|
|||||||
self.focusZone = focusZone
|
self.focusZone = focusZone
|
||||||
self.recentFileCount = recentFileCount
|
self.recentFileCount = recentFileCount
|
||||||
self.searchSeed = searchSeed
|
self.searchSeed = searchSeed
|
||||||
|
self.gitViewOpen = gitViewOpen
|
||||||
|
self.inGitConsole = inGitConsole
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,6 +105,7 @@ public enum KeyRoute: Equatable {
|
|||||||
|
|
||||||
/// Maps a key press to a command. A key that a focused field or terminal needs is never taken:
|
/// 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.
|
/// 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.
|
||||||
public enum KeyRouter {
|
public enum KeyRouter {
|
||||||
public static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
|
public static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
|
||||||
if press.control || press.option { return .pass }
|
if press.control || press.option { return .pass }
|
||||||
@@ -107,7 +114,10 @@ public enum KeyRouter {
|
|||||||
|
|
||||||
switch context.overlay {
|
switch context.overlay {
|
||||||
case .diff(busy: true): return .pass
|
case .diff(busy: true): return .pass
|
||||||
case .none: if press.key == .escape { return .pass }
|
case .none:
|
||||||
|
if press.key == .escape {
|
||||||
|
return context.gitViewOpen && !press.command ? .perform(.closeGitView) : .pass
|
||||||
|
}
|
||||||
default: if press.key == .escape && !press.command { return .perform(.dismissOverlay) }
|
default: if press.key == .escape && !press.command { return .perform(.dismissOverlay) }
|
||||||
}
|
}
|
||||||
switch context.overlay {
|
switch context.overlay {
|
||||||
@@ -117,9 +127,24 @@ public enum KeyRouter {
|
|||||||
case .other: return .pass
|
case .other: return .pass
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if context.gitViewOpen { return gitViewKey(press, context) }
|
||||||
return press.command ? commandKey(press, context) : plainKey(press, context)
|
return press.command ? commandKey(press, context) : plainKey(press, context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Over the Git view the columns' row, focus and editor keys rest; ⌘↵ commits, even from the message field.
|
||||||
|
private static func gitViewKey(_ 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 .enter: return context.inGitConsole ? .pass : .perform(.commit)
|
||||||
|
case .character("a"): return .pass
|
||||||
|
case let .character(c): return commandCharacter(c, context)
|
||||||
|
default: return .pass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static func launcherKey(_ press: KeyPress) -> KeyRoute {
|
private static func launcherKey(_ press: KeyPress) -> KeyRoute {
|
||||||
guard !press.shift else { return .pass }
|
guard !press.shift else { return .pass }
|
||||||
switch press.key {
|
switch press.key {
|
||||||
@@ -131,7 +156,7 @@ public enum KeyRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static func plainKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
|
private static func plainKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
|
||||||
let inList = context.owner == .workspace && (context.activePanel == .sourceControl || context.activePanel == .explorer)
|
let inList = context.owner == .workspace && context.activePanel == .explorer
|
||||||
switch press.key {
|
switch press.key {
|
||||||
case .up where inList && !press.shift: return .perform(.moveRowCursor(-1))
|
case .up where inList && !press.shift: return .perform(.moveRowCursor(-1))
|
||||||
case .down where inList && !press.shift: return .perform(.moveRowCursor(1))
|
case .down where inList && !press.shift: return .perform(.moveRowCursor(1))
|
||||||
@@ -152,16 +177,12 @@ public enum KeyRouter {
|
|||||||
return .perform(.showRecentFiles(initialSelection: ListCursor.recentFilesStart(movingDown: press.key == .down,
|
return .perform(.showRecentFiles(initialSelection: ListCursor.recentFilesStart(movingDown: press.key == .down,
|
||||||
count: context.recentFileCount)))
|
count: context.recentFileCount)))
|
||||||
case .right:
|
case .right:
|
||||||
if owner == .workspace, context.activePanel == .sourceControl || context.activePanel == .explorer {
|
if owner == .workspace, context.activePanel == .explorer { return .perform(.openRowMenu) }
|
||||||
return .perform(.openRowMenu)
|
|
||||||
}
|
|
||||||
if let selection = context.editorTextSelection { return .perform(.passSelection(selection)) }
|
if let selection = context.editorTextSelection { return .perform(.passSelection(selection)) }
|
||||||
if context.hasEditorLineSelection && owner != .terminal { return .perform(.passSelection(nil)) }
|
if context.hasEditorLineSelection && owner != .terminal { return .perform(.passSelection(nil)) }
|
||||||
return owner == .workspace ? .perform(.focusNeighbour(step: 1)) : .pass
|
return owner == .workspace ? .perform(.focusNeighbour(step: 1)) : .pass
|
||||||
case .left:
|
case .left:
|
||||||
return owner == .workspace ? .perform(.focusNeighbour(step: -1)) : .pass
|
return owner == .workspace ? .perform(.focusNeighbour(step: -1)) : .pass
|
||||||
case .enter:
|
|
||||||
return owner == .text(in: .sourceControl) ? .pass : .perform(.commit)
|
|
||||||
case let .character(c):
|
case let .character(c):
|
||||||
return commandCharacter(c, context)
|
return commandCharacter(c, context)
|
||||||
default:
|
default:
|
||||||
@@ -177,6 +198,9 @@ public enum KeyRouter {
|
|||||||
case "m": return .perform(.cycleMode)
|
case "m": return .perform(.cycleMode)
|
||||||
case "w": return .perform(.closeFileOrWindow)
|
case "w": return .perform(.closeFileOrWindow)
|
||||||
case "g": return .perform(.toggleGit)
|
case "g": return .perform(.toggleGit)
|
||||||
|
case "1": return .perform(.togglePane(.explorer))
|
||||||
|
case "2": return .perform(.togglePane(.editor))
|
||||||
|
case "3": return .perform(.togglePane(.terminal))
|
||||||
case "l": return .perform(.toggleAutoFit)
|
case "l": return .perform(.toggleAutoFit)
|
||||||
case ".": return .perform(.toggleHidden)
|
case ".": return .perform(.toggleHidden)
|
||||||
case "a": return context.owner == .workspace ? .perform(.selectAllInFile) : .pass
|
case "a": return context.owner == .workspace ? .perform(.selectAllInFile) : .pass
|
||||||
|
|||||||
@@ -107,31 +107,30 @@ private struct Breadcrumb: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Git · Explorer · File · Claude: one toggle per column. Hiding a column keeps everything inside it.
|
/// Explorer · File · Claude: one toggle per column. Hiding a column keeps everything inside it.
|
||||||
private struct PaneToggles: View {
|
private struct PaneToggles: View {
|
||||||
let model: WorkspaceModel
|
let model: WorkspaceModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ButtonGroup([
|
ButtonGroup([
|
||||||
toggle("Git", .sourceControl, column: "Source Control"),
|
toggle("Explorer", .explorer),
|
||||||
toggle("Explorer", .explorer, column: "Explorer"),
|
toggle("File", .editor),
|
||||||
toggle("File", .editor, column: "File"),
|
toggle("Claude", .terminal),
|
||||||
toggle("Claude", .terminal, column: "Claude"),
|
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
private func toggle(_ label: String, _ panel: Panel, column: String) -> GroupItem {
|
private func toggle(_ label: String, _ panel: Panel) -> GroupItem {
|
||||||
let shown = model.layout.isVisible(panel)
|
let shown = model.layout.isVisible(panel)
|
||||||
let tip = shown
|
let tip = shown
|
||||||
? Tooltip.stated(column + " column: ", "shown", ". Click to hide it.")
|
? Tooltip.stated(label + " column: ", "shown", ". Click to hide it.")
|
||||||
: Tooltip.stated(column + " column: ", "hidden", ". Click to show it.")
|
: Tooltip.stated(label + " column: ", "hidden", ". Click to show it.")
|
||||||
return GroupItem(label, kind: .toggle(isOn: shown), tip: tip) {
|
return GroupItem(label, kind: .toggle(isOn: shown), tip: tip) {
|
||||||
model.perform(.togglePane(panel))
|
model.perform(.togglePane(panel))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Search ⌘F · Fluid ⌘L · Hidden ⌘., then `?`. Search is an action; Fluid and Hidden toggle.
|
/// 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.
|
/// While Helder reads aloud, a Stop toggle leads the group; switching it off stops the reading.
|
||||||
private struct TitleToolbar: View {
|
private struct TitleToolbar: View {
|
||||||
let model: WorkspaceModel
|
let model: WorkspaceModel
|
||||||
@@ -140,6 +139,7 @@ private struct TitleToolbar: View {
|
|||||||
let layout = model.layout
|
let layout = model.layout
|
||||||
HStack(spacing: Metrics.toolbarIconGap) {
|
HStack(spacing: Metrics.toolbarIconGap) {
|
||||||
ButtonGroup(stop + [
|
ButtonGroup(stop + [
|
||||||
|
git,
|
||||||
GroupItem("Search", keys: "⌘F", kind: .action,
|
GroupItem("Search", keys: "⌘F", kind: .action,
|
||||||
tip: Text("Search the open file, the project and the file names.")) { model.perform(.showSearch(seed: "")) },
|
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),
|
GroupItem("Fluid", keys: "⌘L", kind: .toggle(isOn: layout.fluid),
|
||||||
@@ -161,6 +161,18 @@ private struct TitleToolbar: View {
|
|||||||
.fixedSize()
|
.fixedSize()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// N counts changed files, a file both staged and unstaged once; the dot lights while the view is open.
|
||||||
|
private var git: GroupItem {
|
||||||
|
let open = model.layout.isGitViewOpen
|
||||||
|
let count = Set(model.sourceControl?.state.changes.map(\.path) ?? []).count
|
||||||
|
let tip = open
|
||||||
|
? Tooltip.stated("Git view: ", "open", ". Click to close it (⌘G).")
|
||||||
|
: Tooltip.stated("Git view: ", "closed", ". Click to open it (⌘G).")
|
||||||
|
return GroupItem(count > 0 ? "Git \(count)" : "Git", id: "Git", keys: "⌘G", kind: .toggle(isOn: open), tip: tip) {
|
||||||
|
model.perform(.toggleGit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var stop: [GroupItem] {
|
private var stop: [GroupItem] {
|
||||||
guard model.readAloud.isReading else { return [] }
|
guard model.readAloud.isReading else { return [] }
|
||||||
return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) {
|
return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ struct WindowBridge: NSViewRepresentable {
|
|||||||
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
|
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
|
||||||
let title: String
|
let title: String
|
||||||
let hasProject: Bool
|
let hasProject: Bool
|
||||||
|
let gitViewOpen: Bool
|
||||||
|
|
||||||
func makeCoordinator() -> WindowCoordinator {
|
func makeCoordinator() -> WindowCoordinator {
|
||||||
WindowCoordinator(model: model)
|
WindowCoordinator(model: model)
|
||||||
@@ -21,6 +22,7 @@ struct WindowBridge: NSViewRepresentable {
|
|||||||
|
|
||||||
func updateNSView(_ view: BridgeView, context: Context) {
|
func updateNSView(_ view: BridgeView, context: Context) {
|
||||||
context.coordinator.updateTitle(title, hasProject: hasProject)
|
context.coordinator.updateTitle(title, hasProject: hasProject)
|
||||||
|
context.coordinator.updateGitView(open: gitViewOpen)
|
||||||
context.coordinator.guardClose()
|
context.coordinator.guardClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ final class WindowCoordinator: NSObject {
|
|||||||
/// Set once the unsaved prompt said yes, so the second close goes through.
|
/// Set once the unsaved prompt said yes, so the second close goes through.
|
||||||
private var closeApproved = false
|
private var closeApproved = false
|
||||||
private var isAskingToClose = false
|
private var isAskingToClose = false
|
||||||
|
private var gitViewOpen = false
|
||||||
|
|
||||||
init(model: WorkspaceModel) {
|
init(model: WorkspaceModel) {
|
||||||
self.model = model
|
self.model = model
|
||||||
@@ -103,6 +106,14 @@ final class WindowCoordinator: NSObject {
|
|||||||
AppName.set(hasProject ? title : AppName.standard)
|
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 }
|
||||||
|
window.makeFirstResponder(nil)
|
||||||
|
}
|
||||||
|
|
||||||
private func configure(_ window: NSWindow) {
|
private func configure(_ window: NSWindow) {
|
||||||
window.title = model.title
|
window.title = model.title
|
||||||
window.titleVisibility = .hidden
|
window.titleVisibility = .hidden
|
||||||
@@ -203,19 +214,20 @@ final class WindowCoordinator: NSObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Source Control and Explorer have no text view to focus, so they hold the keyboard by clearing first responder.
|
/// The Explorer has no text view to focus, so it holds the keyboard by clearing first responder.
|
||||||
private func takeFocus(for panel: Panel, in window: NSWindow) {
|
private func takeFocus(for panel: Panel, in window: NSWindow) {
|
||||||
if panel == .sourceControl || panel == .explorer { window.makeFirstResponder(nil) }
|
if panel == .explorer { window.makeFirstResponder(nil) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private func handleMouseDown(_ event: NSEvent) {
|
private func handleMouseDown(_ event: NSEvent) {
|
||||||
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented else { return }
|
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented,
|
||||||
|
!model.layout.isGitViewOpen else { return }
|
||||||
let point = event.locationInWindow
|
let point = event.locationInWindow
|
||||||
let height = window.contentView?.bounds.height ?? window.frame.height
|
let height = window.contentView?.bounds.height ?? window.frame.height
|
||||||
guard height - point.y > Metrics.titleBar, point.y > Metrics.statusBar else { return }
|
guard height - point.y > Metrics.titleBar, point.y > Metrics.statusBar else { return }
|
||||||
guard let panel = model.layout.panel(atX: point.x, splitterMargin: 4) else { return }
|
guard let panel = model.layout.panel(atX: point.x, splitterMargin: 4) else { return }
|
||||||
model.pointerFocused(panel)
|
model.pointerFocused(panel)
|
||||||
guard panel == .sourceControl || panel == .explorer else { return }
|
guard panel == .explorer else { return }
|
||||||
// A row click pulls the keyboard out of a text view in another column; otherwise typing lands there.
|
// A row click pulls the keyboard out of a text view in another column; otherwise typing lands there.
|
||||||
DispatchQueue.main.async { [weak self, weak window] in
|
DispatchQueue.main.async { [weak self, weak window] in
|
||||||
guard let self, let window, let view = window.firstResponder as? NSView,
|
guard let self, let window, let view = window.firstResponder as? NSView,
|
||||||
@@ -235,8 +247,9 @@ final class WindowCoordinator: NSObject {
|
|||||||
var hasSelection = false
|
var hasSelection = false
|
||||||
var editorSelection: TextSelectionInfo?
|
var editorSelection: TextSelectionInfo?
|
||||||
var seed = ""
|
var seed = ""
|
||||||
|
let gitViewOpen = model.layout.isGitViewOpen
|
||||||
if let text = responder as? NSTextView {
|
if let text = responder as? NSTextView {
|
||||||
let column = column(of: text)
|
let column = gitViewOpen ? nil : column(of: text)
|
||||||
owner = .text(in: column)
|
owner = .text(in: column)
|
||||||
let range = text.selectedRange()
|
let range = text.selectedRange()
|
||||||
hasSelection = range.length > 0
|
hasSelection = range.length > 0
|
||||||
@@ -270,7 +283,9 @@ final class WindowCoordinator: NSObject {
|
|||||||
activePanel: model.layout.activePanel,
|
activePanel: model.layout.activePanel,
|
||||||
focusZone: model.layout.focusZone,
|
focusZone: model.layout.focusZone,
|
||||||
recentFileCount: editor?.history.count ?? 0,
|
recentFileCount: editor?.history.count ?? 0,
|
||||||
searchSeed: seed
|
searchSeed: seed,
|
||||||
|
gitViewOpen: gitViewOpen,
|
||||||
|
inGitConsole: responder is GitConsoleFieldEditor
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import AppKit
|
|||||||
import HelderCore
|
import HelderCore
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
/// The launcher without a project; with one, the title bar, four columns and status bar, overlays above.
|
/// 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.
|
||||||
struct WorkspaceView: View {
|
struct WorkspaceView: View {
|
||||||
let model: WorkspaceModel
|
let model: WorkspaceModel
|
||||||
|
|
||||||
@@ -29,20 +30,27 @@ struct WorkspaceView: View {
|
|||||||
.zIndex(1)
|
.zIndex(1)
|
||||||
StatusBarView(model: model)
|
StatusBarView(model: model)
|
||||||
}
|
}
|
||||||
|
.overlay {
|
||||||
|
// An overlay over the Git view takes the pointer from it, as from the columns.
|
||||||
|
if model.layout.isGitViewOpen {
|
||||||
|
GitView(model: model)
|
||||||
|
.environment(\.pointerLayer, model.overlay.isPresented ? .workspace : .overlay)
|
||||||
|
}
|
||||||
|
}
|
||||||
.overlay { OverlayHost(model: model) }
|
.overlay { OverlayHost(model: model) }
|
||||||
.overlay {
|
.overlay {
|
||||||
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model).environment(\.pointerLayer, .overlay) }
|
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model).environment(\.pointerLayer, .overlay) }
|
||||||
}
|
}
|
||||||
.background(PointerRefresher(trigger: PointerRefresher.Trigger(
|
.background(PointerRefresher(trigger: PointerRefresher.Trigger(
|
||||||
overlay: model.overlay.current, activePath: model.editor?.activePath, visibility: model.layout.visibility,
|
overlay: model.overlay.current, gitViewOpen: model.layout.isGitViewOpen, activePath: model.editor?.activePath,
|
||||||
scale: model.layout.textScale)))
|
visibility: model.layout.visibility, scale: model.layout.textScale)))
|
||||||
.onAppear { model.layout.windowResized(width: proxy.size.width) }
|
.onAppear { model.layout.windowResized(width: proxy.size.width) }
|
||||||
.onChange(of: proxy.size.width) { _, width in model.layout.windowResized(width: width) }
|
.onChange(of: proxy.size.width) { _, width in model.layout.windowResized(width: width) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The four columns and their splitters. Every column stays mounted: a pane toggle only hides it, so the
|
/// The three columns and their splitters. Every column stays mounted: a pane toggle only hides it, so the
|
||||||
/// terminals, the editor buffer and the tree keep their state. The editor is the flex column; with the editor
|
/// terminals, the editor buffer and the tree keep their state. The editor is the flex column; with the editor
|
||||||
/// hidden the agent column fills. The agent column is keyed by the project so its terminals respawn on a switch.
|
/// hidden the agent column fills. The agent column is keyed by the project so its terminals respawn on a switch.
|
||||||
private struct Columns: View {
|
private struct Columns: View {
|
||||||
@@ -56,12 +64,6 @@ private struct Columns: View {
|
|||||||
let agentFills = v.agent && !v.editor
|
let agentFills = v.agent && !v.editor
|
||||||
let hiddenEditorWidth = max(editorWidth, Metrics.minEditorWidth)
|
let hiddenEditorWidth = max(editorWidth, Metrics.minEditorWidth)
|
||||||
HStack(spacing: 0) {
|
HStack(spacing: 0) {
|
||||||
SourceControlColumn(model: model)
|
|
||||||
.frame(width: layout.widths.sourceControl)
|
|
||||||
.refreshFlash(model.refreshTick)
|
|
||||||
.pane(shown: v.sourceControl)
|
|
||||||
Splitter(onDrag: { layout.dragSourceControl(by: $0) }, onEnd: layout.endDrag)
|
|
||||||
.pane(shown: v.sourceControl && (v.explorer || v.editor || v.agent))
|
|
||||||
ExplorerColumn(model: model)
|
ExplorerColumn(model: model)
|
||||||
.frame(width: layout.widths.explorer)
|
.frame(width: layout.widths.explorer)
|
||||||
.refreshFlash(model.refreshTick)
|
.refreshFlash(model.refreshTick)
|
||||||
@@ -114,7 +116,7 @@ extension View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When a column is hidden while it holds the keyboard (a terminal, the code, the commit box), the window
|
/// When a column is hidden while it holds the keyboard (a terminal, the code), the window
|
||||||
/// takes the keyboard back, so typing never lands in a pane nobody can see.
|
/// takes the keyboard back, so typing never lands in a pane nobody can see.
|
||||||
private struct HiddenPaneFocusGuard: NSViewRepresentable {
|
private struct HiddenPaneFocusGuard: NSViewRepresentable {
|
||||||
let visibility: ColumnVisibility
|
let visibility: ColumnVisibility
|
||||||
@@ -145,10 +147,12 @@ private struct HiddenPaneFocusGuard: NSViewRepresentable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-reads the pointer when what lies under a still mouse changes: an overlay, the open file, a column shown or hidden.
|
/// Re-reads the pointer when what lies under a still mouse changes: an overlay, the Git view, the open file,
|
||||||
|
/// a column shown or hidden.
|
||||||
private struct PointerRefresher: NSViewRepresentable {
|
private struct PointerRefresher: NSViewRepresentable {
|
||||||
struct Trigger: Equatable {
|
struct Trigger: Equatable {
|
||||||
var overlay: Overlay
|
var overlay: Overlay
|
||||||
|
var gitViewOpen: Bool
|
||||||
var activePath: String?
|
var activePath: String?
|
||||||
var visibility: ColumnVisibility
|
var visibility: ColumnVisibility
|
||||||
var scale: Double
|
var scale: Double
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ public struct WorkspaceWindow: View {
|
|||||||
WorkspaceView(model: model)
|
WorkspaceView(model: model)
|
||||||
.frame(minWidth: Metrics.minimumWindow.width, minHeight: Metrics.minimumWindow.height)
|
.frame(minWidth: Metrics.minimumWindow.width, minHeight: Metrics.minimumWindow.height)
|
||||||
.background(Palette.editor)
|
.background(Palette.editor)
|
||||||
.background(WindowBridge(model: model, title: model.title, hasProject: model.root != nil))
|
.background(WindowBridge(model: model, title: model.title, hasProject: model.root != nil,
|
||||||
|
gitViewOpen: model.layout.isGitViewOpen))
|
||||||
.preferredColorScheme(.dark)
|
.preferredColorScheme(.dark)
|
||||||
.focusedSceneValue(\.workspace, model)
|
.focusedSceneValue(\.workspace, model)
|
||||||
.task { await model.start() }
|
.task { await model.start() }
|
||||||
|
|||||||
@@ -1,241 +0,0 @@
|
|||||||
import AppKit
|
|
||||||
import HelderCore
|
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
/// The foot of the Source Control column, edge to edge: the message field over the Commit and push buttons.
|
|
||||||
struct CommitBox: View {
|
|
||||||
let model: WorkspaceModel
|
|
||||||
let store: SourceControlStore
|
|
||||||
@State private var focused = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
VStack(spacing: 0) {
|
|
||||||
field
|
|
||||||
HStack(spacing: 0) {
|
|
||||||
CommitButton(isEnabled: store.state.stagedCount > 0) { model.perform(.commit) }
|
|
||||||
PushButton(lit: store.state.canPush, busy: store.isPushing,
|
|
||||||
help: SourceControlText.pushTooltip(canPush: store.state.canPush, ahead: store.state.ahead)) {
|
|
||||||
model.perform(.push)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(height: 32)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var field: some View {
|
|
||||||
CommitTextView(
|
|
||||||
text: store.commitMessage,
|
|
||||||
focusToken: model.focusRequest?.target == .commitMessage ? model.focusRequest?.id : nil,
|
|
||||||
onChange: { store.setCommitMessage($0) },
|
|
||||||
onCommit: commitFromField,
|
|
||||||
onFocusChange: fieldFocusChanged
|
|
||||||
)
|
|
||||||
.overlay(alignment: .topLeading) {
|
|
||||||
if store.commitMessage.isEmpty {
|
|
||||||
Text("Shift+Enter to commit")
|
|
||||||
.typeRole(Typography.sourceControlRow)
|
|
||||||
.foregroundStyle(Palette.text4)
|
|
||||||
.padding(.leading, CommitTextView.textInset.width)
|
|
||||||
.padding(.top, CommitTextView.textInset.height)
|
|
||||||
.allowsHitTesting(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(maxWidth: .infinity)
|
|
||||||
.frame(height: 72)
|
|
||||||
.background(Palette.editor)
|
|
||||||
.hairline(.top)
|
|
||||||
.overlay {
|
|
||||||
if focused {
|
|
||||||
ZStack {
|
|
||||||
Rectangle().strokeBorder(Palette.amber, lineWidth: Metrics.accentRule)
|
|
||||||
Rectangle().inset(by: Metrics.accentRule).strokeBorder(Palette.focusRing, lineWidth: Metrics.focusRingWidth)
|
|
||||||
}
|
|
||||||
.allowsHitTesting(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.animation(Metrics.smallControlTransition, value: focused)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func fieldFocusChanged(_ isFocused: Bool) {
|
|
||||||
focused = isFocused
|
|
||||||
guard isFocused else { return }
|
|
||||||
model.focusTaken(.commitMessage)
|
|
||||||
model.pointerFocused(.sourceControl)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shift/⌘/Ctrl+Return commits only when there is something to commit; the button always asks the model.
|
|
||||||
private func commitFromField() {
|
|
||||||
guard store.canCommit else { return }
|
|
||||||
model.perform(.commit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The amber button that fills the action row; nothing staged gives the resting panel look.
|
|
||||||
private struct CommitButton: View {
|
|
||||||
let isEnabled: Bool
|
|
||||||
let action: () -> Void
|
|
||||||
@State private var hovered = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Button(action: action) {
|
|
||||||
HStack(spacing: 6) {
|
|
||||||
Text("Commit").typeRole(Typography.commitButton)
|
|
||||||
IconView(glyph: .arrowUp)
|
|
||||||
}
|
|
||||||
.foregroundStyle(isEnabled ? Palette.commitInk : Palette.text4)
|
|
||||||
.padding(.horizontal, 11)
|
|
||||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
||||||
.background(isEnabled ? (hovered ? Palette.amberSoft : Palette.amber) : Palette.panel)
|
|
||||||
.contentShape(Rectangle())
|
|
||||||
}
|
|
||||||
.buttonStyle(.plain)
|
|
||||||
.pointerHand()
|
|
||||||
.disabled(!isEnabled)
|
|
||||||
.onHover { hovered = $0 }
|
|
||||||
.animation(Metrics.colorTransition, value: hovered)
|
|
||||||
.help("Commit the staged files (⌘↵)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The 36pt push button right of Commit; lit (amber on the tint) while the branch is ahead of its remote.
|
|
||||||
private struct PushButton: View {
|
|
||||||
let lit: Bool
|
|
||||||
let busy: Bool
|
|
||||||
let help: String
|
|
||||||
let action: () -> Void
|
|
||||||
@State private var hovered = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Button(action: action) {
|
|
||||||
IconView(glyph: .push)
|
|
||||||
.foregroundStyle(iconColor)
|
|
||||||
.frame(width: 36)
|
|
||||||
.frame(maxHeight: .infinity)
|
|
||||||
.background(lit ? Palette.amberTint : (hovered ? Palette.hover : Palette.panel))
|
|
||||||
.hairline(.top)
|
|
||||||
.hairline(.leading)
|
|
||||||
.contentShape(Rectangle())
|
|
||||||
.opacity(busy ? 0.4 : 1)
|
|
||||||
}
|
|
||||||
.buttonStyle(.plain)
|
|
||||||
.pointerHand()
|
|
||||||
.disabled(busy)
|
|
||||||
.onHover { hovered = $0 }
|
|
||||||
.animation(Metrics.colorTransition, value: hovered)
|
|
||||||
.help(help)
|
|
||||||
}
|
|
||||||
|
|
||||||
private var iconColor: Color {
|
|
||||||
if lit { return hovered ? Palette.amberSoft : Palette.amber }
|
|
||||||
return hovered ? Palette.amber : Palette.text3
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A plain NSTextView, because SwiftUI's fields cannot tell Shift+Return from Return.
|
|
||||||
struct CommitTextView: NSViewRepresentable {
|
|
||||||
/// Where the first glyph sits: 9pt from the top, 12pt from the left.
|
|
||||||
static let textInset = CGSize(width: 12, height: 9)
|
|
||||||
|
|
||||||
let text: String
|
|
||||||
/// A new value takes first responder once.
|
|
||||||
let focusToken: UUID?
|
|
||||||
let onChange: (String) -> Void
|
|
||||||
let onCommit: () -> Void
|
|
||||||
let onFocusChange: (Bool) -> Void
|
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator() }
|
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSScrollView {
|
|
||||||
let scroll = NSScrollView()
|
|
||||||
scroll.drawsBackground = false
|
|
||||||
scroll.hasVerticalScroller = false
|
|
||||||
scroll.borderType = .noBorder
|
|
||||||
|
|
||||||
let textView = CommitNSTextView()
|
|
||||||
textView.delegate = context.coordinator
|
|
||||||
textView.drawsBackground = false
|
|
||||||
textView.isRichText = false
|
|
||||||
textView.allowsUndo = true
|
|
||||||
textView.isAutomaticQuoteSubstitutionEnabled = false
|
|
||||||
textView.isAutomaticDashSubstitutionEnabled = false
|
|
||||||
textView.isAutomaticSpellingCorrectionEnabled = false
|
|
||||||
textView.isContinuousSpellCheckingEnabled = false
|
|
||||||
textView.font = Typography.sourceControlRow.nsFont
|
|
||||||
textView.textColor = NSColor(hex: 0xE4E7E6)
|
|
||||||
textView.insertionPointColor = NSColor(hex: 0xE8913A)
|
|
||||||
let padding = textView.textContainer?.lineFragmentPadding ?? 5
|
|
||||||
textView.textContainerInset = NSSize(width: Self.textInset.width - padding, height: Self.textInset.height)
|
|
||||||
textView.isVerticallyResizable = true
|
|
||||||
textView.isHorizontallyResizable = false
|
|
||||||
textView.autoresizingMask = [.width]
|
|
||||||
textView.textContainer?.widthTracksTextView = true
|
|
||||||
textView.fillsClipView = true
|
|
||||||
let paragraph = NSMutableParagraphStyle()
|
|
||||||
paragraph.minimumLineHeight = 18
|
|
||||||
paragraph.maximumLineHeight = 18
|
|
||||||
textView.defaultParagraphStyle = paragraph
|
|
||||||
textView.typingAttributes[.paragraphStyle] = paragraph
|
|
||||||
scroll.documentView = textView
|
|
||||||
context.coordinator.textView = textView
|
|
||||||
return scroll
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
|
||||||
let coordinator = context.coordinator
|
|
||||||
coordinator.parent = self
|
|
||||||
guard let textView = coordinator.textView else { return }
|
|
||||||
textView.onCommit = onCommit
|
|
||||||
textView.onFocusChange = onFocusChange
|
|
||||||
if textView.string != text {
|
|
||||||
textView.string = text
|
|
||||||
}
|
|
||||||
if let focusToken, coordinator.lastFocusToken != focusToken {
|
|
||||||
coordinator.lastFocusToken = focusToken
|
|
||||||
DispatchQueue.main.async { textView.window?.makeFirstResponder(textView) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
|
||||||
var parent: CommitTextView?
|
|
||||||
weak var textView: CommitNSTextView?
|
|
||||||
var lastFocusToken: UUID?
|
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
|
||||||
guard let textView else { return }
|
|
||||||
let normalized = SourceControlText.normalizeCommitMessage(textView.string)
|
|
||||||
if normalized != textView.string {
|
|
||||||
let caret = textView.selectedRange()
|
|
||||||
textView.string = normalized
|
|
||||||
textView.setSelectedRange(NSRange(location: min(caret.location, (normalized as NSString).length), length: 0))
|
|
||||||
}
|
|
||||||
parent?.onChange(normalized)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final class CommitNSTextView: PointerBoundTextView {
|
|
||||||
var onCommit: (() -> Void)?
|
|
||||||
var onFocusChange: ((Bool) -> Void)?
|
|
||||||
|
|
||||||
override func keyDown(with event: NSEvent) {
|
|
||||||
let isReturn = event.keyCode == 36 || event.keyCode == 76
|
|
||||||
let flags = event.modifierFlags.intersection([.shift, .command, .control])
|
|
||||||
if isReturn && !flags.isEmpty {
|
|
||||||
onCommit?()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
super.keyDown(with: event)
|
|
||||||
}
|
|
||||||
|
|
||||||
override func becomeFirstResponder() -> Bool {
|
|
||||||
let accepted = super.becomeFirstResponder()
|
|
||||||
if accepted { onFocusChange?(true) }
|
|
||||||
return accepted
|
|
||||||
}
|
|
||||||
|
|
||||||
override func resignFirstResponder() -> Bool {
|
|
||||||
let accepted = super.resignFirstResponder()
|
|
||||||
if accepted { onFocusChange?(false) }
|
|
||||||
return accepted
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,291 +0,0 @@
|
|||||||
import HelderCore
|
|
||||||
import SwiftUI
|
|
||||||
|
|
||||||
/// Column A: staged and unstaged rows grouped by folder, with the commit box at the foot.
|
|
||||||
public struct SourceControlColumn: View {
|
|
||||||
let model: WorkspaceModel
|
|
||||||
@State private var columnFrame = CGRect.zero
|
|
||||||
/// A cursor that follows the pointer must not scroll the list under it.
|
|
||||||
@State private var hoveredRowID: String?
|
|
||||||
|
|
||||||
public init(model: WorkspaceModel) {
|
|
||||||
self.model = model
|
|
||||||
}
|
|
||||||
|
|
||||||
public var body: some View {
|
|
||||||
Group {
|
|
||||||
if let store = model.sourceControl {
|
|
||||||
content(store)
|
|
||||||
} else {
|
|
||||||
Color.clear
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
||||||
.background(Palette.column(.sourceControl, active: isActive))
|
|
||||||
.background(GlobalFrameReader(frame: $columnFrame))
|
|
||||||
.simultaneousGesture(TapGesture().onEnded { model.pointerFocused(.sourceControl) })
|
|
||||||
}
|
|
||||||
|
|
||||||
private var isActive: Bool { model.layout.activePanel == .sourceControl }
|
|
||||||
|
|
||||||
private func content(_ store: SourceControlStore) -> some View {
|
|
||||||
VStack(spacing: 0) {
|
|
||||||
list(store)
|
|
||||||
CommitBox(model: model, store: store)
|
|
||||||
}
|
|
||||||
.task { await store.loadIfNeeded() }
|
|
||||||
}
|
|
||||||
|
|
||||||
private func list(_ store: SourceControlStore) -> some View {
|
|
||||||
ScrollViewReader { proxy in
|
|
||||||
ScrollView {
|
|
||||||
LazyVStack(alignment: .leading, spacing: 0) {
|
|
||||||
sections(store)
|
|
||||||
}
|
|
||||||
.padding(.bottom, 8)
|
|
||||||
}
|
|
||||||
.scrollIndicators(.automatic)
|
|
||||||
.onChange(of: store.selectedRowID) { _, id in
|
|
||||||
guard isActive, let id, id != hoveredRowID else { return }
|
|
||||||
proxy.scrollTo(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(maxHeight: .infinity)
|
|
||||||
}
|
|
||||||
|
|
||||||
@ViewBuilder
|
|
||||||
private func sections(_ store: SourceControlStore) -> some View {
|
|
||||||
let staged = store.stagedGroups
|
|
||||||
let unstaged = store.unstagedGroups
|
|
||||||
if store.hasLoaded && !store.state.isRepository {
|
|
||||||
EmptyState(text: "— Not a git repository.")
|
|
||||||
} else if staged.isEmpty && unstaged.isEmpty {
|
|
||||||
EmptyState(text: "— No changes. The working tree is clean.")
|
|
||||||
} else {
|
|
||||||
GroupHeader(title: "Staged Changes", count: store.state.stagedCount,
|
|
||||||
quickAction: staged.isEmpty ? nil : QuickAction(glyph: .minus, help: "Unstage all") {
|
|
||||||
Task { await store.unstageAll() }
|
|
||||||
})
|
|
||||||
if staged.isEmpty {
|
|
||||||
EmptyLine(text: "— Nothing staged.")
|
|
||||||
} else {
|
|
||||||
groups(staged, store)
|
|
||||||
}
|
|
||||||
Hairline().padding(.horizontal, 12).padding(.top, 16)
|
|
||||||
GroupHeader(title: "Changes", count: store.state.unstagedCount,
|
|
||||||
quickAction: unstaged.isEmpty ? nil : QuickAction(glyph: .plus, help: "Stage all") {
|
|
||||||
Task { await store.stageAll() }
|
|
||||||
})
|
|
||||||
if unstaged.isEmpty {
|
|
||||||
EmptyLine(text: "— All changes are staged.")
|
|
||||||
} else {
|
|
||||||
groups(unstaged, store)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func groups(_ groups: [ChangeGroup], _ store: SourceControlStore) -> some View {
|
|
||||||
ForEach(groups, id: \.dir) { group in
|
|
||||||
DirHeader(dir: group.dir)
|
|
||||||
ForEach(group.rows) { change in
|
|
||||||
GitRowView(
|
|
||||||
change: change,
|
|
||||||
selected: isSelected(change, store),
|
|
||||||
onOpen: { open(change, store) },
|
|
||||||
onToggleStage: { toggleStage(change) },
|
|
||||||
onHover: { hoveredRowID = change.id; store.selectedRowID = change.id },
|
|
||||||
onContextMenu: { point in showMenu(for: change, at: point, store) }
|
|
||||||
)
|
|
||||||
.reportsRowFrame(.git(change.id), to: model)
|
|
||||||
.id(change.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Row state and actions
|
|
||||||
|
|
||||||
/// The open file's row (its half, when a git row opened it), the keyboard cursor, or the row whose menu is open.
|
|
||||||
private func isSelected(_ change: Change, _ store: SourceControlStore) -> Bool {
|
|
||||||
if case let .contextMenu(request) = model.overlay.current,
|
|
||||||
request.target == .gitRow(path: change.path, staged: change.staged) { return true }
|
|
||||||
if isActive && store.selectedRowID == change.id { return true }
|
|
||||||
guard let editor = model.editor, editor.activePath == change.path else { return false }
|
|
||||||
guard let side = editor.sides[change.path] else { return true }
|
|
||||||
return side == (change.staged ? .staged : .unstaged)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func open(_ change: Change, _ store: SourceControlStore) {
|
|
||||||
store.selectedRowID = change.id
|
|
||||||
model.perform(.open(change.path, OpenOptions(side: change.staged ? .staged : .unstaged)))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func toggleStage(_ change: Change) {
|
|
||||||
model.perform(.context(change.staged ? .unstage(change.path) : .stage(change.path)))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func showMenu(for change: Change, at point: CGPoint, _ store: SourceControlStore) {
|
|
||||||
model.pointerFocused(.sourceControl)
|
|
||||||
store.selectedRowID = change.id
|
|
||||||
let anchor = CGPoint(x: columnFrame.maxX, y: point.y)
|
|
||||||
model.perform(.showContextMenu(.gitRow(path: change.path, staged: change.staged), anchor: anchor))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Parts
|
|
||||||
|
|
||||||
/// A group's hover-only quick action (Unstage all, Stage all).
|
|
||||||
private struct QuickAction {
|
|
||||||
let glyph: IconGlyph
|
|
||||||
let help: String
|
|
||||||
let action: () -> Void
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct GroupHeader: View {
|
|
||||||
let title: String
|
|
||||||
let count: Int
|
|
||||||
/// nil when the group has no rows.
|
|
||||||
let quickAction: QuickAction?
|
|
||||||
@State private var hovered = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
HStack(spacing: 8) {
|
|
||||||
Text(title).typeRole(RowStyle.groupLabelRole).foregroundStyle(Palette.text4)
|
|
||||||
if let quickAction {
|
|
||||||
QuickActionButton(glyph: quickAction.glyph, help: quickAction.help, action: quickAction.action)
|
|
||||||
.frame(width: 14, height: 10)
|
|
||||||
.opacity(hovered ? 1 : 0)
|
|
||||||
}
|
|
||||||
Spacer(minLength: 0)
|
|
||||||
Text("\(count)").typeRole(RowStyle.groupLabelRole).foregroundStyle(Palette.amber)
|
|
||||||
}
|
|
||||||
.padding(.horizontal, 12)
|
|
||||||
.padding(.top, 14)
|
|
||||||
.padding(.bottom, 6)
|
|
||||||
.contentShape(Rectangle())
|
|
||||||
.onHover { hovered = $0 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct DirHeader: View {
|
|
||||||
let dir: String
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
HStack(spacing: 8) {
|
|
||||||
FolderGlyph(open: false)
|
|
||||||
Text(dir.isEmpty ? "." : dir)
|
|
||||||
.typeRole(RowStyle.dirHeadRole)
|
|
||||||
.foregroundStyle(Palette.text4)
|
|
||||||
.lineLimit(1)
|
|
||||||
.truncationMode(.head)
|
|
||||||
}
|
|
||||||
.padding(.leading, 14)
|
|
||||||
.padding(.trailing, 12)
|
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
|
||||||
.frame(height: 24)
|
|
||||||
.help(dir.isEmpty ? "(project root)" : dir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The column's only line when there is nothing to list.
|
|
||||||
private struct EmptyState: View {
|
|
||||||
let text: String
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Text(text)
|
|
||||||
.typeRole(TypeRole(.sansRegular, 12, lineHeight: 19.2))
|
|
||||||
.foregroundStyle(Palette.text4)
|
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
|
||||||
.padding(.horizontal, 12)
|
|
||||||
.padding(.vertical, 14)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The line under a group header that has no rows.
|
|
||||||
private struct EmptyLine: View {
|
|
||||||
let text: String
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
Text(text)
|
|
||||||
.typeRole(Typography.sourceControlRow)
|
|
||||||
.foregroundStyle(Palette.text4)
|
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
|
||||||
.padding(.horizontal, 12)
|
|
||||||
.padding(.top, 2)
|
|
||||||
.padding(.bottom, 8)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One git row: status letter, badge, name, line counts, and the hover +/− in their place.
|
|
||||||
private struct GitRowView: View {
|
|
||||||
let change: Change
|
|
||||||
let selected: Bool
|
|
||||||
let onOpen: () -> Void
|
|
||||||
let onToggleStage: () -> Void
|
|
||||||
let onHover: () -> Void
|
|
||||||
let onContextMenu: (CGPoint) -> Void
|
|
||||||
@State private var hovered = false
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
HStack(spacing: 8) {
|
|
||||||
Text(change.status.rawValue)
|
|
||||||
.typeRole(RowStyle.gitLetterRole)
|
|
||||||
.foregroundStyle(letterColor)
|
|
||||||
.frame(width: 12, alignment: .leading)
|
|
||||||
TypeBadge(path: change.path)
|
|
||||||
Text(PathUtils.basename(change.path))
|
|
||||||
.typeRole(selected ? TypeRole(.sansMedium, 12) : Typography.sourceControlRow)
|
|
||||||
.strikethrough(change.isDeleted, color: Palette.text4)
|
|
||||||
.foregroundStyle(nameColor)
|
|
||||||
.lineLimit(1)
|
|
||||||
.truncationMode(.tail)
|
|
||||||
Spacer(minLength: 0)
|
|
||||||
trailing
|
|
||||||
}
|
|
||||||
.padding(.leading, 14)
|
|
||||||
.padding(.trailing, 12)
|
|
||||||
.frame(height: Metrics.sourceControlRow)
|
|
||||||
.selectableRow(isSelected: selected, isHovered: hovered)
|
|
||||||
.contentShape(Rectangle())
|
|
||||||
.pointerHand()
|
|
||||||
.onTapGesture(perform: onOpen)
|
|
||||||
.onHover { inside in
|
|
||||||
hovered = inside
|
|
||||||
if inside { onHover() }
|
|
||||||
}
|
|
||||||
.overlay(RightClickArea(onRightClick: onContextMenu))
|
|
||||||
.help(change.path)
|
|
||||||
}
|
|
||||||
|
|
||||||
@ViewBuilder
|
|
||||||
private var trailing: some View {
|
|
||||||
if hovered || selected {
|
|
||||||
QuickActionButton(glyph: change.staged ? .minus : .plus,
|
|
||||||
help: change.staged ? "Unstage changes" : "Stage changes",
|
|
||||||
action: onToggleStage)
|
|
||||||
} else if change.added > 0 || change.removed > 0 {
|
|
||||||
HStack(spacing: 4) {
|
|
||||||
if change.added > 0 { Text("+\(change.added)").foregroundStyle(Palette.addedText) }
|
|
||||||
if change.removed > 0 { Text("\u{2212}\(change.removed)").foregroundStyle(Palette.removedText) }
|
|
||||||
}
|
|
||||||
.typeRole(Typography.meta)
|
|
||||||
.lineLimit(1)
|
|
||||||
.fixedSize()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Staged letters read teal whatever the status; unstaged ones by status.
|
|
||||||
private var letterColor: Color {
|
|
||||||
if change.staged { return Palette.stagedLetter }
|
|
||||||
switch change.status {
|
|
||||||
case .deleted: return Palette.amberDeep
|
|
||||||
case .renamed: return Palette.text3
|
|
||||||
default: return Palette.unstagedLetter
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var nameColor: Color {
|
|
||||||
if change.isDeleted { return Palette.text4 }
|
|
||||||
if selected { return Palette.text1 }
|
|
||||||
return SourceControlText.isTestFile(change.path) ? Palette.text4 : Palette.text3
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -82,7 +82,7 @@ public final class EditorStore {
|
|||||||
/// Closes the overlay only while it is the Diff.
|
/// Closes the overlay only while it is the Diff.
|
||||||
@ObservationIgnored public var dismissDiffOverlay: (() -> Void)?
|
@ObservationIgnored public var dismissDiffOverlay: (() -> Void)?
|
||||||
@ObservationIgnored public var showToast: ((String, String?) -> Void)?
|
@ObservationIgnored public var showToast: ((String, String?) -> Void)?
|
||||||
/// After a write: the git column should re-read.
|
/// After a write: git should re-read.
|
||||||
@ObservationIgnored public var fileSaved: ((String) -> Void)?
|
@ObservationIgnored public var fileSaved: ((String) -> Void)?
|
||||||
/// Asked before a dirty file closes; without it a dirty file stays open.
|
/// Asked before a dirty file closes; without it a dirty file stays open.
|
||||||
@ObservationIgnored public var confirmUnsavedClose: ((String) -> UnsavedCloseChoice)?
|
@ObservationIgnored public var confirmUnsavedClose: ((String) -> UnsavedCloseChoice)?
|
||||||
@@ -110,7 +110,7 @@ public final class EditorStore {
|
|||||||
self.init(root: root, files: files, gitState: { sourceControl.state }, session: session, recentFiles: recentFiles)
|
self.init(root: root, files: files, gitState: { sourceControl.state }, session: session, recentFiles: recentFiles)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `gitState` is read, never written: the editor only follows the git column.
|
/// `gitState` is read, never written: the editor only follows git.
|
||||||
public init(root: String, files: FileServicing, gitState: @escaping @MainActor () -> GitWorkingState,
|
public init(root: String, files: FileServicing, gitState: @escaping @MainActor () -> GitWorkingState,
|
||||||
session: SessionStoring, recentFiles: RecentFilesStoring) {
|
session: SessionStoring, recentFiles: RecentFilesStoring) {
|
||||||
self.root = root
|
self.root = root
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import Observation
|
|||||||
|
|
||||||
/// Which column has keyboard focus: drives the active-panel tint and arrow-key navigation.
|
/// Which column has keyboard focus: drives the active-panel tint and arrow-key navigation.
|
||||||
public enum Panel: String, Sendable, CaseIterable {
|
public enum Panel: String, Sendable, CaseIterable {
|
||||||
case sourceControl
|
|
||||||
case explorer
|
case explorer
|
||||||
case editor
|
case editor
|
||||||
case terminal
|
case terminal
|
||||||
@@ -13,42 +12,36 @@ public enum Panel: String, Sendable, CaseIterable {
|
|||||||
|
|
||||||
/// The column layout one project remembers between launches.
|
/// The column layout one project remembers between launches.
|
||||||
public struct ColumnLayoutSnapshot: Codable, Sendable, Equatable {
|
public struct ColumnLayoutSnapshot: Codable, Sendable, Equatable {
|
||||||
public var sourceControlWidth: Double
|
|
||||||
public var explorerWidth: Double
|
public var explorerWidth: Double
|
||||||
public var agentWidth: Double
|
public var agentWidth: Double
|
||||||
public var fluid: Bool
|
public var fluid: Bool
|
||||||
public var gitVisible: Bool
|
|
||||||
public var explorerVisible: Bool
|
public var explorerVisible: Bool
|
||||||
public var fileVisible: Bool
|
public var fileVisible: Bool
|
||||||
public var claudeVisible: Bool
|
public var claudeVisible: Bool
|
||||||
|
|
||||||
public init(sourceControlWidth: Double, explorerWidth: Double, agentWidth: Double, fluid: Bool,
|
public init(explorerWidth: Double, agentWidth: Double, fluid: Bool, visibility: ColumnVisibility = .all) {
|
||||||
visibility: ColumnVisibility = .all) {
|
|
||||||
self.sourceControlWidth = sourceControlWidth
|
|
||||||
self.explorerWidth = explorerWidth
|
self.explorerWidth = explorerWidth
|
||||||
self.agentWidth = agentWidth
|
self.agentWidth = agentWidth
|
||||||
self.fluid = fluid
|
self.fluid = fluid
|
||||||
gitVisible = visibility.sourceControl
|
|
||||||
explorerVisible = visibility.explorer
|
explorerVisible = visibility.explorer
|
||||||
fileVisible = visibility.editor
|
fileVisible = visibility.editor
|
||||||
claudeVisible = visibility.agent
|
claudeVisible = visibility.agent
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Older snapshots only know `gitVisible`; a missing flag means shown.
|
/// A missing visibility flag means shown. Snapshots from before the Git view also hold
|
||||||
|
/// `sourceControlWidth` and `gitVisible`; they are ignored.
|
||||||
public init(from decoder: Decoder) throws {
|
public init(from decoder: Decoder) throws {
|
||||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
sourceControlWidth = try c.decode(Double.self, forKey: .sourceControlWidth)
|
|
||||||
explorerWidth = try c.decode(Double.self, forKey: .explorerWidth)
|
explorerWidth = try c.decode(Double.self, forKey: .explorerWidth)
|
||||||
agentWidth = try c.decode(Double.self, forKey: .agentWidth)
|
agentWidth = try c.decode(Double.self, forKey: .agentWidth)
|
||||||
fluid = try c.decode(Bool.self, forKey: .fluid)
|
fluid = try c.decode(Bool.self, forKey: .fluid)
|
||||||
gitVisible = try c.decodeIfPresent(Bool.self, forKey: .gitVisible) ?? true
|
|
||||||
explorerVisible = try c.decodeIfPresent(Bool.self, forKey: .explorerVisible) ?? true
|
explorerVisible = try c.decodeIfPresent(Bool.self, forKey: .explorerVisible) ?? true
|
||||||
fileVisible = try c.decodeIfPresent(Bool.self, forKey: .fileVisible) ?? true
|
fileVisible = try c.decodeIfPresent(Bool.self, forKey: .fileVisible) ?? true
|
||||||
claudeVisible = try c.decodeIfPresent(Bool.self, forKey: .claudeVisible) ?? true
|
claudeVisible = try c.decodeIfPresent(Bool.self, forKey: .claudeVisible) ?? true
|
||||||
}
|
}
|
||||||
|
|
||||||
public var visibility: ColumnVisibility {
|
public var visibility: ColumnVisibility {
|
||||||
ColumnVisibility(sourceControl: gitVisible, explorer: explorerVisible, editor: fileVisible, agent: claudeVisible)
|
ColumnVisibility(explorer: explorerVisible, editor: fileVisible, agent: claudeVisible)
|
||||||
}
|
}
|
||||||
|
|
||||||
public static func key(root: String) -> String { "helder.layout:" + root }
|
public static func key(root: String) -> String { "helder.layout:" + root }
|
||||||
@@ -91,12 +84,14 @@ public struct UserDefaultsLayoutStore: LayoutPersisting, @unchecked Sendable {
|
|||||||
@Observable
|
@Observable
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class LayoutStore {
|
public final class LayoutStore {
|
||||||
public private(set) var widths = ColumnWidths(sourceControl: 236, explorer: 288, agent: 480)
|
public private(set) var widths = ColumnWidths(explorer: 288, agent: 480)
|
||||||
/// The agent pane's share of the right column; persisted across launches.
|
/// The agent pane's share of the right column; persisted across launches.
|
||||||
public private(set) var agentFraction: Double
|
public private(set) var agentFraction: Double
|
||||||
public private(set) var windowWidth: Double = 1680
|
public private(set) var windowWidth: Double = 1680
|
||||||
/// The title bar's pane toggles; ⌘G flips Source Control.
|
/// The title bar's pane toggles; ⌘1–⌘3 flip them.
|
||||||
public private(set) var visibility = ColumnVisibility.all
|
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
|
||||||
/// ⌘L: columns re-fit on resize and focus. A manual splitter drag turns this off.
|
/// ⌘L: columns re-fit on resize and focus. A manual splitter drag turns this off.
|
||||||
public private(set) var fluid = true
|
public private(set) var fluid = true
|
||||||
/// ⌘.: dotfiles show in the tree and the search.
|
/// ⌘.: dotfiles show in the tree and the search.
|
||||||
@@ -145,25 +140,23 @@ public final class LayoutStore {
|
|||||||
self.root = root
|
self.root = root
|
||||||
activePanel = nil
|
activePanel = nil
|
||||||
focusZone = .neutral
|
focusZone = .neutral
|
||||||
|
isGitViewOpen = false
|
||||||
let saved = persistence?.load(root: root)
|
let saved = persistence?.load(root: root)
|
||||||
visibility = saved?.visibility ?? .all
|
visibility = saved?.visibility ?? .all
|
||||||
fluid = saved?.fluid ?? true
|
fluid = saved?.fluid ?? true
|
||||||
if let saved, !saved.fluid {
|
if let saved, !saved.fluid {
|
||||||
widths = ColumnWidths(sourceControl: clamp(saved.sourceControlWidth, ColumnLayout.sourceControlRange),
|
widths = ColumnWidths(explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
|
||||||
explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
|
|
||||||
agent: max(saved.agentWidth, ColumnLayout.minEditorWidth))
|
agent: max(saved.agentWidth, ColumnLayout.minEditorWidth))
|
||||||
}
|
}
|
||||||
refit()
|
refit()
|
||||||
}
|
}
|
||||||
|
|
||||||
public var snapshot: ColumnLayoutSnapshot {
|
public var snapshot: ColumnLayoutSnapshot {
|
||||||
ColumnLayoutSnapshot(sourceControlWidth: widths.sourceControl, explorerWidth: widths.explorer,
|
ColumnLayoutSnapshot(explorerWidth: widths.explorer, agentWidth: widths.agent, fluid: fluid, visibility: visibility)
|
||||||
agentWidth: widths.agent, fluid: fluid, visibility: visibility)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func isVisible(_ panel: Panel) -> Bool {
|
public func isVisible(_ panel: Panel) -> Bool {
|
||||||
switch panel {
|
switch panel {
|
||||||
case .sourceControl: visibility.sourceControl
|
|
||||||
case .explorer: visibility.explorer
|
case .explorer: visibility.explorer
|
||||||
case .editor: visibility.editor
|
case .editor: visibility.editor
|
||||||
case .terminal: visibility.agent
|
case .terminal: visibility.agent
|
||||||
@@ -178,7 +171,6 @@ public final class LayoutStore {
|
|||||||
public func setVisible(_ panel: Panel, _ visible: Bool) {
|
public func setVisible(_ panel: Panel, _ visible: Bool) {
|
||||||
guard isVisible(panel) != visible else { return }
|
guard isVisible(panel) != visible else { return }
|
||||||
switch panel {
|
switch panel {
|
||||||
case .sourceControl: visibility.sourceControl = visible
|
|
||||||
case .explorer: visibility.explorer = visible
|
case .explorer: visibility.explorer = visible
|
||||||
case .editor: visibility.editor = visible
|
case .editor: visibility.editor = visible
|
||||||
case .terminal: visibility.agent = visible
|
case .terminal: visibility.agent = visible
|
||||||
@@ -188,6 +180,18 @@ public final class LayoutStore {
|
|||||||
save()
|
save()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public func openGitView() {
|
||||||
|
isGitViewOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
|
public func closeGitView() {
|
||||||
|
isGitViewOpen = false
|
||||||
|
}
|
||||||
|
|
||||||
|
public func toggleGitView() {
|
||||||
|
isGitViewOpen.toggle()
|
||||||
|
}
|
||||||
|
|
||||||
public func toggleFluid() {
|
public func toggleFluid() {
|
||||||
fluid.toggle()
|
fluid.toggle()
|
||||||
refit()
|
refit()
|
||||||
@@ -221,11 +225,6 @@ public final class LayoutStore {
|
|||||||
refit()
|
refit()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func dragSourceControl(by delta: Double) {
|
|
||||||
fluid = false
|
|
||||||
widths.sourceControl = clamp(widths.sourceControl + delta, ColumnLayout.sourceControlRange)
|
|
||||||
}
|
|
||||||
|
|
||||||
public func dragExplorer(by delta: Double) {
|
public func dragExplorer(by delta: Double) {
|
||||||
fluid = false
|
fluid = false
|
||||||
widths.explorer = clamp(widths.explorer + delta, ColumnLayout.explorerRange)
|
widths.explorer = clamp(widths.explorer + delta, ColumnLayout.explorerRange)
|
||||||
@@ -267,12 +266,10 @@ public final class LayoutStore {
|
|||||||
guard isVisible(panel) else { return nil }
|
guard isVisible(panel) else { return nil }
|
||||||
let splitter = ColumnLayout.splitterWidth
|
let splitter = ColumnLayout.splitterWidth
|
||||||
let v = visibility
|
let v = visibility
|
||||||
let explorerStart = v.sourceControl ? widths.sourceControl + splitter : 0
|
let flexStart = v.explorer ? widths.explorer + splitter : 0
|
||||||
let flexStart = explorerStart + (v.explorer ? widths.explorer + splitter : 0)
|
|
||||||
let agentStart = v.editor ? max(flexStart, windowWidth - widths.agent) : flexStart
|
let agentStart = v.editor ? max(flexStart, windowWidth - widths.agent) : flexStart
|
||||||
switch panel {
|
switch panel {
|
||||||
case .sourceControl: return 0...widths.sourceControl
|
case .explorer: return 0...widths.explorer
|
||||||
case .explorer: return explorerStart...(explorerStart + widths.explorer)
|
|
||||||
case .editor: return flexStart...max(flexStart, v.agent ? agentStart - splitter : windowWidth)
|
case .editor: return flexStart...max(flexStart, v.agent ? agentStart - splitter : windowWidth)
|
||||||
case .terminal: return agentStart...max(agentStart, windowWidth)
|
case .terminal: return agentStart...max(agentStart, windowWidth)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,31 +3,76 @@ import HelderCore
|
|||||||
import HelderServices
|
import HelderServices
|
||||||
import Observation
|
import Observation
|
||||||
|
|
||||||
|
/// The long git run the Git view's Pull or Push button is waiting on.
|
||||||
|
public enum GitBusy: Sendable, Equatable {
|
||||||
|
case push
|
||||||
|
case pull
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One console line with an id that stays put while older lines drop off the top.
|
||||||
|
public struct GitConsoleEntry: Identifiable, Sendable, Equatable {
|
||||||
|
public let id: Int
|
||||||
|
public var line: GitConsoleLine
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an expanded file row shows under it.
|
||||||
|
public enum GitRowDetail: Equatable {
|
||||||
|
case rows([InlineDiffRow])
|
||||||
|
/// The file is over the diff cap, so no text was read.
|
||||||
|
case tooBig
|
||||||
|
}
|
||||||
|
|
||||||
@Observable
|
@Observable
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class SourceControlStore {
|
public final class SourceControlStore {
|
||||||
public private(set) var state = GitWorkingState.empty
|
public private(set) var state = GitWorkingState.empty {
|
||||||
/// False until the first read landed, so the column can tell "loading" from "clean".
|
didSet {
|
||||||
|
sections = GitSections.build(state.changes)
|
||||||
|
inlineCache = [:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// False until the first read landed, so the view can tell "loading" from "clean".
|
||||||
public private(set) var hasLoaded = false
|
public private(set) var hasLoaded = false
|
||||||
/// The commit box draft; always one lowercase line (see `setCommitMessage`).
|
public private(set) var sections: [GitSection] = []
|
||||||
|
public private(set) var collapsedSections: Set<GitSectionKind> = []
|
||||||
|
/// Keys from `rowKey(_:_:)`.
|
||||||
|
public private(set) var expandedRows: Set<String> = []
|
||||||
|
/// The commit message draft; always one lowercase line (see `setCommitMessage`).
|
||||||
public private(set) var commitMessage = ""
|
public private(set) var commitMessage = ""
|
||||||
/// The keyboard cursor, kept as a row id because the list reorders under it.
|
/// `user.name <user.email>`, read when the view opens.
|
||||||
public var selectedRowID: String?
|
public private(set) var author: String?
|
||||||
public private(set) var isPushing = false
|
public private(set) var branches = GitBranchList.empty
|
||||||
/// The `git` config section: confirmations and the poll interval.
|
public private(set) var busy: GitBusy?
|
||||||
|
public private(set) var lines: [GitConsoleEntry] = []
|
||||||
|
public var consoleInput = ""
|
||||||
|
public private(set) var history: [String] = []
|
||||||
|
/// The `git` config section: the discard confirmation and the poll interval.
|
||||||
public var config = HelderConfig.Git() {
|
public var config = HelderConfig.Git() {
|
||||||
didSet {
|
didSet {
|
||||||
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
|
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static let maxConsoleLines = 400
|
||||||
|
public static let remoteTimeout: TimeInterval = 120
|
||||||
|
|
||||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
/// 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 public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||||
|
/// Asks for the keyboard in the message field, after git refused an empty message.
|
||||||
|
@ObservationIgnored public var focusMessage: () -> Void = {}
|
||||||
|
|
||||||
@ObservationIgnored private let git: GitServicing
|
@ObservationIgnored private let git: GitServicing
|
||||||
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
||||||
@ObservationIgnored private var refreshGeneration = 0
|
@ObservationIgnored private var refreshGeneration = 0
|
||||||
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
||||||
|
@ObservationIgnored private var nextLineID = 0
|
||||||
|
@ObservationIgnored private var historyCursor: Int?
|
||||||
|
@ObservationIgnored private var isFetching = false
|
||||||
|
@ObservationIgnored private var inlineCache: [String: GitRowDetail] = [:]
|
||||||
|
/// The last git command queued; the next one waits for it, so two never race for `.git/index.lock`.
|
||||||
|
@ObservationIgnored private var commandTail: Task<Void, Never>?
|
||||||
|
/// The status error already in the console, so a poll that keeps failing logs it once.
|
||||||
|
@ObservationIgnored private var loggedStatusError: String?
|
||||||
|
|
||||||
/// `derive` runs off the main actor, since it diffs every changed file.
|
/// `derive` runs off the main actor, since it diffs every changed file.
|
||||||
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||||
@@ -35,21 +80,7 @@ public final class SourceControlStore {
|
|||||||
self.derive = derive
|
self.derive = derive
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Rows
|
// MARK: Derived
|
||||||
|
|
||||||
/// Rows in list order: staged folder groups, then unstaged ones.
|
|
||||||
public var rows: [Change] { SourceControlText.navigationOrder(state.changes) }
|
|
||||||
|
|
||||||
public var stagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter(\.staged)) }
|
|
||||||
public var unstagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter { !$0.staged }) }
|
|
||||||
|
|
||||||
public var selectedRow: Change? { state.changes.first { $0.id == selectedRowID } }
|
|
||||||
|
|
||||||
/// Paths with a staged row, in row order: what "unstage all" sends to git.
|
|
||||||
public var stagedPaths: [String] {
|
|
||||||
var seen = Set<String>()
|
|
||||||
return state.changes.filter { $0.staged && seen.insert($0.path).inserted }.map(\.path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
|
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
|
||||||
public var fileStatuses: [String: GitStatus] {
|
public var fileStatuses: [String: GitStatus] {
|
||||||
@@ -60,30 +91,63 @@ public final class SourceControlStore {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the cursor; a cursor whose row vanished starts over at the top.
|
/// Any change, staged or not; it locks branch switching.
|
||||||
public func moveSelection(by step: Int) {
|
public var isDirty: Bool { !state.changes.isEmpty }
|
||||||
let list = rows
|
|
||||||
guard !list.isEmpty else { return }
|
/// Distinct changed paths, a file with two rows once.
|
||||||
guard let index = list.firstIndex(where: { $0.id == selectedRowID }) else {
|
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
|
||||||
selectedRowID = list[0].id
|
|
||||||
return
|
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
|
||||||
}
|
|
||||||
selectedRowID = list[min(max(index + step, 0), list.count - 1)].id
|
/// The ready look of the Commit button; the button itself always runs git.
|
||||||
|
public var canCommitNow: Bool {
|
||||||
|
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Commit box
|
public var syncLabel: String {
|
||||||
|
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
|
||||||
public var canCommit: Bool {
|
|
||||||
state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: Sections and rows
|
||||||
|
|
||||||
|
public static func rowKey(_ kind: GitSectionKind, _ row: Change) -> String {
|
||||||
|
"\(kind.rawValue):\(row.id)"
|
||||||
|
}
|
||||||
|
|
||||||
|
public func isCollapsed(_ kind: GitSectionKind) -> Bool { collapsedSections.contains(kind) }
|
||||||
|
|
||||||
|
public func toggleSection(_ kind: GitSectionKind) {
|
||||||
|
if !collapsedSections.insert(kind).inserted { collapsedSections.remove(kind) }
|
||||||
|
}
|
||||||
|
|
||||||
|
public func isExpanded(_ kind: GitSectionKind, _ row: Change) -> Bool {
|
||||||
|
expandedRows.contains(Self.rowKey(kind, row))
|
||||||
|
}
|
||||||
|
|
||||||
|
public func toggleRow(_ kind: GitSectionKind, _ row: Change) {
|
||||||
|
let key = Self.rowKey(kind, row)
|
||||||
|
if !expandedRows.insert(key).inserted { expandedRows.remove(key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The inline side-by-side rows of a row's own half; cached until the next status read.
|
||||||
|
public func detail(for row: Change) -> GitRowDetail {
|
||||||
|
if let cached = inlineCache[row.id] { return cached }
|
||||||
|
let diff = state.rowDiffs[row.id]
|
||||||
|
let detail: GitRowDetail = diff?.isTooBig == true ? .tooBig : .rows(diff.map { InlineDiff.rows(from: $0) } ?? [])
|
||||||
|
inlineCache[row.id] = detail
|
||||||
|
return detail
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Commit message
|
||||||
|
|
||||||
public func setCommitMessage(_ value: String) {
|
public func setCommitMessage(_ value: String) {
|
||||||
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Git
|
// MARK: Reading git
|
||||||
|
|
||||||
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
||||||
|
/// A failed read still counts as loaded, so the view never waits forever; its error lands in the console once.
|
||||||
public func refresh() async {
|
public func refresh() async {
|
||||||
refreshGeneration += 1
|
refreshGeneration += 1
|
||||||
let generation = refreshGeneration
|
let generation = refreshGeneration
|
||||||
@@ -91,10 +155,18 @@ public final class SourceControlStore {
|
|||||||
do {
|
do {
|
||||||
snapshot = try await git.load()
|
snapshot = try await git.load()
|
||||||
} catch {
|
} catch {
|
||||||
Log.warn("git", "status failed: \(error)")
|
guard generation == refreshGeneration else { return }
|
||||||
|
let message = "status failed: \(error)"
|
||||||
|
Log.warn("git", message)
|
||||||
|
if message != loggedStatusError {
|
||||||
|
loggedStatusError = message
|
||||||
|
log(message, .error)
|
||||||
|
}
|
||||||
|
hasLoaded = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
guard generation == refreshGeneration else { return }
|
guard generation == refreshGeneration else { return }
|
||||||
|
loggedStatusError = nil
|
||||||
let derive = self.derive
|
let derive = self.derive
|
||||||
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
|
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
|
||||||
guard generation == refreshGeneration else { return }
|
guard generation == refreshGeneration else { return }
|
||||||
@@ -102,104 +174,253 @@ public final class SourceControlStore {
|
|||||||
hasLoaded = true
|
hasLoaded = true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads once for a column that appears before `WorkspaceModel` refreshed.
|
/// Loads once for a view that appears before `WorkspaceModel` refreshed.
|
||||||
public func loadIfNeeded() async {
|
public func loadIfNeeded() async {
|
||||||
if !hasLoaded { await refresh() }
|
if !hasLoaded { await refresh() }
|
||||||
}
|
}
|
||||||
|
|
||||||
public func stage(_ path: String) async {
|
public func reloadBranches() async {
|
||||||
await run("Stage failed", detail: path) { try await self.git.stage([path]) }
|
branches = await git.branches()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func unstage(_ path: String) async {
|
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
|
||||||
await run("Unstage failed", detail: path) { try await self.git.unstage([path]) }
|
/// Without an origin there is nothing to fetch, so the console stays quiet.
|
||||||
|
public func viewOpened() async {
|
||||||
|
author = await git.author()
|
||||||
|
await reloadBranches()
|
||||||
|
await loadIfNeeded()
|
||||||
|
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
|
||||||
|
isFetching = true
|
||||||
|
defer { isFetching = false }
|
||||||
|
await run(["fetch", "origin"], timeout: Self.remoteTimeout)
|
||||||
|
await afterCommand()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stages every path with an unstaged row, including ones that also have a staged row.
|
// MARK: Staging
|
||||||
public func stageAll() async {
|
|
||||||
let paths = state.unstagedPaths
|
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
|
||||||
|
public func stage(_ paths: [String]) async {
|
||||||
guard !paths.isEmpty else { return }
|
guard !paths.isEmpty else { return }
|
||||||
await run("Stage failed", detail: nil) { try await self.git.stage(paths) }
|
await run(["add", "--"] + paths)
|
||||||
|
await afterCommand()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func unstageAll() async {
|
/// A staged rename takes its source along, or the old path stays staged as deleted.
|
||||||
let paths = stagedPaths
|
/// A repository without commits has no HEAD to restore from, so `rm --cached` takes over there.
|
||||||
|
public func unstage(_ paths: [String]) async {
|
||||||
guard !paths.isEmpty else { return }
|
guard !paths.isEmpty else { return }
|
||||||
await run("Unstage failed", detail: nil) { try await self.git.unstage(paths) }
|
let staged = state.changes.filter(\.staged)
|
||||||
}
|
let all = Set(paths) == Set(GitSections.uniquePaths(staged))
|
||||||
|
let sources = staged.filter { $0.status == .renamed && paths.contains($0.path) }.compactMap(\.originalPath)
|
||||||
/// Commits the staged files with the draft, clears it, and returns how many files went in (0 when nothing did).
|
let withSources = paths + sources.filter { !paths.contains($0) }
|
||||||
public func commit() async -> Int {
|
let pathspec = all ? ["."] : ["--"] + withSources
|
||||||
let message = commitMessage.trimmingCharacters(in: .whitespaces)
|
let result = await run(["restore", "--staged"] + pathspec)
|
||||||
guard !message.isEmpty, state.stagedCount > 0 else { return 0 }
|
if !result.succeeded && result.stderr.contains("HEAD") {
|
||||||
let count = Set(state.changes.filter(\.staged).map(\.path)).count
|
await run(["rm", "--cached", "-r"] + pathspec)
|
||||||
commitMessage = ""
|
|
||||||
do {
|
|
||||||
try await git.commit(message: message)
|
|
||||||
} catch {
|
|
||||||
Log.error("git", "commit failed: \(error)")
|
|
||||||
if commitMessage.isEmpty { commitMessage = message }
|
|
||||||
notify("Commit failed", Self.failureDetail(error))
|
|
||||||
return 0
|
|
||||||
}
|
}
|
||||||
await refresh()
|
await afterCommand()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modified and deleted files come back with `restore`, new files go with `clean -f`; conflicts are left alone.
|
||||||
|
public func discard(_ paths: [String]) async {
|
||||||
|
let paths = paths.filter { unstagedStatus($0) != .unmerged }
|
||||||
|
guard !paths.isEmpty else { return }
|
||||||
|
let fresh = paths.filter { unstagedStatus($0) == .added }
|
||||||
|
let tracked = paths.filter { unstagedStatus($0) != .added }
|
||||||
|
if !tracked.isEmpty { await run(["restore", "--"] + tracked) }
|
||||||
|
if !fresh.isEmpty { await run(["clean", "-f", "--"] + fresh) }
|
||||||
|
await afterCommand()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func unstagedStatus(_ path: String) -> GitStatus? {
|
||||||
|
state.changes.first { !$0.staged && $0.path == path }?.status
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The confirm dialog a discard needs, or nil to run it straight away; restoring deleted files never asks.
|
||||||
|
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||||
|
guard case let .gitDiscard(paths) = action, config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||||
|
let statuses = paths.map(unstagedStatus)
|
||||||
|
let hasNew = statuses.contains(.added)
|
||||||
|
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
|
||||||
|
let allNew = statuses.allSatisfy { $0 == .added }
|
||||||
|
let what = paths.count == 1 ? paths[0] : "\(paths.count) files"
|
||||||
|
return ConfirmRequest(
|
||||||
|
title: allNew ? "Delete \(what)?" : "Discard changes to \(what)?",
|
||||||
|
body: hasNew ? "New files are removed from disk. This cannot be undone." : "This reverts to the last commit and cannot be undone.",
|
||||||
|
confirmLabel: allNew ? "Delete" : "Discard",
|
||||||
|
action: action
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Commit, push, pull
|
||||||
|
|
||||||
|
/// Always runs `git commit`, so git's own refusal (nothing staged, empty message) lands in the console.
|
||||||
|
public func commit(andPush: Bool = false) async {
|
||||||
|
let message = commitMessage.trimmingCharacters(in: .whitespaces)
|
||||||
|
let count = stagedPathCount
|
||||||
|
let arguments = ["commit", "-m", message]
|
||||||
|
let result = await run(arguments)
|
||||||
|
await afterCommand()
|
||||||
|
guard result.succeeded else {
|
||||||
|
notify("Commit failed", Self.failureDetail(of: result, arguments: arguments))
|
||||||
|
if message.isEmpty { focusMessage() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if commitMessage.trimmingCharacters(in: .whitespaces) == message { commitMessage = "" }
|
||||||
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
|
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
|
||||||
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
|
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
|
||||||
return count
|
if andPush { await push() }
|
||||||
}
|
}
|
||||||
|
|
||||||
public func push() async -> PushResult {
|
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
|
||||||
guard !isPushing else { return PushResult(ok: false, message: "A push is already running") }
|
public func push() async {
|
||||||
isPushing = true
|
guard busy == nil else { return }
|
||||||
notify("Pushing…", nil)
|
busy = .push
|
||||||
let result = await git.push()
|
let branch = state.branch
|
||||||
isPushing = false
|
let ahead = state.ahead
|
||||||
await refresh()
|
var arguments = ["push"]
|
||||||
notify(result.ok ? "Pushed" : "Push failed", result.message)
|
var result = await run(arguments, timeout: Self.remoteTimeout)
|
||||||
|
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) && branch != "HEAD" && branch != "—" {
|
||||||
|
arguments = ["push", "-u", "origin", branch]
|
||||||
|
result = await run(arguments, timeout: Self.remoteTimeout)
|
||||||
|
}
|
||||||
|
busy = nil
|
||||||
|
await afterCommand()
|
||||||
|
guard result.succeeded else {
|
||||||
|
notify("Push failed", Self.failureDetail(of: result, arguments: arguments))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let commits = ahead > 0 ? "\(ahead) commit\(ahead == 1 ? "" : "s") " : ""
|
||||||
|
notify("Pushed \(commits)to origin/\(branch)", nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merges when the branches diverged; a bare `pull` without `pull.rebase` config refuses to choose.
|
||||||
|
/// Ignored while a push or pull runs.
|
||||||
|
public func pull() async {
|
||||||
|
guard busy == nil else { return }
|
||||||
|
busy = .pull
|
||||||
|
let branch = state.branch
|
||||||
|
let behind = state.behind
|
||||||
|
let arguments = ["pull", "--no-rebase"]
|
||||||
|
let result = await run(arguments, timeout: Self.remoteTimeout)
|
||||||
|
busy = nil
|
||||||
|
await afterCommand()
|
||||||
|
guard result.succeeded else {
|
||||||
|
notify("Pull failed", Self.failureDetail(of: result, arguments: arguments))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if behind > 0 {
|
||||||
|
notify("Pulled \(behind) commit\(behind == 1 ? "" : "s") from origin/\(branch)", nil)
|
||||||
|
} else if !result.stdout.contains("Already up to date") {
|
||||||
|
notify("Pulled from origin/\(branch)", nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Branches
|
||||||
|
|
||||||
|
/// Refuses with a toast while the tree is dirty, without asking git. A remote branch switches by its local
|
||||||
|
/// name, which git creates as a tracking branch when it does not exist yet.
|
||||||
|
@discardableResult
|
||||||
|
public func switchBranch(_ name: String, remote: Bool) async -> Bool {
|
||||||
|
if isDirty {
|
||||||
|
let count = changedPathCount
|
||||||
|
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you switch.", nil)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let local = remote ? GitBranchList.localName(ofRemote: name) : name
|
||||||
|
guard local != state.branch else { return false }
|
||||||
|
let result = await run(["switch", local])
|
||||||
|
await afterCommand()
|
||||||
|
guard result.succeeded else { return false }
|
||||||
|
expandedRows = []
|
||||||
|
notify("Switched to \(local)", nil)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Console
|
||||||
|
|
||||||
|
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
|
||||||
|
public func submitConsoleInput() async {
|
||||||
|
let typed = consoleInput.trimmingCharacters(in: .whitespaces)
|
||||||
|
consoleInput = ""
|
||||||
|
historyCursor = nil
|
||||||
|
guard let arguments = GitConsoleText.parseInput(typed) else { return }
|
||||||
|
history.append(typed)
|
||||||
|
if arguments == ["clear"] {
|
||||||
|
clearConsole()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let run = arguments == ["log"] ? ["log", "--oneline", "--decorate", "-n", "30"] : arguments
|
||||||
|
await self.run(run, literalPathspecs: false, timeout: Self.remoteTimeout)
|
||||||
|
await afterCommand()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ↑ in the input: steps back through what was typed, stopping at the oldest.
|
||||||
|
public func recallPreviousInput() {
|
||||||
|
guard !history.isEmpty else { return }
|
||||||
|
let cursor = max(0, (historyCursor ?? history.count) - 1)
|
||||||
|
historyCursor = cursor
|
||||||
|
consoleInput = history[cursor]
|
||||||
|
}
|
||||||
|
|
||||||
|
public func clearConsole() {
|
||||||
|
lines = []
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Running git
|
||||||
|
|
||||||
|
/// Queues the command behind the one before it, then runs it; see `runNow`.
|
||||||
|
@discardableResult
|
||||||
|
private func run(_ arguments: [String], literalPathspecs: Bool = true, timeout: TimeInterval? = nil) async -> GitCommandResult {
|
||||||
|
let previous = commandTail
|
||||||
|
let command = Task { [weak self] () -> GitCommandResult in
|
||||||
|
await previous?.value
|
||||||
|
guard let self else { return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled") }
|
||||||
|
return await self.runNow(arguments, literalPathspecs: literalPathspecs, timeout: timeout)
|
||||||
|
}
|
||||||
|
commandTail = Task { _ = await command.value }
|
||||||
|
return await command.value
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logs the exact command, streams its output classified line by line, and returns how it ended.
|
||||||
|
/// Lines arrive off the main actor; one consumer keeps them in order and is drained before this returns.
|
||||||
|
private func runNow(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?) async -> GitCommandResult {
|
||||||
|
log(GitConsoleText.commandLine(arguments), .command)
|
||||||
|
let (stream, continuation) = AsyncStream<(String, Bool)>.makeStream()
|
||||||
|
let consumer = Task { [weak self] in
|
||||||
|
var classifier = GitOutputClassifier(arguments: arguments)
|
||||||
|
for await (line, isError) in stream {
|
||||||
|
self?.log(line, classifier.classify(line, isError: isError))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result = await git.execute(arguments, literalPathspecs: literalPathspecs, timeout: timeout) { line, isError in
|
||||||
|
continuation.yield((line, isError))
|
||||||
|
}
|
||||||
|
continuation.finish()
|
||||||
|
await consumer.value
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
public func discard(_ path: String) async {
|
private func afterCommand() async {
|
||||||
do {
|
|
||||||
try await git.discard([path])
|
|
||||||
} catch {
|
|
||||||
Log.error("git", "discard failed: \(error)")
|
|
||||||
notify("Discard failed", path)
|
|
||||||
await refresh()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
await refresh()
|
await refresh()
|
||||||
notify("Discarded changes", path)
|
await reloadBranches()
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Actions
|
private func log(_ text: String, _ kind: GitLineKind) {
|
||||||
|
lines.append(GitConsoleEntry(id: nextLineID, line: GitConsoleLine(text: text, kind: kind)))
|
||||||
/// The confirm dialog an action needs first under the config, or nil to run it straight away.
|
nextLineID += 1
|
||||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
|
||||||
switch action {
|
|
||||||
case let .discard(path) where config.confirmDiscard:
|
|
||||||
ConfirmRequest(title: "Discard changes to \(path)?",
|
|
||||||
body: "This reverts the file to the last commit and cannot be undone.",
|
|
||||||
confirmLabel: "Discard", action: action)
|
|
||||||
case let .stage(path) where config.confirmStage:
|
|
||||||
ConfirmRequest(title: "Stage \(path)?", confirmLabel: "Stage", action: action)
|
|
||||||
case let .unstage(path) where config.confirmUnstage:
|
|
||||||
ConfirmRequest(title: "Unstage \(path)?", confirmLabel: "Unstage", action: action)
|
|
||||||
default:
|
|
||||||
nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs a git action that is already confirmed; false for actions this store does not own.
|
/// The toast detail of a failed run: its first error line, else its last line that is not a hint.
|
||||||
@discardableResult
|
private static func failureDetail(of result: GitCommandResult, arguments: [String]) -> String? {
|
||||||
public func perform(_ action: ContextAction) async -> Bool {
|
var classifier = GitOutputClassifier(arguments: arguments)
|
||||||
switch action {
|
let lines = [(result.stderr, true), (result.stdout, false)].flatMap { text, isError in
|
||||||
case let .stage(path): await stage(path)
|
text.split(whereSeparator: \.isNewline).map { (String($0), isError) }
|
||||||
case let .unstage(path): await unstage(path)
|
|
||||||
case let .discard(path): await discard(path)
|
|
||||||
default: return false
|
|
||||||
}
|
}
|
||||||
return true
|
let classified = lines.map { ($0.0.trimmingCharacters(in: .whitespaces), classifier.classify($0.0, isError: $0.1)) }
|
||||||
|
.filter { !$0.0.isEmpty }
|
||||||
|
return classified.first { $0.1 == .error }?.0 ?? classified.last { $0.1 != .hint }?.0
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Polling
|
// MARK: Polling
|
||||||
@@ -225,19 +446,4 @@ public final class SourceControlStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public var isPolling: Bool { pollTask != nil }
|
public var isPolling: Bool { pollTask != nil }
|
||||||
|
|
||||||
private func run(_ failure: String, detail: String?, _ operation: () async throws -> Void) async {
|
|
||||||
do {
|
|
||||||
try await operation()
|
|
||||||
} catch {
|
|
||||||
Log.error("git", "\(failure): \(error)")
|
|
||||||
notify(failure, detail ?? Self.failureDetail(error))
|
|
||||||
}
|
|
||||||
await refresh()
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func failureDetail(_ error: Error) -> String {
|
|
||||||
if case let GitError.commandFailed(_, _, stderr) = error, !stderr.isEmpty { return stderr }
|
|
||||||
return String(describing: error)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,36 +69,47 @@ extension WorkspaceModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: Git view
|
||||||
|
|
||||||
|
/// Opens the Git view on its message field, re-reads git and fetches origin; an open view only takes the field again.
|
||||||
|
func openGitView() {
|
||||||
|
if !layout.isGitViewOpen {
|
||||||
|
layout.openGitView()
|
||||||
|
scheduleRefresh(.git)
|
||||||
|
if let sourceControl { track { await sourceControl.viewOpened() } }
|
||||||
|
}
|
||||||
|
focusRequest = FocusRequest(.commitMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the keyboard back to the column that had it before the view opened.
|
||||||
|
func closeGitView() {
|
||||||
|
guard layout.isGitViewOpen else { return }
|
||||||
|
layout.closeGitView()
|
||||||
|
guard let panel = layout.activePanel else {
|
||||||
|
focusRequest = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
focusRequest = FocusRequest(.panel(panel))
|
||||||
|
if panel == .editor { editor?.requestTextFocus() }
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: Focus and the row cursor
|
// MARK: Focus and the row cursor
|
||||||
|
|
||||||
func focus(_ panel: Panel) {
|
func focus(_ panel: Panel) {
|
||||||
let previous = layout.activePanel
|
|
||||||
layout.focus(panel)
|
layout.focus(panel)
|
||||||
guard layout.activePanel == panel else { return }
|
guard layout.activePanel == panel else { return }
|
||||||
focusRequest = FocusRequest(.panel(panel))
|
focusRequest = FocusRequest(.panel(panel))
|
||||||
if panel == .editor { editor?.requestTextFocus() }
|
if panel == .editor { editor?.requestTextFocus() }
|
||||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func moveRowCursor(by step: Int) {
|
func moveRowCursor(by step: Int) {
|
||||||
switch layout.activePanel {
|
guard layout.activePanel == .explorer else { return }
|
||||||
case .sourceControl: sourceControl?.moveSelection(by: step)
|
explorer?.moveSelection(by: step, showHidden: layout.showHidden)
|
||||||
case .explorer: explorer?.moveSelection(by: step, showHidden: layout.showHidden)
|
|
||||||
default: break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func openSelectedRow() {
|
func openSelectedRow() {
|
||||||
switch layout.activePanel {
|
guard layout.activePanel == .explorer, let explorer, let row = selectedTreeRow() else { return }
|
||||||
case .sourceControl:
|
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
|
||||||
guard let row = selectedGitRow() else { return }
|
|
||||||
open(row.change.path, OpenOptions(side: row.change.staged ? .staged : .unstaged))
|
|
||||||
case .explorer:
|
|
||||||
guard let explorer, let row = selectedTreeRow() else { return }
|
|
||||||
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Editor
|
// MARK: Editor
|
||||||
|
|||||||
@@ -42,29 +42,12 @@ extension WorkspaceModel {
|
|||||||
|
|
||||||
// MARK: Row menus
|
// MARK: Row menus
|
||||||
|
|
||||||
/// ⌘→ in Source Control or Explorer: the selected row's menu, beside the column at the row's height.
|
/// ⌘→ in the Explorer: the selected row's menu, beside the column at the row's height.
|
||||||
func openRowMenu() {
|
func openRowMenu() {
|
||||||
switch layout.activePanel {
|
guard layout.activePanel == .explorer, let row = selectedTreeRow() else { return }
|
||||||
case .sourceControl:
|
showContextMenu(ExplorerStore.target(for: row.row),
|
||||||
guard let row = selectedGitRow() else { return }
|
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
|
||||||
showContextMenu(.gitRow(path: row.change.path, staged: row.change.staged),
|
estimate: row.index, rowHeight: Metrics.explorerRow))
|
||||||
anchor: rowMenuAnchor(.sourceControl, frame: rowFrames[.git(row.change.id)],
|
|
||||||
estimate: row.index, rowHeight: Metrics.sourceControlRow))
|
|
||||||
case .explorer:
|
|
||||||
guard let row = selectedTreeRow() else { return }
|
|
||||||
showContextMenu(ExplorerStore.target(for: row.row),
|
|
||||||
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
|
|
||||||
estimate: row.index, rowHeight: Metrics.explorerRow))
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func selectedGitRow() -> (change: Change, index: Int)? {
|
|
||||||
guard let sourceControl else { return nil }
|
|
||||||
let rows = sourceControl.rows
|
|
||||||
guard let index = rows.firstIndex(where: { $0.id == sourceControl.selectedRowID }) else { return nil }
|
|
||||||
return (rows[index], index)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
|
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
|
||||||
@@ -90,7 +73,13 @@ extension WorkspaceModel {
|
|||||||
let sourceControl = sourceControl, explorer = explorer, editor = editor
|
let sourceControl = sourceControl, explorer = explorer, editor = editor
|
||||||
switch action {
|
switch action {
|
||||||
case let .passOnReference(reference, code):
|
case let .passOnReference(reference, code):
|
||||||
|
closeGitView()
|
||||||
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
|
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
|
||||||
|
case let .openFile(path):
|
||||||
|
closeGitView()
|
||||||
|
open(path)
|
||||||
|
case let .commit(andPush):
|
||||||
|
track { await sourceControl?.commit(andPush: andPush) }
|
||||||
case let .passOnFileName(name):
|
case let .passOnFileName(name):
|
||||||
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
|
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
|
||||||
case let .bouwen(name):
|
case let .bouwen(name):
|
||||||
@@ -118,18 +107,16 @@ extension WorkspaceModel {
|
|||||||
case let .rename(path, isDirectory):
|
case let .rename(path, isDirectory):
|
||||||
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
|
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
|
||||||
initialName: PathUtils.basename(path), anchor: anchor)))
|
initialName: PathUtils.basename(path), anchor: anchor)))
|
||||||
case let .openDiff(path):
|
|
||||||
open(path, OpenOptions(showDiff: true))
|
|
||||||
case let .showDiff(path, line):
|
case let .showDiff(path, line):
|
||||||
if editor?.activePath == path { editor?.openDiff(atLine: line) }
|
if editor?.activePath == path { editor?.openDiff(atLine: line) }
|
||||||
case let .copyTerminalSelection(kind):
|
case let .copyTerminalSelection(kind):
|
||||||
if let text = terminal.selection(kind) { app.system.copy(text) }
|
if let text = terminal.selection(kind) { app.system.copy(text) }
|
||||||
case let .pasteIntoTerminal(kind):
|
case let .pasteIntoTerminal(kind):
|
||||||
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
|
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
|
||||||
case let .discard(path):
|
case let .gitDiscard(paths):
|
||||||
track {
|
track {
|
||||||
await sourceControl?.discard(path)
|
await sourceControl?.discard(paths)
|
||||||
await editor?.reloadFromDisk(path)
|
for path in paths where editor?.isLoaded(path) == true { await editor?.reloadFromDisk(path) }
|
||||||
}
|
}
|
||||||
case let .delete(path, isDirectory):
|
case let .delete(path, isDirectory):
|
||||||
track {
|
track {
|
||||||
@@ -138,10 +125,7 @@ extension WorkspaceModel {
|
|||||||
await sourceControl?.refresh()
|
await sourceControl?.refresh()
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
track {
|
track { _ = await explorer?.perform(action) }
|
||||||
if await sourceControl?.perform(action) == true { return }
|
|
||||||
await explorer?.perform(action)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ extension WorkspaceModel {
|
|||||||
|
|
||||||
let sourceControl = SourceControlStore(git: services.git)
|
let sourceControl = SourceControlStore(git: services.git)
|
||||||
sourceControl.notify = notify
|
sourceControl.notify = notify
|
||||||
|
sourceControl.focusMessage = { [weak self] in self?.focusRequest = FocusRequest(.commitMessage) }
|
||||||
self.sourceControl = sourceControl
|
self.sourceControl = sourceControl
|
||||||
|
|
||||||
let explorer = ExplorerStore(files: services.files, system: app.system)
|
let explorer = ExplorerStore(files: services.files, system: app.system)
|
||||||
|
|||||||
@@ -45,8 +45,6 @@ public struct RefreshScope: OptionSet, Sendable {
|
|||||||
|
|
||||||
/// A list row whose on-screen frame the ⌘→ menu anchors to.
|
/// A list row whose on-screen frame the ⌘→ menu anchors to.
|
||||||
public enum RowKey: Hashable, Sendable {
|
public enum RowKey: Hashable, Sendable {
|
||||||
/// A Source Control row, by `Change.id`.
|
|
||||||
case git(String)
|
|
||||||
/// An Explorer row, by path.
|
/// An Explorer row, by path.
|
||||||
case tree(String)
|
case tree(String)
|
||||||
}
|
}
|
||||||
@@ -100,7 +98,7 @@ public final class WorkspaceModel {
|
|||||||
@ObservationIgnored var lifecycleTask: Task<Void, Never>?
|
@ObservationIgnored var lifecycleTask: Task<Void, Never>?
|
||||||
/// Moves on every project switch, so work that awaited across one can tell its project is gone.
|
/// Moves on every project switch, so work that awaited across one can tell its project is gone.
|
||||||
@ObservationIgnored var generation = 0
|
@ObservationIgnored var generation = 0
|
||||||
/// Where the Source Control and Explorer rows sit on screen, in top-left window coordinates.
|
/// Where the Explorer rows sit on screen, in top-left window coordinates.
|
||||||
@ObservationIgnored var rowFrames: [RowKey: CGRect] = [:]
|
@ObservationIgnored var rowFrames: [RowKey: CGRect] = [:]
|
||||||
@ObservationIgnored var hasStarted = false
|
@ObservationIgnored var hasStarted = false
|
||||||
@ObservationIgnored var resignedKey = false
|
@ObservationIgnored var resignedKey = false
|
||||||
@@ -148,7 +146,8 @@ public final class WorkspaceModel {
|
|||||||
case let .launcherSelect(index): launcher.select(index)
|
case let .launcherSelect(index): launcher.select(index)
|
||||||
case .launcherActivate: activateLauncher()
|
case .launcherActivate: activateLauncher()
|
||||||
|
|
||||||
case .toggleGit: layout.togglePane(.sourceControl)
|
case .toggleGit: layout.isGitViewOpen ? closeGitView() : openGitView()
|
||||||
|
case .closeGitView: closeGitView()
|
||||||
case let .togglePane(panel): layout.togglePane(panel)
|
case let .togglePane(panel): layout.togglePane(panel)
|
||||||
case .toggleAutoFit: layout.toggleFluid()
|
case .toggleAutoFit: layout.toggleFluid()
|
||||||
case .toggleHidden: layout.toggleHidden()
|
case .toggleHidden: layout.toggleHidden()
|
||||||
@@ -174,15 +173,36 @@ public final class WorkspaceModel {
|
|||||||
case .selectAllInFile: editor?.selectAll()
|
case .selectAllInFile: editor?.selectAll()
|
||||||
|
|
||||||
case .commit:
|
case .commit:
|
||||||
guard let sourceControl, sourceControl.canCommit else { return }
|
guard let sourceControl else { return }
|
||||||
track { _ = await sourceControl.commit() }
|
track { await sourceControl.commit() }
|
||||||
case .push:
|
case .push:
|
||||||
guard let sourceControl else { return }
|
guard let sourceControl else { return }
|
||||||
track { _ = await sourceControl.push() }
|
track { await sourceControl.push() }
|
||||||
case .focusCommitMessage:
|
case .pull:
|
||||||
layout.setVisible(.sourceControl, true)
|
guard let sourceControl else { return }
|
||||||
layout.focus(.sourceControl)
|
track {
|
||||||
focusRequest = FocusRequest(.commitMessage)
|
await sourceControl.pull()
|
||||||
|
self.scheduleRefresh([.tree, .openFiles])
|
||||||
|
}
|
||||||
|
case let .stage(paths):
|
||||||
|
guard let sourceControl else { return }
|
||||||
|
track { await sourceControl.stage(paths) }
|
||||||
|
case let .unstage(paths):
|
||||||
|
guard let sourceControl else { return }
|
||||||
|
track { await sourceControl.unstage(paths) }
|
||||||
|
case let .switchBranch(name, remote):
|
||||||
|
guard let sourceControl else { return }
|
||||||
|
track {
|
||||||
|
guard await sourceControl.switchBranch(name, remote: remote) else { return }
|
||||||
|
self.scheduleRefresh([.tree, .openFiles])
|
||||||
|
}
|
||||||
|
case .submitConsoleInput:
|
||||||
|
guard let sourceControl else { return }
|
||||||
|
track {
|
||||||
|
await sourceControl.submitConsoleInput()
|
||||||
|
self.scheduleRefresh([.tree, .openFiles])
|
||||||
|
}
|
||||||
|
case .focusCommitMessage: openGitView()
|
||||||
|
|
||||||
case .copyCleanCopy: copyCleanCopy()
|
case .copyCleanCopy: copyCleanCopy()
|
||||||
|
|
||||||
@@ -230,9 +250,7 @@ public final class WorkspaceModel {
|
|||||||
|
|
||||||
/// A click inside a column: it becomes the active panel without taking first responder.
|
/// A click inside a column: it becomes the active panel without taking first responder.
|
||||||
public func pointerFocused(_ panel: Panel) {
|
public func pointerFocused(_ panel: Panel) {
|
||||||
let previous = layout.activePanel
|
|
||||||
layout.focus(panel)
|
layout.focus(panel)
|
||||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func wireTerminal() {
|
func wireTerminal() {
|
||||||
@@ -241,7 +259,7 @@ public final class WorkspaceModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A Source Control or Explorer row reports where it sits (nil when it leaves the screen).
|
/// An Explorer row reports where it sits (nil when it leaves the screen).
|
||||||
public func rowFrameChanged(_ key: RowKey, _ frame: CGRect?) {
|
public func rowFrameChanged(_ key: RowKey, _ frame: CGRect?) {
|
||||||
rowFrames[key] = frame
|
rowFrames[key] = frame
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ public enum Metrics {
|
|||||||
// MARK: Rows and bars
|
// MARK: Rows and bars
|
||||||
|
|
||||||
public static let explorerRow: CGFloat = 24
|
public static let explorerRow: CGFloat = 24
|
||||||
public static let sourceControlRow: CGFloat = 26
|
|
||||||
public static let statusBar: CGFloat = 28
|
public static let statusBar: CGFloat = 28
|
||||||
public static let contextMenuItem: CGFloat = 30
|
public static let contextMenuItem: CGFloat = 30
|
||||||
/// The one top-bar height: Explorer head, Diff bar.
|
/// The one top-bar height: Explorer head, Diff bar.
|
||||||
@@ -18,8 +17,6 @@ public enum Metrics {
|
|||||||
public static let launcherRow: CGFloat = 38
|
public static let launcherRow: CGFloat = 38
|
||||||
public static let launcherNewRow: CGFloat = 46
|
public static let launcherNewRow: CGFloat = 46
|
||||||
public static let searchQueryBar: CGFloat = 54
|
public static let searchQueryBar: CGFloat = 54
|
||||||
public static let commitBox: CGFloat = 52
|
|
||||||
public static let pushButton: CGFloat = 34
|
|
||||||
|
|
||||||
// MARK: Radii
|
// MARK: Radii
|
||||||
|
|
||||||
@@ -40,7 +37,6 @@ public enum Metrics {
|
|||||||
|
|
||||||
// MARK: Columns
|
// MARK: Columns
|
||||||
|
|
||||||
public static let sourceControlWidth: CGFloat = 236
|
|
||||||
public static let explorerWidth: CGFloat = 288
|
public static let explorerWidth: CGFloat = 288
|
||||||
public static let agentWidth: CGFloat = 480
|
public static let agentWidth: CGFloat = 480
|
||||||
public static let minEditorWidth: CGFloat = 280
|
public static let minEditorWidth: CGFloat = 280
|
||||||
@@ -80,8 +76,6 @@ public enum Metrics {
|
|||||||
// MARK: Overlays
|
// MARK: Overlays
|
||||||
|
|
||||||
public static let overlayInset: CGFloat = 34
|
public static let overlayInset: CGFloat = 34
|
||||||
/// The widest an `.inset` overlay grows; past it the card stays centred.
|
|
||||||
public static let insetOverlayMaxWidth: CGFloat = 1200
|
|
||||||
public static let contextMenuWidth: CGFloat = 320
|
public static let contextMenuWidth: CGFloat = 320
|
||||||
public static let passOnWidth: CGFloat = 460
|
public static let passOnWidth: CGFloat = 460
|
||||||
public static let launcherWidth: CGFloat = 520
|
public static let launcherWidth: CGFloat = 520
|
||||||
|
|||||||
@@ -49,8 +49,6 @@ public enum Palette {
|
|||||||
public static let amberKeycapBorder = Color(hex: 0xE8913A, alpha: 0.35)
|
public static let amberKeycapBorder = Color(hex: 0xE8913A, alpha: 0.35)
|
||||||
/// Text on an amber fill: always ink, never white.
|
/// Text on an amber fill: always ink, never white.
|
||||||
public static let ink = Color(hex: 0x171C22)
|
public static let ink = Color(hex: 0x171C22)
|
||||||
/// The Commit button's label, a warmer ink than `ink`.
|
|
||||||
public static let commitInk = Color(hex: 0x201608)
|
|
||||||
/// Keycap border on an amber fill.
|
/// Keycap border on an amber fill.
|
||||||
public static let inkKeycapBorder = Color(hex: 0x171C22, alpha: 0.25)
|
public static let inkKeycapBorder = Color(hex: 0x171C22, alpha: 0.25)
|
||||||
|
|
||||||
@@ -121,9 +119,44 @@ public enum Palette {
|
|||||||
public static let menuIconModify = Color(hex: 0xF0B476)
|
public static let menuIconModify = Color(hex: 0xF0B476)
|
||||||
public static let menuIconRename = Color(hex: 0xBAC0C0)
|
public static let menuIconRename = Color(hex: 0xBAC0C0)
|
||||||
|
|
||||||
/// Git status letters: staged rows in teal, unstaged in amber-soft.
|
|
||||||
public static let stagedLetter = Color(hex: 0x8FBFB4)
|
// MARK: Git view
|
||||||
public static let unstagedLetter = Color(hex: 0xF0B476)
|
|
||||||
|
/// Secondary meta between text-3 and text-4: the sync label, the author, directories, hints.
|
||||||
|
public static let textMuted = Color(hex: 0x828D9A)
|
||||||
|
/// A file row under the pointer.
|
||||||
|
public static let gitRowHover = Color(hex: 0x1F2834)
|
||||||
|
/// The idle Commit button under the pointer: `raised` one step darker.
|
||||||
|
public static let commitIdleHover = Color(hex: 0x202834)
|
||||||
|
/// Status colours: modified, new, deleted; staged is `amber`.
|
||||||
|
public static let gitModified = Color(hex: 0xF0B476)
|
||||||
|
public static let gitNew = Color(hex: 0x8FBFB4)
|
||||||
|
public static let gitDeleted = Color(hex: 0xC3A6CE)
|
||||||
|
/// Section header fills.
|
||||||
|
public static let gitStagedTint = Color(hex: 0xE8913A, alpha: 0.08)
|
||||||
|
public static let gitModifiedTint = Color(hex: 0xF0B476, alpha: 0.06)
|
||||||
|
public static let gitNewTint = Color(hex: 0x8FBFB4, alpha: 0.06)
|
||||||
|
public static let gitDeletedTint = Color(hex: 0xC3A6CE, alpha: 0.06)
|
||||||
|
/// The current branch row.
|
||||||
|
public static let gitCurrentBranch = Color(hex: 0xE8913A, alpha: 0.08)
|
||||||
|
/// Inline diff: line fills, the differing middle of a paired line, and the side with no line.
|
||||||
|
public static let inlineRemovedFill = Color(hex: 0xE8913A, alpha: 0.12)
|
||||||
|
public static let inlineAddedFill = Color(hex: 0x8FBFB4, alpha: 0.12)
|
||||||
|
public static let inlineRemovedHighlight = Color(hex: 0xE8913A, alpha: 0.38)
|
||||||
|
public static let inlineAddedHighlight = Color(hex: 0x8FBFB4, alpha: 0.36)
|
||||||
|
public static let inlineFiller = Color(hex: 0x232C39, alpha: 0.35)
|
||||||
|
|
||||||
|
/// The colour of a console line.
|
||||||
|
public static func console(_ kind: GitLineKind) -> Color {
|
||||||
|
switch kind {
|
||||||
|
case .command: text1
|
||||||
|
case .output: text3
|
||||||
|
case .error: amber
|
||||||
|
case .hint: textMuted
|
||||||
|
case .staged, .success: gitNew
|
||||||
|
case .unstaged: gitModified
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Color {
|
extension Color {
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ public enum Typography {
|
|||||||
public static let terminal = TypeRole(.monoRegular, 12, lineHeight: 20.4)
|
public static let terminal = TypeRole(.monoRegular, 12, lineHeight: 20.4)
|
||||||
public static let row = TypeRole(.sansRegular, 13)
|
public static let row = TypeRole(.sansRegular, 13)
|
||||||
public static let rowSelected = TypeRole(.sansMedium, 13)
|
public static let rowSelected = TypeRole(.sansMedium, 13)
|
||||||
public static let sourceControlRow = TypeRole(.sansRegular, 12)
|
public static let rowSmall = TypeRole(.sansRegular, 12)
|
||||||
public static let body = TypeRole(.sansRegular, 14, lineHeight: 23.8)
|
public static let body = TypeRole(.sansRegular, 14, lineHeight: 23.8)
|
||||||
public static let tooltip = TypeRole(.sansRegular, 12, lineHeight: 18)
|
public static let tooltip = TypeRole(.sansRegular, 12, lineHeight: 18)
|
||||||
public static let button = TypeRole(.sansMedium, 12)
|
public static let button = TypeRole(.sansMedium, 12)
|
||||||
@@ -88,10 +88,28 @@ public enum Typography {
|
|||||||
public static let toolbarLabel = TypeRole(.sansRegular, 12)
|
public static let toolbarLabel = TypeRole(.sansRegular, 12)
|
||||||
public static let menuItem = TypeRole(.sansRegular, 13)
|
public static let menuItem = TypeRole(.sansRegular, 13)
|
||||||
public static let menuItemHighlighted = TypeRole(.sansMedium, 13)
|
public static let menuItemHighlighted = TypeRole(.sansMedium, 13)
|
||||||
|
/// The main item of a menu, such as "Open in editor".
|
||||||
|
public static let menuItemEmphasized = TypeRole(.sansSemiBold, 13)
|
||||||
public static let note = TypeRole(.monoRegular, 14, lineHeight: 23.8)
|
public static let note = TypeRole(.monoRegular, 14, lineHeight: 23.8)
|
||||||
public static let markdownH2 = TypeRole(.monoBold, 24, lineHeight: 26.4, trackingEm: -0.03)
|
public static let markdownH2 = TypeRole(.monoBold, 24, lineHeight: 26.4, trackingEm: -0.03)
|
||||||
public static let markdownH3 = TypeRole(.monoBold, 17, lineHeight: 20.4)
|
public static let markdownH3 = TypeRole(.monoBold, 17, lineHeight: 20.4)
|
||||||
public static let markdownQuote = TypeRole(.sansItalic, 15)
|
public static let markdownQuote = TypeRole(.sansItalic, 15)
|
||||||
|
|
||||||
|
// MARK: Git view
|
||||||
|
|
||||||
|
/// `[ git ]` and the section labels: 11px mono 700, uppercase.
|
||||||
|
public static let gitLabel = TypeRole(.monoBold, 11, trackingEm: 0.14, uppercase: true)
|
||||||
|
/// The ↓2 / ↑1 counts, the ⌘G hint and the section count badge.
|
||||||
|
public static let gitCount = TypeRole(.monoSemiBold, 11)
|
||||||
|
public static let commitMessage = TypeRole(.monoRegular, 14, lineHeight: 22.4)
|
||||||
|
public static let gitCommitButton = TypeRole(.sansSemiBold, 13)
|
||||||
|
public static let gitStatusLetter = TypeRole(.monoBold, 11)
|
||||||
|
public static let gitPath = TypeRole(.monoRegular, 13)
|
||||||
|
public static let gitStats = TypeRole(.monoMedium, 12)
|
||||||
|
public static let inlineDiff = TypeRole(.monoRegular, 13, lineHeight: 22)
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
extension View {
|
extension View {
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ import Testing
|
|||||||
#expect(c.editor.tabSize == 4)
|
#expect(c.editor.tabSize == 4)
|
||||||
#expect(c.editor.wordWrap == .markdown)
|
#expect(c.editor.wordWrap == .markdown)
|
||||||
#expect(c.git.confirmDiscard)
|
#expect(c.git.confirmDiscard)
|
||||||
#expect(!c.git.confirmStage)
|
|
||||||
#expect(!c.git.confirmUnstage)
|
|
||||||
#expect(c.git.defaultDiffMode == .updated)
|
#expect(c.git.defaultDiffMode == .updated)
|
||||||
#expect(c.git.refreshInterval == 10_000)
|
#expect(c.git.refreshInterval == 10_000)
|
||||||
#expect(c.files.exclude.isEmpty)
|
#expect(c.files.exclude.isEmpty)
|
||||||
@@ -31,13 +29,20 @@ import Testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test func anOlderOriginalDefaultDiffModeDecodesAsUpdated() throws {
|
@Test func anOlderOriginalDefaultDiffModeDecodesAsUpdated() throws {
|
||||||
let json = #"{"git":{"defaultDiffMode":"original","confirmStage":true}}"#
|
let json = #"{"git":{"defaultDiffMode":"original"}}"#
|
||||||
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
|
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
|
||||||
#expect(c.git.defaultDiffMode == .updated)
|
#expect(c.git.defaultDiffMode == .updated)
|
||||||
#expect(c.git.confirmStage)
|
|
||||||
#expect(ViewMode(c.git.defaultDiffMode) == .actual)
|
#expect(ViewMode(c.git.defaultDiffMode) == .actual)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func theRemovedStageConfirmKeysStillDecode() throws {
|
||||||
|
let json = #"{"git":{"confirmStage":true,"confirmUnstage":true,"confirmDiscard":false,"refreshInterval":5000}}"#
|
||||||
|
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
|
||||||
|
#expect(!c.git.confirmDiscard)
|
||||||
|
#expect(c.git.refreshInterval == 5000)
|
||||||
|
#expect(HelderConfig.resolved(overrides: Data(json.utf8)).git.refreshInterval == 5000)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func sparseOverridesMergeKeyByKey() {
|
@Test func sparseOverridesMergeKeyByKey() {
|
||||||
let json = ##"{"editor":{"tabSize":2},"terminal":{"fontSize":14,"theme":{"red":"#FF0000"}},"files":{"exclude":["*.log"]}}"##
|
let json = ##"{"editor":{"tabSize":2},"terminal":{"fontSize":14,"theme":{"red":"#FF0000"}},"files":{"exclude":["*.log"]}}"##
|
||||||
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ import Testing
|
|||||||
|
|
||||||
@Test func fileGitRowAndRootMenusKeepTheirHeader() {
|
@Test func fileGitRowAndRootMenusKeepTheirHeader() {
|
||||||
#expect(ContextActions.header(for: .file(path: "src/a.php"), projectName: "app") == "src/a.php")
|
#expect(ContextActions.header(for: .file(path: "src/a.php"), projectName: "app") == "src/a.php")
|
||||||
#expect(ContextActions.header(for: .gitRow(path: "src/a.php", staged: false), projectName: "app") == "src/a.php")
|
#expect(ContextActions.header(for: .gitRow(path: "src/a.php", isDeleted: false), projectName: "app") == "src/a.php")
|
||||||
#expect(ContextActions.header(for: .projectRoot, projectName: "app") == "app/")
|
#expect(ContextActions.header(for: .projectRoot, projectName: "app") == "app/")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,15 +122,37 @@ import Testing
|
|||||||
.action(.readAloudFile("docs/guide.md"), label: "Read aloud"),
|
.action(.readAloudFile("docs/guide.md"), label: "Read aloud"),
|
||||||
.separator,
|
.separator,
|
||||||
])
|
])
|
||||||
#expect(readAloud(.gitRow(path: "README.md", staged: true)) == [.action(.readAloudFile("README.md"), label: "Read aloud")])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func otherFilesCannot() {
|
@Test func otherFilesCannot() {
|
||||||
#expect(readAloud(.file(path: "src/app.php")).isEmpty)
|
#expect(readAloud(.file(path: "src/app.php")).isEmpty)
|
||||||
#expect(readAloud(.gitRow(path: "src/app.php", staged: false)).isEmpty)
|
|
||||||
#expect(readAloud(.directory(path: "docs")).isEmpty)
|
#expect(readAloud(.directory(path: "docs")).isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func aGitRowOpensInTheEditorThenPassesOnItsPath() {
|
||||||
|
#expect(ContextActions.entries(for: .gitRow(path: "src/a.php", isDeleted: false)) == [
|
||||||
|
.action(.openFile("src/a.php"), label: "Open in editor"),
|
||||||
|
.separator,
|
||||||
|
.action(.passOnReference("src/a.php", code: nil), label: "Pass on reference"),
|
||||||
|
.action(.copyReference("src/a.php"), label: "Copy reference"),
|
||||||
|
])
|
||||||
|
#expect(ContextActions.entries(for: .gitRow(path: "gone.php", isDeleted: true)) == [
|
||||||
|
.action(.passOnReference("gone.php", code: nil), label: "Pass on reference"),
|
||||||
|
.action(.copyReference("gone.php"), label: "Copy reference"),
|
||||||
|
])
|
||||||
|
#expect(ContextAction.openFile("src/a.php").isEmphasized)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theCommitMenuOffersCommitAndABoldCommitAndPush() {
|
||||||
|
#expect(ContextActions.header(for: .commitMenu, projectName: "app") == "")
|
||||||
|
#expect(ContextActions.entries(for: .commitMenu) == [
|
||||||
|
.action(.commit(andPush: false), label: "Commit"),
|
||||||
|
.action(.commit(andPush: true), label: "Commit and push"),
|
||||||
|
])
|
||||||
|
#expect(ContextAction.commit(andPush: true).isEmphasized)
|
||||||
|
#expect(!ContextAction.commit(andPush: false).isEmphasized)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func aSelectionCanBeReadAloudAfterCopyReference() {
|
@Test func aSelectionCanBeReadAloudAfterCopyReference() {
|
||||||
let reference = AgentReference(path: "src/a.php", startLine: 3, endLine: 4)
|
let reference = AgentReference(path: "src/a.php", startLine: 3, endLine: 4)
|
||||||
#expect(ContextActions.entries(for: .editor(reference: reference, code: "$a = 1;", showDiffLine: 3)) == [
|
#expect(ContextActions.entries(for: .editor(reference: reference, code: "$a = 1;", showDiffLine: 3)) == [
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import HelderCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite struct GitBranchesTests {
|
||||||
|
@Test("refs split into sorted local and origin branches without origin/HEAD")
|
||||||
|
func parse() {
|
||||||
|
let raw = """
|
||||||
|
refs/heads/main
|
||||||
|
refs/heads/feature/b
|
||||||
|
refs/heads/feature/a
|
||||||
|
refs/remotes/origin/HEAD
|
||||||
|
refs/remotes/origin/main
|
||||||
|
refs/remotes/origin/feature/c
|
||||||
|
refs/remotes/upstream/main
|
||||||
|
|
||||||
|
"""
|
||||||
|
let list = GitBranchParsing.parse(raw)
|
||||||
|
#expect(list.local == ["feature/a", "feature/b", "main"])
|
||||||
|
#expect(list.remote == ["origin/feature/c", "origin/main"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("empty output is no branches")
|
||||||
|
func empty() {
|
||||||
|
#expect(GitBranchParsing.parse("") == .empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a remote branch checks out under its name without the remote", arguments: [
|
||||||
|
("origin/main", "main"),
|
||||||
|
("origin/feature/a", "feature/a"),
|
||||||
|
("main", "main"),
|
||||||
|
])
|
||||||
|
func localName(remote: String, local: String) {
|
||||||
|
#expect(GitBranchList.localName(ofRemote: remote) == local)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a remote branch is tracked when its local name exists")
|
||||||
|
func tracked() {
|
||||||
|
let list = GitBranchList(local: ["main", "feature/a"], remote: ["origin/main", "origin/feature/a", "origin/other"])
|
||||||
|
#expect(list.isTracked("origin/main"))
|
||||||
|
#expect(list.isTracked("origin/feature/a"))
|
||||||
|
#expect(!list.isTracked("origin/other"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import HelderCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite struct GitConsoleTests {
|
||||||
|
// MARK: commandLine
|
||||||
|
|
||||||
|
@Test("the echo quotes only what needs quotes", arguments: [
|
||||||
|
(["status"], "$ git status"),
|
||||||
|
(["commit", "-m", "fix the bar"], "$ git commit -m \"fix the bar\""),
|
||||||
|
(["commit", "-m", "say \"hi\""], "$ git commit -m \"say \\\"hi\\\"\""),
|
||||||
|
(["commit", "-m", "it's"], "$ git commit -m \"it's\""),
|
||||||
|
(["commit", "-m", ""], "$ git commit -m \"\""),
|
||||||
|
(["add", "--", "pages/[id].vue"], "$ git add -- pages/[id].vue"),
|
||||||
|
])
|
||||||
|
func commandLine(arguments: [String], expected: String) {
|
||||||
|
#expect(GitConsoleText.commandLine(arguments) == expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: parseInput
|
||||||
|
|
||||||
|
@Test("typed input splits like a shell", arguments: [
|
||||||
|
("status", ["status"]),
|
||||||
|
(" git status ", ["status"]),
|
||||||
|
("git commit -m \"fix the bar\"", ["commit", "-m", "fix the bar"]),
|
||||||
|
("commit -m 'it is \"fine\"'", ["commit", "-m", "it is \"fine\""]),
|
||||||
|
("commit -m \"say \\\"hi\\\"\"", ["commit", "-m", "say \"hi\""]),
|
||||||
|
("commit -m \"a\\nb\"", ["commit", "-m", "a\\nb"]),
|
||||||
|
("commit -m \"\"", ["commit", "-m", ""]),
|
||||||
|
("log --format='%h %s'", ["log", "--format=%h %s"]),
|
||||||
|
("add my\\ file.txt", ["add", "my file.txt"]),
|
||||||
|
("commit -m \"unclosed", ["commit", "-m", "unclosed"]),
|
||||||
|
])
|
||||||
|
func parseInput(input: String, expected: [String]) {
|
||||||
|
#expect(GitConsoleText.parseInput(input) == expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("nothing to run is nil", arguments: ["", " ", "git", " git "])
|
||||||
|
func parseNothing(input: String) {
|
||||||
|
#expect(GitConsoleText.parseInput(input) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: syncLabel
|
||||||
|
|
||||||
|
@Test("the sync label names the remote", arguments: [
|
||||||
|
(0, 2, "origin/main", "2 behind origin"),
|
||||||
|
(1, 2, "origin/main", "1 ahead · 2 behind origin"),
|
||||||
|
(1, 0, "origin/main", "1 ahead of origin"),
|
||||||
|
(0, 0, "origin/feature/x", "in sync with origin"),
|
||||||
|
(0, 0, "upstream/main", "in sync with upstream"),
|
||||||
|
(3, 0, nil, "no upstream"),
|
||||||
|
] as [(Int, Int, String?, String)])
|
||||||
|
func syncLabel(ahead: Int, behind: Int, upstream: String?, expected: String) {
|
||||||
|
#expect(GitConsoleText.syncLabel(ahead: ahead, behind: behind, upstream: upstream) == expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: classifier
|
||||||
|
|
||||||
|
@Test("hints and errors are recognised for any command, whatever the stream", arguments: [
|
||||||
|
("hint: Updates were rejected", GitLineKind.hint),
|
||||||
|
("error: failed to push some refs", .error),
|
||||||
|
("fatal: not a git repository", .error),
|
||||||
|
(" ! [rejected] main -> main (fetch first)", .error),
|
||||||
|
(" ! [remote rejected] main -> main (pre-receive hook declined)", .error),
|
||||||
|
("Aborting", .error),
|
||||||
|
("Please commit your changes or stash them before you switch branches.", .error),
|
||||||
|
("Already up to date.", .output),
|
||||||
|
])
|
||||||
|
func generic(line: String, kind: GitLineKind) {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["pull"])
|
||||||
|
#expect(classifier.classify(line, isError: true) == kind)
|
||||||
|
var other = GitOutputClassifier(arguments: ["push"])
|
||||||
|
#expect(other.classify(line, isError: false) == kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("stderr progress is plain output")
|
||||||
|
func progressIsOutput() {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["push"])
|
||||||
|
#expect(classifier.classify("Writing objects: 100% (3/3), 280 bytes | 280.00 KiB/s, done.", isError: true) == .output)
|
||||||
|
#expect(classifier.classify("To github.com:x/y.git", isError: true) == .output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a push ref update is a success", arguments: [
|
||||||
|
" a1b2c3d..e4f5a6b main -> main",
|
||||||
|
" * [new branch] feature/x -> feature/x",
|
||||||
|
" + a1b2c3d...e4f5a6b main -> main (forced update)",
|
||||||
|
])
|
||||||
|
func pushSuccess(line: String) {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["push", "-u", "origin", "main"])
|
||||||
|
#expect(classifier.classify(line, isError: true) == .success)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a ref update outside push is plain output")
|
||||||
|
func refUpdateOutsidePush() {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["fetch"])
|
||||||
|
#expect(classifier.classify(" a1b2c3d..e4f5a6b main -> origin/main", isError: true) == .output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("status paths take the kind of their section")
|
||||||
|
func statusSections() {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["-c", "color.ui=never", "status"])
|
||||||
|
let lines: [(String, GitLineKind)] = [
|
||||||
|
("On branch main", .output),
|
||||||
|
("Changes to be committed:", .output),
|
||||||
|
(" (use \"git restore --staged <file>...\" to unstage)", .output),
|
||||||
|
("\tmodified: a.txt", .staged),
|
||||||
|
("Changes not staged for commit:", .output),
|
||||||
|
("\tmodified: b.txt", .unstaged),
|
||||||
|
("Untracked files:", .output),
|
||||||
|
("\tnew.txt", .unstaged),
|
||||||
|
]
|
||||||
|
for (line, kind) in lines {
|
||||||
|
#expect(classifier.classify(line, isError: false) == kind, "\(line)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("tab lines outside status are plain output")
|
||||||
|
func tabLinesOutsideStatus() {
|
||||||
|
var classifier = GitOutputClassifier(arguments: ["commit"])
|
||||||
|
_ = classifier.classify("Changes to be committed:", isError: false)
|
||||||
|
#expect(classifier.classify("\tmodified: a.txt", isError: false) == .output)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,15 @@ import Testing
|
|||||||
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
|
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test("behind and upstream pass through from the snapshot")
|
||||||
|
func behindAndUpstream() {
|
||||||
|
let state = GitDerivation.derive(GitSnapshot(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", changes: []))
|
||||||
|
#expect(state.behind == 2)
|
||||||
|
#expect(state.upstream == "origin/main")
|
||||||
|
#expect(GitDerivation.derive(nil).upstream == nil)
|
||||||
|
#expect(GitDerivation.derive(nil).behind == 0)
|
||||||
|
}
|
||||||
|
|
||||||
@Test("no snapshot means not a repository")
|
@Test("no snapshot means not a repository")
|
||||||
func notARepository() {
|
func notARepository() {
|
||||||
let state = GitDerivation.derive(nil)
|
let state = GitDerivation.derive(nil)
|
||||||
@@ -105,48 +114,8 @@ import Testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Suite struct SourceControlTextTests {
|
@Suite struct SourceControlTextTests {
|
||||||
private func change(_ path: String, staged: Bool = false) -> Change {
|
|
||||||
Change(path: path, status: .modified, added: 1, removed: 0, staged: staged)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("one group per folder, even when git returns the folder in separate runs")
|
|
||||||
func oneGroupPerFolder() {
|
|
||||||
let groups = SourceControlText.groupByDir([
|
|
||||||
change("tests/Feature/AlphaTest.php"), change("app/Models/User.php"), change("tests/Feature/BetaTest.php"),
|
|
||||||
])
|
|
||||||
#expect(groups.map(\.dir) == ["tests/Feature", "app/Models"])
|
|
||||||
#expect(groups[0].rows.map(\.path) == ["tests/Feature/AlphaTest.php", "tests/Feature/BetaTest.php"])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("every row is kept, so the keyboard cursor walks the full list")
|
|
||||||
func keepsEveryRow() {
|
|
||||||
let list = ["a/one.ts", "b/two.ts", "a/three.ts", "four.ts"].map { change($0) }
|
|
||||||
let flat = SourceControlText.groupByDir(list).flatMap(\.rows)
|
|
||||||
#expect(flat.count == list.count)
|
|
||||||
#expect(Set(flat.map(\.id)).count == list.count)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("a project-root file sits in the empty-string group")
|
|
||||||
func rootGroup() {
|
|
||||||
#expect(SourceControlText.groupByDir([change("README.md")]) == [ChangeGroup(dir: "", rows: [change("README.md")])])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("navigation walks staged groups before unstaged ones")
|
|
||||||
func navigationOrder() {
|
|
||||||
let order = SourceControlText.navigationOrder([change("b/x"), change("a/y", staged: true), change("b/z")])
|
|
||||||
#expect(order.map(\.path) == ["a/y", "b/x", "b/z"])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("a dictated commit message becomes one lowercase line")
|
@Test("a dictated commit message becomes one lowercase line")
|
||||||
func commitMessage() {
|
func commitMessage() {
|
||||||
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
|
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test("the push tooltip counts commits")
|
|
||||||
func pushTooltip() {
|
|
||||||
#expect(SourceControlText.pushTooltip(canPush: false, ahead: 0) == "Nothing to push (⌘P)")
|
|
||||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 1) == "Push 1 commit to remote (⌘P)")
|
|
||||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 3) == "Push 3 commits to remote (⌘P)")
|
|
||||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 0) == "Push the branch to remote (⌘P)")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import HelderCore
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite struct GitSectionsTests {
|
||||||
|
private func row(_ path: String, _ status: GitStatus, staged: Bool) -> Change {
|
||||||
|
Change(path: path, status: status, added: 1, removed: 0, staged: staged)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: build
|
||||||
|
|
||||||
|
@Test("rows land in the fixed section order, keeping their own order")
|
||||||
|
func build() {
|
||||||
|
let rows = [
|
||||||
|
row("gone.txt", .deleted, staged: false),
|
||||||
|
row("new.txt", .added, staged: false),
|
||||||
|
row("b.txt", .modified, staged: false),
|
||||||
|
row("staged-delete.txt", .deleted, staged: true),
|
||||||
|
row("a.txt", .modified, staged: false),
|
||||||
|
row("staged-add.txt", .added, staged: true),
|
||||||
|
]
|
||||||
|
let sections = GitSections.build(rows)
|
||||||
|
#expect(sections.map(\.kind) == [.staged, .changed, .untracked, .deleted])
|
||||||
|
#expect(sections.map(\.id) == ["staged", "changed", "untracked", "deleted"])
|
||||||
|
#expect(sections[0].rows.map(\.path) == ["staged-delete.txt", "staged-add.txt"])
|
||||||
|
#expect(sections[1].rows.map(\.path) == ["b.txt", "a.txt"])
|
||||||
|
#expect(sections[2].rows.map(\.path) == ["new.txt"])
|
||||||
|
#expect(sections[3].rows.map(\.path) == ["gone.txt"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("unstaged renames and conflicts count as changed", arguments: [GitStatus.modified, .renamed, .unmerged])
|
||||||
|
func changed(status: GitStatus) {
|
||||||
|
#expect(GitSections.build([row("x", status, staged: false)]).map(\.kind) == [.changed])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("empty sections are left out")
|
||||||
|
func emptySections() {
|
||||||
|
#expect(GitSections.build([]).isEmpty)
|
||||||
|
#expect(GitSections.build([row("gone", .deleted, staged: false)]).map(\.kind) == [.deleted])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("unique paths keep the first occurrence")
|
||||||
|
func uniquePaths() {
|
||||||
|
let rows = [row("a", .modified, staged: true), row("b", .added, staged: false), row("a", .modified, staged: false)]
|
||||||
|
#expect(GitSections.uniquePaths(rows) == ["a", "b"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: inline diff
|
||||||
|
|
||||||
|
private func lines(_ count: Int, changing changed: Int? = nil) -> (String, String) {
|
||||||
|
let original = (1...count).map { "line \($0)\n" }.joined()
|
||||||
|
let updated = (1...count).map { $0 == changed ? "line \($0) edited\n" : "line \($0)\n" }.joined()
|
||||||
|
return (original, updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a diff without changes has no rows")
|
||||||
|
func noChanges() {
|
||||||
|
let diff = LineDiff.build(original: "a\nb\n", updated: "a\nb\n")
|
||||||
|
#expect(InlineDiff.rows(from: diff).isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("unchanged runs beyond the context fold into gaps, leading and trailing included")
|
||||||
|
func gaps() {
|
||||||
|
let (original, updated) = lines(20, changing: 10)
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated))
|
||||||
|
#expect(rows.count == 9)
|
||||||
|
#expect(rows.first == .gap(6))
|
||||||
|
#expect(rows.last == .gap(7))
|
||||||
|
guard case let .line(left, right) = rows[1] else { Issue.record("expected a line"); return }
|
||||||
|
#expect(left?.number == 7)
|
||||||
|
#expect(right?.number == 7)
|
||||||
|
#expect(left?.mark == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a change near the edge keeps every row up to it")
|
||||||
|
func noLeadingGap() {
|
||||||
|
let (original, updated) = lines(5, changing: 2)
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 1)
|
||||||
|
#expect(rows.count == 4)
|
||||||
|
#expect(rows.last == .gap(2))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("two changes whose context touches share one run")
|
||||||
|
func mergedContext() {
|
||||||
|
let original = (1...10).map { "\($0)\n" }.joined()
|
||||||
|
let updated = original.replacingOccurrences(of: "3\n", with: "x\n").replacingOccurrences(of: "8\n", with: "y\n")
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: original, updated: updated), context: 2)
|
||||||
|
#expect(!rows.contains { if case .gap = $0 { true } else { false } })
|
||||||
|
#expect(rows.count == 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("a replaced line highlights the differing middle on both sides")
|
||||||
|
func highlight() {
|
||||||
|
let diff = LineDiff.build(original: "let a = 1\n", updated: "let a = 22\n")
|
||||||
|
let rows = InlineDiff.rows(from: diff)
|
||||||
|
#expect(rows == [.line(
|
||||||
|
left: InlineDiffCell(number: 1, text: "let a = 1", mark: .removed, highlight: 8..<9),
|
||||||
|
right: InlineDiffCell(number: 1, text: "let a = 22", mark: .added, highlight: 8..<10)
|
||||||
|
)])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("an insertion highlights only the side that grew")
|
||||||
|
func highlightOneSide() {
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: "foo()\n", updated: "foo(bar)\n"))
|
||||||
|
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
|
||||||
|
#expect(left?.highlight == nil)
|
||||||
|
#expect(right?.highlight == 4..<7)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("lines with nothing in common get no highlight")
|
||||||
|
func noCommonPart() {
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: "abc\n", updated: "xyz\n"))
|
||||||
|
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
|
||||||
|
#expect(left?.mark == .removed)
|
||||||
|
#expect(right?.mark == .added)
|
||||||
|
#expect(left?.highlight == nil)
|
||||||
|
#expect(right?.highlight == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("prefix and suffix never overlap on a repeated character")
|
||||||
|
func noOverlap() {
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: "aa\n", updated: "aaa\n"))
|
||||||
|
guard case let .line(left, right) = rows.first else { Issue.record("expected a line"); return }
|
||||||
|
#expect(left?.highlight == nil)
|
||||||
|
#expect(right?.highlight == 2..<3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("an added line alone has no highlight")
|
||||||
|
func unpaired() {
|
||||||
|
let rows = InlineDiff.rows(from: LineDiff.build(original: "a\n", updated: "a\nb\n"))
|
||||||
|
#expect(rows.last == .line(left: nil, right: InlineDiffCell(number: 2, text: "b", mark: .added)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,30 @@ import Testing
|
|||||||
#expect(result.canPush == canPush)
|
#expect(result.canPush == canPush)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test("the behind count comes from the header", arguments: [
|
||||||
|
("main...origin/main [ahead 1, behind 2]", 2),
|
||||||
|
("main...origin/main [behind 5]", 5),
|
||||||
|
("main...origin/main [ahead 3]", 0),
|
||||||
|
("main...origin/main", 0),
|
||||||
|
("feature/x", 0),
|
||||||
|
("HEAD (no branch)", 0),
|
||||||
|
])
|
||||||
|
func behind(header: String, count: Int) {
|
||||||
|
#expect(Porcelain.parseBehind(header: header) == count)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("the upstream comes from the header", arguments: [
|
||||||
|
("main...origin/main [ahead 1, behind 2]", "origin/main"),
|
||||||
|
("feature/x...origin/feature/x", "origin/feature/x"),
|
||||||
|
("main...origin/main [gone]", "origin/main"),
|
||||||
|
("main", nil),
|
||||||
|
("No commits yet on main", nil),
|
||||||
|
("HEAD (no branch)", nil),
|
||||||
|
] as [(String, String?)])
|
||||||
|
func upstream(header: String, name: String?) {
|
||||||
|
#expect(Porcelain.parseUpstream(header: header) == name)
|
||||||
|
}
|
||||||
|
|
||||||
@Test("the branch name comes from the header", arguments: [
|
@Test("the branch name comes from the header", arguments: [
|
||||||
("main...origin/main [ahead 1]", "main"),
|
("main...origin/main [ahead 1]", "main"),
|
||||||
("main", "main"),
|
("main", "main"),
|
||||||
@@ -72,6 +96,8 @@ import Testing
|
|||||||
#expect(parsed.branch == "main")
|
#expect(parsed.branch == "main")
|
||||||
#expect(parsed.ahead == 2)
|
#expect(parsed.ahead == 2)
|
||||||
#expect(parsed.canPush)
|
#expect(parsed.canPush)
|
||||||
|
#expect(parsed.behind == 0)
|
||||||
|
#expect(parsed.upstream == "origin/main")
|
||||||
#expect(parsed.entries == [
|
#expect(parsed.entries == [
|
||||||
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
|
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
|
||||||
StatusEntry(index: "?", working: "?", path: "new file.txt"),
|
StatusEntry(index: "?", working: "?", path: "new file.txt"),
|
||||||
@@ -107,6 +133,12 @@ import Testing
|
|||||||
#expect(parsed.entries.count == 1)
|
#expect(parsed.entries.count == 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test("a header ahead and behind carries both counts and the upstream")
|
||||||
|
func aheadAndBehind() {
|
||||||
|
let parsed = Porcelain.parseStatus("## main...origin/main [ahead 1, behind 2]\0")
|
||||||
|
#expect(parsed == ParsedStatus(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", entries: []))
|
||||||
|
}
|
||||||
|
|
||||||
@Test("empty output is a clean tree")
|
@Test("empty output is a clean tree")
|
||||||
func empty() {
|
func empty() {
|
||||||
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
|
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
|
||||||
@@ -120,14 +152,6 @@ import Testing
|
|||||||
|
|
||||||
// MARK: push
|
// MARK: push
|
||||||
|
|
||||||
@Test("a push toast prefers the ref line, a failure its last line")
|
|
||||||
func pushSummary() {
|
|
||||||
let ok = Porcelain.pushSummary(exitCode: 0, stdout: "", stderr: "To github.com:x/y.git\n abc..def main -> main\n")
|
|
||||||
#expect(ok == PushResult(ok: true, message: "abc..def main -> main"))
|
|
||||||
let failed = Porcelain.pushSummary(exitCode: 1, stdout: "", stderr: "error: failed to push\nhint: pull first\n")
|
|
||||||
#expect(failed == PushResult(ok: false, message: "hint: pull first"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test("a missing upstream is detected from git's hint")
|
@Test("a missing upstream is detected from git's hint")
|
||||||
func needsUpstream() {
|
func needsUpstream() {
|
||||||
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))
|
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import Testing
|
|||||||
@Suite struct ColumnLayoutTests {
|
@Suite struct ColumnLayoutTests {
|
||||||
@Test func roomyWindowUsesTheDesignRatios() {
|
@Test func roomyWindowUsesTheDesignRatios() {
|
||||||
let w = ColumnLayout.fluid(windowWidth: 1760, focus: .terminal)
|
let w = ColumnLayout.fluid(windowWidth: 1760, focus: .terminal)
|
||||||
#expect(w == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
|
#expect(w == ColumnWidths(explorer: 289, agent: 480))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func tightWindowFollowsFocus() {
|
@Test func tightWindowFollowsFocus() {
|
||||||
@@ -13,52 +13,45 @@ import Testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test func fittingKeepsTheEditorMinimum() {
|
@Test func fittingKeepsTheEditorMinimum() {
|
||||||
let fitted = ColumnLayout.fitted(ColumnWidths(sourceControl: 400, explorer: 400, agent: 400), windowWidth: 1000, visible: .all)
|
let fitted = ColumnLayout.fitted(ColumnWidths(explorer: 400, agent: 600), windowWidth: 1000, visible: .all)
|
||||||
#expect(fitted.sourceControl + fitted.explorer + fitted.agent <= 1000 - 3 - ColumnLayout.minEditorWidth)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aHiddenColumnIsNeitherCountedNorScaled() {
|
|
||||||
let widths = ColumnWidths(sourceControl: 400, explorer: 400, agent: 400)
|
|
||||||
let visible = ColumnVisibility(sourceControl: false)
|
|
||||||
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible)
|
|
||||||
#expect(fitted.sourceControl == 400)
|
|
||||||
#expect(fitted.explorer + fitted.agent <= 1000 - 2 - ColumnLayout.minEditorWidth)
|
#expect(fitted.explorer + fitted.agent <= 1000 - 2 - ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func withTheEditorHiddenTheAgentIsTheFlexColumn() {
|
@Test func aHiddenColumnIsNeitherCountedNorScaled() {
|
||||||
let widths = ColumnWidths(sourceControl: 400, explorer: 400, agent: 900)
|
let widths = ColumnWidths(explorer: 400, agent: 900)
|
||||||
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(editor: false))
|
let visible = ColumnVisibility(explorer: false)
|
||||||
#expect(fitted.agent == 900)
|
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible)
|
||||||
#expect(fitted.sourceControl + fitted.explorer <= 1000 - 2 - ColumnLayout.minEditorWidth)
|
#expect(fitted.explorer == 400)
|
||||||
}
|
|
||||||
|
|
||||||
@Test func withoutAFlexColumnTheFixedOnesOnlyHaveToFitTheWindow() {
|
|
||||||
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 480)
|
|
||||||
let visible = ColumnVisibility(editor: false, agent: false)
|
|
||||||
#expect(ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible) == widths)
|
|
||||||
let narrow = ColumnLayout.fitted(widths, windowWidth: 501, visible: visible)
|
|
||||||
#expect(narrow.sourceControl + narrow.explorer <= 500)
|
|
||||||
#expect(narrow.agent == 480)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func fittingWithOnlyTheAgentBesideTheEditor() {
|
|
||||||
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 900)
|
|
||||||
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(sourceControl: false, explorer: false))
|
|
||||||
#expect(fitted.sourceControl == 300)
|
|
||||||
#expect(fitted.agent <= 1000 - 1 - ColumnLayout.minEditorWidth)
|
#expect(fitted.agent <= 1000 - 1 - ColumnLayout.minEditorWidth)
|
||||||
#expect(fitted.agent >= 1000 - 2 - ColumnLayout.minEditorWidth)
|
#expect(fitted.agent >= 1000 - 2 - ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func withTheEditorHiddenTheAgentIsTheFlexColumn() {
|
||||||
|
let widths = ColumnWidths(explorer: 900, agent: 900)
|
||||||
|
let fitted = ColumnLayout.fitted(widths, windowWidth: 1000, visible: ColumnVisibility(editor: false))
|
||||||
|
#expect(fitted.agent == 900)
|
||||||
|
#expect(fitted.explorer <= 1000 - 1 - ColumnLayout.minEditorWidth)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func withoutAFlexColumnTheFixedOnesOnlyHaveToFitTheWindow() {
|
||||||
|
let widths = ColumnWidths(explorer: 400, agent: 480)
|
||||||
|
let visible = ColumnVisibility(editor: false, agent: false)
|
||||||
|
#expect(ColumnLayout.fitted(widths, windowWidth: 1000, visible: visible) == widths)
|
||||||
|
let narrow = ColumnLayout.fitted(widths, windowWidth: 300, visible: visible)
|
||||||
|
#expect(narrow.explorer <= 300)
|
||||||
|
#expect(narrow.agent == 480)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func splittersSitOnlyBetweenVisibleColumns() {
|
@Test func splittersSitOnlyBetweenVisibleColumns() {
|
||||||
#expect(ColumnVisibility.all.splitterCount == 3)
|
#expect(ColumnVisibility.all.splitterCount == 2)
|
||||||
#expect(ColumnVisibility(sourceControl: false, editor: false).splitterCount == 1)
|
#expect(ColumnVisibility(editor: false).splitterCount == 1)
|
||||||
#expect(ColumnVisibility(sourceControl: false, explorer: false, editor: false, agent: false).splitterCount == 0)
|
#expect(ColumnVisibility(explorer: false, editor: false, agent: false).splitterCount == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func theAgentLimitCountsOnlyVisibleColumns() {
|
@Test func theAgentLimitCountsOnlyVisibleColumns() {
|
||||||
let widths = ColumnWidths(sourceControl: 300, explorer: 300, agent: 480)
|
let widths = ColumnWidths(explorer: 300, agent: 480)
|
||||||
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: .all) == 1600 - 3 - 600 - ColumnLayout.minEditorWidth)
|
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: .all) == 1600 - 2 - 300 - ColumnLayout.minEditorWidth)
|
||||||
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: ColumnVisibility(explorer: false))
|
#expect(ColumnLayout.maxAgentWidth(windowWidth: 1600, widths: widths, visible: ColumnVisibility(explorer: false))
|
||||||
== 1600 - 2 - 300 - ColumnLayout.minEditorWidth)
|
== 1600 - 1 - ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import Foundation
|
||||||
|
import HelderCore
|
||||||
|
import HelderServices
|
||||||
|
import Testing
|
||||||
|
|
||||||
|
@Suite struct GitServiceConsoleTests {
|
||||||
|
/// A repository with `a.txt` committed, plus a bare remote it knows as `origin`.
|
||||||
|
private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) {
|
||||||
|
let remote = try TempGitRepo(bare: true)
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
try repo.commit(["a.txt": "a\n"], message: "init")
|
||||||
|
try repo.run("remote", "add", "origin", remote.root.path)
|
||||||
|
return (repo, remote)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: execute
|
||||||
|
|
||||||
|
@Test func executeStreamsTheLinesAndReturnsTheExitCode() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
try repo.commit(["a.txt": "a\n"])
|
||||||
|
try repo.write("a.txt", "b\n")
|
||||||
|
let log = LineLog()
|
||||||
|
let result = await GitService(root: repo.root).execute(["status"], onLine: log.append)
|
||||||
|
#expect(result.succeeded)
|
||||||
|
#expect(log.outputs.contains("On branch main"))
|
||||||
|
#expect(log.outputs.contains("\tmodified: a.txt"))
|
||||||
|
#expect(result.stdout.contains("modified: a.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aFailingCommandReturnsItsCodeAndStreamsStderr() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
try repo.commit(["a.txt": "a\n"])
|
||||||
|
let log = LineLog()
|
||||||
|
let result = await GitService(root: repo.root).execute(["checkout", "no-such-branch"], onLine: log.append)
|
||||||
|
#expect(!result.succeeded)
|
||||||
|
#expect(result.exitCode > 0)
|
||||||
|
#expect(log.errors.contains { $0.hasPrefix("error:") })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aCommitWithoutAMessageAbortsInsteadOfOpeningAnEditor() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
try repo.commit(["a.txt": "a\n"])
|
||||||
|
try repo.write("a.txt", "b\n")
|
||||||
|
try repo.run("add", "a.txt")
|
||||||
|
let log = LineLog()
|
||||||
|
let result = await GitService(root: repo.root).execute(["commit"], literalPathspecs: true, timeout: 10, onLine: log.append)
|
||||||
|
#expect(!result.succeeded)
|
||||||
|
#expect(result.exitCode != -1)
|
||||||
|
#expect(try repo.run("log", "--format=%s") == "commit\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func executeSwitchesOffPromptsEditorsAndPagers() async throws {
|
||||||
|
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") }
|
||||||
|
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
||||||
|
_ = await service.execute(["log"], onLine: { _, _ in })
|
||||||
|
_ = await service.execute(["log"], literalPathspecs: false, timeout: nil, onLine: { _, _ in })
|
||||||
|
let calls = runner.calls
|
||||||
|
#expect(calls.map(\.arguments) == [["log"], ["log"]])
|
||||||
|
for call in calls {
|
||||||
|
#expect(call.executable == "git")
|
||||||
|
#expect(call.environment?["GIT_TERMINAL_PROMPT"] == "0")
|
||||||
|
#expect(call.environment?["GCM_INTERACTIVE"] == "never")
|
||||||
|
#expect(call.environment?["GIT_EDITOR"] == "true")
|
||||||
|
#expect(call.environment?["GIT_PAGER"] == "cat")
|
||||||
|
#expect(call.environment?["PAGER"] == "cat")
|
||||||
|
}
|
||||||
|
#expect(calls[0].environment?["GIT_LITERAL_PATHSPECS"] == "1")
|
||||||
|
#expect(calls[1].environment?["GIT_LITERAL_PATHSPECS"] == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aHangingCommandGivesUpAfterTheTimeout() async throws {
|
||||||
|
let runner = ScriptedRunner { _ in
|
||||||
|
try await Task.sleep(nanoseconds: 30_000_000_000)
|
||||||
|
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
|
||||||
|
}
|
||||||
|
let log = LineLog()
|
||||||
|
let started = Date()
|
||||||
|
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
||||||
|
.execute(["fetch"], literalPathspecs: true, timeout: 0.2, onLine: log.append)
|
||||||
|
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "timed out after 0.2s"))
|
||||||
|
#expect(log.errors == ["timed out after 0.2s"])
|
||||||
|
#expect(Date().timeIntervalSince(started) < 5)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(.timeLimit(.minutes(1)))
|
||||||
|
func aTimeoutDoesNotWaitForAGrandchildHoldingStderr() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
let log = LineLog()
|
||||||
|
let started = Date()
|
||||||
|
let result = await GitService(root: repo.root)
|
||||||
|
.execute(["-c", "alias.hang=!sleep 30 >&2 & sleep 30", "hang"], literalPathspecs: true, timeout: 0.5, onLine: log.append)
|
||||||
|
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "timed out after 0.5s"))
|
||||||
|
#expect(Date().timeIntervalSince(started) < 1.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aMissingGitIsALaunchFailureNotAThrow() async throws {
|
||||||
|
let runner = ProcessRunner(locator: ExecutableLocator(directories: []))
|
||||||
|
let log = LineLog()
|
||||||
|
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).execute(["status"], onLine: log.append)
|
||||||
|
#expect(result == GitCommandResult(exitCode: -1, stdout: "", stderr: "git not found"))
|
||||||
|
#expect(log.errors == ["git not found"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: branches
|
||||||
|
|
||||||
|
@Test func branchesListsLocalAndOriginBranches() async throws {
|
||||||
|
let (repo, remote) = try repoWithRemote()
|
||||||
|
defer { withExtendedLifetime(remote) {} }
|
||||||
|
try repo.run("branch", "feature/a")
|
||||||
|
try repo.run("push", "-q", "origin", "main", "feature/a")
|
||||||
|
try repo.run("branch", "local-only")
|
||||||
|
try repo.run("remote", "set-head", "origin", "main")
|
||||||
|
let list = await GitService(root: repo.root).branches()
|
||||||
|
#expect(list.local == ["feature/a", "local-only", "main"])
|
||||||
|
#expect(list.remote == ["origin/feature/a", "origin/main"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func branchesOutsideARepositoryAreEmpty() async throws {
|
||||||
|
let dir = try TempDirectory()
|
||||||
|
#expect(await GitService(root: dir.root).branches() == .empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: author
|
||||||
|
|
||||||
|
@Test func authorReadsNameAndEmailFromConfig() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
#expect(await GitService(root: repo.root).author() == "Helder Tests <tests@helder.invalid>")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func authorIsNilWithoutAName() async throws {
|
||||||
|
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 1, stdout: "", stderr: "") }
|
||||||
|
#expect(await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).author() == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func authorIsTheNameAloneWithoutAnEmail() async throws {
|
||||||
|
let runner = ScriptedRunner { call in
|
||||||
|
call.arguments.last == "user.name"
|
||||||
|
? ProcessResult(exitCode: 0, stdout: "Ada\n", stderr: "")
|
||||||
|
: ProcessResult(exitCode: 1, stdout: "", stderr: "")
|
||||||
|
}
|
||||||
|
#expect(await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).author() == "Ada")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: status header
|
||||||
|
|
||||||
|
@Test func loadReadsBehindAndUpstream() async throws {
|
||||||
|
let (repo, remote) = try repoWithRemote()
|
||||||
|
defer { withExtendedLifetime(remote) {} }
|
||||||
|
try repo.commit(["b.txt": "b\n"], message: "second")
|
||||||
|
try repo.run("push", "-q", "-u", "origin", "main")
|
||||||
|
try repo.run("reset", "-q", "--hard", "HEAD~1")
|
||||||
|
try repo.commit(["c.txt": "c\n"], message: "local")
|
||||||
|
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||||
|
#expect(snapshot.ahead == 1)
|
||||||
|
#expect(snapshot.behind == 1)
|
||||||
|
#expect(snapshot.upstream == "origin/main")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aBranchWithoutUpstreamHasNone() async throws {
|
||||||
|
let repo = try TempGitRepo()
|
||||||
|
try repo.commit(["a.txt": "a\n"])
|
||||||
|
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||||
|
#expect(snapshot.upstream == nil)
|
||||||
|
#expect(snapshot.behind == 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ import Testing
|
|||||||
let repo = try repo()
|
let repo = try repo()
|
||||||
try repo.write("a.txt", "1\n2\n3\n4\n")
|
try repo.write("a.txt", "1\n2\n3\n4\n")
|
||||||
let service = GitService(root: repo.root)
|
let service = GitService(root: repo.root)
|
||||||
try await service.stage(["a.txt"])
|
try repo.run("add", "--", "a.txt")
|
||||||
let snapshot = try await service.load()
|
let snapshot = try await service.load()
|
||||||
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")])
|
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")])
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ import Testing
|
|||||||
let repo = try repo()
|
let repo = try repo()
|
||||||
let service = GitService(root: repo.root)
|
let service = GitService(root: repo.root)
|
||||||
try repo.write("a.txt", "1\nSTAGED\n3\n")
|
try repo.write("a.txt", "1\nSTAGED\n3\n")
|
||||||
try await service.stage(["a.txt"])
|
try repo.run("add", "--", "a.txt")
|
||||||
try repo.write("a.txt", "1\nSTAGED\n3\n4\n")
|
try repo.write("a.txt", "1\nSTAGED\n3\n4\n")
|
||||||
let snapshot = try await service.load()
|
let snapshot = try await service.load()
|
||||||
#expect(rows(snapshot, "a.txt") == [
|
#expect(rows(snapshot, "a.txt") == [
|
||||||
@@ -61,7 +61,7 @@ import Testing
|
|||||||
let repo = try repo()
|
let repo = try repo()
|
||||||
let service = GitService(root: repo.root)
|
let service = GitService(root: repo.root)
|
||||||
try repo.write("fresh.txt", "one\n")
|
try repo.write("fresh.txt", "one\n")
|
||||||
try await service.stage(["fresh.txt"])
|
try repo.run("add", "--", "fresh.txt")
|
||||||
try repo.write("fresh.txt", "one\ntwo\n")
|
try repo.write("fresh.txt", "one\ntwo\n")
|
||||||
let snapshot = try await service.load()
|
let snapshot = try await service.load()
|
||||||
#expect(rows(snapshot, "fresh.txt") == [
|
#expect(rows(snapshot, "fresh.txt") == [
|
||||||
@@ -192,183 +192,13 @@ import Testing
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suite struct GitServiceWriteTests {
|
@Suite struct GitServiceReadTests {
|
||||||
private func repo() throws -> TempGitRepo {
|
private func repo() throws -> TempGitRepo {
|
||||||
let repo = try TempGitRepo()
|
let repo = try TempGitRepo()
|
||||||
try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init")
|
try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init")
|
||||||
return repo
|
return repo
|
||||||
}
|
}
|
||||||
|
|
||||||
private func status(_ repo: TempGitRepo) throws -> String {
|
|
||||||
try repo.run("status", "--porcelain")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stagingADeletionRemovesTheFileFromTheIndex() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
|
|
||||||
try await GitService(root: repo.root).stage(["a.txt"])
|
|
||||||
#expect(try status(repo) == "D a.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stagingBothSidesOfAMoveRecordsARename() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try FileManager.default.moveItem(at: repo.root.appendingPathComponent("a.txt"), to: repo.root.appendingPathComponent("c.txt"))
|
|
||||||
try await GitService(root: repo.root).stage(["a.txt", "c.txt"])
|
|
||||||
#expect(try status(repo) == "R a.txt -> c.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func unstagingADeletionKeepsTheFileDeletedOnDisk() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.run("rm", "-q", "a.txt")
|
|
||||||
try await GitService(root: repo.root).unstage(["a.txt"])
|
|
||||||
#expect(try status(repo) == " D a.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func unstagingARenameLeavesTheOldPathStagedAsDeleted() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.run("mv", "a.txt", "c.txt")
|
|
||||||
try await GitService(root: repo.root).unstage(["c.txt"])
|
|
||||||
#expect(try status(repo) == "D a.txt\n?? c.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func unstagingWorksInARepositoryWithoutCommits() async throws {
|
|
||||||
let repo = try TempGitRepo()
|
|
||||||
try repo.write("first.txt", "x\n")
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
try await service.stage(["first.txt"])
|
|
||||||
#expect(try status(repo) == "A first.txt\n")
|
|
||||||
try await service.unstage(["first.txt"])
|
|
||||||
#expect(try status(repo) == "?? first.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stagingNothingRunsNoGit() async throws {
|
|
||||||
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") }
|
|
||||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
|
||||||
try await service.stage([])
|
|
||||||
try await service.unstage([])
|
|
||||||
#expect(runner.calls.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aFailedCommitThrowsWithGitsStderr() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
do {
|
|
||||||
try await GitService(root: repo.root).commit(message: "nothing")
|
|
||||||
Issue.record("commit with nothing staged should fail")
|
|
||||||
} catch let GitError.commandFailed(arguments, exitCode, _) {
|
|
||||||
#expect(arguments == ["commit", "-m", "nothing"])
|
|
||||||
#expect(exitCode != 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aFailedStageCarriesStderr() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
do {
|
|
||||||
try await GitService(root: repo.root).stage(["missing.txt"])
|
|
||||||
Issue.record("staging a missing path should fail")
|
|
||||||
} catch let GitError.commandFailed(_, _, stderr) {
|
|
||||||
#expect(stderr.contains("missing.txt"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardRevertsAModifiedFileToHead() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("a.txt", "1\nCHANGED\n3\n")
|
|
||||||
try await GitService(root: repo.root).discard(["a.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardRevertsAFileStagedThenEdited() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("a.txt", "staged\n")
|
|
||||||
try repo.run("add", "a.txt")
|
|
||||||
try repo.write("a.txt", "edited again\n")
|
|
||||||
try await GitService(root: repo.root).discard(["a.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardRemovesAnUntrackedFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("new.txt", "fresh\n")
|
|
||||||
try await GitService(root: repo.root).discard(["new.txt"])
|
|
||||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new.txt").path))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardUnstagesAndRemovesAStagedNewFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("staged-new.txt", "x\n")
|
|
||||||
try repo.run("add", "staged-new.txt")
|
|
||||||
try await GitService(root: repo.root).discard(["staged-new.txt"])
|
|
||||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("staged-new.txt").path))
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardRestoresADeletedFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
|
|
||||||
try await GitService(root: repo.root).discard(["a.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardRestoresAStagedDeletion() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.run("rm", "-q", "a.txt")
|
|
||||||
try await GitService(root: repo.root).discard(["a.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardHandlesSeveralPathsInOneCall() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("a.txt", "changed\n")
|
|
||||||
try repo.write("new.txt", "new\n")
|
|
||||||
try await GitService(root: repo.root).discard(["a.txt", "new.txt"])
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardNeverDeletesAFolderOrAnythingOutsideTheProject() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
let outside = repo.root.deletingLastPathComponent().appendingPathComponent("helder-outside-\(UUID().uuidString).txt")
|
|
||||||
try Data("keep\n".utf8).write(to: outside)
|
|
||||||
defer { try? FileManager.default.removeItem(at: outside) }
|
|
||||||
try repo.write("folder/inner.txt", "keep\n")
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
try await service.discard(["folder", "../" + outside.lastPathComponent])
|
|
||||||
#expect(FileManager.default.fileExists(atPath: outside.path))
|
|
||||||
#expect(try repo.read("folder/inner.txt") == "keep\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardingAStagedRenameRestoresTheSourceAndRemovesTheTarget() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.run("mv", "a.txt", "c.txt")
|
|
||||||
try await GitService(root: repo.root).discard(["c.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardingAStagedRenameEditedAfterwardsStillRestoresTheSource() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.run("mv", "a.txt", "c.txt")
|
|
||||||
try repo.write("c.txt", "edited\n")
|
|
||||||
try await GitService(root: repo.root).discard(["c.txt"])
|
|
||||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
|
||||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
|
|
||||||
#expect(try status(repo) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func contentsReadsTheHeadAndIndexCopies() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("a.txt", "staged\n")
|
|
||||||
try repo.run("add", "a.txt")
|
|
||||||
try repo.write("a.txt", "disk\n")
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
#expect(await service.contents(of: "a.txt", at: .head) == "1\n2\n3\n")
|
|
||||||
#expect(await service.contents(of: "a.txt", at: .index) == "staged\n")
|
|
||||||
#expect(await service.contents(of: "nope.txt", at: .head) == "")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func isRepositoryAcceptsAWorktreeGitFile() async throws {
|
@Test func isRepositoryAcceptsAWorktreeGitFile() async throws {
|
||||||
let repo = try repo()
|
let repo = try repo()
|
||||||
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
|
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
|
||||||
@@ -376,9 +206,6 @@ import Testing
|
|||||||
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
|
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
|
||||||
let service = GitService(root: worktree)
|
let service = GitService(root: worktree)
|
||||||
#expect(await service.isRepository())
|
#expect(await service.isRepository())
|
||||||
try Data("wt\n".utf8).write(to: worktree.appendingPathComponent("a.txt"))
|
|
||||||
try await service.discard(["a.txt"])
|
|
||||||
#expect(try String(contentsOf: worktree.appendingPathComponent("a.txt"), encoding: .utf8) == "1\n2\n3\n")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -394,59 +221,6 @@ import Testing
|
|||||||
return repo
|
return repo
|
||||||
}
|
}
|
||||||
|
|
||||||
private func status(_ repo: TempGitRepo) throws -> String {
|
|
||||||
try repo.run("status", "--porcelain")
|
|
||||||
}
|
|
||||||
|
|
||||||
private func editAll(_ repo: TempGitRepo) throws {
|
|
||||||
for path in ["pages/[id].vue", "pages/i.vue", "pages/d.vue", "a*.txt", "ab.txt", "a?.txt", "ac.txt", "-dash.txt", "with space.txt"] {
|
|
||||||
try repo.write(path, "changed\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardTouchesOnlyTheNamedFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try editAll(repo)
|
|
||||||
try await GitService(root: repo.root).discard(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
|
|
||||||
#expect(try repo.read("pages/[id].vue") == "id\n")
|
|
||||||
#expect(try repo.read("pages/i.vue") == "changed\n")
|
|
||||||
#expect(try repo.read("pages/d.vue") == "changed\n")
|
|
||||||
#expect(try repo.read("a*.txt") == "star\n")
|
|
||||||
#expect(try repo.read("ab.txt") == "changed\n")
|
|
||||||
#expect(try repo.read("ac.txt") == "changed\n")
|
|
||||||
#expect(try repo.read("-dash.txt") == "dash\n")
|
|
||||||
#expect(try repo.read("with space.txt") == "space\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func discardOfAnUntrackedGlobNameRemovesOnlyThatFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try repo.write("new/[x].txt", "n\n")
|
|
||||||
try repo.write("new/x.txt", "keep\n")
|
|
||||||
try await GitService(root: repo.root).discard(["new/[x].txt"])
|
|
||||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new/[x].txt").path))
|
|
||||||
#expect(try repo.read("new/x.txt") == "keep\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stageAndUnstageTouchOnlyTheNamedFile() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
try editAll(repo)
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
try await service.stage(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
|
|
||||||
let staged = try repo.run("diff", "--cached", "--name-only")
|
|
||||||
#expect(staged == "-dash.txt\na*.txt\na?.txt\npages/[id].vue\nwith space.txt\n")
|
|
||||||
try await service.stage(["pages/i.vue", "ab.txt"])
|
|
||||||
try await service.unstage(["pages/[id].vue", "a*.txt"])
|
|
||||||
#expect(try repo.run("diff", "--cached", "--name-only") == "-dash.txt\na?.txt\nab.txt\npages/i.vue\nwith space.txt\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func contentsReadsANameWithGlobCharactersOrALeadingDash() async throws {
|
|
||||||
let repo = try repo()
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
#expect(await service.contents(of: "pages/[id].vue", at: .head) == "id\n")
|
|
||||||
#expect(await service.contents(of: "-dash.txt", at: .head) == "dash\n")
|
|
||||||
#expect(await service.contents(of: "with space.txt", at: .index) == "space\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func everyGitCallRunsWithLiteralPathspecs() async throws {
|
@Test func everyGitCallRunsWithLiteralPathspecs() async throws {
|
||||||
let runner = ScriptedRunner { call in
|
let runner = ScriptedRunner { call in
|
||||||
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
|
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
|
||||||
@@ -454,83 +228,7 @@ import Testing
|
|||||||
}
|
}
|
||||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
||||||
_ = try await service.load()
|
_ = try await service.load()
|
||||||
try await service.stage(["a"])
|
|
||||||
try await service.unstage(["a"])
|
|
||||||
try await service.discard(["a"])
|
|
||||||
_ = await service.contents(of: "a", at: .head)
|
|
||||||
try await service.commit(message: "m")
|
|
||||||
_ = await service.push()
|
|
||||||
#expect(!runner.calls.isEmpty)
|
#expect(!runner.calls.isEmpty)
|
||||||
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
|
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suite struct GitServicePushTests {
|
|
||||||
/// A committed repository plus a bare remote it knows as `origin`.
|
|
||||||
private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) {
|
|
||||||
let remote = try TempGitRepo(bare: true)
|
|
||||||
let repo = try TempGitRepo()
|
|
||||||
try repo.commit(["a.txt": "a\n"], message: "init")
|
|
||||||
try repo.run("remote", "add", "origin", remote.root.path)
|
|
||||||
return (repo, remote)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aFirstPushSetsTheUpstream() async throws {
|
|
||||||
let (repo, remote) = try repoWithRemote()
|
|
||||||
defer { withExtendedLifetime(remote) {} }
|
|
||||||
let result = await GitService(root: repo.root).push()
|
|
||||||
#expect(result.ok)
|
|
||||||
#expect(result.message.contains("main"))
|
|
||||||
#expect(try repo.run("rev-parse", "--abbrev-ref", "main@{upstream}") == "origin/main\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aPushWithNothingNewReportsUpToDate() async throws {
|
|
||||||
let (repo, remote) = try repoWithRemote()
|
|
||||||
defer { withExtendedLifetime(remote) {} }
|
|
||||||
try repo.run("push", "-q", "-u", "origin", "main")
|
|
||||||
let result = await GitService(root: repo.root).push()
|
|
||||||
#expect(result == PushResult(ok: true, message: "Everything up-to-date"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aPushWithoutARemoteFailsWithGitsLastLine() async throws {
|
|
||||||
let repo = try TempGitRepo()
|
|
||||||
try repo.commit(["a.txt": "a\n"])
|
|
||||||
let result = await GitService(root: repo.root).push()
|
|
||||||
#expect(!result.ok)
|
|
||||||
#expect(!result.message.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func pushTurnsOffCredentialPrompts() async throws {
|
|
||||||
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "Everything up-to-date\n") }
|
|
||||||
_ = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
|
|
||||||
#expect(runner.calls.first?.arguments == ["push"])
|
|
||||||
#expect(runner.calls.first?.environment?["GIT_TERMINAL_PROMPT"] == "0")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aPushWithoutUpstreamRetriesWithTheCurrentBranch() async throws {
|
|
||||||
let runner = ScriptedRunner { call in
|
|
||||||
switch call.arguments {
|
|
||||||
case ["push"]:
|
|
||||||
return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: The current branch feature has no upstream branch.\n")
|
|
||||||
case ["rev-parse", "--abbrev-ref", "HEAD"]:
|
|
||||||
return ProcessResult(exitCode: 0, stdout: "feature\n", stderr: "")
|
|
||||||
default:
|
|
||||||
return ProcessResult(exitCode: 0, stdout: "", stderr: " * [new branch] feature -> feature\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
|
|
||||||
#expect(runner.calls.map(\.arguments).last == ["push", "-u", "origin", "feature"])
|
|
||||||
#expect(result == PushResult(ok: true, message: "* [new branch] feature -> feature"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aHangingPushGivesUpAfterTheTimeout() async throws {
|
|
||||||
let runner = ScriptedRunner { _ in
|
|
||||||
try await Task.sleep(nanoseconds: 30_000_000_000)
|
|
||||||
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
|
|
||||||
}
|
|
||||||
let started = Date()
|
|
||||||
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, pushTimeout: 0.2).push()
|
|
||||||
#expect(result == PushResult(ok: false, message: "push timed out"))
|
|
||||||
#expect(Date().timeIntervalSince(started) < 5)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -14,19 +14,4 @@ import Testing
|
|||||||
repo = nil
|
repo = nil
|
||||||
#expect(!FileManager.default.fileExists(atPath: root.path))
|
#expect(!FileManager.default.fileExists(atPath: root.path))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func gitServiceStagesAndCommits() async throws {
|
|
||||||
let repo = try TempGitRepo()
|
|
||||||
try repo.commit(["a.txt": "one\n"])
|
|
||||||
try repo.write("a.txt", "two\n")
|
|
||||||
let service = GitService(root: repo.root)
|
|
||||||
#expect(await service.isRepository())
|
|
||||||
try await service.stage(["a.txt"])
|
|
||||||
#expect(try repo.run("status", "--porcelain") == "M a.txt\n")
|
|
||||||
try await service.unstage(["a.txt"])
|
|
||||||
#expect(try repo.run("status", "--porcelain") == " M a.txt\n")
|
|
||||||
try await service.stage(["a.txt"])
|
|
||||||
try await service.commit(message: "second")
|
|
||||||
#expect(try repo.run("log", "--format=%s") == "second\ncommit\n")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,3 +63,93 @@ import Testing
|
|||||||
#expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh")
|
#expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Suite struct ProcessRunnerStreamTests {
|
||||||
|
let runner = ProcessRunner()
|
||||||
|
|
||||||
|
@Test func streamsEachLineWithItsStreamAndKeepsTheFullOutput() async throws {
|
||||||
|
let log = LineLog()
|
||||||
|
let result = try await runner.stream("sh", arguments: ["-c", "echo one; echo two >&2; printf 'three'"], in: nil,
|
||||||
|
environment: nil, onLine: log.append)
|
||||||
|
#expect(log.outputs == ["one", "three"])
|
||||||
|
#expect(log.errors == ["two"])
|
||||||
|
#expect(result == ProcessResult(exitCode: 0, stdout: "one\nthree", stderr: "two\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aCarriageReturnEndsALineAndEmptyLinesAreDropped() async throws {
|
||||||
|
let log = LineLog()
|
||||||
|
let script = "printf 'Counting 10%%\\rCounting 100%%\\r\\n\\ndone\\n' >&2"
|
||||||
|
let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append)
|
||||||
|
#expect(log.errors == ["Counting 10%", "Counting 100%", "done"])
|
||||||
|
#expect(result.stderr == "Counting 10%\rCounting 100%\r\n\ndone\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func linesArriveBeforeTheProcessEnds() async throws {
|
||||||
|
let arrivals = LineLog()
|
||||||
|
let started = Date()
|
||||||
|
_ = try await runner.stream("sh", arguments: ["-c", "echo first; sleep 1; echo second"], in: nil, environment: nil) { line, _ in
|
||||||
|
arrivals.append("\(line) \(Date().timeIntervalSince(started))", false)
|
||||||
|
}
|
||||||
|
let times = arrivals.texts.compactMap { $0.split(separator: " ").last.flatMap { Double($0) } }
|
||||||
|
try #require(times.count == 2)
|
||||||
|
#expect(times[1] - times[0] > 0.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func largeStreamedOutputOnBothPipesDoesNotDeadlock() async throws {
|
||||||
|
let log = LineLog()
|
||||||
|
let script = "i=0; while [ $i -lt 5000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done"
|
||||||
|
let result = try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil, onLine: log.append)
|
||||||
|
#expect(log.outputs.count == 5000)
|
||||||
|
#expect(log.errors.count == 5000)
|
||||||
|
#expect(log.outputs.last == "line4999")
|
||||||
|
#expect(result.stdout.split(separator: "\n").count == 5000)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func stdinIsClosedWhileStreaming() async throws {
|
||||||
|
let result = try await runner.stream("cat", arguments: [], in: nil, environment: nil) { _, _ in }
|
||||||
|
#expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: ""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func cancellationTerminatesAStreamingChild() async throws {
|
||||||
|
let started = Date()
|
||||||
|
let task = Task { try await runner.stream("sleep", arguments: ["10"], in: nil, environment: nil) { _, _ in } }
|
||||||
|
try await Task.sleep(for: .milliseconds(200))
|
||||||
|
task.cancel()
|
||||||
|
await #expect(throws: CancellationError.self) { try await task.value }
|
||||||
|
#expect(Date().timeIntervalSince(started) < 5)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(.timeLimit(.minutes(1)))
|
||||||
|
func cancellationDoesNotWaitForAGrandchildHoldingAPipe() async throws {
|
||||||
|
let marker = "helder-grandchild-\(UUID().uuidString.prefix(8))"
|
||||||
|
let script = "sleep 30 >&2 & echo $! > /tmp/\(marker); sleep 30"
|
||||||
|
let started = Date()
|
||||||
|
let task = Task { try await runner.stream("sh", arguments: ["-c", script], in: nil, environment: nil) { _, _ in } }
|
||||||
|
try await Task.sleep(for: .milliseconds(300))
|
||||||
|
task.cancel()
|
||||||
|
await #expect(throws: CancellationError.self) { try await task.value }
|
||||||
|
#expect(Date().timeIntervalSince(started) < 2)
|
||||||
|
let pid = try #require(pid_t(String(contentsOfFile: "/tmp/\(marker)", encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines)))
|
||||||
|
try? FileManager.default.removeItem(atPath: "/tmp/\(marker)")
|
||||||
|
try await Task.sleep(for: .milliseconds(200))
|
||||||
|
#expect(kill(pid, 0) != 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theDefaultStreamEmitsStdoutThenStderrAfterTheRun() async throws {
|
||||||
|
let log = LineLog()
|
||||||
|
let fake = CannedRunner(result: ProcessResult(exitCode: 2, stdout: "a\r\nb\n", stderr: "c\n\nd"))
|
||||||
|
let result = try await fake.stream("x", arguments: [], in: nil, environment: nil, onLine: log.append)
|
||||||
|
#expect(log.lines.map(\.text) == ["a", "b", "c", "d"])
|
||||||
|
#expect(log.lines.map(\.isError) == [false, false, true, true])
|
||||||
|
#expect(result.exitCode == 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A runner that only implements `run`, so `stream` falls back to the protocol's default.
|
||||||
|
private struct CannedRunner: ProcessRunning {
|
||||||
|
var result: ProcessResult
|
||||||
|
|
||||||
|
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Collects streamed output lines from any thread, for tests of `stream` and `execute`.
|
||||||
|
final class LineLog: @unchecked Sendable {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var recorded: [(text: String, isError: Bool)] = []
|
||||||
|
|
||||||
|
var lines: [(text: String, isError: Bool)] { lock.withLock { recorded } }
|
||||||
|
var texts: [String] { lines.map(\.text) }
|
||||||
|
var errors: [String] { lines.filter(\.isError).map(\.text) }
|
||||||
|
var outputs: [String] { lines.filter { !$0.isError }.map(\.text) }
|
||||||
|
|
||||||
|
func append(_ text: String, _ isError: Bool) {
|
||||||
|
lock.withLock { recorded.append((text, isError)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,26 +7,24 @@ import Testing
|
|||||||
@Test func addingActionsAreTeal() {
|
@Test func addingActionsAreTeal() {
|
||||||
#expect(ContextMenuOverlay.tint(for: .newFile(inDirectory: "")) == .add)
|
#expect(ContextMenuOverlay.tint(for: .newFile(inDirectory: "")) == .add)
|
||||||
#expect(ContextMenuOverlay.tint(for: .newFolder(inDirectory: "src")) == .add)
|
#expect(ContextMenuOverlay.tint(for: .newFolder(inDirectory: "src")) == .add)
|
||||||
#expect(ContextMenuOverlay.tint(for: .stage("a.php")) == .add)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func finderUnstageAndCopyFileNameAreAmberSoft() {
|
@Test func finderAndCopyFileNameAreAmberSoft() {
|
||||||
#expect(ContextMenuOverlay.tint(for: .revealInFinder("a.php")) == .modify)
|
#expect(ContextMenuOverlay.tint(for: .revealInFinder("a.php")) == .modify)
|
||||||
#expect(ContextMenuOverlay.tint(for: .unstage("a.php")) == .modify)
|
|
||||||
#expect(ContextMenuOverlay.tint(for: .copyFileName("a.php")) == .modify)
|
#expect(ContextMenuOverlay.tint(for: .copyFileName("a.php")) == .modify)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func passOnOpenDiffAndRenameAreGrey() {
|
@Test func passOnShowDiffAndRenameAreGrey() {
|
||||||
#expect(ContextMenuOverlay.tint(for: .passOnReference("a.php", code: nil)) == .rename)
|
#expect(ContextMenuOverlay.tint(for: .passOnReference("a.php", code: nil)) == .rename)
|
||||||
#expect(ContextMenuOverlay.tint(for: .passOnFileName("a.php")) == .rename)
|
#expect(ContextMenuOverlay.tint(for: .passOnFileName("a.php")) == .rename)
|
||||||
#expect(ContextMenuOverlay.tint(for: .bouwen("x")) == .rename)
|
#expect(ContextMenuOverlay.tint(for: .bouwen("x")) == .rename)
|
||||||
#expect(ContextMenuOverlay.tint(for: .openDiff("a.php")) == .rename)
|
|
||||||
#expect(ContextMenuOverlay.tint(for: .showDiff("a.php", line: 3)) == .rename)
|
#expect(ContextMenuOverlay.tint(for: .showDiff("a.php", line: 3)) == .rename)
|
||||||
#expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename)
|
#expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func showDiffWearsTheOpenDiffIcon() {
|
@Test func theGitViewItemsKeepThePlainIcon() {
|
||||||
#expect(ContextMenuOverlay.symbol(for: .showDiff("a.php", line: 3)) == ContextMenuOverlay.symbol(for: .openDiff("a.php")))
|
#expect(ContextMenuOverlay.tint(for: .openFile("a.php")) == .plain)
|
||||||
|
#expect(ContextMenuOverlay.tint(for: .commit(andPush: true)) == .plain)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() {
|
@Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() {
|
||||||
@@ -35,7 +33,7 @@ import Testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test func destructiveActionsAreAmberDeep() {
|
@Test func destructiveActionsAreAmberDeep() {
|
||||||
#expect(ContextMenuOverlay.tint(for: .discard("a.php")) == .danger)
|
#expect(ContextMenuOverlay.tint(for: .gitDiscard(["a.php"])) == .danger)
|
||||||
#expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger)
|
#expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import Testing
|
|||||||
let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() })
|
let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() })
|
||||||
let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘P",
|
let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘P",
|
||||||
"⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc",
|
"⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc",
|
||||||
"⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−"]
|
"⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−", "⌘1", "⌘2", "⌘3"]
|
||||||
#expect(Set(handled).subtracting(listed).isEmpty)
|
#expect(Set(handled).subtracting(listed).isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -218,15 +218,17 @@ private func makeModel(results: [String: [ContentGroup]] = [:], delays: [String:
|
|||||||
#expect(model.emptyMessage(for: .files) == "No file names match.")
|
#expect(model.emptyMessage(for: .files) == "No file names match.")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func theFocusedColumnTakesSeventyPercentAndTheSidesKeepTheirMinimum() {
|
@Test func withThisFileTheColumnsTakeThirtyFortyFiveAndTwentyFivePercent() {
|
||||||
let three: [SearchModel.Column] = [.thisFile, .project, .files]
|
let widths = SearchModel.widths(total: 1000, columns: [.thisFile, .project, .files])
|
||||||
let resting = SearchModel.widths(total: 1000, columns: three, focused: .project)
|
#expect(widths[.thisFile] == 300)
|
||||||
#expect(resting[.thisFile] == 230)
|
#expect(widths[.project] == 450)
|
||||||
#expect(resting[.files] == 250)
|
#expect(widths[.files] == 250)
|
||||||
#expect(resting[.project] == 520)
|
}
|
||||||
let files = SearchModel.widths(total: 1000, columns: three, focused: .files)
|
|
||||||
#expect(files[.files] == 700)
|
@Test func withoutThisFileTheColumnsTakeSixtyFiveAndThirtyFivePercent() {
|
||||||
#expect(files[.thisFile] == 180)
|
let widths = SearchModel.widths(total: 1000, columns: [.project, .files])
|
||||||
#expect(files[.project] == 120)
|
#expect(widths[.thisFile] == nil)
|
||||||
|
#expect(widths[.project] == 650)
|
||||||
|
#expect(widths[.files] == 350)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import Testing
|
|||||||
@Test(arguments: [
|
@Test(arguments: [
|
||||||
("p", Command.push), ("s", .save), ("m", .cycleMode), ("g", .toggleGit),
|
("p", Command.push), ("s", .save), ("m", .cycleMode), ("g", .toggleGit),
|
||||||
("l", .toggleAutoFit), (".", .toggleHidden), ("w", .closeFileOrWindow),
|
("l", .toggleAutoFit), (".", .toggleHidden), ("w", .closeFileOrWindow),
|
||||||
|
("1", .togglePane(.explorer)), ("2", .togglePane(.editor)), ("3", .togglePane(.terminal)),
|
||||||
])
|
])
|
||||||
func commandLettersMapToTheirCommand(key: String, command: Command) {
|
func commandLettersMapToTheirCommand(key: String, command: Command) {
|
||||||
#expect(route(cmd(key)) == .perform(command))
|
#expect(route(cmd(key)) == .perform(command))
|
||||||
@@ -41,9 +42,16 @@ import Testing
|
|||||||
#expect(route(cmd("c"), KeyContext(owner: .terminal, hasTextSelection: true)) == .pass)
|
#expect(route(cmd("c"), KeyContext(owner: .terminal, hasTextSelection: true)) == .pass)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commandEnterCommitsExceptInTheCommitBoxItself() {
|
@Test func commandEnterCommitsOnlyOverTheGitView() {
|
||||||
#expect(route(KeyPress(.enter, command: true)) == .perform(.commit))
|
#expect(route(KeyPress(.enter, command: true)) == .pass)
|
||||||
#expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
|
#expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .editor))) == .pass)
|
||||||
|
#expect(route(KeyPress(.enter, command: true), KeyContext(gitViewOpen: true)) == .perform(.commit))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func commandEnterInTheGitConsoleStaysWithTheConsole() {
|
||||||
|
let console = KeyContext(owner: .text(in: nil), gitViewOpen: true, inGitConsole: true)
|
||||||
|
#expect(route(KeyPress(.enter, command: true), console) == .pass)
|
||||||
|
#expect(route(cmd("p"), console) == .perform(.push))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func arrowsMoveTheRowCursorOnlyInAListWithoutAField() {
|
@Test func arrowsMoveTheRowCursorOnlyInAListWithoutAField() {
|
||||||
@@ -52,12 +60,12 @@ import Testing
|
|||||||
#expect(route(KeyPress(.up), list) == .perform(.moveRowCursor(-1)))
|
#expect(route(KeyPress(.up), list) == .perform(.moveRowCursor(-1)))
|
||||||
#expect(route(KeyPress(.enter), list) == .perform(.openSelectedRow))
|
#expect(route(KeyPress(.enter), list) == .perform(.openSelectedRow))
|
||||||
#expect(route(KeyPress(.down), KeyContext(activePanel: .editor)) == .pass)
|
#expect(route(KeyPress(.down), KeyContext(activePanel: .editor)) == .pass)
|
||||||
#expect(route(KeyPress(.down), KeyContext(owner: .text(in: .sourceControl), activePanel: .sourceControl)) == .pass)
|
#expect(route(KeyPress(.down), KeyContext(owner: .text(in: .explorer), activePanel: .explorer)) == .pass)
|
||||||
#expect(route(KeyPress(.enter), KeyContext(owner: .terminal, activePanel: .terminal)) == .pass)
|
#expect(route(KeyPress(.enter), KeyContext(owner: .terminal, activePanel: .terminal)) == .pass)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commandRightOpensTheRowMenuPassesASelectionOrMovesFocus() {
|
@Test func commandRightOpensTheRowMenuPassesASelectionOrMovesFocus() {
|
||||||
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .sourceControl)) == .perform(.openRowMenu))
|
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .explorer)) == .perform(.openRowMenu))
|
||||||
let selection = TextSelectionInfo(text: "x", startLine: 3, endLine: 4)
|
let selection = TextSelectionInfo(text: "x", startLine: 3, endLine: 4)
|
||||||
#expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor), editorTextSelection: selection))
|
#expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor), editorTextSelection: selection))
|
||||||
== .perform(.passSelection(selection)))
|
== .perform(.passSelection(selection)))
|
||||||
@@ -83,7 +91,7 @@ import Testing
|
|||||||
|
|
||||||
@Test func questionMarkOpensHelpButTypesInAField() {
|
@Test func questionMarkOpensHelpButTypesInAField() {
|
||||||
#expect(route(KeyPress(.character("?"), shift: true)) == .perform(.showShortcuts))
|
#expect(route(KeyPress(.character("?"), shift: true)) == .perform(.showShortcuts))
|
||||||
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
|
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .editor))) == .pass)
|
||||||
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .terminal)) == .pass)
|
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .terminal)) == .pass)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +101,45 @@ import Testing
|
|||||||
#expect(route(KeyPress(.escape), KeyContext(owner: .terminal)) == .pass)
|
#expect(route(KeyPress(.escape), KeyContext(owner: .terminal)) == .pass)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func commandGTogglesTheGitViewFromAnywhere() {
|
||||||
|
#expect(route(cmd("g")) == .perform(.toggleGit))
|
||||||
|
#expect(route(cmd("g"), KeyContext(owner: .terminal)) == .perform(.toggleGit))
|
||||||
|
#expect(route(cmd("g"), KeyContext(owner: .text(in: nil), gitViewOpen: true)) == .perform(.toggleGit))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func escapeClosesTheGitViewOnlyWhenNoOverlayIsOpen() {
|
||||||
|
let git = KeyContext(gitViewOpen: true)
|
||||||
|
#expect(route(KeyPress(.escape), git) == .perform(.closeGitView))
|
||||||
|
#expect(route(KeyPress(.escape), KeyContext(owner: .text(in: nil), gitViewOpen: true)) == .perform(.closeGitView))
|
||||||
|
#expect(route(KeyPress(.escape), KeyContext(overlay: .other, gitViewOpen: true)) == .perform(.dismissOverlay))
|
||||||
|
#expect(route(KeyPress(.escape), KeyContext(overlay: .diff(busy: false), gitViewOpen: true)) == .perform(.dismissOverlay))
|
||||||
|
#expect(route(KeyPress(.escape), KeyContext(overlay: .diff(busy: true), gitViewOpen: true)) == .pass)
|
||||||
|
#expect(route(KeyPress(.escape)) == .pass)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func overTheGitViewCommitPushAndSearchWorkFromItsFields() {
|
||||||
|
let field = KeyContext(owner: .text(in: nil), gitViewOpen: true)
|
||||||
|
#expect(route(KeyPress(.enter, command: true), field) == .perform(.commit))
|
||||||
|
#expect(route(cmd("p"), field) == .perform(.push))
|
||||||
|
#expect(route(cmd("f"), field) == .perform(.showSearch(seed: "")))
|
||||||
|
#expect(route(cmd("g"), field) == .perform(.toggleGit))
|
||||||
|
#expect(route(cmd("2"), field) == .perform(.togglePane(.editor)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func overTheGitViewTheColumnKeysRestAndTypingReachesTheField() {
|
||||||
|
let git = KeyContext(activePanel: .explorer, focusZone: .editor, recentFileCount: 3, gitViewOpen: true)
|
||||||
|
#expect(route(KeyPress(.down), git) == .pass)
|
||||||
|
#expect(route(KeyPress(.enter), git) == .pass)
|
||||||
|
#expect(route(KeyPress(.right, command: true), git) == .pass)
|
||||||
|
#expect(route(KeyPress(.left, command: true), git) == .pass)
|
||||||
|
#expect(route(KeyPress(.down, command: true), git) == .pass)
|
||||||
|
#expect(route(cmd("a"), git) == .pass)
|
||||||
|
let field = KeyContext(owner: .text(in: nil), gitViewOpen: true)
|
||||||
|
#expect(route(KeyPress(.character("x")), field) == .pass)
|
||||||
|
#expect(route(KeyPress(.character("?"), shift: true), field) == .pass)
|
||||||
|
#expect(route(cmd("c"), KeyContext(owner: .text(in: nil), hasTextSelection: true, gitViewOpen: true)) == .pass)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func anOpenOverlayOwnsEveryOtherKey() {
|
@Test func anOpenOverlayOwnsEveryOtherKey() {
|
||||||
let search = KeyContext(overlay: .other, activePanel: .explorer)
|
let search = KeyContext(overlay: .other, activePanel: .explorer)
|
||||||
#expect(route(cmd("g"), search) == .pass)
|
#expect(route(cmd("g"), search) == .pass)
|
||||||
@@ -125,7 +172,7 @@ import Testing
|
|||||||
#expect(route(cmd("p"), diff) == .perform(.push))
|
#expect(route(cmd("p"), diff) == .perform(.push))
|
||||||
#expect(route(cmd("s"), diff) == .perform(.save))
|
#expect(route(cmd("s"), diff) == .perform(.save))
|
||||||
#expect(route(cmd("c"), diff) == .perform(.focusCommitMessage))
|
#expect(route(cmd("c"), diff) == .perform(.focusCommitMessage))
|
||||||
#expect(route(KeyPress(.enter, command: true), diff) == .perform(.commit))
|
#expect(route(KeyPress(.enter, command: true), diff) == .pass)
|
||||||
#expect(route(KeyPress(.down, command: true), KeyContext(overlay: .diff(busy: false), focusZone: .editor, recentFileCount: 2))
|
#expect(route(KeyPress(.down, command: true), KeyContext(overlay: .diff(busy: false), focusZone: .editor, recentFileCount: 2))
|
||||||
== .perform(.showRecentFiles(initialSelection: 1)))
|
== .perform(.showRecentFiles(initialSelection: 1)))
|
||||||
#expect(route(KeyPress(.escape), diff) == .perform(.dismissOverlay))
|
#expect(route(KeyPress(.escape), diff) == .perform(.dismissOverlay))
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import HelderCore
|
import HelderCore
|
||||||
import HelderServices
|
import HelderServices
|
||||||
import HelderUI
|
@testable import HelderUI
|
||||||
import Testing
|
import Testing
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
@@ -13,6 +13,7 @@ import Testing
|
|||||||
("src/a.php", .modified, false),
|
("src/a.php", .modified, false),
|
||||||
("config/app.json", .modified, true),
|
("config/app.json", .modified, true),
|
||||||
("src/c.php", .deleted, false),
|
("src/c.php", .deleted, false),
|
||||||
|
("new.txt", .added, false),
|
||||||
])
|
])
|
||||||
|
|
||||||
private func makeStore(_ snapshot: GitSnapshot? = nil) async -> (SourceControlStore, FakeGit, Recorder) {
|
private func makeStore(_ snapshot: GitSnapshot? = nil) async -> (SourceControlStore, FakeGit, Recorder) {
|
||||||
@@ -24,22 +25,26 @@ import Testing
|
|||||||
return (store, git, recorder)
|
return (store, git, recorder)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func texts(_ store: SourceControlStore) -> [String] { store.lines.map(\.line.text) }
|
||||||
|
private func kinds(_ store: SourceControlStore) -> [GitLineKind] { store.lines.map(\.line.kind) }
|
||||||
|
|
||||||
// MARK: Loading
|
// MARK: Loading
|
||||||
|
|
||||||
@Test func refreshDerivesTheRowsFromGit() async {
|
@Test func refreshDerivesTheRowsFromGit() async {
|
||||||
let (store, _, _) = await makeStore()
|
let (store, _, _) = await makeStore()
|
||||||
#expect(store.hasLoaded)
|
#expect(store.hasLoaded)
|
||||||
#expect(store.state.isRepository)
|
#expect(store.state.isRepository)
|
||||||
#expect(store.state.stagedCount == 2)
|
#expect(store.stagedPathCount == 2)
|
||||||
#expect(store.state.unstagedCount == 4)
|
#expect(store.changedPathCount == 6)
|
||||||
|
#expect(store.isDirty)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func aProjectWithoutGitReadsAsNotARepository() async {
|
@Test func aProjectWithoutGitReadsAsNotARepository() async {
|
||||||
let git = FakeGit(nil)
|
let store = SourceControlStore(git: FakeGit(nil), derive: TestDerivation.derive)
|
||||||
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
|
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
#expect(store.hasLoaded)
|
#expect(store.hasLoaded)
|
||||||
#expect(!store.state.isRepository)
|
#expect(!store.state.isRepository)
|
||||||
|
#expect(!store.isDirty)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func anOlderSlowerRefreshCannotOverwriteANewerOne() async {
|
@Test func anOlderSlowerRefreshCannotOverwriteANewerOne() async {
|
||||||
@@ -62,29 +67,21 @@ import Testing
|
|||||||
}
|
}
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
#expect(onMain.current == [false])
|
#expect(onMain.current == [false])
|
||||||
#expect(store.state.changes.count == 6)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(.timeLimit(.minutes(1)))
|
@Test func aFailedStatusReadStillLoadsAndLogsItsErrorOnce() async {
|
||||||
func aSlowDerivationOvertakenByANewerRefreshIsDropped() async {
|
struct StatusFailed: Error, CustomStringConvertible { var description: String { "index.lock exists" } }
|
||||||
let git = FakeGit()
|
let git = FakeGit(sample)
|
||||||
git.queue(snapshot([("old.txt", .modified, false)]), after: .zero)
|
git.setLoadError(StatusFailed())
|
||||||
git.queue(snapshot([("new.txt", .modified, false)]), after: .zero)
|
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
|
||||||
let release = DispatchSemaphore(value: 0)
|
|
||||||
let started = Locked(0)
|
|
||||||
let store = SourceControlStore(git: git) { snapshot in
|
|
||||||
if snapshot?.changes.first?.path == "old.txt" {
|
|
||||||
started.mutate { $0 += 1 }
|
|
||||||
release.wait()
|
|
||||||
}
|
|
||||||
return TestDerivation.derive(snapshot)
|
|
||||||
}
|
|
||||||
let slow = Task { await store.refresh() }
|
|
||||||
#expect(await eventually { started.current == 1 })
|
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
release.signal()
|
await store.refresh()
|
||||||
await slow.value
|
#expect(store.hasLoaded)
|
||||||
#expect(store.state.changes.map(\.path) == ["new.txt"])
|
#expect(texts(store) == ["status failed: index.lock exists"])
|
||||||
|
#expect(kinds(store) == [.error])
|
||||||
|
git.setLoadError(nil)
|
||||||
|
await store.refresh()
|
||||||
|
#expect(store.isDirty)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func loadIfNeededReadsGitOnlyOnce() async {
|
@Test func loadIfNeededReadsGitOnlyOnce() async {
|
||||||
@@ -93,24 +90,6 @@ import Testing
|
|||||||
#expect(git.loads == 1)
|
#expect(git.loads == 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Grouping and order
|
|
||||||
|
|
||||||
@Test func rowsWalkStagedFoldersFirstThenUnstagedFoldersInOrderOfFirstAppearance() async {
|
|
||||||
let (store, _, _) = await makeStore()
|
|
||||||
#expect(store.stagedGroups.map(\.dir) == ["src", "config"])
|
|
||||||
#expect(store.unstagedGroups.map(\.dir) == ["src", ""])
|
|
||||||
#expect(store.unstagedGroups[0].rows.map(\.path) == ["src/b.php", "src/a.php", "src/c.php"])
|
|
||||||
#expect(store.rows.map(\.id) == [
|
|
||||||
"s:src/a.php", "s:config/app.json",
|
|
||||||
"w:src/b.php", "w:src/a.php", "w:src/c.php", "w:README.md",
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func aFileStagedAndEditedAgainHasTwoRows() async {
|
|
||||||
let (store, _, _) = await makeStore()
|
|
||||||
#expect(store.rows.filter { $0.path == "src/a.php" }.map(\.staged) == [true, false])
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func theExplorerLetterComesFromTheUnstagedRow() async {
|
@Test func theExplorerLetterComesFromTheUnstagedRow() async {
|
||||||
let (store, _, _) = await makeStore()
|
let (store, _, _) = await makeStore()
|
||||||
#expect(store.fileStatuses["src/a.php"] == .modified)
|
#expect(store.fileStatuses["src/a.php"] == .modified)
|
||||||
@@ -118,91 +97,232 @@ import Testing
|
|||||||
#expect(store.fileStatuses["src/c.php"] == .deleted)
|
#expect(store.fileStatuses["src/c.php"] == .deleted)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Keyboard cursor
|
// MARK: Sections and rows
|
||||||
|
|
||||||
@Test func theCursorStartsAtTheTopClampsAtTheEndsAndFollowsRowIDs() async {
|
@Test func rowsFallIntoTheFourSectionsStagedFirst() async {
|
||||||
let (store, _, _) = await makeStore()
|
let (store, _, _) = await makeStore()
|
||||||
store.moveSelection(by: 1)
|
#expect(store.sections.map(\.kind) == [.staged, .changed, .untracked, .deleted])
|
||||||
#expect(store.selectedRowID == "s:src/a.php")
|
#expect(store.sections[0].rows.map(\.path) == ["src/a.php", "config/app.json"])
|
||||||
store.moveSelection(by: -1)
|
#expect(store.sections[1].rows.map(\.path) == ["src/b.php", "README.md", "src/a.php"])
|
||||||
#expect(store.selectedRowID == "s:src/a.php")
|
#expect(store.sections[2].rows.map(\.path) == ["new.txt"])
|
||||||
store.moveSelection(by: 100)
|
#expect(store.sections[3].rows.map(\.path) == ["src/c.php"])
|
||||||
#expect(store.selectedRowID == "w:README.md")
|
|
||||||
#expect(store.selectedRow?.path == "README.md")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func aCursorWhoseRowVanishedStartsOverAtTheTop() async {
|
@Test func sectionsStartOpenAndRowsStartClosed() async {
|
||||||
let (store, git, _) = await makeStore()
|
let (store, _, _) = await makeStore()
|
||||||
store.selectedRowID = "w:src/c.php"
|
let row = store.sections[1].rows[0]
|
||||||
git.set(snapshot([("x.txt", .modified, true)]))
|
#expect(!store.isCollapsed(.changed))
|
||||||
|
store.toggleSection(.changed)
|
||||||
|
#expect(store.isCollapsed(.changed))
|
||||||
|
store.toggleSection(.changed)
|
||||||
|
#expect(!store.isCollapsed(.changed))
|
||||||
|
#expect(!store.isExpanded(.changed, row))
|
||||||
|
store.toggleRow(.changed, row)
|
||||||
|
#expect(store.expandedRows == ["changed:w:src/b.php"])
|
||||||
|
store.toggleRow(.changed, row)
|
||||||
|
#expect(store.expandedRows.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func anExpandedRowShowsItsOwnHalfOrTooBig() async {
|
||||||
|
let big = GitFileChange(path: "big.bin", status: .modified, staged: false, original: "", updated: "", isTooBig: true)
|
||||||
|
let git = FakeGit(GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||||
|
GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n", updated: "1\nX\n"), big,
|
||||||
|
]))
|
||||||
|
let store = SourceControlStore(git: git)
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
store.moveSelection(by: 1)
|
let rows = store.sections[0].rows
|
||||||
#expect(store.selectedRowID == "s:x.txt")
|
guard case let .rows(lines) = store.detail(for: rows[0]) else {
|
||||||
|
Issue.record("expected inline rows")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(!lines.isEmpty)
|
||||||
|
#expect(store.detail(for: rows[1]) == .tooBig)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Staging
|
// MARK: Every action logs the command and streams its output
|
||||||
|
|
||||||
@Test func stagingAndUnstagingSendTheRowPathAndReload() async {
|
@Test func stagingLogsTheExactCommandThenItsOutput() async {
|
||||||
let (store, git, _) = await makeStore()
|
let (store, git, _) = await makeStore()
|
||||||
await store.stage("src/b.php")
|
git.setRun(FakeGitRun(lines: [("warning: LF will be replaced", true)]), forCommand: "add")
|
||||||
await store.unstage("config/app.json")
|
await store.stage(["src/b.php"])
|
||||||
#expect(git.staged == [["src/b.php"]])
|
#expect(git.executed == [["add", "--", "src/b.php"]])
|
||||||
#expect(git.unstaged == [["config/app.json"]])
|
#expect(texts(store) == ["$ git add -- src/b.php", "warning: LF will be replaced"])
|
||||||
#expect(git.loads == 3)
|
#expect(kinds(store) == [.command, .output])
|
||||||
|
#expect(git.loads == 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func stageAllSendsEveryPathWithAnUnstagedRowOnce() async {
|
@Test func stagingEveryUnstagedPathStillListsThePaths() async {
|
||||||
let (store, git, _) = await makeStore()
|
let (store, git, _) = await makeStore()
|
||||||
await store.stageAll()
|
let paths = store.state.unstagedPaths
|
||||||
#expect(git.staged == [["src/b.php", "README.md", "src/a.php", "src/c.php"]])
|
await store.stage(paths)
|
||||||
|
#expect(git.executed == [["add", "--"] + paths])
|
||||||
|
#expect(!git.executed.flatMap { $0 }.contains("-A"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func unstageAllSendsEveryStagedPath() async {
|
@Test func twoQuickActionsRunOneAfterTheOther() async {
|
||||||
let (store, git, _) = await makeStore()
|
let (store, git, _) = await makeStore()
|
||||||
await store.unstageAll()
|
git.setRun(FakeGitRun(delay: .milliseconds(150)), for: ["add", "--", "src/b.php"])
|
||||||
#expect(git.unstaged == [["src/a.php", "config/app.json"]])
|
let first = Task { await store.stage(["src/b.php"]) }
|
||||||
|
let second = Task { await store.stage(["README.md"]) }
|
||||||
|
await first.value
|
||||||
|
await second.value
|
||||||
|
#expect(git.events == ["start add -- src/b.php", "end add -- src/b.php", "start add -- README.md", "end add -- README.md"])
|
||||||
|
#expect(texts(store) == ["$ git add -- src/b.php", "$ git add -- README.md"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func stageAllWithNothingToStageCallsNoGit() async {
|
@Test func unstagingARenameTakesItsSourceAlong() async {
|
||||||
let (store, git, _) = await makeStore(snapshot([("a.txt", .modified, true)]))
|
let renamed = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||||
await store.stageAll()
|
GitFileChange(path: "new.txt", status: .renamed, staged: true, original: "a", updated: "a", originalPath: "old.txt"),
|
||||||
#expect(git.staged.isEmpty)
|
GitFileChange(path: "other.txt", status: .modified, staged: true, original: "a", updated: "b"),
|
||||||
|
])
|
||||||
|
let (store, git, _) = await makeStore(renamed)
|
||||||
|
await store.unstage(["new.txt"])
|
||||||
|
#expect(git.executed == [["restore", "--staged", "--", "new.txt", "old.txt"]])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func discardLeavesAConflictAlone() async {
|
||||||
|
let (store, git, _) = await makeStore(snapshot([("both.txt", .unmerged, false), ("src/b.php", .modified, false)]))
|
||||||
|
await store.discard(["both.txt"])
|
||||||
|
#expect(git.executed.isEmpty)
|
||||||
|
await store.discard(["both.txt", "src/b.php"])
|
||||||
|
#expect(git.executed == [["restore", "--", "src/b.php"]])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func unstagingLogsRestoreStaged() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
await store.unstage(["config/app.json"])
|
||||||
|
await store.unstage(["src/a.php", "config/app.json"])
|
||||||
|
#expect(git.executed == [["restore", "--staged", "--", "config/app.json"], ["restore", "--staged", "."]])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func withoutCommitsUnstagingFallsBackToRmCached() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
git.setRun(FakeGitRun(exitCode: 128, lines: [("fatal: could not resolve HEAD", true)]), forCommand: "restore")
|
||||||
|
await store.unstage(["config/app.json"])
|
||||||
|
#expect(git.executed == [["restore", "--staged", "--", "config/app.json"], ["rm", "--cached", "-r", "--", "config/app.json"]])
|
||||||
|
#expect(texts(store) == [
|
||||||
|
"$ git restore --staged -- config/app.json", "fatal: could not resolve HEAD", "$ git rm --cached -r -- config/app.json",
|
||||||
|
])
|
||||||
|
#expect(kinds(store) == [.command, .error, .command])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func outputIsClassifiedPerCommand() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
git.setRun(FakeGitRun(lines: [
|
||||||
|
("Changes to be committed:", false), ("\tmodified: a.php", false),
|
||||||
|
("Untracked files:", false), ("\tnew.txt", false), ("hint: use git add", false),
|
||||||
|
]), forCommand: "status")
|
||||||
|
store.consoleInput = "status"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
#expect(kinds(store) == [.command, .output, .staged, .output, .unstaged, .hint])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func linesFromAnotherThreadArriveInOrderBeforeTheActionEnds() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
let many = (1...50).map { ("line \($0)", false) }
|
||||||
|
git.setRun(FakeGitRun(lines: many), forCommand: "log")
|
||||||
|
store.consoleInput = "log -n 50"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
#expect(texts(store) == ["$ git log -n 50"] + many.map(\.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Discard, delete, restore
|
||||||
|
|
||||||
|
@Test func discardingModifiedFilesAsksWithTheRevertCopy() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
let one = store.confirmation(for: .gitDiscard(["src/b.php"]))
|
||||||
|
#expect(one?.title == "Discard changes to src/b.php?")
|
||||||
|
#expect(one?.body == "This reverts to the last commit and cannot be undone.")
|
||||||
|
#expect(one?.confirmLabel == "Discard")
|
||||||
|
#expect(store.confirmation(for: .gitDiscard(["src/b.php", "README.md"]))?.title == "Discard changes to 2 files?")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func deletingNewFilesAsksWithTheDeleteCopy() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
let request = store.confirmation(for: .gitDiscard(["new.txt"]))
|
||||||
|
#expect(request?.title == "Delete new.txt?")
|
||||||
|
#expect(request?.body == "New files are removed from disk. This cannot be undone.")
|
||||||
|
#expect(request?.confirmLabel == "Delete")
|
||||||
|
let mixed = store.confirmation(for: .gitDiscard(["new.txt", "src/b.php"]))
|
||||||
|
#expect(mixed?.title == "Discard changes to 2 files?")
|
||||||
|
#expect(mixed?.body == "New files are removed from disk. This cannot be undone.")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func restoringDeletedFilesNeverAsks() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
#expect(store.confirmation(for: .gitDiscard(["src/c.php"])) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theConfigCanSwitchTheQuestionOff() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
store.config.confirmDiscard = false
|
||||||
|
#expect(store.confirmation(for: .gitDiscard(["src/b.php"])) == nil)
|
||||||
|
#expect(store.confirmation(for: .copyReference("a")) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func discardRestoresTrackedFilesAndCleansNewOnes() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
git.setRun(FakeGitRun(lines: [("Removing new.txt", false)]), forCommand: "clean")
|
||||||
|
await store.discard(["src/b.php", "new.txt", "src/c.php"])
|
||||||
|
#expect(git.executed == [["restore", "--", "src/b.php", "src/c.php"], ["clean", "-f", "--", "new.txt"]])
|
||||||
|
#expect(texts(store) == ["$ git restore -- src/b.php src/c.php", "$ git clean -f -- new.txt", "Removing new.txt"])
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Commit
|
// MARK: Commit
|
||||||
|
|
||||||
@Test func commitNeedsAStagedFileAndAMessage() async {
|
@Test func commitAlwaysRunsGitEvenWithNothingStagedOrNoMessage() async {
|
||||||
let (store, _, _) = await makeStore()
|
let (store, git, recorder) = await makeStore(snapshot([("a.txt", .modified, false)]))
|
||||||
#expect(!store.canCommit)
|
git.setRun(FakeGitRun(exitCode: 1, lines: [("no changes added to commit (use \"git add\" and/or \"git commit -a\")", false)]),
|
||||||
store.setCommitMessage(" ")
|
forCommand: "commit")
|
||||||
#expect(!store.canCommit)
|
var focused = 0
|
||||||
|
store.focusMessage = { focused += 1 }
|
||||||
store.setCommitMessage("fix it")
|
store.setCommitMessage("fix it")
|
||||||
#expect(store.canCommit)
|
await store.commit()
|
||||||
|
store.setCommitMessage("")
|
||||||
let (clean, git, _) = await makeStore(snapshot([("a.txt", .modified, false)]))
|
await store.commit()
|
||||||
clean.setCommitMessage("fix it")
|
#expect(git.executed == [["commit", "-m", "fix it"], ["commit", "-m", ""]])
|
||||||
#expect(!clean.canCommit)
|
#expect(texts(store).first == "$ git commit -m \"fix it\"")
|
||||||
#expect(await clean.commit() == 0)
|
#expect(texts(store).contains("$ git commit -m \"\""))
|
||||||
#expect(git.commits.isEmpty)
|
#expect(focused == 1)
|
||||||
|
#expect(recorder.toastTitles == ["Commit failed", "Commit failed"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commitSendsTheMessageClearsTheDraftAndCountsDistinctFiles() async {
|
@Test func aSuccessfulCommitClearsTheMessageAndCountsDistinctFiles() async {
|
||||||
let (store, git, recorder) = await makeStore()
|
let (store, git, recorder) = await makeStore()
|
||||||
store.setCommitMessage("add the payment service ")
|
store.setCommitMessage("add the payment service ")
|
||||||
let count = await store.commit()
|
#expect(store.canCommitNow)
|
||||||
#expect(count == 2)
|
await store.commit()
|
||||||
#expect(git.commits == ["add the payment service"])
|
#expect(git.executed == [["commit", "-m", "add the payment service"]])
|
||||||
#expect(store.commitMessage.isEmpty)
|
#expect(store.commitMessage.isEmpty)
|
||||||
#expect(recorder.toastTitles == ["Committed 2 files"])
|
#expect(recorder.toastTitles == ["Committed 2 files"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func aFailedCommitKeepsTheDraft() async {
|
@Test func aFailedCommitKeepsTheMessage() async {
|
||||||
let (store, git, recorder) = await makeStore()
|
let (store, git, _) = await makeStore()
|
||||||
git.setFailCommit(true)
|
git.setRun(FakeGitRun(exitCode: 1, lines: [("error: hook failed", true)]), forCommand: "commit")
|
||||||
store.setCommitMessage("wip")
|
store.setCommitMessage("wip")
|
||||||
#expect(await store.commit() == 0)
|
await store.commit()
|
||||||
#expect(store.commitMessage == "wip")
|
#expect(store.commitMessage == "wip")
|
||||||
#expect(recorder.toastTitles == ["Commit failed"])
|
}
|
||||||
|
|
||||||
|
@Test func theReadyLookNeedsAStagedFileAndAMessage() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
#expect(!store.canCommitNow)
|
||||||
|
store.setCommitMessage(" ")
|
||||||
|
#expect(!store.canCommitNow)
|
||||||
|
store.setCommitMessage("fix it")
|
||||||
|
#expect(store.canCommitNow)
|
||||||
|
let (clean, _, _) = await makeStore(snapshot([("a.txt", .modified, false)]))
|
||||||
|
clean.setCommitMessage("fix it")
|
||||||
|
#expect(!clean.canCommitNow)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theMessageFieldGrowsWithWrappedLinesWithinItsBounds() {
|
||||||
|
#expect(GitMessageField.height(of: "", width: 800) == GitMetrics.messageMin)
|
||||||
|
#expect(GitMessageField.height(of: "fix it", width: 800) == GitMetrics.messageMin)
|
||||||
|
let three = GitMessageField.height(of: String(repeating: "word ", count: 30), width: 300)
|
||||||
|
#expect(three > GitMetrics.messageMin && three < GitMetrics.messageMax)
|
||||||
|
#expect(GitMessageField.height(of: String(repeating: "word ", count: 400), width: 300) == GitMetrics.messageMax)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func dictatedMessagesBecomeOneLowercaseLine() {
|
@Test func dictatedMessagesBecomeOneLowercaseLine() {
|
||||||
@@ -211,52 +331,180 @@ import Testing
|
|||||||
#expect(store.commitMessage == "fix the bug and the test")
|
#expect(store.commitMessage == "fix the bug and the test")
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Push
|
@Test func commitAndPushPushesOnlyAfterASuccessfulCommit() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
store.setCommitMessage("ship it")
|
||||||
|
await store.commit(andPush: true)
|
||||||
|
#expect(git.executed == [["commit", "-m", "ship it"], ["push"]])
|
||||||
|
|
||||||
@Test func pushTellsTheOutcomeInAToast() async {
|
let (failing, failingGit, _) = await makeStore()
|
||||||
|
failingGit.setRun(FakeGitRun(exitCode: 1, lines: [("error: hook failed", true)]), forCommand: "commit")
|
||||||
|
failing.setCommitMessage("ship it")
|
||||||
|
await failing.commit(andPush: true)
|
||||||
|
#expect(failingGit.executed == [["commit", "-m", "ship it"]])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Push and pull
|
||||||
|
|
||||||
|
@Test func aPushWithoutUpstreamRetriesWithTheBranch() async {
|
||||||
|
let (store, git, recorder) = await makeStore(snapshot([], branch: "feature"))
|
||||||
|
git.setRun(FakeGitRun(exitCode: 128, lines: [("fatal: The current branch feature has no upstream branch.", true)]), for: ["push"])
|
||||||
|
git.setRun(FakeGitRun(lines: [(" * [new branch] feature -> feature", true)]), for: ["push", "-u", "origin", "feature"])
|
||||||
|
await store.push()
|
||||||
|
#expect(git.executed == [["push"], ["push", "-u", "origin", "feature"]])
|
||||||
|
#expect(texts(store).contains("$ git push -u origin feature"))
|
||||||
|
#expect(kinds(store).last == .success)
|
||||||
|
#expect(store.busy == nil)
|
||||||
|
#expect(recorder.toastTitles == ["Pushed to origin/feature"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aRejectedPushIsAnErrorInTheConsoleAndAToast() async {
|
||||||
let (store, git, recorder) = await makeStore()
|
let (store, git, recorder) = await makeStore()
|
||||||
git.setPushResult(PushResult(ok: false, message: "rejected"))
|
git.setRun(FakeGitRun(exitCode: 1, lines: [(" ! [rejected] main -> main (fetch first)", true),
|
||||||
let result = await store.push()
|
("hint: Updates were rejected", true)]), forCommand: "push")
|
||||||
#expect(!result.ok)
|
await store.push()
|
||||||
#expect(!store.isPushing)
|
#expect(git.executed == [["push"]])
|
||||||
#expect(git.pushes == 1)
|
#expect(kinds(store) == [.command, .error, .hint])
|
||||||
#expect(recorder.toastTitles == ["Pushing…", "Push failed"])
|
#expect(recorder.toastTitles == ["Push failed"])
|
||||||
#expect(recorder.toasts.last?.1 == "rejected")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Discard and confirmations
|
@Test func aFailureToastShowsTheErrorLineNotTheTrailingHint() async {
|
||||||
|
|
||||||
@Test func discardAsksFirstWhileConfirmDiscardIsOn() async {
|
|
||||||
let (store, _, _) = await makeStore()
|
|
||||||
let request = store.confirmation(for: .discard("src/b.php"))
|
|
||||||
#expect(request?.title == "Discard changes to src/b.php?")
|
|
||||||
#expect(request?.confirmLabel == "Discard")
|
|
||||||
#expect(request?.action == .discard("src/b.php"))
|
|
||||||
|
|
||||||
store.config.confirmDiscard = false
|
|
||||||
#expect(store.confirmation(for: .discard("src/b.php")) == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func stagingAsksOnlyWhenTheConfigSaysSo() async {
|
|
||||||
let (store, _, _) = await makeStore()
|
|
||||||
#expect(store.confirmation(for: .stage("a")) == nil)
|
|
||||||
#expect(store.confirmation(for: .unstage("a")) == nil)
|
|
||||||
store.config.confirmStage = true
|
|
||||||
store.config.confirmUnstage = true
|
|
||||||
#expect(store.confirmation(for: .stage("a"))?.title == "Stage a?")
|
|
||||||
#expect(store.confirmation(for: .unstage("a"))?.title == "Unstage a?")
|
|
||||||
#expect(store.confirmation(for: .copyReference("a")) == nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test func performRunsGitActionsAndDeclinesTheRest() async {
|
|
||||||
let (store, git, recorder) = await makeStore()
|
let (store, git, recorder) = await makeStore()
|
||||||
#expect(await store.perform(.discard("src/b.php")))
|
git.setRun(FakeGitRun(exitCode: 1, lines: [("To origin.git", true),
|
||||||
#expect(git.discarded == [["src/b.php"]])
|
(" ! [rejected] main -> main (non-fast-forward)", true),
|
||||||
#expect(recorder.toasts.last?.0 == "Discarded changes")
|
("error: failed to push some refs to 'origin.git'", true),
|
||||||
#expect(await store.perform(.stage("README.md")))
|
("hint: See the 'Note about fast-forwards' in 'git push --help' for details.", true)]),
|
||||||
#expect(git.staged == [["README.md"]])
|
forCommand: "push")
|
||||||
#expect(await !store.perform(.openDiff("README.md")))
|
await store.push()
|
||||||
#expect(await !store.perform(.copyReference("README.md")))
|
#expect(recorder.toasts.last?.1 == "! [rejected] main -> main (non-fast-forward)")
|
||||||
|
|
||||||
|
git.setRun(FakeGitRun(exitCode: 1, lines: [("something went wrong", true), ("hint: try again", true)]), forCommand: "pull")
|
||||||
|
await store.pull()
|
||||||
|
#expect(recorder.toasts.last?.0 == "Pull failed")
|
||||||
|
#expect(recorder.toasts.last?.1 == "something went wrong")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aPullToastsTheCommitsItWasBehind() async {
|
||||||
|
let behind = GitSnapshot(branch: "main", ahead: 0, canPush: false, behind: 3, upstream: "origin/main", changes: [])
|
||||||
|
let (store, git, recorder) = await makeStore(behind)
|
||||||
|
await store.pull()
|
||||||
|
#expect(git.executed == [["pull", "--no-rebase"]])
|
||||||
|
#expect(recorder.toastTitles == ["Pulled 3 commits from origin/main"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aDivergedPullMergesInsteadOfAskingHowToReconcile() async {
|
||||||
|
let diverged = GitSnapshot(branch: "main", ahead: 1, canPush: true, behind: 2, upstream: "origin/main", changes: [])
|
||||||
|
let (store, git, recorder) = await makeStore(diverged)
|
||||||
|
git.setRun(FakeGitRun(lines: [("From origin", true), ("Merge made by the 'ort' strategy.", false)]), forCommand: "pull")
|
||||||
|
await store.pull()
|
||||||
|
#expect(texts(store).first == "$ git pull --no-rebase")
|
||||||
|
#expect(texts(store).contains("Merge made by the 'ort' strategy."))
|
||||||
|
#expect(recorder.toastTitles == ["Pulled 2 commits from origin/main"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Branches
|
||||||
|
|
||||||
|
@Test func switchingIsRefusedWhileDirtyWithoutAskingGit() async {
|
||||||
|
let (store, git, recorder) = await makeStore()
|
||||||
|
#expect(await !store.switchBranch("develop", remote: false))
|
||||||
|
#expect(git.executed.isEmpty)
|
||||||
|
#expect(recorder.toastTitles == ["— Commit or discard 6 files before you switch."])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aCleanTreeSwitchesClearsExpandedRowsAndToasts() async {
|
||||||
|
let (store, git, recorder) = await makeStore(snapshot([]))
|
||||||
|
git.setBranches(GitBranchList(local: ["develop", "main"], remote: ["origin/main"]))
|
||||||
|
#expect(await store.switchBranch("develop", remote: false))
|
||||||
|
#expect(git.executed == [["switch", "develop"]])
|
||||||
|
#expect(texts(store).first == "$ git switch develop")
|
||||||
|
#expect(store.branches.local == ["develop", "main"])
|
||||||
|
#expect(store.expandedRows.isEmpty)
|
||||||
|
#expect(recorder.toastTitles == ["Switched to develop"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aRemoteBranchSwitchesByItsLocalName() async {
|
||||||
|
let (store, git, _) = await makeStore(snapshot([]))
|
||||||
|
await store.switchBranch("origin/feature/login", remote: true)
|
||||||
|
#expect(git.executed == [["switch", "feature/login"]])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theCurrentBranchIsNoSwitch() async {
|
||||||
|
let (store, git, _) = await makeStore(snapshot([]))
|
||||||
|
#expect(await !store.switchBranch("main", remote: false))
|
||||||
|
#expect(await !store.switchBranch("origin/main", remote: true))
|
||||||
|
#expect(git.executed.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Console
|
||||||
|
|
||||||
|
@Test func clearEmptiesTheLogWithoutGit() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
await store.stage(["src/b.php"])
|
||||||
|
store.consoleInput = "clear"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
#expect(store.lines.isEmpty)
|
||||||
|
#expect(git.executed == [["add", "--", "src/b.php"]])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aBareLogRunsTheShortLogAndALeadingGitIsOptional() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
store.consoleInput = "git log"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
store.consoleInput = "commit -m \"two words\""
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
#expect(git.executed == [["log", "--oneline", "--decorate", "-n", "30"], ["commit", "-m", "two words"]])
|
||||||
|
#expect(texts(store).first == "$ git log --oneline --decorate -n 30")
|
||||||
|
#expect(store.consoleInput.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func upRecallsThePreviousCommands() async {
|
||||||
|
let (store, _, _) = await makeStore()
|
||||||
|
store.recallPreviousInput()
|
||||||
|
#expect(store.consoleInput.isEmpty)
|
||||||
|
store.consoleInput = "status"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
store.consoleInput = "branch -a"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
store.recallPreviousInput()
|
||||||
|
#expect(store.consoleInput == "branch -a")
|
||||||
|
store.recallPreviousInput()
|
||||||
|
#expect(store.consoleInput == "status")
|
||||||
|
store.recallPreviousInput()
|
||||||
|
#expect(store.consoleInput == "status")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theLogKeepsTheLast400Lines() async {
|
||||||
|
let (store, git, _) = await makeStore()
|
||||||
|
git.setRun(FakeGitRun(lines: (1...450).map { ("line \($0)", false) }), forCommand: "log")
|
||||||
|
store.consoleInput = "log"
|
||||||
|
await store.submitConsoleInput()
|
||||||
|
#expect(store.lines.count == SourceControlStore.maxConsoleLines)
|
||||||
|
#expect(store.lines.last?.line.text == "line 450")
|
||||||
|
#expect(store.lines.first?.line.text == "line 51")
|
||||||
|
#expect(Set(store.lines.map(\.id)).count == store.lines.count)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Opening the view
|
||||||
|
|
||||||
|
@Test func openingTheViewFetchesOnlyWithAnOrigin() async {
|
||||||
|
let (store, git, _) = await makeStore(snapshot([]))
|
||||||
|
git.setAuthor("Jonathan van Rij <jonathan@blijnder.nl>")
|
||||||
|
await store.viewOpened()
|
||||||
|
#expect(store.author == "Jonathan van Rij <jonathan@blijnder.nl>")
|
||||||
|
#expect(git.executed.isEmpty)
|
||||||
|
|
||||||
|
git.setBranches(GitBranchList(local: ["main"], remote: ["origin/main"]))
|
||||||
|
await store.viewOpened()
|
||||||
|
#expect(git.executed == [["fetch", "origin"]])
|
||||||
|
#expect(texts(store).first == "$ git fetch origin")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func anUpstreamOnOriginIsEnoughToFetch() async {
|
||||||
|
let tracked = GitSnapshot(branch: "main", ahead: 1, canPush: true, upstream: "origin/main", changes: [])
|
||||||
|
let (store, git, _) = await makeStore(tracked)
|
||||||
|
await store.viewOpened()
|
||||||
|
#expect(git.executed == [["fetch", "origin"]])
|
||||||
|
#expect(store.syncLabel == "1 ahead of origin")
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Polling
|
// MARK: Polling
|
||||||
|
|||||||
@@ -26,26 +26,26 @@ private struct MemorySession: SessionStoring {
|
|||||||
#expect(layout.widths.explorer == 520)
|
#expect(layout.widths.explorer == 520)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func sourceControlDragsStayInsideTheirRange() {
|
@Test func explorerDragsStayInsideTheirRange() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.dragSourceControl(by: -1000)
|
layout.dragExplorer(by: -1000)
|
||||||
#expect(layout.widths.sourceControl == 160)
|
#expect(layout.widths.explorer == 160)
|
||||||
layout.dragSourceControl(by: 5000)
|
layout.dragExplorer(by: 5000)
|
||||||
#expect(layout.widths.sourceControl == 460)
|
#expect(layout.widths.explorer == 520)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() {
|
@Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
layout.dragAgent(by: -5000)
|
layout.dragAgent(by: -5000)
|
||||||
let editor = 1760 - 3 - layout.widths.sourceControl - layout.widths.explorer - layout.widths.agent
|
let editor = 1760 - 2 - layout.widths.explorer - layout.widths.agent
|
||||||
#expect(editor >= ColumnLayout.minEditorWidth)
|
#expect(editor >= ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func roomyWindowsUseTheDesignProportions() {
|
@Test func roomyWindowsUseTheDesignProportions() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
#expect(layout.widths == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
|
#expect(layout.widths == ColumnWidths(explorer: 289, agent: 480))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func focusChangesTheFluidWidthsOnlyBelow1600() {
|
@Test func focusChangesTheFluidWidthsOnlyBelow1600() {
|
||||||
@@ -75,19 +75,44 @@ private struct MemorySession: SessionStoring {
|
|||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
layout.dragExplorer(by: 0)
|
layout.dragExplorer(by: 0)
|
||||||
layout.windowResized(width: 1100)
|
layout.windowResized(width: 1100)
|
||||||
let total = layout.widths.sourceControl + layout.widths.explorer + layout.widths.agent
|
layout.windowResized(width: 900)
|
||||||
#expect(total <= 1100 - 3 - ColumnLayout.minEditorWidth)
|
let total = layout.widths.explorer + layout.widths.agent
|
||||||
|
#expect(total <= 900 - 2 - ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func hidingGitDropsItsFocus() {
|
@Test func hidingTheExplorerDropsItsFocus() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.focus(.sourceControl)
|
layout.focus(.explorer)
|
||||||
layout.togglePane(.sourceControl)
|
layout.togglePane(.explorer)
|
||||||
#expect(layout.activePanel == nil)
|
#expect(layout.activePanel == nil)
|
||||||
layout.focus(.sourceControl)
|
layout.focus(.explorer)
|
||||||
#expect(layout.activePanel == nil)
|
#expect(layout.activePanel == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func theGitViewOpensClosesAndToggles() {
|
||||||
|
let layout = LayoutStore(session: MemorySession())
|
||||||
|
#expect(!layout.isGitViewOpen)
|
||||||
|
layout.openGitView()
|
||||||
|
#expect(layout.isGitViewOpen)
|
||||||
|
layout.closeGitView()
|
||||||
|
#expect(!layout.isGitViewOpen)
|
||||||
|
layout.toggleGitView()
|
||||||
|
#expect(layout.isGitViewOpen)
|
||||||
|
layout.toggleGitView()
|
||||||
|
#expect(!layout.isGitViewOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theGitViewIsNeitherSavedNorKeptAcrossAProjectSwitch() {
|
||||||
|
let store = FakeLayouts()
|
||||||
|
let layout = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
|
layout.restore(root: "/p")
|
||||||
|
layout.openGitView()
|
||||||
|
#expect(store.saved["/p"] == nil)
|
||||||
|
layout.restore(root: "/q")
|
||||||
|
#expect(!layout.isGitViewOpen)
|
||||||
|
#expect(layout.visibility == .all)
|
||||||
|
}
|
||||||
|
|
||||||
@Test func aProjectsColumnsSurviveARestart() {
|
@Test func aProjectsColumnsSurviveARestart() {
|
||||||
let store = FakeLayouts()
|
let store = FakeLayouts()
|
||||||
let first = LayoutStore(session: MemorySession(), persistence: store)
|
let first = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
@@ -95,13 +120,13 @@ private struct MemorySession: SessionStoring {
|
|||||||
first.windowResized(width: 1760)
|
first.windowResized(width: 1760)
|
||||||
first.dragExplorer(by: 40)
|
first.dragExplorer(by: 40)
|
||||||
first.endDrag()
|
first.endDrag()
|
||||||
first.togglePane(.sourceControl)
|
first.togglePane(.terminal)
|
||||||
|
|
||||||
let second = LayoutStore(session: MemorySession(), persistence: store)
|
let second = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
second.windowResized(width: 1760)
|
second.windowResized(width: 1760)
|
||||||
second.restore(root: "/p")
|
second.restore(root: "/p")
|
||||||
#expect(!second.fluid)
|
#expect(!second.fluid)
|
||||||
#expect(!second.isVisible(.sourceControl))
|
#expect(!second.isVisible(.terminal))
|
||||||
#expect(second.widths.explorer == first.widths.explorer)
|
#expect(second.widths.explorer == first.widths.explorer)
|
||||||
#expect(second.widths.agent == first.widths.agent)
|
#expect(second.widths.agent == first.widths.agent)
|
||||||
}
|
}
|
||||||
@@ -110,11 +135,11 @@ private struct MemorySession: SessionStoring {
|
|||||||
let store = FakeLayouts()
|
let store = FakeLayouts()
|
||||||
let layout = LayoutStore(session: MemorySession(), persistence: store)
|
let layout = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
layout.restore(root: "/a")
|
layout.restore(root: "/a")
|
||||||
layout.togglePane(.sourceControl)
|
layout.togglePane(.explorer)
|
||||||
layout.restore(root: "/b")
|
layout.restore(root: "/b")
|
||||||
#expect(layout.isVisible(.sourceControl))
|
#expect(layout.isVisible(.explorer))
|
||||||
layout.restore(root: "/a")
|
layout.restore(root: "/a")
|
||||||
#expect(!layout.isVisible(.sourceControl))
|
#expect(!layout.isVisible(.explorer))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func dragsSaveOnlyWhenTheyEnd() {
|
@Test func dragsSaveOnlyWhenTheyEnd() {
|
||||||
@@ -140,22 +165,22 @@ private struct MemorySession: SessionStoring {
|
|||||||
@Test func aWindowXMapsToTheColumnUnderIt() {
|
@Test func aWindowXMapsToTheColumnUnderIt() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
#expect(layout.panel(atX: 10) == .sourceControl)
|
#expect(layout.panel(atX: 10) == .explorer)
|
||||||
#expect(layout.panel(atX: 300) == .explorer)
|
|
||||||
#expect(layout.panel(atX: 900) == .editor)
|
#expect(layout.panel(atX: 900) == .editor)
|
||||||
#expect(layout.panel(atX: 1700) == .terminal)
|
#expect(layout.panel(atX: 1700) == .terminal)
|
||||||
#expect(layout.panel(atX: 236, splitterMargin: 4) == nil)
|
#expect(layout.panel(atX: 289, splitterMargin: 4) == nil)
|
||||||
layout.togglePane(.sourceControl)
|
layout.togglePane(.explorer)
|
||||||
#expect(layout.panel(atX: 10) == .explorer)
|
#expect(layout.panel(atX: 10) == .editor)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenGitColumn() {
|
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenColumn() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
#expect(layout.neighbour(of: nil, step: 1) == .terminal)
|
#expect(layout.neighbour(of: nil, step: 1) == .terminal)
|
||||||
#expect(layout.neighbour(of: .terminal, step: 1) == .terminal)
|
#expect(layout.neighbour(of: .terminal, step: 1) == .terminal)
|
||||||
#expect(layout.neighbour(of: .explorer, step: -1) == .sourceControl)
|
|
||||||
layout.togglePane(.sourceControl)
|
|
||||||
#expect(layout.neighbour(of: .explorer, step: -1) == .explorer)
|
#expect(layout.neighbour(of: .explorer, step: -1) == .explorer)
|
||||||
|
#expect(layout.neighbour(of: .editor, step: -1) == .explorer)
|
||||||
|
layout.togglePane(.explorer)
|
||||||
|
#expect(layout.neighbour(of: .editor, step: -1) == .editor)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func everyPaneStartsShownAndTogglesOnItsOwn() {
|
@Test func everyPaneStartsShownAndTogglesOnItsOwn() {
|
||||||
@@ -163,8 +188,8 @@ private struct MemorySession: SessionStoring {
|
|||||||
#expect(layout.visibility == .all)
|
#expect(layout.visibility == .all)
|
||||||
layout.togglePane(.explorer)
|
layout.togglePane(.explorer)
|
||||||
layout.togglePane(.terminal)
|
layout.togglePane(.terminal)
|
||||||
#expect(layout.visibility == ColumnVisibility(sourceControl: true, explorer: false, editor: true, agent: false))
|
#expect(layout.visibility == ColumnVisibility(explorer: false, editor: true, agent: false))
|
||||||
#expect(layout.columns == [.sourceControl, .editor])
|
#expect(layout.columns == [.editor])
|
||||||
layout.togglePane(.terminal)
|
layout.togglePane(.terminal)
|
||||||
#expect(layout.isVisible(.terminal))
|
#expect(layout.isVisible(.terminal))
|
||||||
}
|
}
|
||||||
@@ -181,7 +206,7 @@ private struct MemorySession: SessionStoring {
|
|||||||
#expect(layout.activePanel == .editor)
|
#expect(layout.activePanel == .editor)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func allFourPaneFlagsSurviveARestart() {
|
@Test func allThreePaneFlagsSurviveARestart() {
|
||||||
let store = FakeLayouts()
|
let store = FakeLayouts()
|
||||||
let first = LayoutStore(session: MemorySession(), persistence: store)
|
let first = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
first.restore(root: "/p")
|
first.restore(root: "/p")
|
||||||
@@ -191,20 +216,43 @@ private struct MemorySession: SessionStoring {
|
|||||||
|
|
||||||
let second = LayoutStore(session: MemorySession(), persistence: store)
|
let second = LayoutStore(session: MemorySession(), persistence: store)
|
||||||
second.restore(root: "/p")
|
second.restore(root: "/p")
|
||||||
#expect(second.visibility == ColumnVisibility(sourceControl: true, explorer: false, editor: false, agent: false))
|
#expect(second.visibility == ColumnVisibility(explorer: false, editor: false, agent: false))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func anOlderSnapshotWithOnlyTheGitFlagStillLoads() throws {
|
@Test func anOlderSnapshotWithOnlyTheGitFlagStillLoads() throws {
|
||||||
let json = #"{"sourceControlWidth":240,"explorerWidth":300,"agentWidth":500,"fluid":false,"gitVisible":false}"#
|
let json = #"{"sourceControlWidth":240,"explorerWidth":300,"agentWidth":500,"fluid":false,"gitVisible":false}"#
|
||||||
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
|
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
|
||||||
#expect(snapshot.visibility == ColumnVisibility(sourceControl: false, explorer: true, editor: true, agent: true))
|
#expect(snapshot.visibility == .all)
|
||||||
#expect(snapshot.explorerWidth == 300)
|
#expect(snapshot.explorerWidth == 300)
|
||||||
|
#expect(snapshot.agentWidth == 500)
|
||||||
#expect(!snapshot.fluid)
|
#expect(!snapshot.fluid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func aSnapshotFromTheGitColumnDaysKeepsItsPaneFlags() throws {
|
||||||
|
let json = #"{"sourceControlWidth":240,"explorerWidth":300,"agentWidth":500,"fluid":true,"gitVisible":true,"#
|
||||||
|
+ #""explorerVisible":false,"fileVisible":true,"claudeVisible":false}"#
|
||||||
|
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
|
||||||
|
#expect(snapshot.visibility == ColumnVisibility(explorer: false, editor: true, agent: false))
|
||||||
|
#expect(snapshot.fluid)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aSnapshotWithoutTheGitKeysLoads() throws {
|
||||||
|
let json = #"{"explorerWidth":300,"agentWidth":500,"fluid":false,"explorerVisible":true,"fileVisible":false,"claudeVisible":true}"#
|
||||||
|
let snapshot = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: Data(json.utf8))
|
||||||
|
#expect(snapshot.visibility == ColumnVisibility(explorer: true, editor: false, agent: true))
|
||||||
|
#expect(snapshot.explorerWidth == 300)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func aSavedSnapshotNoLongerWritesTheGitKeys() throws {
|
||||||
|
let data = try JSONEncoder().encode(ColumnLayoutSnapshot(explorerWidth: 288, agentWidth: 480, fluid: true))
|
||||||
|
let keys = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]).keys
|
||||||
|
#expect(!keys.contains("sourceControlWidth"))
|
||||||
|
#expect(!keys.contains("gitVisible"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test func aSnapshotRoundTripsItsPaneFlags() throws {
|
@Test func aSnapshotRoundTripsItsPaneFlags() throws {
|
||||||
let visibility = ColumnVisibility(sourceControl: true, explorer: false, editor: true, agent: false)
|
let visibility = ColumnVisibility(explorer: false, editor: true, agent: false)
|
||||||
let snapshot = ColumnLayoutSnapshot(sourceControlWidth: 236, explorerWidth: 288, agentWidth: 480, fluid: true, visibility: visibility)
|
let snapshot = ColumnLayoutSnapshot(explorerWidth: 288, agentWidth: 480, fluid: true, visibility: visibility)
|
||||||
let decoded = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: JSONEncoder().encode(snapshot))
|
let decoded = try JSONDecoder().decode(ColumnLayoutSnapshot.self, from: JSONEncoder().encode(snapshot))
|
||||||
#expect(decoded == snapshot)
|
#expect(decoded == snapshot)
|
||||||
#expect(decoded.visibility == visibility)
|
#expect(decoded.visibility == visibility)
|
||||||
@@ -214,9 +262,9 @@ private struct MemorySession: SessionStoring {
|
|||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
layout.togglePane(.editor)
|
layout.togglePane(.editor)
|
||||||
#expect(layout.columns == [.sourceControl, .explorer, .terminal])
|
#expect(layout.columns == [.explorer, .terminal])
|
||||||
#expect(layout.span(of: .editor) == nil)
|
#expect(layout.span(of: .editor) == nil)
|
||||||
let agentStart = layout.widths.sourceControl + 1 + layout.widths.explorer + 1
|
let agentStart = layout.widths.explorer + 1
|
||||||
#expect(layout.span(of: .terminal) == agentStart...1760)
|
#expect(layout.span(of: .terminal) == agentStart...1760)
|
||||||
#expect(layout.panel(atX: 1000) == .terminal)
|
#expect(layout.panel(atX: 1000) == .terminal)
|
||||||
}
|
}
|
||||||
@@ -225,7 +273,6 @@ private struct MemorySession: SessionStoring {
|
|||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
layout.togglePane(.terminal)
|
layout.togglePane(.terminal)
|
||||||
layout.togglePane(.sourceControl)
|
|
||||||
#expect(layout.span(of: .explorer) == 0...layout.widths.explorer)
|
#expect(layout.span(of: .explorer) == 0...layout.widths.explorer)
|
||||||
#expect(layout.span(of: .editor) == (layout.widths.explorer + 1)...1760)
|
#expect(layout.span(of: .editor) == (layout.widths.explorer + 1)...1760)
|
||||||
#expect(layout.span(of: .terminal) == nil)
|
#expect(layout.span(of: .terminal) == nil)
|
||||||
@@ -244,9 +291,8 @@ private struct MemorySession: SessionStoring {
|
|||||||
@Test func neighboursSkipEveryHiddenPane() {
|
@Test func neighboursSkipEveryHiddenPane() {
|
||||||
let layout = LayoutStore(session: MemorySession())
|
let layout = LayoutStore(session: MemorySession())
|
||||||
layout.togglePane(.editor)
|
layout.togglePane(.editor)
|
||||||
layout.togglePane(.explorer)
|
#expect(layout.neighbour(of: .explorer, step: 1) == .terminal)
|
||||||
#expect(layout.neighbour(of: .sourceControl, step: 1) == .terminal)
|
#expect(layout.neighbour(of: .terminal, step: -1) == .explorer)
|
||||||
#expect(layout.neighbour(of: .terminal, step: -1) == .sourceControl)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func theAgentMayGrowIntoTheRoomAHiddenExplorerLeaves() {
|
@Test func theAgentMayGrowIntoTheRoomAHiddenExplorerLeaves() {
|
||||||
@@ -254,6 +300,6 @@ private struct MemorySession: SessionStoring {
|
|||||||
layout.windowResized(width: 1760)
|
layout.windowResized(width: 1760)
|
||||||
layout.togglePane(.explorer)
|
layout.togglePane(.explorer)
|
||||||
layout.dragAgent(by: -5000)
|
layout.dragAgent(by: -5000)
|
||||||
#expect(layout.widths.agent == 1760 - 2 - layout.widths.sourceControl - ColumnLayout.minEditorWidth)
|
#expect(layout.widths.agent == 1760 - 1 - ColumnLayout.minEditorWidth)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ import Testing
|
|||||||
await harness.model.settle()
|
await harness.model.settle()
|
||||||
let oldEditor = harness.model.editor
|
let oldEditor = harness.model.editor
|
||||||
let gate = harness.files.holdNextRead("a.php")
|
let gate = harness.files.holdNextRead("a.php")
|
||||||
harness.model.perform(.context(.discard("a.php")))
|
harness.model.perform(.context(.gitDiscard(["a.php"])))
|
||||||
harness.model.perform(.confirmPending)
|
harness.model.perform(.confirmPending)
|
||||||
#expect(await eventually { gate.isWaiting })
|
#expect(await eventually { gate.isWaiting })
|
||||||
harness.model.perform(.openRecentProject("/fake/other"))
|
harness.model.perform(.openRecentProject("/fake/other"))
|
||||||
|
|||||||
@@ -61,13 +61,13 @@ import Testing
|
|||||||
await harness.start()
|
await harness.start()
|
||||||
var changed = HelderConfig.defaults
|
var changed = HelderConfig.defaults
|
||||||
changed.ai.command = "other-agent"
|
changed.ai.command = "other-agent"
|
||||||
changed.git.confirmStage = true
|
changed.git.confirmDiscard = false
|
||||||
changed.editor.tabSize = 8
|
changed.editor.tabSize = 8
|
||||||
harness.config.set(changed)
|
harness.config.set(changed)
|
||||||
await harness.model.handle(.config)
|
await harness.model.handle(.config)
|
||||||
#expect(harness.model.config.ai.command == "other-agent")
|
#expect(harness.model.config.ai.command == "other-agent")
|
||||||
#expect(harness.model.terminal.config.ai.command == "other-agent")
|
#expect(harness.model.terminal.config.ai.command == "other-agent")
|
||||||
#expect(harness.model.sourceControl?.config.confirmStage == true)
|
#expect(harness.model.sourceControl?.config.confirmDiscard == false)
|
||||||
#expect(harness.model.editor?.editorConfig.tabSize == 8)
|
#expect(harness.model.editor?.editorConfig.tabSize == 8)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,11 +204,11 @@ import Testing
|
|||||||
#expect(harness.files.treeLoads == 2)
|
#expect(harness.files.treeLoads == 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func focusingSourceControlRefreshesGitOnce() async {
|
@Test func openingTheGitViewRefreshesGitOnce() async {
|
||||||
let harness = WorkspaceHarness()
|
let harness = WorkspaceHarness()
|
||||||
await harness.start()
|
await harness.start()
|
||||||
harness.model.pointerFocused(.sourceControl)
|
harness.model.perform(.toggleGit)
|
||||||
harness.model.pointerFocused(.sourceControl)
|
harness.model.perform(.focusCommitMessage)
|
||||||
await harness.model.settle()
|
await harness.model.settle()
|
||||||
#expect(harness.git.loads == 2)
|
#expect(harness.git.loads == 2)
|
||||||
}
|
}
|
||||||
@@ -277,36 +277,29 @@ import Testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test func discardAsksUnderTheConfigThenReloadsTheFile() async {
|
@Test func discardAsksUnderTheConfigThenReloadsTheFile() async {
|
||||||
let harness = WorkspaceHarness(contents: ["a.php": "edited"])
|
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "edited"])
|
||||||
await harness.start()
|
await harness.start()
|
||||||
harness.model.open("a.php")
|
harness.model.open("a.php")
|
||||||
await harness.model.settle()
|
await harness.model.settle()
|
||||||
await harness.perform(.context(.discard("a.php")))
|
await harness.perform(.context(.gitDiscard(["a.php"])))
|
||||||
guard case let .confirm(request) = harness.model.overlay.current else {
|
guard case let .confirm(request) = harness.model.overlay.current else {
|
||||||
Issue.record("expected a confirm overlay")
|
Issue.record("expected a confirm overlay")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
#expect(request.confirmLabel == "Discard")
|
#expect(request.confirmLabel == "Discard")
|
||||||
|
#expect(harness.git.executed.isEmpty)
|
||||||
harness.files.set("a.php", "committed")
|
harness.files.set("a.php", "committed")
|
||||||
await harness.perform(.confirmPending)
|
await harness.perform(.confirmPending)
|
||||||
#expect(harness.git.discarded == [["a.php"]])
|
#expect(harness.git.executed == [["restore", "--", "a.php"]])
|
||||||
#expect(harness.model.editor?.text(for: "a.php") == "committed")
|
#expect(harness.model.editor?.text(for: "a.php") == "committed")
|
||||||
#expect(harness.toastTitles == ["Discarded changes"])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func stagingRunsStraightAwayUnlessTheConfigAsks() async {
|
@Test func stagingRunsGitStraightAway() async {
|
||||||
let harness = WorkspaceHarness()
|
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .modified, false)]))
|
||||||
await harness.start()
|
await harness.start()
|
||||||
await harness.perform(.context(.stage("a.php")))
|
await harness.perform(.stage(["a.php"]))
|
||||||
#expect(harness.git.staged == [["a.php"]])
|
#expect(harness.git.executed == [["add", "--", "a.php"]])
|
||||||
|
#expect(harness.model.overlay.current == .none)
|
||||||
var config = HelderConfig.defaults
|
|
||||||
config.git.confirmStage = true
|
|
||||||
let asking = WorkspaceHarness(config: config)
|
|
||||||
await asking.start()
|
|
||||||
await asking.perform(.context(.stage("a.php")))
|
|
||||||
#expect(asking.git.staged.isEmpty)
|
|
||||||
#expect(asking.model.overlay.current != .none)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func revealInFinderResolvesAgainstTheProject() async {
|
@Test func revealInFinderResolvesAgainstTheProject() async {
|
||||||
@@ -354,17 +347,32 @@ import Testing
|
|||||||
await harness.start()
|
await harness.start()
|
||||||
harness.model.sourceControl?.setCommitMessage("fix it")
|
harness.model.sourceControl?.setCommitMessage("fix it")
|
||||||
await harness.perform(.commit)
|
await harness.perform(.commit)
|
||||||
#expect(harness.git.commits == ["fix it"])
|
#expect(harness.git.executed == [["commit", "-m", "fix it"]])
|
||||||
await harness.perform(.push)
|
await harness.perform(.push)
|
||||||
#expect(harness.git.pushes == 1)
|
#expect(harness.git.executed.last == ["push"])
|
||||||
#expect(harness.toastTitles == ["Committed 1 file", "Pushing…", "Pushed"])
|
#expect(harness.toastTitles == ["Committed 1 file", "Pushed to origin/main"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commitWithoutAMessageDoesNothing() async {
|
@Test func commitWithoutAMessageStillAsksGitThenFocusesTheMessage() async {
|
||||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||||
await harness.start()
|
await harness.start()
|
||||||
|
harness.git.setRun(FakeGitRun(exitCode: 1, lines: [("Aborting commit due to empty commit message.", true)]), forCommand: "commit")
|
||||||
await harness.perform(.commit)
|
await harness.perform(.commit)
|
||||||
#expect(harness.git.commits.isEmpty)
|
#expect(harness.git.executed == [["commit", "-m", ""]])
|
||||||
|
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||||
|
#expect(harness.toastTitles == ["Commit failed"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func theRowMenuOpensTheFileAndClosesTheGitView() async {
|
||||||
|
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "<?php"])
|
||||||
|
await harness.start()
|
||||||
|
harness.model.perform(.toggleGit)
|
||||||
|
await harness.model.settle()
|
||||||
|
harness.model.perform(.showContextMenu(.gitRow(path: "a.php", isDeleted: false), anchor: CGPoint(x: 10, y: 20)))
|
||||||
|
await harness.perform(.context(.openFile("a.php")))
|
||||||
|
#expect(!harness.model.layout.isGitViewOpen)
|
||||||
|
#expect(harness.model.overlay.current == .none)
|
||||||
|
#expect(harness.model.editor?.activePath == "a.php")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func thePassOnPromptInsertsIntoTheAgent() async {
|
@Test func thePassOnPromptInsertsIntoTheAgent() async {
|
||||||
@@ -466,14 +474,49 @@ import Testing
|
|||||||
#expect(harness.model.focusRequest?.target == .panel(.editor))
|
#expect(harness.model.focusRequest?.target == .panel(.editor))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commandCShowsAHiddenGitColumnAndFocusesTheCommitBox() async {
|
@Test func commandCOpensTheGitViewOnItsMessageField() async {
|
||||||
|
let harness = WorkspaceHarness()
|
||||||
|
await harness.start()
|
||||||
|
harness.model.perform(.focusCommitMessage)
|
||||||
|
#expect(harness.model.layout.isGitViewOpen)
|
||||||
|
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||||
|
harness.model.focusTaken(.commitMessage)
|
||||||
|
harness.model.perform(.focusCommitMessage)
|
||||||
|
#expect(harness.model.layout.isGitViewOpen)
|
||||||
|
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func commandGTogglesTheGitViewAndClosingGivesTheKeyboardBack() async {
|
||||||
|
let harness = WorkspaceHarness()
|
||||||
|
await harness.start()
|
||||||
|
harness.model.perform(.focus(.terminal))
|
||||||
|
harness.model.perform(.toggleGit)
|
||||||
|
#expect(harness.model.layout.isGitViewOpen)
|
||||||
|
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||||
|
#expect(harness.model.layout.visibility == .all)
|
||||||
|
harness.model.perform(.toggleGit)
|
||||||
|
#expect(!harness.model.layout.isGitViewOpen)
|
||||||
|
#expect(harness.model.focusRequest?.target == .panel(.terminal))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func closingTheGitViewWithNoActiveColumnDropsTheFieldRequest() async {
|
||||||
let harness = WorkspaceHarness()
|
let harness = WorkspaceHarness()
|
||||||
await harness.start()
|
await harness.start()
|
||||||
harness.model.perform(.toggleGit)
|
harness.model.perform(.toggleGit)
|
||||||
#expect(!harness.model.layout.isVisible(.sourceControl))
|
harness.model.perform(.closeGitView)
|
||||||
harness.model.perform(.focusCommitMessage)
|
#expect(!harness.model.layout.isGitViewOpen)
|
||||||
#expect(harness.model.layout.isVisible(.sourceControl))
|
#expect(harness.model.focusRequest == nil)
|
||||||
#expect(harness.model.focusRequest?.target == .commitMessage)
|
harness.model.perform(.closeGitView)
|
||||||
|
#expect(!harness.model.layout.isGitViewOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func paneTogglesLeaveTheGitViewAlone() async {
|
||||||
|
let harness = WorkspaceHarness()
|
||||||
|
await harness.start()
|
||||||
|
harness.model.perform(.toggleGit)
|
||||||
|
harness.model.perform(.togglePane(.explorer))
|
||||||
|
#expect(!harness.model.layout.isVisible(.explorer))
|
||||||
|
#expect(harness.model.layout.isGitViewOpen)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func aPaneToggleHidesItsColumnAndAHiddenColumnTakesNoFocus() async {
|
@Test func aPaneToggleHidesItsColumnAndAHiddenColumnTakesNoFocus() async {
|
||||||
@@ -491,18 +534,19 @@ import Testing
|
|||||||
#expect(harness.model.layout.isVisible(.terminal))
|
#expect(harness.model.layout.isVisible(.terminal))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func rowCursorKeysDriveTheFocusedList() async {
|
@Test func rowCursorKeysDriveOnlyTheExplorer() async {
|
||||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .added, true)]),
|
let harness = WorkspaceHarness(contents: ["README.md": "# hi"])
|
||||||
contents: ["a.php": "", "b.php": ""])
|
|
||||||
await harness.start()
|
await harness.start()
|
||||||
harness.model.perform(.focus(.sourceControl))
|
let before = harness.model.explorer?.selectedPath
|
||||||
|
harness.model.perform(.focus(.editor))
|
||||||
harness.model.perform(.moveRowCursor(1))
|
harness.model.perform(.moveRowCursor(1))
|
||||||
#expect(harness.model.sourceControl?.selectedRow?.path == "b.php")
|
#expect(harness.model.explorer?.selectedPath == before)
|
||||||
harness.model.perform(.moveRowCursor(1))
|
harness.model.perform(.focus(.explorer))
|
||||||
#expect(harness.model.sourceControl?.selectedRow?.path == "a.php")
|
harness.model.perform(.moveRowCursor(10))
|
||||||
|
harness.model.perform(.moveRowCursor(10))
|
||||||
|
#expect(harness.model.explorer?.selectedPath == "README.md")
|
||||||
await harness.perform(.openSelectedRow)
|
await harness.perform(.openSelectedRow)
|
||||||
#expect(harness.model.editor?.activePath == "a.php")
|
#expect(harness.model.editor?.activePath == "README.md")
|
||||||
#expect(harness.model.editor?.sides["a.php"] == .unstaged)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func commandRightOnARowOpensItsMenuBesideTheColumn() async {
|
@Test func commandRightOnARowOpensItsMenuBesideTheColumn() async {
|
||||||
|
|||||||
@@ -2,19 +2,38 @@ import Foundation
|
|||||||
import HelderCore
|
import HelderCore
|
||||||
import HelderServices
|
import HelderServices
|
||||||
|
|
||||||
|
/// A scripted `execute` run: the lines it streams (`isError` for stderr) and its exit code.
|
||||||
|
struct FakeGitRun {
|
||||||
|
var exitCode: Int32 = 0
|
||||||
|
var lines: [(text: String, isError: Bool)] = []
|
||||||
|
/// How long the run takes after its lines.
|
||||||
|
var delay: Duration = .zero
|
||||||
|
|
||||||
|
static let success = FakeGitRun()
|
||||||
|
|
||||||
|
var result: GitCommandResult {
|
||||||
|
func joined(_ isError: Bool) -> String {
|
||||||
|
lines.filter { $0.isError == isError }.map { $0.text + "\n" }.joined()
|
||||||
|
}
|
||||||
|
return GitCommandResult(exitCode: exitCode, stdout: joined(false), stderr: joined(true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one.
|
/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one.
|
||||||
|
///
|
||||||
|
/// `execute` answers with the run scripted for the full argument list, else for its first argument, else success.
|
||||||
final class FakeGit: GitServicing, @unchecked Sendable {
|
final class FakeGit: GitServicing, @unchecked Sendable {
|
||||||
private struct State {
|
private struct State {
|
||||||
var loads = 0
|
var loads = 0
|
||||||
var staged: [[String]] = []
|
|
||||||
var unstaged: [[String]] = []
|
|
||||||
var commits: [String] = []
|
|
||||||
var discarded: [[String]] = []
|
|
||||||
var pushes = 0
|
|
||||||
var queued: [(GitSnapshot?, Duration)] = []
|
var queued: [(GitSnapshot?, Duration)] = []
|
||||||
var current: GitSnapshot?
|
var current: GitSnapshot?
|
||||||
var failCommit = false
|
var executed: [[String]] = []
|
||||||
var pushResult = PushResult(ok: true, message: "main -> main")
|
var events: [String] = []
|
||||||
|
var loadError: Error?
|
||||||
|
var runsByArguments: [[String]: FakeGitRun] = [:]
|
||||||
|
var runsByCommand: [String: FakeGitRun] = [:]
|
||||||
|
var branches = GitBranchList.empty
|
||||||
|
var author: String?
|
||||||
}
|
}
|
||||||
|
|
||||||
private let state: Locked<State>
|
private let state: Locked<State>
|
||||||
@@ -24,18 +43,25 @@ final class FakeGit: GitServicing, @unchecked Sendable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var loads: Int { state.current.loads }
|
var loads: Int { state.current.loads }
|
||||||
var staged: [[String]] { state.current.staged }
|
/// Every `execute` argument list, in call order.
|
||||||
var unstaged: [[String]] { state.current.unstaged }
|
var executed: [[String]] { state.current.executed }
|
||||||
var commits: [String] { state.current.commits }
|
/// `start <args>` and `end <args>` per `execute`, in the order they happened.
|
||||||
var discarded: [[String]] { state.current.discarded }
|
var events: [String] { state.current.events }
|
||||||
var pushes: Int { state.current.pushes }
|
|
||||||
|
|
||||||
func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } }
|
func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } }
|
||||||
func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } }
|
func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } }
|
||||||
func setFailCommit(_ value: Bool) { state.mutate { $0.failCommit = value } }
|
func setRun(_ run: FakeGitRun, for arguments: [String]) { state.mutate { $0.runsByArguments[arguments] = run } }
|
||||||
func setPushResult(_ value: PushResult) { state.mutate { $0.pushResult = value } }
|
func setRun(_ run: FakeGitRun, forCommand command: String) { state.mutate { $0.runsByCommand[command] = run } }
|
||||||
|
func setBranches(_ value: GitBranchList) { state.mutate { $0.branches = value } }
|
||||||
|
func setAuthor(_ value: String?) { state.mutate { $0.author = value } }
|
||||||
|
/// Makes every `load` throw this error, or read normally again with nil.
|
||||||
|
func setLoadError(_ error: Error?) { state.mutate { $0.loadError = error } }
|
||||||
|
|
||||||
func load() async throws -> GitSnapshot? {
|
func load() async throws -> GitSnapshot? {
|
||||||
|
if let error = state.current.loadError {
|
||||||
|
state.mutate { $0.loads += 1 }
|
||||||
|
throw error
|
||||||
|
}
|
||||||
let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in
|
let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in
|
||||||
state.loads += 1
|
state.loads += 1
|
||||||
return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst()
|
return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst()
|
||||||
@@ -44,24 +70,22 @@ final class FakeGit: GitServicing, @unchecked Sendable {
|
|||||||
return snapshot
|
return snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
func stage(_ paths: [String]) async throws { state.mutate { $0.staged.append(paths) } }
|
func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
|
||||||
func unstage(_ paths: [String]) async throws { state.mutate { $0.unstaged.append(paths) } }
|
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult {
|
||||||
|
let name = arguments.joined(separator: " ")
|
||||||
func commit(message: String) async throws {
|
let run = state.mutate { state in
|
||||||
try state.mutate { state in
|
state.executed.append(arguments)
|
||||||
if state.failCommit { throw FakeError() }
|
state.events.append("start \(name)")
|
||||||
state.commits.append(message)
|
return state.runsByArguments[arguments] ?? arguments.first.flatMap { state.runsByCommand[$0] } ?? .success
|
||||||
}
|
}
|
||||||
|
for line in run.lines { onLine(line.text, line.isError) }
|
||||||
|
if run.delay > .zero { try? await Task.sleep(for: run.delay) }
|
||||||
|
state.mutate { $0.events.append("end \(name)") }
|
||||||
|
return run.result
|
||||||
}
|
}
|
||||||
|
|
||||||
func push() async -> PushResult {
|
func branches() async -> GitBranchList { state.current.branches }
|
||||||
state.mutate { state in
|
func author() async -> String? { state.current.author }
|
||||||
state.pushes += 1
|
|
||||||
return state.pushResult
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func discard(_ paths: [String]) async throws { state.mutate { $0.discarded.append(paths) } }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A snapshot with one change per row: (path, status, staged).
|
/// A snapshot with one change per row: (path, status, staged).
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ enum TestDerivation {
|
|||||||
guard let snapshot else { return GitWorkingState() }
|
guard let snapshot else { return GitWorkingState() }
|
||||||
let changes = snapshot.changes.map {
|
let changes = snapshot.changes.map {
|
||||||
Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1,
|
Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1,
|
||||||
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged)
|
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged, originalPath: $0.originalPath)
|
||||||
}
|
}
|
||||||
return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
|
return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
|
||||||
changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
|
behind: snapshot.behind, upstream: snapshot.upstream, changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
|
||||||
isRepository: true)
|
isRepository: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
@@ -26,10 +26,12 @@ Helder (executable) → HelderUI → HelderServices → HelderCore
|
|||||||
- **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the session and ends the terminals.
|
- **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the session and ends the terminals.
|
||||||
- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the session, stops the watcher and polling, and ends both terminals.
|
- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the session, stops the watcher and polling, and ends both terminals.
|
||||||
- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live.
|
- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live.
|
||||||
|
- **Git view.** ⌘G toggles `LayoutStore.isGitViewOpen` (never persisted, reset on a project switch). `WorkspaceView` draws `GitView` as an overlay over title bar, columns and status bar, under `OverlayHost`, so every overlay and toast sits above it; the columns stay mounted. `KeyContext.gitViewOpen` sends keys to `KeyRouter.gitViewKey` (column keys rest, ⌘↵ commits) and makes a bare Esc `.closeGitView` once no overlay is open; `inGitConsole` (first responder is a `GitConsoleFieldEditor`) keeps ⌘↵ from committing out of the console. `openGitView()` / `closeGitView()` in `+Commands` move the focus request (commit message in, previous `activePanel` out). Design source: `docs/design_handoff_helder_app_v2/README.md`.
|
||||||
|
- **Git commands.** Every git write and every typed console command goes through `SourceControlStore.run`, which chains onto `commandTail` so two commands never race for `.git/index.lock`, logs `$ git …` and streams lines via `GitServicing.execute` → `ProcessRunning.stream` into the console (`GitOutputClassifier`, one per run). `execute` never throws and switches off prompts, editors and pagers (`GIT_TERMINAL_PROMPT=0`, `GIT_EDITOR=true`, `GIT_PAGER=cat`), so a run can never wait on input. Typed commands run without literal pathspecs (globs work); buttons always pass explicit paths, never `add -A`. Push/pull/fetch and typed commands get `remoteTimeout` (120 s). Commit always runs git, even when `canCommitNow` is false, so git's refusal is the error the user sees. Branch switching is refused in the store while `isDirty`, without asking git. The status read (`load`) stays on `ProcessRunning.run`.
|
||||||
- **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`.
|
- **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`.
|
||||||
- **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject <path>`, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window.
|
- **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject <path>`, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window.
|
||||||
- **Editor.** `EditorStore` shows exactly one file (`activePath`); opening another replaces it, and there are no tabs. Every `open` (Git column, Explorer, search, recent files, links) re-reads the file from disk; the disk wins. Unsaved edits do not outlive switching: opening any file, the same one included, while the open file is dirty asks Save / Don't Save / Cancel (with `editor.autoSave` on it saves silently). Cancel moves nothing, Explorer selection included; a failed save keeps the dirty file open. `dirtyPaths` is therefore at most the open file plus a vanished-file buffer, and the close/quit flow asks about each. ⌘W closes the open file (asking first when dirty) and shows the empty state. `EditorBar` above the code shows the type badge, the path, the unsaved dot and `+N`/`−N`, then a Preview button for Markdown and a Diff button for a changed file (`EditorPresentation.barButtons`). A changed file shows Actual (the live buffer with changed lines marked), an unchanged one plain code; ⌘M only flips Markdown between code and preview. The session stores the open file and its mode and side; a stored `openTabs` list and unknown modes are ignored.
|
- **Editor.** `EditorStore` shows exactly one file (`activePath`); opening another replaces it, and there are no tabs. Every `open` (Git view, Explorer, search, recent files, links) re-reads the file from disk; the disk wins. Unsaved edits do not outlive switching: opening any file, the same one included, while the open file is dirty asks Save / Don't Save / Cancel (with `editor.autoSave` on it saves silently). Cancel moves nothing, Explorer selection included; a failed save keeps the dirty file open. `dirtyPaths` is therefore at most the open file plus a vanished-file buffer, and the close/quit flow asks about each. ⌘W closes the open file (asking first when dirty) and shows the empty state. `EditorBar` above the code shows the type badge, the path, the unsaved dot and `+N`/`−N`, then a Preview button for Markdown and a Diff button for a changed file (`EditorPresentation.barButtons`). A changed file shows Actual (the live buffer with changed lines marked), an unchanged one plain code; ⌘M only flips Markdown between code and preview. The session stores the open file and its mode and side; a stored `openTabs` list and unknown modes are ignored.
|
||||||
- **Focus.** `WorkspaceModel.focusRequest` names where the keyboard should go (a column, the commit box); the view that takes it calls `focusTaken(_:)`. The editor's text view follows `EditorStore.textFocusRequest`, which also moves when the Diff closes.
|
- **Focus.** `WorkspaceModel.focusRequest` names where the keyboard should go (a column, the Git view's commit message); the view that takes it calls `focusTaken(_:)`. The editor's text view follows `EditorStore.textFocusRequest`, which also moves when the Diff closes.
|
||||||
|
|
||||||
## Where things live
|
## Where things live
|
||||||
|
|
||||||
@@ -39,7 +41,8 @@ Sources/HelderCore/
|
|||||||
Config/ HelderConfig (tolerant decoding), config resolution, .env title
|
Config/ HelderConfig (tolerant decoding), config resolution, .env title
|
||||||
Diff/ Diff models, LineDiff, DiffViews, ViewMode
|
Diff/ Diff models, LineDiff, DiffViews, ViewMode
|
||||||
Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus)
|
Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus)
|
||||||
Git/ GitStatus/Change/GitSnapshot, Porcelain parsing, GitDerivation (rows, grouping, commit text)
|
Git/ GitStatus/Change/GitSnapshot, Porcelain parsing (incl. behind/upstream), GitDerivation (rows, commit text),
|
||||||
|
GitSections (the four sections, InlineDiff), GitConsole (echo, input parsing, line classifier), GitBranches
|
||||||
Highlight/ SyntaxHighlighter and one grammar per language
|
Highlight/ SyntaxHighlighter and one grammar per language
|
||||||
Markdown/ block/inline tree and parser, MarkdownSpeech (the prose Read aloud speaks)
|
Markdown/ block/inline tree and parser, MarkdownSpeech (the prose Read aloud speaks)
|
||||||
Search/ result models, Fuzzy, InFileSearch, rg --json parsing
|
Search/ result models, Fuzzy, InFileSearch, rg --json parsing
|
||||||
@@ -49,7 +52,7 @@ Sources/HelderServices/
|
|||||||
Files/ FileServicing (read, readText → .binary), FileService, FSEventsWatcher + WatchDebounce
|
Files/ FileServicing (read, readText → .binary), FileService, FSEventsWatcher + WatchDebounce
|
||||||
Git/ GitServicing, GitService, GitDirectory (worktrees)
|
Git/ GitServicing, GitService, GitDirectory (worktrees)
|
||||||
Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log)
|
Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log)
|
||||||
Process/ ProcessRunner, ExecutableLocator, ChildReaper, InstanceLauncher
|
Process/ ProcessRunner (`run`, and `stream` for line-by-line output), ExecutableLocator, ChildReaper, InstanceLauncher
|
||||||
Project/ ConfigService, RecentStores, SessionStore, ProjectLocator
|
Project/ ConfigService, RecentStores, SessionStore, ProjectLocator
|
||||||
Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk)
|
Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk)
|
||||||
Speech/ SpeechServicing + SpeechService (AVSpeechSynthesizer, the system voice), shared by the window
|
Speech/ SpeechServicing + SpeechService (AVSpeechSynthesizer, the system voice), shared by the window
|
||||||
@@ -61,7 +64,7 @@ Sources/HelderUI/
|
|||||||
Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator,
|
Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator,
|
||||||
Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter,
|
Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter,
|
||||||
ButtonGroup (pane toggles, toolbar), Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink
|
ButtonGroup (pane toggles, toolbar), Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink
|
||||||
SourceControl/ the git column and the commit box
|
GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches
|
||||||
Explorer/ the file tree column and the row glyphs
|
Explorer/ the file tree column and the row glyphs
|
||||||
Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup
|
Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup
|
||||||
Terminal/ agent + shell panes over SwiftTerm
|
Terminal/ agent + shell panes over SwiftTerm
|
||||||
@@ -104,6 +107,7 @@ How the suites are organised and how to run one: see the Testing section of the
|
|||||||
- **`bundle.sh --install`** refuses to replace a `~/Applications/Helder.app` with a different bundle id without `--force`.
|
- **`bundle.sh --install`** refuses to replace a `~/Applications/Helder.app` with a different bundle id without `--force`.
|
||||||
- **⌘N** is unbound; "New Window" is ⇧⌘N. New Window starts a new process on the launcher, and the child never inherits `HELDER_PROJECT` (it would win over the folder argument). ⌘A is select-all in the focused view (in the code pane, the whole file); fluid columns are ⌘L.
|
- **⌘N** is unbound; "New Window" is ⇧⌘N. New Window starts a new process on the launcher, and the child never inherits `HELDER_PROJECT` (it would win over the folder argument). ⌘A is select-all in the focused view (in the code pane, the whole file); fluid columns are ⌘L.
|
||||||
- **Config.** `files.followGitignore` defaults to **false** (the main-process value). There is no CSS layer: code font and size come from config/Typography.
|
- **Config.** `files.followGitignore` defaults to **false** (the main-process value). There is no CSS layer: code font and size come from config/Typography.
|
||||||
|
- **Removed keys still decode.** `git.confirmStage` / `git.confirmUnstage` are gone from `HelderConfig.Git`; old configs load and ignore them. A saved `ColumnLayoutSnapshot` from the Git-column era still decodes; its `sourceControlWidth` and `gitVisible` are ignored. Keep both tolerant when touching these types.
|
||||||
- **One file, no Original.** The editor deliberately has no tabs and no Original mode. `git.defaultDiffMode: "original"` in an older config decodes as `"updated"`.
|
- **One file, no Original.** The editor deliberately has no tabs and no Original mode. `git.defaultDiffMode: "original"` in an older config decodes as `"updated"`.
|
||||||
- **SwiftTerm** has no line-height or letter-spacing setting, so `terminal.lineHeight`/`letterSpacing` from the config are ignored.
|
- **SwiftTerm** has no line-height or letter-spacing setting, so `terminal.lineHeight`/`letterSpacing` from the config are ignored.
|
||||||
- **Pointer.** `Components/PointerPolicy.swift` is the one rule: I-beam, pointing hand or arrow. Text views conform to `PointerTextTarget`; a SwiftUI button or row gets the hand with `.pointerHand()` on the exact view a left click acts on, never on a container. Its region view takes no clicks and reads `\.isEnabled`, `disabledLook` and `\.pointerLayer` (`.overlay` under `OverlayHost` and the ⇧⌘O list), so a disabled button and every column behind an overlay keep the arrow. `updateCursor` asks the `PointerOwner` under the mouse first, so a text field inside a clickable row keeps the I-beam. AppKit hands a cursor update to the hit view, and a region view takes no hits, so `NSHostingView` would set the arrow; `PointerPolicy.installCursorUpdateMonitor()` (called at launch) swallows every cursor update in the key window, passes every mouse move on untouched, and for both runs `updateCursor` once afterwards (`scheduleUpdate`, coalesced per window). Inside an event SwiftUI's hit test returns its root view, so nothing calls `updateCursor` from inside an event, and the deferred call never resets cursor rects, which would fire new updates. Region views and the terminals keep a `PointerTracker` area (cursor update, enter, exit) so AppKit still sends an update when the mouse crosses their edge.
|
- **Pointer.** `Components/PointerPolicy.swift` is the one rule: I-beam, pointing hand or arrow. Text views conform to `PointerTextTarget`; a SwiftUI button or row gets the hand with `.pointerHand()` on the exact view a left click acts on, never on a container. Its region view takes no clicks and reads `\.isEnabled`, `disabledLook` and `\.pointerLayer` (`.overlay` under `OverlayHost` and the ⇧⌘O list), so a disabled button and every column behind an overlay keep the arrow. `updateCursor` asks the `PointerOwner` under the mouse first, so a text field inside a clickable row keeps the I-beam. AppKit hands a cursor update to the hit view, and a region view takes no hits, so `NSHostingView` would set the arrow; `PointerPolicy.installCursorUpdateMonitor()` (called at launch) swallows every cursor update in the key window, passes every mouse move on untouched, and for both runs `updateCursor` once afterwards (`scheduleUpdate`, coalesced per window). Inside an event SwiftUI's hit test returns its root view, so nothing calls `updateCursor` from inside an event, and the deferred call never resets cursor rects, which would fire new updates. Region views and the terminals keep a `PointerTracker` area (cursor update, enter, exit) so AppKit still sends an update when the mouse crosses their edge.
|
||||||
|
|||||||
+63
-62
@@ -11,17 +11,18 @@ Helder is a dark, AI-first macOS code editor for reviewing and navigating code w
|
|||||||
The window has three horizontal regions stacked top to bottom:
|
The window has three horizontal regions stacked top to bottom:
|
||||||
|
|
||||||
1. A top bar.
|
1. A top bar.
|
||||||
2. The main body, split into four resizable columns.
|
2. The main body, split into three resizable columns.
|
||||||
3. A bottom status bar.
|
3. A bottom status bar.
|
||||||
|
|
||||||
The four columns of the body, left to right, are:
|
The three columns of the body, left to right, are:
|
||||||
|
|
||||||
1. **Source Control**
|
1. **Explorer** (file tree)
|
||||||
2. **Explorer** (file tree)
|
2. **Editor** (one file and its code)
|
||||||
3. **Editor** (one file and its code)
|
3. **Agent and Terminal**, a single column split into two stacked panes: the Claude agent pane on top and a shell terminal below it.
|
||||||
4. **Agent and Terminal**, a single column split into two stacked panes: the Claude agent pane on top and a shell terminal below it.
|
|
||||||
|
|
||||||
Every boundary between panes is a draggable splitter. The vertical splitters between the four columns adjust their widths. The horizontal splitter between the agent pane and the terminal pane adjusts their heights. Splitter positions persist across launches. Panes have sensible minimum widths and heights so they cannot be collapsed to nothing by dragging.
|
Git is not a column: the full-screen **Git view** (section 3) covers all three regions while it is open.
|
||||||
|
|
||||||
|
Every boundary between panes is a draggable splitter. The vertical splitters between the three columns adjust their widths. The horizontal splitter between the agent pane and the terminal pane adjusts their heights. Splitter positions persist across launches. Panes have sensible minimum widths and heights so they cannot be collapsed to nothing by dragging.
|
||||||
|
|
||||||
The interface is dark only. Code is always syntax highlighted, in every panel and every view.
|
The interface is dark only. Code is always syntax highlighted, in every panel and every view.
|
||||||
|
|
||||||
@@ -33,68 +34,66 @@ The top bar contains, left to right:
|
|||||||
|
|
||||||
- The Helder wordmark.
|
- The Helder wordmark.
|
||||||
- A breadcrumb showing the path to the active file, for example `console / src / Http / Controller / UserController.php`. The breadcrumb is **display only** for now. It is not clickable and does not navigate.
|
- A breadcrumb showing the path to the active file, for example `console / src / Http / Controller / UserController.php`. The breadcrumb is **display only** for now. It is not clickable and does not navigate.
|
||||||
- Centred on the window, the **pane toggles**: Git · Explorer · File · Claude, one per column, all on by default (see Pane toggles in section 9). The breadcrumb truncates before it reaches them.
|
- Centred on the window, the **pane toggles**: Explorer · File · Claude. Each shows or hides one column, all on by default (see Pane toggles in section 9). The breadcrumb truncates before it reaches them.
|
||||||
- On the right, the toolbar: **Search** (`Cmd+F`) is an action; **Fluid** (`Cmd+L`) and **Hidden** (`Cmd+.`) are toggles. Then `?` for the keyboard shortcuts.
|
- On the right, the toolbar: **`Git N`** (`Cmd+G`) toggles the Git view (section 3); N counts the changed files, a file both staged and unstaged once, and the count is left out when there are none. **Search** (`Cmd+F`) is an action; **Fluid** (`Cmd+L`) and **Hidden** (`Cmd+.`) are toggles. Then `?` for the keyboard shortcuts.
|
||||||
- While Helder reads aloud, a **Stop** toggle appears left of **Search**, in the same style and switched on. A click switches it off and stops the reading; the button then goes away. It also goes away when the reading reaches the end, and a project switch or window close stops the reading.
|
- While Helder reads aloud, a **Stop** toggle appears left of **Git**, in the same style and switched on. A click switches it off and stops the reading; the button then goes away. It also goes away when the reading reaches the end, and a project switch or window close stops the reading.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Source Control panel
|
## 3. Git view
|
||||||
|
|
||||||
The leftmost column. It shows the working state of the project's git repository and is where staging and committing happen.
|
A full-screen view over the whole window (top bar, columns and status bar) for staging, committing, pulling, pushing and switching branches. `Cmd+G`, the `Git N` toggle and View › Show Git open it. `Cmd+G`, `Esc` and its **Close** button close it. Dialogs, context menus, search, the Diff and toasts sit above it. The columns stay mounted under it, so terminals keep running and the editor keeps its state. Opening it puts the keyboard in the commit message; closing it hands the keyboard back to the column that had it. It is not persisted: a project always opens with it closed.
|
||||||
|
|
||||||
### Header
|
While it is open, the columns' row, focus and editor keys rest. `Cmd+Return` commits, except from the console input. The other `Cmd` shortcuts keep working. `Cmd+C` with no selection, outside a terminal, opens the view on the commit message. `Esc` closes the topmost layer: an overlay (context menu, dialog, search, Diff) first, then the Git view; with neither open it reaches the terminal.
|
||||||
|
|
||||||
A `SOURCE CONTROL` header with a count badge showing the total number of changed files (staged plus unstaged).
|
From top to bottom:
|
||||||
|
|
||||||
### Commit area
|
### Top bar
|
||||||
|
|
||||||
Directly under the header:
|
`[ git ]`, the current branch in amber, and its place against the upstream: `in sync with origin`, `N ahead of origin`, `N behind origin`, `N ahead · M behind origin`, or `no upstream`. Ahead and behind come from the status header. On the right: **Pull** (with `↓N` when behind), **Push** (with `↑N` when ahead) and **Close** (`⌘G`).
|
||||||
|
|
||||||
- A single-line **commit message** input.
|
Opening the view reads the author and the branches, re-reads git and runs `git fetch origin`, but only when an origin exists, so ahead/behind are current.
|
||||||
- A **Commit** button whose label includes the staged count, for example `Commit 2`.
|
|
||||||
- The Commit button is enabled only when there is at least one staged change and the message field is not empty. Clicking it commits the staged changes with the typed message, clears the message field, and moves the committed files out of the staged section. The working tree updates accordingly.
|
- **Pull** runs `git pull --no-rebase`: diverged branches merge instead of failing on an unset `pull.rebase`.
|
||||||
|
- **Push** runs `git push`; when git reports there is no upstream, it retries with `git push -u origin <branch>`. `Cmd+P` pushes from anywhere.
|
||||||
|
- Both time out after 120 seconds. While one runs its button reads `Pulling…` / `Pushing…`, the console header says so, and a second pull or push is ignored. Git never prompts: no terminal prompt, no editor, no pager.
|
||||||
|
- The result is a toast: `Pushed N commits to origin/<branch>`, `Pulled N commits from origin/<branch>`, or `Push failed` / `Pull failed` with git's first error line.
|
||||||
|
|
||||||
|
### Commit block
|
||||||
|
|
||||||
|
- The **commit message**: always one lowercase line. Capitals become lowercase and line breaks become spaces as the user types or pastes, so `Enter` never starts a second line. The field grows with wrapped text from 56 to 180 points. An amber underline shows focus.
|
||||||
|
- The **author**, `user.name <user.email>` from git config.
|
||||||
|
- A `⌘↵ commits` hint.
|
||||||
|
- A **Commit** split button: `Commit N files`, or `Nothing staged`. It is amber when something is staged and the message is not empty, grey otherwise. The caret opens **Commit** and **Commit and push**.
|
||||||
|
- A commit always runs `git commit -m`, also from the grey button, so git's own refusal shows in the console. On success the message clears and a toast says `Committed N files` with the subject; on failure the message stays, a toast says `Commit failed`, and an empty message takes the focus back. **Commit and push** pushes only after a successful commit.
|
||||||
|
|
||||||
### Sections
|
### Sections
|
||||||
|
|
||||||
Two stacked sections, each with its own header and count:
|
Four colour-coded sections, each only when it has rows, in this order:
|
||||||
|
|
||||||
1. **STAGED CHANGES (n)** on top, listing files that are staged.
|
1. **staged**: every staged row, whatever its status. Row and bulk action: **Unstage** / **Unstage all**.
|
||||||
2. **CHANGES (n)** below, listing unstaged working-tree changes (added, modified, deleted).
|
2. **changed**: unstaged edits to tracked files, including renames and conflicts. **Discard** and **Stage**.
|
||||||
|
3. **new · untracked**: **Delete** and **Stage**.
|
||||||
|
4. **deleted**: **Restore** and **Stage**.
|
||||||
|
|
||||||
### Row anatomy
|
- A header shows the name, a count badge and the bulk actions; a click folds the section.
|
||||||
|
- A row shows a chevron, a status badge (`A`, `M`, `D`, `R`, `U`), the path (folder dim, name bright, struck through when deleted), `+N` / `−N`, and its actions. A click expands an inline side-by-side diff of that row's half, last commit (or index) left and working tree right, with 3 lines of context around each change and longer unchanged runs folded into `⋯ N unchanged lines`. A file over the diff cap shows `Too big.`.
|
||||||
|
- A conflicted row offers only **Stage**: staging marks the resolution.
|
||||||
|
- **Discard** reverts unstaged changes (modified and deleted files from the index, new files removed). **Discard** and **Delete** ask first (`git.confirmDiscard`, default on); **Restore** never asks. Stage and unstage never ask.
|
||||||
|
- **Right-click** a row: **Open in editor** (left out for a deleted file), **Pass on reference**, **Copy reference**. Open in editor and Pass on reference close the view first.
|
||||||
|
|
||||||
Each row, identical in both sections:
|
### Console
|
||||||
|
|
||||||
- A status letter on the far left: `A` added, `M` modified, `D` deleted, each in its own color (added teal, modified amber, deleted amber-deep).
|
The bottom-left panel. Every action logs the exact git command (`$ git add -- path`) and streams its output line by line, coloured by kind: errors, hints, staged and unstaged lines of `status`, and the ref update of a push. Below the log, a `$ git` input runs typed commands, with or without a leading `git`. `clear` empties the log, a bare `log` runs `log --oneline --decorate -n 30`, and `Up` recalls earlier input. Commands, typed or from buttons, run one at a time. The log keeps the last 400 lines.
|
||||||
- A file-type icon, then the file name.
|
|
||||||
- The dimmed relative path, aligned to the right of the name.
|
|
||||||
- Change counts at the far right: additions in teal (`+N`) and deletions in amber-deep (`-N`).
|
|
||||||
- Deleted files are shown with the file name struck through and dimmed.
|
|
||||||
- Rows have default, hover, and selected states. The selected row is the file currently open in the editor.
|
|
||||||
|
|
||||||
### Interactions
|
### Branches
|
||||||
|
|
||||||
- **Left-click** a row opens that file in the editor, on the live file. It does not open the full-screen Diff.
|
The bottom-right panel: **local** branches, then **remote · origin**. The current branch is marked; a remote branch with a local counterpart reads `tracked`. A click switches (`switch →`); a remote branch without a local one is checked out as a new tracking branch (`checkout →`). While there are uncommitted changes, switching is locked: the header says so, the other branches dim, and a click shows a toast instead of running git.
|
||||||
- **Right-click** a row opens a context menu, designed to grow over time:
|
|
||||||
- In CHANGES (unstaged): **Open diff**, **Stage file**, and **Discard changes**.
|
|
||||||
- In STAGED: **Open diff**, and **Unstage file**.
|
|
||||||
- **Open diff** is the explicit way into the full-screen Diff (section 5).
|
|
||||||
- **Hover quick action**: on hover, an unstaged row shows a `+` to stage it in one click, and a staged row shows a `-` to unstage it.
|
|
||||||
- Optional section actions: **Stage all** on the CHANGES header and **Unstage all** on the STAGED header.
|
|
||||||
- **Discard** is a destructive action. It asks for confirmation first (controlled by `git.confirmDiscard`, default on). Discarding reverts a modified file to its committed state and restores a deleted file.
|
|
||||||
- Staging and unstaging do not ask for confirmation by default (`git.confirmStage` and `git.confirmUnstage`, default off).
|
|
||||||
|
|
||||||
### Branch summary bar
|
|
||||||
|
|
||||||
At the very bottom of this column, a bar shows the current branch name and the total line changes across the working tree, for example `feat/payments-balance +50 -38`. This bar is **display only**. It does not switch branches.
|
|
||||||
|
|
||||||
### Empty states
|
### Empty states
|
||||||
|
|
||||||
- When nothing is staged, the STAGED section shows a dimmed line: `No staged changes`.
|
- Not a repository: `— Not a git repository.`
|
||||||
- When the working tree is clean, the CHANGES section shows a dimmed line: `Working tree clean`.
|
- Clean working tree: `— No changes. The working tree is clean.`
|
||||||
|
|
||||||
Scope note: git in this version covers staging, unstaging, committing, and discarding. Push, pull, fetch, and branch switching are not part of this version.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -104,11 +103,11 @@ The second column. A standard project file tree.
|
|||||||
|
|
||||||
- An `EXPLORER` header.
|
- An `EXPLORER` header.
|
||||||
- Folders expand and collapse. Files and folders use type icons.
|
- Folders expand and collapse. Files and folders use type icons.
|
||||||
- Files that have changes show the same status letter as the Source Control panel (`A`, `M`, `D`) on the right of their row.
|
- Files that have changes show their status letter (`A`, `M`, `D`) on the right of their row.
|
||||||
- **Left-click** a file opens it in the editor. The selected file is highlighted.
|
- **Left-click** a file opens it in the editor. The selected file is highlighted.
|
||||||
- The tree hides paths matched by `files.exclude` and, when `files.followGitignore` is on, paths ignored by git.
|
- The tree hides paths matched by `files.exclude` and, when `files.followGitignore` is on, paths ignored by git.
|
||||||
- **Right-click** a file offers **Copy reference**, which copies the file's project-relative path to the clipboard (the file-level form of the editor's Copy reference).
|
- **Right-click** a file offers **Copy reference**, which copies the file's project-relative path to the clipboard (the file-level form of the editor's Copy reference).
|
||||||
- A Markdown file (`.md`) also offers **Read aloud**, in its own group after the pass-on and copy items, in the Explorer and on its git rows. Helder reads the text with the system voice: headings, paragraphs, list items, quotes and table cells, with the markup and link URLs left out and code blocks skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. A new Read aloud replaces the one that is playing. A `$` is read as "dollar", except before a digit (`$5` stays "five dollars").
|
- A Markdown file (`.md`) also offers **Read aloud**, in its own group after the pass-on and copy items, in the Explorer. Helder reads the text with the system voice: headings, paragraphs, list items, quotes and table cells, with the markup and link URLs left out and code blocks skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. A new Read aloud replaces the one that is playing. A `$` is read as "dollar", except before a digit (`$5` stays "five dollars").
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -228,26 +227,28 @@ Opens a fuzzy file-open overlay. The user types part of a file name or path, the
|
|||||||
|
|
||||||
### Search (`Cmd+F`)
|
### Search (`Cmd+F`)
|
||||||
|
|
||||||
Opens a modal search overlay that searches **both** file contents and file names at once. The overlay covers 90 percent of the application width and is centered over a dimmed background.
|
Opens a modal search overlay that searches the open file, file contents and file names at once. Like the Git view, it covers the whole window edge to edge, title bar and status bar included: no margin, no dimmed background, no card. It sits above the Git view when opened from there; toasts sit above it.
|
||||||
|
|
||||||
Inside the overlay:
|
Inside the overlay:
|
||||||
|
|
||||||
- A query field at the top.
|
- A query field at the top, with the type chips and a summary.
|
||||||
- Two result columns below:
|
- Result columns below, each with a fixed share of the width that never changes when the focus moves:
|
||||||
- **Left column, 70 percent width**: matches found inside files (content search), grouped by file, each match shown as the matching line with the query highlighted in context.
|
- **This file** (30 percent, only when a file is open): matches in the open file.
|
||||||
- **Right column, 30 percent width**: files whose name or path matches the query.
|
- **Project** (45 percent, 65 percent without This file): matches found inside files, grouped by file, each match shown as the matching line with the query highlighted in context.
|
||||||
|
- **Files** (25 percent, 35 percent without This file): files whose name or path matches the query.
|
||||||
|
- The focused column shows its focus only by its amber title and count.
|
||||||
- Selecting a content result opens the file and jumps to that line. Selecting a file-name result opens that file.
|
- Selecting a content result opens the file and jumps to that line. Selecting a file-name result opens that file.
|
||||||
- When nothing matches, each column shows a brief no-results message.
|
- When nothing matches, each column shows a brief no-results message.
|
||||||
- `Esc` closes the overlay. The respected excludes are the same as the Explorer (`files.exclude` and, when on, gitignore).
|
- `Esc` closes the overlay; there is no area to click to close it. The respected excludes are the same as the Explorer (`files.exclude` and, when on, gitignore).
|
||||||
|
|
||||||
### Mouse pointer
|
### Mouse pointer
|
||||||
|
|
||||||
The pointer shows what a left click does at that spot. It depends only on what lies under the mouse.
|
The pointer shows what a left click does at that spot. It depends only on what lies under the mouse.
|
||||||
|
|
||||||
- **Pointing hand** only where a left click runs an action: buttons (title-bar toggles and tools, `?`, Preview, Diff, Commit, Push, stage `+` / unstage `−`, Stage all / Unstage all, dialog buttons, Collapse, search chips), clickable rows (Git file rows, Explorer rows, search results, recent files and projects, launcher rows, symbol popup rows, context-menu items) and the project name in the title bar. Never on a view that only reacts to a right-click, a tooltip or hover.
|
- **Pointing hand** only where a left click runs an action: buttons (title-bar toggles and tools, `?`, Preview, Diff, the Git view's buttons and section headers, dialog buttons, Collapse, search chips), clickable rows (Git view file rows and switchable branches, Explorer rows, search results, recent files and projects, launcher rows, symbol popup rows, context-menu items) and the project name in the title bar. Never on a view that only reacts to a right-click, a tooltip or hover.
|
||||||
- **I-beam** where a click places a caret or starts a selection: the code (also below the last line), the Markdown preview, both terminals, the commit message and every overlay input.
|
- **I-beam** where a click places a caret or starts a selection: the code (also below the last line), the Markdown preview, both terminals, the commit message, the Git console and every overlay input.
|
||||||
- **Arrow** everywhere else: labels, headers, folder labels, the gutter, the status bar, scrims, toasts, empty states, and a disabled button such as Commit with nothing staged.
|
- **Arrow** everywhere else: labels, headers, folder labels, the gutter, the status bar, scrims, toasts, empty states, and a disabled button such as Commit with nothing staged.
|
||||||
- With an overlay open, every column behind it shows the arrow; the overlay's own buttons, rows and inputs keep theirs.
|
- With an overlay open, every column behind it, and the Git view, shows the arrow; the overlay's own buttons, rows and inputs keep theirs.
|
||||||
- A splitter shows a resize arrow; `Cmd` over a known PHP class name in the code shows the hand. No other pointers are used.
|
- A splitter shows a resize arrow; `Cmd` over a known PHP class name in the code shows the hand. No other pointers are used.
|
||||||
|
|
||||||
### Pane resizing
|
### Pane resizing
|
||||||
@@ -256,7 +257,7 @@ Dragging any splitter resizes the adjacent panes. Positions persist across launc
|
|||||||
|
|
||||||
### Pane toggles
|
### Pane toggles
|
||||||
|
|
||||||
Each title-bar toggle shows or hides its column; `Cmd+G` is the same as the Git toggle. Hiding only hides: the terminals and their processes, the editor buffer and scroll, and the Explorer's expanded folders survive any number of hide/show cycles. The editor absorbs the freed width; with the editor hidden the Agent and Terminal column fills the rest. With every column off the body shows the editor background. A hidden column cannot take focus, and hiding the focused column hands the keyboard back to the window. `Cmd+C` to the commit box shows a hidden Source Control column. The four flags are saved per project.
|
Each column toggle in the title bar shows or hides its column; `Cmd+1`, `Cmd+2` and `Cmd+3` do the same for Explorer, File and Claude. Hiding only hides: the terminals and their processes, the editor buffer and scroll, and the Explorer's expanded folders survive any number of hide/show cycles. The editor absorbs the freed width; with the editor hidden the Agent and Terminal column fills the rest. With every column off the body shows the editor background. A hidden column cannot take focus, and hiding the focused column hands the keyboard back to the window. The three flags are saved per project. A saved layout from before the Git view still loads; its Git width and flag are ignored.
|
||||||
|
|
||||||
### Session restore
|
### Session restore
|
||||||
|
|
||||||
@@ -273,14 +274,14 @@ Settings are project-scoped and live in a `.helder` folder in the project root.
|
|||||||
- **Effective value** of any setting: the value from `config.json` if present, otherwise the value from `config.default.json`, merged key by key.
|
- **Effective value** of any setting: the value from `config.json` if present, otherwise the value from `config.default.json`, merged key by key.
|
||||||
- There is no theme file. The code font and size are built in; `Cmd+0`, `Cmd++` and `Cmd+−` zoom the editor, Diff and terminal text.
|
- There is no theme file. The code font and size are built in; `Cmd+0`, `Cmd++` and `Cmd+−` zoom the editor, Diff and terminal text.
|
||||||
|
|
||||||
Settings that affect behavior described above include indentation and editor display, file and search excludes, the default diff mode (`updated` or `diff`), git confirmation prompts, the terminal shell override, the agent auto-launch and command, and session restore.
|
Settings that affect behavior described above include indentation and editor display, file and search excludes, the default diff mode (`updated` or `diff`), the git discard confirmation, the terminal shell override, the agent auto-launch and command, and session restore.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. States and edge cases summary
|
## 11. States and edge cases summary
|
||||||
|
|
||||||
- **No project open**: the window shows an empty state inviting the user to open a project folder.
|
- **No project open**: the window shows an empty state inviting the user to open a project folder.
|
||||||
- **Clean working tree**: Source Control shows its empty-section messages; the Explorer still shows the full tree.
|
- **Clean working tree**: the Git view shows its clean message; the Explorer still shows the full tree.
|
||||||
- **Unchanged file open**: normal editable view, no Diff button.
|
- **Unchanged file open**: normal editable view, no Diff button.
|
||||||
- **Added or deleted file**: views behave as described in section 5.
|
- **Added or deleted file**: views behave as described in section 5.
|
||||||
- **Binary or unsupported file**: placeholder, no Preview or Diff button.
|
- **Binary or unsupported file**: placeholder, no Preview or Diff button.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,409 +0,0 @@
|
|||||||
# Handoff: Helder — editor for working with Claude Code
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
Helder is a desktop code editor built around one job: work on a codebase together with
|
|
||||||
Claude Code. It replaces a general IDE with four columns — source control, explorer,
|
|
||||||
editor, agent — plus four overlays (search, keyboard shortcuts, project
|
|
||||||
launcher, expanded diff) and a set of small surfaces (context menus, a pass-on-to-agent
|
|
||||||
prompt, tooltips, a markdown preview).
|
|
||||||
|
|
||||||
This handoff describes one consistent visual system for all of those screens.
|
|
||||||
|
|
||||||
## About the design files
|
|
||||||
|
|
||||||
The files in this bundle are **design references written in HTML**. They show the
|
|
||||||
intended look, spacing and states. They are not production code to copy.
|
|
||||||
|
|
||||||
The task is to **recreate these screens in the target codebase's own environment**
|
|
||||||
(Electron + React, Tauri + Svelte, SwiftUI, whatever the app already uses) with its
|
|
||||||
established patterns. If no environment exists yet, pick the framework that fits a
|
|
||||||
desktop editor and implement the design there.
|
|
||||||
|
|
||||||
`Helder IDE.dc.html` is a single-canvas board: every screen sits on one page, side by
|
|
||||||
side, at real pixel sizes. Open it in a browser to inspect any value with devtools.
|
|
||||||
|
|
||||||
## Fidelity
|
|
||||||
|
|
||||||
**High fidelity.** Colours, type, row heights, paddings, radii and states are final and
|
|
||||||
exact. Recreate them pixel-for-pixel. Everything is authored with inline styles so any
|
|
||||||
element's computed value can be read directly from the file.
|
|
||||||
|
|
||||||
Two things are deliberately *not* final:
|
|
||||||
- The code shown inside the editor panes is sample content, not a spec.
|
|
||||||
- Icons are Unicode stand-ins (`⌕ ▤ ◇ ⧉ ✎ ↺ ⇄ ⑂ ◆ →`). Ship them as Lucide glyphs at
|
|
||||||
stroke width 1.75, 16px inline / 18px standalone.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Design tokens
|
|
||||||
|
|
||||||
### Surfaces (four, no more)
|
|
||||||
|
|
||||||
| Token | Hex | Use |
|
|
||||||
|---|---|---|
|
|
||||||
| `editor` | `#101720` | Editor canvas, terminal, launcher backdrop, code blocks |
|
|
||||||
| `panel` | `#18202B` | Title bar, side panels, status bar, overlays, menus, tooltip host |
|
|
||||||
| `raised` | `#232C39` | Selected row, hairline borders, tooltip surface, keycap borders |
|
|
||||||
| `hover` | `#1E2733` | Row hover fill only |
|
|
||||||
|
|
||||||
### Text on dark
|
|
||||||
|
|
||||||
| Token | Hex | Use |
|
|
||||||
|---|---|---|
|
|
||||||
| `text-1` | `#F4F5F4` | Active file, dialog titles, selected row |
|
|
||||||
| `text-2` | `#E4E7E6` | Body copy, code plain text |
|
|
||||||
| `text-3` | `#BAC0C0` | Inactive rows, identifiers, secondary copy |
|
|
||||||
| `text-4` | `#6C7783` | Labels, paths, meta, comments |
|
|
||||||
| `text-5` | `#3A424C` | Line numbers, disabled |
|
|
||||||
|
|
||||||
### Accent — amber, reserved
|
|
||||||
|
|
||||||
`#E8913A` primary · `#C4741F` deep · `#F0B476` soft · `rgba(232,145,58,.10)` tint ·
|
|
||||||
`rgba(232,145,58,.22)` focus ring.
|
|
||||||
|
|
||||||
Amber is allowed **only** for: the active toolbar toggle (tint fill), the 2px selection
|
|
||||||
rule, the caret, keycap glyphs, the blinking period in the wordmark, the primary button
|
|
||||||
fill (ink text on amber, never white), the search-hit highlight, section markers, list
|
|
||||||
markers, links, and counts in the status bar. Never an amber panel, never an amber
|
|
||||||
heading.
|
|
||||||
|
|
||||||
### Light canvas (this board only)
|
|
||||||
|
|
||||||
`#EFF0EE` page · `#E5E7E4` spec card · `#CDD1CD` hairline · `#171C22` ink ·
|
|
||||||
`#3A424C` ink muted · `#6B7480` ink dim. The application itself is dark only.
|
|
||||||
|
|
||||||
### Syntax — eight colours, lifted but unsaturated
|
|
||||||
|
|
||||||
| Role | Hex |
|
|
||||||
|---|---|
|
|
||||||
| plain / punctuation | `#F1F3F2` |
|
|
||||||
| function / method name | `#A9C0E4` |
|
|
||||||
| class / type / CSS selector | `#EFBCB0` |
|
|
||||||
| variable / property | `#D4D9D8` |
|
|
||||||
| comment | `#828D9A` |
|
|
||||||
| keyword / operator / pseudo-class | `#D8BEE4` |
|
|
||||||
| string / value / type path | `#A8D6CB` |
|
|
||||||
| number / tag / hex literal | `#F8C793` |
|
|
||||||
|
|
||||||
No bold, no italic in code. Weight stays 400 so the column reads flat.
|
|
||||||
|
|
||||||
### Diff
|
|
||||||
|
|
||||||
- added: text `#8FBFB4`, fill `rgba(143,191,180,.12)`, 2px left rule `#8FBFB4`
|
|
||||||
- removed: text `#C4741F`, fill `rgba(196,116,31,.14)`, 2px left rule `#C4741F`
|
|
||||||
- counts in headers: `+1` in `#8FBFB4`, `−1` in `#C4741F` (real minus sign U+2212)
|
|
||||||
|
|
||||||
No green, no red anywhere. The diff reads on shape and on the 2px rule.
|
|
||||||
|
|
||||||
### Type
|
|
||||||
|
|
||||||
- `IBM Plex Mono` — 400/500/600/700. All labels, paths, code, keycaps, titles, numbers.
|
|
||||||
- `IBM Plex Sans` — 400/500. Rows, menu items, tooltips, buttons, running text.
|
|
||||||
|
|
||||||
| Role | Spec |
|
|
||||||
|---|---|
|
|
||||||
| Board display | Mono 700, 58px/1.02, `-0.04em` |
|
|
||||||
| Section title | Mono 700, 20px/1.2, `-0.02em` |
|
|
||||||
| Dialog title | Mono 700, 14px/1 |
|
|
||||||
| Section/panel label | Mono 700, 10px, `0.14em`, uppercase, `#6C7783` |
|
|
||||||
| Board label | Mono 700, 10–11px, `0.14em`, uppercase, `#6B7480` |
|
|
||||||
| Code | Mono 400, 13px / 20px line box |
|
|
||||||
| Search hit line | Mono 400, 12px / 24px line box |
|
|
||||||
| Path / meta / status bar | Mono 400, 11–12px |
|
|
||||||
| Keycap | Mono 600, 12px, padding 4px 6px, 1px `#232C39`, radius 2px, glyph `#E8913A` |
|
|
||||||
| Row label | Sans 400 13px (500 when selected) |
|
|
||||||
| Body copy | Sans 400, 14px/1.7, max 68ch |
|
|
||||||
| Tooltip | Sans 400, 12px/1.5 |
|
|
||||||
|
|
||||||
### Geometry
|
|
||||||
|
|
||||||
| Value | Where |
|
|
||||||
|---|---|
|
|
||||||
| 24px | Explorer / launcher-adjacent row height |
|
|
||||||
| 26px | Source-control row height |
|
|
||||||
| 28px | Status bar, state-specimen rows |
|
|
||||||
| 30px | Context-menu item height |
|
|
||||||
| 34px | Editor tab strip, markdown/code panel header |
|
|
||||||
| 44px | Title bar and toolbar |
|
|
||||||
| 20px | Code line box (13px type) |
|
|
||||||
| 2px | Radius: buttons, inputs, tags, keycaps, menus' inner rows, code blocks |
|
|
||||||
| 4px | Radius: panels, cards, menus |
|
|
||||||
| 8px | Radius: overlays (modals) only |
|
|
||||||
| 1px | Every hairline (`#232C39` on dark, `#CDD1CD` on light) |
|
|
||||||
| 2px | Accent rule: selection, focus border, pull-quote |
|
|
||||||
| 9999px | Traffic-light dots and avatars only |
|
|
||||||
|
|
||||||
Column widths in the workspace: source control 300 · explorer 288 · editor flex ·
|
|
||||||
agent 480 (the agent takes `flex: 1` when the editor is hidden). Agent terminal block 190px tall. Full frame 1760 × 1000.
|
|
||||||
|
|
||||||
### Elevation
|
|
||||||
|
|
||||||
Only two shadows exist:
|
|
||||||
- dropdown / context menu: `0 4px 16px rgba(23,28,34,.10)`
|
|
||||||
- overlay: `0 16px 48px rgba(23,28,34,.18)`
|
|
||||||
|
|
||||||
No ambient card shadow, no glow.
|
|
||||||
|
|
||||||
### Motion
|
|
||||||
|
|
||||||
Colour transitions only, 160ms `cubic-bezier(0.22,1,0.36,1)` (120ms on small controls).
|
|
||||||
The single exception is `blink`: a stepped 1.1s on/off (no fade) used for the caret, the
|
|
||||||
terminal block cursor and the amber period in the wordmark. No entrance animation, no
|
|
||||||
lift, no scale, no parallax.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Screens
|
|
||||||
|
|
||||||
### 01 · Workspace (1760 × 1000)
|
|
||||||
|
|
||||||
Vertical stack: title bar 44px → body (flex row) → status bar 28px.
|
|
||||||
|
|
||||||
**Title bar** (`#18202B`, 1px bottom `#232C39`, padding 0 14px, gap 18px)
|
|
||||||
Traffic lights 12px (`#E8913A`, `#6C7783`, `#3A424C`, gap 8px) · wordmark
|
|
||||||
`helder` Mono 700 13px `#F4F5F4` with a blinking `.` in `#E8913A` · project `odynt`
|
|
||||||
Mono 12px `#6C7783` · `·` · branch `main` Mono 500 12px `#E8913A` · breadcrumb of the
|
|
||||||
open path in Mono 12px `#6C7783`, last segment `#F4F5F4` 600, `›` separators · the
|
|
||||||
pane-toggle group, centred · the toolbar group, right-aligned · `?` (26px square, 1px
|
|
||||||
`#232C39`, radius 2, Mono 600 12px `#6C7783`), 8px gap from the toolbar group.
|
|
||||||
|
|
||||||
**Button group** — one shared treatment for both header groups. Container: 1px
|
|
||||||
`#232C39`, radius 2, overflow hidden, no gap. Each button: padding 6px 10px, gap 7px,
|
|
||||||
Sans 500 12px/1, `white-space: nowrap`, 1px `#232C39` left divider (not on the first).
|
|
||||||
- On: fill `rgba(232,145,58,.10)`, label `#F4F5F4`, 6px round dot `#E8913A`.
|
|
||||||
- Off: no fill, label `#6C7783`, dot `#3A424C`.
|
|
||||||
- Action (not a toggle): no dot, label `#BAC0C0`.
|
|
||||||
- Shortcut, when shown: Mono 600 11px, no border — `#E8913A` when on or on an action,
|
|
||||||
`#6C7783` when off.
|
|
||||||
|
|
||||||
**Pane toggles** (centred: `position:absolute; left:50%; top:50%;
|
|
||||||
transform:translate(-50%,-50%)` inside the title bar) — Git · Explorer · File · Claude.
|
|
||||||
One per column, all on by default, no shortcut shown.
|
|
||||||
|
|
||||||
**Toolbar** (right) — Search ⌘F (action) · Auto-fit ⌘A (toggle, on) · Hidden ⌘.
|
|
||||||
(toggle, off). The old Git ⌘G toolbar button is removed; the
|
|
||||||
Git pane toggle replaces it.
|
|
||||||
|
|
||||||
**Source control column** (300px, `#18202B`, 1px right border)
|
|
||||||
Commit box: 52px `#101720` field, 1px `#232C39`, radius 2, placeholder
|
|
||||||
"Shift+Enter to commit" `#6C7783`; 34px push button `↑` beside it, same border.
|
|
||||||
Group header: Mono 700 10px `0.14em` uppercase `#6C7783`, count right in `#E8913A`
|
|
||||||
("STAGED CHANGES 4", "CHANGES 1"). Under each group the files are clustered per folder:
|
|
||||||
a 22px subhead carries `▤` plus the directory path in Mono 400 11px `#6C7783` —
|
|
||||||
one path per cluster, never repeated on the rows — and clusters are separated by an 8px
|
|
||||||
gap. Rows 26px: status letter (Mono 600 10px — staged
|
|
||||||
`#8FBFB4`, unstaged `#F0B476`) · 8px type badge · file name Sans 12px, ellipsised.
|
|
||||||
Footer line "4 staged · 1 unstaged" Mono 11px `#6C7783`.
|
|
||||||
|
|
||||||
**Explorer** (288px, `#18202B`) — 30px header ("EXPLORER" / project name), then 24px
|
|
||||||
rows. Indent 16px per level (12 · 28 · 44 · 60 · 76 padding-left). Collapsed `›`
|
|
||||||
`#6C7783`; expanded `⌄` `#E8913A`, its label `#F4F5F4`. File rows carry an 8px type
|
|
||||||
badge and, when dirty, a trailing `M` in `#8FBFB4`.
|
|
||||||
|
|
||||||
Type badge: Mono 600 8px, ink text `#101720` on a per-extension fill, radius 2,
|
|
||||||
padding 3px 4px — php `#C3A6CE` · md `#BAC0C0` · js `#F0B476` · css `#8FBFB4`.
|
|
||||||
|
|
||||||
**Editor** (flex, `#101720`) — 34px strip: "MODIFIED" label, `+1` / `−1` counts, then a
|
|
||||||
right-aligned segmented control (1px `#232C39`, radius 2, dividers 1px): Actual ·
|
|
||||||
Original · Diff · Split. Active segment = amber fill with `#171C22` text.
|
|
||||||
Code area: CSS grid `56px 1fr`, line box 20px, numbers right-aligned `#5A6472` with
|
|
||||||
14px right padding. **Indentation is padding-left on the code cell** (7.82px per space:
|
|
||||||
31.3 / 62.6 / 93.8 / 125.1) — do not ship non-breaking spaces.
|
|
||||||
|
|
||||||
**Agent panel** (480px, `#18202B`, 1px left border)
|
|
||||||
Header: 60px `#232C39` square (mark), then `Claude Code` Mono 700 14px + version in
|
|
||||||
`#6C7783`, model line Sans 12px `#BAC0C0`, cwd Mono 12px `#6C7783`.
|
|
||||||
Notice strip: fill `rgba(232,145,58,.10)`, `[ ! ]` Mono 600 12px `#E8913A`, sentence
|
|
||||||
Sans 12px, inline command in Mono `#F0B476`.
|
|
||||||
Transcript: user turn prefixed `›` in `#E8913A`, agent turn `◆` in `#6C7783`, text
|
|
||||||
Sans 13px/1.6. Tool calls sit in a `#101720` block, 1px `#232C39`: verb in `#8FBFB4`
|
|
||||||
(read) or `#F0B476` (write), target and counts `#6C7783`.
|
|
||||||
Prompt field: 44px, `#101720`, **2px `#E8913A` border + `0 0 0 2px rgba(232,145,58,.22)`
|
|
||||||
ring** (this is the focus treatment everywhere), `›` prefix, blinking 1px caret.
|
|
||||||
Status line: Mono 11px `#6C7783`; project chip = amber fill with `#171C22` text;
|
|
||||||
`▸▸ auto mode` in `#E8913A`; slash hint right.
|
|
||||||
Terminal: 190px, `#101720`, Mono 12px/1.7 — `[main]` `#8FBFB4`, `[~/path]$` `#6C7783`,
|
|
||||||
output `#6C7783`, 7×14px blinking amber block cursor.
|
|
||||||
|
|
||||||
**Status bar** (28px, `#18202B`) — `⑂ main` in `#E8913A`, `+16` `#8FBFB4`, `−12`
|
|
||||||
`#C4741F`, then right-aligned path · Ln/Col · UTF-8 · LF · language (`#BAC0C0`).
|
|
||||||
|
|
||||||
### 02a · Search (⌘F)
|
|
||||||
|
|
||||||
Overlay: flat ink scrim `rgba(16,23,32,.72)` (no blur), 34px inset, panel `#18202B`,
|
|
||||||
1px `#232C39`, radius 8, overlay shadow.
|
|
||||||
|
|
||||||
- Query bar 54px: `⌕` `#E8913A`, query Mono 500 16px `#F4F5F4`, blinking caret; right
|
|
||||||
side = extension filters (active = amber fill + ink text; inactive = 1px border,
|
|
||||||
`#BAC0C0`) and a Mono 11px result summary `#6C7783` behind a 1px left divider.
|
|
||||||
- Three columns: **this file** (230px) · **project** (flex) · **files** (250px), split by
|
|
||||||
1px borders. Column headers are the standard 10px mono labels; the focused column's
|
|
||||||
header is `#E8913A` with a count chip (amber fill, ink text).
|
|
||||||
- Result group header: type badge + path Mono 12px `#BAC0C0`, hit count right `#6C7783`.
|
|
||||||
- Hit lines: grid `64px 1fr`, line box 24px. Match run = amber fill with `#171C22` text
|
|
||||||
on the selected row, `#F0B476` text elsewhere. Selected row: `#232C39` fill, 2px amber
|
|
||||||
left rule, and the line number lifts to `#E8913A` (never leave it at `#3A424C`).
|
|
||||||
- Empty column state: one plain sentence, Sans 12px `#6C7783` ("No matches in this
|
|
||||||
file." / "No file names match."). No illustration.
|
|
||||||
- Footer 38px: key hints (`⌘←`/`⌘→` column, `⌘↑`/`⌘↓` row, `↵` open) with amber glyphs,
|
|
||||||
`esc` chip right.
|
|
||||||
|
|
||||||
### 02b · Keyboard shortcuts (`?`)
|
|
||||||
|
|
||||||
Same overlay shell. 50px header with `◇` `#E8913A` + "Keyboard shortcuts" + `esc` chip.
|
|
||||||
Body groups (`NAVIGATE`, `AGENT`, `GIT`, `FILE`) each a 10px mono label, then a
|
|
||||||
`92px 1fr` grid: keycap cluster left (gap 4px), description Sans 13px `#E4E7E6` right,
|
|
||||||
6px vertical padding per row.
|
|
||||||
|
|
||||||
### 02d · Project launcher
|
|
||||||
|
|
||||||
Window `#101720` with only traffic lights (34px), no title bar. Centred panel on
|
|
||||||
`#18202B`, radius 8, overlay shadow, top-aligned with 20px/40px padding.
|
|
||||||
Header: `◆` amber + wordmark with blinking period + "Open a project to begin" Sans 12px
|
|
||||||
`#6C7783`. Then a 46px "Open new project…" row with `+` amber and an `↵` chip.
|
|
||||||
`RECENT` label, then 38px rows: `▤` icon, name Sans 500 13px, path Mono 11px `#6C7783`.
|
|
||||||
Selected row: `#232C39`, 2px amber left rule, icon and path lift one step.
|
|
||||||
Footer 36px: `⌘↑↓ navigate · ↵ open`.
|
|
||||||
|
|
||||||
### 03 · Expanded diff (1760 × 620)
|
|
||||||
|
|
||||||
Own window: 42px title bar (traffic lights, path Mono 500 12px `#F4F5F4`, "MODIFIED",
|
|
||||||
`+1` / `−1`, "staged → actual" Mono 11px `#6C7783`, and a right-aligned
|
|
||||||
"Collapse `esc`" button with 1px border).
|
|
||||||
Two panes split by a 1px border; each has a 30px header — left `ORIGINAL` + "before"
|
|
||||||
`#3A424C`, right `UPDATED` in `#E8913A` + "after".
|
|
||||||
Panes are grids `52px 1fr`, line box 22px, indentation as padding-left, and **identical
|
|
||||||
line numbering in both panes** so the eye can travel across. Changed row gets the fill,
|
|
||||||
the 2px left rule and a lifted number colour.
|
|
||||||
|
|
||||||
### 04 · Small surfaces
|
|
||||||
|
|
||||||
**Context menu** (explorer and source control) — 320px, `#18202B`, 1px `#232C39`,
|
|
||||||
radius 4, dropdown shadow, 8px vertical padding. First a path header (Mono 11px
|
|
||||||
`#6C7783`, 1px bottom border). Items 30px, Sans 13px `#BAC0C0`, icon `#6C7783`.
|
|
||||||
Highlighted item: `#232C39` fill, 2px amber left rule, label `#F4F5F4` 500, icon amber.
|
|
||||||
Destructive item ("Delete file", "Discard changes"): `#C4741F` label. Groups separated
|
|
||||||
by a 1px rule with 6px margins.
|
|
||||||
|
|
||||||
Explorer items: Pass on reference · Copy reference · Pass on file name · Copy file name
|
|
||||||
| Rename file · Show in Finder · Delete file.
|
|
||||||
Source-control items: Pass on reference · Copy reference | Stage changes · Open diff ·
|
|
||||||
Discard changes.
|
|
||||||
|
|
||||||
**Pass on to agent** — 460px panel, 14px padding, gap 12. Title row (`◇` amber +
|
|
||||||
Mono 700 13px + `esc` chip), a focused 38px input (2px amber border + ring, blinking
|
|
||||||
caret), then an INSERTS preview: 10px mono label + the composed string on an amber fill
|
|
||||||
with `#171C22` text, radius 2, ellipsised. Footer hint `↵ insert into agent · esc cancel`
|
|
||||||
with amber glyphs.
|
|
||||||
|
|
||||||
**Tooltip** — `#232C39` surface, 1px `#3A424C`, radius 2, padding 8px 10px, max 300px,
|
|
||||||
Sans 12px/1.5 `#E4E7E6`. No arrow, no shadow. The current state is named inside the
|
|
||||||
sentence in amber ("Hidden files: *hidden* — …", "Auto-fit panels: *on* — …"), then one
|
|
||||||
sentence saying what a click does.
|
|
||||||
|
|
||||||
**Markdown Actual / Preview** — same 34px header on both halves; the segmented control's
|
|
||||||
active side is the amber fill. Actual = the code grid (`44px 1fr`, line box 20px) with
|
|
||||||
`##` headings in `#F0B476`. Preview: 18px/20px padding, max 68ch, Sans 13px/1.7 body,
|
|
||||||
Mono 700 headings with a 1px `#232C39` underline.
|
|
||||||
|
|
||||||
### 06 · Code colours and markdown preview
|
|
||||||
|
|
||||||
Four specimens at 620px: a JS module, a PHP class, a CSS file and the full markdown
|
|
||||||
preview. Each panel: 34px header with type badge, path Mono 500 12px, and a right
|
|
||||||
language label (or the Actual/Preview control).
|
|
||||||
|
|
||||||
The markdown preview is the reading surface, so it is the one place where Sans body copy
|
|
||||||
gets room:
|
|
||||||
- eyebrow: 10px mono label `#6C7783`
|
|
||||||
- h2: Mono 700 24px/1.1, `-0.03em`, `#F4F5F4`
|
|
||||||
- h3: Mono 700 17px/1.2 with a 1px `#232C39` underline, 8px below the text
|
|
||||||
- paragraph: Sans 14px/1.7 `#E4E7E6`, max 68ch, `text-wrap: pretty`
|
|
||||||
- list: flex rows, gap 10, `—` marker in `#E8913A` (never a bullet, never an emoji)
|
|
||||||
- inline code: Mono 13px `#F0B476` on `#18202B`, 1px `#232C39`, radius 2, padding 1px 5px
|
|
||||||
- block quote: 2px amber left rule, 16px left padding, Sans *italic* 15px `#F0B476`
|
|
||||||
- code block: `#18202B`, 1px `#232C39`, radius 2, padding 14px 16px, Mono 13px/20px,
|
|
||||||
syntax palette as above
|
|
||||||
- table: 1px `#232C39` container, radius 2; header row on `#18202B` with 10px mono
|
|
||||||
labels; body rows Sans 13px `#BAC0C0`, cells 10px 14px, 1px row rules; state words use
|
|
||||||
`#8FBFB4` (done) and `#E8913A` (open)
|
|
||||||
- link: `#E8913A` with a 1px `#232C39` bottom border; hover lifts the text to `#F4F5F4`
|
|
||||||
and the border to `#E8913A`. `→` marks forward action.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Interactions and behaviour
|
|
||||||
|
|
||||||
| Trigger | Result |
|
|
||||||
|---|---|
|
|
||||||
| `⌘F` | Search overlay, query seeded from the editor selection |
|
|
||||||
| `⌘↑` / `⌘↓` | Move the row cursor in the focused list |
|
|
||||||
| `⌘←` / `⌘→` | Move focus between search columns |
|
|
||||||
| `↵` | Open the selected row (search hit, file, recent project) |
|
|
||||||
| `⌘→` (editor) | Pass the current selection to the agent |
|
|
||||||
| `⌘M` | Cycle Actual · Original · Diff · Split |
|
|
||||||
| `⌘C` / `⌘↵` / `⌘P` (git) | Focus commit message / commit staged / push branch |
|
|
||||||
| `⌘A` | Toggle auto-fit panels (columns re-fit on resize and focus) |
|
|
||||||
| `⌘.` | Toggle hidden dotfiles in tree and search |
|
|
||||||
| `⌘G` | Show or hide the source-control column (same as the Git pane toggle) |
|
|
||||||
| Pane toggle click | Show or hide that column — see below |
|
|
||||||
| `⌘S` / `⌘W` / `⌘D` | Save / close / delete (confirm) the current file |
|
|
||||||
| right-click a row | Context menu, anchored to the pointer, first item pre-highlighted |
|
|
||||||
| `esc` | Close the top overlay, menu or prompt; never more than one |
|
|
||||||
|
|
||||||
**Pane visibility — strictly visibility.** A pane toggle only hides or shows its
|
|
||||||
column. It must never unmount, re-create or reset what is inside it:
|
|
||||||
- Keep every column mounted; hide with `display: none` (or equivalent), not by removing
|
|
||||||
it from the tree or rendering conditionally.
|
|
||||||
- The Claude Code session, the terminal process and its scrollback, the prompt draft,
|
|
||||||
the explorer's expanded state, the editor buffer, cursor and scroll position all
|
|
||||||
survive any number of hide/show cycles.
|
|
||||||
- No session restart, no PTY respawn, no re-fetch when a column comes back.
|
|
||||||
- Remaining columns reflow: the editor (flex) absorbs freed width; when the editor is
|
|
||||||
hidden the agent column grows to fill. All four may be off at once; the body then
|
|
||||||
shows the editor background.
|
|
||||||
- Persist the four flags per project.
|
|
||||||
|
|
||||||
Rules that hold everywhere:
|
|
||||||
- Exactly one overlay at a time, on a flat ink scrim. Overlays never stack.
|
|
||||||
- Hover changes fill one step and nothing else. No lift, no scale, no shadow, no opacity.
|
|
||||||
- Press holds the hover colour. Nothing shrinks.
|
|
||||||
- Focus is always the 2px amber border plus the 2px 22% ring. Never remove it.
|
|
||||||
- Disabled is 40% opacity plus `cursor: not-allowed`, no recolouring.
|
|
||||||
- Empty and error states are one plain sentence starting with an em dash. No icon, no
|
|
||||||
apology, no exclamation mark.
|
|
||||||
|
|
||||||
## State
|
|
||||||
|
|
||||||
- `project` — path, branch, recent list (persisted)
|
|
||||||
- `openFile` — path, language, dirty flag, cursor line/col, view mode
|
|
||||||
(`actual|original|diff|split`)
|
|
||||||
- `tree` — expanded paths, selected path, `showHidden`
|
|
||||||
- `git` — staged[], unstaged[], commit message draft, ahead/behind counts
|
|
||||||
- `agent` — model, session, transcript, prompt draft, pending tool calls, auth notices
|
|
||||||
- `overlay` — `null | search | shortcuts | diff | launcher | menu | passOn`
|
|
||||||
- `panels` — column widths, `autoFit`, and `visible: { git, explorer, file, claude }`
|
|
||||||
(all `true` by default, persisted per project)
|
|
||||||
|
|
||||||
Search runs per keystroke against three indexes (open file, project contents, file
|
|
||||||
names) and reports counts per column; a query with no hits leaves the columns in their
|
|
||||||
empty state rather than collapsing them.
|
|
||||||
|
|
||||||
## Assets
|
|
||||||
|
|
||||||
None. No images, no illustrations, no photography. Icons come from Lucide
|
|
||||||
(`lucide@0.544.0`, stroke width 1.75); the Unicode glyphs in the mock are placeholders.
|
|
||||||
Fonts are IBM Plex Mono and IBM Plex Sans (currently from Google Fonts — swap in local
|
|
||||||
woff2 for a desktop build).
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
- `Helder IDE.dc.html` — the design board: all screens, one canvas, real sizes
|
|
||||||
- `tokens/*.css` — the Kade token files the board is built on (colour, type, spacing,
|
|
||||||
radius, elevation, motion, fonts)
|
|
||||||
- `styles.css` — the token entry point
|
|
||||||
|
|
||||||
- `support.js` — the runtime the board needs to open in a browser (not part of the design)
|
|
||||||
|
|
||||||
Open `Helder IDE.dc.html` in a browser. The board is inert except for the four pane
|
|
||||||
toggles in the workspace title bar, which demonstrate the hide/show behaviour.
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
@import url("tokens/fonts.css");
|
|
||||||
@import url("tokens/colors.css");
|
|
||||||
@import url("tokens/typography.css");
|
|
||||||
@import url("tokens/spacing.css");
|
|
||||||
@import url("tokens/radius.css");
|
|
||||||
@import url("tokens/elevation.css");
|
|
||||||
@import url("tokens/motion.css");
|
|
||||||
@import url("tokens/base.css");
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
*,
|
|
||||||
*::before,
|
|
||||||
*::after { box-sizing: border-box; }
|
|
||||||
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
background: var(--color-stone);
|
|
||||||
color: var(--color-ink-body);
|
|
||||||
font-family: var(--font-body);
|
|
||||||
font-size: var(--text-base);
|
|
||||||
font-weight: var(--weight-body);
|
|
||||||
line-height: var(--leading-normal);
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
}
|
|
||||||
|
|
||||||
a { color: var(--color-amber-deep); text-decoration-color: var(--color-stone-rule); text-underline-offset: 3px; transition: var(--transition-color); }
|
|
||||||
a:hover { color: var(--color-ink-body); text-decoration-color: var(--color-ink-dim); }
|
|
||||||
[data-surface="slate"] a { color: var(--color-amber); }
|
|
||||||
[data-surface="slate"] a:hover { color: var(--color-neutral-1); }
|
|
||||||
|
|
||||||
::selection { background: var(--color-amber-ring); color: var(--color-ink-body); }
|
|
||||||
|
|
||||||
:focus-visible { outline: 2px solid var(--color-amber); outline-offset: 2px; }
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
/* Kade palette — cool stone paper, slate-ink dark punctuation, amber as the only accent. */
|
|
||||||
:root {
|
|
||||||
/* Stone — the default canvas. Cool, quarried, never white. */
|
|
||||||
--color-stone: #EFF0EE;
|
|
||||||
--color-stone-2: #E5E7E4;
|
|
||||||
--color-stone-3: #D8DBD7;
|
|
||||||
--color-stone-rule: #CDD1CD;
|
|
||||||
|
|
||||||
/* Ink ramp — text on stone. */
|
|
||||||
--color-ink-body: #171C22;
|
|
||||||
--color-ink-muted: #3A424C;
|
|
||||||
--color-ink-dim: #6B7480;
|
|
||||||
|
|
||||||
/* Slate — the sparing dark surface. One or two blocks per page. */
|
|
||||||
--color-slate: #101720;
|
|
||||||
--color-slate-2: #18202B;
|
|
||||||
--color-slate-3: #232C39;
|
|
||||||
|
|
||||||
/* Neutral ramp — text on slate. Pure white does not exist in this system. */
|
|
||||||
--color-neutral-1: #F4F5F4;
|
|
||||||
--color-neutral-2: #E4E7E6;
|
|
||||||
--color-neutral-3: #BAC0C0;
|
|
||||||
--color-neutral-4: #6C7783;
|
|
||||||
|
|
||||||
/* Amber — the single accent. Reserved for action, state and signal. */
|
|
||||||
--color-amber: #E8913A;
|
|
||||||
--color-amber-deep: #C4741F;
|
|
||||||
--color-amber-soft: #F0B476;
|
|
||||||
--color-amber-tint: rgba(232, 145, 58, 0.10);
|
|
||||||
--color-amber-ring: rgba(232, 145, 58, 0.22);
|
|
||||||
|
|
||||||
/* Semantic aliases — prefer these in component code. */
|
|
||||||
--surface-page: var(--color-stone);
|
|
||||||
--surface-card: var(--color-stone-2);
|
|
||||||
--surface-card-hover: var(--color-stone-3);
|
|
||||||
--surface-dark: var(--color-slate);
|
|
||||||
--surface-dark-card: var(--color-slate-2);
|
|
||||||
|
|
||||||
--text-body: var(--color-ink-body);
|
|
||||||
--text-muted: var(--color-ink-muted);
|
|
||||||
--text-dim: var(--color-ink-dim);
|
|
||||||
--text-accent: var(--color-amber-deep);
|
|
||||||
--text-on-accent: var(--color-ink-body);
|
|
||||||
|
|
||||||
--border-hairline: var(--color-stone-rule);
|
|
||||||
--border-strong: var(--color-ink-muted);
|
|
||||||
|
|
||||||
--action-fill: var(--color-amber);
|
|
||||||
--action-fill-hover: var(--color-amber-deep);
|
|
||||||
--focus-ring: var(--color-amber-ring);
|
|
||||||
--focus-border: var(--color-amber);
|
|
||||||
--signal-error: var(--color-amber-deep);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Slate scope — inside a dark block the ramps invert. Apply to the block, not the page. */
|
|
||||||
[data-surface="slate"] {
|
|
||||||
--surface-page: var(--color-slate);
|
|
||||||
--surface-card: var(--color-slate-2);
|
|
||||||
--surface-card-hover: var(--color-slate-3);
|
|
||||||
--text-body: var(--color-neutral-1);
|
|
||||||
--text-muted: var(--color-neutral-2);
|
|
||||||
--text-dim: var(--color-neutral-4);
|
|
||||||
--text-accent: var(--color-amber);
|
|
||||||
--border-hairline: var(--color-slate-3);
|
|
||||||
--border-strong: var(--color-neutral-3);
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
/* Elevation is carried by the stone ramp, not by shadow. Shadows exist only for layers that
|
|
||||||
cross the page plane (dropdown, modal) and for the amber focus ring. */
|
|
||||||
:root {
|
|
||||||
--shadow-none: none;
|
|
||||||
--shadow-dropdown: 0 4px 16px rgba(23, 28, 34, 0.10);
|
|
||||||
--shadow-modal: 0 16px 48px rgba(23, 28, 34, 0.18);
|
|
||||||
--ring-focus: 0 0 0 2px var(--color-amber-ring);
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/* Kade type stack — IBM Plex Mono (display + labels) and IBM Plex Sans (body + UI).
|
|
||||||
No licensed binaries shipped with the source skills, so the families load from Google Fonts.
|
|
||||||
Replace this @import with local @font-face rules once real woff2 files are supplied. */
|
|
||||||
@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;0,700;1,400&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap");
|
|
||||||
|
|
||||||
:root {
|
|
||||||
--font-display: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
||||||
--font-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
||||||
--font-body: "IBM Plex Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/* Colour shifts only. Kade never translates, lifts, or scales on hover. */
|
|
||||||
:root {
|
|
||||||
--ease-out: cubic-bezier(0.22, 1, 0.36, 1); /* @kind other */
|
|
||||||
--duration-fast: 120ms; /* @kind other */
|
|
||||||
--duration-base: 160ms; /* @kind other */
|
|
||||||
--duration-slow: 260ms; /* @kind other */
|
|
||||||
--transition-color: color var(--duration-base) var(--ease-out),
|
|
||||||
background-color var(--duration-base) var(--ease-out),
|
|
||||||
border-color var(--duration-base) var(--ease-out);
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/* Kade is rectangular. A rounded card is an antipattern. */
|
|
||||||
:root {
|
|
||||||
--radius-none: 0px;
|
|
||||||
--radius-sm: 2px;
|
|
||||||
--radius-md: 4px;
|
|
||||||
--radius-lg: 8px;
|
|
||||||
--radius-full: 9999px;
|
|
||||||
|
|
||||||
--border-width: 1px;
|
|
||||||
--border-width-accent: 2px;
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
/* 4px base step. Section rhythm is deliberately generous; the calm comes from air, not decoration. */
|
|
||||||
:root {
|
|
||||||
--space-1: 4px;
|
|
||||||
--space-2: 8px;
|
|
||||||
--space-3: 12px;
|
|
||||||
--space-4: 16px;
|
|
||||||
--space-5: 20px;
|
|
||||||
--space-6: 24px;
|
|
||||||
--space-8: 32px;
|
|
||||||
--space-10: 40px;
|
|
||||||
--space-12: 48px;
|
|
||||||
--space-16: 64px;
|
|
||||||
--space-20: 80px;
|
|
||||||
--space-24: 96px;
|
|
||||||
|
|
||||||
--gutter: var(--space-6);
|
|
||||||
--section-y: var(--space-24);
|
|
||||||
--section-y-tight: var(--space-16);
|
|
||||||
--container: 1140px;
|
|
||||||
--measure: 68ch;
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
/* One scale for display (Plex Mono 700) and body (Plex Sans). Line-height tightens as size grows. */
|
|
||||||
:root {
|
|
||||||
--text-2xs: 10px;
|
|
||||||
--text-xs: 11px;
|
|
||||||
--text-sm: 13px;
|
|
||||||
--text-base: 15px;
|
|
||||||
--text-md: 17px;
|
|
||||||
--text-lg: 20px;
|
|
||||||
--text-xl: 24px;
|
|
||||||
--text-2xl: 32px;
|
|
||||||
--text-4xl: 44px;
|
|
||||||
--text-6xl: 58px;
|
|
||||||
--text-7xl: 76px;
|
|
||||||
|
|
||||||
--leading-display: 1.02;
|
|
||||||
--leading-tight: 1.15;
|
|
||||||
--leading-snug: 1.3;
|
|
||||||
--leading-normal: 1.6;
|
|
||||||
--leading-loose: 1.7;
|
|
||||||
|
|
||||||
/* Plex Mono display tracking is negative; label tracking is wide. */
|
|
||||||
--tracking-display: -0.04em;
|
|
||||||
--tracking-heading: -0.02em;
|
|
||||||
--tracking-normal: 0;
|
|
||||||
--tracking-label: 0.14em;
|
|
||||||
|
|
||||||
--weight-body: 400;
|
|
||||||
--weight-medium: 500;
|
|
||||||
--weight-semibold: 600;
|
|
||||||
--weight-display: 700;
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,319 @@
|
|||||||
|
# Handoff: Helder App v2 — full-screen Git view
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
Helder is a desktop IDE shell for one developer working with Claude Code. It has a title bar, an Explorer (file tree), a File editor, a Claude transcript with prompt and terminal, a status bar, plus overlays for search and file diff.
|
||||||
|
|
||||||
|
**v2 replaces the old 264px Git sidebar with a full-screen Git view.** Press **⌘G** to toggle it. The view covers the whole window, the same way the file diff overlay does. In it the user can:
|
||||||
|
|
||||||
|
- see staged, changed, new (untracked) and deleted files, each in its own colour-coded section, with **Staged always on top**
|
||||||
|
- expand any file to see an inline side-by-side diff with collapsed context
|
||||||
|
- stage, unstage, discard, delete or restore files one at a time or in bulk
|
||||||
|
- write a commit message and commit, or commit and push
|
||||||
|
- pull and push, with ahead/behind counts
|
||||||
|
- read the real git commands and their output in a **console**, and type git commands there
|
||||||
|
- see local and remote **branches** and switch between them, but only when the working tree is clean
|
||||||
|
|
||||||
|
Everything outside the Git view works as it did in v1 (Explorer, File, Claude, terminal, search, diff, menus, modals). The only exceptions are the changed shortcuts listed below.
|
||||||
|
|
||||||
|
## About the design files
|
||||||
|
The files in this bundle are **design references created in HTML**. They are prototypes that show the intended look and behaviour; they are not production code to copy. The task is to **recreate this design in Helder's real codebase**, using its existing framework, state management and git layer. If no environment exists yet, pick the best fit; for a desktop IDE shell that is likely Electron or Tauri, with React and a real git backend such as `simple-git`, `isomorphic-git` or shelling out to `git`.
|
||||||
|
|
||||||
|
The prototype fakes git: file contents live in memory, and console output is simulated. The real build must run real git commands and stream their real stdout and stderr into the console.
|
||||||
|
|
||||||
|
## Fidelity
|
||||||
|
**High-fidelity.** Colours, type, spacing, states and copy are final. Recreate them pixel-precisely with the codebase's own components. The visual language is the Blijnder **Kade** design system in its dark (slate) application: IBM Plex Mono and IBM Plex Sans, flat fields, 2px radii, amber as the only accent, no shadows except on menus and modals.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Keyboard shortcuts (v2)
|
||||||
|
| Key | Action |
|
||||||
|
|---|---|
|
||||||
|
| ⌘G / Ctrl+G | Open or close the Git view |
|
||||||
|
| ⌘1 / ⌘2 / ⌘3 | Toggle Explorer / File / Claude (in v1 this was ⌘1–4, with Git on ⌘1) |
|
||||||
|
| ⌘F | Search the project |
|
||||||
|
| ⌘L | Fluid (soft wrap) |
|
||||||
|
| ⌘. | Show hidden files |
|
||||||
|
| ⌘N | Scratch note |
|
||||||
|
| ⌘↵ (in the commit message) | Commit |
|
||||||
|
| ↑ (in the console input) | Recall the last command |
|
||||||
|
| Esc | Closes the topmost layer, in this order: context menu → modal → search → file diff → Git view → interrupts Claude |
|
||||||
|
|
||||||
|
The title-bar panel toggle group now reads `Git N · Explorer · File · Claude`. **N** is the number of changed files, and the Git button's dot is amber while the view is open.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Screen: Git view (full screen)
|
||||||
|
|
||||||
|
A `position: fixed; inset: 0` layer, `z-index: 44`, background `#101720`, min-width 900px, laid out as a flex column. It sits above the app shell and below the file diff overlay (45), context menu (60/61), modal (70) and toast (80). This lets the confirm modals and the commit menu appear on top of it.
|
||||||
|
|
||||||
|
From top to bottom:
|
||||||
|
|
||||||
|
### 1. Top bar — 44px
|
||||||
|
- Background `#18202B`, bottom border `1px #232C39`, padding `0 14px`, flex row, gap 14px, items centred.
|
||||||
|
- **`[ GIT ]`**: Plex Mono 700, 11px, letter-spacing .14em, uppercase, `#828D9A`.
|
||||||
|
- **Branch**: Lucide `git-branch` icon at 13px, then the branch name. Plex Mono 500, 12px, `#E8913A`, truncated with an ellipsis.
|
||||||
|
- **Sync label**: Plex Mono 400, 12px, `#828D9A`. Text is `2 behind origin`, `1 ahead · 2 behind origin`, or `in sync with origin`.
|
||||||
|
- A flex spacer, then three buttons, each 28px tall:
|
||||||
|
- Shared style: padding `0 11px`, border `1px #232C39`, radius 2px, transparent background, Plex Sans 500 12px `#BAC0C0`, icon 14px, gap 7px.
|
||||||
|
- Hover: text `#F4F5F4`, border `#3A424C`.
|
||||||
|
- **Pull**: icon `arrow-down-to-line`, label `Pull` (`Pulling…` while busy), then the count `↓2` in Plex Mono 600 11px `#E8913A`. The count is hidden when 0.
|
||||||
|
- **Push**: icon `arrow-up-from-line`, label `Push` (`Pushing…` while busy), then the count `↑1` in the same amber style.
|
||||||
|
- **Close**: icon `minimize-2`, label `Close`, then the key hint `⌘G` in amber mono 11px.
|
||||||
|
|
||||||
|
### 2. Commit block
|
||||||
|
- Background `#18202B`, bottom border `1px #232C39`.
|
||||||
|
- **Message textarea**: full width, auto-grows (`field-sizing: content`) from 56px up to 180px.
|
||||||
|
- Background `#101720`, no border except a `1px #232C39` bottom border, which turns `#E8913A` on focus.
|
||||||
|
- Padding `14px 16px`, Plex Mono 400, 14px / 1.6, colour `#F4F5F4`, caret `#E8913A`.
|
||||||
|
- Placeholder: `Commit message`. The field gets focus when the Git view opens.
|
||||||
|
- **Footer row**: 52px tall, padding `0 14px 0 16px`, gap 16px.
|
||||||
|
- Author `Jonathan van Rij <jonathan@blijnder.nl>` in Plex Mono 12px `#828D9A`. In the real build, read this from `git config user.name` and `user.email`.
|
||||||
|
- Hint `⌘↵ commits` in Plex Mono 12px `#6C7783`.
|
||||||
|
- A spacer, then a **split button**, radius 2px, 32px tall:
|
||||||
|
- Main part: min-width 160px, padding `0 18px`, Plex Sans 600 13px.
|
||||||
|
- Label: `Commit N file(s)`, or `Nothing staged` when nothing is staged.
|
||||||
|
- Ready state (≥1 staged file **and** a non-empty message): background `#E8913A`, text `#101720`.
|
||||||
|
- Otherwise: background `#232C39`, text `#828D9A`. It stays clickable, so git's own error appears in the console.
|
||||||
|
- Caret part: 32×32px, `chevron-down` icon at 14px, separated from the main part by a `1px #101720` left border. It opens a context menu with `Commit` (icon `check`) and **`Commit and push`** (icon `arrow-up-from-line`, bold).
|
||||||
|
- Hover on either part: `filter: brightness(.92)`. (Real build: use amber-deep `#C4741F` instead, per Kade.)
|
||||||
|
|
||||||
|
### 3. File sections (scrolling area, `flex: 1`, padding-bottom 24px)
|
||||||
|
Sections appear in this fixed order, and only when they contain files:
|
||||||
|
|
||||||
|
| Section | Contains | Colour | Tint (header background) | Bulk actions (left column · right column) | Row actions (left · right) |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| **STAGED** | every staged path, any status | `#E8913A` | `rgba(232,145,58,.08)` | — · Unstage all | — · Unstage |
|
||||||
|
| **CHANGED** | unstaged, modified | `#F0B476` | `rgba(240,180,118,.06)` | Discard all · Stage all | Discard · Stage |
|
||||||
|
| **NEW · UNTRACKED** | unstaged, added | `#8FBFB4` | `rgba(143,191,180,.06)` | Delete all · Stage all | Delete · Stage |
|
||||||
|
| **DELETED** | unstaged, deleted | `#C3A6CE` | `rgba(195,166,206,.06)` | Restore all · Stage all | Restore · Stage |
|
||||||
|
|
||||||
|
The section right after Staged gets `margin-top: 28px` and a `1px #232C39` top border, which visually separates staged from unstaged work.
|
||||||
|
|
||||||
|
If there are no changes at all, the area shows only: `— No changes. The working tree is clean.` (Plex Sans 13px / 1.6, `#828D9A`, padding `24px 16px`).
|
||||||
|
|
||||||
|
**Section header**: 46px tall, padding `0 14px 0 11px`, a `3px` left border in the section colour, the tint background, and a `1px #232C39` bottom border. Hover background is `#18202B`. Clicking it collapses or expands the section. From left to right:
|
||||||
|
- Chevron at 14px: `chevron-down` in `#E8913A` when open, `chevron-right` in `#6C7783` when closed.
|
||||||
|
- Label: Plex Mono 700, 11px, .14em, uppercase, in the section colour.
|
||||||
|
- Count badge: Plex Mono 600 11px, text `#101720` on the section colour, radius 2px, padding `3px 6px`.
|
||||||
|
- A spacer, then the **actions table**.
|
||||||
|
|
||||||
|
**Actions table** (identical in headers and rows, so the buttons line up as columns): a CSS grid `grid-template-columns: 100px 100px; gap: 6px`. When a section has only one action (Staged), the left cell is an empty spacer, so `Unstage` always sits in the right column.
|
||||||
|
- **Header buttons**: 100×28px, border `1px #3A424C`, radius 2px, transparent background, Plex Sans 500 12px. Hover: border `#6C7783`, background `#232C39`.
|
||||||
|
- **Row buttons**: 100×26px, border transparent, background transparent. Hover: border `#3A424C`, background `#232C39`, text `#F4F5F4`.
|
||||||
|
- **Text colour**: destructive actions (Discard, Delete, and their "all" versions) use `#F0B476`; all others use `#BAC0C0`.
|
||||||
|
- Buttons stop propagation, so clicking one never expands the row.
|
||||||
|
|
||||||
|
**File row**: 36px tall, padding `0 14px 0 11px`, gap 10px, row bottom border `1px #232C39`.
|
||||||
|
- A 3px left border: `#E8913A` for rows in Staged, transparent elsewhere.
|
||||||
|
- Background `#18202B` when expanded, transparent otherwise. Hover background is `#1F2834`.
|
||||||
|
- Click toggles the inline diff; right-click opens the context menu (below).
|
||||||
|
- From left to right:
|
||||||
|
1. Chevron at 13px: `chevron-down` in `#E8913A` when expanded, otherwise `chevron-right` in `#6C7783`.
|
||||||
|
2. **Status badge**: 18×18px, radius 2px, filled with the status colour (M `#F0B476`, A `#8FBFB4`, D `#C3A6CE`), letter in Plex Mono 700 11px `#101720`. Tooltip: Modified / New file / Deleted.
|
||||||
|
3. **Path**: flex 1, ellipsis, Plex Mono 400 13px. The directory part plus `/` is `#828D9A`; the file name is `#F4F5F4`. Deleted files have a `line-through` and the name in `#828D9A`.
|
||||||
|
4. **Stats**, placed just left of the actions table:
|
||||||
|
- `+N` in a 52px right-aligned cell, Plex Mono 500 12px `#8FBFB4`.
|
||||||
|
- `−N` in a 52px right-aligned cell, Plex Mono 500 12px `#F0B476`, padding-right 8px. Use a real minus sign `−`.
|
||||||
|
5. The actions table.
|
||||||
|
|
||||||
|
**Row context menu**:
|
||||||
|
- `Open in editor` (bold, icon `file-text`; not shown for deleted files): closes the Git view and opens the file.
|
||||||
|
- Separator.
|
||||||
|
- `Pass on reference` (icon `sparkle`): closes the Git view and inserts `@path` into the Claude prompt.
|
||||||
|
- `Copy reference` (icon `files`).
|
||||||
|
|
||||||
|
### 4. Inline diff (inside an expanded row)
|
||||||
|
- A `1px #232C39` top border, padding `8px 0 12px`, Plex Mono 400 13px / 22px.
|
||||||
|
- Each line is a two-column grid, `minmax(0,1fr) minmax(0,1fr)`. Left is the last commit, right is the working tree. The left cell has a `1px #232C39` right border.
|
||||||
|
- **Each cell**:
|
||||||
|
- Line-number column: 52px wide, right-aligned, padding-right 12px, `user-select: none`.
|
||||||
|
- Code: `white-space: pre-wrap; word-break: break-word; tab-size: 4`, colour `#E4E7E6`.
|
||||||
|
- **Line types**:
|
||||||
|
|
||||||
|
| Type | Background | Line-number colour |
|
||||||
|
|---|---|---|
|
||||||
|
| Unchanged | transparent | `#3A424C` |
|
||||||
|
| Removed (left) | `rgba(232,145,58,.12)` | `#F0B476` |
|
||||||
|
| Added (right) | `rgba(143,191,180,.12)` | `#8FBFB4` |
|
||||||
|
| Empty filler (the side with no line) | `rgba(35,44,57,.35)` | — |
|
||||||
|
|
||||||
|
- **Intra-line highlight**: when a removed line is paired with an added line, compute their common prefix and suffix. Highlight the differing middle with a background of `rgba(232,145,58,.38)` on the left and `rgba(143,191,180,.36)` on the right. If they share no prefix or suffix, there is no highlight.
|
||||||
|
- **Hunking**: keep 3 lines of context around each change. Collapse any other run of unchanged lines into one separator row:
|
||||||
|
- 28px tall, `margin: 6px 0`, background `#18202B`, padding-left 64px.
|
||||||
|
- Text: `⋯ N unchanged lines` in Plex Mono 11px `#6C7783`.
|
||||||
|
- Added files show everything on the right; deleted files show everything on the left.
|
||||||
|
- The prototype uses an LCS line diff (`diffOps`). In production, use `git diff` hunks (`--unified=3`), or a proper diff library, and pair `-`/`+` runs line by line.
|
||||||
|
|
||||||
|
### 5. Bottom strip — 230px, split 50/50
|
||||||
|
- Background `#18202B`, top border `1px #232C39`.
|
||||||
|
- `display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr)`. The left half has a `1px #232C39` right border.
|
||||||
|
|
||||||
|
**Left — Console**
|
||||||
|
- **Header**: 32px tall, padding `0 12px 0 16px`.
|
||||||
|
- `[ CONSOLE ] GIT` in Plex Mono 700 10px, .14em, uppercase, `#6C7783`.
|
||||||
|
- Busy label: `→ pushing to origin…` or `→ pulling from origin…` in 12px `#E8913A`.
|
||||||
|
- A spacer, then the clear button (icon `eraser` at 14px, `#828D9A`, hover `#F4F5F4`).
|
||||||
|
- **Log**: scrolls, auto-scrolls to the bottom on every new line, padding `0 16px 12px`, Plex Mono 12px / 1.6, `pre-wrap`, `tab-size: 4`, max 400 lines kept.
|
||||||
|
- Command lines: `$ git …` in `#F4F5F4`.
|
||||||
|
- Normal output: `#BAC0C0`.
|
||||||
|
- Errors and rejections: `#E8913A`.
|
||||||
|
- Hints: `#828D9A`.
|
||||||
|
- Staged paths in `status`: `#8FBFB4`; unstaged and untracked paths: `#F0B476`.
|
||||||
|
- **Input line**: prompt `$ git` in `#8FBFB4`, then an input with no border, Plex Mono 12px `#F4F5F4`. Placeholder: `status · add -A · commit -m "…" · push · pull · log`. Clicking anywhere in the console focuses it, unless the user is selecting text. Enter runs the command; ↑ recalls the last one; `clear` empties the log. A leading `git ` is optional.
|
||||||
|
|
||||||
|
**Every UI action logs the exact git command it ran.** The prototype supports these commands, and the real build should simply run git:
|
||||||
|
- `status`
|
||||||
|
- `add <path|.|-A>`
|
||||||
|
- `restore --staged <path|.>`
|
||||||
|
- `restore <path>`
|
||||||
|
- `clean -f <path>`
|
||||||
|
- `commit -m "…"`
|
||||||
|
- `push`
|
||||||
|
- `pull`
|
||||||
|
- `log`
|
||||||
|
- `diff [--staged]`
|
||||||
|
- `branch [-a]`
|
||||||
|
- `switch <name>` / `checkout <name>`
|
||||||
|
|
||||||
|
**Right — Branches**
|
||||||
|
- **Header**: 32px tall, padding `0 16px`.
|
||||||
|
- `[ BRANCHES ]` in the same style as the console header.
|
||||||
|
- Right side, 12px mono: `clean · click to switch` in `#828D9A`, or `— N uncommitted files · switching locked` in `#F0B476`.
|
||||||
|
- **List**: scrolls, with two groups. Group labels are Plex Mono 700 10px, .14em, uppercase, `#6C7783`, padding `8px 16px 4px`:
|
||||||
|
- **LOCAL**: local branches.
|
||||||
|
- **REMOTE · ORIGIN**: `origin/*` branches.
|
||||||
|
- **Branch row**: 28px tall, padding `0 16px 0 13px`, a 3px left border, gap 10px, hover background `#232C39`. From left to right:
|
||||||
|
- Icon at 13px: `git-branch` for local branches, `cloud` for remote ones.
|
||||||
|
- Name: Plex Mono 12px, ellipsis.
|
||||||
|
- Meta text: 11px `#6C7783`.
|
||||||
|
- Action text: 11px Plex Mono 600 `#E8913A`.
|
||||||
|
- **States**:
|
||||||
|
|
||||||
|
| State | Left border | Background | Name | Icon | Meta | Action | Cursor / opacity |
|
||||||
|
|---|---|---|---|---|---|---|---|
|
||||||
|
| Current | `#E8913A` | `rgba(232,145,58,.08)` | 600, `#F4F5F4` | `#E8913A` | `current` | — | default cursor |
|
||||||
|
| Other, tree clean | transparent | transparent | 400, `#BAC0C0` | `#6C7783` | `tracked` on remotes that already have a local branch | `switch →`, or `checkout →` for a remote with no local branch | pointer |
|
||||||
|
| Other, tree dirty | transparent | transparent | 400, `#BAC0C0` | `#6C7783` | — | — | 40% opacity, `not-allowed` cursor |
|
||||||
|
|
||||||
|
Tooltip on the dirty state: `Commit or discard your changes first`.
|
||||||
|
- **Switch rules**:
|
||||||
|
- "Dirty" means there is at least one changed file, staged or not.
|
||||||
|
- Clicking a branch while dirty only shows the toast `— Commit or discard N files before you switch.` Typing `git switch` while dirty logs git's real error: `error: Your local changes to N files would be overwritten by checkout.` / `Please commit your changes or stash them before you switch branches.` / `Aborting`.
|
||||||
|
- When clean, switching to a local branch runs `git switch <name>`.
|
||||||
|
- Switching to a remote branch with no local branch runs `git switch <name>`, which auto-creates a tracking branch. It logs `branch '<name>' set up to track 'origin/<name>'.` and `Switched to a new branch '<name>'`, then adds the branch to the local list.
|
||||||
|
- After a switch: the title bar, status bar and Git top bar show the new branch; ahead/behind are recalculated; expanded diffs are cleared; a toast reads `Switched to <name>`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Interactions & behaviour
|
||||||
|
|
||||||
|
**Stage / unstage**
|
||||||
|
- Stage runs `git add <paths>`; when all unstaged paths are staged at once, it logs `git add -A`.
|
||||||
|
- Unstage runs `git restore --staged <paths>`, or `.` when everything is unstaged.
|
||||||
|
- Each file moves between sections immediately.
|
||||||
|
|
||||||
|
**Discard / delete / restore**
|
||||||
|
- Modified files: `git restore <paths>`. New files: `git clean -f <paths>`, which logs `Removing <path>` per file.
|
||||||
|
- Modified and new files open a confirm modal first:
|
||||||
|
- Title: `Discard changes to <path|N files>?`, or `Delete <path|N files>?` when every file is new.
|
||||||
|
- Body: `This reverts to the last commit and cannot be undone.`, or `New files are removed from disk. This cannot be undone.` when the batch includes new files.
|
||||||
|
- Confirm button: `Discard` or `Delete` (amber). Enter confirms, Esc cancels.
|
||||||
|
- Restoring deleted files is not destructive, so it runs at once without a modal.
|
||||||
|
|
||||||
|
**Commit**
|
||||||
|
- Validation runs through git and shows in the console:
|
||||||
|
- Nothing staged: `no changes added to commit (use "git add" and/or "git commit -a")`, or `nothing to commit, working tree clean`.
|
||||||
|
- Empty message: `Aborting commit due to empty commit message.`, and the message field gets focus.
|
||||||
|
- On success the console shows:
|
||||||
|
- `[<branch> <sha>] <first line>`
|
||||||
|
- ` N files changed, X insertions(+), Y deletions(-)`
|
||||||
|
- ` create mode 100644 <path>` / ` delete mode 100644 <path>` for added and deleted files
|
||||||
|
- After a commit: the message clears, the staged section disappears, ahead increases by 1, and the commit is added to `git log`.
|
||||||
|
- **Commit and push** pushes right after a successful commit.
|
||||||
|
|
||||||
|
**Push**
|
||||||
|
- Ahead 0: `Everything up-to-date`.
|
||||||
|
- Behind > 0: rejected (all in `#E8913A` except the hints):
|
||||||
|
- ` ! [rejected] <br> -> <br> (fetch first)`
|
||||||
|
- `error: failed to push some refs to '…'`
|
||||||
|
- Two hint lines in `#828D9A`: `hint: Updates were rejected because the remote contains work that you do not` / `hint: have locally. Pull first, then push again.`
|
||||||
|
- Otherwise the console shows the real progress output (`Enumerating…`, `Writing objects…`, `To …`) and ends with ` <old>..<new> <br> -> <br>` in `#8FBFB4`. Then ahead becomes 0 and a toast confirms.
|
||||||
|
- While busy the button reads `Pushing…` and further push/pull clicks are ignored.
|
||||||
|
|
||||||
|
**Pull**
|
||||||
|
- Behind 0: `Already up to date.`
|
||||||
|
- Otherwise: `From …`, then a fast-forward (`Updating a..b`, `Fast-forward`, and a diffstat), or `Merge made by the 'ort' strategy.` when ahead > 0, which creates a merge commit. Then behind becomes 0 and a toast reads `Pulled N commits from origin/<br>`.
|
||||||
|
- In the real build, refresh the file list after a pull.
|
||||||
|
|
||||||
|
**Other details**
|
||||||
|
- On open, the prototype seeds the console with `git fetch origin` output; this is what makes it show "2 behind". In the real build, run a background fetch when the view opens, or every few minutes, to keep the ahead/behind counts honest.
|
||||||
|
- Toasts appear at the bottom centre: background `#232C39`, border `1px #3A424C`, radius 2px, Plex Mono 13px, prefix `→ ` in amber, hidden after 2.4s.
|
||||||
|
- **Motion**: colour transitions only, 120–160ms on `cubic-bezier(0.22,1,0.36,1)`. Nothing slides or scales.
|
||||||
|
|
||||||
|
## State (Git view)
|
||||||
|
```
|
||||||
|
gitOpen: boolean // ⌘G
|
||||||
|
gitSec: { [sectionKey]: boolean } // false = collapsed (default: open)
|
||||||
|
gitOpenFiles: string[] // expanded rows, key = `${section}:${path}`
|
||||||
|
commitMsg: string
|
||||||
|
staged: string[] // staged paths (real build: from `git status --porcelain=v2`)
|
||||||
|
files: { [path]: { orig, content } } // prototype only — replace with git status + git diff
|
||||||
|
BR: string // current branch
|
||||||
|
branches: string[]; remotes: string[] // `git branch`, `git branch -r`
|
||||||
|
ahead: number; behind: number // `git rev-list --left-right --count HEAD...@{u}`
|
||||||
|
commits: { sha, msg }[]
|
||||||
|
gBusy: null | 'push' | 'pull'
|
||||||
|
glog: { t: string, c: color }[] // console lines, cap 400
|
||||||
|
gInput: string; gHist: string[] // console input + history
|
||||||
|
```
|
||||||
|
**Derived values**:
|
||||||
|
- File status: M if `orig ≠ content`, A if `orig === null`, D if `content === null`.
|
||||||
|
- `unstaged` = changed minus staged. Sections come from status plus staged membership.
|
||||||
|
- `dirty` = changed.length > 0; it locks branch switching.
|
||||||
|
|
||||||
|
## Design tokens used
|
||||||
|
- **Slate surfaces**:
|
||||||
|
- `#101720`: page, editor, diff, message field
|
||||||
|
- `#18202B`: bars, panels, expanded row, separators
|
||||||
|
- `#1F2834`: row hover
|
||||||
|
- `#232C39`: rules, hover fills, disabled button
|
||||||
|
- `#2B3544`: menu border
|
||||||
|
- `#3A424C`: strong rule, button border, unchanged line numbers
|
||||||
|
- **Text**:
|
||||||
|
- `#F4F5F4`: primary
|
||||||
|
- `#E4E7E6`: code
|
||||||
|
- `#BAC0C0`: secondary
|
||||||
|
- `#828D9A`: muted
|
||||||
|
- `#6C7783`: faint
|
||||||
|
- **Accent**: `#E8913A` (amber), `#C4741F` (amber-deep, hover), `#F0B476` (amber-soft).
|
||||||
|
- **Status**:
|
||||||
|
- Modified `#F0B476`, New `#8FBFB4` (teal), Deleted `#C3A6CE` (lilac), Staged `#E8913A`.
|
||||||
|
- Teal and lilac already exist in Helder's v1 vocabulary (diff colours and the php badge). They are app-level additions outside the core Kade palette.
|
||||||
|
- **Type**:
|
||||||
|
- IBM Plex Mono (400/500/600/700) and IBM Plex Sans (400/500/600).
|
||||||
|
- Sizes used: 10, 11, 12, 13, 14px.
|
||||||
|
- Label style: 700, letter-spacing .14em, uppercase, written lowercase in source and in brackets, e.g. `[ console ] git`.
|
||||||
|
- **Radius**: 2px for buttons, badges and inputs; 4px for menus; 8px for modals.
|
||||||
|
- **Shadows**: only for menus `0 4px 16px rgba(16,23,32,.45)` and modals `0 16px 48px rgba(16,23,32,.5)`.
|
||||||
|
- **Spacing**: 4px steps. Common values are 6, 8, 10, 12, 14 and 16px.
|
||||||
|
|
||||||
|
## Assets
|
||||||
|
- **Icons**: Lucide 0.544.0 at stroke width 1.75, through the Kade `Icon` component. Used here:
|
||||||
|
- `git-branch`, `cloud`
|
||||||
|
- `arrow-down-to-line`, `arrow-up-from-line`
|
||||||
|
- `minimize-2`, `chevron-down`, `chevron-right`
|
||||||
|
- `eraser`, `check`, `file-text`, `sparkle`, `files`
|
||||||
|
- **Fonts**: IBM Plex Mono and IBM Plex Sans (Google Fonts, through the Kade `tokens/fonts.css`).
|
||||||
|
- There are no images.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
- `Helder App v2.dc.html`: the full prototype. Open it in a browser next to `support.js`; it loads the Kade tokens and bundle from `_ds/blijnder-e2fd6583-1c87-4e16-bc91-117f035adbbc/` in the source project.
|
||||||
|
- **Where to look in the file**:
|
||||||
|
|
||||||
|
| What | Where |
|
||||||
|
|---|---|
|
||||||
|
| Git view markup | the `<!-- git overlay -->` block |
|
||||||
|
| Git logic | methods prefixed `g…`: `gStage`, `gUnstage`, `gDiscard`, `gCommit`, `gPush`, `gPull`, `gSwitch`, `gStatus`, `gRun`, `gitRows` |
|
||||||
|
| Section, row and branch view models | `renderVals()`, from `const GC` to `brGroups` |
|
||||||
|
|
||||||
|
- `support.js`: the prototype runtime, needed only to open the HTML. Do not port it.
|
||||||
@@ -79,16 +79,16 @@ Example `config.json`:
|
|||||||
| `editor.tabSize` | `4` | Spaces per indent step for `Tab` and `Shift+Tab`. Helder indents with spaces |
|
| `editor.tabSize` | `4` | Spaces per indent step for `Tab` and `Shift+Tab`. Helder indents with spaces |
|
||||||
| `editor.wordWrap` | `"markdown"` | Fold long lines: `"off"` never, `"on"` always, `"markdown"` only in Markdown files. The Diff never wraps |
|
| `editor.wordWrap` | `"markdown"` | Fold long lines: `"off"` never, `"on"` always, `"markdown"` only in Markdown files. The Diff never wraps |
|
||||||
|
|
||||||
### git: the Git column
|
### git: the Git view
|
||||||
|
|
||||||
| Setting | Default | Effect |
|
| Setting | Default | Effect |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `git.confirmDiscard` | `true` | Ask before Discard changes |
|
| `git.confirmDiscard` | `true` | Ask before Discard and Delete in the Git view. Restore never asks |
|
||||||
| `git.confirmStage` | `false` | Ask before staging a file |
|
|
||||||
| `git.confirmUnstage` | `false` | Ask before unstaging a file |
|
|
||||||
| `git.defaultDiffMode` | `"updated"` | How a changed file opens: `"updated"` on the live file, `"diff"` in the full-screen Diff |
|
| `git.defaultDiffMode` | `"updated"` | How a changed file opens: `"updated"` on the live file, `"diff"` in the full-screen Diff |
|
||||||
| `git.refreshInterval` | `10000` | Milliseconds between automatic git status checks. `0` turns the check off. File watching still works |
|
| `git.refreshInterval` | `10000` | Milliseconds between automatic git status checks. `0` turns the check off. File watching still works |
|
||||||
|
|
||||||
|
`git.confirmStage` and `git.confirmUnstage` are gone: staging never asks. An older `config.json` that still has them loads fine; Helder ignores them.
|
||||||
|
|
||||||
### files: the Explorer and search
|
### files: the Explorer and search
|
||||||
|
|
||||||
| Setting | Default | Effect |
|
| Setting | Default | Effect |
|
||||||
|
|||||||
+10
-13
@@ -12,8 +12,8 @@ Helder asks you something in three ways: a confirm dialog before a risky action,
|
|||||||
|////////// +------------------------------------------------+ ////////////|
|
|////////// +------------------------------------------------+ ////////////|
|
||||||
|////////// | (1) Discard changes to app/Http/User.php? | ////////////|
|
|////////// | (1) Discard changes to app/Http/User.php? | ////////////|
|
||||||
|////////// | | ////////////|
|
|////////// | | ////////////|
|
||||||
|////////// | (2) This reverts the file to the last commit | ////////////|
|
|////////// | (2) This reverts to the last commit and | ////////////|
|
||||||
|////////// | and cannot be undone. | ////////////|
|
|////////// | cannot be undone. | ////////////|
|
||||||
|////////// | | ////////////|
|
|////////// | | ////////////|
|
||||||
|////////// | (3)[ Cancel esc ] (4)[ Discard enter ] | ////////////|
|
|////////// | (3)[ Cancel esc ] (4)[ Discard enter ] | ////////////|
|
||||||
|////////// +------------------------------------------------+ ////////////|
|
|////////// +------------------------------------------------+ ////////////|
|
||||||
@@ -24,7 +24,7 @@ Helder asks you something in three ways: a confirm dialog before a risky action,
|
|||||||
1. **Title**: the question, often with the path it is about.
|
1. **Title**: the question, often with the path it is about.
|
||||||
2. **Body**: what will happen. Not every confirm dialog has one.
|
2. **Body**: what will happen. Not every confirm dialog has one.
|
||||||
3. **Cancel**: closes the dialog and does nothing. Its key is `Esc`.
|
3. **Cancel**: closes the dialog and does nothing. Its key is `Esc`.
|
||||||
4. **Confirm button**: amber-deep, named after the action (Discard, Delete, Stage, Unstage). Its key is `Enter`.
|
4. **Confirm button**: amber-deep, named after the action (Discard or Delete). Its key is `Enter`.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -39,19 +39,18 @@ Helder shows a confirm dialog for these actions:
|
|||||||
|
|
||||||
| Action | Title | Body | Button | When |
|
| Action | Title | Body | Button | When |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| Discard changes | `Discard changes to <path>?` | `This reverts the file to the last commit and cannot be undone.` | Discard | When `git.confirmDiscard` is on (default) |
|
| Discard (Git view) | `Discard changes to <path>?` | `This reverts to the last commit and cannot be undone.` | Discard | When `git.confirmDiscard` is on (default) |
|
||||||
| Stage changes | `Stage <path>?` | none | Stage | Only when `git.confirmStage` is on |
|
| Delete (Git view, new files) | `Delete <path>?` | `New files are removed from disk. This cannot be undone.` | Delete | When `git.confirmDiscard` is on (default) |
|
||||||
| Unstage changes | `Unstage <path>?` | none | Unstage | Only when `git.confirmUnstage` is on |
|
|
||||||
| Delete file | `Delete file?` | `<path> will be permanently deleted.` | Delete | Always |
|
| Delete file | `Delete file?` | `<path> will be permanently deleted.` | Delete | Always |
|
||||||
| Delete folder | `Delete folder?` | `<path>/ and everything inside it will be permanently deleted.` | Delete | Always |
|
| Delete folder | `Delete folder?` | `<path>/ and everything inside it will be permanently deleted.` | Delete | Always |
|
||||||
|
|
||||||
#### Discard changes
|
#### Discard changes
|
||||||
|
|
||||||
Comes from **Discard changes** on a [Git](git.md) row. On confirm, the file goes back to the last commit, both its staged and unstaged changes. A new file is deleted. An open copy in the [File view](file-view.md) reloads. A [notification](notifications.md) says `Discarded changes`.
|
Comes from **Discard** or **Delete** in the [Git](git.md) view, on a row or as **Discard all** / **Delete all** on a section. With more than one file, the title names the count instead of a path, for example `Discard changes to 3 files?`. When the files include a new file, the body says `New files are removed from disk. This cannot be undone.`
|
||||||
|
|
||||||
#### Stage and unstage
|
On confirm, a changed file loses its unstaged changes: it goes back to its staged version, or to the last commit when nothing is staged. A new file is deleted from disk. An open copy in the [File view](file-view.md) reloads.
|
||||||
|
|
||||||
Come from the hover `+` / `−` on a git row, or from the [right-click menu](right-click-menu.md#git-rows), but only when you turned the matching setting on. **Stage all** and **Unstage all** never ask.
|
**Restore** on a deleted file never asks. Stage and unstage never ask either.
|
||||||
|
|
||||||
#### Delete file or folder
|
#### Delete file or folder
|
||||||
|
|
||||||
@@ -151,15 +150,13 @@ With `editor.autoSave` on, opening another file saves the open one silently, wit
|
|||||||
|
|
||||||
| Setting | Default | Effect |
|
| Setting | Default | Effect |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `git.confirmDiscard` | `true` | Ask before Discard changes |
|
| `git.confirmDiscard` | `true` | Ask before Discard and Delete in the Git view |
|
||||||
| `git.confirmStage` | `false` | Ask before staging one file |
|
|
||||||
| `git.confirmUnstage` | `false` | Ask before unstaging one file |
|
|
||||||
| `editor.autoSave` | `false` | Save the open file silently instead of asking, when you open another file |
|
| `editor.autoSave` | `false` | Save the open file silently instead of asking, when you open another file |
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [Right-click menu](right-click-menu.md): where most of these dialogs start.
|
- [Right-click menu](right-click-menu.md): where most of these dialogs start.
|
||||||
- [Git](git.md): discard, stage and unstage.
|
- [Git](git.md): discard and delete.
|
||||||
- [Explorer](explorer.md): new, rename and delete.
|
- [Explorer](explorer.md): new, rename and delete.
|
||||||
- [File view](file-view.md): saving, and the unsaved-edits dot.
|
- [File view](file-view.md): saving, and the unsaved-edits dot.
|
||||||
- [Notifications](notifications.md): the message after each action.
|
- [Notifications](notifications.md): the message after each action.
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ The Explorer is the project's file tree. It is the second column from the left,
|
|||||||
- Click a folder to expand it. Click it again to collapse it.
|
- Click a folder to expand it. Click it again to collapse it.
|
||||||
- Each click also re-reads that folder from disk, so files the agent just added show up.
|
- Each click also re-reads that folder from disk, so files the agent just added show up.
|
||||||
- A project opens with every folder collapsed.
|
- A project opens with every folder collapsed.
|
||||||
- Opening a file from anywhere (Git column, [Go to file](go-to-file.md), [Search](search.md)) expands its folders and highlights it in the tree.
|
- Opening a file from anywhere (the [Git](git.md) view, [Go to file](go-to-file.md), [Search](search.md)) expands its folders and highlights it in the tree.
|
||||||
- Folders come first, then files, each sorted by name. Case does not matter in the sort.
|
- Folders come first, then files, each sorted by name. Case does not matter in the sort.
|
||||||
|
|
||||||
### Icons
|
### Icons
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ The Diff is a full-screen, side-by-side comparison of a changed file. It covers
|
|||||||
### Open the Diff
|
### Open the Diff
|
||||||
- Click **Diff** in the [file view](file-view.md) bar. The button shows only on a file with git changes.
|
- Click **Diff** in the [file view](file-view.md) bar. The button shows only on a file with git changes.
|
||||||
- Right-click a marked (teal) line in the file view and choose **Show diff**. The Diff opens centred on that line.
|
- Right-click a marked (teal) line in the file view and choose **Show diff**. The Diff opens centred on that line.
|
||||||
- Right-click a row in [Git](git.md) and choose **Open diff**.
|
- Show diff on a marked line always compares the last commit with the file on disk.
|
||||||
- A file you open from a Git row remembers that row. The **Diff** button then shows that row's half (staged or unstaged). Show diff on a marked line always compares the last commit with the file on disk.
|
- The [Git](git.md) view has its own inline diff per file row. **Open in editor** on a row opens the file; click **Diff** there for the full-screen view.
|
||||||
|
|
||||||
### Layout
|
### Layout
|
||||||
- The Diff covers all columns. The window's shortcuts still work over it.
|
- The Diff covers all columns. The window's shortcuts still work over it.
|
||||||
@@ -95,6 +95,6 @@ The Diff is a full-screen, side-by-side comparison of a changed file. It covers
|
|||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [File view](file-view.md): the live view with teal line marks, where **Show diff** opens the Diff.
|
- [File view](file-view.md): the live view with teal line marks, where **Show diff** opens the Diff.
|
||||||
- [Git](git.md): the changes, the staged and unstaged halves, and **Open diff**.
|
- [Git](git.md): the Git view, with an inline diff per changed file.
|
||||||
- [Pass on to Agent](pass-on-to-agent.md): the reference format and the prompt.
|
- [Pass on to Agent](pass-on-to-agent.md): the reference format and the prompt.
|
||||||
- [Right-click menu](right-click-menu.md): the menus across Helder.
|
- [Right-click menu](right-click-menu.md): the menus across Helder.
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ The file view is the third column (Col C), between the [Explorer](explorer.md) a
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
### Open a file
|
### Open a file
|
||||||
- Click a file in the [Explorer](explorer.md) or a row in [Git](git.md), pick a result in [Search](search.md), or use [Go to file](go-to-file.md).
|
- Click a file in the [Explorer](explorer.md), choose **Open in editor** on a row in the [Git](git.md) view, pick a result in [Search](search.md), or use [Go to file](go-to-file.md).
|
||||||
- The new file replaces the one that was open. Helder shows one file at a time.
|
- The new file replaces the one that was open. Helder shows one file at a time.
|
||||||
- A file always opens fresh from disk.
|
- A file always opens fresh from disk.
|
||||||
- When you open a file at a line (from Search or the [symbol popup](code-symbols.md)), that line moves to the middle of the pane and flashes amber for about a second.
|
- When you open a file at a line (from Search or the [symbol popup](code-symbols.md)), that line moves to the middle of the pane and flashes amber for about a second.
|
||||||
@@ -53,7 +53,7 @@ The file view is the third column (Col C), between the [Explorer](explorer.md) a
|
|||||||
- Type to edit. Undo and redo work as usual (`Cmd+Z`, `Cmd+Shift+Z`).
|
- Type to edit. Undo and redo work as usual (`Cmd+Z`, `Cmd+Shift+Z`).
|
||||||
- `Cmd+S` saves the file. A "Saved" [notification](notifications.md) confirms it. If the write fails, you see "Save failed" and the file stays open with your edits.
|
- `Cmd+S` saves the file. A "Saved" [notification](notifications.md) confirms it. If the write fails, you see "Save failed" and the file stays open with your edits.
|
||||||
- `Cmd+S` on a file without edits does nothing.
|
- `Cmd+S` on a file without edits does nothing.
|
||||||
- After a save, the [Git](git.md) column updates.
|
- After a save, git re-reads, so the [Git](git.md) view and the status bar update.
|
||||||
|
|
||||||
### Auto-save
|
### Auto-save
|
||||||
- Auto-save is off by default. Turn it on with `editor.autoSave` in the [configuration](configuration.md).
|
- Auto-save is off by default. Turn it on with `editor.autoSave` in the [configuration](configuration.md).
|
||||||
|
|||||||
@@ -1,98 +1,76 @@
|
|||||||
# Git commit form
|
# Git commit form
|
||||||
|
|
||||||
The commit form sits at the foot of the [Git](git.md) column, edge to edge. It holds the commit message field, the Commit button and the Push button.
|
The commit form is the block at the top of the [Git](git.md) view, under its top bar. It holds the commit message, the author, and the Commit split button.
|
||||||
|
|
||||||
[Guide index](index.md) · Related: [Git](git.md), [Notifications](notifications.md), [Keyboard shortcuts](keyboard-shortcuts.md)
|
[Guide index](index.md) · Related: [Git](git.md), [Notifications](notifications.md), [Keyboard shortcuts](keyboard-shortcuts.md)
|
||||||
|
|
||||||
## At a glance
|
## At a glance
|
||||||
|
|
||||||
```text
|
```text
|
||||||
+-------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
| (1) Shift+Enter to commit |
|
| (1) fix the login form_ |
|
||||||
| |
|
|----------------------------------------------------------------------------|
|
||||||
| |
|
| (2) Jonathan <jonathan@example.com> (3) Cmd+Enter commits |
|
||||||
|-------------------------------------|
|
| (4) [ Commit 2 files | v ] |
|
||||||
| (2) Commit ^ | (3)^ |
|
+----------------------------------------------------------------------------+
|
||||||
+-------------------------------------+
|
(5)
|
||||||
|
+------------------------+
|
||||||
|
| v Commit |
|
||||||
|
| ^ Commit and push |
|
||||||
|
+------------------------+
|
||||||
```
|
```
|
||||||
|
|
||||||
1. **Message field**: one line of commit message. The grey hint `Shift+Enter to commit` shows while it is empty.
|
1. **Message field**: the commit message. The grey placeholder `Commit message` shows while it is empty.
|
||||||
2. **Commit button**: amber when there is something staged.
|
2. **Author**: `user.name <user.email>` from your git config, read when the view opens. With no email set, only the name shows; with no name, nothing.
|
||||||
3. **Push button**: a narrow button with an up arrow. It lights up when the branch has commits to push.
|
3. **Hint**: `⌘↵ commits`.
|
||||||
|
4. **Commit button**: `Commit N files`, or `Nothing staged`. The caret on its right opens the menu.
|
||||||
|
5. **Commit menu**: **Commit** and **Commit and push**.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### Write the message
|
### Write the message
|
||||||
|
- Opening the [Git](git.md) view puts the cursor in the field. `Cmd+C` with no text selected, outside a terminal, opens the view there too.
|
||||||
- Click the field, or press `Cmd+C` anywhere outside a terminal with no text selected. `Cmd+C` also shows the [Git](git.md) column when it is hidden.
|
- The field gets an amber line under it while it has the cursor.
|
||||||
- The focused field gets an amber outline.
|
- The field grows with long text and scrolls after about seven lines.
|
||||||
- A commit message in Helder is always **one lowercase line**:
|
- A commit message in Helder is always **one lowercase line**:
|
||||||
- Capitals become lowercase as you type or paste.
|
- Capitals become lowercase as you type or paste.
|
||||||
- A line break becomes a space. Pressing `Enter` on its own does not start a new line.
|
- A line break becomes a space. `Enter` does not start a new line, and it does not commit.
|
||||||
- This keeps dictated or pasted text as one short subject line.
|
- This keeps dictated or pasted text as one short subject line.
|
||||||
- The draft stays in the field while you work elsewhere in the window.
|
- The draft stays in the field while the view is closed.
|
||||||
|
|
||||||
### Commit
|
### Commit
|
||||||
|
|
||||||
You can commit in three ways:
|
You can commit in three ways:
|
||||||
|
|
||||||
- Click **Commit**.
|
- Click **Commit N files**.
|
||||||
- Press `Shift+Enter` (or `Cmd+Enter`, or `Ctrl+Enter`) in the message field.
|
- Choose **Commit** from the caret menu.
|
||||||
- Press `Cmd+Enter` anywhere in the window.
|
- Press `Cmd+Enter` while the view is open. This works from the message field too, but not from the console input.
|
||||||
|
|
||||||
A commit only happens when both are true:
|
The button is amber when at least one file is staged and the message is not empty. Otherwise it is grey. A click always runs `git commit`, also when the button is grey, so git's own refusal shows in the [console](git.md#console).
|
||||||
|
|
||||||
- At least one file is staged.
|
### Commit and push
|
||||||
- The message is not empty (spaces alone do not count).
|
- Choose **Commit and push** from the caret menu. It commits, and when the commit succeeds it pushes, the same as the **Push** button. See [Pull and push](git.md#pull-and-push).
|
||||||
|
|
||||||
The **Commit** button follows the first rule only. It is amber when something is staged and grey and disabled when nothing is. With files staged but an empty message, the button looks ready but a click does nothing. Type a message first.
|
|
||||||
|
|
||||||
### After a commit
|
### After a commit
|
||||||
|
|
||||||
- The message field clears.
|
- The message field clears.
|
||||||
- The committed files leave **Staged Changes**. Unstaged edits stay in **Changes**.
|
- The committed files leave the **staged** section. Unstaged edits stay where they were.
|
||||||
- A [notification](notifications.md) says `Committed N files`, with the start of your message below it (cut off after 34 characters).
|
- A [notification](notifications.md) says `Committed N files`, with the start of your message below it (cut off after 34 characters).
|
||||||
- The Push button lights up, because the branch is now ahead of its remote.
|
- **Push** in the top bar shows `↑N`, because the branch is now ahead of its remote.
|
||||||
|
|
||||||
### When a commit fails
|
### When a commit fails
|
||||||
|
- Your message stays in the field, so you can fix and retry.
|
||||||
- Your message comes back in the field, so you can fix and retry.
|
- A notification says `Commit failed`, with git's first error line below it. The full output is in the console. Typical causes are nothing staged, an empty message, or a git hook that rejected the commit.
|
||||||
- A notification says `Commit failed`, with git's own error text below it. A typical cause is a git hook that rejected the commit.
|
- When the message was empty, the cursor goes back to the field.
|
||||||
|
|
||||||
### Push
|
|
||||||
|
|
||||||
- Click the **Push** button right of Commit, or press `Cmd+P`.
|
|
||||||
- The button is **lit** (amber arrow on an amber tint) when there is something to push:
|
|
||||||
- The branch is ahead of its remote branch, or
|
|
||||||
- The branch has no remote branch yet.
|
|
||||||
- It is grey when there is nothing to push. A click still runs the push; git then reports it is up to date.
|
|
||||||
- Hover the button for a tooltip: `Push 2 commits to remote (⌘P)`, `Push the branch to remote (⌘P)`, or `Nothing to push (⌘P)`.
|
|
||||||
|
|
||||||
What happens when you push:
|
|
||||||
|
|
||||||
- A notification says `Pushing…`. The button dims and ignores clicks until the push ends.
|
|
||||||
- A branch with no remote branch is pushed to `origin` and set to track it, so the next push needs nothing extra.
|
|
||||||
- Helder never asks for a password. Git must already have access to the remote, for example through an SSH key or a credential helper.
|
|
||||||
- A push that takes longer than two minutes stops.
|
|
||||||
- When it ends, a notification says `Pushed` with git's summary line, or `Push failed` with git's last error line.
|
|
||||||
- The Git column re-reads git, so the Push button goes back to grey.
|
|
||||||
|
|
||||||
Pull, fetch and branch switching are not part of Helder. Use the [Command line](command-line.md) for those.
|
|
||||||
|
|
||||||
## Keyboard
|
## Keyboard
|
||||||
|
|
||||||
| Keys | Action |
|
| Keys | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Cmd+C` | Focus the message field (no text selected, not in a terminal) |
|
| `Cmd+C` | Open the Git view on the message field (no text selected, not in a terminal) |
|
||||||
| `Shift+Enter` | Commit, while in the message field |
|
| `Cmd+Enter` | Commit, while the Git view is open (not from the console input) |
|
||||||
| `Cmd+Enter` | Commit, from anywhere in the window |
|
|
||||||
| `Ctrl+Enter` | Commit, while in the message field |
|
|
||||||
| `Cmd+P` | Push the current branch |
|
| `Cmd+P` | Push the current branch |
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [Git](git.md): the column that holds this form, and where you stage files.
|
- [Git](git.md): the view that holds this form, and where you stage files.
|
||||||
- [Notifications](notifications.md): the messages after a commit or push.
|
- [Notifications](notifications.md): the messages after a commit or push.
|
||||||
- [Status bar](status-bar.md): shows the branch you commit and push to.
|
|
||||||
- [Command line](command-line.md): for git commands Helder has no button for.
|
|
||||||
- [Keyboard shortcuts](keyboard-shortcuts.md): every shortcut in one list.
|
- [Keyboard shortcuts](keyboard-shortcuts.md): every shortcut in one list.
|
||||||
|
|||||||
+125
-129
@@ -1,163 +1,162 @@
|
|||||||
# Git
|
# Git
|
||||||
|
|
||||||
The Git column (Source Control) is the leftmost column of the window. It lists every changed file in the project's git repository, lets you stage and unstage them, and holds the commit box at its foot.
|
The Git view is a full-screen page for everything git: it lists every changed file with an inline diff, stages and commits, pulls and pushes, switches branches, and shows each git command it runs in a console. Open it with `Cmd+G`.
|
||||||
|
|
||||||
[Guide index](index.md) · Related: [Git commit form](git-commit-form.md), [Right-click menu](right-click-menu.md), [Dialogs](dialogs.md), [File view: Diff](file-view-diff.md), [Status bar](status-bar.md)
|
[Guide index](index.md) · Related: [Git commit form](git-commit-form.md), [Right-click menu](right-click-menu.md#git-rows), [Dialogs](dialogs.md), [Notifications](notifications.md), [Status bar](status-bar.md)
|
||||||
|
|
||||||
## At a glance
|
## At a glance
|
||||||
|
|
||||||
```text
|
```text
|
||||||
+-------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
| (1) STAGED CHANGES - 2 |
|
| (1) [ git ] <> main 1 ahead of origin [Pull] [Push ^1] [Close CmdG] |
|
||||||
| (2) [] app/Http |
|
|----------------------------------------------------------------------------|
|
||||||
| (3) M [php] UserController.php +4 |
|
| (2) fix the login form_ |
|
||||||
| A [php] Invoice.php +31 |
|
| Jonathan <jonathan@example.com> Cmd+Enter commits [Commit 2 files|v] |
|
||||||
|-------------------------------------|
|
|----------------------------------------------------------------------------|
|
||||||
| (1) CHANGES + 3 |
|
| (3)|v staged (2) [ ] [Unstage all]|
|
||||||
| [] . |
|
| |> [M] app/Http/UserController.php +4 -1 [Unstage] |
|
||||||
| M [md] README.md +2 -1 |
|
| |> [A] app/Models/Invoice.php +31 -0 [Unstage] |
|
||||||
| [] tests/Feature |
|
| |
|
||||||
| (4) M [php] UserTest.php [ + ] |
|
| (3) v changed (1) [Discard all] [Stage all]|
|
||||||
| D [php] -OldTest.php- -12 |
|
| (4) v [M] README.md +2 -1 [Discard] [Stage] |
|
||||||
| |
|
| (5) 12 | old line || 12 | new line |
|
||||||
|-------------------------------------|
|
| 13 | same line || 13 | same line |
|
||||||
| (5) Shift+Enter to commit |
|
| ... 40 unchanged lines |
|
||||||
| |
|
| v new . untracked (1) [Delete all] [Stage all]|
|
||||||
|-------------------------------------|
|
| v deleted (1) [Restore all] [Stage all]|
|
||||||
| (6) Commit ^ | (7) ^ |
|
|----------------------------------------------------------------------------|
|
||||||
+-------------------------------------+
|
| (6) [ console ] git (x) | (7) [ branches ] clean . ... |
|
||||||
|
| $ git add -- README.md | local |
|
||||||
|
| $ git commit -m "fix the login form" | |<> main current |
|
||||||
|
| $ git _ | <> feature/a switch -> |
|
||||||
|
| | remote . origin |
|
||||||
|
| | () origin/feature/b checkout->|
|
||||||
|
+----------------------------------------------------------------------------+
|
||||||
```
|
```
|
||||||
|
|
||||||
1. **Group header**: `Staged Changes` or `Changes`, with the row count in amber on the right. Hover the header to see its quick action: `-` (Unstage all) or `+` (Stage all).
|
1. **Top bar**: the branch, where it stands against origin, and the Pull, Push and Close buttons.
|
||||||
2. **Folder line**: the folder that the rows below it live in. `.` is the project root.
|
2. **Commit block**: the message, the author and the Commit button. See [Git commit form](git-commit-form.md).
|
||||||
3. **Row**: status letter, file-type badge, file name, and line counts.
|
3. **Section header**: the section name, its row count, and the bulk actions.
|
||||||
4. **Hover quick action**: a `+` or `-` that replaces the line counts while you hover or select the row.
|
4. **File row**: status badge, path, line counts and the row actions.
|
||||||
5. **Commit message**: see [Git commit form](git-commit-form.md).
|
5. **Inline diff**: the last commit on the left, the working tree on the right.
|
||||||
6. **Commit button**: see [Git commit form](git-commit-form.md).
|
6. **Console**: every git command the view runs, with its output, and an input line for your own.
|
||||||
7. **Push button**: see [Git commit form](git-commit-form.md).
|
7. **Branches**: local branches and the branches on origin.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### Two groups: staged and unstaged
|
### Open and close the view
|
||||||
|
- `Cmd+G`, the **Git** toggle in the [Title bar](title-bar.md), or View > Show Git opens it. The toggle reads `Git N`, where N counts the changed files.
|
||||||
|
- The view covers the whole window: title bar, columns and status bar. The columns stay as they were under it. Terminals keep running.
|
||||||
|
- When it opens, the keyboard goes to the commit message.
|
||||||
|
- `Cmd+C` with no text selected, outside a terminal, also opens the view on the commit message.
|
||||||
|
- Close it with `Cmd+G`, `Esc`, or the **Close** button. The keyboard goes back to the column that had it.
|
||||||
|
- Dialogs, right-click menus, [Search](search.md), the full-screen [Diff](file-view-diff.md) and [notifications](notifications.md) show on top of the view. `Esc` closes those first, then the view.
|
||||||
|
- While the view is open, the column keys rest (arrows, `Cmd+Left` / `Cmd+Right`). `Cmd+1`, `Cmd+2` and `Cmd+3` still toggle the columns under it.
|
||||||
|
- The view is not remembered: a project always opens with it closed.
|
||||||
|
|
||||||
- **Staged Changes** sits on top. It lists what the next commit will hold.
|
### Top bar
|
||||||
- **Changes** sits below. It lists edits in the working tree that are not staged yet.
|
- `[ git ]`, then the current branch in amber.
|
||||||
- Each group shows its row count on the right of its header.
|
- Next to it, where the branch stands against its remote: `in sync with origin`, `1 ahead of origin`, `2 behind origin`, `1 ahead · 2 behind origin`, or `no upstream`.
|
||||||
- Inside a group, rows are grouped by folder. Each folder gets a small folder line with its path. Hover a folder line to see the full path; the project root reads `.`.
|
- **Pull** shows `↓N` when there are commits to pull. **Push** shows `↑N` when there are commits to push.
|
||||||
- One file can show up twice: once in Staged Changes and once in Changes. That happens when you staged a file and then edited it again. Each row stands for its own half of the change.
|
- Opening the view runs `git fetch origin`, so the ahead and behind numbers are up to date. A repository without an `origin` skips this.
|
||||||
|
|
||||||
There is no column header or title. The column starts with the first group.
|
### Sections
|
||||||
|
The changes sit in up to four sections, in this order. A section with no rows is left out.
|
||||||
|
|
||||||
### Row anatomy
|
| Section | Colour | What it holds | Row actions | Bulk actions |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **staged** | amber | Everything staged for the next commit, whatever its status | Unstage | Unstage all |
|
||||||
|
| **changed** | light amber | Unstaged edits to tracked files; also renames and conflicts | Discard, Stage | Discard all, Stage all |
|
||||||
|
| **new · untracked** | teal | New files git does not track yet | Delete, Stage | Delete all, Stage all |
|
||||||
|
| **deleted** | lilac | Tracked files deleted from disk | Restore, Stage | Restore all, Stage all |
|
||||||
|
|
||||||
|
- Click a section header to fold or unfold it.
|
||||||
|
- One file can show up twice: once in staged and once in another section. That happens when you staged a file and then edited it again. Each row stands for its own half.
|
||||||
|
- A conflicted row (`U`) only offers **Stage**. Staging it marks the conflict as resolved.
|
||||||
|
|
||||||
|
### File rows
|
||||||
Every row, left to right:
|
Every row, left to right:
|
||||||
|
|
||||||
- **Status letter** (see the table below).
|
- A chevron: click anywhere on the row to show or hide its inline diff.
|
||||||
- **File-type badge**, the same badge the [Explorer](explorer.md) uses.
|
- A status badge: `A` new, `M` modified, `D` deleted, `R` renamed, `U` conflict. Hover it for the word.
|
||||||
- **File name**. A deleted file has its name struck through and dimmed. Files under `tests/` or `cypress/` show in a dimmer grey, so source files stand out.
|
- The path: the folder dim, the file name bright. A deleted file is struck through.
|
||||||
- **Line counts** on the far right: `+N` in teal for added lines, `−N` in amber-deep for removed lines. A count of zero is left out.
|
- The line counts: `+N` in teal and `−N` in light amber.
|
||||||
|
- The row actions, from the table above.
|
||||||
|
|
||||||
Hover a row to see its full project-relative path in a tooltip.
|
Staged rows carry an amber bar on their left edge.
|
||||||
|
|
||||||
### Status letters and colours
|
### Row actions
|
||||||
|
- **Stage** and **Unstage** run at once. They never ask.
|
||||||
|
- **Discard** throws away the unstaged changes of a file. The file goes back to its staged version, or to the last commit when nothing is staged.
|
||||||
|
- **Delete** removes a new file from disk.
|
||||||
|
- **Restore** brings a deleted file back.
|
||||||
|
- Discard and Delete ask first by default (`git.confirmDiscard`). See [Dialogs](dialogs.md#discard-changes). Restore never asks.
|
||||||
|
- An open file in the [File view](file-view.md) reloads after a Discard, Delete or Restore.
|
||||||
|
|
||||||
| Letter | Meaning | Colour in Staged Changes | Colour in Changes |
|
### Inline diff
|
||||||
|---|---|---|---|
|
- The last commit (or the staged version) is on the left, the working tree on the right, lines side by side.
|
||||||
| `A` | Added: a new file, also an untracked one or a copy | teal | amber |
|
- Removed lines have an amber tint, added lines a teal tint. In a changed line pair, the part that differs is highlighted.
|
||||||
| `M` | Modified; a merge conflict also reads `M` | teal | amber |
|
- Each change keeps 3 unchanged lines around it. Longer unchanged runs fold into `⋯ N unchanged lines`.
|
||||||
| `D` | Deleted | teal | amber-deep |
|
- A file over 1 MB shows `Too big.`. A file with no text changes shows `— No line changes.`.
|
||||||
| `R` | Renamed | teal | light grey |
|
- For the full-screen comparison, open the file and use the [Diff](file-view-diff.md).
|
||||||
|
|
||||||
Staged letters are always teal, whatever the status. Unstaged letters follow the status. A merge conflict shows as one `M` row in Staged Changes, because git cannot stage half of a conflict.
|
### Right-click a row
|
||||||
|
Right-click a file row for **Open in editor**, **Pass on reference** and **Copy reference**. See the [right-click menu](right-click-menu.md#git-rows). Open in editor and Pass on reference close the view first.
|
||||||
|
|
||||||
### Open a file from a row
|
### Pull and push
|
||||||
|
- **Pull** runs `git pull --no-rebase`. When your branch and origin both have new commits, git merges them.
|
||||||
|
- **Push** runs `git push`, or `Cmd+P` from anywhere. A branch with no upstream yet is pushed again with `git push -u origin <branch>`, so the next push needs nothing extra.
|
||||||
|
- While one runs, its button reads `Pulling…` or `Pushing…` and the console header says so. A second Pull or Push is ignored until it ends.
|
||||||
|
- Pull and push stop after 120 seconds.
|
||||||
|
- Helder never asks for a password. Git must already have access to the remote, for example through an SSH key or a credential helper.
|
||||||
|
- A [notification](notifications.md) says how it ended, for example `Pushed 2 commits to origin/main` or `Push failed` with git's error line.
|
||||||
|
|
||||||
- **Click** a row to open that file in the [File view](file-view.md). It opens on the live file, not the full-screen Diff.
|
### Console
|
||||||
- The row remembers which half you clicked. When the file has rows in both groups, the Diff for that file then compares just that half: `HEAD → staged` for a staged row, `staged → actual` for an unstaged row.
|
- Every action in the view logs the exact git command, such as `$ git add -- README.md`, and then git's output as it arrives.
|
||||||
- The row of the open file stays highlighted.
|
- Errors read in amber, hints dim, staged and unstaged files from `status` in their colours, and a pushed branch in teal.
|
||||||
- To go straight into the full-screen Diff, use **Open diff** in the [right-click menu](right-click-menu.md#git-rows).
|
- Type your own command after `$ git` and press `Enter`. A leading `git` is allowed: `status` and `git status` do the same.
|
||||||
|
- `clear` empties the console. So does the eraser button in its header.
|
||||||
|
- `log` on its own shows the last 30 commits, one line each.
|
||||||
|
- `Up` brings back the commands you typed before, newest first.
|
||||||
|
- Commands run one at a time, in order. Typed commands also stop after 120 seconds.
|
||||||
|
- Git cannot ask you anything here: there is no editor and no pager. A command that needs an editor, such as `commit` without `-m`, stops with git's error.
|
||||||
|
- Click the console log without selecting text to put the cursor on the input line.
|
||||||
|
- The console keeps the last 400 lines.
|
||||||
|
|
||||||
### Stage and unstage one file
|
### Branches
|
||||||
|
- **local** lists your local branches. **remote · origin** lists the branches on origin.
|
||||||
|
- The current branch has an amber bar and reads `current`. A remote branch that has a local branch reads `tracked`.
|
||||||
|
- Click a branch to switch to it (`switch →`).
|
||||||
|
- Click a remote branch with no local branch to check it out (`checkout →`). Git creates a local branch that tracks it.
|
||||||
|
- Switching is locked while there are uncommitted changes. The header then reads `— N uncommitted files · switching locked`, the other branches are dimmed, and a click shows a notification that asks you to commit or discard first.
|
||||||
|
|
||||||
- Hover a row. Its line counts make way for a quick action button:
|
### When the view is empty
|
||||||
- `+` on a row in Changes: **Stage changes**.
|
- **Not a repository**: `— Not a git repository.`
|
||||||
- `−` on a row in Staged Changes: **Unstage changes**.
|
- **Clean working tree**: `— No changes. The working tree is clean.`
|
||||||
- Click the button. The row moves to the other group.
|
|
||||||
- The same actions sit in the [right-click menu](right-click-menu.md#git-rows).
|
|
||||||
- By default there is no confirmation. Turn on `git.confirmStage` or `git.confirmUnstage` to get a [confirm dialog](dialogs.md#confirm-dialog) first.
|
|
||||||
|
|
||||||
### Stage all and unstage all
|
|
||||||
|
|
||||||
- Hover the **Changes** header and click `+` (**Stage all**). Every unstaged file is staged.
|
|
||||||
- Hover the **Staged Changes** header and click `−` (**Unstage all**). Every staged file goes back to Changes.
|
|
||||||
- The button only shows while the group has rows.
|
|
||||||
- Stage all and Unstage all never ask for confirmation.
|
|
||||||
|
|
||||||
### Discard changes
|
|
||||||
|
|
||||||
- Right-click a row and choose **Discard changes**. See the [right-click menu](right-click-menu.md#git-rows).
|
|
||||||
- It asks first by default (`git.confirmDiscard`). See [Dialogs](dialogs.md#discard-changes).
|
|
||||||
- A file that exists in the last commit goes back to that version, in the staging area and on disk. Both its staged and its unstaged changes are gone.
|
|
||||||
- A file that is not in the last commit (a new file) is unstaged and deleted from disk.
|
|
||||||
- A staged rename also gets its old file back.
|
|
||||||
- An open file reloads from disk after a discard.
|
|
||||||
|
|
||||||
### Row cursor and keyboard
|
|
||||||
|
|
||||||
The column has a keyboard cursor: one highlighted row.
|
|
||||||
|
|
||||||
- Click the column, or move focus to it with `Cmd+Left` / `Cmd+Right`, to make it the active column.
|
|
||||||
- `Up` and `Down` move the cursor through the rows: first all staged rows, then all unstaged rows, folder by folder.
|
|
||||||
- `Enter` opens the row under the cursor, the same as a click.
|
|
||||||
- `Cmd+Right` opens the row's [right-click menu](right-click-menu.md#git-rows), beside the column at the row's height.
|
|
||||||
- Hovering a row with the pointer also moves the cursor to it.
|
|
||||||
- When the cursor's row disappears, for example after a commit, the next `Up` or `Down` starts again at the top.
|
|
||||||
|
|
||||||
### Empty states
|
|
||||||
|
|
||||||
- **Not a repository**: the column shows `— Not a git repository.` and nothing else. The commit box stays at the foot.
|
|
||||||
- **Clean working tree**: the column shows `— No changes. The working tree is clean.`
|
|
||||||
- **Nothing staged**: under the Staged Changes header, `— Nothing staged.`
|
|
||||||
- **Everything staged**: under the Changes header, `— All changes are staged.`
|
|
||||||
|
|
||||||
### Branch and totals
|
|
||||||
|
|
||||||
The column itself shows no branch. The current branch, the line totals of all changes, and the staged and unstaged counts sit on the left of the [Status bar](status-bar.md). The branch cannot be switched from Helder.
|
|
||||||
|
|
||||||
### Worktrees
|
### Worktrees
|
||||||
|
|
||||||
A project folder that is a git worktree (or a submodule) works like a normal repository. Helder finds the real git folder and watches it for changes. There is no worktree list or worktree switcher.
|
A project folder that is a git worktree (or a submodule) works like a normal repository. Helder finds the real git folder and watches it for changes. There is no worktree list or worktree switcher.
|
||||||
|
|
||||||
### How the list stays up to date
|
### How the list stays up to date
|
||||||
|
|
||||||
You do not need to refresh by hand. The list updates by itself:
|
You do not need to refresh by hand. The list updates by itself:
|
||||||
|
|
||||||
- **On every change**: Helder watches the project folder and the git folder. Edits by you, by the agent, or by git in a terminal update the list after a short pause.
|
- **On every change**: Helder watches the project folder and the git folder. Edits by you, by the agent, or by git in a terminal update the list after a short pause.
|
||||||
- **On a timer**: as a backstop, git is re-read every 10 seconds by default (`git.refreshInterval`).
|
- **On a timer**: as a backstop, git is re-read every 10 seconds by default (`git.refreshInterval`).
|
||||||
- **When you click into the column**: moving focus into the Git column from another column re-reads git.
|
- **When the view opens**: git is re-read, then origin is fetched.
|
||||||
- **After every action**: stage, unstage, discard, commit and push all re-read git when they finish.
|
- **After every action**: every git command from the view, typed ones included, re-reads git and the branches when it ends. Pull, a branch switch and typed commands also re-read the file tree and the open file.
|
||||||
- **By hand**: `Cmd+R` (View → Refresh) re-reads git, the file tree and the open file. The column flashes briefly to show it.
|
- **By hand**: `Cmd+R` (View > Refresh) re-reads git, the file tree and the open file.
|
||||||
|
|
||||||
When a git action fails, a [notification](notifications.md) names the action, for example `Stage failed`, with the file or git's own error line.
|
|
||||||
|
|
||||||
### Show or hide the column
|
|
||||||
|
|
||||||
- `Cmd+G`, or the **Git** toggle in the [Title bar](title-bar.md), shows or hides the column.
|
|
||||||
- `Cmd+C` (with no text selected and outside a terminal) shows a hidden column and puts the cursor in the commit message.
|
|
||||||
- See [Layout](layout.md) for column widths and splitters.
|
|
||||||
|
|
||||||
## Keyboard
|
## Keyboard
|
||||||
|
|
||||||
| Keys | Action |
|
| Keys | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Up` / `Down` | Move the row cursor (Git column active) |
|
| `Cmd+G` | Open or close the Git view |
|
||||||
| `Enter` | Open the row under the cursor |
|
| `Esc` | Close the Git view (after any dialog, menu, search or Diff on top of it) |
|
||||||
| `Cmd+Right` | Open the right-click menu of the row under the cursor |
|
| `Cmd+C` | Open the view on the commit message (no text selected, not in a terminal) |
|
||||||
| `Cmd+Left` / `Cmd+Right` | Move focus to the column on the left or right |
|
| `Cmd+Enter` | Commit, while the view is open (not from the console input) |
|
||||||
| `Cmd+C` | Focus the commit message (no text selected, not in a terminal) |
|
|
||||||
| `Cmd+Enter` | Commit the staged files |
|
|
||||||
| `Cmd+P` | Push the current branch |
|
| `Cmd+P` | Push the current branch |
|
||||||
| `Cmd+G` | Show or hide the Git column |
|
| `Enter` | Run the command in the console input |
|
||||||
|
| `Up` | Recall the previous console command |
|
||||||
| `Cmd+R` | Re-read git, the file tree and the open file |
|
| `Cmd+R` | Re-read git, the file tree and the open file |
|
||||||
|
|
||||||
## Settings
|
## Settings
|
||||||
@@ -166,20 +165,17 @@ All settings live in `.helder/config.json`. See [Configuration](configuration.md
|
|||||||
|
|
||||||
| Setting | Default | Effect |
|
| Setting | Default | Effect |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `git.confirmDiscard` | `true` | Ask before Discard changes |
|
| `git.confirmDiscard` | `true` | Ask before Discard and Delete |
|
||||||
| `git.confirmStage` | `false` | Ask before staging one file |
|
|
||||||
| `git.confirmUnstage` | `false` | Ask before unstaging one file |
|
|
||||||
| `git.refreshInterval` | `10000` | Milliseconds between automatic git re-reads; `0` turns the timer off |
|
| `git.refreshInterval` | `10000` | Milliseconds between automatic git re-reads; `0` turns the timer off |
|
||||||
| `git.defaultDiffMode` | `updated` | How a changed file opens; see [File view: Diff](file-view-diff.md) |
|
| `git.defaultDiffMode` | `updated` | How a changed file opens; see [File view: Diff](file-view-diff.md) |
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [Git commit form](git-commit-form.md): the message field, Commit and Push at the foot of this column.
|
- [Git commit form](git-commit-form.md): the message, author and Commit button at the top of the view.
|
||||||
- [Right-click menu](right-click-menu.md#git-rows): every action on a git row.
|
- [Right-click menu](right-click-menu.md#git-rows): the menu on a file row.
|
||||||
- [Dialogs](dialogs.md): the confirm dialog for discard, stage and unstage.
|
- [Dialogs](dialogs.md): the confirm dialog for Discard and Delete.
|
||||||
- [File view](file-view.md): where a clicked row opens.
|
- [File view: Diff](file-view-diff.md): the full-screen comparison of one file.
|
||||||
- [File view: Diff](file-view-diff.md): the full-screen comparison behind Open diff.
|
|
||||||
- [Explorer](explorer.md): shows the same status letters in the file tree.
|
- [Explorer](explorer.md): shows the same status letters in the file tree.
|
||||||
- [Status bar](status-bar.md): branch, line totals and counts.
|
- [Status bar](status-bar.md): branch, line totals and counts while the view is closed.
|
||||||
- [Notifications](notifications.md): the messages after a commit, push or failed action.
|
- [Notifications](notifications.md): the messages after a commit, pull, push or branch switch.
|
||||||
- [Keyboard shortcuts](keyboard-shortcuts.md): every shortcut in one list.
|
- [Keyboard shortcuts](keyboard-shortcuts.md): every shortcut in one list.
|
||||||
|
|||||||
+14
-14
@@ -8,22 +8,22 @@ This guide explains Helder from the user's side: what each part of the window sh
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
+----------------------------------------------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
| (1) Helder console / src / app.php [Git][Explorer][File][Claude] ... ? |
|
| (1) Helder console / src / app.php [Explorer][File][Claude] [Git 2] .. ? |
|
||||||
+-----------+-----------+----------------------------------+-----------------+
|
| (2) |
|
||||||
| (2) GIT | (3) | (4) FILE | (5) CLAUDE |
|
+----------------+-----------------------------------+-----------------------+
|
||||||
| | EXPLORER | | |
|
| (3) EXPLORER | (4) FILE | (5) CLAUDE |
|
||||||
| STAGED | > src | 12 function handle() { | > _ |
|
| > src | 12 function handle() { | > _ |
|
||||||
| M app.php| app.php | 13 return true; | |
|
| app.php | 13 return true; | |
|
||||||
| CHANGES | > tests | 14 } +-----------------+
|
| > tests | 14 } +-----------------------+
|
||||||
| | | | (6) TERMINAL |
|
| | | (6) TERMINAL |
|
||||||
| [commit] | | | $ _ |
|
| | | $ _ |
|
||||||
+-----------+-----------+----------------------------------+-----------------+
|
+----------------+-----------------------------------+-----------------------+
|
||||||
| (7) main +50 -38 Ln 12, Col 4 UTF-8 PHP |
|
| (7) main +50 -38 Ln 12, Col 4 UTF-8 PHP |
|
||||||
+----------------------------------------------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
```
|
```
|
||||||
|
|
||||||
1. [Title bar](title-bar.md): breadcrumb, pane toggles and toolbar.
|
1. [Title bar](title-bar.md): breadcrumb, pane toggles and toolbar.
|
||||||
2. [Git](git.md): staged and unstaged changes, with the [commit form](git-commit-form.md) at its foot.
|
2. [Git](git.md): the full-screen Git view (`Cmd+G`), with the [commit form](git-commit-form.md), a console and the branches.
|
||||||
3. [Explorer](explorer.md): the project's file tree.
|
3. [Explorer](explorer.md): the project's file tree.
|
||||||
4. [File view](file-view.md): one open file, with [Markdown preview](file-view-markdown.md) and [Diff](file-view-diff.md).
|
4. [File view](file-view.md): one open file, with [Markdown preview](file-view-markdown.md) and [Diff](file-view-diff.md).
|
||||||
5. [Claude Code](claude-code.md): the agent session.
|
5. [Claude Code](claude-code.md): the agent session.
|
||||||
@@ -41,10 +41,10 @@ This guide explains Helder from the user's side: what each part of the window sh
|
|||||||
- [Recent projects](recent-projects.md): switch to or open another project.
|
- [Recent projects](recent-projects.md): switch to or open another project.
|
||||||
- [Notifications](notifications.md): the short messages that confirm or warn.
|
- [Notifications](notifications.md): the short messages that confirm or warn.
|
||||||
|
|
||||||
### Source control and files
|
### Git and files
|
||||||
|
|
||||||
- [Git](git.md): the Source Control column.
|
- [Git](git.md): the full-screen Git view: changes, inline diffs, pull, push, console and branches.
|
||||||
- [Git commit form](git-commit-form.md): write a message, commit and push.
|
- [Git commit form](git-commit-form.md): write a message, commit, or commit and push.
|
||||||
- [Explorer](explorer.md): browse, create, rename and delete files.
|
- [Explorer](explorer.md): browse, create, rename and delete files.
|
||||||
|
|
||||||
### The file view
|
### The file view
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m
|
|||||||
- Close it with `Esc`, or by clicking the dimmed backdrop.
|
- Close it with `Esc`, or by clicking the dimmed backdrop.
|
||||||
- It scrolls only when the window is too short to show all of it.
|
- It scrolls only when the window is too short to show all of it.
|
||||||
- It holds the main shortcuts, in four groups:
|
- It holds the main shortcuts, in four groups:
|
||||||
- **Navigate**: search, list movement, column movement, recent projects, open folder, new window, PHP class lookup, and this list.
|
- **Navigate**: search, list movement, column movement, the Explorer row cursor, the column toggles `Cmd+1` to `Cmd+3`, recent projects, open folder, new window, PHP class lookup, and this list.
|
||||||
- **Agent**: pass the selection to the agent.
|
- **Agent**: pass the selection to the agent.
|
||||||
- **Git**: focus the commit message, commit, Git column on or off, push.
|
- **Git**: open or close the Git view, focus the commit message, commit, push.
|
||||||
- **File**: save, Markdown preview, close, refresh, hidden files, select all, Fluid columns, zoom, and `Esc`.
|
- **File**: save, Markdown preview, close, refresh, hidden files, select all, Fluid columns, zoom, and `Esc`.
|
||||||
- The full reference is below.
|
- The full reference is below.
|
||||||
|
|
||||||
@@ -48,6 +48,8 @@ Helder is built to run from the keyboard. Press `?` to see a short list of the m
|
|||||||
- A text field, the code, or a terminal keeps the keys it needs. Arrows, `Return`, `?`, `Cmd+A` and `Cmd+C` with a selection go to the field, not to Helder.
|
- A text field, the code, or a terminal keeps the keys it needs. Arrows, `Return`, `?`, `Cmd+A` and `Cmd+C` with a selection go to the field, not to Helder.
|
||||||
- Keys with `Ctrl` or `Opt` always go to the field or terminal, except the menu shortcuts that use them.
|
- Keys with `Ctrl` or `Opt` always go to the field or terminal, except the menu shortcuts that use them.
|
||||||
- While an overlay is open, it owns the keys. `Esc` closes it. The Diff is the exception: the workspace shortcuts keep working over it.
|
- While an overlay is open, it owns the keys. `Esc` closes it. The Diff is the exception: the workspace shortcuts keep working over it.
|
||||||
|
- `Esc` closes the topmost layer: a right-click menu, a dialog, search or the Diff first, then the [Git](git.md) view. With none of those open, `Esc` goes to the terminal.
|
||||||
|
- While the Git view is open, the column keys rest: arrows, `Return` and `Cmd+Left` / `Cmd+Right` do nothing in the columns under it.
|
||||||
|
|
||||||
## Keyboard
|
## Keyboard
|
||||||
|
|
||||||
@@ -71,7 +73,9 @@ See [Window layout](layout.md) and [Title bar](title-bar.md).
|
|||||||
|
|
||||||
| Keys | Action |
|
| Keys | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Cmd+G` | Show or hide the Git column |
|
| `Cmd+1` | Show or hide the Explorer column |
|
||||||
|
| `Cmd+2` | Show or hide the File column |
|
||||||
|
| `Cmd+3` | Show or hide the Claude column |
|
||||||
| `Cmd+L` | Fluid column widths on or off |
|
| `Cmd+L` | Fluid column widths on or off |
|
||||||
| `Cmd+.` | Hidden files on or off |
|
| `Cmd+.` | Hidden files on or off |
|
||||||
| `Cmd+Left` / `Cmd+Right` | Focus the column to the left or right (outside text fields and terminals) |
|
| `Cmd+Left` / `Cmd+Right` | Focus the column to the left or right (outside text fields and terminals) |
|
||||||
@@ -87,18 +91,18 @@ See [Start screen](start-screen.md).
|
|||||||
| `Up` / `Down`, `Cmd+Up` / `Cmd+Down` | Move the selection |
|
| `Up` / `Down`, `Cmd+Up` / `Cmd+Down` | Move the selection |
|
||||||
| `Return` | Open the selected row |
|
| `Return` | Open the selected row |
|
||||||
|
|
||||||
### Git column
|
### Git view
|
||||||
See [Git](git.md) and [Git commit form](git-commit-form.md).
|
See [Git](git.md) and [Git commit form](git-commit-form.md).
|
||||||
|
|
||||||
| Keys | Action |
|
| Keys | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Up` / `Down` | Move the row cursor (when the column is active) |
|
| `Cmd+G` | Open or close the Git view |
|
||||||
| `Return` | Open the selected file |
|
| `Esc` | Close the Git view (when nothing is on top of it) |
|
||||||
| `Cmd+Right` | Open the selected row's menu |
|
| `Cmd+C` | Open the Git view on the commit message (with no text selected, outside a terminal) |
|
||||||
| `Cmd+C` | Focus the commit message (with no text selected, outside a terminal); shows the Git column if hidden |
|
| `Cmd+Return` | Commit, while the Git view is open (not from the console input) |
|
||||||
| `Cmd+Return` | Commit the staged files (from anywhere) |
|
| `Cmd+P` | Push the current branch (also with the view closed) |
|
||||||
| `Shift+Return`, `Ctrl+Return` | Commit, while typing in the commit message |
|
| `Return` | Run the command in the console input |
|
||||||
| `Cmd+P` | Push the current branch |
|
| `Up` | Recall the previous console command |
|
||||||
|
|
||||||
### Explorer
|
### Explorer
|
||||||
See [Explorer](explorer.md).
|
See [Explorer](explorer.md).
|
||||||
@@ -180,7 +184,7 @@ See [Right-click menu](right-click-menu.md) and [Dialogs](dialogs.md).
|
|||||||
| `Up` / `Down`, `Cmd+Up` / `Cmd+Down` | Move through a menu |
|
| `Up` / `Down`, `Cmd+Up` / `Cmd+Down` | Move through a menu |
|
||||||
| `Return` | Choose the menu item, confirm a dialog, or accept a name |
|
| `Return` | Choose the menu item, confirm a dialog, or accept a name |
|
||||||
| `Esc` | Close the menu or dialog |
|
| `Esc` | Close the menu or dialog |
|
||||||
| `Ctrl+click` | Same as a right-click on a Git or Explorer row |
|
| `Ctrl+click` | Same as a right-click on a Git view or Explorer row |
|
||||||
|
|
||||||
### Terminals
|
### Terminals
|
||||||
See [Claude Code](claude-code.md) and [Command line](command-line.md).
|
See [Claude Code](claude-code.md) and [Command line](command-line.md).
|
||||||
|
|||||||
+39
-39
@@ -1,6 +1,6 @@
|
|||||||
# Window layout
|
# Window layout
|
||||||
|
|
||||||
A Helder window holds one project. It has a title bar on top, four columns in the middle and a status bar at the bottom.
|
A Helder window holds one project. It has a title bar on top, three columns in the middle and a status bar at the bottom. The [Git](git.md) view (`Cmd+G`) covers all of it when open.
|
||||||
|
|
||||||
[Guide index](index.md) · Related: [Title bar](title-bar.md), [Status bar](status-bar.md), [Keyboard shortcuts](keyboard-shortcuts.md), [Configuration](configuration.md)
|
[Guide index](index.md) · Related: [Title bar](title-bar.md), [Status bar](status-bar.md), [Keyboard shortcuts](keyboard-shortcuts.md), [Configuration](configuration.md)
|
||||||
|
|
||||||
@@ -8,39 +8,39 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
+----------------------------------------------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
| ooo Helder. shop . main app>User.php [Git|Expl|File|Claude] [Search..] [?]|
|
| ooo Helder. shop . main app>User.php [Git 3|Expl|File|Claude] [Search] [?]|
|
||||||
| (1) |
|
| (1) |
|
||||||
+-----------+------------+-------------------------------+-------------------+
|
+-----------------+-------------------------------------+--------------------+
|
||||||
| SOURCE | EXPLORER | User.php +12 -3 | (claude running) |
|
| EXPLORER | User.php +12 -3 | (claude running) |
|
||||||
| CONTROL | | | |
|
| | | |
|
||||||
| [message ]| > app | 1 <?php | > _ |
|
| > app | 1 <?php | > _ |
|
||||||
| [Commit 2]| v Http | 2 | (5) |
|
| v Http | 2 | (4) |
|
||||||
| | User.. | 3 class User | |
|
| User.. | 3 class User | |
|
||||||
| STAGED | > config | 4 { | |
|
| > config | 4 { | |
|
||||||
| M a.php | > routes | 5 ... +-------------------+
|
| > routes | 5 ... +--------------------+
|
||||||
| CHANGES | .env | | $ zsh |
|
| .env | | $ zsh |
|
||||||
| A b.php | | | |
|
| | | |
|
||||||
| (2) | (3) | (4) | (6) |
|
| (2) | (3) | (5) |
|
||||||
+-----------+------------+-------------------------------+-------------------+
|
+-----------------+-------------------------------------+--------------------+
|
||||||
| main +50 -38 1 staged . 2 unstaged app/User.php . Ln 3, Col 1 . PHP |
|
| main +50 -38 1 staged . 2 unstaged app/User.php . Ln 3, Col 1 . PHP |
|
||||||
+----------------------------------------------------------------------------+
|
+----------------------------------------------------------------------------+
|
||||||
^ ^ ^ (7)
|
^ ^ (6)
|
||||||
(8) (8) (8)
|
(7) (7)
|
||||||
```
|
```
|
||||||
|
|
||||||
1. **Title bar**: wordmark, project and branch, breadcrumb, pane toggles and toolbar. See [Title bar](title-bar.md).
|
1. **Title bar**: wordmark, project and branch, breadcrumb, the pane toggles, and the toolbar with the Git toggle. See [Title bar](title-bar.md).
|
||||||
2. **Git column** (Source Control): staging, committing and pushing. See [Git](git.md).
|
2. **Explorer column**: the project file tree. See [Explorer](explorer.md).
|
||||||
3. **Explorer column**: the project file tree. See [Explorer](explorer.md).
|
3. **File column**: the one open file. See [File view](file-view.md).
|
||||||
4. **File column**: the one open file. See [File view](file-view.md).
|
4. **Claude pane**: the agent terminal, top of the right column. See [Claude Code](claude-code.md).
|
||||||
5. **Claude pane**: the agent terminal, top of the right column. See [Claude Code](claude-code.md).
|
5. **Shell pane**: a plain terminal, bottom of the right column. See [Command line](command-line.md).
|
||||||
6. **Shell pane**: a plain terminal, bottom of the right column. See [Command line](command-line.md).
|
6. **Status bar**: branch, change counts and file facts. See [Status bar](status-bar.md).
|
||||||
7. **Status bar**: branch, change counts and file facts. See [Status bar](status-bar.md).
|
7. **Splitters**: the thin lines between columns. Drag them to resize.
|
||||||
8. **Splitters**: the thin lines between columns. Drag them to resize.
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### The four columns
|
### The three columns
|
||||||
- From left to right: **Git**, **Explorer**, **File**, and **Claude + Terminal**.
|
- From left to right: **Explorer**, **File**, and **Claude + Terminal**.
|
||||||
|
- Git is not a column. The full-screen [Git](git.md) view opens over the window with `Cmd+G` and leaves the columns as they were.
|
||||||
- The File column is the flexible one. It takes the width the other columns leave.
|
- The File column is the flexible one. It takes the width the other columns leave.
|
||||||
- The right column holds two terminals stacked on top of each other: Claude on top, a shell below.
|
- The right column holds two terminals stacked on top of each other: Claude on top, a shell below.
|
||||||
|
|
||||||
@@ -49,7 +49,6 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
- Drag a vertical splitter to change a column's width.
|
- Drag a vertical splitter to change a column's width.
|
||||||
- Drag the horizontal splitter in the right column to share the height between Claude and the shell.
|
- Drag the horizontal splitter in the right column to share the height between Claude and the shell.
|
||||||
- Columns have limits, so you cannot drag them away:
|
- Columns have limits, so you cannot drag them away:
|
||||||
- Git: 160 to 460 points wide.
|
|
||||||
- Explorer: 160 to 520 points wide.
|
- Explorer: 160 to 520 points wide.
|
||||||
- File: at least 280 points wide.
|
- File: at least 280 points wide.
|
||||||
- Claude + Terminal: at least 280 points, and never so wide that File drops below 280.
|
- Claude + Terminal: at least 280 points, and never so wide that File drops below 280.
|
||||||
@@ -58,8 +57,8 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
|
|
||||||
### Fluid column widths (`Cmd+L`)
|
### Fluid column widths (`Cmd+L`)
|
||||||
- With **Fluid** on, Helder sizes the columns for you. It re-fits them when you resize the window and when focus moves.
|
- With **Fluid** on, Helder sizes the columns for you. It re-fits them when you resize the window and when focus moves.
|
||||||
- At a window width of 1600 points or more, the columns keep fixed shares: Git about 13%, Explorer about 16%, Claude about 27%, File the rest.
|
- At a window width of 1600 points or more, the columns keep fixed shares: Explorer about 16%, Claude about 27%, File the rest.
|
||||||
- Below 1600 points, Git and Explorer take 15% each, and the right column follows your focus:
|
- Below 1600 points, Explorer takes 15%, and the right column follows your focus:
|
||||||
- 30% when neither side has focus.
|
- 30% when neither side has focus.
|
||||||
- 20% when the File column has focus, or when you just opened a file.
|
- 20% when the File column has focus, or when you just opened a file.
|
||||||
- 50% when a terminal has focus.
|
- 50% when a terminal has focus.
|
||||||
@@ -68,13 +67,12 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
- Toggle it with `Cmd+L`, the **Fluid** button in the title bar, or View > Fluid Column Widths / Lock Column Widths.
|
- Toggle it with `Cmd+L`, the **Fluid** button in the title bar, or View > Fluid Column Widths / Lock Column Widths.
|
||||||
|
|
||||||
### Showing and hiding columns
|
### Showing and hiding columns
|
||||||
- Each column has a toggle in the title bar: **Git**, **Explorer**, **File**, **Claude**. A dot on the button shows that the column is on.
|
- Each column has a toggle in the title bar: **Explorer**, **File**, **Claude**. A dot on the button shows that the column is on.
|
||||||
- `Cmd+G` toggles the Git column. The View menu has Show/Hide items for all four.
|
- `Cmd+1`, `Cmd+2` and `Cmd+3` toggle Explorer, File and Claude. The View menu has Show/Hide items for all three.
|
||||||
- Hiding only hides. The terminals keep running, the open file keeps its edits and scroll position, and the tree keeps its open folders.
|
- Hiding only hides. The terminals keep running, the open file keeps its edits and scroll position, and the tree keeps its open folders.
|
||||||
- When a column hides, File takes the free width. With File hidden, the Claude + Terminal column fills the rest.
|
- When a column hides, File takes the free width. With File hidden, the Claude + Terminal column fills the rest.
|
||||||
- With every column hidden, the middle of the window is empty.
|
- With every column hidden, the middle of the window is empty.
|
||||||
- A hidden column cannot take focus. If you hide the column you are typing in, the keyboard goes back to the window, so nothing lands in a pane you cannot see.
|
- A hidden column cannot take focus. If you hide the column you are typing in, the keyboard goes back to the window, so nothing lands in a pane you cannot see.
|
||||||
- `Cmd+C` (with no text selected, outside a terminal) shows the Git column again if it was hidden, and puts the cursor in the commit message.
|
|
||||||
|
|
||||||
### Hidden files (`Cmd+.`)
|
### Hidden files (`Cmd+.`)
|
||||||
- **Hidden** shows or hides dotfiles such as `.env` in the Explorer and in search.
|
- **Hidden** shows or hides dotfiles such as `.env` in the Explorer and in search.
|
||||||
@@ -82,10 +80,10 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
- Toggle it with `Cmd+.`, the **Hidden** button, or View > Show Hidden Files.
|
- Toggle it with `Cmd+.`, the **Hidden** button, or View > Show Hidden Files.
|
||||||
|
|
||||||
### Focus and the active column
|
### Focus and the active column
|
||||||
- Click inside a column to make it the active column. Git and Explorer get a lighter background when active.
|
- Click inside a column to make it the active column. The Explorer gets a lighter background when active.
|
||||||
- `Cmd+Left` and `Cmd+Right` move focus to the next visible column. This works when the keyboard is not inside a text field, the code, or a terminal. In those places the keys keep their normal meaning.
|
- `Cmd+Left` and `Cmd+Right` move focus to the next visible column. This works when the keyboard is not inside a text field, the code, or a terminal. In those places the keys keep their normal meaning.
|
||||||
- In the Git and Explorer columns, `Up` and `Down` move the row cursor and `Return` opens the row. See [Git](git.md) and [Explorer](explorer.md).
|
- In the Explorer, `Up` and `Down` move the row cursor and `Return` opens the row. See [Explorer](explorer.md).
|
||||||
- Clicking a row in Git or Explorer takes the keyboard out of a text field in another column.
|
- Clicking an Explorer row takes the keyboard out of a text field in another column.
|
||||||
|
|
||||||
### The mouse pointer
|
### The mouse pointer
|
||||||
- A pointing hand means a left click runs an action: a button, a clickable row, the project name.
|
- A pointing hand means a left click runs an action: a button, a clickable row, the project name.
|
||||||
@@ -126,7 +124,7 @@ A Helder window holds one project. It has a title bar on top, four columns in th
|
|||||||
|
|
||||||
### What Helder remembers
|
### What Helder remembers
|
||||||
Per project, always:
|
Per project, always:
|
||||||
- Which of the four columns are shown.
|
- Which of the three columns are shown.
|
||||||
- Whether **Fluid** is on.
|
- Whether **Fluid** is on.
|
||||||
- The column widths, when **Fluid** is off.
|
- The column widths, when **Fluid** is off.
|
||||||
|
|
||||||
@@ -137,13 +135,14 @@ For all projects together:
|
|||||||
- The zoom level.
|
- The zoom level.
|
||||||
- The height split between Claude and the shell.
|
- The height split between Claude and the shell.
|
||||||
|
|
||||||
Not remembered: **Hidden** files (starts off) and which column had focus.
|
Not remembered: **Hidden** files (starts off), which column had focus, and whether the Git view was open.
|
||||||
|
|
||||||
## Keyboard
|
## Keyboard
|
||||||
|
|
||||||
| Keys | Action |
|
| Keys | Action |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `Cmd+G` | Show or hide the Git column |
|
| `Cmd+G` | Open or close the Git view |
|
||||||
|
| `Cmd+1` / `Cmd+2` / `Cmd+3` | Show or hide the Explorer, File or Claude column |
|
||||||
| `Cmd+L` | Fluid column widths on or off |
|
| `Cmd+L` | Fluid column widths on or off |
|
||||||
| `Cmd+.` | Hidden files on or off |
|
| `Cmd+.` | Hidden files on or off |
|
||||||
| `Cmd+Left` / `Cmd+Right` | Focus the column to the left or right (outside text and terminals) |
|
| `Cmd+Left` / `Cmd+Right` | Focus the column to the left or right (outside text and terminals) |
|
||||||
@@ -162,7 +161,8 @@ Not remembered: **Hidden** files (starts off) and which column had focus.
|
|||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [Title bar](title-bar.md): the pane toggles and the Fluid and Hidden buttons live here.
|
- [Title bar](title-bar.md): the pane toggles and the Git, Fluid and Hidden buttons live here.
|
||||||
|
- [Git](git.md): the full-screen Git view.
|
||||||
- [Status bar](status-bar.md): the bar along the bottom edge.
|
- [Status bar](status-bar.md): the bar along the bottom edge.
|
||||||
- [Start screen](start-screen.md): what a window shows before a project is open.
|
- [Start screen](start-screen.md): what a window shows before a project is open.
|
||||||
- [Recent projects](recent-projects.md): switch this window to another project.
|
- [Recent projects](recent-projects.md): switch this window to another project.
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user