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
@@ -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))
}
}