adds nice git interface

This commit is contained in:
2026-10-30 13:21:45 +01:00
parent b9c03a7637
commit caec81e762
107 changed files with 6466 additions and 3992 deletions
+1 -5
View File
@@ -71,8 +71,6 @@ public struct HelderConfig: Codable, Sendable, Equatable {
public struct Git: Codable, Sendable, Equatable {
public var confirmDiscard = true
public var confirmStage = false
public var confirmUnstage = false
public var defaultDiffMode = DefaultDiffMode.updated
/// Milliseconds between git status polls; 0 disables the poll.
public var refreshInterval = 10_000
@@ -182,15 +180,13 @@ extension HelderConfig.Editor {
extension HelderConfig.Git {
private enum CodingKeys: String, CodingKey {
case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval
case confirmDiscard, defaultDiffMode, refreshInterval
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
confirmStage = c.value(.confirmStage, d.confirmStage)
confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage)
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
}
+30 -15
View File
@@ -7,8 +7,10 @@ public enum ContextTarget: Sendable, Equatable {
case editor(reference: AgentReference, code: String?, showDiffLine: Int? = nil)
case file(path: String)
case directory(path: String)
/// A git row; the row carries its own half, since one file can have two rows.
case gitRow(path: String, staged: Bool)
/// A file row in the Git view; a deleted file has nothing to open.
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.
case projectRoot
case terminal(TerminalKind, hasSelection: Bool)
@@ -17,7 +19,7 @@ public enum ContextTarget: Sendable, Equatable {
switch self {
case let .editor(reference, _, _): reference.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 newFile(inDirectory: String)
case newFolder(inDirectory: String)
case stage(String)
case unstage(String)
case openDiff(String)
/// Opens a file from the Git view, which closes first.
case openFile(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.
case showDiff(String, line: Int)
case discard(String)
case rename(String, isDirectory: Bool)
case revealInFinder(String)
case delete(String, isDirectory: Bool)
@@ -58,7 +61,15 @@ public enum ContextAction: Sendable, Equatable {
/// Destructive items read in amber-deep.
public var isDestructive: Bool {
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
}
}
@@ -76,7 +87,7 @@ public enum ContextActions {
switch target {
case let .file(path), let .gitRow(path, _): path
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?")] : []
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
case let .gitRow(path, staged):
return fileHead(path) + readAloudFile(path) + [
.separator,
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
.action(.openDiff(path), label: "Open diff"),
.action(.discard(path), label: "Discard changes"),
case let .gitRow(path, isDeleted):
let open: [ContextMenuEntry] = isDeleted ? [] : [.action(.openFile(path), label: "Open in editor"), .separator]
return open + [
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
.action(.copyReference(path), label: "Copy reference"),
]
case .commitMenu:
return [
.action(.commit(andPush: false), label: "Commit"),
.action(.commit(andPush: true), label: "Commit and push"),
]
}
}
+48
View File
@@ -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
}
}
+164
View File
@@ -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
}
}
+2 -47
View File
@@ -8,7 +8,8 @@ public enum GitDerivation {
/// so a file staged as modified but deleted on disk reads as deleted.
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
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 tooBig = Set<String>()
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 {
/// 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.
public static func normalizeCommitMessage(_ value: String) -> String {
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/")
}
}
+15 -13
View File
@@ -41,12 +41,18 @@ public struct GitSnapshot: Sendable, Equatable {
public var ahead: Int
/// True when a push would send something, including a branch without an upstream.
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 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.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.changes = changes
}
}
@@ -86,6 +92,10 @@ public struct GitWorkingState: Sendable, Equatable {
public var branch: String
public var ahead: Int
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]
/// Per path: HEAD vs disk. Drives the Actual view.
public var fileDiffs: [String: Diff]
@@ -97,13 +107,16 @@ public struct GitWorkingState: Sendable, Equatable {
public var isRepository: Bool
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] = [:],
stagedPaths: Set<String> = [], isRepository: Bool = false
) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.changes = changes
self.fileDiffs = fileDiffs
self.rowDiffs = rowDiffs
@@ -127,14 +140,3 @@ public struct GitWorkingState: Sendable, Equatable {
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
}
}
+126
View File
@@ -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)
}
}
+21 -15
View File
@@ -25,12 +25,16 @@ public struct ParsedStatus: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var behind: Int
public var upstream: String?
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.ahead = ahead
self.canPush = canPush
self.behind = behind
self.upstream = upstream
self.entries = entries
}
}
@@ -69,6 +73,8 @@ public enum Porcelain {
let header = String(part.dropFirst(3))
result.branch = parseBranch(header: header)
(result.ahead, result.canPush) = parseAhead(header: header)
result.behind = parseBehind(header: header)
result.upstream = parseUpstream(header: header)
continue
}
let chars = Array(part.prefix(2))
@@ -101,6 +107,20 @@ public enum Porcelain {
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.
public static func status(for code: Character) -> GitStatus {
switch code {
@@ -125,20 +145,6 @@ public enum Porcelain {
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>`.
public static func needsUpstream(stderr: String) -> Bool {
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
+12 -19
View File
@@ -7,14 +7,12 @@ public enum FocusZone: String, Sendable, Equatable {
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 var sourceControl: Double
public var explorer: Double
public var agent: Double
public init(sourceControl: Double, explorer: Double, agent: Double) {
self.sourceControl = sourceControl
public init(explorer: Double, agent: Double) {
self.explorer = explorer
self.agent = agent
}
@@ -25,18 +23,17 @@ public enum ColumnLayout {
public static let roomyWidth = 1600.0
public static let minEditorWidth = 280.0
public static let splitterWidth = 1.0
public static let sourceControlRange = 160.0...460.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
/// 236 · 288 · flex · 480 on a 1760 frame). Tight: 15% · 15%, and the agent column
/// takes 30%, or 20% with the editor focused, or 50% with a terminal focused.
/// Fluid widths for a window. Roomy: 16.4% · flex · 27.3% (the design's 288 · flex · 480
/// on a 1760 frame). Tight: 15%, and the agent column takes 30%, or 20% with the editor
/// focused, or 50% with a terminal focused.
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
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
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.
@@ -45,12 +42,10 @@ public enum ColumnLayout {
let agentIsFixed = visible.agent && visible.editor
let flexMinimum = visible.editor || visible.agent ? minEditorWidth : 0
let budget = windowWidth - Double(visible.splitterCount) * splitterWidth - flexMinimum
let total = (visible.sourceControl ? widths.sourceControl : 0) + (visible.explorer ? widths.explorer : 0)
+ (agentIsFixed ? widths.agent : 0)
let total = (visible.explorer ? widths.explorer : 0) + (agentIsFixed ? widths.agent : 0)
guard total > budget, total > 0 else { return widths }
let k = max(0, budget) / total
return ColumnWidths(
sourceControl: visible.sourceControl ? (widths.sourceControl * k).rounded(.down) : widths.sourceControl,
explorer: visible.explorer ? (widths.explorer * k).rounded(.down) : widths.explorer,
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.
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)
}
}
/// 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 var sourceControl: Bool
public var explorer: Bool
public var editor: Bool
public var agent: Bool
public init(sourceControl: Bool = true, explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
self.sourceControl = sourceControl
public init(explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
self.explorer = explorer
self.editor = editor
self.agent = agent
@@ -81,6 +74,6 @@ public struct ColumnVisibility: Sendable, Equatable {
/// One splitter between each pair of neighbouring visible columns.
public var splitterCount: Int {
max(0, [sourceControl, explorer, editor, agent].filter { $0 }.count - 1)
max(0, [explorer, editor, agent].filter { $0 }.count - 1)
}
}
+68 -98
View File
@@ -6,7 +6,6 @@ public actor GitService: GitServicing {
private let runner: ProcessRunning
private let statusAttempts: Int
private let statusRetryDelay: TimeInterval
private let pushTimeout: TimeInterval
private let maxDiffBytes: Int
/// 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`.
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) {
self.root = root
self.runner = runner
self.statusAttempts = statusAttempts
self.statusRetryDelay = statusRetryDelay
self.pushTimeout = pushTimeout
self.maxDiffBytes = maxDiffBytes
}
@@ -50,11 +48,6 @@ public actor GitService: GitServicing {
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.
public func isRepository() async -> Bool {
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)
}
public func stage(_ paths: [String]) async throws {
guard !paths.isEmpty else { return }
try await git(["add", "--"] + paths)
}
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"])
/// Prompts, editors and pagers are switched off, so a run can never wait on input: a commit without `-m` aborts.
public func execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
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
let runner = self.runner, root = self.root
let attempt = Task { () async throws -> ProcessResult in
var result = try await runner.run("git", arguments: ["push"], in: root, environment: environment)
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) {
let head = try await runner.run("git", arguments: ["rev-parse", "--abbrev-ref", "HEAD"], in: root, environment: environment)
let branch = head.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
if !branch.isEmpty && branch != "HEAD" {
result = try await runner.run("git", arguments: ["push", "-u", "origin", branch], in: root, environment: environment)
let outcome = await withTaskGroup(of: ExecuteOutcome?.self) { group -> ExecuteOutcome? in
group.addTask {
do {
return .finished(try await runner.stream("git", arguments: arguments, in: root, environment: environment, onLine: onLine))
} catch is CancellationError {
return nil
} catch let ProcessRunnerError.executableNotFound(name) {
return .failed("\(name) not found")
} catch let ProcessRunnerError.launchFailed(reason) {
return .failed(reason)
} catch {
return .failed("\(error)")
}
}
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 {
try await Task.sleep(nanoseconds: UInt64(pushTimeout * 1_000_000_000))
attempt.cancel()
}
defer { timeout.cancel() }
do {
let result = try await attempt.value
return Porcelain.pushSummary(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
} catch is CancellationError {
return PushResult(ok: false, message: "push timed out")
} catch {
return PushResult(ok: false, message: "\(error)")
switch outcome {
case let .finished(result):
return GitCommandResult(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
case let .failed(reason):
onLine(reason, true)
return GitCommandResult(exitCode: -1, stdout: "", stderr: reason)
case nil:
return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled")
}
}
/// A path HEAD has is checked out from HEAD (index and disk); any other path is unstaged
/// and its file deleted. A staged rename also gets its source back. Folders are never deleted.
public func discard(_ paths: [String]) async throws {
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)
}
public func branches() async -> GitBranchList {
guard let result = try? await Self.run(GitBranchParsing.arguments, root: root, runner: runner), result.succeeded else {
return .empty
}
return GitBranchParsing.parse(result.stdout)
}
/// Rename target → source for every rename in the index.
private func stagedRenameSources() async throws -> [String: String] {
let parsed = Porcelain.parseStatus(try await statusWithRetry())
var sources: [String: String] = [:]
for entry in parsed.entries where entry.isStagedRename {
sources[entry.path] = entry.originalPath
}
return sources
/// The name alone when no email is set.
public func author() async -> String? {
guard let name = await configValue("user.name") else { return nil }
guard let email = await configValue("user.email") else { return name }
return "\(name) <\(email)>"
}
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
@@ -166,7 +152,8 @@ public actor GitService: GitServicing {
let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in
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.
@@ -279,27 +266,10 @@ public actor GitService: GitServicing {
adding extra: [String: String] = [:]) async throws -> ProcessResult {
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.
public enum GitRevision: Sendable {
/// Which stored copy of a file a blob read takes.
enum GitRevision: Sendable {
case head
case index
+29 -8
View File
@@ -6,15 +6,36 @@ public enum GitError: Error, Equatable {
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 {
/// The working state, or nil when the project is not a git repository.
func load() async throws -> GitSnapshot?
/// Stages modifications, additions and deletions of the paths.
func stage(_ paths: [String]) async throws
func unstage(_ paths: [String]) async throws
func commit(message: String) async throws
/// Never throws: a failed push is a toast, not an error.
func push() async -> PushResult
/// Reverts each path to HEAD; a file HEAD does not have is unstaged and deleted, and a staged rename gets its source back.
func discard(_ paths: [String]) async throws
/// 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 execute(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?,
onLine: @escaping @Sendable (String, Bool) -> Void) async -> GitCommandResult
/// Local and origin branches.
func branches() async -> GitBranchList
/// `user.name <user.email>` from git config, nil when unset.
func author() async -> String?
}
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
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.
/// 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
/// 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 {
/// 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 {
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 {
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) }
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 {
try await withCheckedThrowingContinuation { continuation in
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
/// 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 let process = Process()
private let lock = NSLock()
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.arguments = arguments
if let directory { process.currentDirectoryURL = directory }
@@ -80,53 +144,102 @@ private final class Job: @unchecked Sendable {
process.terminationHandler = { _ in group.leave() }
lock.lock()
let alreadyCancelled = cancelled
if cancelled {
lock.unlock()
continuation.resume(throwing: CancellationError())
return
}
do {
if !alreadyCancelled { try process.run() }
try process.run()
} catch {
lock.unlock()
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
return
}
self.continuation = continuation
lock.unlock()
if alreadyCancelled {
continuation.resume(throwing: CancellationError())
return
}
group.enter()
DispatchQueue.global().async {
outData = out.fileHandleForReading.readDataToEndOfFile()
DispatchQueue.global().async { [self] in
outData = drain(out.fileHandleForReading, isError: false)
group.leave()
}
group.enter()
DispatchQueue.global().async {
errData = err.fileHandleForReading.readDataToEndOfFile()
DispatchQueue.global().async { [self] in
errData = drain(err.fileHandleForReading, isError: true)
group.leave()
}
group.notify(queue: .global()) { [self, process] in
if wasCancelled {
continuation.resume(throwing: CancellationError())
return
}
continuation.resume(returning: ProcessResult(
resume(with: .success(ProcessResult(
exitCode: process.terminationStatus,
stdout: String(decoding: outData, 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()
defer { lock.unlock() }
return cancelled
let pending = continuation
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() {
lock.lock()
defer { lock.unlock() }
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)
}
/// Keeps a button's identity while its label changes, as `Git 3` does.
var id: String
var label: String
var keys: String?
var kind: Kind
var tip: Text
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.keys = keys
self.kind = kind
@@ -34,7 +37,7 @@ public struct ButtonGroup: View {
public var body: some View {
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)
.tip(item.tip, edge: tipEdge)
}
@@ -50,15 +50,17 @@ public struct ContextMenuRow: View {
var shortcut: String?
var isHighlighted: Bool
var isDestructive: Bool
var isEmphasized: Bool
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.systemImage = systemImage
self.iconTint = iconTint
self.shortcut = shortcut
self.isHighlighted = isHighlighted
self.isDestructive = isDestructive
self.isEmphasized = isEmphasized
}
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
@@ -77,7 +79,7 @@ public struct ContextMenuRow: View {
.foregroundStyle(iconColor)
.frame(width: 15)
}
Text(label).typeRole(isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem)
Text(label).typeRole(labelRole)
.foregroundStyle(labelColor)
Spacer(minLength: 8)
if let shortcut {
@@ -95,6 +97,11 @@ public struct ContextMenuRow: View {
.pointerHand()
}
private var labelRole: TypeRole {
if isEmphasized { return Typography.menuItemEmphasized }
return isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem
}
private var labelColor: Color {
if isDestructive { return Palette.removedText }
return isHighlighted ? Palette.text1 : Palette.text3
+18 -22
View File
@@ -1,12 +1,11 @@
import SwiftUI
/// The frame every overlay sits in: a flat ink scrim (no blur) and a `panel` card with a hairline border,
/// radius 8 and the overlay shadow. `.inset` fills the window minus 34pt, up to 1200pt wide; `.sized` centres a fixed-width card
/// at the top. A click on the scrim calls `onDismiss`.
/// The frame every overlay sits in. `.sized` puts a top-aligned `panel` card on a flat ink scrim, and a click
/// on the scrim calls `onDismiss`; `.fullScreen` fills the window edge to edge on the slate page, like the Git view.
public struct OverlayShell<Content: View>: View {
public enum Placement {
/// Search, Diff: the whole window minus the 34pt inset, at most `insetOverlayMaxWidth` wide.
case inset
/// Search: the whole window, title bar and status bar included, with no scrim to click.
case fullScreen
/// A card of this width, top-aligned inside the inset.
case sized(width: CGFloat)
}
@@ -15,31 +14,28 @@ public struct OverlayShell<Content: View>: View {
var onDismiss: () -> Void
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.onDismiss = onDismiss
self.content = content()
}
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 {
case .inset:
OverlayCard { content }
.frame(maxWidth: Metrics.insetOverlayMaxWidth, maxHeight: .infinity)
case .fullScreen:
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
.contentShape(Rectangle())
case let .sized(width):
OverlayCard { content }
.frame(width: width)
ZStack(alignment: .top) {
Palette.scrim
.contentShape(Rectangle())
.onTapGesture(perform: onDismiss)
OverlayCard { content }
.frame(width: width)
.padding(Metrics.overlayInset)
}
}
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ public struct PanelLabel: View {
}
/// 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 {
var title: String
var height: CGFloat
@@ -196,9 +196,10 @@ extension PointerPolicy {
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 {
guard let window else { return false }
return WorkspaceRegistry.model(for: window)?.overlay.isPresented ?? false
guard let window, let model = WorkspaceRegistry.model(for: window) else { return 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.
@@ -420,7 +421,7 @@ final class PointerTracker: NSResponder {
}
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
/// False under `disabledLook`, whose hit-testing switch SwiftUI does not expose.
@Entry var allowsPointerHand = true
+1 -1
View File
@@ -1,4 +1,4 @@
// Pieces shared by the Source Control and Explorer rows.
// Pieces of the Explorer rows.
import AppKit
import HelderCore
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 {}
+71
View File
@@ -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)
}
}
+62
View File
@@ -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)
}
}
+90
View File
@@ -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()
case let .action(action, label):
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 } }
.onTapGesture { onPerform(action) }
}
@@ -109,11 +110,11 @@ struct ContextMenuOverlay: View {
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
switch action {
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText, .readAloudTerminalSelection,
.plak, .plakTerminalSelection: .plain
case .newFile, .newFolder, .stage: .add
case .copyFileName, .unstage, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .openDiff, .showDiff, .rename: .rename
case .discard, .delete: .danger
.plak, .plakTerminalSelection, .openFile, .commit: .plain
case .newFile, .newFolder: .add
case .copyFileName, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .showDiff, .rename: .rename
case .gitDiscard, .delete: .danger
}
}
@@ -125,13 +126,14 @@ struct ContextMenuOverlay: View {
case .readAloudFile, .readAloudText, .readAloudTerminalSelection: "speaker.wave.2"
case .plak, .plakTerminalSelection: "note.text.badge.plus"
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 .newFile: "doc.badge.plus"
case .newFolder: "folder.badge.plus"
case .stage: "plus"
case .unstage: "minus"
case .openDiff, .showDiff: "arrow.left.arrow.right"
case .discard: "arrow.uturn.backward"
case .showDiff: "arrow.left.arrow.right"
case .gitDiscard: "arrow.uturn.backward"
case .rename: "pencil"
case .revealInFinder: "folder"
case .delete: "trash"
@@ -26,6 +26,7 @@ public struct OverlayHost: View {
activeText: path.map { model.editor?.text(for: $0) ?? "" } ?? "",
showHidden: model.layout.showHidden),
changedPaths: model.changedPaths,
isFullScreen: model.layout.isFullScreen,
onOpen: { model.perform(.open($0.path, OpenOptions(line: $0.line))) },
onClose: dismiss
)
+7 -11
View File
@@ -290,20 +290,16 @@ public final class SearchModel {
// MARK: Layout
/// Column widths: the focused column takes 70%; at rest this file is 230, files 250,
/// and a side column never drops below 180.
public static func widths(total: CGFloat, columns: [Column], focused: Column) -> [Column: CGFloat] {
let restingSide: [Column: CGFloat] = [.thisFile: 230, .files: 250]
let minimumSide: CGFloat = 180
/// Fixed column widths that never follow the focus: 30 · 45 · 25 with this file, else 65 · 35.
public static func widths(total: CGFloat, columns: [Column]) -> [Column: CGFloat] {
var widths: [Column: CGFloat] = [:]
if focused == .project {
for side in columns where side != .project { widths[side] = restingSide[side] }
if columns.contains(.thisFile) {
widths[.thisFile] = (total * 0.30).rounded()
widths[.files] = (total * 0.25).rounded()
} else {
widths[focused] = (total * 0.7).rounded()
for side in columns where side != .project && side != focused { widths[side] = minimumSide }
widths[.files] = (total * 0.35).rounded()
}
let used = widths.values.reduce(0, +)
widths[.project] = max(0, total - used)
widths[.project] = max(0, total - widths.values.reduce(0, +))
return widths
}
}
+10 -6
View File
@@ -7,6 +7,8 @@ struct SearchOverlay: View {
@State private var model: SearchModel
/// Paths with a git change get a dot in the files column.
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 onClose: () -> Void
@@ -14,15 +16,17 @@ struct SearchOverlay: View {
@State private var parkedPointer: CGPoint?
@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)
self.changedPaths = changedPaths
self.isFullScreen = isFullScreen
self.onOpen = onOpen
self.onClose = onClose
}
var body: some View {
OverlayShell(.inset, onDismiss: onClose) {
OverlayShell(.fullScreen, onDismiss: onClose) {
VStack(spacing: 0) {
queryBar.zIndex(1)
columns
@@ -54,7 +58,8 @@ struct SearchOverlay: View {
.padding(.leading, 12)
.hairline(.leading)
}
.padding(.horizontal, 18)
.padding(.leading, isFullScreen ? 18 : Metrics.trafficLightInset)
.padding(.trailing, 18)
.frame(height: Metrics.searchQueryBar)
.hairline(.bottom)
}
@@ -85,7 +90,7 @@ struct SearchOverlay: View {
private var columns: some View {
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) {
if model.columns.contains(.thisFile) {
thisFileColumn.frame(width: widths[.thisFile])
@@ -95,7 +100,6 @@ struct SearchOverlay: View {
divider
filesColumn.frame(width: widths[.files])
}
.animation(Metrics.colorTransition, value: model.column)
}
}
@@ -263,7 +267,7 @@ struct SearchOverlay: View {
TypeBadge(path: match.path)
VStack(alignment: .leading, spacing: 1) {
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)
if !directory.isEmpty {
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: "Open the selected item"),
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 project folder"),
ShortcutRow(keys: ["⇧", "⌘", "N"], label: "Open a new window"),
@@ -30,9 +33,9 @@ public enum ShortcutCatalog {
ShortcutRow(keys: ["⌘", "→"], label: "Pass the selection to the agent"),
]),
ShortcutGroup(title: "Git", rows: [
ShortcutRow(keys: ["⌘", "G"], label: "Open or close the Git view"),
ShortcutRow(keys: ["⌘", "C"], label: "Focus the commit message"),
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"),
]),
ShortcutGroup(title: "File", rows: [
@@ -46,7 +49,7 @@ public enum ShortcutCatalog {
ShortcutRow(keys: ["⌘", "+"], label: "Zoom in"),
ShortcutRow(keys: ["⌘", "−"], label: "Zoom out"),
ShortcutRow(keys: ["⌘", "0"], label: "Actual size"),
ShortcutRow(keys: ["Esc"], label: "Close an overlay or a split view"),
ShortcutRow(keys: ["Esc"], label: "Close an overlay, then the Git view"),
]),
]
}
+16 -7
View File
@@ -6,7 +6,7 @@ import HelderCore
/// first responder when it names them.
public enum FocusTarget: Equatable, Sendable {
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
}
@@ -72,9 +72,11 @@ public enum Command: Equatable, Sendable {
// 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
/// 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)
/// ⌘L
case toggleAutoFit
@@ -85,11 +87,11 @@ public enum Command: Equatable, Sendable {
/// ⌘←/⌘→ outside a text field.
case focusNeighbour(step: Int)
// MARK: Row cursor in Source Control and Explorer
// MARK: Row cursor in the Explorer
/// ↑/↓
case moveRowCursor(Int)
/// ↵: git row opens its half, a file opens, a folder toggles.
/// ↵: a file opens, a folder toggles.
case openSelectedRow
/// ⌘→ on a row: its context menu, anchored to the column's right edge.
case openRowMenu
@@ -110,11 +112,18 @@ public enum Command: Equatable, Sendable {
// MARK: Git
/// ⌘↵
/// ⌘↵ and the Commit button: always runs git, so its refusal shows in the console.
case commit
/// ⌘P
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
// MARK: Clean copy
+5 -2
View File
@@ -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.
struct HelderCommands: Commands {
@FocusedValue(\.workspace) private var workspace
@@ -66,19 +66,22 @@ struct HelderCommands: Commands {
.keyboardShortcut("r", modifiers: .command)
.disabled(workspace?.root == nil)
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)
}
.keyboardShortcut("g", modifiers: .command)
Button(workspace?.layout.isVisible(.explorer) == false ? "Show Explorer" : "Hide Explorer") {
workspace?.perform(.togglePane(.explorer))
}
.keyboardShortcut("1", modifiers: .command)
Button(workspace?.layout.isVisible(.editor) == false ? "Show File" : "Hide File") {
workspace?.perform(.togglePane(.editor))
}
.keyboardShortcut("2", modifiers: .command)
Button(workspace?.layout.isVisible(.terminal) == false ? "Show Claude" : "Hide Claude") {
workspace?.perform(.togglePane(.terminal))
}
.keyboardShortcut("3", modifiers: .command)
Button(workspace?.layout.fluid == false ? "Fluid Column Widths" : "Lock Column Widths") {
workspace?.perform(.toggleAutoFit)
}
+32 -8
View File
@@ -55,11 +55,15 @@ public struct KeyContext: Equatable, Sendable {
public var recentFileCount: Int
/// The seed ⌘F uses: the first line of the current selection.
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,
hasTextSelection: Bool = false, editorTextSelection: TextSelectionInfo? = nil,
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.overlay = overlay
self.owner = owner
@@ -70,6 +74,8 @@ public struct KeyContext: Equatable, Sendable {
self.focusZone = focusZone
self.recentFileCount = recentFileCount
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:
/// 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 static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
if press.control || press.option { return .pass }
@@ -107,7 +114,10 @@ public enum KeyRouter {
switch context.overlay {
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) }
}
switch context.overlay {
@@ -117,9 +127,24 @@ public enum KeyRouter {
case .other: return .pass
}
if context.gitViewOpen { return gitViewKey(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 {
guard !press.shift else { return .pass }
switch press.key {
@@ -131,7 +156,7 @@ public enum KeyRouter {
}
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 {
case .up 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,
count: context.recentFileCount)))
case .right:
if owner == .workspace, context.activePanel == .sourceControl || context.activePanel == .explorer {
return .perform(.openRowMenu)
}
if owner == .workspace, context.activePanel == .explorer { return .perform(.openRowMenu) }
if let selection = context.editorTextSelection { return .perform(.passSelection(selection)) }
if context.hasEditorLineSelection && owner != .terminal { return .perform(.passSelection(nil)) }
return owner == .workspace ? .perform(.focusNeighbour(step: 1)) : .pass
case .left:
return owner == .workspace ? .perform(.focusNeighbour(step: -1)) : .pass
case .enter:
return owner == .text(in: .sourceControl) ? .pass : .perform(.commit)
case let .character(c):
return commandCharacter(c, context)
default:
@@ -177,6 +198,9 @@ public enum KeyRouter {
case "m": return .perform(.cycleMode)
case "w": return .perform(.closeFileOrWindow)
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 ".": return .perform(.toggleHidden)
case "a": return context.owner == .workspace ? .perform(.selectAllInFile) : .pass
+21 -9
View File
@@ -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 {
let model: WorkspaceModel
var body: some View {
ButtonGroup([
toggle("Git", .sourceControl, column: "Source Control"),
toggle("Explorer", .explorer, column: "Explorer"),
toggle("File", .editor, column: "File"),
toggle("Claude", .terminal, column: "Claude"),
toggle("Explorer", .explorer),
toggle("File", .editor),
toggle("Claude", .terminal),
])
}
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 tip = shown
? Tooltip.stated(column + " column: ", "shown", ". Click to hide it.")
: Tooltip.stated(column + " column: ", "hidden", ". Click to show it.")
? Tooltip.stated(label + " column: ", "shown", ". Click to hide it.")
: Tooltip.stated(label + " column: ", "hidden", ". Click to show it.")
return GroupItem(label, kind: .toggle(isOn: shown), tip: tip) {
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.
private struct TitleToolbar: View {
let model: WorkspaceModel
@@ -140,6 +139,7 @@ private struct TitleToolbar: View {
let layout = model.layout
HStack(spacing: Metrics.toolbarIconGap) {
ButtonGroup(stop + [
git,
GroupItem("Search", keys: "⌘F", kind: .action,
tip: Text("Search the open file, the project and the file names.")) { model.perform(.showSearch(seed: "")) },
GroupItem("Fluid", keys: "⌘L", kind: .toggle(isOn: layout.fluid),
@@ -161,6 +161,18 @@ private struct TitleToolbar: View {
.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] {
guard model.readAloud.isReading else { return [] }
return [GroupItem("Stop", kind: .toggle(isOn: true), tip: Tooltip.stated("Read aloud: ", "playing", ". Click to stop.")) {
+21 -6
View File
@@ -8,6 +8,7 @@ struct WindowBridge: NSViewRepresentable {
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
let title: String
let hasProject: Bool
let gitViewOpen: Bool
func makeCoordinator() -> WindowCoordinator {
WindowCoordinator(model: model)
@@ -21,6 +22,7 @@ struct WindowBridge: NSViewRepresentable {
func updateNSView(_ view: BridgeView, context: Context) {
context.coordinator.updateTitle(title, hasProject: hasProject)
context.coordinator.updateGitView(open: gitViewOpen)
context.coordinator.guardClose()
}
@@ -48,6 +50,7 @@ final class WindowCoordinator: NSObject {
/// Set once the unsaved prompt said yes, so the second close goes through.
private var closeApproved = false
private var isAskingToClose = false
private var gitViewOpen = false
init(model: WorkspaceModel) {
self.model = model
@@ -103,6 +106,14 @@ final class WindowCoordinator: NSObject {
AppName.set(hasProject ? title : AppName.standard)
}
/// Opening the Git view takes the keyboard from the column behind it at once; its message field
/// takes focus a run loop later, so typing never lands in a covered terminal.
func updateGitView(open: Bool) {
defer { gitViewOpen = open }
guard open, !gitViewOpen, let window else { return }
window.makeFirstResponder(nil)
}
private func configure(_ window: NSWindow) {
window.title = model.title
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) {
if panel == .sourceControl || panel == .explorer { window.makeFirstResponder(nil) }
if panel == .explorer { window.makeFirstResponder(nil) }
}
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 height = window.contentView?.bounds.height ?? window.frame.height
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 }
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.
DispatchQueue.main.async { [weak self, weak window] in
guard let self, let window, let view = window.firstResponder as? NSView,
@@ -235,8 +247,9 @@ final class WindowCoordinator: NSObject {
var hasSelection = false
var editorSelection: TextSelectionInfo?
var seed = ""
let gitViewOpen = model.layout.isGitViewOpen
if let text = responder as? NSTextView {
let column = column(of: text)
let column = gitViewOpen ? nil : column(of: text)
owner = .text(in: column)
let range = text.selectedRange()
hasSelection = range.length > 0
@@ -270,7 +283,9 @@ final class WindowCoordinator: NSObject {
activePanel: model.layout.activePanel,
focusZone: model.layout.focusZone,
recentFileCount: editor?.history.count ?? 0,
searchSeed: seed
searchSeed: seed,
gitViewOpen: gitViewOpen,
inGitConsole: responder is GitConsoleFieldEditor
)
}
+16 -12
View File
@@ -2,7 +2,8 @@ import AppKit
import HelderCore
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 {
let model: WorkspaceModel
@@ -29,20 +30,27 @@ struct WorkspaceView: View {
.zIndex(1)
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 {
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model).environment(\.pointerLayer, .overlay) }
}
.background(PointerRefresher(trigger: PointerRefresher.Trigger(
overlay: model.overlay.current, activePath: model.editor?.activePath, visibility: model.layout.visibility,
scale: model.layout.textScale)))
overlay: model.overlay.current, gitViewOpen: model.layout.isGitViewOpen, activePath: model.editor?.activePath,
visibility: model.layout.visibility, scale: model.layout.textScale)))
.onAppear { model.layout.windowResized(width: proxy.size.width) }
.onChange(of: proxy.size.width) { _, width in model.layout.windowResized(width: width) }
}
}
}
/// 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
/// hidden the agent column fills. The agent column is keyed by the project so its terminals respawn on a switch.
private struct Columns: View {
@@ -56,12 +64,6 @@ private struct Columns: View {
let agentFills = v.agent && !v.editor
let hiddenEditorWidth = max(editorWidth, Metrics.minEditorWidth)
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)
.frame(width: layout.widths.explorer)
.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.
private struct HiddenPaneFocusGuard: NSViewRepresentable {
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 {
struct Trigger: Equatable {
var overlay: Overlay
var gitViewOpen: Bool
var activePath: String?
var visibility: ColumnVisibility
var scale: Double
+2 -1
View File
@@ -13,7 +13,8 @@ public struct WorkspaceWindow: View {
WorkspaceView(model: model)
.frame(minWidth: Metrics.minimumWindow.width, minHeight: Metrics.minimumWindow.height)
.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)
.focusedSceneValue(\.workspace, model)
.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
}
}
+2 -2
View File
@@ -82,7 +82,7 @@ public final class EditorStore {
/// Closes the overlay only while it is the Diff.
@ObservationIgnored public var dismissDiffOverlay: (() -> 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)?
/// Asked before a dirty file closes; without it a dirty file stays open.
@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)
}
/// `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,
session: SessionStoring, recentFiles: RecentFilesStoring) {
self.root = root
+25 -28
View File
@@ -5,7 +5,6 @@ import Observation
/// Which column has keyboard focus: drives the active-panel tint and arrow-key navigation.
public enum Panel: String, Sendable, CaseIterable {
case sourceControl
case explorer
case editor
case terminal
@@ -13,42 +12,36 @@ public enum Panel: String, Sendable, CaseIterable {
/// The column layout one project remembers between launches.
public struct ColumnLayoutSnapshot: Codable, Sendable, Equatable {
public var sourceControlWidth: Double
public var explorerWidth: Double
public var agentWidth: Double
public var fluid: Bool
public var gitVisible: Bool
public var explorerVisible: Bool
public var fileVisible: Bool
public var claudeVisible: Bool
public init(sourceControlWidth: Double, explorerWidth: Double, agentWidth: Double, fluid: Bool,
visibility: ColumnVisibility = .all) {
self.sourceControlWidth = sourceControlWidth
public init(explorerWidth: Double, agentWidth: Double, fluid: Bool, visibility: ColumnVisibility = .all) {
self.explorerWidth = explorerWidth
self.agentWidth = agentWidth
self.fluid = fluid
gitVisible = visibility.sourceControl
explorerVisible = visibility.explorer
fileVisible = visibility.editor
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 {
let c = try decoder.container(keyedBy: CodingKeys.self)
sourceControlWidth = try c.decode(Double.self, forKey: .sourceControlWidth)
explorerWidth = try c.decode(Double.self, forKey: .explorerWidth)
agentWidth = try c.decode(Double.self, forKey: .agentWidth)
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
fileVisible = try c.decodeIfPresent(Bool.self, forKey: .fileVisible) ?? true
claudeVisible = try c.decodeIfPresent(Bool.self, forKey: .claudeVisible) ?? true
}
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 }
@@ -91,12 +84,14 @@ public struct UserDefaultsLayoutStore: LayoutPersisting, @unchecked Sendable {
@Observable
@MainActor
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.
public private(set) var agentFraction: Double
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
/// ⌘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.
public private(set) var fluid = true
/// ⌘.: dotfiles show in the tree and the search.
@@ -145,25 +140,23 @@ public final class LayoutStore {
self.root = root
activePanel = nil
focusZone = .neutral
isGitViewOpen = false
let saved = persistence?.load(root: root)
visibility = saved?.visibility ?? .all
fluid = saved?.fluid ?? true
if let saved, !saved.fluid {
widths = ColumnWidths(sourceControl: clamp(saved.sourceControlWidth, ColumnLayout.sourceControlRange),
explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
widths = ColumnWidths(explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
agent: max(saved.agentWidth, ColumnLayout.minEditorWidth))
}
refit()
}
public var snapshot: ColumnLayoutSnapshot {
ColumnLayoutSnapshot(sourceControlWidth: widths.sourceControl, explorerWidth: widths.explorer,
agentWidth: widths.agent, fluid: fluid, visibility: visibility)
ColumnLayoutSnapshot(explorerWidth: widths.explorer, agentWidth: widths.agent, fluid: fluid, visibility: visibility)
}
public func isVisible(_ panel: Panel) -> Bool {
switch panel {
case .sourceControl: visibility.sourceControl
case .explorer: visibility.explorer
case .editor: visibility.editor
case .terminal: visibility.agent
@@ -178,7 +171,6 @@ public final class LayoutStore {
public func setVisible(_ panel: Panel, _ visible: Bool) {
guard isVisible(panel) != visible else { return }
switch panel {
case .sourceControl: visibility.sourceControl = visible
case .explorer: visibility.explorer = visible
case .editor: visibility.editor = visible
case .terminal: visibility.agent = visible
@@ -188,6 +180,18 @@ public final class LayoutStore {
save()
}
public func openGitView() {
isGitViewOpen = true
}
public func closeGitView() {
isGitViewOpen = false
}
public func toggleGitView() {
isGitViewOpen.toggle()
}
public func toggleFluid() {
fluid.toggle()
refit()
@@ -221,11 +225,6 @@ public final class LayoutStore {
refit()
}
public func dragSourceControl(by delta: Double) {
fluid = false
widths.sourceControl = clamp(widths.sourceControl + delta, ColumnLayout.sourceControlRange)
}
public func dragExplorer(by delta: Double) {
fluid = false
widths.explorer = clamp(widths.explorer + delta, ColumnLayout.explorerRange)
@@ -267,12 +266,10 @@ public final class LayoutStore {
guard isVisible(panel) else { return nil }
let splitter = ColumnLayout.splitterWidth
let v = visibility
let explorerStart = v.sourceControl ? widths.sourceControl + splitter : 0
let flexStart = explorerStart + (v.explorer ? widths.explorer + splitter : 0)
let flexStart = v.explorer ? widths.explorer + splitter : 0
let agentStart = v.editor ? max(flexStart, windowWidth - widths.agent) : flexStart
switch panel {
case .sourceControl: return 0...widths.sourceControl
case .explorer: return explorerStart...(explorerStart + widths.explorer)
case .explorer: return 0...widths.explorer
case .editor: return flexStart...max(flexStart, v.agent ? agentStart - splitter : windowWidth)
case .terminal: return agentStart...max(agentStart, windowWidth)
}
+330 -124
View File
@@ -3,31 +3,76 @@ import HelderCore
import HelderServices
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
@MainActor
public final class SourceControlStore {
public private(set) var state = GitWorkingState.empty
/// False until the first read landed, so the column can tell "loading" from "clean".
public private(set) var state = GitWorkingState.empty {
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
/// 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 = ""
/// The keyboard cursor, kept as a row id because the list reorders under it.
public var selectedRowID: String?
public private(set) var isPushing = false
/// The `git` config section: confirmations and the poll interval.
/// `user.name <user.email>`, read when the view opens.
public private(set) var author: String?
public private(set) var branches = GitBranchList.empty
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() {
didSet {
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`.
@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 derive: @Sendable (GitSnapshot?) -> GitWorkingState
@ObservationIgnored private var refreshGeneration = 0
@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.
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
@@ -35,21 +80,7 @@ public final class SourceControlStore {
self.derive = derive
}
// MARK: Rows
/// 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)
}
// MARK: Derived
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
public var fileStatuses: [String: GitStatus] {
@@ -60,30 +91,63 @@ public final class SourceControlStore {
return out
}
/// Moves the cursor; a cursor whose row vanished starts over at the top.
public func moveSelection(by step: Int) {
let list = rows
guard !list.isEmpty else { return }
guard let index = list.firstIndex(where: { $0.id == selectedRowID }) else {
selectedRowID = list[0].id
return
}
selectedRowID = list[min(max(index + step, 0), list.count - 1)].id
/// Any change, staged or not; it locks branch switching.
public var isDirty: Bool { !state.changes.isEmpty }
/// Distinct changed paths, a file with two rows once.
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
/// 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 canCommit: Bool {
state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
public var syncLabel: String {
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
}
// 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) {
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.
/// A failed read still counts as loaded, so the view never waits forever; its error lands in the console once.
public func refresh() async {
refreshGeneration += 1
let generation = refreshGeneration
@@ -91,10 +155,18 @@ public final class SourceControlStore {
do {
snapshot = try await git.load()
} 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
}
guard generation == refreshGeneration else { return }
loggedStatusError = nil
let derive = self.derive
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
guard generation == refreshGeneration else { return }
@@ -102,104 +174,253 @@ public final class SourceControlStore {
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 {
if !hasLoaded { await refresh() }
}
public func stage(_ path: String) async {
await run("Stage failed", detail: path) { try await self.git.stage([path]) }
public func reloadBranches() async {
branches = await git.branches()
}
public func unstage(_ path: String) async {
await run("Unstage failed", detail: path) { try await self.git.unstage([path]) }
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
/// 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.
public func stageAll() async {
let paths = state.unstagedPaths
// MARK: Staging
/// 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 }
await run("Stage failed", detail: nil) { try await self.git.stage(paths) }
await run(["add", "--"] + paths)
await afterCommand()
}
public func unstageAll() async {
let paths = stagedPaths
/// A staged rename takes its source along, or the old path stays staged as deleted.
/// 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 }
await run("Unstage failed", detail: nil) { try await self.git.unstage(paths) }
}
/// Commits the staged files with the draft, clears it, and returns how many files went in (0 when nothing did).
public func commit() async -> Int {
let message = commitMessage.trimmingCharacters(in: .whitespaces)
guard !message.isEmpty, state.stagedCount > 0 else { return 0 }
let count = Set(state.changes.filter(\.staged).map(\.path)).count
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
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)
let withSources = paths + sources.filter { !paths.contains($0) }
let pathspec = all ? ["."] : ["--"] + withSources
let result = await run(["restore", "--staged"] + pathspec)
if !result.succeeded && result.stderr.contains("HEAD") {
await run(["rm", "--cached", "-r"] + pathspec)
}
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
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
return count
if andPush { await push() }
}
public func push() async -> PushResult {
guard !isPushing else { return PushResult(ok: false, message: "A push is already running") }
isPushing = true
notify("Pushing…", nil)
let result = await git.push()
isPushing = false
await refresh()
notify(result.ok ? "Pushed" : "Push failed", result.message)
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
public func push() async {
guard busy == nil else { return }
busy = .push
let branch = state.branch
let ahead = state.ahead
var arguments = ["push"]
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
}
public func discard(_ path: String) async {
do {
try await git.discard([path])
} catch {
Log.error("git", "discard failed: \(error)")
notify("Discard failed", path)
await refresh()
return
}
private func afterCommand() async {
await refresh()
notify("Discarded changes", path)
await reloadBranches()
}
// MARK: Actions
/// The confirm dialog an action needs first under the config, or nil to run it straight away.
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
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
}
private func log(_ text: String, _ kind: GitLineKind) {
lines.append(GitConsoleEntry(id: nextLineID, line: GitConsoleLine(text: text, kind: kind)))
nextLineID += 1
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
}
/// Runs a git action that is already confirmed; false for actions this store does not own.
@discardableResult
public func perform(_ action: ContextAction) async -> Bool {
switch action {
case let .stage(path): await stage(path)
case let .unstage(path): await unstage(path)
case let .discard(path): await discard(path)
default: return false
/// The toast detail of a failed run: its first error line, else its last line that is not a hint.
private static func failureDetail(of result: GitCommandResult, arguments: [String]) -> String? {
var classifier = GitOutputClassifier(arguments: arguments)
let lines = [(result.stderr, true), (result.stdout, false)].flatMap { text, isError in
text.split(whereSeparator: \.isNewline).map { (String($0), isError) }
}
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
@@ -225,19 +446,4 @@ public final class SourceControlStore {
}
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
func focus(_ panel: Panel) {
let previous = layout.activePanel
layout.focus(panel)
guard layout.activePanel == panel else { return }
focusRequest = FocusRequest(.panel(panel))
if panel == .editor { editor?.requestTextFocus() }
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
}
func moveRowCursor(by step: Int) {
switch layout.activePanel {
case .sourceControl: sourceControl?.moveSelection(by: step)
case .explorer: explorer?.moveSelection(by: step, showHidden: layout.showHidden)
default: break
}
guard layout.activePanel == .explorer else { return }
explorer?.moveSelection(by: step, showHidden: layout.showHidden)
}
func openSelectedRow() {
switch layout.activePanel {
case .sourceControl:
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
}
guard layout.activePanel == .explorer, let explorer, let row = selectedTreeRow() else { return }
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
}
// MARK: Editor
@@ -42,29 +42,12 @@ extension WorkspaceModel {
// 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() {
switch layout.activePanel {
case .sourceControl:
guard let row = selectedGitRow() else { return }
showContextMenu(.gitRow(path: row.change.path, staged: row.change.staged),
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)
guard layout.activePanel == .explorer, 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))
}
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
@@ -90,7 +73,13 @@ extension WorkspaceModel {
let sourceControl = sourceControl, explorer = explorer, editor = editor
switch action {
case let .passOnReference(reference, code):
closeGitView()
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):
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
case let .bouwen(name):
@@ -118,18 +107,16 @@ extension WorkspaceModel {
case let .rename(path, isDirectory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
initialName: PathUtils.basename(path), anchor: anchor)))
case let .openDiff(path):
open(path, OpenOptions(showDiff: true))
case let .showDiff(path, line):
if editor?.activePath == path { editor?.openDiff(atLine: line) }
case let .copyTerminalSelection(kind):
if let text = terminal.selection(kind) { app.system.copy(text) }
case let .pasteIntoTerminal(kind):
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
case let .discard(path):
case let .gitDiscard(paths):
track {
await sourceControl?.discard(path)
await editor?.reloadFromDisk(path)
await sourceControl?.discard(paths)
for path in paths where editor?.isLoaded(path) == true { await editor?.reloadFromDisk(path) }
}
case let .delete(path, isDirectory):
track {
@@ -138,10 +125,7 @@ extension WorkspaceModel {
await sourceControl?.refresh()
}
default:
track {
if await sourceControl?.perform(action) == true { return }
await explorer?.perform(action)
}
track { _ = await explorer?.perform(action) }
}
}
@@ -54,6 +54,7 @@ extension WorkspaceModel {
let sourceControl = SourceControlStore(git: services.git)
sourceControl.notify = notify
sourceControl.focusMessage = { [weak self] in self?.focusRequest = FocusRequest(.commitMessage) }
self.sourceControl = sourceControl
let explorer = ExplorerStore(files: services.files, system: app.system)
+32 -14
View File
@@ -45,8 +45,6 @@ public struct RefreshScope: OptionSet, Sendable {
/// A list row whose on-screen frame the ⌘→ menu anchors to.
public enum RowKey: Hashable, Sendable {
/// A Source Control row, by `Change.id`.
case git(String)
/// An Explorer row, by path.
case tree(String)
}
@@ -100,7 +98,7 @@ public final class WorkspaceModel {
@ObservationIgnored var lifecycleTask: Task<Void, Never>?
/// Moves on every project switch, so work that awaited across one can tell its project is gone.
@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 hasStarted = false
@ObservationIgnored var resignedKey = false
@@ -148,7 +146,8 @@ public final class WorkspaceModel {
case let .launcherSelect(index): launcher.select(index)
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 .toggleAutoFit: layout.toggleFluid()
case .toggleHidden: layout.toggleHidden()
@@ -174,15 +173,36 @@ public final class WorkspaceModel {
case .selectAllInFile: editor?.selectAll()
case .commit:
guard let sourceControl, sourceControl.canCommit else { return }
track { _ = await sourceControl.commit() }
guard let sourceControl else { return }
track { await sourceControl.commit() }
case .push:
guard let sourceControl else { return }
track { _ = await sourceControl.push() }
case .focusCommitMessage:
layout.setVisible(.sourceControl, true)
layout.focus(.sourceControl)
focusRequest = FocusRequest(.commitMessage)
track { await sourceControl.push() }
case .pull:
guard let sourceControl else { return }
track {
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()
@@ -230,9 +250,7 @@ public final class WorkspaceModel {
/// A click inside a column: it becomes the active panel without taking first responder.
public func pointerFocused(_ panel: Panel) {
let previous = layout.activePanel
layout.focus(panel)
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
}
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?) {
rowFrames[key] = frame
}
-6
View File
@@ -4,7 +4,6 @@ public enum Metrics {
// MARK: Rows and bars
public static let explorerRow: CGFloat = 24
public static let sourceControlRow: CGFloat = 26
public static let statusBar: CGFloat = 28
public static let contextMenuItem: CGFloat = 30
/// 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 launcherNewRow: CGFloat = 46
public static let searchQueryBar: CGFloat = 54
public static let commitBox: CGFloat = 52
public static let pushButton: CGFloat = 34
// MARK: Radii
@@ -40,7 +37,6 @@ public enum Metrics {
// MARK: Columns
public static let sourceControlWidth: CGFloat = 236
public static let explorerWidth: CGFloat = 288
public static let agentWidth: CGFloat = 480
public static let minEditorWidth: CGFloat = 280
@@ -80,8 +76,6 @@ public enum Metrics {
// MARK: Overlays
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 passOnWidth: CGFloat = 460
public static let launcherWidth: CGFloat = 520
+38 -5
View File
@@ -49,8 +49,6 @@ public enum Palette {
public static let amberKeycapBorder = Color(hex: 0xE8913A, alpha: 0.35)
/// Text on an amber fill: always ink, never white.
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.
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 menuIconRename = Color(hex: 0xBAC0C0)
/// Git status letters: staged rows in teal, unstaged in amber-soft.
public static let stagedLetter = Color(hex: 0x8FBFB4)
public static let unstagedLetter = Color(hex: 0xF0B476)
// MARK: Git view
/// 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 {
+19 -1
View File
@@ -77,7 +77,7 @@ public enum Typography {
public static let terminal = TypeRole(.monoRegular, 12, lineHeight: 20.4)
public static let row = TypeRole(.sansRegular, 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 tooltip = TypeRole(.sansRegular, 12, lineHeight: 18)
public static let button = TypeRole(.sansMedium, 12)
@@ -88,10 +88,28 @@ public enum Typography {
public static let toolbarLabel = TypeRole(.sansRegular, 12)
public static let menuItem = TypeRole(.sansRegular, 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 markdownH2 = TypeRole(.monoBold, 24, lineHeight: 26.4, trackingEm: -0.03)
public static let markdownH3 = TypeRole(.monoBold, 17, lineHeight: 20.4)
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 {