restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
+47
View File
@@ -0,0 +1,47 @@
import SwiftUI
/// The stepped on/off blink of the caret, terminal cursor and wordmark period: no fade.
struct BlinkModifier: ViewModifier {
var isActive: Bool
func body(content: Content) -> some View {
if isActive {
TimelineView(.periodic(from: .now, by: Metrics.blinkInterval / 2)) { context in
content.opacity(Self.isOn(at: context.date) ? 1 : 0)
}
} else {
content
}
}
/// On for the first half of each 1.1s cycle, off for the second.
static func isOn(at date: Date) -> Bool {
let half = Metrics.blinkInterval / 2
return Int(date.timeIntervalSinceReferenceDate / half).isMultiple(of: 2)
}
}
extension View {
/// Blinks the view with the design's stepped 1.1s cycle.
public func blinking(_ isActive: Bool = true) -> some View {
modifier(BlinkModifier(isActive: isActive))
}
}
/// `Helder` with the blinking amber period.
public struct Wordmark: View {
var role: TypeRole
public init(role: TypeRole = Typography.wordmark) {
self.role = role
}
public var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text("Helder").foregroundStyle(Palette.text1)
Text(".").foregroundStyle(Palette.amber).blinking()
}
.typeRole(role)
.fixedSize()
}
}
+89
View File
@@ -0,0 +1,89 @@
import SwiftUI
/// The one primary action on a surface: amber fill, ink Sans 500 12 label, radius 2, padding 6×10.
/// `destructive` switches to amber-deep with a light label (Delete, Discard).
public struct PrimaryButtonStyle: ButtonStyle {
var destructive: Bool
public init(destructive: Bool = false) {
self.destructive = destructive
}
public func makeBody(configuration: Configuration) -> some View {
configuration.label
.typeRole(Typography.button)
.foregroundStyle(destructive ? Palette.onDeep : Palette.ink)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(destructive ? Palette.amberDeep : Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
}
/// A secondary action beside a primary one (Cancel): hairline border, text-3 label, hover fill.
public struct SecondaryButtonStyle: ButtonStyle {
public init() {}
public func makeBody(configuration: Configuration) -> some View {
SecondaryButtonBody(configuration: configuration)
}
}
private struct SecondaryButtonBody: View {
let configuration: ButtonStyleConfiguration
@State private var isHovered = false
var body: some View {
configuration.label
.typeRole(Typography.button)
.foregroundStyle(isHovered || configuration.isPressed ? Palette.text1 : Palette.text3)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(isHovered || configuration.isPressed ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
extension ButtonStyle where Self == PrimaryButtonStyle {
public static var primary: PrimaryButtonStyle { PrimaryButtonStyle() }
public static var destructive: PrimaryButtonStyle { PrimaryButtonStyle(destructive: true) }
}
extension ButtonStyle where Self == SecondaryButtonStyle {
public static var secondary: SecondaryButtonStyle { SecondaryButtonStyle() }
}
/// The focus treatment used everywhere: a 2pt amber border plus a 2pt 22% amber ring outside it.
struct FocusRingModifier: ViewModifier {
var isFocused: Bool
var cornerRadius: CGFloat
func body(content: Content) -> some View {
content
.overlay(
RoundedRectangle(cornerRadius: cornerRadius)
.strokeBorder(isFocused ? Palette.amber : Palette.raised, lineWidth: isFocused ? Metrics.accentRule : Metrics.hairline)
)
.background(
RoundedRectangle(cornerRadius: cornerRadius + Metrics.focusRingWidth)
.fill(isFocused ? Palette.focusRing : .clear)
.padding(-Metrics.focusRingWidth)
)
.animation(Metrics.smallControlTransition, value: isFocused)
}
}
extension View {
/// Draws the field border: a hairline at rest, the amber border and ring when focused. Never remove it.
public func focusRing(_ isFocused: Bool, cornerRadius: CGFloat = Metrics.radiusSmall) -> some View {
modifier(FocusRingModifier(isFocused: isFocused, cornerRadius: cornerRadius))
}
/// Disabled is 40% opacity and nothing else: no recolouring.
public func disabledLook(_ isDisabled: Bool) -> some View {
opacity(isDisabled ? 0.4 : 1).allowsHitTesting(!isDisabled)
}
}
@@ -0,0 +1,116 @@
import SwiftUI
/// The context-menu surface: 320pt, `panel`, hairline border, radius 4, menu shadow, 8pt vertical padding.
/// Fill it with a `ContextMenuHeader`, then `ContextMenuRow`s and `ContextMenuSeparator`s.
public struct ContextMenuPanel<Content: View>: View {
var content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
VStack(alignment: .leading, spacing: 0) { content }
.padding(.vertical, 8)
.frame(width: Metrics.contextMenuWidth, alignment: .leading)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
}
/// The path line at the top of a context menu: mono 11, text-4, hairline below.
public struct ContextMenuHeader: View {
var text: String
public init(_ text: String) {
self.text = text
}
public var body: some View {
Text(text)
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 14)
.padding(.bottom, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.hairline(.bottom)
.padding(.bottom, 8)
}
}
/// One 30pt menu item. Highlighted: `raised` fill, 2pt amber left rule, text-1 500 label, amber icon.
/// A tinted icon keeps its tint when highlighted; destructive items stay amber-deep in every state.
public struct ContextMenuRow: View {
var label: String
var systemImage: String?
var iconTint: Color?
var shortcut: String?
var isHighlighted: Bool
var isDestructive: Bool
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
isHighlighted: Bool, isDestructive: Bool = false) {
self.label = label
self.systemImage = systemImage
self.iconTint = iconTint
self.shortcut = shortcut
self.isHighlighted = isHighlighted
self.isDestructive = isDestructive
}
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
nonisolated public static let spark = "helder.spark"
public var body: some View {
HStack(spacing: 10) {
if systemImage == Self.spark {
SparkGlyph()
.stroke(iconColor, style: StrokeStyle(lineWidth: 1.1 * 13 / 16, lineJoin: .round))
.frame(width: 13, height: 13)
.frame(width: 15)
} else if let systemImage {
Image(systemName: systemImage)
.font(.system(size: 12, weight: .light))
.foregroundStyle(iconColor)
.frame(width: 15)
}
Text(label).typeRole(isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem)
.foregroundStyle(labelColor)
Spacer(minLength: 8)
if let shortcut {
Text(shortcut).typeRole(Typography.chip).foregroundStyle(Palette.text4)
}
}
.padding(.leading, 16)
.padding(.trailing, 14)
.frame(height: Metrics.contextMenuItem)
.background(isHighlighted ? Palette.raised : .clear)
.overlay(alignment: .leading) {
Rectangle().fill(isHighlighted ? Palette.amber : .clear).frame(width: Metrics.accentRule)
}
.contentShape(Rectangle())
}
private var labelColor: Color {
if isDestructive { return Palette.removedText }
return isHighlighted ? Palette.text1 : Palette.text3
}
private var iconColor: Color {
if isDestructive { return Palette.removedText }
if let iconTint { return iconTint }
return isHighlighted ? Palette.amber : Palette.text4
}
}
/// The 1pt rule between menu groups, with 6pt above and below.
public struct ContextMenuSeparator: View {
public init() {}
public var body: some View {
Hairline().padding(.vertical, 6)
}
}
@@ -0,0 +1,38 @@
import SwiftUI
/// The 1pt `raised` divider. Use it for every border between panels, rows and bars.
public struct Hairline: View {
var axis: Axis
/// `.horizontal` draws a line across (a row divider); `.vertical` draws a column divider.
public init(_ axis: Axis = .horizontal) {
self.axis = axis
}
public var body: some View {
Rectangle()
.fill(Palette.raised)
.frame(width: axis == .vertical ? Metrics.hairline : nil,
height: axis == .horizontal ? Metrics.hairline : nil)
}
}
extension View {
/// Draws a hairline along one edge without changing the layout.
public func hairline(_ edge: Edge) -> some View {
overlay(alignment: edge.alignment) {
Hairline(edge == .top || edge == .bottom ? .horizontal : .vertical)
}
}
}
extension Edge {
fileprivate var alignment: Alignment {
switch self {
case .top: .top
case .bottom: .bottom
case .leading: .leading
case .trailing: .trailing
}
}
}
+78
View File
@@ -0,0 +1,78 @@
import SwiftUI
/// A key hint: 12pt mono 600, amber glyph, 1pt border, radius 2. Use it for every shortcut shown in the UI.
public struct Keycap: View {
public enum Style {
/// Amber glyph, raised border.
case normal
/// On an active toolbar toggle: the border turns amber.
case active
/// On a toggle that is off by meaning: glyph and border step back to text-4.
case muted
/// On an amber fill (primary button): ink glyph, ink border.
case onAmber
/// On an amber-deep fill (destructive button): light glyph, light border.
case onDeep
}
var keys: String
var style: Style
var role: TypeRole
public init(_ keys: String, style: Style = .normal, small: Bool = false) {
self.keys = keys
self.style = style
role = small ? Typography.keycapSmall : Typography.keycap
}
public init(_ keys: String, highlighted: Bool) {
self.init(keys, style: highlighted ? .active : .normal)
}
public var body: some View {
Text(keys)
.typeRole(role)
.foregroundStyle(glyph)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(border, lineWidth: Metrics.hairline))
.fixedSize()
}
private var glyph: Color {
switch style {
case .normal, .active: Palette.amber
case .muted: Palette.text4
case .onAmber: Palette.ink
case .onDeep: Palette.onDeep
}
}
private var border: Color {
switch style {
case .normal, .muted: Palette.raised
case .active: Palette.amberKeycapBorder
case .onAmber: Palette.inkKeycapBorder
case .onDeep: Palette.onDeep.opacity(0.4)
}
}
}
/// The `esc` (or `↵`) chip at the right of an overlay header or footer: mono 11, text-4, hairline border.
public struct EscChip: View {
var label: String
public init(_ label: String = "esc") {
self.label = label
}
public var body: some View {
Text(label)
.typeRole(Typography.chip)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.fixedSize()
}
}
@@ -0,0 +1,146 @@
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; `.sized` centres a fixed-width card
/// at the top. A click on the scrim calls `onDismiss`.
public struct OverlayShell<Content: View>: View {
public enum Placement {
/// Search, Diff: the whole window minus the 34pt inset.
case inset
/// A card of this width, top-aligned inside the inset.
case sized(width: CGFloat)
}
var placement: Placement
var onDismiss: () -> Void
var content: Content
public init(_ placement: Placement = .inset, 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: .infinity, maxHeight: .infinity)
case let .sized(width):
OverlayCard { content }
.frame(width: width)
}
}
}
/// The overlay card alone, for surfaces that place themselves (the launcher, the pass-on prompt).
public struct OverlayCard<Content: View>: View {
var content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
content
.background(Palette.panel)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusOverlay).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius / 2, y: Metrics.overlayShadowY)
}
}
/// An overlay's header row: glyph (amber by default), mono 700 14 title, an optional mono detail right after it,
/// optional trailing content, then the `esc` chip unless `showsEscChip` is false.
public struct OverlayHeader<Trailing: View>: View {
var systemImage: String
var title: String
var detail: String?
var iconColor: Color
var showsEscChip: Bool
var height: CGFloat
var trailing: Trailing
public init(systemImage: String, title: String, detail: String? = nil, iconColor: Color = Palette.amber,
showsEscChip: Bool = true, height: CGFloat = 50, @ViewBuilder trailing: () -> Trailing) {
self.systemImage = systemImage
self.title = title
self.detail = detail
self.iconColor = iconColor
self.showsEscChip = showsEscChip
self.height = height
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 12) {
Image(systemName: systemImage).font(.system(size: 14, weight: .light)).foregroundStyle(iconColor)
Text(title).typeRole(Typography.dialogTitle).foregroundStyle(Palette.text1)
if let detail {
Text(detail).typeRole(Typography.path).foregroundStyle(Palette.text4).lineLimit(1)
}
Spacer(minLength: 12)
trailing
if showsEscChip { EscChip() }
}
.padding(.horizontal, 18)
.frame(height: height)
.hairline(.bottom)
}
}
extension OverlayHeader where Trailing == EmptyView {
public init(systemImage: String, title: String, detail: String? = nil, iconColor: Color = Palette.amber,
showsEscChip: Bool = true, height: CGFloat = 50) {
self.init(systemImage: systemImage, title: title, detail: detail, iconColor: iconColor,
showsEscChip: showsEscChip, height: height) { EmptyView() }
}
}
/// An overlay footer (38pt): mono 11 key hints with amber glyphs. Build the hints with `OverlayFooter.hint`.
public struct OverlayFooter<Trailing: View>: View {
var hints: Text
var trailing: Trailing
public init(_ hints: Text, @ViewBuilder trailing: () -> Trailing) {
self.hints = hints
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 14) {
hints.typeRole(Typography.chip)
Spacer(minLength: 0)
trailing
}
.padding(.horizontal, 18)
.frame(height: 38)
.hairline(.top)
}
}
extension OverlayFooter where Trailing == EmptyView {
public init(_ hints: Text) {
self.init(hints) { EmptyView() }
}
/// "⌘↑↓ navigate · ↵ open": pass pairs of (keys, action).
public static func hint(_ pairs: [(keys: String, action: String)]) -> Text {
pairs.enumerated().reduce(Text("")) { text, item in
let (index, pair) = item
let separator = index == 0 ? Text("") : Text(" · ").foregroundColor(Palette.text4)
return text + separator + Text(pair.keys).foregroundColor(Palette.amber) + Text(" " + pair.action).foregroundColor(Palette.text4)
}
}
}
@@ -0,0 +1,53 @@
import SwiftUI
/// The 10pt uppercase mono label over a panel or section, with an optional amber count.
public struct PanelLabel: View {
var title: String
var count: Int?
public init(_ title: String, count: Int? = nil) {
self.title = title
self.count = count
}
public var body: some View {
HStack {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer()
if let count {
Text("\(count)").typeRole(Typography.panelLabel).foregroundStyle(Palette.amber)
}
}
}
}
/// 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.
public struct PanelHeader<Trailing: View>: View {
var title: String
var height: CGFloat
var trailing: Trailing
public init(_ title: String, height: CGFloat = Metrics.panelHeader, @ViewBuilder trailing: () -> Trailing) {
self.title = title
self.height = height
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 8) {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer(minLength: 8)
trailing
}
.padding(.horizontal, 12)
.frame(height: height)
.hairline(.bottom)
}
}
extension PanelHeader where Trailing == EmptyView {
public init(_ title: String, height: CGFloat = Metrics.panelHeader) {
self.init(title, height: height) { EmptyView() }
}
}
@@ -0,0 +1,34 @@
import SwiftUI
/// A framed segment button: hairline frame, radius 2; while on, an amber fill with ink text.
public struct SegmentButton: View {
var label: String
var isOn: Bool
var action: () -> Void
@State private var isHovered = false
public init(_ label: String, isOn: Bool, action: @escaping () -> Void) {
self.label = label
self.isOn = isOn
self.action = action
}
public var body: some View {
Button(action: action) {
Text(label)
.typeRole(isOn ? Typography.segmentOn : Typography.segment)
.foregroundStyle(isOn ? Palette.ink : isHovered ? Palette.text1 : Palette.text3)
.padding(.horizontal, 12)
.padding(.vertical, 5)
.background(isOn ? Palette.amber : isHovered ? Palette.hover : .clear)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.fixedSize()
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.accessibilityAddTraits(isOn ? .isSelected : [])
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
@@ -0,0 +1,24 @@
import SwiftUI
/// Row states shared by every list (git rows, tree rows, launcher, search hits): hover is one fill step,
/// selected is `raised` with the 2pt amber rule on the left. Nothing lifts, scales or fades.
struct SelectableRowModifier: ViewModifier {
var isSelected: Bool
var isHovered: Bool
func body(content: Content) -> some View {
content
.background(isSelected ? Palette.raised : isHovered ? Palette.hover : .clear)
.overlay(alignment: .leading) {
Rectangle().fill(isSelected ? Palette.amber : .clear).frame(width: Metrics.accentRule)
}
.animation(Metrics.colorTransition, value: isHovered)
}
}
extension View {
/// Applies the selected and hover fills plus the amber selection rule.
public func selectableRow(isSelected: Bool, isHovered: Bool = false) -> some View {
modifier(SelectableRowModifier(isSelected: isSelected, isHovered: isHovered))
}
}
@@ -0,0 +1,66 @@
import AppKit
import SwiftUI
/// A 1pt hairline divider that resizes what is next to it. The pointer target reaches 3pt past the line
/// on both sides; hover and drag turn the line amber. `onDrag` receives the movement since the last call.
public struct Splitter: View {
var axis: Axis
var onDrag: (Double) -> Void
var onEnd: () -> Void
@State private var isHovered = false
@State private var isDragging = false
@State private var last: CGFloat = 0
/// `.vertical` is a column divider dragged left and right; `.horizontal` a row divider dragged up and down.
public init(_ axis: Axis = .vertical, onDrag: @escaping (Double) -> Void, onEnd: @escaping () -> Void = {}) {
self.axis = axis
self.onDrag = onDrag
self.onEnd = onEnd
}
public var body: some View {
Rectangle()
.fill(isHovered || isDragging ? Palette.amber : Palette.raised)
.frame(width: axis == .vertical ? Metrics.hairline : nil, height: axis == .horizontal ? Metrics.hairline : nil)
.overlay {
Color.clear
.frame(width: axis == .vertical ? Metrics.splitterHitArea : nil,
height: axis == .horizontal ? Metrics.splitterHitArea : nil)
.contentShape(Rectangle())
.onHover(perform: hover)
.gesture(drag)
}
.zIndex(5)
.animation(Metrics.smallControlTransition, value: isHovered || isDragging)
}
private var drag: some Gesture {
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
let position = axis == .vertical ? value.translation.width : value.translation.height
if !isDragging {
isDragging = true
last = 0
}
onDrag(Double(position - last))
last = position
}
.onEnded { _ in
isDragging = false
last = 0
if !isHovered { NSCursor.pop() }
onEnd()
}
}
private func hover(_ inside: Bool) {
guard inside != isHovered else { return }
isHovered = inside
if isDragging { return }
if inside {
(axis == .vertical ? NSCursor.resizeLeftRight : NSCursor.resizeUpDown).push()
} else {
NSCursor.pop()
}
}
}
@@ -0,0 +1,75 @@
import SwiftUI
/// A title-bar toggle: Sans 12 label plus keycap. Off has no fill; on gets the amber tint and an amber keycap border;
/// `muted` is for a toggle that is off by meaning (hidden files), where label and keycap step back to text-4.
public struct ToolbarToggle: View {
var label: String
var keys: String
var isOn: Bool
var isMuted: Bool
var action: () -> Void
@State private var isHovered = false
public init(_ label: String, keys: String, isOn: Bool, muted: Bool = false, action: @escaping () -> Void) {
self.label = label
self.keys = keys
self.isOn = isOn
isMuted = muted
self.action = action
}
public var body: some View {
Button(action: action) {
HStack(spacing: 8) {
Text(label).typeRole(isOn ? Typography.toolbarLabelOn : Typography.toolbarLabel)
Keycap(keys, style: isOn ? .active : isMuted ? .muted : .normal)
}
.foregroundStyle(labelColor)
.padding(Metrics.toolbarPadding)
.background(fill, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
.animation(Metrics.smallControlTransition, value: isOn)
}
private var labelColor: Color {
if isOn { return Palette.text1 }
if isMuted { return isHovered ? Palette.text3 : Palette.text4 }
return isHovered ? Palette.text1 : Palette.text3
}
private var fill: Color {
if isOn { return Palette.amberTint }
return isHovered && !isMuted ? Palette.hover : .clear
}
}
/// The icon-only title-bar control (the `?`): a 26pt square with a hairline border.
public struct ToolbarIconButton: View {
var glyph: String
var action: () -> Void
@State private var isHovered = false
public init(_ glyph: String, action: @escaping () -> Void) {
self.glyph = glyph
self.action = action
}
public var body: some View {
Button(action: action) {
Text(glyph)
.typeRole(Typography.keycap)
.foregroundStyle(isHovered ? Palette.text1 : Palette.text4)
.frame(width: Metrics.toolbarIconButton, height: Metrics.toolbarIconButton)
.background(isHovered ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
+76
View File
@@ -0,0 +1,76 @@
import SwiftUI
/// The design's tooltip: `raised` surface, text-5 border, radius 2, Sans 12/1.5, no arrow, no shadow.
/// Name the current state in amber with `Tooltip.stated`, then say what a click does.
public struct Tooltip: View {
var text: Text
public init(_ text: Text) {
self.text = text
}
public init(_ string: String) {
text = Text(string)
}
/// "Lead: *state* — rest", with the state word in amber.
public static func stated(_ lead: String, _ state: String, _ rest: String) -> Text {
Text(lead).foregroundColor(Palette.text2) + Text(state).foregroundColor(Palette.amber) + Text(rest).foregroundColor(Palette.text2)
}
public var body: some View {
text
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text2)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.frame(maxWidth: Metrics.tooltipMaxWidth, alignment: .leading)
.fixedSize()
.background(Palette.raised, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.tooltipBorder, lineWidth: Metrics.hairline))
}
}
struct TooltipModifier: ViewModifier {
var text: Text
var edge: HorizontalAlignment
@State private var isShown = false
@State private var pending: Task<Void, Never>?
func body(content: Content) -> some View {
content
.onHover { inside in
pending?.cancel()
if inside {
pending = Task { @MainActor in
try? await Task.sleep(for: Metrics.tooltipDelay)
if !Task.isCancelled { isShown = true }
}
} else {
isShown = false
}
}
.simultaneousGesture(TapGesture().onEnded { pending?.cancel(); isShown = false })
.overlay(alignment: Alignment(horizontal: edge, vertical: .bottom)) {
if isShown {
Tooltip(text)
.alignmentGuide(.bottom) { $0[.top] - 8 }
.allowsHitTesting(false)
}
}
}
}
extension View {
/// Shows a design tooltip 350ms after the pointer rests on the view, 8pt below it.
/// The host must sit above its neighbours (`zIndex`) so the tip is not drawn under them.
public func tip(_ text: Text, edge: HorizontalAlignment = .leading) -> some View {
modifier(TooltipModifier(text: text, edge: edge))
}
public func tip(_ string: String, edge: HorizontalAlignment = .leading) -> some View {
tip(Text(string), edge: edge)
}
}
@@ -0,0 +1,21 @@
import HelderCore
import SwiftUI
/// The per-extension chip: a fixed 28pt wide, mono 600 10 in ink on the badge fill, radius 2.
/// The fixed width keeps the file names beside it in one column.
public struct TypeBadge: View {
var badge: FileBadge
public init(path: String) {
badge = FileType.badge(for: path)
}
public var body: some View {
Text(badge.text)
.typeRole(TypeRole(.monoSemiBold, 10))
.foregroundStyle(Palette.badgeText)
.lineLimit(1)
.frame(width: 28, height: 16)
.background(Palette.badge(badge.tint), in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
+174
View File
@@ -0,0 +1,174 @@
import AppKit
import HelderCore
/// One file's text as the editor holds it: its own storage, undo history, line index and tokens,
/// so switching files swaps storages instead of re-reading and re-colouring the file.
@MainActor
final class CodeDocument: NSObject, NSTextStorageDelegate {
let id: String
let storage = NSTextStorage()
let undoManager = UndoManager()
var revision = -1
var language: Language?
var tabSize = 4
private(set) var scale: CGFloat = 1
private(set) var lineIndex = LineIndex("")
var selection = NSRange(location: 0, length: 0)
var scrollOrigin = NSPoint.zero
private(set) var tokens: [Token] = []
private var tokenTextLength = 0
private var knownSymbols: Set<String> = []
/// Which symbol list the colours were computed with.
private(set) var symbolsVersion = -1
private var generation = 0
/// What changed since the last paint, in current text coordinates.
private var dirty: NSRange?
/// Suppresses the edit bookkeeping while the document replaces its own text.
private var isLoading = false
init(id: String) {
self.id = id
super.init()
storage.delegate = self
}
var length: Int { storage.length }
/// Replaces the whole text from outside (load, reload); the undo history no longer applies.
func load(_ text: String, revision: Int, tabSize: Int) {
self.revision = revision
self.tabSize = tabSize
isLoading = true
storage.setAttributedString(NSAttributedString(string: text, attributes: EditorFonts.baseAttributes(tabSize: tabSize, scale: scale)))
isLoading = false
lineIndex = LineIndex(text)
undoManager.removeAllActions()
tokens = []
tokenTextLength = storage.length
dirty = nil
selection = NSRange(location: min(selection.location, storage.length), length: 0)
}
func setTabSize(_ size: Int) {
guard size != tabSize else { return }
tabSize = size
restyle()
}
/// View → Zoom: the font and row height change in place, keeping the text and its undo history.
func setScale(_ next: CGFloat) {
guard next != scale else { return }
scale = next
restyle()
}
private func restyle() {
let font = EditorFonts.code(scale: scale)
let whole = NSRange(location: 0, length: storage.length)
storage.beginEditing()
storage.addAttribute(.font, value: font, range: whole)
storage.addAttribute(.paragraphStyle, value: EditorFonts.paragraphStyle(tabSize: tabSize, font: font, scale: scale), range: whole)
storage.endEditing()
}
nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions,
range editedRange: NSRange, changeInLength delta: Int) {
guard editedMask.contains(.editedCharacters) else { return }
MainActor.assumeIsolated {
guard !isLoading else { return }
let inserted = (textStorage.string as NSString).substring(with: editedRange)
lineIndex.applyEdit(editedRange: editedRange, delta: delta, inserted: inserted)
markDirty(editedRange, delta: delta)
}
}
private func markDirty(_ range: NSRange, delta: Int) {
guard let previous = dirty else {
dirty = range
return
}
let shiftedEnd = NSMaxRange(previous) >= range.location ? NSMaxRange(previous) + delta : NSMaxRange(previous)
let start = min(previous.location, range.location)
let end = max(shiftedEnd, NSMaxRange(range))
dirty = NSRange(location: start, length: max(0, end - start))
}
// MARK: Highlighting
/// Colours the whole text off the main thread; the plain text shows at once, colours follow.
func highlightAll(symbols: Set<String>, version: Int) {
knownSymbols = symbols
symbolsVersion = version
dirty = nil
run(full: true, delay: nil)
}
/// After a keystroke: waits for a pause, re-tokenises, repaints only what changed.
func highlightEdits() {
run(full: false, delay: .milliseconds(40))
}
private func run(full: Bool, delay: Duration?) {
generation += 1
let mine = generation
guard let language else {
if full { paint(NSRange(location: 0, length: storage.length), with: []) }
return
}
Task { @MainActor [weak self] in
if let delay { try? await Task.sleep(for: delay) }
guard let self, mine == self.generation else { return }
let text = self.storage.string
let symbols = self.knownSymbols
let tokens = await Task.detached(priority: .userInitiated) {
SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
}.value
guard mine == self.generation, (text as NSString).length == self.storage.length else { return }
let length = self.storage.length
let range: NSRange
if full || self.tokens.isEmpty {
range = NSRange(location: 0, length: length)
} else {
let edited = self.dirty ?? NSRange(location: 0, length: 0)
range = HighlightDiff.repaintRange(old: self.tokens, new: tokens, edited: edited,
delta: length - self.tokenTextLength, newLength: length)
}
self.tokens = tokens
self.tokenTextLength = length
self.dirty = nil
self.paint(range, with: tokens)
}
}
private func paint(_ range: NSRange, with tokens: [Token]) {
guard range.length > 0 else { return }
storage.beginEditing()
storage.addAttribute(.foregroundColor, value: EditorColors.syntax(.plain), range: range)
var index = firstToken(endingAfter: range.location, in: tokens)
let end = NSMaxRange(range)
while index < tokens.count, tokens[index].location < end {
let token = tokens[index]
index += 1
guard token.role != .plain else { continue }
let hit = NSIntersectionRange(range, NSRange(location: token.location, length: token.length))
if hit.length > 0 { storage.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: hit) }
}
storage.endEditing()
}
private func firstToken(endingAfter location: Int, in tokens: [Token]) -> Int {
var low = 0
var high = tokens.count
while low < high {
let mid = (low + high) / 2
if tokens[mid].location + tokens[mid].length <= location { low = mid + 1 } else { high = mid }
}
return low
}
/// Ranges of the ⌘-clickable class names, for the underline while ⌘ is held.
var symbolRanges: [NSRange] {
tokens.filter { $0.role == .symbol }.map { NSRange(location: $0.location, length: $0.length) }
}
}
@@ -0,0 +1,130 @@
import AppKit
import HelderCore
/// The pane's own paint: change marks, the read-only caret row, the jump flash, the ⌘ underline and the gutter.
extension CodeEditorController {
/// The caret row is only tinted in the read-only panes; the editable buffer shows the caret alone.
private var caretLine: Int? {
guard !textView.isEditable, let doc = document else { return nil }
let selection = textView.selectedRange()
guard selection.length == 0 else { return nil }
return doc.lineIndex.line(containing: selection.location)
}
/// Behind the text, from the code edge: Actual's tint and teal rule, gap rules, the caret row, the flash.
func drawRowBackgrounds(in rect: NSRect) {
let width = max(textView.bounds.width, rect.maxX)
let caret = caretLine
let flash = flashStrength
forEachRow(in: rect) { row in
let band = NSRect(x: 0, y: row.rect.minY, width: width, height: row.rect.height)
let mark = marks[row.line]
if let mark, mark.tint, let tone = mark.tone {
EditorColors.fill(tone).setFill()
band.fill()
EditorColors.tone(tone).setFill()
NSRect(x: 0, y: band.minY, width: Metrics.accentRule, height: band.height).fill()
} else if mark == nil, row.line == caret {
EditorColors.activeLine.setFill()
band.fill()
}
if row.line == flashLine, flash > 0 {
EditorColors.flash.withAlphaComponent(EditorColors.flash.alphaComponent * flash).setFill()
band.fill(using: .sourceOver)
EditorColors.amber.withAlphaComponent(flash).setFill()
NSRect(x: 0, y: band.minY, width: Metrics.accentRule, height: band.height).fill(using: .sourceOver)
}
drawGapRule(mark, row: row, width: width)
}
}
private func drawGapRule(_ mark: CodeLineMark?, row: Row, width: CGFloat) {
guard let gap = mark?.gap else { return }
let y: CGFloat
switch gap {
case .above:
guard row.isFirst else { return }
y = row.rect.minY
case .below:
guard row.isLast else { return }
y = row.rect.maxY - Metrics.accentRule
}
EditorColors.removedText.setFill()
NSRect(x: 0, y: y, width: width, height: Metrics.accentRule).fill()
}
/// Over the text while ⌘ is held: an amber underline 3pt under the baseline of each clickable class name.
func drawSymbolUnderlines(in rect: NSRect) {
guard symbolsUnderlined, configuration?.knownSymbols.isEmpty == false, let doc = document else { return }
let origin = textView.textContainerOrigin
let visible = layout.glyphRange(forBoundingRect: rect.offsetBy(dx: -origin.x, dy: -origin.y), in: textContainer)
let characters = layout.characterRange(forGlyphRange: visible, actualGlyphRange: nil)
let baseline = EditorFonts.baseline(scale: fontScale)
EditorColors.amber.setFill()
for range in doc.symbolRanges where NSMaxRange(range) <= doc.length && NSIntersectionRange(range, characters).length > 0 {
let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
layout.enumerateEnclosingRects(forGlyphRange: glyphs, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
in: textContainer) { box, _ in
let fragment = self.layout.lineFragmentRect(forGlyphAt: glyphs.location, effectiveRange: nil)
let y = fragment.minY + baseline + 3 + origin.y
NSRect(x: box.minX + origin.x, y: y, width: box.width, height: 1).fill()
}
}
}
/// Numbers only: a changed line in Actual lifts its number to teal; the read-only caret row lifts its number.
func drawGutter(in rect: NSRect, of ruler: CodeGutterView) {
EditorColors.background.setFill()
rect.fill()
let font = EditorFonts.code(scale: fontScale)
let lineHeight = EditorFonts.lineHeight(scale: fontScale)
let caret = caretLine
let thickness = ruler.ruleThickness
forEachRow(in: textView.visibleRect) { row in
let y = ruler.convert(NSPoint(x: 0, y: row.rect.minY), from: textView).y
let band = NSRect(x: 0, y: y, width: thickness, height: row.rect.height)
guard band.intersects(rect) else { return }
let mark = marks[row.line]
var color = mark == nil && row.line == caret ? EditorColors.lineNumberActive : EditorColors.lineNumber
if let mark, mark.tint, let tone = mark.tone { color = EditorColors.tone(tone) }
guard row.isFirst else { return }
let label = String(row.line) as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color]
let size = label.size(withAttributes: attributes)
let baseline = (lineHeight - (font.ascender - font.descender)) / 2
label.draw(at: NSPoint(x: thickness - 14 - size.width, y: band.minY + baseline), withAttributes: attributes)
}
}
// MARK: The jump flash
/// Full strength for the first 65% of the flash, then fading out.
private var flashStrength: CGFloat {
guard flashLine != nil, let start = flashStart else { return 0 }
let elapsed = Date().timeIntervalSince(start) / EditorFonts.flashDuration
if elapsed < 0.65 { return 1 }
return max(0, 1 - (elapsed - 0.65) / 0.35)
}
func startFlash(on line: Int) {
flashLine = line
flashStart = Date()
flashTimer?.invalidate()
flashTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] timer in
MainActor.assumeIsolated {
guard let self else { return timer.invalidate() }
self.textView.needsDisplay = true
if let start = self.flashStart, Date().timeIntervalSince(start) >= EditorFonts.flashDuration { self.endFlash() }
}
}
textView.needsDisplay = true
}
func endFlash() {
flashTimer?.invalidate()
flashTimer = nil
flashLine = nil
flashStart = nil
textView.needsDisplay = true
}
}
@@ -0,0 +1,540 @@
import AppKit
import HelderCore
/// What the code pane shows; rebuilt by SwiftUI on every update, applied only where it changed.
struct CodeEditorConfiguration {
/// Identifies the document: the path plus the variant (`#original` for the HEAD text).
var documentID: String
var path: String
var text: String
/// Replace the view's text only when this moves; otherwise the user's typing is the truth.
var revision: Int
var language: Language?
var isEditable: Bool
var wrap: Bool
var tabSize: Int
/// Cheap identity of the marks; `makeMarks` runs only when it moves.
var marksKey: String
var makeMarks: () -> [Int: CodeLineMark]
var opensDiffOnClick: Bool
var knownSymbols: Set<String>
var symbolsVersion: Int
var flash: LineFlash?
/// The text view takes keyboard focus when this moves while the pane is shown.
var focusRequest: Int
/// ⌘A outside the text view: everything is selected when this moves while the pane is shown.
var selectAllRequest: Int
/// View → Zoom.
var fontScale: CGFloat
var isShown: Bool
}
struct CodeEditorActions {
var edited: (String) -> Void = { _ in }
var cursorMoved: (_ line: Int, _ column: Int) -> Void = { _, _ in }
var selectionChanged: (_ lines: ClosedRange<Int>?, _ code: String?) -> Void = { _, _ in }
var markedLineClicked: (Int) -> Void = { _ in }
/// Reference, selected code, and the anchor in top-left window coordinates.
var contextMenu: (AgentReference, String?, CGPoint) -> Void = { _, _, _ in }
var symbolClicked: (String) -> Void = { _ in }
/// ⌘→ with a selection; returns false when there was nothing to pass.
var passOnSelection: (CGPoint) -> Bool = { _ in false }
var command: (EditorKeyCommand) -> Void = { _ in }
}
@MainActor
final class CodeEditorController: NSObject, NSTextViewDelegate, NSLayoutManagerDelegate {
let scrollView = CodeScrollView()
let textView: CodeTextView
let gutter: CodeGutterView
var actions = CodeEditorActions()
private let layoutManager = NSLayoutManager()
private let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
private var documents: [String: CodeDocument] = [:]
private var recent: [String] = []
private(set) var document: CodeDocument?
private(set) var configuration: CodeEditorConfiguration?
private(set) var marks: [Int: CodeLineMark] = [:]
private var wrap: Bool?
private var appliedFlash: UUID?
var flashLine: Int?
var flashStart: Date?
var flashTimer: Timer?
private(set) var symbolsUnderlined = false
private var appliedFocusRequest: Int?
private var appliedSelectAll: Int?
/// Read by the layout delegate, which AppKit calls off the main-actor annotation.
nonisolated(unsafe) private(set) var fontScale: CGFloat = 1
/// True inside `apply`: store updates then wait a turn, since SwiftUI is mid-update.
private var isApplying = false
var layout: NSLayoutManager { layoutManager }
var textContainer: NSTextContainer { container }
private static let documentCacheSize = 12
override init() {
let storage = NSTextStorage()
storage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(container)
layoutManager.allowsNonContiguousLayout = true
textView = CodeTextView(frame: .zero, textContainer: container)
gutter = CodeGutterView(scrollView: scrollView, orientation: .verticalRuler)
super.init()
layoutManager.delegate = self
configureTextView()
configureScrollView()
}
private func configureTextView() {
let tv = textView
tv.controller = self
tv.delegate = self
tv.isRichText = false
tv.importsGraphics = false
tv.allowsUndo = true
tv.usesFindBar = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.isContinuousSpellCheckingEnabled = false
tv.isGrammarCheckingEnabled = false
tv.isAutomaticLinkDetectionEnabled = false
tv.smartInsertDeleteEnabled = false
tv.drawsBackground = true
tv.backgroundColor = EditorColors.background
tv.insertionPointColor = EditorColors.amber
tv.selectedTextAttributes = [.backgroundColor: EditorColors.selection]
tv.font = EditorFonts.code
tv.textColor = EditorColors.syntax(.plain)
tv.typingAttributes = EditorFonts.baseAttributes(tabSize: 4)
tv.textContainerInset = NSSize(width: 0, height: EditorFonts.topInset)
tv.isVerticallyResizable = true
tv.minSize = .zero
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
container.lineFragmentPadding = 6
}
private func configureScrollView() {
scrollView.onTile = { [weak self] in self?.fitTextView() }
scrollView.documentView = textView
scrollView.drawsBackground = true
scrollView.backgroundColor = EditorColors.background
scrollView.hasVerticalScroller = true
scrollView.autohidesScrollers = true
scrollView.borderType = .noBorder
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: EditorFonts.bottomInset - EditorFonts.topInset, right: 0)
gutter.controller = self
gutter.ruleThickness = Metrics.codeGutter
// Since macOS 14 a view may draw outside its bounds; unclipped, the gutter paints over the columns around it.
gutter.clipsToBounds = true
gutter.clientView = textView
scrollView.verticalRulerView = gutter
scrollView.hasVerticalRuler = true
scrollView.rulersVisible = true
scrollView.contentView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(scrolled), name: NSView.boundsDidChangeNotification,
object: scrollView.contentView)
}
@objc private func scrolled() {
gutter.needsDisplay = true
}
// MARK: Applying the configuration
func apply(_ next: CodeEditorConfiguration) {
isApplying = true
defer { isApplying = false }
let previous = configuration
configuration = next
applyWrap(next.wrap)
applyScale(next.fontScale)
textView.isEditable = next.isEditable
textView.isSelectable = true
var reloaded = false
if document?.id != next.documentID {
reloaded = switchDocument(to: next)
} else if let doc = document, doc.revision != next.revision {
replaceText(of: doc, with: next)
reloaded = true
}
guard let doc = document else { return }
doc.setTabSize(next.tabSize)
doc.setScale(fontScale)
if reloaded || doc.language != next.language || doc.symbolsVersion != next.symbolsVersion {
doc.language = next.language
doc.highlightAll(symbols: next.knownSymbols, version: next.symbolsVersion)
}
if previous?.marksKey != next.marksKey || previous?.documentID != next.documentID {
marks = next.makeMarks()
textView.needsDisplay = true
gutter.needsDisplay = true
}
applyFlash(next.flash, path: next.path)
applyFocusRequest(next)
applySelectAll(next)
}
private func applySelectAll(_ next: CodeEditorConfiguration) {
defer { appliedSelectAll = next.selectAllRequest }
guard let applied = appliedSelectAll, applied != next.selectAllRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.focusTextView()
self.textView.selectAll(nil)
}
}
private func applyScale(_ scale: CGFloat) {
guard scale != fontScale else { return }
fontScale = scale
textView.font = EditorFonts.code(scale: scale)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: configuration?.tabSize ?? 4, scale: scale)
for doc in documents.values { doc.setScale(scale) }
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
textView.needsDisplay = true
gutter.needsDisplay = true
}
/// Waits a turn so an overlay that just closed has left the window, and never takes
/// focus from a text field another overlay is typing in.
private func applyFocusRequest(_ next: CodeEditorConfiguration) {
defer { appliedFocusRequest = next.focusRequest }
guard let applied = appliedFocusRequest, applied != next.focusRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self, let window = self.textView.window else { return }
if let field = window.firstResponder as? NSTextView, field.isFieldEditor { return }
self.focusTextView()
}
}
/// Returns true when the document's text was (re)loaded and needs colouring.
private func switchDocument(to next: CodeEditorConfiguration) -> Bool {
if let current = document {
current.selection = textView.selectedRange()
current.scrollOrigin = scrollView.contentView.bounds.origin
}
let doc = documents[next.documentID] ?? CodeDocument(id: next.documentID)
documents[next.documentID] = doc
recent.removeAll { $0 == next.documentID }
recent.insert(next.documentID, at: 0)
for evicted in recent.dropFirst(Self.documentCacheSize) { documents[evicted] = nil }
recent = Array(recent.prefix(Self.documentCacheSize))
let isNew = doc.revision != next.revision
if isNew {
doc.language = next.language
doc.setScale(fontScale)
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
}
document = doc
layoutManager.replaceTextStorage(doc.storage)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: next.tabSize, scale: fontScale)
textView.setSelectedRange(clamped(doc.selection, in: doc))
appliedFlash = nil
flashLine = nil
let clip = scrollView.contentView
// The ruler gives the clip view a left inset, so its resting origin is not .zero.
let home = NSPoint(x: -clip.contentInsets.left, y: -clip.contentInsets.top)
clip.scroll(to: isNew ? home : doc.scrollOrigin)
scrollView.reflectScrolledClipView(clip)
textView.needsDisplay = true
gutter.needsDisplay = true
reportSelection()
return isNew
}
private func replaceText(of doc: CodeDocument, with next: CodeEditorConfiguration) {
let selection = textView.selectedRange()
let origin = scrollView.contentView.bounds.origin
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
textView.setSelectedRange(NSRange(location: min(selection.location, doc.length), length: 0))
scrollView.contentView.scroll(to: origin)
scrollView.reflectScrolledClipView(scrollView.contentView)
gutter.needsDisplay = true
}
private func clamped(_ range: NSRange, in doc: CodeDocument) -> NSRange {
let location = min(range.location, doc.length)
return NSRange(location: location, length: min(range.length, doc.length - location))
}
/// The text view always fills the visible width; unwrapped it may grow wider.
private func fitTextView() {
let size = scrollView.contentSize
let width = visibleWidth
if textView.frame.origin != .zero { textView.setFrameOrigin(.zero) }
textView.minSize = NSSize(width: width, height: size.height)
if wrap == true || textView.frame.width < width {
textView.frame.size.width = width
}
if textView.frame.height < size.height { textView.frame.size.height = size.height }
}
/// The content width right of the gutter.
private var visibleWidth: CGFloat {
max(1, scrollView.contentSize.width - scrollView.contentView.contentInsets.left)
}
private func applyWrap(_ on: Bool) {
guard wrap != on else { return }
wrap = on
scrollView.hasHorizontalScroller = !on
textView.isHorizontallyResizable = !on
container.widthTracksTextView = on
textView.autoresizingMask = on ? [.width] : []
container.containerSize = NSSize(width: on ? visibleWidth : CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
fitTextView()
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
gutter.needsDisplay = true
}
private func applyFlash(_ flash: LineFlash?, path: String) {
guard let flash, flash.path == path else {
if flashLine != nil { endFlash() }
return
}
guard appliedFlash != flash.id, let doc = document, doc.revision > 0 || doc.length > 0 else { return }
appliedFlash = flash.id
startFlash(on: flash.line)
scroll(toLine: flash.line)
let offset = doc.lineIndex.start(ofLine: flash.line)
textView.setSelectedRange(NSRange(location: min(offset, doc.length), length: 0))
textView.needsDisplay = true
}
/// Centres a line in the pane, as near as the file permits.
func scroll(toLine line: Int) {
guard let doc = document else { return }
let rect = rowRect(forLine: line, in: doc)
let clip = scrollView.contentView
let maxY = max(0, textView.frame.height - clip.bounds.height)
let y = min(max(0, rect.midY - clip.bounds.height / 2), maxY)
clip.scroll(to: NSPoint(x: clip.bounds.origin.x, y: y))
scrollView.reflectScrolledClipView(clip)
}
private func rowRect(forLine line: Int, in doc: CodeDocument) -> NSRect {
let offset = doc.lineIndex.start(ofLine: line)
let origin = textView.textContainerOrigin
guard offset < doc.length else {
return layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
}
let glyph = layoutManager.glyphIndexForCharacter(at: offset)
return layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).offsetBy(dx: origin.x, dy: origin.y)
}
// MARK: Rows
struct Row {
var line: Int
var isFirst: Bool
var isLast: Bool
/// In text view coordinates.
var rect: NSRect
}
/// Every visual row that intersects `rect` (text view coordinates), wrapped rows included.
func forEachRow(in rect: NSRect, _ body: (Row) -> Void) {
guard let doc = document else { return }
let origin = textView.textContainerOrigin
let index = doc.lineIndex
let bounds = rect.offsetBy(dx: -origin.x, dy: -origin.y)
let glyphs = layoutManager.glyphRange(forBoundingRect: bounds, in: container)
var glyph = glyphs.location
while glyph < NSMaxRange(glyphs) {
var fragment = NSRange()
let frame = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &fragment)
let chars = layoutManager.characterRange(forGlyphRange: fragment, actualGlyphRange: nil)
let line = index.line(containing: chars.location)
body(Row(line: line, isFirst: index.isLineStart(chars.location),
isLast: NSMaxRange(chars) >= index.end(ofLine: line),
rect: frame.offsetBy(dx: origin.x, dy: origin.y)))
glyph = max(NSMaxRange(fragment), glyph + 1)
}
if layoutManager.extraLineFragmentTextContainer != nil {
let extra = layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
if extra.intersects(rect.insetBy(dx: 0, dy: -1)) {
body(Row(line: index.lineCount, isFirst: true, isLast: true, rect: extra))
}
}
}
// MARK: Layout: fixed rows, 20pt at actual size
nonisolated func layoutManager(_ layoutManager: NSLayoutManager,
shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<NSRect>,
lineFragmentUsedRect: UnsafeMutablePointer<NSRect>,
baselineOffset: UnsafeMutablePointer<CGFloat>,
in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool {
let height = EditorFonts.lineHeight(scale: fontScale)
lineFragmentRect.pointee.size.height = height
lineFragmentUsedRect.pointee.size.height = height
baselineOffset.pointee = EditorFonts.baseline(scale: fontScale)
return true
}
// MARK: Text view delegate
nonisolated func undoManager(for view: NSTextView) -> UndoManager? {
MainActor.assumeIsolated { document?.undoManager }
}
nonisolated func textDidChange(_ notification: Notification) {
MainActor.assumeIsolated {
guard let doc = document else { return }
doc.highlightEdits()
actions.edited(textView.string)
gutter.needsDisplay = true
}
}
nonisolated func textViewDidChangeSelection(_ notification: Notification) {
MainActor.assumeIsolated {
reportSelection()
textView.needsDisplay = true
gutter.needsDisplay = true
}
}
private func reportSelection() {
if isApplying {
DispatchQueue.main.async { [weak self] in self?.reportSelection() }
return
}
guard let doc = document else { return }
let range = textView.selectedRange()
let caret = min(range.location + range.length, doc.length)
actions.cursorMoved(doc.lineIndex.line(containing: caret), doc.lineIndex.column(of: caret))
if range.length > 0 {
let code = (doc.storage.string as NSString).substring(with: clamped(range, in: doc))
actions.selectionChanged(EditorReference.lines(of: range, in: doc.lineIndex), code)
} else {
actions.selectionChanged(nil, nil)
}
}
// MARK: Gestures
private func characterIndex(atWindowPoint point: NSPoint) -> Int {
textView.characterIndexForInsertion(at: textView.convert(point, from: nil))
}
private func line(atWindowPoint point: NSPoint) -> Int? {
guard let doc = document else { return nil }
let local = textView.convert(point, from: nil)
let used = layoutManager.usedRect(for: container).offsetBy(dx: 0, dy: textView.textContainerOrigin.y)
guard local.y <= used.maxY else { return nil }
return doc.lineIndex.line(containing: characterIndex(atWindowPoint: point))
}
/// A plain click on a marked line in Actual opens the Diff there.
func plainClick(atWindowPoint point: NSPoint) {
guard configuration?.opensDiffOnClick == true,
let line = line(atWindowPoint: point), marks[line] != nil else { return }
let action = actions.markedLineClicked
DispatchQueue.main.async { action(line) }
}
/// ⌘-click: follows a class name the project declares.
func followSymbol(at event: NSEvent) -> Bool {
guard let name = symbol(atWindowPoint: event.locationInWindow) else { return false }
actions.symbolClicked(name)
return true
}
/// The known class name under the pointer; only a hit on the glyph itself counts, not the space after a line.
func symbol(atWindowPoint point: NSPoint) -> String? {
guard let configuration, !configuration.knownSymbols.isEmpty, let doc = document, doc.length > 0 else { return nil }
let origin = textView.textContainerOrigin
let local = textView.convert(point, from: nil)
let inContainer = NSPoint(x: local.x - origin.x, y: local.y - origin.y)
let glyph = layoutManager.glyphIndex(for: inContainer, in: container)
let box = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: container)
guard box.contains(inContainer) else { return nil }
let name = PHPSymbols.word(in: doc.storage.string, at: layoutManager.characterIndexForGlyph(at: glyph))
return configuration.knownSymbols.contains(name) ? name : nil
}
func showContextMenu(for event: NSEvent) {
guard let configuration, let doc = document else { return }
focusTextView()
let selection = textView.selectedRange()
let clicked = line(atWindowPoint: event.locationInWindow) ?? doc.lineIndex.lineCount
let lines = selection.length > 0 ? EditorReference.lines(of: selection, in: doc.lineIndex) : nil
let code = selection.length > 0 ? (doc.storage.string as NSString).substring(with: clamped(selection, in: doc)) : nil
let reference = EditorReference.make(path: configuration.path, selectedLines: lines, clickedLine: clicked)
actions.contextMenu(reference, code, topLeft(event.locationInWindow))
}
func passOnSelection() -> Bool {
let range = textView.selectedRange()
guard range.length > 0, let window = textView.window else { return false }
let screen = textView.firstRect(forCharacterRange: range, actualRange: nil)
let rect = window.convertFromScreen(screen)
return actions.passOnSelection(topLeft(NSPoint(x: rect.minX, y: rect.minY)))
}
func run(_ command: EditorKeyCommand) {
actions.command(command)
}
func indent(outdent: Bool) -> Bool {
guard textView.isEditable, let configuration, let doc = document,
let edit = Indentation.edit(doc.storage.string, selection: textView.selectedRange(),
tabSize: configuration.tabSize, outdent: outdent) else { return textView.isEditable }
guard textView.shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return true }
doc.storage.replaceCharacters(in: edit.range, with: NSAttributedString(string: edit.replacement, attributes: textView.typingAttributes))
textView.didChangeText()
textView.setSelectedRange(edit.selection)
textView.scrollRangeToVisible(edit.selection)
return true
}
func gutterClick(atWindowPoint point: NSPoint, extend: Bool) {
guard let doc = document else { return }
focusTextView()
let local = textView.convert(point, from: nil)
let line = doc.lineIndex.line(containing: textView.characterIndexForInsertion(at: NSPoint(x: 0, y: local.y)))
let start = doc.lineIndex.start(ofLine: line)
let end = doc.lineIndex.end(ofLine: line)
var range = NSRange(location: start, length: end - start)
if extend {
range = NSUnionRange(range, textView.selectedRange())
}
textView.setSelectedRange(range)
}
/// Underlines the class names while ⌘ is held, so the affordance shows exactly when a click would work.
func commandKeyChanged(_ down: Bool) {
guard down != symbolsUnderlined, document != nil else { return }
symbolsUnderlined = down
textView.needsDisplay = true
}
func focusTextView() {
if textView.window?.firstResponder !== textView { textView.window?.makeFirstResponder(textView) }
}
private func topLeft(_ point: NSPoint) -> CGPoint {
let height = textView.window?.contentView?.bounds.height ?? 0
return CGPoint(x: point.x, y: height - point.y)
}
}
/// Tells the controller when the visible size changes, so the text view can follow it.
final class CodeScrollView: NSScrollView {
var onTile: () -> Void = {}
override func tile() {
super.tile()
onTile()
}
}
@@ -0,0 +1,21 @@
import AppKit
import SwiftUI
/// SwiftUI face of the AppKit code pane; all the work happens in `CodeEditorController`.
struct CodeEditorView: NSViewRepresentable {
var configuration: CodeEditorConfiguration
var actions: CodeEditorActions
func makeCoordinator() -> CodeEditorController {
CodeEditorController()
}
func makeNSView(context: Context) -> NSScrollView {
context.coordinator.scrollView
}
func updateNSView(_ view: NSScrollView, context: Context) {
context.coordinator.actions = actions
context.coordinator.apply(configuration)
}
}
+225
View File
@@ -0,0 +1,225 @@
import CoreGraphics
import Foundation
import HelderCore
/// Line starts of a text as UTF-16 offsets, the unit NSTextView and the tokens use.
public struct LineIndex: Equatable, Sendable {
/// Offset of the first character of each line; always starts with 0.
public private(set) var starts: [Int]
public private(set) var length: Int
public init(_ text: String) {
var starts = [0]
var offset = 0
for unit in text.utf16 {
offset += 1
if unit == 10 { starts.append(offset) }
}
self.starts = starts
length = offset
}
/// A text ending in a newline has an empty last line, as the editor shows it.
public var lineCount: Int { starts.count }
/// The 1-based line holding a UTF-16 offset; offsets past the end land on the last line.
public func line(containing offset: Int) -> Int {
var low = 0
var high = starts.count - 1
while low < high {
let mid = (low + high + 1) / 2
if starts[mid] <= offset { low = mid } else { high = mid - 1 }
}
return low + 1
}
public func isLineStart(_ offset: Int) -> Bool {
starts[line(containing: offset) - 1] == offset
}
/// Offset of the first character of a 1-based line, clamped to the text.
public func start(ofLine line: Int) -> Int {
starts[min(max(line, 1), starts.count) - 1]
}
/// The 1-based column of an offset within its line.
public func column(of offset: Int) -> Int {
offset - start(ofLine: line(containing: offset)) + 1
}
/// Offset just past a line: the next line's start, or the end of the text for the last line.
public func end(ofLine line: Int) -> Int {
line < starts.count ? starts[line] : length
}
/// Follows one edit without rescanning the whole text: `editedRange` is in the new text,
/// `inserted` is the text now in that range, `delta` the change in length.
public mutating func applyEdit(editedRange: NSRange, delta: Int, inserted: String) {
let location = editedRange.location
let oldEnd = NSMaxRange(editedRange) - delta
var next = Array(starts.prefix { $0 <= location })
var offset = location
for unit in inserted.utf16 {
offset += 1
if unit == 10 { next.append(offset) }
}
next.append(contentsOf: starts.drop { $0 <= oldEnd }.map { $0 + delta })
starts = next
length += delta
}
}
/// How one line of an editor pane is marked.
public struct CodeLineMark: Equatable, Sendable {
public enum Tone: Equatable, Sendable {
/// Teal: what the file holds now.
case added
/// Amber-deep: what it held before.
case removed
}
/// Fill the whole row; false for a gap-only mark.
public var tint: Bool
/// The 2px left rule and the lifted number; nil for a gap-only mark.
public var tone: Tone?
/// A removed run owns no line in Actual, so its amber-deep rule sits on this line's edge.
public var gap: GapEdge?
public init(tint: Bool = false, tone: Tone? = nil, gap: GapEdge? = nil) {
self.tint = tint
self.tone = tone
self.gap = gap
}
}
public enum ChangeMarks {
/// Actual: tinted added lines plus the gap rules of pure deletions, keyed by line number.
public static func actual(_ lines: [ViewLine]) -> [Int: CodeLineMark] {
var marks: [Int: CodeLineMark] = [:]
for line in lines {
guard let no = line.no else { continue }
let added = line.style == .added
guard added || line.gap != nil else { continue }
marks[no] = CodeLineMark(tint: added, tone: added ? .added : nil, gap: line.gap)
}
return marks
}
}
public enum GutterNumbers {
/// The number each visual row shows: a wrapped line numbers only its first row.
public static func labels(rowStarts: [Int], index: LineIndex) -> [Int?] {
rowStarts.map { index.isLineStart($0) ? index.line(containing: $0) : nil }
}
}
public enum DiffOverlayLayout {
public static let rowHeight: CGFloat = 22
public static let topPadding: CGFloat = 6
/// The split row that shows an updated-side line.
public static func rowIndex(forUpdatedLine line: Int, in rows: [SplitRow]) -> Int? {
rows.firstIndex { $0.right?.no == line }
}
/// The scroll offset that puts a row in the middle of the viewport, as near as the file permits.
public static func centredOffset(rowIndex: Int, rowCount: Int, viewportHeight: CGFloat,
rowHeight: CGFloat = rowHeight, topPadding: CGFloat = topPadding) -> CGFloat {
let contentHeight = topPadding * 2 + CGFloat(rowCount) * rowHeight
let rowTop = topPadding + CGFloat(rowIndex) * rowHeight
let wanted = rowTop - (viewportHeight - rowHeight) / 2
return min(max(0, wanted), max(0, contentHeight - viewportHeight))
}
}
/// A replacement the Tab key makes, plus where the selection goes afterwards.
public struct TextEdit: Equatable, Sendable {
public var range: NSRange
public var replacement: String
public var selection: NSRange
}
public enum Indentation {
/// Tab inserts spaces on one line; over several lines, or with Shift, every touched line
/// moves by one level. A selection that stops at column 0 leaves that last line alone.
public static func edit(_ text: String, selection: NSRange, tabSize: Int, outdent: Bool) -> TextEdit? {
let ns = text as NSString
let size = max(1, tabSize)
let pad = String(repeating: " ", count: size)
let from = selection.location
let to = NSMaxRange(selection)
if !outdent && !ns.substring(with: selection).contains("\n") {
return TextEdit(range: selection, replacement: pad, selection: NSRange(location: from + size, length: 0))
}
let previousNewline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: from))
let start = previousNewline.location == NSNotFound ? 0 : previousNewline.location + 1
let tail = to > from && to > 0 && ns.character(at: to - 1) == 10 ? to - 1 : to
let newline = ns.range(of: "\n", options: [], range: NSRange(location: tail, length: ns.length - tail))
let end = newline.location == NSNotFound ? ns.length : newline.location
let block = ns.substring(with: NSRange(location: start, length: end - start))
let lines = block.components(separatedBy: "\n")
func cut(_ line: String) -> Int {
guard outdent else { return 0 }
if line.hasPrefix("\t") { return 1 }
return min(size, line.prefix { $0 == " " }.count)
}
let next = lines.map { outdent ? String($0.dropFirst(cut($0))) : pad + $0 }.joined(separator: "\n")
if next == block { return nil }
let head = outdent ? -cut(lines[0]) : size
let total = outdent ? -lines.reduce(0) { $0 + cut($1) } : size * lines.count
let newFrom = max(start, from + head)
let newTo = max(start, to + total)
return TextEdit(range: NSRange(location: start, length: end - start), replacement: next,
selection: NSRange(location: newFrom, length: max(0, newTo - newFrom)))
}
}
public enum EditorReference {
/// The lines a text selection touches, as the reference names them.
public static func lines(of range: NSRange, in index: LineIndex) -> ClosedRange<Int> {
let first = index.line(containing: range.location)
let last = index.line(containing: NSMaxRange(range))
return first...max(first, last)
}
/// `path:start-end` for a selection, else `path:line` for the clicked line.
public static func make(path: String, selectedLines: ClosedRange<Int>?, clickedLine: Int) -> AgentReference {
if let lines = selectedLines { return AgentReference(path: path, lines: lines) }
return AgentReference(path: path, startLine: max(1, clickedLine))
}
}
public enum HighlightDiff {
/// The part of the new text whose colours may be wrong after an edit: the edited range plus
/// every token that differs, so a keystroke repaints a line, not the file. An opened block
/// comment still repaints everything after it, because every later token differs.
public static func repaintRange(old: [Token], new: [Token], edited: NSRange, delta: Int, newLength: Int) -> NSRange {
let editedEndOld = NSMaxRange(edited) - delta
var prefix = 0
while prefix < old.count, prefix < new.count, old[prefix] == new[prefix],
old[prefix].location + old[prefix].length <= edited.location {
prefix += 1
}
var suffix = 0
while suffix < old.count - prefix, suffix < new.count - prefix {
let o = old[old.count - 1 - suffix]
let n = new[new.count - 1 - suffix]
guard o.location >= editedEndOld, o.location + delta == n.location, o.length == n.length, o.role == n.role else { break }
suffix += 1
}
var start = edited.location
var end = NSMaxRange(edited)
for t in old[prefix..<(old.count - suffix)] {
let tEnd = t.location + t.length
start = min(start, t.location < edited.location ? t.location : t.location + delta)
end = max(end, tEnd > editedEndOld ? tEnd + delta : min(tEnd, edited.location))
}
for t in new[prefix..<(new.count - suffix)] {
start = min(start, t.location)
end = max(end, t.location + t.length)
}
start = max(0, min(start, newLength))
end = max(start, min(end, newLength))
return NSRange(location: start, length: end - start)
}
}
+133
View File
@@ -0,0 +1,133 @@
import AppKit
/// The NSTextView that holds the code. It only forwards gestures; `CodeEditorController` decides.
final class CodeTextView: NSTextView {
weak var controller: CodeEditorController?
/// Pointer travel that still counts as a click and not as a text selection.
private static let dragSlop: CGFloat = 4
private var pointerTracking: NSTrackingArea?
override func drawBackground(in rect: NSRect) {
super.drawBackground(in: rect)
controller?.drawRowBackgrounds(in: rect)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
controller?.drawSymbolUnderlines(in: dirtyRect)
}
override func mouseDown(with event: NSEvent) {
if event.modifierFlags.contains(.command), controller?.followSymbol(at: event) == true { return }
let hadSelection = selectedRange().length > 0
let down = event.locationInWindow
super.mouseDown(with: event)
guard event.clickCount == 1, !hadSelection, selectedRange().length == 0,
event.modifierFlags.isDisjoint(with: [.shift, .option, .command, .control]),
let up = window?.mouseLocationOutsideOfEventStream,
abs(up.x - down.x) + abs(up.y - down.y) <= Self.dragSlop else { return }
controller?.plainClick(atWindowPoint: down)
}
override func menu(for event: NSEvent) -> NSMenu? {
controller?.showContextMenu(for: event)
return nil
}
override func keyDown(with event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting([.numericPad, .function])
if event.keyCode == 124, flags == .command, controller?.passOnSelection() == true { return }
super.keyDown(with: event)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard window?.firstResponder === self else { return super.performKeyEquivalent(with: event) }
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
if flags == .command, let key = event.charactersIgnoringModifiers?.lowercased(),
let command = EditorKeyCommand(key: key) {
controller?.run(command)
return true
}
return super.performKeyEquivalent(with: event)
}
override func flagsChanged(with event: NSEvent) {
super.flagsChanged(with: event)
let command = event.modifierFlags.contains(.command)
controller?.commandKeyChanged(command)
if let window { updatePointer(at: window.mouseLocationOutsideOfEventStream, command: command) }
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
guard pointerTracking == nil else { return }
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeInKeyWindow, .inVisibleRect], owner: self)
addTrackingArea(area)
pointerTracking = area
}
override func mouseMoved(with event: NSEvent) {
super.mouseMoved(with: event)
updatePointer(at: event.locationInWindow, command: event.modifierFlags.contains(.command))
}
override func cursorUpdate(with event: NSEvent) {
super.cursorUpdate(with: event)
updatePointer(at: event.locationInWindow, command: event.modifierFlags.contains(.command))
}
/// The pointing hand over a symbol ⌘-click would follow, the I-beam elsewhere in the text.
private func updatePointer(at windowPoint: NSPoint, command: Bool) {
guard visibleRect.contains(convert(windowPoint, from: nil)) else { return }
if command, controller?.symbol(atWindowPoint: windowPoint) != nil {
NSCursor.pointingHand.set()
} else {
NSCursor.iBeam.set()
}
}
override func resignFirstResponder() -> Bool {
controller?.commandKeyChanged(false)
return super.resignFirstResponder()
}
override func insertTab(_ sender: Any?) {
if controller?.indent(outdent: false) != true { super.insertTab(sender) }
}
override func insertBacktab(_ sender: Any?) {
if controller?.indent(outdent: true) != true { super.insertBacktab(sender) }
}
}
/// The editor shortcuts the text view answers itself while it has focus.
enum EditorKeyCommand {
case save
case close
case cycleMode
init?(key: String) {
switch key {
case "s": self = .save
case "w": self = .close
case "m": self = .cycleMode
default: return nil
}
}
}
/// The line-number column; a click selects the line, Shift-click extends to it.
final class CodeGutterView: NSRulerView {
weak var controller: CodeEditorController?
override var isFlipped: Bool { true }
override func drawHashMarksAndLabels(in rect: NSRect) {
controller?.drawGutter(in: rect, of: self)
}
override func mouseDown(with event: NSEvent) {
controller?.gutterClick(atWindowPoint: event.locationInWindow, extend: event.modifierFlags.contains(.shift))
}
}
+327
View File
@@ -0,0 +1,327 @@
import AppKit
import HelderCore
import SwiftUI
/// The keys the Diff answers while its canvas holds focus.
enum DiffCanvasKey {
case escape
case up
case down
case enter
init?(keyCode: UInt16) {
switch keyCode {
case 53: self = .escape
case 126: self = .up
case 125: self = .down
case 36, 76: self = .enter
default: return nil
}
}
}
/// Both halves of the side-by-side Diff: one vertical scroll, one shared sideways offset, never wraps.
/// Rows are drawn, not laid out, so a 5k-line diff costs only the rows on screen.
struct DiffCanvas: NSViewRepresentable {
let rows: [SplitRow]
let language: Language?
let knownSymbols: Set<String>
/// Identifies the pair shown; a new key redraws and re-centres.
let key: String
let focusLine: Int?
/// View → Zoom.
let scale: CGFloat
/// The canvas takes keyboard focus back whenever this moves.
let focusRequest: Int
/// Returns false for a key it leaves alone.
let onKey: (DiffCanvasKey) -> Bool
/// The clicked side's line number, and the click in top-left window coordinates.
let contextMenu: (_ line: Int, _ anchor: CGPoint) -> Void
func makeNSView(context: Context) -> DiffScrollView {
let scroll = DiffScrollView()
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
scroll.drawsBackground = true
scroll.backgroundColor = EditorColors.background
scroll.borderType = .noBorder
scroll.documentView = scroll.canvas
return scroll
}
func updateNSView(_ scroll: DiffScrollView, context: Context) {
let canvas = scroll.canvas
canvas.onKey = onKey
canvas.contextMenu = contextMenu
if canvas.focusRequest != focusRequest {
canvas.focusRequest = focusRequest
scroll.window?.makeFirstResponder(canvas)
}
let loadKey = "\(key)|\(scale)"
guard canvas.key != loadKey else { return }
canvas.key = loadKey
canvas.load(rows: rows, language: language, knownSymbols: knownSymbols, scale: scale)
scroll.centre(onUpdatedLine: focusLine)
}
}
final class DiffScrollView: NSScrollView {
let canvas = DiffCanvasView()
/// Sideways gestures move both halves together; the view itself only scrolls vertically.
override func scrollWheel(with event: NSEvent) {
if abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) {
canvas.shift(by: -event.scrollingDeltaX)
} else {
super.scrollWheel(with: event)
}
}
override func layout() {
super.layout()
canvas.frame.size.width = contentSize.width
canvas.frame.size.height = max(canvas.contentHeight, contentSize.height)
if let line = pendingFocus, contentSize.height > 0 {
pendingFocus = nil
centre(onUpdatedLine: line)
}
}
private var pendingFocus: Int?
/// Puts the clicked line in the middle of the window, as near as the file permits.
func centre(onUpdatedLine line: Int?) {
window?.makeFirstResponder(canvas)
guard let line else {
contentView.scroll(to: .zero)
reflectScrolledClipView(contentView)
return
}
guard contentSize.height > 0 else {
pendingFocus = line
needsLayout = true
return
}
guard let index = DiffOverlayLayout.rowIndex(forUpdatedLine: line, in: canvas.rows) else { return }
let y = DiffOverlayLayout.centredOffset(rowIndex: index, rowCount: canvas.rows.count, viewportHeight: contentSize.height,
rowHeight: canvas.rowHeight)
contentView.scroll(to: NSPoint(x: 0, y: y))
reflectScrolledClipView(contentView)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
window?.makeFirstResponder(canvas)
}
}
final class DiffCanvasView: NSView {
enum Side { case left, right }
/// Whole lines dragged over on one side, as row indices; the other side stays out of it.
struct LineSelection: Equatable {
var side: Side
var anchor: Int
var head: Int
var rows: ClosedRange<Int> { min(anchor, head)...max(anchor, head) }
}
var key = ""
var focusRequest = 0
var onKey: (DiffCanvasKey) -> Bool = { _ in false }
var contextMenu: (Int, CGPoint) -> Void = { _, _ in }
private(set) var rows: [SplitRow] = []
private var language: Language?
private var knownSymbols: Set<String> = []
private var cache: [Int: NSAttributedString] = [:]
private var offsetX: CGFloat = 0
private var widestText: CGFloat = 0
private(set) var selection: LineSelection?
private var dragStart: (side: Side, row: Int)?
private(set) var rowHeight = DiffOverlayLayout.rowHeight
private var font = EditorFonts.code
private let top = DiffOverlayLayout.topPadding
private let gutter = Metrics.diffOverlayGutter
private let codeInset: CGFloat = 0
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { true }
var contentHeight: CGFloat { top * 2 + CGFloat(rows.count) * rowHeight }
func load(rows: [SplitRow], language: Language?, knownSymbols: Set<String>, scale: CGFloat) {
rowHeight = (DiffOverlayLayout.rowHeight * scale).rounded()
font = EditorFonts.code(scale: scale)
self.rows = rows
self.language = language
self.knownSymbols = knownSymbols
cache.removeAll()
offsetX = 0
selection = nil
let longest = rows.lazy.map { max($0.left?.text.utf16.count ?? 0, $0.right?.text.utf16.count ?? 0) }.max() ?? 0
widestText = CGFloat(longest) * (" " as NSString).size(withAttributes: [.font: font]).width + 24
superview?.superview?.needsLayout = true
frame.size.height = contentHeight
needsDisplay = true
}
func shift(by delta: CGFloat) {
let room = bounds.width / 2 - gutter - codeInset
offsetX = min(max(0, offsetX + delta), max(0, widestText - room))
needsDisplay = true
}
override func keyDown(with event: NSEvent) {
if let key = DiffCanvasKey(keyCode: event.keyCode), onKey(key) { return }
super.keyDown(with: event)
}
override func cancelOperation(_ sender: Any?) {
_ = onKey(.escape)
}
// MARK: Selection
var hasSelection: Bool { selection != nil }
/// The selected lines of one side; rows where that side has no line are skipped.
var selectedText: String? {
guard let selection else { return nil }
let lines = selection.rows.compactMap { index -> String? in
guard rows.indices.contains(index) else { return nil }
return (selection.side == .left ? rows[index].left : rows[index].right)?.text
}
return lines.isEmpty ? nil : lines.joined(separator: "\n")
}
@objc func copy(_ sender: Any?) {
guard let text = selectedText else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
/// ⌘A: the side that holds the selection, else the Original side.
override func selectAll(_ sender: Any?) {
guard !rows.isEmpty else { return }
selection = LineSelection(side: selection?.side ?? .left, anchor: 0, head: rows.count - 1)
needsDisplay = true
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard window?.firstResponder === self,
event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command else { return super.performKeyEquivalent(with: event) }
switch event.charactersIgnoringModifiers?.lowercased() {
case "c" where hasSelection:
copy(nil)
return true
case "a":
selectAll(nil)
return true
default:
return super.performKeyEquivalent(with: event)
}
}
private func hit(_ event: NSEvent) -> (side: Side, row: Int) {
let point = convert(event.locationInWindow, from: nil)
let row = Int(((point.y - top) / rowHeight).rounded(.down))
return (point.x < bounds.width / 2 ? .left : .right, min(max(row, 0), max(rows.count - 1, 0)))
}
override func mouseDown(with event: NSEvent) {
window?.makeFirstResponder(self)
dragStart = hit(event)
if selection != nil {
selection = nil
needsDisplay = true
}
}
override func mouseDragged(with event: NSEvent) {
guard let start = dragStart, !rows.isEmpty else { return }
autoscroll(with: event)
let next = LineSelection(side: start.side, anchor: start.row, head: hit(event).row)
guard next != selection else { return }
selection = next
needsDisplay = true
}
override func mouseUp(with event: NSEvent) {
dragStart = nil
}
/// An empty half of a row refers to line 1.
override func rightMouseDown(with event: NSEvent) {
let point = convert(event.locationInWindow, from: nil)
let index = Int(((point.y - top) / rowHeight).rounded(.down))
let row = rows.indices.contains(index) ? rows[index] : nil
let side = point.x < bounds.width / 2 ? row?.left : row?.right
let height = window?.contentView?.bounds.height ?? 0
contextMenu(side?.no ?? 1, CGPoint(x: event.locationInWindow.x, y: height - event.locationInWindow.y))
}
override func draw(_ dirtyRect: NSRect) {
EditorColors.background.setFill()
dirtyRect.fill()
guard !rows.isEmpty else { return }
let half = (bounds.width / 2).rounded(.down)
let first = max(0, Int((dirtyRect.minY - top) / rowHeight))
let last = min(rows.count - 1, Int((dirtyRect.maxY - top) / rowHeight))
if first <= last {
for index in first...last {
let y = top + CGFloat(index) * rowHeight
draw(side: rows[index].left, index: index * 2, x: 0, width: half, y: y, tone: .removed)
draw(side: rows[index].right, index: index * 2 + 1, x: half + 1, width: bounds.width - half - 1, y: y, tone: .added)
}
}
EditorColors.raised.setFill()
NSRect(x: half, y: dirtyRect.minY, width: Metrics.hairline, height: dirtyRect.height).fill()
}
private func draw(side line: SideLine?, index: Int, x: CGFloat, width: CGFloat, y: CGFloat, tone: CodeLineMark.Tone) {
guard let line else { return }
let changed = line.mark != nil
let row = NSRect(x: x, y: y, width: width, height: rowHeight)
if let selection, selection.side == (tone == .removed ? .left : .right), selection.rows.contains(index / 2) {
EditorColors.selection.setFill()
row.fill()
}
if changed {
EditorColors.fill(tone).setFill()
row.fill()
EditorColors.tone(tone).setFill()
NSRect(x: x, y: y, width: Metrics.accentRule, height: rowHeight).fill()
}
let textTop = y + (rowHeight - (font.ascender - font.descender + font.leading)) / 2
let number = String(line.no) as NSString
let numberAttributes: [NSAttributedString.Key: Any] = [
.font: font, .foregroundColor: changed ? EditorColors.tone(tone) : EditorColors.lineNumber,
]
let numberWidth = number.size(withAttributes: numberAttributes).width
number.draw(at: NSPoint(x: x + gutter - 14 - numberWidth, y: textTop), withAttributes: numberAttributes)
let codeX = x + gutter + codeInset
NSGraphicsContext.saveGraphicsState()
NSRect(x: codeX, y: y, width: max(0, x + width - codeX), height: rowHeight).clip()
text(for: line, index: index).draw(at: NSPoint(x: codeX - offsetX, y: textTop))
NSGraphicsContext.restoreGraphicsState()
}
private func text(for line: SideLine, index: Int) -> NSAttributedString {
if let cached = cache[index] { return cached }
let attributed = NSMutableAttributedString(string: line.text, attributes: [
.font: font, .foregroundColor: EditorColors.syntax(.plain),
])
if let language {
let length = attributed.length
for token in SyntaxHighlighter.lineTokens(for: line.text, language: language, knownSymbols: knownSymbols)
where token.role != .plain {
let range = NSIntersectionRange(NSRange(location: token.location, length: token.length), NSRange(location: 0, length: length))
attributed.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: range)
}
}
cache[index] = attributed
return attributed
}
}
@@ -0,0 +1,258 @@
import HelderCore
import SwiftUI
/// The full-screen side-by-side Diff: Original left, Actual right, over the whole window.
/// Its right-click menu and pass-on prompt are drawn inside it, since a second overlay would replace it.
struct DiffOverlayView: View {
let editor: EditorStore
/// Full screen hides the traffic lights, so the header reclaims their inset.
let isFullScreen: Bool
/// View → Zoom.
let scale: CGFloat
let request: DiffOverlayRequest
/// Every menu action except pass-on, which stays inside the Diff.
let perform: (ContextAction) -> Void
/// The composed text and the reference for the toast.
let passToAgent: (String, String) -> Void
@State private var menu: ContextMenuRequest?
@State private var highlighted: Int?
@State private var passOn: PassOnRequest?
@State private var canvasFocus = 0
var body: some View {
GeometryReader { geometry in
let origin = geometry.frame(in: .global).origin
ZStack(alignment: .topLeading) {
content
if let menu {
DiffContextMenu(request: menu, origin: origin, size: geometry.size, highlighted: $highlighted,
choose: choose, close: closeMenu)
}
if let passOn {
PassOnPanel(request: local(passOn, origin: origin),
insert: { text in
passToAgent(text, passOn.reference)
closePassOn()
},
cancel: closePassOn)
}
}
}
.onExitCommand(perform: escape)
.onChange(of: menu != nil || passOn != nil, initial: true) { _, busy in editor.diffOverlayBusy = busy }
.onDisappear { editor.diffOverlayBusy = false }
}
private var content: some View {
let diff = editor.overlayDiff(for: request.path, side: request.side)
return VStack(spacing: 0) {
header(diff)
HStack(spacing: 0) {
paneLabel("Original", note: "before", color: Palette.text4)
Rectangle().fill(Palette.raised).frame(width: Metrics.hairline)
paneLabel("Actual", note: "after", color: Palette.amber)
}
.frame(height: Metrics.panelHeader)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
if let diff, diff.isTooBig {
Text("Too big.")
.typeRole(Typography.body)
.foregroundStyle(Palette.text4)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if let diff {
DiffCanvas(rows: diff.split, language: FileType.language(for: request.path), knownSymbols: editor.knownSymbols,
key: key(diff), focusLine: request.focusLine, scale: scale, focusRequest: canvasFocus,
onKey: handle, contextMenu: openMenu)
} else {
Text("— No changes to compare.")
.typeRole(Typography.body)
.foregroundStyle(Palette.text3)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.background(Palette.editor)
}
// MARK: Menu and prompt
private func openMenu(line: Int, anchor: CGPoint) {
guard passOn == nil else { return }
let reference = AgentReference(path: request.path, startLine: line)
let next = editor.contextMenuRequest(reference: reference, code: nil, anchor: anchor)
menu = next
highlighted = MenuCursor.first(in: next.entries)
}
private func choose(_ action: ContextAction) {
let anchor = menu?.anchor ?? .zero
menu = nil
if case let .passOnReference(reference, code) = action {
passOn = PassOnRequest(reference: reference, code: code, anchor: anchor)
} else {
perform(action)
}
}
private func closeMenu() {
menu = nil
}
private func closePassOn() {
passOn = nil
canvasFocus += 1
}
/// Esc closes the innermost layer first: the menu, then the prompt, then the Diff itself.
private func escape() {
if menu != nil {
closeMenu()
} else if passOn != nil {
closePassOn()
} else {
editor.collapseDiff()
}
}
private func handle(_ key: DiffCanvasKey) -> Bool {
if key == .escape {
escape()
return true
}
guard let menu else { return false }
switch key {
case .up: highlighted = MenuCursor.step(highlighted ?? -1, by: -1, in: menu.entries)
case .down: highlighted = MenuCursor.step(highlighted ?? -1, by: 1, in: menu.entries)
case .enter:
if let highlighted, case let .action(action, _) = menu.entries[highlighted] { choose(action) }
case .escape: break
}
return true
}
/// The prompt lays itself out in this view's space, not the window's.
private func local(_ request: PassOnRequest, origin: CGPoint) -> PassOnRequest {
var moved = request
moved.anchor = CGPoint(x: request.anchor.x - origin.x, y: request.anchor.y - origin.y)
return moved
}
private func key(_ diff: Diff) -> String {
"\(request.path)|\(request.side?.rawValue ?? "file")|\(request.focusLine ?? 0)|\(diff.added).\(diff.removed).\(diff.split.count).\(diff.updated.utf8.count)"
}
private func header(_ diff: Diff?) -> some View {
HStack(spacing: 14) {
TypeBadge(path: request.path)
Text(request.path)
.typeRole(TypeRole(.monoMedium, 12))
.foregroundStyle(Palette.text1)
.lineLimit(1)
.truncationMode(.head)
if let diff {
let status = FileChangeStatus(diff)
Text(status.rawValue).typeRole(Typography.panelLabel).foregroundStyle(color(status))
if diff.added > 0 { Text("+\(diff.added)").typeRole(TypeRole(.monoMedium, 12)).foregroundStyle(Palette.addedText) }
if diff.removed > 0 { Text("\u{2212}\(diff.removed)").typeRole(TypeRole(.monoMedium, 12)).foregroundStyle(Palette.removedText) }
}
if editor.hasBothSides(request.path) {
Text(request.side == .unstaged ? "staged → actual" : "HEAD → staged")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
}
Spacer(minLength: 0)
CollapseButton { editor.collapseDiff() }
}
.padding(.leading, isFullScreen ? 16 : Metrics.trafficLightInset)
.padding(.trailing, 16)
.frame(height: 42)
.background(Palette.panel)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
private func paneLabel(_ title: String, note: String, color: Color) -> some View {
HStack(spacing: 10) {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(color)
Text(note).typeRole(Typography.meta).foregroundStyle(Palette.text5)
Spacer(minLength: 0)
}
.padding(.horizontal, 16)
.frame(maxWidth: .infinity)
}
private func color(_ status: FileChangeStatus) -> Color {
switch status {
case .added: Palette.addedText
case .deleted: Palette.removedText
case .modified: Palette.text4
}
}
}
/// The editor menu (Pass on reference, Copy reference) at the pointer, over the Diff.
private struct DiffContextMenu: View {
let request: ContextMenuRequest
/// The Diff's top-left corner in window coordinates.
let origin: CGPoint
let size: CGSize
@Binding var highlighted: Int?
let choose: (ContextAction) -> Void
let close: () -> Void
var body: some View {
ZStack(alignment: .topLeading) {
Color.clear
.contentShape(Rectangle())
.onTapGesture(perform: close)
ContextMenuPanel {
ContextMenuHeader(request.header)
ForEach(Array(request.entries.enumerated()), id: \.offset) { index, entry in
switch entry {
case .separator:
ContextMenuSeparator()
case let .action(action, label):
ContextMenuRow(label, systemImage: ContextMenuOverlay.symbol(for: action),
iconTint: ContextMenuOverlay.tint(for: action).color,
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { choose(action) }
}
}
}
.fixedSize()
.offset(position)
}
}
/// Keeps the menu inside the Diff.
private var position: CGSize {
let height = CGFloat(request.entries.count) * Metrics.contextMenuItem + 60
let x = min(request.anchor.x - origin.x, size.width - Metrics.contextMenuWidth - 8)
let y = min(request.anchor.y - origin.y, size.height - height)
return CGSize(width: max(8, x), height: max(8, y))
}
}
private struct CollapseButton: View {
let action: () -> Void
@State private var hovering = false
var body: some View {
HStack(spacing: 8) {
Image(systemName: "arrow.down.right.and.arrow.up.left")
.font(.system(size: 11, weight: .regular))
Text("Collapse").typeRole(Typography.toolbarLabel)
Keycap("Esc")
}
.foregroundStyle(hovering ? Palette.text1 : Palette.text3)
.padding(.leading, 9)
.padding(.trailing, 4)
.padding(.vertical, 3)
.background(hovering ? Palette.hover : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onTapGesture(perform: action)
.onHover { hovering = $0 }
.animation(Metrics.colorTransition, value: hovering)
}
}
+54
View File
@@ -0,0 +1,54 @@
import HelderCore
import SwiftUI
/// The bar above the code: which file is open, whether it is unsaved or changed, and its Preview and Diff buttons.
/// With no file open it stays as an empty bar, so the column's top edge lines up with its neighbours.
struct EditorBar: View {
var editor: EditorStore?
var presentation: EditorPresentation?
var body: some View {
HStack(spacing: 10) {
if let editor, let presentation {
content(editor, presentation)
}
}
.padding(.horizontal, 14)
.frame(height: Metrics.editorBar)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.editor)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
@ViewBuilder
private func content(_ editor: EditorStore, _ presentation: EditorPresentation) -> some View {
let path = presentation.path
TypeBadge(path: path)
Text(path)
.typeRole(Typography.path)
.foregroundStyle(Palette.text2)
.lineLimit(1)
.truncationMode(.head)
.help(path)
if editor.isDirty(path) {
Circle().fill(Palette.text2).frame(width: 7, height: 7)
.accessibilityLabel("Unsaved changes")
}
if let diff = editor.diff(for: path), presentation.hasDiff {
HStack(spacing: 8) {
if diff.added > 0 { Text("+\(diff.added)").foregroundStyle(Palette.addedText) }
if diff.removed > 0 { Text("\u{2212}\(diff.removed)").foregroundStyle(Palette.removedText) }
}
.typeRole(TypeRole(.monoMedium, 12))
}
Spacer(minLength: 0)
ForEach(presentation.barButtons, id: \.self) { button in
switch button {
case .preview:
SegmentButton("Preview", isOn: presentation.mode == .preview) { editor.togglePreview() }
case .diff:
SegmentButton("Diff", isOn: presentation.mode == .diff) { editor.setMode(.diff, for: path) }
}
}
}
}
@@ -0,0 +1,80 @@
import AppKit
import HelderCore
/// AppKit twins of the Palette tokens, for the NSTextView and the diff canvas.
enum EditorColors {
static let background = NSColor(hex: 0x101720)
static let raised = NSColor(hex: 0x232C39)
static let lineNumber = NSColor(hex: 0x3A424C)
/// The caret line's number, one step up from the rest.
static let lineNumberActive = NSColor(hex: 0xBAC0C0)
static let amber = NSColor(hex: 0xE8913A)
static let selection = NSColor(hex: 0xE8913A, alpha: 0.22)
static let flash = NSColor(hex: 0xE8913A, alpha: 0.10)
static let activeLine = NSColor(white: 1, alpha: 0.03)
static let addedText = NSColor(hex: 0x8FBFB4)
static let addedFill = NSColor(hex: 0x8FBFB4, alpha: 0.12)
static let removedText = NSColor(hex: 0xC4741F)
static let removedFill = NSColor(hex: 0xC4741F, alpha: 0.14)
static func syntax(_ role: TokenRole) -> NSColor {
switch role {
case .plain, .symbol: NSColor(hex: 0xE4E7E6)
case .variable: NSColor(hex: 0xBAC0C0)
case .comment: NSColor(hex: 0x6C7783)
case .keyword: NSColor(hex: 0xC3A6CE)
case .string: NSColor(hex: 0x8FBFB4)
case .number: NSColor(hex: 0xF0B476)
}
}
static func tone(_ tone: CodeLineMark.Tone) -> NSColor {
tone == .added ? addedText : removedText
}
static func fill(_ tone: CodeLineMark.Tone) -> NSColor {
tone == .added ? addedFill : removedFill
}
}
/// Code text at a View → Zoom scale; 1 is actual size.
enum EditorFonts {
/// 13pt Plex Mono 400: code stays flat, never bold or italic.
static let code: NSFont = Typography.code.nsFont
static let topInset: CGFloat = 10
/// Room under the last line, so it never sits on the pane's bottom edge.
static let bottomInset: CGFloat = 40
static let flashDuration: TimeInterval = 1
static func code(scale: CGFloat) -> NSFont {
scale == 1 ? code : NSFont(descriptor: code.fontDescriptor, size: code.pointSize * scale) ?? code
}
static func lineHeight(scale: CGFloat) -> CGFloat { (20 * scale).rounded() }
/// Baseline inside the row that centres the glyphs vertically.
static func baseline(scale: CGFloat) -> CGFloat {
let font = code(scale: scale)
return (lineHeight(scale: scale) - (font.ascender - font.descender)) / 2 + font.ascender
}
/// Fixed rows with the tab width of `tabSize` spaces.
static func paragraphStyle(tabSize: Int, font: NSFont, scale: CGFloat = 1) -> NSParagraphStyle {
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight(scale: scale)
style.maximumLineHeight = lineHeight(scale: scale)
style.tabStops = []
let space = (" " as NSString).size(withAttributes: [.font: font]).width
style.defaultTabInterval = space * CGFloat(max(1, tabSize))
return style
}
static func baseAttributes(tabSize: Int, scale: CGFloat = 1) -> [NSAttributedString.Key: Any] {
let font = code(scale: scale)
return [
.font: font,
.foregroundColor: EditorColors.syntax(.plain),
.paragraphStyle: paragraphStyle(tabSize: tabSize, font: font, scale: scale),
]
}
}
@@ -0,0 +1,99 @@
import HelderCore
import SwiftUI
/// Column C: the bar and the pane for the open file.
public struct EditorColumn: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
Group {
if let editor = model.editor {
EditorWorkspace(model: model, editor: editor)
} else {
VStack(spacing: 0) {
EditorBar()
EditorEmptyState()
}
}
}
.background(Palette.editor)
}
}
private struct EditorWorkspace: View {
let model: WorkspaceModel
let editor: EditorStore
var body: some View {
VStack(spacing: 0) {
if let path = editor.activePath {
let presentation = editor.presentation(for: path)
EditorBar(editor: editor, presentation: presentation)
EditorPane(editor: editor, presentation: presentation, fontScale: model.layout.textScale)
} else {
EditorBar()
EditorEmptyState()
}
}
.overlay { TooBigFlash(notice: editor.tooBig) }
}
}
/// What the column shows with no file open: only what works without one.
struct EditorEmptyState: View {
private let keys: [(String, String)] = [
("Open folder", "⌘O"), ("Recent projects", "⇧⌘O"), ("Search files & content", "⌘F"), ("Project note", "⌘N"),
]
var body: some View {
VStack(spacing: 18) {
Text("No file open")
.typeRole(Typography.body)
.foregroundStyle(Palette.text4)
VStack(spacing: 6) {
ForEach(keys, id: \.0) { label, key in
HStack {
Text(label).typeRole(Typography.row).foregroundStyle(Palette.text2)
Spacer(minLength: 14)
Keycap(key)
}
.frame(width: 260)
.padding(.vertical, 2)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
}
}
/// "Too big." for 1.6 seconds when a file like `composer.lock` is refused.
private struct TooBigFlash: View {
let notice: TooBigNotice?
@State private var visible: UUID?
var body: some View {
ZStack {
if let notice, visible == notice.id {
Text("Too big.")
.typeRole(Typography.path)
.foregroundStyle(Palette.amber)
.padding(.horizontal, 16)
.padding(.vertical, 10)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: 4))
.overlay(RoundedRectangle(cornerRadius: 4).stroke(Palette.raised, lineWidth: Metrics.hairline))
}
}
.allowsHitTesting(false)
.task(id: notice?.id) {
guard let id = notice?.id else { return }
visible = id
try? await Task.sleep(for: .milliseconds(1600))
if visible == id { visible = nil }
}
}
}
@@ -0,0 +1,42 @@
import HelderCore
import SwiftUI
/// The overlays the editor draws: the full-screen Diff, the pass-on prompt and the symbol popup.
/// `OverlayHost` shows this view whenever `handles` is true for the current overlay.
public struct EditorOverlayContent: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public static func handles(_ overlay: Overlay) -> Bool {
switch overlay {
case .diff, .passOn, .symbol: true
default: false
}
}
public var body: some View {
switch model.overlay.current {
case let .diff(request):
if let editor = model.editor {
DiffOverlayView(editor: editor, isFullScreen: model.layout.isFullScreen, scale: model.layout.textScale, request: request,
perform: { model.perform(.context($0)) },
passToAgent: { text, reference in model.passToAgent(text, toast: reference) })
}
case let .passOn(request):
PassOnPanel(request: request,
insert: { model.perform(.passToAgent(text: $0, reference: request.reference)) },
cancel: { model.perform(.dismissOverlay) })
case let .symbol(name):
if let editor = model.editor {
SymbolPopupView(editor: editor, name: name,
dismiss: { model.perform(.dismissOverlay) },
openAt: { path, line in model.perform(.open(path, OpenOptions(line: line))) })
}
default:
EmptyView()
}
}
}
+184
View File
@@ -0,0 +1,184 @@
import AppKit
import HelderCore
import SwiftUI
/// The pane under the bar: code, Markdown preview, image, or a placeholder.
struct EditorPane: View {
let editor: EditorStore
let presentation: EditorPresentation
/// View → Zoom.
var fontScale: CGFloat = 1
var body: some View {
let path = presentation.path
let showsCode = presentation.kind == .text && presentation.placeholder == nil && presentation.paneMode != .preview
ZStack {
// Kept alive while hidden, so a trip to Preview keeps each file's undo history and colours.
if presentation.kind == .text {
CodeEditorView(configuration: configuration(path, isShown: showsCode), actions: actions)
.opacity(showsCode ? 1 : 0)
.allowsHitTesting(showsCode)
}
if presentation.kind == .image {
ImagePreview(data: editor.image(for: path), failed: editor.isUnreadableImage(path), name: PathUtils.basename(path))
.overlay(RightClickCatcher { fileMenu(path, at: $0) })
} else if let placeholder = presentation.placeholder {
EditorPlaceholderView(placeholder: placeholder)
.background(Palette.editor)
} else if presentation.paneMode == .preview {
MarkdownPreviewView(editor: editor, path: path, text: editor.text(for: path))
.overlay(RightClickCatcher { fileMenu(path, at: $0) })
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
}
/// Views without lines refer to the file's first line.
private func fileMenu(_ path: String, at anchor: CGPoint) {
let request = editor.contextMenuRequest(reference: AgentReference(path: path, startLine: 1), code: nil, anchor: anchor)
editor.presentOverlay?(.contextMenu(request))
}
private func configuration(_ path: String, isShown: Bool) -> CodeEditorConfiguration {
let diff = editor.diff(for: path)
let wrap: Bool = switch editor.editorConfig.wordWrap {
case .on: true
case .off: false
case .markdown: presentation.isMarkdown
}
let marked = presentation.paneMode == .actual ? diff : nil
return CodeEditorConfiguration(
documentID: path, path: path, text: editor.text(for: path), revision: editor.revision(for: path),
language: FileType.language(for: path), isEditable: presentation.isEditable, wrap: wrap,
tabSize: editor.editorConfig.tabSize,
marksKey: marked.map { "actual:" + Self.stamp($0) } ?? "none",
makeMarks: { marked.map { ChangeMarks.actual(DiffViews.actual($0)) } ?? [:] },
opensDiffOnClick: presentation.opensDiffOnClick, knownSymbols: editor.knownSymbols,
symbolsVersion: editor.knownSymbolsVersion, flash: editor.flash,
focusRequest: editor.textFocusRequest, selectAllRequest: editor.selectAllRequest, fontScale: fontScale,
isShown: isShown)
}
/// Cheap identity of a diff: counts and byte lengths, never a full comparison.
private static func stamp(_ diff: Diff) -> String {
"\(diff.added).\(diff.removed).\(diff.rows.count).\(diff.original.utf8.count).\(diff.updated.utf8.count)"
}
private var actions: CodeEditorActions {
let editor = editor
return CodeEditorActions(
edited: { editor.edit($0) },
cursorMoved: { editor.updateCursor(line: $0, column: $1) },
selectionChanged: { editor.updateSelection(lines: $0, code: $1) },
markedLineClicked: { editor.openDiff(atLine: $0) },
contextMenu: { reference, code, anchor in
editor.presentOverlay?(.contextMenu(editor.contextMenuRequest(reference: reference, code: code, anchor: anchor)))
},
symbolClicked: { editor.lookupSymbol($0) },
passOnSelection: { anchor in
guard let request = editor.passOnSelectionRequest(anchor: anchor) else { return false }
editor.presentOverlay?(.passOn(request))
return true
},
command: { command in
switch command {
case .save: Task { try? await editor.save() }
case .close: Task { await editor.requestCloseActive() }
case .cycleMode: editor.togglePreview()
}
})
}
}
/// A short line in place of the code, with a note under it.
struct EditorPlaceholderView: View {
let placeholder: EditorPlaceholder
var body: some View {
VStack(spacing: 10) {
Text(placeholder.title)
.typeRole(Typography.body)
.foregroundStyle(color)
if let note = placeholder.note {
Text(note).typeRole(Typography.path).foregroundStyle(Palette.text4)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var color: Color {
switch placeholder {
case .noUpdated: Palette.removedText
case .cannotDisplay: Palette.text4
}
}
}
/// An image file, centred on the editor surface; read-only.
struct ImagePreview: View {
let data: Data?
let failed: Bool
let name: String
var body: some View {
Group {
if let data, let image = NSImage(data: data) {
Image(nsImage: image)
.resizable()
.interpolation(.high)
.aspectRatio(contentMode: .fit)
.background(Checkerboard())
.frame(maxWidth: image.size.width, maxHeight: image.size.height)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.accessibilityLabel(name)
.padding(24)
} else if failed || data != nil {
Text("Can’t preview this image").typeRole(Typography.body).foregroundStyle(Palette.text4)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// 10pt squares behind an image, so a transparent PNG or SVG reads on the dark ground.
private struct Checkerboard: View {
var body: some View {
Canvas { context, size in
context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(Palette.panel))
let square: CGFloat = 10
for row in 0..<Int((size.height / square).rounded(.up)) {
for column in 0..<Int((size.width / square).rounded(.up)) where (row + column).isMultiple(of: 2) {
context.fill(Path(CGRect(x: CGFloat(column) * square, y: CGFloat(row) * square, width: square, height: square)),
with: .color(Palette.raised))
}
}
}
}
}
/// Takes only right-clicks, so the view under it keeps scrolling, selecting and following links.
struct RightClickCatcher: NSViewRepresentable {
/// Receives the click in top-left window coordinates.
let action: (CGPoint) -> Void
func makeNSView(context: Context) -> CatcherView { CatcherView() }
func updateNSView(_ view: CatcherView, context: Context) {
view.action = action
}
final class CatcherView: NSView {
var action: (CGPoint) -> Void = { _ in }
override func hitTest(_ point: NSPoint) -> NSView? {
NSApp.currentEvent?.type == .rightMouseDown ? super.hitTest(point) : nil
}
override func rightMouseDown(with event: NSEvent) {
let height = window?.contentView?.bounds.height ?? 0
action(CGPoint(x: event.locationInWindow.x, y: height - event.locationInWindow.y))
}
}
}
@@ -0,0 +1,119 @@
import Foundation
import HelderCore
/// How the editor can show a file at all.
public enum EditorFileKind: Equatable, Sendable {
case text
case image
/// Known binary formats: a placeholder, never a text buffer.
case binary
private static let binaryExtensions: Set<String> = [
"pdf", "zip", "gz", "tgz", "tar", "bz2", "xz", "7z", "rar", "jar", "war", "class",
"woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "m4a", "mov", "avi", "wav", "ogg", "webm",
"exe", "dll", "so", "dylib", "a", "o", "bin", "dat", "psd", "sqlite", "sqlite3", "db", "phar",
"heic", "tiff", "tif", "icns", "DS_Store",
]
public static func of(_ path: String) -> EditorFileKind {
if FileType.isImage(path) { return .image }
if PathUtils.basename(path) == ".DS_Store" { return .binary }
return binaryExtensions.contains(FileType.ext(path)) ? .binary : .text
}
}
/// The file-level change, taken from the whole-file diff rather than one git row.
public enum FileChangeStatus: String, Equatable, Sendable {
case added = "Added"
case modified = "Modified"
case deleted = "Deleted"
public init(_ diff: Diff) {
self = diff.isDeletedFile ? .deleted : diff.isAddedFile ? .added : .modified
}
}
/// A one-sentence empty state in place of the code.
public enum EditorPlaceholder: Equatable, Sendable {
/// Actual of a file the change deleted.
case noUpdated
case cannotDisplay
public var title: String {
switch self {
case .noUpdated: "No updated version"
case .cannotDisplay: "This file cannot be displayed"
}
}
public var note: String? {
switch self {
case .noUpdated: "This file was deleted in the change."
case .cannotDisplay: nil
}
}
}
/// A button on the bar above the code.
public enum EditorBarButton: Equatable, Sendable {
/// Toggles the rendered Markdown.
case preview
/// Opens the side-by-side Diff overlay.
case diff
}
/// Everything the column needs to decide what to draw for one file.
public struct EditorPresentation: Equatable, Sendable {
public var path: String
public var kind: EditorFileKind
public var hasDiff: Bool
public var isMarkdown: Bool
/// The requested mode resolved against what the file supports.
public var mode: ViewMode
/// What the pane under the Diff overlay shows: Diff falls back to Actual.
public var paneMode: ViewMode
public var status: FileChangeStatus?
public var placeholder: EditorPlaceholder?
/// A mode carried over from another state (or an unchanged file asked for a diff view)
/// falls back to a view the file has, so nothing renders blank. `isBinary` is what the read
/// found, for a binary file whose extension looks like text.
public init(path: String, requested: ViewMode?, diff: Diff?, defaultMode: ViewMode = .actual, isBinary: Bool = false) {
self.path = path
let byName = EditorFileKind.of(path)
kind = isBinary && byName == .text ? .binary : byName
hasDiff = kind == .text && diff != nil
isMarkdown = FileType.isMarkdown(path)
let wanted = requested ?? (hasDiff ? defaultMode : .code)
if wanted == .preview && isMarkdown {
mode = .preview
} else if hasDiff {
mode = wanted == .diff ? .diff : .actual
} else {
mode = .code
}
paneMode = mode == .diff ? .actual : mode
status = diff.map(FileChangeStatus.init)
if kind == .binary {
placeholder = .cannotDisplay
} else if paneMode == .actual && status == .deleted {
placeholder = .noUpdated
} else {
placeholder = nil
}
}
/// Preview only for Markdown, Diff only for a file with changes.
public var barButtons: [EditorBarButton] {
var buttons: [EditorBarButton] = []
if kind == .text && isMarkdown { buttons.append(.preview) }
if hasDiff { buttons.append(.diff) }
return buttons
}
/// Actual and Code edit the live buffer; Preview is a read-only view.
public var isEditable: Bool { kind == .text && placeholder == nil && (paneMode == .code || paneMode == .actual) }
/// A click on a marked line opens the Diff, except on a new file where every line is marked.
public var opensDiffOnClick: Bool { paneMode == .actual && hasDiff && status != .added }
}
@@ -0,0 +1,354 @@
import AppKit
import HelderCore
import SwiftUI
/// The rendered Markdown document: read-only, derived from the live buffer.
struct MarkdownPreviewView: View {
let editor: EditorStore
let path: String
let text: String
var body: some View {
let blocks = MarkdownParser.parse(text, baseDir: PathUtils.dirname(path))
ScrollView {
MarkdownBlocks(blocks: blocks, editor: editor)
.frame(maxWidth: MarkdownStyle.measure, alignment: .leading)
.padding(EdgeInsets(top: 18, leading: 20, bottom: 48, trailing: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
.background(Palette.editor)
.environment(\.openURL, OpenURLAction { url in open(url) })
}
/// Web links go to the browser; a link to a file in the project opens it in the editor.
private func open(_ url: URL) -> OpenURLAction.Result {
if url.scheme == MarkdownStyle.fileScheme {
let path = String(url.absoluteString.dropFirst(MarkdownStyle.fileScheme.count + 1)).removingPercentEncoding ?? ""
if !path.isEmpty { editor.open(path) }
return .handled
}
guard let scheme = url.scheme?.lowercased(), ["http", "https", "mailto"].contains(scheme) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
}
}
enum MarkdownStyle {
/// About 68 characters of 14pt Plex Sans.
static let measure: CGFloat = 580
static let fileScheme = "helder-file"
static let body = Typography.body
static let bodyLineSpacing: CGFloat = 14 * 1.7 - 18
static func heading(_ level: Int) -> TypeRole {
switch level {
case 1, 2: Typography.markdownH2
case 3: Typography.markdownH3
case 4: TypeRole(.monoBold, 15, lineHeight: 18)
default: TypeRole(.monoBold, 13, lineHeight: 16)
}
}
/// Block margins; neighbours collapse to the larger one.
static func margins(_ block: MarkdownBlock) -> (top: CGFloat, bottom: CGFloat) {
switch block {
case let .heading(level, _):
let size = heading(level).size
return (1.6 * size, 0.6 * size)
case .paragraph, .list, .table: return (14, 14)
case .quote, .code: return (16.8, 16.8)
case .rule: return (22.4, 22.4)
}
}
}
/// A run of blocks with collapsed margins between them.
struct MarkdownBlocks: View {
let blocks: [MarkdownBlock]
let editor: EditorStore
var quoted = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in
MarkdownBlockView(block: block, editor: editor, quoted: quoted)
.padding(.top, index == 0 ? firstTop(block) : max(MarkdownStyle.margins(blocks[index - 1]).bottom, MarkdownStyle.margins(block).top))
}
}
}
private func firstTop(_ block: MarkdownBlock) -> CGFloat {
if case let .heading(level, _) = block { return 0.2 * MarkdownStyle.heading(level).size }
return 0
}
}
private struct MarkdownBlockView: View {
let block: MarkdownBlock
let editor: EditorStore
let quoted: Bool
var body: some View {
switch block {
case let .heading(level, content):
let role = MarkdownStyle.heading(level)
VStack(alignment: .leading, spacing: 8) {
Text(MarkdownInlines.attributed(content, style: .heading(role)))
.typeRole(role)
.foregroundStyle(Palette.text1)
.fixedSize(horizontal: false, vertical: true)
if level == 3 { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
case let .paragraph(content):
if case let .image(alt, source, _)? = content.first, content.count == 1 {
MarkdownImage(alt: alt, source: source, editor: editor)
} else {
paragraph(content)
}
case let .code(language, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(MarkdownInlines.highlighted(text, language: language))
.font(Typography.code.font)
.lineSpacing(20 - 17)
.fixedSize()
.padding(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
case let .quote(blocks):
HStack(alignment: .top, spacing: 16) {
Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule)
MarkdownBlocks(blocks: blocks, editor: editor, quoted: true)
}
.fixedSize(horizontal: false, vertical: true)
case let .list(ordered, items):
VStack(alignment: .leading, spacing: 7) {
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(ordered ? "\(index + 1)." : "—")
.typeRole(MarkdownStyle.body)
.foregroundStyle(Palette.amber)
.frame(minWidth: 12, alignment: .leading)
paragraph(item)
}
}
}
case let .table(header, alignments, rows):
MarkdownTable(header: header, alignments: alignments, rows: rows)
case .rule:
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline)
}
}
private func paragraph(_ content: [MarkdownInline]) -> some View {
Text(MarkdownInlines.attributed(content, style: quoted ? .quote : .body))
.typeRole(quoted ? Typography.markdownQuote : MarkdownStyle.body)
.lineSpacing(MarkdownStyle.bodyLineSpacing)
.foregroundStyle(quoted ? Palette.amberSoft : Palette.text2)
.fixedSize(horizontal: false, vertical: true)
}
}
private struct MarkdownTable: View {
let header: [[MarkdownInline]]
let alignments: [TableAlignment?]
let rows: [[[MarkdownInline]]]
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {
GridRow {
ForEach(Array(header.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .tableHeader))
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
.background(Palette.panel)
.gridColumnAlignment(horizontal(column))
}
}
ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline).gridCellUnsizedAxes(.horizontal)
GridRow {
ForEach(Array(row.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .body))
.typeRole(Typography.row)
.foregroundStyle(Palette.text3)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
}
}
}
}
.fixedSize()
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
private func alignment(_ column: Int) -> Alignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
private func horizontal(_ column: Int) -> HorizontalAlignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
}
/// A block image: a project file read through the file service, or a remote URL.
private struct MarkdownImage: View {
let alt: String
let source: ImageSource
let editor: EditorStore
@State private var data: Data?
@State private var failed = false
var body: some View {
Group {
switch source {
case let .remote(url):
AsyncImage(url: url) { phase in
if let image = phase.image {
image.resizable().aspectRatio(contentMode: .fit)
} else {
altText
}
}
case let .local(path):
if let data, let image = NSImage(data: data) {
Image(nsImage: image).resizable().aspectRatio(contentMode: .fit)
.frame(maxWidth: image.size.width)
} else {
altText.task(id: path) {
data = await editor.readImage(path)
failed = data == nil
}
}
}
}
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.accessibilityLabel(alt)
}
private var altText: some View {
Text(alt.isEmpty ? "—" : alt).typeRole(Typography.path).foregroundStyle(Palette.text3)
}
}
/// Inline runs as one AttributedString, so a paragraph wraps and selects as a single text.
enum MarkdownInlines {
enum Style {
case body
case quote
case heading(TypeRole)
case tableHeader
var role: TypeRole {
switch self {
case .body: MarkdownStyle.body
case .quote: Typography.markdownQuote
case let .heading(role): role
case .tableHeader: Typography.panelLabel
}
}
}
static func attributed(_ inlines: [MarkdownInline], style: Style) -> AttributedString {
var out = AttributedString()
append(inlines, to: &out, style: style, strong: false, emphasis: false)
return out
}
private static func append(_ inlines: [MarkdownInline], to out: inout AttributedString, style: Style,
strong: Bool, emphasis: Bool, link: URL? = nil, strike: Bool = false) {
for inline in inlines {
switch inline {
case let .text(text):
var run = AttributedString(text)
run.font = font(style: style, strong: strong, emphasis: emphasis)
if strong { run.foregroundColor = Palette.text1 }
if let link {
run.link = link
run.foregroundColor = Palette.amber
}
if strike { run.strikethroughStyle = .single }
out += run
case let .code(code):
var run = AttributedString("\u{2009}" + code + "\u{2009}")
run.font = Typography.code.font
run.foregroundColor = Palette.amberSoft
run.backgroundColor = Palette.panel
if let link { run.link = link }
out += run
case let .strong(children):
append(children, to: &out, style: style, strong: true, emphasis: emphasis, link: link, strike: strike)
case let .emphasis(children):
append(children, to: &out, style: style, strong: strong, emphasis: true, link: link, strike: strike)
case let .strikethrough(children):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: link, strike: true)
case let .link(children, url, _):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: linkURL(url), strike: strike)
case let .image(alt, _, _):
var run = AttributedString(alt)
run.font = Typography.path.font
run.foregroundColor = Palette.text4
out += run
}
}
}
/// Relative links point into the project; they get a private scheme the preview opens in the editor.
static func linkURL(_ raw: String) -> URL? {
guard let safe = MarkdownParser.safeURL(raw), !safe.hasPrefix("#") else { return nil }
if MarkdownParser.isLocalURL(safe) {
let encoded = safe.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? safe
return URL(string: MarkdownStyle.fileScheme + ":" + encoded)
}
return URL(string: safe)
}
private static func font(style: Style, strong: Bool, emphasis: Bool) -> Font {
switch style {
case .heading, .tableHeader:
return style.role.font
case .quote:
return Typography.markdownQuote.font
case .body:
if emphasis { return Typography.markdownQuote.nsFont.withSize(14).swiftUIFont }
return (strong ? Typography.rowSelected.nsFont : MarkdownStyle.body.nsFont).withSize(14).swiftUIFont
}
}
/// Fenced code with the six syntax colours, flat weight.
static func highlighted(_ text: String, language: Language?) -> AttributedString {
let ns = text as NSString
let colored = NSMutableAttributedString(string: text, attributes: [.foregroundColor: EditorColors.syntax(.plain)])
if let language {
for token in SyntaxHighlighter.tokens(for: text, language: language) where token.role != .plain {
let range = NSIntersectionRange(NSRange(location: token.location, length: token.length), NSRange(location: 0, length: ns.length))
colored.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: range)
}
}
var out = AttributedString(text)
colored.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: ns.length)) { value, range, _ in
guard let color = value as? NSColor, let bounds = Range(range, in: out) else { return }
out[bounds].foregroundColor = Color(nsColor: color)
}
return out
}
}
private extension NSFont {
var swiftUIFont: Font { Font(self) }
}
+110
View File
@@ -0,0 +1,110 @@
import HelderCore
import SwiftUI
/// The 460pt prompt: an optional note over the reference it inserts into the agent's composer.
public struct PassOnPanel: View {
let request: PassOnRequest
let insert: (String) -> Void
let cancel: () -> Void
@State private var note = ""
@FocusState private var focused: Bool
public init(request: PassOnRequest, insert: @escaping (String) -> Void, cancel: @escaping () -> Void) {
self.request = request
self.insert = insert
self.cancel = cancel
}
private var composed: String {
PassOn.compose(note: note, reference: request.reference, code: request.code)
}
public var body: some View {
GeometryReader { geometry in
ZStack(alignment: .topLeading) {
Color.clear
.contentShape(Rectangle())
.onTapGesture(perform: cancel)
panel
.offset(x: min(max(8, request.anchor.x), geometry.size.width - Metrics.passOnWidth - 8),
y: min(max(8, request.anchor.y + 6), geometry.size.height - 170))
}
}
}
private var panel: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
SparkGlyph()
.stroke(Palette.amber, style: StrokeStyle(lineWidth: 1.1 * 13 / 16, lineJoin: .round))
.frame(width: 13, height: 13)
Text("Pass on to agent").typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
EscChip()
}
TextField("", text: $note, prompt: Text("Add a note (optional)…").foregroundStyle(Palette.text4))
.textFieldStyle(.plain)
.typeRole(TypeRole(.monoRegular, 13))
.foregroundStyle(Palette.text1)
.focused($focused)
.onSubmit { insert(composed) }
.onExitCommand(perform: cancel)
.padding(.horizontal, 10)
.frame(height: 38)
.background(Palette.editor, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.amber, lineWidth: Metrics.accentRule))
.padding(Metrics.focusRingWidth)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall + 2).stroke(Palette.focusRing, lineWidth: Metrics.focusRingWidth))
.padding(-Metrics.focusRingWidth)
HStack(alignment: .top, spacing: 10) {
Text("Inserts").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).padding(.top, 5)
preview
}
OverlayFooter.hint([("↵", "insert into agent"), ("esc", "cancel")])
.typeRole(Typography.meta)
}
.padding(14)
.frame(width: Metrics.passOnWidth)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).stroke(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius, y: Metrics.menuShadowY)
.onAppear { focused = true }
}
@ViewBuilder
private var preview: some View {
let chip = Text(composed)
.typeRole(Typography.path)
.foregroundStyle(Palette.ink)
.padding(.horizontal, 8)
.padding(.vertical, 4)
if request.code != nil {
ScrollView {
chip.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 132)
.fixedSize(horizontal: false, vertical: true)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
} else {
chip.lineLimit(1)
.truncationMode(.tail)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
}
/// The four-point spark that marks every "Pass on" action, drawn on a 16-unit grid.
struct SparkGlyph: Shape {
func path(in rect: CGRect) -> Path {
let unit = min(rect.width, rect.height) / 16
let points: [(CGFloat, CGFloat)] = [(8, 1.5), (9.6, 6.4), (14.5, 8), (9.6, 9.6), (8, 14.5), (6.4, 9.6), (1.5, 8), (6.4, 6.4)]
var path = Path()
for (index, point) in points.enumerated() {
let p = CGPoint(x: rect.minX + point.0 * unit, y: rect.minY + point.1 * unit)
if index == 0 { path.move(to: p) } else { path.addLine(to: p) }
}
path.closeSubpath()
return path
}
}
@@ -0,0 +1,249 @@
import HelderCore
import SwiftUI
/// One row the keyboard can land on: a declaration or a reference line.
public struct SymbolTarget: Equatable, Sendable {
public var path: String
public var line: Int
}
public enum SymbolTargets {
/// Declarations first, then every reference line, as one flat list for ↑↓↵.
public static func flatten(_ lookup: SymbolLookup?) -> [SymbolTarget] {
guard let lookup else { return [] }
return lookup.definitions.map { SymbolTarget(path: $0.path, line: $0.line) }
+ lookup.references.flatMap { group in group.hits.map { SymbolTarget(path: group.path, line: $0.line) } }
}
/// One declaration is named in full, the way the file does; several share only the short name.
public static func title(_ name: String, _ lookup: SymbolLookup?) -> String {
guard let lookup, lookup.definitions.count == 1 else { return name }
return lookup.definitions[0].qualifiedName
}
}
/// ⌘-click on a PHP class name: where it is declared, then every reference. Centred on the window,
/// because the list is as long as the class is popular.
struct SymbolPopupView: View {
let editor: EditorStore
let name: String
let dismiss: () -> Void
/// Opens a file at a line (and reveals it in the Explorer).
let openAt: (String, Int) -> Void
@State private var highlighted = 0
@FocusState private var focused: Bool
private var lookup: SymbolLookup? { editor.symbolName == name ? editor.symbolLookup : nil }
var body: some View {
let targets = SymbolTargets.flatten(lookup)
GeometryReader { geometry in
ZStack {
Palette.scrim.onTapGesture(perform: dismiss)
panel(targets)
.frame(width: min(700, geometry.size.width * 0.82))
.frame(maxHeight: min(geometry.size.height * 0.72, 640))
.fixedSize(horizontal: false, vertical: true)
}
}
.focusable()
.focused($focused)
.focusEffectDisabled()
.onAppear { focused = true }
.onChange(of: lookup) { highlighted = 0 }
.onKeyPress(.downArrow) { highlighted = min(highlighted + 1, max(0, targets.count - 1)); return .handled }
.onKeyPress(.upArrow) { highlighted = max(highlighted - 1, 0); return .handled }
.onKeyPress(.return) {
if highlighted < targets.count { open(targets[highlighted]) }
return .handled
}
.onExitCommand(perform: dismiss)
}
private func panel(_ targets: [SymbolTarget]) -> some View {
VStack(spacing: 0) {
HStack(spacing: 10) {
Text(SymbolTargets.title(name, lookup)).typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
if let lookup {
Text("\(lookup.referenceCount) reference\(lookup.referenceCount == 1 ? "" : "s")")
.typeRole(TypeRole(.monoRegular, 10.5))
.foregroundStyle(Palette.text4)
}
}
.padding(.horizontal, 18)
.frame(height: 50)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
if let lookup {
ScrollViewReader { proxy in
ScrollView {
results(lookup)
.padding(.bottom, 6)
}
.onChange(of: highlighted) { _, index in proxy.scrollTo(index) }
}
} else {
empty("Searching…")
}
}
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.overlay(alignment: .leading) { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusOverlay).stroke(Palette.raised, lineWidth: Metrics.hairline))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius, y: Metrics.overlayShadowY)
}
private func results(_ lookup: SymbolLookup) -> some View {
let definitionCount = lookup.definitions.count
return LazyVStack(alignment: .leading, spacing: 0) {
section("Defined in")
if lookup.definitions.isEmpty { empty("No declaration in this project") }
ForEach(Array(lookup.definitions.enumerated()), id: \.offset) { index, def in
SymbolRow(isHighlighted: highlighted == index) {
HStack(spacing: 8) {
TypeBadge(path: def.path)
Text(def.path).typeRole(Typography.path).foregroundStyle(Palette.text2).lineLimit(1).truncationMode(.head)
Text(def.kind)
.typeRole(TypeRole(.monoRegular, 10))
.foregroundStyle(Palette.text4)
.padding(.horizontal, 5)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.tooltipBorder, lineWidth: Metrics.hairline))
Spacer()
Text("\(def.line)").typeRole(Typography.meta).foregroundStyle(Palette.text4)
}
.padding(.horizontal, 13)
.padding(.vertical, 4)
}
.id(index)
.onHover { if $0 { highlighted = index } }
.onTapGesture { open(SymbolTarget(path: def.path, line: def.line)) }
}
ForEach(Array(lookup.definitions.enumerated()), id: \.offset) { _, def in relations(def) }
if !lookup.references.isEmpty { section("Used in") }
ForEach(Array(referenceRows(lookup, offset: definitionCount).enumerated()), id: \.offset) { _, row in
switch row {
case let .file(group):
HStack(spacing: 8) {
TypeBadge(path: group.path)
Text(group.path).typeRole(Typography.path).foregroundStyle(Palette.text3).lineLimit(1).truncationMode(.head)
Spacer()
Text("\(group.hits.count)").typeRole(Typography.meta).foregroundStyle(Palette.text4)
}
.padding(.horizontal, 13)
.padding(.top, 8)
.padding(.bottom, 2)
.contentShape(Rectangle())
.onTapGesture { if let first = group.hits.first { open(SymbolTarget(path: group.path, line: first.line)) } }
case let .hit(path, hit, index):
SymbolRow(isHighlighted: highlighted == index) {
HStack(spacing: 12) {
Text("\(hit.line)").typeRole(Typography.searchHit).foregroundStyle(highlighted == index ? Palette.amber : Palette.text5)
.frame(width: 40, alignment: .trailing)
Text(String(hit.text.prefix(200))).typeRole(Typography.searchHit).foregroundStyle(Palette.text3).lineLimit(1)
Spacer(minLength: 0)
}
.padding(.leading, 13)
.frame(height: Metrics.searchHitLine)
}
.id(index)
.onHover { if $0 { highlighted = index } }
.onTapGesture { open(SymbolTarget(path: path, line: hit.line)) }
}
}
}
}
private enum ReferenceRow {
case file(RefGroup)
case hit(path: String, ContentHit, index: Int)
}
private func referenceRows(_ lookup: SymbolLookup, offset: Int) -> [ReferenceRow] {
var rows: [ReferenceRow] = []
var index = offset
for group in lookup.references {
rows.append(.file(group))
for hit in group.hits {
rows.append(.hit(path: group.path, hit, index: index))
index += 1
}
}
return rows
}
/// What a declaration extends, implements and uses; a name this project declares is a chip you can follow.
@ViewBuilder
private func relations(_ def: SymbolDef) -> some View {
let groups = [("extends", def.parents), ("implements", def.interfaces), ("uses", def.traits)].filter { !$0.1.isEmpty }
if !groups.isEmpty {
VStack(alignment: .leading, spacing: 3) {
ForEach(groups, id: \.0) { key, names in
HStack(spacing: 6) {
Text(key.uppercased()).typeRole(TypeRole(.sansRegular, 10)).foregroundStyle(Palette.text4)
.frame(minWidth: 66, alignment: .leading)
ForEach(names, id: \.self) { chip($0) }
}
}
}
.padding(EdgeInsets(top: 2, leading: 34, bottom: 6, trailing: 13))
}
}
private func chip(_ name: String) -> some View {
SymbolChip(name: name, known: editor.knownSymbols.contains(name)) { editor.lookupSymbol(name) }
}
private func section(_ title: String) -> some View {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 14, leading: 16, bottom: 6, trailing: 16))
}
private func empty(_ text: String) -> some View {
Text(text).typeRole(Typography.tooltip).foregroundStyle(Palette.text4)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.frame(maxWidth: .infinity, alignment: .leading)
}
private func open(_ target: SymbolTarget) {
dismiss()
openAt(target.path, target.line)
}
}
/// A selectable row: raised fill and the 2px amber rule when highlighted.
private struct SymbolRow<Content: View>: View {
let isHighlighted: Bool
@ViewBuilder let content: () -> Content
var body: some View {
content()
.frame(maxWidth: .infinity, alignment: .leading)
.background(isHighlighted ? Palette.raised : Color.clear)
.overlay(alignment: .leading) {
if isHighlighted { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
}
.contentShape(Rectangle())
}
}
/// A related class name; one the project declares lights amber under the pointer and reloads the popup on it.
private struct SymbolChip: View {
let name: String
let known: Bool
let follow: () -> Void
@State private var hovering = false
var body: some View {
let lit = known && hovering
Text(name)
.typeRole(TypeRole(.monoRegular, 11))
.foregroundStyle(lit ? Palette.amber : known ? Palette.text2 : Palette.text4)
.padding(.horizontal, 7)
.background(lit ? Palette.amberTint : .clear, in: RoundedRectangle(cornerRadius: 3))
.overlay(RoundedRectangle(cornerRadius: 3).stroke(lit ? Palette.amberKeycapBorder : Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onHover { hovering = $0 }
.onTapGesture { if known { follow() } }
}
}
@@ -0,0 +1,170 @@
import HelderCore
import SwiftUI
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy.
public struct ExplorerColumn: 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 hoveredPath: String?
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
if let store = model.explorer {
tree(store)
} else {
Spacer()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.column(.explorer, active: isActive))
.background(GlobalFrameReader(frame: $columnFrame))
.simultaneousGesture(TapGesture().onEnded { model.pointerFocused(.explorer) })
}
private var isActive: Bool { model.layout.activePanel == .explorer }
private var showHidden: Bool { model.layout.showHidden }
private var header: some View {
HStack(spacing: 8) {
Text("Explorer").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer(minLength: 8)
Text(model.name)
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
}
.padding(.horizontal, 12)
.frame(height: Metrics.panelHeader)
.hairline(.bottom)
}
private func tree(_ store: ExplorerStore) -> some View {
let statuses = model.sourceControl?.fileStatuses ?? [:]
return GeometryReader { viewport in
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(store.rows(showHidden: showHidden), id: \.path) { row in
TreeRowView(
row: row,
isOpen: store.expanded.contains(row.path),
selected: isSelected(row, store),
status: row.kind == .file ? statuses[row.path] : nil,
onClick: { click(row, store) },
onHover: { hoveredPath = row.path; store.selectedPath = row.path },
onContextMenu: { point in showMenu(for: ExplorerStore.target(for: row), at: point, store) }
)
.reportsRowFrame(.tree(row.path), to: model)
.id(row.path)
}
}
.padding(.top, 6)
.padding(.bottom, 14)
.frame(minHeight: viewport.size.height, alignment: .top)
// The bare space under the rows is the project folder itself.
.background(RightClickArea { point in showMenu(for: .projectRoot, at: point, store) })
}
.onChange(of: store.selectedPath) { _, path in
guard let path, path != hoveredPath else { return }
proxy.scrollTo(path)
}
}
}
.task { await store.loadIfNeeded() }
}
/// The open file, the keyboard cursor, or the row whose menu is open.
private func isSelected(_ row: TreeRow, _ store: ExplorerStore) -> Bool {
if case let .contextMenu(request) = model.overlay.current, request.target == ExplorerStore.target(for: row) {
return true
}
if isActive && store.selectedPath == row.path { return true }
return row.kind == .file && model.editor?.activePath == row.path
}
private func click(_ row: TreeRow, _ store: ExplorerStore) {
store.selectedPath = row.path
if row.kind == .directory {
store.toggle(row.path)
} else {
model.perform(.open(row.path, OpenOptions()))
}
}
/// Rows anchor the menu to the column's right edge; the empty space under them anchors it at the click.
private func showMenu(for target: ContextTarget, at point: CGPoint, _ store: ExplorerStore) {
model.pointerFocused(.explorer)
if target != .projectRoot { store.selectedPath = target.path }
let anchor = target == .projectRoot ? point : CGPoint(x: columnFrame.maxX, y: point.y)
model.perform(.showContextMenu(target, anchor: anchor))
}
}
/// One tree row: indent, chevron, folder glyph or type badge, name, change letter.
private struct TreeRowView: View {
let row: TreeRow
let isOpen: Bool
let selected: Bool
let status: GitStatus?
let onClick: () -> Void
let onHover: () -> Void
let onContextMenu: (CGPoint) -> Void
@State private var hovered = false
private var isDirectory: Bool { row.kind == .directory }
var body: some View {
HStack(spacing: 7) {
Group {
if isDirectory {
ChevronGlyph(open: isOpen).foregroundStyle(isOpen ? Palette.amber : Palette.text4)
} else {
Color.clear
}
}
.frame(width: 10, height: 10)
if isDirectory {
FolderGlyph(open: isOpen).frame(width: 16, height: 16)
} else {
TypeBadge(path: row.path)
}
Text(PathUtils.basename(row.path))
.typeRole(selected ? Typography.rowSelected : Typography.row)
.strikethrough(status == .deleted, color: Palette.text4)
.foregroundStyle(labelColor)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 0)
if let status {
Text(status.rawValue)
.typeRole(RowStyle.changeLetterRole)
.foregroundStyle(status == .deleted ? Palette.amberDeep : Palette.addedText)
.padding(.leading, 8)
}
}
.padding(.leading, Metrics.explorerBaseIndent + CGFloat(row.depth) * Metrics.explorerIndent)
.padding(.trailing, 12)
.frame(height: Metrics.explorerRow)
.selectableRow(isSelected: selected, isHovered: hovered)
.contentShape(Rectangle())
.onTapGesture(perform: onClick)
.onHover { inside in
hovered = inside
if inside { onHover() }
}
.overlay(RightClickArea(onRightClick: onContextMenu))
.help(isDirectory ? "" : row.path)
}
private var labelColor: Color {
if status == .deleted { return Palette.text4 }
return selected || (isDirectory && isOpen) ? Palette.text1 : Palette.text3
}
}
+209
View File
@@ -0,0 +1,209 @@
// Pieces shared by the Source Control and Explorer rows.
import AppKit
import HelderCore
import SwiftUI
enum RowStyle {
static let folderFill = Color(hex: 0x7A838C, alpha: 0.12)
static let openFolderFill = Color(hex: 0x7A838C, alpha: 0.16)
static let openFolderFrontFill = Color(hex: 0x7A838C, alpha: 0.22)
static let changeLetterRole = TypeRole(.monoSemiBold, 10)
static let gitLetterRole = TypeRole(.monoSemiBold, 11)
static let dirHeadRole = TypeRole(.monoRegular, 11)
static let groupLabelRole = Typography.panelLabel
}
// MARK: Glyphs (drawn on 16-unit grids)
struct ChevronGlyph: View {
let open: Bool
var body: some View {
Path { p in
p.move(to: CGPoint(x: 3.5, y: 2))
p.addLine(to: CGPoint(x: 7, y: 5))
p.addLine(to: CGPoint(x: 3.5, y: 8))
}
.stroke(style: StrokeStyle(lineWidth: 1.4, lineCap: .round, lineJoin: .round))
.frame(width: 10, height: 10)
.scaleEffect(0.9)
.rotationEffect(.degrees(open ? 90 : 0))
}
}
struct FolderGlyph: View {
let open: Bool
var size: CGFloat = 14
var body: some View {
Canvas { context, canvas in
let k = canvas.width / 16
func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: x * k, y: y * k) }
let line = StrokeStyle(lineWidth: 1.1, lineJoin: .round)
if open {
var back = Path()
back.move(to: pt(2, 12.5)); back.addLine(to: pt(2, 4.5)); back.addLine(to: pt(5.6, 4.5))
back.addLine(to: pt(6.8, 5.9)); back.addLine(to: pt(13.5, 5.9)); back.addLine(to: pt(13.5, 7.4))
context.fill(back, with: .color(RowStyle.openFolderFill))
context.stroke(back, with: .color(Palette.text4), style: line)
var front = Path()
front.move(to: pt(1.4, 12.6)); front.addLine(to: pt(3.3, 7.5)); front.addLine(to: pt(14.7, 7.5))
front.addLine(to: pt(12.8, 12.6)); front.closeSubpath()
context.fill(front, with: .color(RowStyle.openFolderFrontFill))
context.stroke(front, with: .color(Palette.text4), style: line)
} else {
var shape = Path()
shape.move(to: pt(1.5, 4.5)); shape.addLine(to: pt(5.5, 4.5)); shape.addLine(to: pt(6.7, 5.9))
shape.addLine(to: pt(14, 5.9)); shape.addLine(to: pt(14, 13)); shape.addLine(to: pt(1.5, 13))
shape.closeSubpath()
context.fill(shape, with: .color(RowStyle.folderFill))
context.stroke(shape, with: .color(Palette.text4), style: line)
}
}
.frame(width: size, height: size)
}
}
/// The plus, minus, push and arrow-up icons.
enum IconGlyph {
case plus, minus, push, arrowUp
func path(in size: CGFloat) -> Path {
switch self {
case .plus:
let k = size / 14
var p = Path()
p.move(to: CGPoint(x: 7 * k, y: 2.5 * k)); p.addLine(to: CGPoint(x: 7 * k, y: 11.5 * k))
p.move(to: CGPoint(x: 2.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
case .minus:
let k = size / 14
var p = Path()
p.move(to: CGPoint(x: 2.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
case .push:
let k = size / 16
var p = Path()
p.move(to: CGPoint(x: 8 * k, y: 13 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 4 * k))
p.move(to: CGPoint(x: 4.5 * k, y: 7.5 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 4 * k))
p.addLine(to: CGPoint(x: 11.5 * k, y: 7.5 * k))
p.move(to: CGPoint(x: 3.5 * k, y: 2.5 * k)); p.addLine(to: CGPoint(x: 12.5 * k, y: 2.5 * k))
return p
case .arrowUp:
let k = size / 16
var p = Path()
p.move(to: CGPoint(x: 8 * k, y: 13 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 3.5 * k))
p.move(to: CGPoint(x: 4.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 3.5 * k))
p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
}
}
}
struct IconView: View {
let glyph: IconGlyph
var size: CGFloat = 13
var body: some View {
glyph.path(in: size)
.stroke(style: StrokeStyle(lineWidth: glyph == .push || glyph == .arrowUp ? 1.4 : 1.5, lineCap: .round, lineJoin: .round))
.frame(width: size, height: size)
}
}
/// A borderless icon button that turns amber under the pointer.
struct QuickActionButton: View {
let glyph: IconGlyph
let help: String
let action: () -> Void
@State private var hovered = false
var body: some View {
Button(action: action) {
IconView(glyph: glyph)
.foregroundStyle(hovered ? Palette.amber : Palette.text4)
.frame(width: 18, height: 18)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hovered = $0 }
.help(help)
}
}
// MARK: Right click
/// Reports a right click (or control-click) with its point in window coordinates, top-left origin.
/// It only claims right clicks, so left clicks and hover still reach the SwiftUI row beneath.
struct RightClickArea: NSViewRepresentable {
let onRightClick: (CGPoint) -> Void
func makeNSView(context: Context) -> CatcherView {
let view = CatcherView()
view.onRightClick = onRightClick
return view
}
func updateNSView(_ view: CatcherView, context: Context) {
view.onRightClick = onRightClick
}
final class CatcherView: NSView {
var onRightClick: ((CGPoint) -> Void)?
override func hitTest(_ point: NSPoint) -> NSView? {
guard let event = NSApp.currentEvent, Self.isContextClick(event) else { return nil }
return super.hitTest(point)
}
override func rightMouseDown(with event: NSEvent) { report(event) }
override func mouseDown(with event: NSEvent) {
if Self.isContextClick(event) { report(event) } else { super.mouseDown(with: event) }
}
private func report(_ event: NSEvent) {
guard let content = window?.contentView else { return }
let p = content.convert(event.locationInWindow, from: nil)
onRightClick?(CGPoint(x: p.x, y: content.isFlipped ? p.y : content.bounds.height - p.y))
}
private static func isContextClick(_ event: NSEvent) -> Bool {
event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))
}
}
}
/// Reads a view's frame in window coordinates, for anchoring menus to a column's right edge.
struct GlobalFrameReader: View {
@Binding var frame: CGRect
var body: some View {
GeometryReader { proxy in
Color.clear
.onAppear { frame = proxy.frame(in: .global) }
.onChange(of: proxy.frame(in: .global)) { _, new in frame = new }
}
}
}
/// Tells the model where a list row sits in the window, for the ⌘→ menu; nil once the row is gone.
private struct RowFrameReporter: ViewModifier {
let key: RowKey
let model: WorkspaceModel
func body(content: Content) -> some View {
content.background(GeometryReader { proxy in
Color.clear
.onAppear { model.rowFrameChanged(key, proxy.frame(in: .global)) }
.onChange(of: proxy.frame(in: .global)) { _, frame in model.rowFrameChanged(key, frame) }
.onDisappear { model.rowFrameChanged(key, nil) }
})
}
}
extension View {
func reportsRowFrame(_ key: RowKey, to model: WorkspaceModel) -> some View {
modifier(RowFrameReporter(key: key, model: model))
}
}
@@ -0,0 +1,54 @@
import SwiftUI
/// A destructive action waiting for a yes: ↵ confirms, esc cancels.
struct ConfirmOverlay: View {
let request: ConfirmRequest
var onConfirm: () -> Void
var onClose: () -> Void
var body: some View {
OverlayShell(.sized(width: 460), onDismiss: onClose) {
VStack(alignment: .leading, spacing: 0) {
Text(request.title).typeRole(Typography.dialogTitle).foregroundStyle(Palette.text1)
if let body = request.body {
Text(body)
.typeRole(TypeRole(.monoRegular, 12, lineHeight: 19.2))
.foregroundStyle(Palette.text4)
.fixedSize(horizontal: false, vertical: true)
.padding(.top, 12)
}
HStack(spacing: 8) {
Spacer()
Button(action: onClose) {
HStack(spacing: 8) {
Text("Cancel")
Keycap("esc")
}
}
.buttonStyle(.secondary)
// The model dismisses the overlay itself; closing here first would drop the pending request.
Button(action: onConfirm) {
HStack(spacing: 8) {
Text(request.confirmLabel)
Keycap("↵", style: .onDeep)
}
}
.buttonStyle(.destructive)
}
.padding(.top, 20)
}
.padding(20)
.frame(maxWidth: .infinity, alignment: .leading)
.background(OverlayKeyCatcher(onKey: handle))
}
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .enter: onConfirm()
case .escape: onClose()
default: return false
}
return true
}
}
@@ -0,0 +1,180 @@
import AppKit
import HelderCore
import SwiftUI
enum MenuCursor {
static func first(in entries: [ContextMenuEntry]) -> Int? {
entries.firstIndex { $0 != .separator }
}
/// The next selectable entry in `step` direction, wrapping around and skipping separators.
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int {
guard !entries.isEmpty else { return current }
var index = current
for _ in entries.indices {
index = (index + step + entries.count) % entries.count
if entries[index] != .separator { return index }
}
return current
}
}
/// The colour an action's icon carries at rest.
enum MenuIconTint: Equatable {
/// text-4, amber when highlighted.
case plain
case add, modify, rename, danger
var color: Color? {
switch self {
case .plain: nil
case .add: Palette.menuIconAdd
case .modify: Palette.menuIconModify
case .rename: Palette.menuIconRename
case .danger: Palette.removedText
}
}
}
/// When a mouse-down closes the menu: anywhere in the menu's window outside the menu itself.
enum MenuDismissal {
static func closes(clickAt point: CGPoint, menuBounds: CGRect, sameWindow: Bool) -> Bool {
sameWindow && !menuBounds.contains(point)
}
}
/// A right-click menu at the pointer: path header, then the actions; the first one is pre-highlighted.
/// A click outside closes it and still reaches whatever was clicked.
/// `onPerform` alone runs an item: the model closes the menu itself and reads its anchor to place what opens next.
struct ContextMenuOverlay: View {
let request: ContextMenuRequest
var onPerform: (ContextAction) -> Void
var onClose: () -> Void
@State private var highlighted: Int?
init(request: ContextMenuRequest, onPerform: @escaping (ContextAction) -> Void, onClose: @escaping () -> Void) {
self.request = request
self.onPerform = onPerform
self.onClose = onClose
_highlighted = State(initialValue: MenuCursor.first(in: request.entries))
}
var body: some View {
GeometryReader { proxy in
menu
.background(OverlayKeyCatcher(onKey: handle))
.background(OutsideClickMonitor(onOutside: onClose))
.offset(position(in: proxy.size))
}
}
private var menu: some View {
ContextMenuPanel {
if !request.header.isEmpty { ContextMenuHeader(request.header) }
ForEach(Array(request.entries.enumerated()), id: \.offset) { index, entry in
switch entry {
case .separator:
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)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { onPerform(action) }
}
}
}
}
/// Keeps the menu inside the window.
private func position(in size: CGSize) -> CGSize {
let height = CGFloat(request.entries.count) * 34 + 60
let x = min(request.anchor.x, size.width - Metrics.contextMenuWidth - 8)
let y = min(request.anchor.y, size.height - height)
return CGSize(width: max(8, x), height: max(8, y))
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .up, .commandUp: highlighted = MenuCursor.step(highlighted ?? -1, by: -1, in: request.entries)
case .down, .commandDown: highlighted = MenuCursor.step(highlighted ?? -1, by: 1, in: request.entries)
case .enter:
if let highlighted, case let .action(action, _) = request.entries[highlighted] { onPerform(action) }
case .escape: onClose()
default: return false
}
return true
}
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
switch action {
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal: .plain
case .newFile, .newFolder, .stage: .add
case .copyFileName, .unstage, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .openDiff, .rename: .rename
case .discard, .delete: .danger
}
}
nonisolated static func symbol(for action: ContextAction) -> String {
switch action {
case .passOnReference, .passOnFileName: ContextMenuRow.spark
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
case .pasteIntoTerminal: "doc.on.clipboard"
case .newFile: "doc.badge.plus"
case .newFolder: "folder.badge.plus"
case .stage: "plus"
case .unstage: "minus"
case .openDiff: "arrow.left.arrow.right"
case .discard: "arrow.uturn.backward"
case .rename: "pencil"
case .revealInFinder: "folder"
case .delete: "trash"
}
}
}
/// Watches mouse-downs in its window without consuming them; one outside its own bounds calls `onOutside`.
private struct OutsideClickMonitor: NSViewRepresentable {
var onOutside: () -> Void
func makeNSView(context: Context) -> MonitorView {
let view = MonitorView()
view.onOutside = onOutside
return view
}
func updateNSView(_ view: MonitorView, context: Context) {
view.onOutside = onOutside
}
static func dismantleNSView(_ view: MonitorView, coordinator: ()) {
view.stop()
}
final class MonitorView: NSView {
var onOutside: () -> Void = {}
private var monitor: Any?
override func hitTest(_ point: NSPoint) -> NSView? { nil }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
stop()
guard window != nil else { return }
monitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { [weak self] event in
guard let self else { return event }
let point = self.convert(event.locationInWindow, from: nil)
if MenuDismissal.closes(clickAt: point, menuBounds: self.bounds, sameWindow: event.window === self.window) {
self.onOutside()
}
return event
}
}
func stop() {
if let monitor { NSEvent.removeMonitor(monitor) }
monitor = nil
}
}
}
@@ -0,0 +1,129 @@
import HelderCore
import SwiftUI
/// The words and target path of the new-file, new-folder and rename prompt.
struct NamePromptText: Equatable {
var purpose: NamePromptRequest.Purpose
var title: String
var placeholder: String
var previewLabel: String
/// The footer's "create file" / "rename folder".
var action: String
var initialName: String
var isFolder: Bool
var isRename: Bool
init(_ request: NamePromptRequest) {
purpose = request.purpose
switch request.purpose {
case .newFile: (isFolder, isRename) = (false, false)
case .newFolder: (isFolder, isRename) = (true, false)
case let .rename(_, isDirectory): (isFolder, isRename) = (isDirectory, true)
}
initialName = request.initialName
let noun = isFolder ? "folder" : "file"
title = isRename ? "Rename \(noun)" : (isFolder ? "New folder" : "New file")
placeholder = isFolder ? "folder name…" : "file name…"
previewLabel = isRename ? "renames to" : "creates"
action = (isRename ? "rename " : "create ") + noun
}
/// The path a submit would produce, from the same rule the Explorer applies.
func preview(for name: String) -> String {
ExplorerStore.promptTarget(for: purpose, name: name) ?? "…"
}
/// ↵ does nothing for an empty or invalid name, or an unchanged rename.
func canSubmit(_ name: String) -> Bool {
ExplorerStore.promptTarget(for: purpose, name: name) != nil
}
/// A rename selects the stem only, so typing keeps the extension.
var initialSelection: NSRange {
let name = initialName as NSString
let dot = name.range(of: ".", options: .backwards).location
let stem = isRename && dot != NSNotFound && dot > 0 ? dot : name.length
return NSRange(location: 0, length: stem)
}
}
/// A small anchored prompt for naming a new entry or renaming one.
struct NamePromptOverlay: View {
let request: NamePromptRequest
var onSubmit: (String) -> Void
var onClose: () -> Void
@State private var name: String
private let text: NamePromptText
init(request: NamePromptRequest, onSubmit: @escaping (String) -> Void, onClose: @escaping () -> Void) {
self.request = request
self.onSubmit = onSubmit
self.onClose = onClose
text = NamePromptText(request)
_name = State(initialValue: request.initialName)
}
var body: some View {
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
Color.clear.contentShape(Rectangle()).onTapGesture(perform: onClose)
prompt.offset(position(in: proxy.size))
}
}
}
private var prompt: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
Image(systemName: text.isFolder ? "folder" : "doc")
.font(.system(size: 13, weight: .light))
.foregroundStyle(Palette.amber)
Text(text.title).typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
EscChip()
}
OverlayCommandField(text: $name, placeholder: text.placeholder, font: TypeRole(.monoRegular, 13).nsFont,
initialSelection: text.initialSelection, onKey: handle)
.padding(.horizontal, 10)
.frame(height: 38)
.background(Palette.editor, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.focusRing(true)
HStack(spacing: 10) {
Text(text.previewLabel).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Text(text.preview(for: name))
.typeRole(Typography.path)
.foregroundStyle(Palette.ink)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
OverlayFooter.hint([("↵", text.action), ("esc", "cancel")])
.typeRole(Typography.chip)
}
.padding(14)
.frame(width: Metrics.passOnWidth)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
private func position(in size: CGSize) -> CGSize {
let x = min(request.anchor.x, size.width - Metrics.passOnWidth - 8)
let y = min(request.anchor.y + 6, size.height - 150)
return CGSize(width: max(8, x), height: max(8, y))
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .enter:
// The model closes the prompt itself; closing here first would drop the request it answers.
if text.canSubmit(name) { onSubmit(name.trimmingCharacters(in: .whitespacesAndNewlines)) }
case .escape: onClose()
default: return false
}
return true
}
}
+138
View File
@@ -0,0 +1,138 @@
import AppKit
import SwiftUI
/// ⌘N: the project's plain-text note. Closing it in any way saves it.
struct NoteOverlay: View {
let note: NoteStore
var onPassOn: () -> Void
var onClose: () -> Void
var body: some View {
OverlayShell(.sized(width: 780), onDismiss: onClose) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "note.text", title: "Note", detail: NoteStore.fileName) {
Button(action: onPassOn) {
HStack(spacing: 8) {
Text("To the agent")
Keycap("⌘P", style: .onAmber, small: true)
}
}
.buttonStyle(.primary)
}
NoteEditor(text: Binding(get: { note.text }, set: { note.text = $0 }), onKey: handle)
.frame(maxWidth: .infinity, maxHeight: .infinity)
Text("saved on focus loss · \(note.characterCount) characters")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 34)
.hairline(.top)
}
.frame(maxHeight: .infinity)
}
.onDisappear { Task { await note.save() } }
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .commandP: onPassOn()
case .escape: onClose()
default: return false
}
return true
}
}
/// Mono 14/1.7 plain-text editor with an amber caret, focused with the caret at the end.
private struct NoteEditor: NSViewRepresentable {
@Binding var text: String
var onKey: (OverlayKey) -> Bool
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.drawsBackground = false
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
let textView = NoteTextView(frame: .zero)
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
textView.autoresizingMask = [.width]
textView.textContainer?.widthTracksTextView = true
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
scroll.documentView = textView
let role = Typography.note
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = role.lineHeight ?? 23.8
paragraph.maximumLineHeight = role.lineHeight ?? 23.8
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: 0xE4E7E6)
textView.insertionPointColor = NSColor(hex: 0xE8913A)
textView.defaultParagraphStyle = paragraph
textView.typingAttributes = [.font: role.nsFont, .foregroundColor: NSColor(hex: 0xE4E7E6), .paragraphStyle: paragraph]
textView.textContainerInset = NSSize(width: 20, height: 18)
textView.string = text
textView.delegate = context.coordinator
textView.onKey = onKey
textView.placeholder = "Anything you want to keep next to this project…"
DispatchQueue.main.async {
guard let window = textView.window, window.makeFirstResponder(textView) else { return }
textView.setSelectedRange(NSRange(location: (textView.string as NSString).length, length: 0))
textView.scrollRangeToVisible(textView.selectedRange())
}
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
guard let textView = scroll.documentView as? NoteTextView else { return }
textView.onKey = onKey
if textView.string != text { textView.string = text }
}
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: NoteEditor
init(_ parent: NoteEditor) {
self.parent = parent
}
func textDidChange(_ notification: Notification) {
guard let textView = notification.object as? NSTextView else { return }
parent.text = textView.string
textView.needsDisplay = true
}
func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {
selector == #selector(NSResponder.cancelOperation(_:)) ? parent.onKey(.escape) : false
}
}
}
/// Catches ⌘P before the menu bar's ⌘P (push) and draws the placeholder.
private final class NoteTextView: NSTextView {
var onKey: (OverlayKey) -> Bool = { _ in false }
var placeholder = ""
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if window?.firstResponder === self, OverlayKey(event: event) == .commandP, onKey(.commandP) { return true }
return super.performKeyEquivalent(with: event)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard string.isEmpty, !placeholder.isEmpty else { return }
let attributes: [NSAttributedString.Key: Any] = [.font: font ?? Typography.note.nsFont, .foregroundColor: NSColor(hex: 0x6C7783)]
let origin = NSPoint(x: textContainerInset.width + (textContainer?.lineFragmentPadding ?? 0), y: textContainerInset.height)
(placeholder as NSString).draw(at: origin, withAttributes: attributes)
}
}
@@ -0,0 +1,53 @@
import HelderCore
import SwiftUI
/// Renders `model.overlay.current`: exactly one overlay at a time. The launcher is drawn by the shell.
public struct OverlayHost: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
switch model.overlay.current {
case .none, .launcher:
EmptyView()
case let .search(seed):
if let search = model.services?.search {
let path = model.editor?.activePath
SearchOverlay(
model: SearchModel(search: search, seed: seed, activePath: path,
activeText: path.map { model.editor?.text(for: $0) ?? "" } ?? "",
showHidden: model.layout.showHidden),
changedPaths: model.changedPaths,
onOpen: { model.perform(.open($0.path, OpenOptions(line: $0.line))) },
onClose: dismiss
)
}
case .shortcuts:
ShortcutsOverlay(onClose: dismiss)
case .note:
if let note = model.note {
NoteOverlay(note: note, onPassOn: { model.perform(.passNote) }, onClose: dismiss)
}
case let .recentFiles(initialSelection):
RecentFilesOverlay(history: model.editor?.history ?? [], initialSelection: initialSelection,
changedPaths: model.changedPaths,
onOpen: { model.perform(.open($0, OpenOptions())) },
onClose: dismiss)
case let .contextMenu(request):
ContextMenuOverlay(request: request, onPerform: { model.perform(.context($0)) }, onClose: dismiss)
case let .namePrompt(request):
NamePromptOverlay(request: request, onSubmit: { model.perform(.submitName($0)) }, onClose: dismiss)
case let .confirm(request):
ConfirmOverlay(request: request, onConfirm: { model.perform(.confirmPending) }, onClose: dismiss)
case .diff, .passOn, .symbol:
EditorOverlayContent(model: model)
}
}
private func dismiss() {
model.perform(.dismissOverlay)
}
}
+154
View File
@@ -0,0 +1,154 @@
import AppKit
import SwiftUI
/// The keys the overlays react to, from a text field or a bare key catcher.
enum OverlayKey: Equatable {
case up, down, commandUp, commandDown, commandLeft, commandRight, enter, escape
case commandP
/// Maps the text system's commands back to the keys that produced them.
init?(selector: Selector) {
switch selector {
case #selector(NSResponder.moveUp(_:)): self = .up
case #selector(NSResponder.moveDown(_:)): self = .down
case #selector(NSResponder.moveToBeginningOfDocument(_:)): self = .commandUp
case #selector(NSResponder.moveToEndOfDocument(_:)): self = .commandDown
case #selector(NSResponder.moveToBeginningOfLine(_:)), #selector(NSResponder.moveToLeftEndOfLine(_:)): self = .commandLeft
case #selector(NSResponder.moveToEndOfLine(_:)), #selector(NSResponder.moveToRightEndOfLine(_:)): self = .commandRight
case #selector(NSResponder.insertNewline(_:)): self = .enter
case #selector(NSResponder.cancelOperation(_:)): self = .escape
default: return nil
}
}
/// Maps a raw key event, for overlays without a text field.
init?(event: NSEvent) {
let command = event.modifierFlags.contains(.command)
switch event.keyCode {
case 126: self = command ? .commandUp : .up
case 125: self = command ? .commandDown : .down
case 123 where command: self = .commandLeft
case 124 where command: self = .commandRight
case 36, 76: self = .enter
case 53: self = .escape
default:
guard command, event.charactersIgnoringModifiers?.lowercased() == "p" else { return nil }
self = .commandP
}
}
}
/// A borderless single-line field that hands navigation keys to the overlay before the text system sees them.
struct OverlayCommandField: NSViewRepresentable {
@Binding var text: String
var placeholder: String
var font: NSFont
/// nil selects the whole text on focus, so typing replaces a seeded query.
var initialSelection: NSRange?
var onKey: (OverlayKey) -> Bool
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSTextField {
let field = FocusingTextField()
field.isBordered = false
field.drawsBackground = false
field.focusRingType = .none
field.font = font
field.textColor = NSColor(hex: 0xF4F5F4)
field.placeholderAttributedString = NSAttributedString(
string: placeholder,
attributes: [.foregroundColor: NSColor(hex: 0x6C7783), .font: font]
)
field.stringValue = text
field.delegate = context.coordinator
field.cell?.isScrollable = true
field.cell?.wraps = false
field.initialSelection = initialSelection
return field
}
func updateNSView(_ field: NSTextField, context: Context) {
context.coordinator.parent = self
if field.stringValue != text { field.stringValue = text }
}
final class Coordinator: NSObject, NSTextFieldDelegate {
var parent: OverlayCommandField
init(_ parent: OverlayCommandField) {
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 {
guard let key = OverlayKey(selector: selector) else { return false }
return parent.onKey(key)
}
}
}
/// An invisible first responder that forwards the overlay keys and swallows the ones it handles.
struct OverlayKeyCatcher: NSViewRepresentable {
var onKey: (OverlayKey) -> Bool
func makeNSView(context: Context) -> CatcherView {
let view = CatcherView()
view.onKey = onKey
return view
}
func updateNSView(_ view: CatcherView, context: Context) {
view.onKey = onKey
}
final class CatcherView: NSView {
var onKey: (OverlayKey) -> Bool = { _ in false }
override var acceptsFirstResponder: Bool { true }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
DispatchQueue.main.async { [weak self] in
guard let self, let window = self.window else { return }
window.makeFirstResponder(self)
}
}
override func keyDown(with event: NSEvent) {
if let key = OverlayKey(event: event), onKey(key) { return }
super.keyDown(with: event)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard window?.firstResponder === self, let key = OverlayKey(event: event) else {
return super.performKeyEquivalent(with: event)
}
return onKey(key) || super.performKeyEquivalent(with: event)
}
}
}
/// Takes focus once it is on screen and applies the initial selection.
private final class FocusingTextField: NSTextField {
var initialSelection: NSRange?
private var focused = false
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard !focused, window != nil else { return }
focused = true
DispatchQueue.main.async { [weak self] in
guard let self, let window = self.window, window.makeFirstResponder(self) else { return }
guard let editor = self.currentEditor() as? NSTextView else { return }
editor.insertionPointColor = NSColor(hex: 0xE8913A)
let length = (self.stringValue as NSString).length
editor.selectedRange = self.initialSelection.map { NSRange(location: min($0.location, length), length: min($0.length, length)) }
?? NSRange(location: 0, length: length)
}
}
}
@@ -0,0 +1,135 @@
import AppKit
import HelderCore
import SwiftUI
/// Keyboard movement through a plain list, clamped at both ends.
enum ListCursor {
static func step(_ current: Int, by step: Int, count: Int) -> Int {
guard count > 0 else { return 0 }
return min(max(current + step, 0), count - 1)
}
/// ⌘↓ from the editor starts on the previous file (row 1), ⌘↑ on the current one.
static func recentFilesStart(movingDown: Bool, count: Int) -> Int {
movingDown ? max(0, min(1, count - 1)) : 0
}
}
/// ⌘↑/⌘↓ from the editor: the recently opened files, newest first.
struct RecentFilesOverlay: View {
let history: [String]
var changedPaths: Set<String>
var onOpen: (String) -> Void
var onClose: () -> Void
@State private var selection: Int
@State private var parkedPointer: CGPoint?
init(history: [String], initialSelection: Int, changedPaths: Set<String>,
onOpen: @escaping (String) -> Void, onClose: @escaping () -> Void) {
self.history = history
self.changedPaths = changedPaths
self.onOpen = onOpen
self.onClose = onClose
_selection = State(initialValue: ListCursor.step(initialSelection, by: 0, count: history.count))
}
var body: some View {
OverlayShell(.sized(width: 560), onDismiss: onClose) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "doc", title: "Recent files", iconColor: Palette.text4, showsEscChip: false) {
HStack(spacing: 4) {
Text("\(history.count) file\(history.count == 1 ? "" : "s") ·")
Keycap("⌘↓")
Keycap("⌘↑")
Keycap("↵")
}
.typeRole(Typography.path)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
}
list
}
.background(OverlayKeyCatcher(onKey: handle))
}
}
private var list: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(spacing: 0) {
if history.isEmpty {
Text("No files opened yet")
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
.frame(maxWidth: .infinity, alignment: .leading)
}
ForEach(Array(history.enumerated()), id: \.element) { index, path in
row(path, selected: index == selection)
.id(index)
.onHover { inside in if inside { hover(index) } }
.onTapGesture { open(path) }
}
}
.padding(.vertical, 6)
}
.frame(height: min(460, CGFloat(max(history.count, 1)) * Metrics.launcherRow + 12 + (history.isEmpty ? 12 : 0)))
.onChange(of: selection) { _, row in proxy.scrollTo(row) }
}
}
private func row(_ path: String, selected: Bool) -> some View {
let directory = PathUtils.dirname(path)
return HStack(spacing: 10) {
TypeBadge(path: path)
VStack(alignment: .leading, spacing: 1) {
Text(PathUtils.basename(path))
.typeRole(Typography.rowSelected)
.foregroundStyle(selected ? Palette.text1 : Palette.text3)
.lineLimit(1)
Text(directory.isEmpty ? "" : directory + "/")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.head)
}
Spacer(minLength: 0)
if changedPaths.contains(path) {
Text("•").typeRole(Typography.statusLetter).foregroundStyle(Palette.changedDot)
}
}
.padding(.horizontal, 14)
.frame(height: Metrics.launcherRow)
.contentShape(Rectangle())
.selectableRow(isSelected: selected)
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .up, .commandUp: park(); selection = ListCursor.step(selection, by: -1, count: history.count)
case .down, .commandDown: park(); selection = ListCursor.step(selection, by: 1, count: history.count)
case .enter: if history.indices.contains(selection) { open(history[selection]) }
case .escape: onClose()
default: return false
}
return true
}
private func park() {
parkedPointer = NSEvent.mouseLocation
}
private func hover(_ index: Int) {
if let parked = parkedPointer, parked == NSEvent.mouseLocation { return }
parkedPointer = nil
selection = index
}
private func open(_ path: String) {
onClose()
onOpen(path)
}
}
+309
View File
@@ -0,0 +1,309 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
import Observation
/// The ⌘F overlay's state: three indexes searched per keystroke (open file, project contents, file names).
@Observable
@MainActor
public final class SearchModel {
public enum Column: Equatable, Sendable {
case thisFile, project, files
}
/// What ↵ or a click opens: a file, optionally at a line.
public struct Target: Equatable, Sendable {
public var path: String
public var line: Int?
}
/// One content hit as it appears in the project column; `index` is its position for the keyboard.
public struct HitRow: Equatable, Identifiable {
public var path: String
public var hit: ContentHit
public var index: Int
public var id: String { "\(path):\(hit.line)" }
}
public struct Group: Equatable, Identifiable {
public var path: String
/// Every hit ripgrep reported, for the count.
public var hitCount: Int
/// The hits drawn under the header.
public var rows: [HitRow]
public var id: String { path }
}
/// A file-type chip and how many results of that type the unfiltered set carries.
public struct ExtensionChip: Equatable, Sendable {
public var ext: String
public var count: Int
}
/// Ranks file names for a query; injectable so a test can count the calls.
public typealias FileRanker = (_ query: String, _ paths: [String], _ showHidden: Bool) -> [FileNameMatch]
/// Hit lines shown per file; the header count still says how many there are.
public static let shownHitsPerFile = 12
public private(set) var query: String
public private(set) var column = Column.project
public private(set) var projectSelection = 0
public private(set) var fileSelection = 0
public private(set) var inFileSelection = 0
/// nil shows every file type.
public private(set) var extensionFilter: String?
public private(set) var content: [ContentGroup] = []
public private(set) var allPaths: [String] = []
public var showHidden: Bool {
didSet {
guard showHidden != oldValue else { return }
rankFileNames()
recomputeContent()
}
}
// Derived once per change, not per read: a view body reads these many times per render.
public private(set) var inFileHits: [ContentHit] = []
public private(set) var groups: [Group] = []
public private(set) var hitRows: [HitRow] = []
public private(set) var totalHits = 0
/// Every file-name match after the type filter; the column draws the first `maxFileNameResults`.
public private(set) var fileMatches: [FileNameMatch] = []
public private(set) var shownFileMatches: [FileNameMatch] = []
/// Chips for every type the unfiltered results carry; empty when there is only one.
public private(set) var chips: [ExtensionChip] = []
@ObservationIgnored private var allFileMatches: [FileNameMatch] = []
@ObservationIgnored private var shownContent: [ContentGroup] = []
public let activePath: String?
@ObservationIgnored private let activeText: String
@ObservationIgnored private let search: SearchServicing
@ObservationIgnored private let debounce: Duration
@ObservationIgnored private let ranker: FileRanker
@ObservationIgnored public private(set) var pendingSearch: Task<Void, Never>?
public init(search: SearchServicing, seed: String = "", activePath: String? = nil, activeText: String = "",
showHidden: Bool = false, debounce: Duration = .milliseconds(SearchLimits.debounceMilliseconds),
ranker: @escaping FileRanker = { Fuzzy.rankFileNames(query: $0, paths: $1, showHidden: $2) }) {
self.search = search
self.query = seed
self.activePath = activePath
self.activeText = activeText
self.showHidden = showHidden
self.debounce = debounce
self.ranker = ranker
findInFile()
}
/// Loads the file-name index and runs the seeded query.
public func start() async {
scheduleContentSearch()
let paths = await search.listFiles(under: nil)
allPaths = paths
rankFileNames()
recomputeContent()
}
public var term: String { query.trimmingCharacters(in: .whitespaces) }
public var columns: [Column] {
activePath == nil ? [.project, .files] : [.thisFile, .project, .files]
}
// MARK: Results
public var extensionChips: [String] { chips.map(\.ext) }
/// "0 here · 39 hits · 2 files"; the first part only when a file is open.
public var summary: String {
let files = fileMatches.count
let here = activePath == nil ? "" : "\(inFileHits.count) here · "
return here + "\(totalHits) hit\(totalHits == 1 ? "" : "s") · \(files) file\(files == 1 ? "" : "s")"
}
/// The hover text of a type chip.
public nonisolated static func chipTooltip(count: Int, isChosen: Bool) -> String {
"\(count) result\(count == 1 ? "" : "s") · " + (isChosen ? "click to show every type" : "click to show only this type")
}
/// The one sentence a column shows instead of results, or nil when it has results.
public func emptyMessage(for column: Column) -> String? {
switch column {
case .thisFile:
if term.isEmpty { return "Type to search this file." }
return inFileHits.isEmpty ? "No matches in this file." : nil
case .project:
if term.count < SearchLimits.minContentQuery { return "Type at least two characters." }
return groups.isEmpty ? "No content matches." : nil
case .files:
if term.isEmpty { return "Type to search file names." }
return fileMatches.isEmpty ? "No file names match." : nil
}
}
// MARK: Editing
public func setQuery(_ value: String) {
guard value != query else { return }
let termChanged = value.trimmingCharacters(in: .whitespaces) != term
query = value
resetSelection()
guard termChanged else { return }
findInFile()
rankFileNames()
scheduleContentSearch()
recomputeContent()
}
/// Clicking the chosen chip again shows every type.
public func toggleExtension(_ ext: String) {
extensionFilter = extensionFilter == ext ? nil : ext
resetSelection()
recomputeFiltered()
}
/// Debounced per keystroke; a newer keystroke cancels the older search and its result.
private func scheduleContentSearch() {
pendingSearch?.cancel()
let term = self.term
guard term.count >= SearchLimits.minContentQuery else {
pendingSearch = nil
content = []
return
}
let debounce = self.debounce
let search = self.search
pendingSearch = Task { [weak self] in
do { try await Task.sleep(for: debounce) } catch { return }
let groups = await search.searchContent(term)
guard !Task.isCancelled, let self, self.term == term else { return }
self.content = groups
self.recomputeContent()
}
}
private func findInFile() {
guard activePath != nil, !term.isEmpty else {
inFileHits = []
return
}
inFileHits = Array(InFileSearch.hits(query: term, in: activeText).prefix(SearchLimits.maxInFileResults))
}
private func rankFileNames() {
allFileMatches = term.isEmpty ? [] : ranker(term, allPaths, showHidden)
}
/// After the content, the hidden toggle or the ranking changed: chips, then the filtered lists.
private func recomputeContent() {
shownContent = showHidden ? content : content.filter { !PathUtils.isHidden($0.path) }
let counts = InFileSearch.extensionCounts(paths: shownContent.map(\.path) + allFileMatches.map(\.path))
chips = counts.count > 1 ? counts.map { ExtensionChip(ext: $0.ext, count: $0.count) } : []
// A chosen type the new results no longer carry falls back to every type.
if let extensionFilter, !chips.contains(where: { $0.ext == extensionFilter }) {
self.extensionFilter = nil
}
recomputeFiltered()
}
private func recomputeFiltered() {
let visible = extensionFilter.map { ext in shownContent.filter { FileType.ext($0.path) == ext } } ?? shownContent
var index = 0
groups = visible.map { group in
let rows = group.hits.prefix(Self.shownHitsPerFile).map { hit -> HitRow in
defer { index += 1 }
return HitRow(path: group.path, hit: hit, index: index)
}
return Group(path: group.path, hitCount: group.hits.count, rows: rows)
}
hitRows = groups.flatMap(\.rows)
totalHits = groups.reduce(0) { $0 + $1.hitCount }
fileMatches = extensionFilter.map { ext in allFileMatches.filter { FileType.ext($0.path) == ext } } ?? allFileMatches
shownFileMatches = Array(fileMatches.prefix(SearchLimits.maxFileNameResults))
}
private func resetSelection() {
projectSelection = 0
fileSelection = 0
inFileSelection = 0
}
// MARK: Keyboard
/// ⌘← / ⌘→: stops at the ends.
public func moveColumn(by step: Int) {
let list = columns
let index = list.firstIndex(of: column) ?? 0
column = list[min(max(index + step, 0), list.count - 1)]
}
/// ↑↓ and ⌘↑⌘↓ inside the focused column.
public func moveRow(by step: Int) {
switch column {
case .thisFile: inFileSelection = clamp(inFileSelection + step, count: inFileHits.count)
case .project: projectSelection = clamp(projectSelection + step, count: hitRows.count)
case .files: fileSelection = clamp(fileSelection + step, count: shownFileMatches.count)
}
}
/// Hover: the pointer moves the focus and the row together.
public func select(_ column: Column, row: Int) {
self.column = column
switch column {
case .thisFile: inFileSelection = row
case .project: projectSelection = row
case .files: fileSelection = row
}
}
public func selection(in column: Column) -> Int {
switch column {
case .thisFile: inFileSelection
case .project: projectSelection
case .files: fileSelection
}
}
/// ↵: the selected row, falling back to the other result kind when the column is empty.
public func target() -> Target? {
let hits = hitRows
let files = shownFileMatches
switch column {
case .thisFile:
guard let activePath, inFileHits.indices.contains(inFileSelection) else { return nil }
return Target(path: activePath, line: inFileHits[inFileSelection].line)
case .files:
if files.indices.contains(fileSelection) { return Target(path: files[fileSelection].path, line: nil) }
if hits.indices.contains(projectSelection) { return Target(path: hits[projectSelection].path, line: hits[projectSelection].hit.line) }
return nil
case .project:
if hits.indices.contains(projectSelection) { return Target(path: hits[projectSelection].path, line: hits[projectSelection].hit.line) }
return files.first.map { Target(path: $0.path, line: nil) }
}
}
private func clamp(_ value: Int, count: Int) -> Int {
max(0, min(value, count - 1))
}
// 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
var widths: [Column: CGFloat] = [:]
if focused == .project {
for side in columns where side != .project { widths[side] = restingSide[side] }
} else {
widths[focused] = (total * 0.7).rounded()
for side in columns where side != .project && side != focused { widths[side] = minimumSide }
}
let used = widths.values.reduce(0, +)
widths[.project] = max(0, total - used)
return widths
}
}
@@ -0,0 +1,360 @@
import AppKit
import HelderCore
import SwiftUI
/// ⌘F: this file | project | files, one query, keyboard-driven.
struct SearchOverlay: View {
@State private var model: SearchModel
/// Paths with a git change get a dot in the files column.
var changedPaths: Set<String>
var onOpen: (SearchModel.Target) -> Void
var onClose: () -> Void
/// Where the pointer was when the keyboard last moved; hover ignores rows that scroll under a parked pointer.
@State private var parkedPointer: CGPoint?
@State private var hoveredGroup: String?
init(model: SearchModel, changedPaths: Set<String>, onOpen: @escaping (SearchModel.Target) -> Void, onClose: @escaping () -> Void) {
_model = State(initialValue: model)
self.changedPaths = changedPaths
self.onOpen = onOpen
self.onClose = onClose
}
var body: some View {
OverlayShell(.inset, onDismiss: onClose) {
VStack(spacing: 0) {
queryBar.zIndex(1)
columns
footer
}
}
.task { await model.start() }
}
// MARK: Query bar
private var queryBar: some View {
HStack(spacing: 12) {
Image(systemName: "magnifyingglass").font(.system(size: 13)).foregroundStyle(Palette.text4)
OverlayCommandField(
text: Binding(get: { model.query }, set: { model.setQuery($0) }),
placeholder: "Search this file, the project, and file names…",
font: Typography.searchQuery.nsFont,
initialSelection: nil,
onKey: handle
)
.frame(maxWidth: .infinity)
chips
Text(model.summary)
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.fixedSize()
.padding(.leading, 12)
.hairline(.leading)
}
.padding(.horizontal, 18)
.frame(height: Metrics.searchQueryBar)
.hairline(.bottom)
}
private var chips: some View {
HStack(spacing: 4) {
ForEach(model.chips, id: \.ext) { chip in
let on = model.extensionFilter == nil || model.extensionFilter == chip.ext
Button { model.toggleExtension(chip.ext) } label: {
Text(chip.ext)
.font(TypeRole(.monoSemiBold, 10).font)
.foregroundStyle(on ? Palette.ink : Palette.text3)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.background(on ? Palette.amber : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall)
.strokeBorder(on ? Palette.amber : Palette.raised, lineWidth: Metrics.hairline))
}
.buttonStyle(.plain)
.tip(SearchModel.chipTooltip(count: chip.count, isChosen: model.extensionFilter == chip.ext))
}
}
.fixedSize()
}
// MARK: Columns
private var columns: some View {
GeometryReader { proxy in
let widths = SearchModel.widths(total: proxy.size.width, columns: model.columns, focused: model.column)
HStack(spacing: 0) {
if model.columns.contains(.thisFile) {
thisFileColumn.frame(width: widths[.thisFile])
divider
}
projectColumn.frame(width: max(0, (widths[.project] ?? 0) - dividerCount * Metrics.hairline))
divider
filesColumn.frame(width: widths[.files])
}
.animation(Metrics.colorTransition, value: model.column)
}
}
private var dividerCount: CGFloat { CGFloat(model.columns.count - 1) }
private var divider: some View {
Hairline(.vertical)
}
private func columnHeader(_ column: SearchModel.Column, title: String, count: Int?, badgePath: String? = nil) -> some View {
let focused = model.column == column
return HStack(spacing: 10) {
if let badgePath { TypeBadge(path: badgePath) }
Text(title)
.typeRole(Typography.panelLabel)
.foregroundStyle(focused ? Palette.amber : Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
if let count {
Text("\(count)")
.font(TypeRole(.monoSemiBold, 10).font)
.foregroundStyle(focused ? Palette.ink : Palette.text4)
.padding(.horizontal, focused ? 6 : 0)
.padding(.vertical, focused ? 3 : 0)
.background(focused ? Palette.amber : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
Spacer(minLength: 0)
}
.padding(.horizontal, column == .project ? 16 : 14)
.padding(.top, 12)
.padding(.bottom, 10)
.background(Palette.panel)
}
private func empty(_ text: String) -> some View {
Text(text)
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 14)
.frame(maxWidth: .infinity, alignment: .leading)
}
private var thisFileColumn: some View {
let hits = model.inFileHits
let path = model.activePath ?? ""
return VStack(spacing: 0) {
columnHeader(.thisFile, title: PathUtils.basename(path), count: hits.isEmpty ? nil : hits.count, badgePath: path)
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
if let message = model.emptyMessage(for: .thisFile) { empty(message) }
ForEach(Array(hits.enumerated()), id: \.offset) { index, hit in
let selected = model.column == .thisFile && model.inFileSelection == index
hitLine(hit, selected: selected)
.id(index)
.onHover { inside in if inside { hover(.thisFile, row: index) } }
.onTapGesture { open(SearchModel.Target(path: path, line: hit.line)) }
}
}
}
.onChange(of: model.inFileSelection) { _, row in proxy.scrollTo(row) }
}
}
}
private var projectColumn: some View {
let groups = model.groups
return VStack(spacing: 0) {
columnHeader(.project, title: "Project", count: model.totalHits > 0 ? model.totalHits : nil)
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
if let message = model.emptyMessage(for: .project) { empty(message) }
ForEach(groups) { group in
groupHeader(group)
ForEach(group.rows) { row in
let selected = model.column == .project && model.projectSelection == row.index
hitLine(row.hit, selected: selected)
.id(row.index)
.onHover { inside in if inside { hover(.project, row: row.index) } }
.onTapGesture { open(SearchModel.Target(path: row.path, line: row.hit.line)) }
}
}
}
.padding(.bottom, 12)
}
.onChange(of: model.projectSelection) { _, row in proxy.scrollTo(row) }
}
}
}
private func groupHeader(_ group: SearchModel.Group) -> some View {
HStack(spacing: 8) {
TypeBadge(path: group.path)
Text(group.path)
.typeRole(Typography.path)
.foregroundStyle(Palette.text3)
.lineLimit(1)
.truncationMode(.middle)
Spacer(minLength: 8)
Text("\(group.hitCount)").typeRole(Typography.path).foregroundStyle(Palette.text4)
}
.padding(EdgeInsets(top: 14, leading: 16, bottom: 6, trailing: 16))
.contentShape(Rectangle())
.selectableRow(isSelected: false, isHovered: hoveredGroup == group.path)
.onHover { inside in
if inside { hoveredGroup = group.path } else if hoveredGroup == group.path { hoveredGroup = nil }
}
.onTapGesture {
if let first = group.rows.first { open(SearchModel.Target(path: group.path, line: first.hit.line)) }
}
}
private func hitLine(_ hit: ContentHit, selected: Bool) -> some View {
HStack(spacing: 0) {
Text("\(hit.line)")
.typeRole(Typography.searchHit)
.foregroundStyle(selected ? Palette.amber : Palette.text5)
.frame(width: Metrics.searchHitGutter - 14, alignment: .trailing)
.padding(.trailing, 14)
Text(SearchHighlight.line(hit, length: (model.term as NSString).length, selected: selected))
.typeRole(Typography.searchHit)
.lineLimit(1)
.truncationMode(.tail)
.padding(.trailing, 14)
Spacer(minLength: 0)
}
.frame(height: Metrics.searchHitLine)
.contentShape(Rectangle())
.selectableRow(isSelected: selected)
}
private var filesColumn: some View {
let matches = model.shownFileMatches
return VStack(spacing: 0) {
columnHeader(.files, title: "Files", count: model.fileMatches.count)
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
if let message = model.emptyMessage(for: .files) { empty(message) }
ForEach(Array(matches.enumerated()), id: \.element.path) { index, match in
let selected = model.column == .files && model.fileSelection == index
fileRow(match, selected: selected)
.id(index)
.onHover { inside in if inside { hover(.files, row: index) } }
.onTapGesture { open(SearchModel.Target(path: match.path, line: nil)) }
}
}
}
.onChange(of: model.fileSelection) { _, row in proxy.scrollTo(row) }
}
}
}
private func fileRow(_ match: FileNameMatch, selected: Bool) -> some View {
let directory = PathUtils.dirname(match.path)
return HStack(spacing: 8) {
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)
.lineLimit(1)
if !directory.isEmpty {
Text(directory + "/").typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).truncationMode(.head)
}
}
Spacer(minLength: 0)
if changedPaths.contains(match.path) {
Text("•").typeRole(Typography.statusLetter).foregroundStyle(Palette.changedDot)
}
}
.padding(.horizontal, 14)
.padding(.vertical, 4)
.frame(minHeight: 26)
.contentShape(Rectangle())
.selectableRow(isSelected: selected)
}
// MARK: Footer
private var footer: some View {
OverlayFooter(Self.footerHints) { EscChip() }
}
/// "⌘← / ⌘→ column ⌘↑ / ⌘↓ row ↵ open": amber keys, grey slashes and words.
private static let footerHints: Text = {
let hints: [(keys: [String], action: String)] = [(["⌘←", "⌘→"], "column"), (["⌘↑", "⌘↓"], "row"), (["↵"], "open")]
return hints.enumerated().reduce(Text("")) { text, item in
let (index, hint) = item
let keys = hint.keys.enumerated().reduce(Text("")) { keys, key in
keys + (key.offset == 0 ? Text("") : Text(" / ").foregroundColor(Palette.text4))
+ Text(key.element).foregroundColor(Palette.amber)
}
return text + Text(index == 0 ? "" : " ") + keys + Text(" " + hint.action).foregroundColor(Palette.text4)
}
}()
// MARK: Actions
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .commandLeft: model.moveColumn(by: -1)
case .commandRight: model.moveColumn(by: 1)
case .up, .commandUp: park(); model.moveRow(by: -1)
case .down, .commandDown: park(); model.moveRow(by: 1)
case .enter: if let target = model.target() { open(target) }
case .escape: onClose()
case .commandP: return false
}
return true
}
private func park() {
parkedPointer = NSEvent.mouseLocation
}
private func hover(_ column: SearchModel.Column, row: Int) {
if let parked = parkedPointer, parked == NSEvent.mouseLocation { return }
parkedPointer = nil
model.select(column, row: row)
}
private func open(_ target: SearchModel.Target) {
onClose()
onOpen(target)
}
}
/// The amber runs inside search results.
enum SearchHighlight {
/// The match run: amber fill with ink text on the selected row, amber-soft text elsewhere.
static func line(_ hit: ContentHit, length: Int, selected: Bool) -> AttributedString {
let text = hit.text as NSString
let start = min(max(0, hit.matchOffset), text.length)
let end = min(start + max(0, length), text.length)
var before = AttributedString(text.substring(to: start))
var match = AttributedString(text.substring(with: NSRange(location: start, length: end - start)))
var after = AttributedString(text.substring(from: end))
let plain = selected ? Palette.text2 : Palette.text3
before.foregroundColor = plain
after.foregroundColor = plain
match.foregroundColor = selected ? Palette.ink : Palette.amberSoft
if selected { match.backgroundColor = Palette.amber }
return before + match + after
}
/// Fuzzy-matched letters of a file name in bold amber.
static func name(_ name: String, indices: [Int]?, selected: Bool) -> AttributedString {
let marked = Set(indices ?? [])
var result = AttributedString()
for (offset, character) in name.enumerated() {
var piece = AttributedString(String(character))
if marked.contains(offset) {
piece.foregroundColor = Palette.amber
piece.font = TypeRole(.sansMedium, 12).font.bold()
} else {
piece.foregroundColor = selected ? Palette.text1 : Palette.text3
}
result += piece
}
return result
}
}
@@ -0,0 +1,103 @@
import SwiftUI
public struct ShortcutRow: Equatable, Sendable {
/// Each element is one keycap.
public var keys: [String]
public var label: String
}
public struct ShortcutGroup: Equatable, Sendable {
public var title: String
public var rows: [ShortcutRow]
}
/// The keyboard reference the `?` overlay shows. Keep it in step with the keyboard routing.
public enum ShortcutCatalog {
public static let groups: [ShortcutGroup] = [
ShortcutGroup(title: "Navigate", rows: [
ShortcutRow(keys: ["⌘", "F"], label: "Search contents and names"),
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: ["⇧", "⌘", "O"], label: "Open a recent project"),
ShortcutRow(keys: ["⌘", "O"], label: "Open a project folder"),
ShortcutRow(keys: ["⇧", "⌘", "N"], label: "Open a new window"),
ShortcutRow(keys: ["⌘", "click"], label: "PHP class: declaration and references"),
ShortcutRow(keys: ["?"], label: "This list of shortcuts"),
]),
ShortcutGroup(title: "Agent", rows: [
ShortcutRow(keys: ["⌘", "→"], label: "Pass the selection to the agent"),
ShortcutRow(keys: ["⌘", "N"], label: "Open the project note"),
ShortcutRow(keys: ["⌘", "P"], label: "Pass on the whole note"),
]),
ShortcutGroup(title: "Git", rows: [
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: [
ShortcutRow(keys: ["⌘", "S"], label: "Save this file"),
ShortcutRow(keys: ["⌘", "M"], label: "Markdown: code or rendered preview"),
ShortcutRow(keys: ["⌘", "W"], label: "Close this file, or the window when none is open"),
ShortcutRow(keys: ["⌘", "R"], label: "Re-read git and the files from disk"),
ShortcutRow(keys: ["⌘", "."], label: "Hidden files on or off"),
ShortcutRow(keys: ["⌘", "A"], label: "Select all in this pane"),
ShortcutRow(keys: ["⌘", "L"], label: "Fluid columns on or off"),
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"),
]),
]
}
/// `?`: the keyboard reference, grouped NAVIGATE / AGENT / GIT / FILE.
struct ShortcutsOverlay: View {
var onClose: () -> Void
var body: some View {
OverlayShell(.sized(width: 600), onDismiss: onClose) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "questionmark.circle", title: "Keyboard shortcuts")
// Grows with its content, and scrolls only when the window is too short for it.
ViewThatFits(in: .vertical) {
list
ScrollView { list }
}
}
.background(OverlayKeyCatcher { key in
guard key == .escape else { return false }
onClose()
return true
})
}
}
private var list: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(ShortcutCatalog.groups.enumerated()), id: \.offset) { index, group in
Text(group.title)
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(.top, index == 0 ? 0 : 16)
.padding(.bottom, 8)
ForEach(Array(group.rows.enumerated()), id: \.offset) { _, row in
HStack(spacing: 14) {
HStack(spacing: 4) {
ForEach(Array(row.keys.enumerated()), id: \.offset) { _, key in
Keycap(key).frame(minWidth: 22)
}
}
.frame(width: 92, alignment: .leading)
Text(row.label).typeRole(Typography.row).foregroundStyle(Palette.text2)
}
.padding(.vertical, 6)
}
}
}
.padding(EdgeInsets(top: 18, leading: 20, bottom: 22, trailing: 20))
.frame(maxWidth: .infinity, alignment: .leading)
}
}
+93
View File
@@ -0,0 +1,93 @@
Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ThinItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLight.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-ExtraLightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Light.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-LightItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Regular.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Italic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Medium.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-MediumItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-SemiBoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-Bold.ttf: Copyright 2017 IBM Corp. All rights reserved. IBMPlexMono-BoldItalic.ttf: Copyright 2017 IBM Corp. All rights reserved.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+64
View File
@@ -0,0 +1,64 @@
import AppKit
import HelderServices
/// App-level setup that SwiftUI has no hook for.
@MainActor
public final class AppDelegate: NSObject, NSApplicationDelegate {
public override init() {
super.init()
}
public func applicationWillFinishLaunching(_ notification: Notification) {
Log.setSink(FileLogger(directory: FileLogger.defaultDirectory))
FontRegistry.registerBundledFonts()
// `swift run` starts a bare executable, which macOS treats as a background tool without these two.
NSApp.setActivationPolicy(.regular)
NSApp.appearance = NSAppearance(named: .darkAqua)
// Every window is one project; tabs would put two projects in one window.
NSWindow.allowsAutomaticWindowTabbing = false
// One window per process: a quit must not leave windows for the next launch to reopen.
// Set in the app's domain, which wins over the system-wide "Close windows when quitting" choice.
UserDefaults.standard.set(false, forKey: "NSQuitAlwaysKeepsWindows")
// The View menu carries its own full-screen item; AppKit's automatic one would be a duplicate.
UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere")
}
public func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.activate(ignoringOtherApps: true)
}
public func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
false
}
/// ⌘Q asks about unsaved files in every window first, and writes each note and session before quitting.
public func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let models = WorkspaceRegistry.models
guard !models.isEmpty else { return .terminateNow }
Task { @MainActor in
for model in models where !(await model.prepareToClose()) {
sender.reply(toApplicationShouldTerminate: false)
return
}
for model in models { await model.closeProject() }
sender.reply(toApplicationShouldTerminate: true)
}
return .terminateLater
}
/// The Dock's right-click menu: the project's name, then New Window (a new process).
public func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
let menu = NSMenu()
menu.autoenablesItems = false
if let model = WorkspaceRegistry.current, model.root != nil {
menu.addItem(withTitle: model.title, action: nil, keyEquivalent: "").isEnabled = false
menu.addItem(.separator())
}
menu.addItem(withTitle: "New Window", action: #selector(newWindow), keyEquivalent: "").target = self
return menu
}
@objc private func newWindow() {
LiveSystemActions().openNewInstance(nil)
}
}
+44
View File
@@ -0,0 +1,44 @@
import Darwin
import Foundation
import HelderServices
/// Renames the running app, which is what Mission Control, the Dock tooltip and ⌘Tab show.
/// Uses private LaunchServices calls looked up at runtime; when one is missing the name stays as it is.
@MainActor
enum AppName {
static let standard = "Helder"
private static var current: String?
static func set(_ name: String) {
guard name != current else { return }
current = name
guard let calls = LaunchServicesCalls.shared, let asn = calls.currentASN()?.takeUnretainedValue() else { return }
let status = calls.setItem(LaunchServicesCalls.defaultSession, asn, calls.displayNameKey, name as CFString, nil)
if status != noErr { Log.warn("app", "could not rename the app to \(name): \(status)") }
}
}
private struct LaunchServicesCalls {
typealias CurrentASN = @convention(c) () -> Unmanaged<CFTypeRef>?
typealias SetItem = @convention(c) (Int32, CFTypeRef, CFString, CFTypeRef, UnsafeMutableRawPointer?) -> OSStatus
/// `kLSDefaultSessionID`
static let defaultSession: Int32 = -2
let currentASN: CurrentASN
let setItem: SetItem
let displayNameKey: CFString
static let shared: LaunchServicesCalls? = {
guard let handle = dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY),
let asn = dlsym(handle, "_LSGetCurrentApplicationASN"),
let set = dlsym(handle, "_LSSetApplicationInformationItem"),
let key = dlsym(handle, "_kLSDisplayNameKey") else {
Log.warn("app", "LaunchServices rename calls not found; the app keeps its name")
return nil
}
return LaunchServicesCalls(currentASN: unsafeBitCast(asn, to: CurrentASN.self),
setItem: unsafeBitCast(set, to: SetItem.self),
displayNameKey: key.load(as: CFString.self))
}()
}
+139
View File
@@ -0,0 +1,139 @@
import CoreGraphics
import Foundation
import HelderCore
/// Where a focus request sends the keyboard. Views observe `WorkspaceModel.focusRequest` and take
/// first responder when it names them.
public enum FocusTarget: Equatable, Sendable {
case panel(Panel)
/// ⌘C without a selection: the commit message field.
case commitMessage
}
/// A focus request; `id` makes a repeated request for the same target observable.
public struct FocusRequest: Equatable {
public var target: FocusTarget
public var id = UUID()
public init(_ target: FocusTarget) {
self.target = target
}
}
/// A text selection read from the focused text view, for ⌘→ and ⌘F.
public struct TextSelectionInfo: Equatable, Sendable {
public var text: String
/// 1-based, inclusive.
public var startLine: Int
public var endLine: Int
public init(text: String, startLine: Int, endLine: Int) {
self.text = text
self.startLine = startLine
self.endLine = endLine
}
}
public enum ZoomStep: Equatable, Sendable {
case reset
case bigger
case smaller
}
/// Everything the user can ask a workspace window to do. Views, menus and the key router all call
/// `WorkspaceModel.perform(_:)` with one of these, so one shortcut and its button can never drift apart.
public enum Command: Equatable, Sendable {
// MARK: Overlays
/// ⌘F; the seed is the first line of the current selection.
case showSearch(seed: String)
/// ⌘N
case showNote
/// `?`
case showShortcuts
/// ⇧⌘O: the other recent projects.
case showRecentProjects
/// ⌘↑/⌘↓ from the editor.
case showRecentFiles(initialSelection: Int)
/// Right-click or ⌘→ on a row; `anchor` is in window coordinates.
case showContextMenu(ContextTarget, anchor: CGPoint)
/// Esc: closes the one open overlay, with its own close behaviour (the note saves, Diff restores the mode).
case dismissOverlay
/// The confirm overlay's yes.
case confirmPending
/// The name prompt's ↵ with the typed name.
case submitName(String)
/// The pass-on prompt's ↵: inserts `text` into the agent and toasts `reference`.
case passToAgent(text: String, reference: String?)
// MARK: Launcher
case launcherMove(Int)
case launcherSelect(Int)
case launcherActivate
// MARK: Layout and focus
/// ⌘G
case toggleGit
/// ⌘L
case toggleAutoFit
/// ⌘.
case toggleHidden
/// Moves keyboard focus to a column (and takes first responder).
case focus(Panel)
/// ⌘←/⌘→ outside a text field.
case focusNeighbour(step: Int)
// MARK: Row cursor in Source Control and Explorer
/// ↑/↓
case moveRowCursor(Int)
/// ↵: git row opens its half, a file opens, a folder toggles.
case openSelectedRow
/// ⌘→ on a row: its context menu, anchored to the column's right edge.
case openRowMenu
// MARK: Editor
case open(String, OpenOptions)
/// ⌘S
case save
/// ⌘W: closes the active file, or the window when none is open.
case closeFileOrWindow
/// ⌘M
case cycleMode
/// ⌘→ with a selection: the pass-on prompt for it. nil falls back to the editor's line selection.
case passSelection(TextSelectionInfo?)
/// ⌘A outside a text field: the whole open file in its pane.
case selectAllInFile
// MARK: Git
/// ⌘↵
case commit
/// ⌘P
case push
/// ⌘C without a selection
case focusCommitMessage
// MARK: Note
/// ⌘P while the note is open.
case passNote
// MARK: Project and window
/// ⌘O
case openFolder
case openRecentProject(String)
/// ⌘R: git, tree and the open file, re-read from disk.
case refresh
/// ⇧⌘N
case newWindow
/// View → Actual Size, Zoom In, Zoom Out: the code and terminal text size.
case zoom(ZoomStep)
/// A context-menu item.
case context(ContextAction)
}
+23
View File
@@ -0,0 +1,23 @@
import SwiftUI
/// `⑂ branch │ project`, centred for half a second when the window becomes key again. No fade.
struct FocusFlash: View {
let model: WorkspaceModel
var body: some View {
HStack(spacing: 11) {
Image(systemName: "arrow.triangle.branch").font(.system(size: 18, weight: .light)).foregroundStyle(Palette.amber)
Text(model.sourceControl?.state.branch ?? "—").typeRole(Typography.focusFlash).foregroundStyle(Palette.amber)
Rectangle().fill(Palette.raised).frame(width: 1, height: 17).padding(.horizontal, 1)
Text(model.name).typeRole(Typography.focusFlashName).foregroundStyle(Palette.text1).lineLimit(1)
}
.padding(.horizontal, 22)
.padding(.vertical, 15)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.overlay(alignment: .leading) { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius / 2, y: Metrics.overlayShadowY)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.allowsHitTesting(false)
}
}
+143
View File
@@ -0,0 +1,143 @@
import AppKit
import HelderCore
import HelderServices
import SwiftUI
/// The app's window scene: one project per window.
public struct HelderScene: Scene {
public static let windowID = "workspace"
public init() {}
public var body: some Scene {
WindowGroup(id: Self.windowID) {
WorkspaceWindow(root: LaunchState.claimRoot())
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: Metrics.defaultWindow.width, height: Metrics.defaultWindow.height)
.commands { HelderCommands() }
}
}
/// The menu bar. Shortcuts the key router owns (⌘F, ⌘G, ⌘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
var body: some Commands {
CommandGroup(replacing: .newItem) {
Button("New Window") { openNewInstance(nil) }
.keyboardShortcut("n", modifiers: [.command, .shift])
Button("Open Folder…") { openFolder() }
.keyboardShortcut("o", modifiers: .command)
Menu("Open Recent") {
let recents = workspace?.recentProjects.filter { $0.path != workspace?.root?.path } ?? []
if recents.isEmpty {
Text("No Recent Projects")
} else {
ForEach(recents) { project in
Button(project.name) { openRecent(project.path) }
}
}
}
Button("Open Recent Project…") { workspace?.perform(.showRecentProjects) }
.keyboardShortcut("o", modifiers: [.command, .shift])
.disabled(workspace?.root == nil)
}
CommandGroup(replacing: .saveItem) {
Button(workspace?.editor?.activePath == nil ? "Close" : "Close File") {
if let workspace { workspace.perform(.closeFileOrWindow) } else { NSApp.keyWindow?.performClose(nil) }
}
.keyboardShortcut("w", modifiers: .command)
Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
.keyboardShortcut("w", modifiers: [.command, .shift])
Divider()
Button("Save") { workspace?.perform(.save) }
.keyboardShortcut("s", modifiers: .command)
.disabled(workspace?.editor?.activePath == nil)
}
// ⌘M cycles the editor's view, so Minimize gives up its shortcut.
CommandGroup(replacing: .windowSize) {
Button("Minimize") { NSApp.keyWindow?.miniaturize(nil) }
Button("Zoom") { NSApp.keyWindow?.zoom(nil) }
}
CommandGroup(before: .toolbar) {
Button("Refresh") { workspace?.perform(.refresh) }
.keyboardShortcut("r", modifiers: .command)
.disabled(workspace?.root == nil)
Divider()
Button(workspace?.layout.gitVisible == false ? "Show Source Control" : "Hide Source Control") {
workspace?.perform(.toggleGit)
}
.keyboardShortcut("g", modifiers: .command)
Button(workspace?.layout.fluid == false ? "Fluid Column Widths" : "Lock Column Widths") {
workspace?.perform(.toggleAutoFit)
}
.keyboardShortcut("l", modifiers: .command)
Button(workspace?.layout.showHidden == true ? "Hide Hidden Files" : "Show Hidden Files") {
workspace?.perform(.toggleHidden)
}
.keyboardShortcut(".", modifiers: .command)
Divider()
Button("Search") { workspace?.perform(.showSearch(seed: "")) }
.keyboardShortcut("f", modifiers: .command)
Button("Project Note") { workspace?.perform(.showNote) }
.keyboardShortcut("n", modifiers: .command)
Button("Keyboard Shortcuts") { workspace?.perform(.showShortcuts) }
Divider()
Button("Actual Size") { workspace?.perform(.zoom(.reset)) }
.keyboardShortcut("0", modifiers: .command)
Button("Zoom In") { workspace?.perform(.zoom(.bigger)) }
.keyboardShortcut("+", modifiers: .command)
Button("Zoom Out") { workspace?.perform(.zoom(.smaller)) }
.keyboardShortcut("-", modifiers: .command)
Divider()
Button(workspace?.layout.isFullScreen == true ? "Exit Full Screen" : "Enter Full Screen") {
NSApp.keyWindow?.toggleFullScreen(nil)
}
.keyboardShortcut("f", modifiers: [.command, .control])
}
CommandGroup(replacing: .help) {
Button("Keyboard Shortcuts") { workspace?.perform(.showShortcuts) }
Divider()
Button("Open Log") { LiveSystemActions().openLog() }
Button("Reveal Log in Finder") { LiveSystemActions().revealLog() }
}
}
private func openNewInstance(_ root: URL?) {
LiveSystemActions().openNewInstance(root)
}
/// Without a key window there is no project to switch, so the choice opens in a new process.
private func openFolder() {
if let workspace {
workspace.perform(.openFolder)
return
}
Task { @MainActor in
if let url = await LiveSystemActions().chooseFolder() { openNewInstance(url) }
}
}
private func openRecent(_ path: String) {
if let workspace {
workspace.perform(.openRecentProject(path))
} else {
openNewInstance(URL(fileURLWithPath: path))
}
}
}
/// Hands the launch folder (`$HELDER_PROJECT` or an argument) to the first window; a later window
/// in this process (the Dock reopening one after the last closed) starts on the launcher.
@MainActor
enum LaunchState {
private static var claimedInitial = false
static func claimRoot() -> URL? {
guard !claimedInitial else { return nil }
claimedInitial = true
return ProjectLocator.initialRoot()
}
}
+194
View File
@@ -0,0 +1,194 @@
import Foundation
import HelderCore
/// A key press, reduced to what the router matches on.
public struct KeyPress: Equatable, Sendable {
public enum Key: Equatable, Sendable {
/// Lowercased, as typed without modifiers; `?` arrives as itself.
case character(String)
case up, down, left, right
case enter
case escape
case other
}
public var key: Key
public var command: Bool
public var shift: Bool
public var option: Bool
public var control: Bool
public init(_ key: Key, command: Bool = false, shift: Bool = false, option: Bool = false, control: Bool = false) {
self.key = key
self.command = command
self.shift = shift
self.option = option
self.control = control
}
static func cmd(_ key: Key, shift: Bool = false) -> KeyPress { KeyPress(key, command: true, shift: shift) }
}
/// Who holds the keyboard when the key arrives.
public enum KeyboardOwner: Equatable, Sendable {
/// No text input: the workspace itself.
case workspace
/// A text field or text view, and the column it sits in.
case text(in: Panel?)
/// A terminal pane.
case terminal
}
/// The state a routing decision depends on; built from the window and the model at key time.
public struct KeyContext: Equatable, Sendable {
public var hasProject: Bool
public var overlay: OverlayKind
public var owner: KeyboardOwner
/// The focused text view or terminal has a non-empty selection.
public var hasTextSelection: Bool
/// The focused text view's selection, when it sits in the editor column.
public var editorTextSelection: TextSelectionInfo?
/// The editor's read-only panes hold a multi-line selection.
public var hasEditorLineSelection: Bool
public var activePanel: Panel?
public var focusZone: FocusZone
public var recentFileCount: Int
/// The seed ⌘F uses: the first line of the current selection.
public var searchSeed: String
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 = "") {
self.hasProject = hasProject
self.overlay = overlay
self.owner = owner
self.hasTextSelection = hasTextSelection
self.editorTextSelection = editorTextSelection
self.hasEditorLineSelection = hasEditorLineSelection
self.activePanel = activePanel
self.focusZone = focusZone
self.recentFileCount = recentFileCount
self.searchSeed = searchSeed
}
}
/// The overlay kinds the router tells apart.
public enum OverlayKind: Equatable, Sendable {
case none
case note
/// The full-screen Diff: the workspace shortcuts keep working over it. `busy` while its own
/// menu or pass-on prompt is open; those then own every key.
case diff(busy: Bool)
/// Any other overlay: it owns every key but Esc.
case other
public init(_ overlay: Overlay, diffBusy: Bool = false) {
switch overlay {
case .none: self = .none
case .note: self = .note
case .diff: self = .diff(busy: diffBusy)
default: self = .other
}
}
}
public enum KeyRoute: Equatable {
/// The key belongs to someone else: a text field, a terminal, an overlay's own handler, or a menu.
case pass
case perform(Command)
}
/// 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.
public enum KeyRouter {
public static func route(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
if press.control || press.option { return .pass }
if !context.hasProject { return launcherKey(press) }
switch context.overlay {
case .diff(busy: true): return .pass
case .none: if press.key == .escape { return .pass }
default: if press.key == .escape && !press.command { return .perform(.dismissOverlay) }
}
switch context.overlay {
case .none: break
case .diff:
if press == .cmd(.character("a")) { return .pass }
case .note:
return press == .cmd(.character("p")) ? .perform(.passNote) : .pass
case .other: return .pass
}
return press.command ? commandKey(press, context) : plainKey(press, context)
}
private static func launcherKey(_ press: KeyPress) -> KeyRoute {
guard !press.shift else { return .pass }
switch press.key {
case .up: return .perform(.launcherMove(-1))
case .down: return .perform(.launcherMove(1))
case .enter where !press.command: return .perform(.launcherActivate)
default: return .pass
}
}
private static func plainKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
let inList = context.owner == .workspace && (context.activePanel == .sourceControl || 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))
case .enter where inList && !press.shift: return .perform(.openSelectedRow)
case .character("?") where context.owner == .workspace: return .perform(.showShortcuts)
default: return .pass
}
}
private static func commandKey(_ press: KeyPress, _ context: KeyContext) -> KeyRoute {
let owner = context.owner
if press.shift {
return press.key == .character("o") ? .perform(.showRecentProjects) : .pass
}
switch press.key {
case .up, .down:
guard context.focusZone == .editor, context.recentFileCount > 0 else { return .pass }
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 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:
return .pass
}
}
private static func commandCharacter(_ c: String, _ context: KeyContext) -> KeyRoute {
switch c {
case "f": return .perform(.showSearch(seed: context.searchSeed))
case "p": return .perform(.push)
case "n": return .perform(.showNote)
case "s": return .perform(.save)
case "m": return .perform(.cycleMode)
case "w": return .perform(.closeFileOrWindow)
case "g": return .perform(.toggleGit)
case "l": return .perform(.toggleAutoFit)
case ".": return .perform(.toggleHidden)
case "a": return context.owner == .workspace ? .perform(.selectAllInFile) : .pass
case "c":
if context.hasTextSelection || context.hasEditorLineSelection { return .pass }
return .perform(.focusCommitMessage)
default: return .pass
}
}
}
+39
View File
@@ -0,0 +1,39 @@
import Foundation
import HelderCore
/// What choosing a launcher row does.
public enum LauncherChoice: Equatable {
/// "Open new project…": the folder picker.
case chooseFolder
case open(path: String)
}
/// The launcher's rows and keyboard cursor: row 0 is "Open new project…", then the recent projects.
public struct LauncherList: Equatable {
public private(set) var recents: [RecentProject]
public private(set) var selection = 0
/// `excluding` drops the window's own project, so ⇧⌘O never offers the folder that is already open.
public init(recents: [RecentProject] = [], excluding root: String? = nil) {
self.recents = recents.filter { $0.path != root }
}
public var count: Int { recents.count + 1 }
/// Moves the cursor, clamped to the first and last row.
public mutating func move(by step: Int) {
selection = min(max(selection + step, 0), count - 1)
}
public mutating func select(_ index: Int) {
selection = min(max(index, 0), count - 1)
}
public func choice(at index: Int) -> LauncherChoice? {
if index == 0 { return .chooseFolder }
guard recents.indices.contains(index - 1) else { return nil }
return .open(path: recents[index - 1].path)
}
public var selectedChoice: LauncherChoice? { choice(at: selection) }
}
+152
View File
@@ -0,0 +1,152 @@
import HelderCore
import SwiftUI
/// The bare window: no title bar, the launcher card top-centred on the editor ground.
struct LauncherScreen: View {
let model: WorkspaceModel
var body: some View {
ZStack(alignment: .top) {
Palette.editor
LauncherCard(model: model)
.padding(.top, Metrics.launcherTopPadding)
.padding(.horizontal, 20)
.padding(.bottom, 20)
}
}
}
/// Head, "Open new project…", the RECENT list and the key hints. Hover and the arrows move the same cursor.
/// The card hugs a short list and scrolls a long one inside the window.
struct LauncherCard: View {
let model: WorkspaceModel
var body: some View {
OverlayCard {
ViewThatFits(in: .vertical) {
VStack(spacing: 0) {
head
rows
footer
}
VStack(spacing: 0) {
head
ScrollViewReader { proxy in
ScrollView { rows }
.onChange(of: model.launcher.selection) { _, selection in proxy.scrollTo(selection) }
}
footer
}
}
}
.frame(width: Metrics.launcherWidth)
.frame(maxHeight: .infinity, alignment: .top)
}
private var rows: some View {
let launcher = model.launcher
return LazyVStack(alignment: .leading, spacing: 0) {
LauncherRow(index: 0, model: model) {
Image(systemName: "plus")
} text: {
Text("Open new project…").typeRole(Typography.rowSelected).foregroundStyle(Palette.text1)
} trailing: {
EscChip("↵")
}
.frame(height: Metrics.launcherNewRow)
.hairline(.bottom)
if !launcher.recents.isEmpty {
Text("Recent")
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 14, leading: 20, bottom: 6, trailing: 20))
}
ForEach(Array(launcher.recents.enumerated()), id: \.element.id) { offset, project in
recentRow(project, index: offset + 1)
}
}
}
private var head: some View {
HStack(spacing: 14) {
Image(systemName: "sparkle").font(.system(size: 16, weight: .light)).foregroundStyle(Palette.amber)
VStack(alignment: .leading, spacing: 5) {
Wordmark(role: Typography.launcherWordmark)
Text("Open a project to begin").typeRole(Typography.tooltip).foregroundStyle(Palette.text4)
}
Spacer(minLength: 0)
}
.padding(20)
.hairline(.bottom)
}
private func recentRow(_ project: RecentProject, index: Int) -> some View {
let selected = model.launcher.selection == index
return LauncherRow(index: index, model: model) {
Image(systemName: "folder")
} text: {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(project.name).typeRole(Typography.rowSelected).foregroundStyle(selected ? Palette.text1 : Palette.text3)
.lineLimit(1)
Text(project.path).typeRole(Typography.meta).foregroundStyle(selected ? Palette.text3 : Palette.text4)
.lineLimit(1).truncationMode(.head)
}
} trailing: {
EmptyView()
}
.frame(height: Metrics.launcherRow)
.help(project.path)
}
private var footer: some View {
OverlayFooter.hint([("⌘↑↓", "navigate"), ("↵", "open")])
.typeRole(Typography.chip)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, minHeight: Metrics.launcherFooter, alignment: .leading)
.hairline(.top)
}
}
private struct LauncherRow<Icon: View, Label: View, Trailing: View>: View {
let index: Int
let model: WorkspaceModel
let icon: Icon
let text: Label
let trailing: Trailing
@State private var isHovered = false
init(index: Int, model: WorkspaceModel, @ViewBuilder icon: () -> Icon, @ViewBuilder text: () -> Label,
@ViewBuilder trailing: () -> Trailing) {
self.index = index
self.model = model
self.icon = icon()
self.text = text()
self.trailing = trailing()
}
var body: some View {
let selected = model.launcher.selection == index
HStack(spacing: 12) {
icon
.font(.system(size: 13, weight: .light))
.foregroundStyle(selected || index == 0 ? Palette.amber : Palette.text4)
.frame(width: 16, height: 16)
text
Spacer(minLength: 8)
trailing
}
.padding(.horizontal, 20)
.frame(maxHeight: .infinity)
.selectableRow(isSelected: selected, isHovered: isHovered)
.contentShape(Rectangle())
.id(index)
.onHover { inside in
isHovered = inside
if inside { model.perform(.launcherSelect(index)) }
}
.onTapGesture {
model.perform(.launcherSelect(index))
model.perform(.launcherActivate)
}
}
}
@@ -0,0 +1,117 @@
import AppKit
import HelderCore
import SwiftUI
/// ⇧⌘O: the other recent projects; ↵ or a click switches this window to one.
struct RecentProjectsOverlay: View {
let model: WorkspaceModel
@State private var selection = 0
@State private var parkedPointer: CGPoint?
private var projects: [RecentProject] { model.otherRecentProjects }
var body: some View {
OverlayShell(.sized(width: 560), onDismiss: close) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "folder", title: "Open recent project", iconColor: Palette.text4, showsEscChip: false) {
HStack(spacing: 4) {
Text("\(projects.count) project\(projects.count == 1 ? "" : "s") ·")
Keycap("⌘↓")
Keycap("⌘↑")
Keycap("↵")
}
.typeRole(Typography.path)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
}
list
}
.background(OverlayKeyCatcher(onKey: handle))
}
}
private var list: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(spacing: 0) {
if projects.isEmpty {
Text("No other recent projects")
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
.frame(maxWidth: .infinity, alignment: .leading)
}
ForEach(Array(projects.enumerated()), id: \.element.id) { index, project in
row(project, selected: index == selection)
.id(index)
.onHover { inside in if inside { hover(index) } }
.onTapGesture { open(project) }
}
}
.padding(.vertical, 6)
}
.frame(height: min(460, CGFloat(max(projects.count, 1)) * Metrics.launcherRow + 12 + (projects.isEmpty ? 12 : 0)))
.onChange(of: selection) { _, row in proxy.scrollTo(row) }
}
}
private func row(_ project: RecentProject, selected: Bool) -> some View {
HStack(spacing: 10) {
Image(systemName: "folder")
.font(.system(size: 13, weight: .light))
.foregroundStyle(selected ? Palette.amber : Palette.text4)
.frame(width: 16)
VStack(alignment: .leading, spacing: 1) {
Text(project.name)
.typeRole(Typography.rowSelected)
.foregroundStyle(selected ? Palette.text1 : Palette.text2)
.lineLimit(1)
Text(project.path)
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.head)
}
Spacer(minLength: 0)
}
.padding(.horizontal, 14)
.frame(height: Metrics.launcherRow)
.contentShape(Rectangle())
.selectableRow(isSelected: selected)
.help(project.path)
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .up, .commandUp: park(); selection = ListCursor.step(selection, by: -1, count: projects.count)
case .down, .commandDown: park(); selection = ListCursor.step(selection, by: 1, count: projects.count)
case .enter: if projects.indices.contains(selection) { open(projects[selection]) }
case .escape: close()
default: return false
}
return true
}
/// Arrow keys park the pointer, so a list scrolling under a still mouse does not steal the selection.
private func park() {
parkedPointer = NSEvent.mouseLocation
}
private func hover(_ index: Int) {
if let parked = parkedPointer, parked == NSEvent.mouseLocation { return }
parkedPointer = nil
selection = index
}
private func close() {
model.perform(.dismissOverlay)
}
private func open(_ project: RecentProject) {
close()
model.perform(.openRecentProject(project.path))
}
}
@@ -0,0 +1,47 @@
import HelderCore
import SwiftUI
/// 28pt display-only bar: branch, line totals and staged/unstaged counts left; path, position, encoding, line ending and language right.
struct StatusBarView: View {
let model: WorkspaceModel
var body: some View {
let git = model.sourceControl?.state ?? .empty
let totals = git.totals
let editor = model.editor
let path = editor?.activePath
HStack(spacing: Metrics.statusBarGap) {
Text("⑂ \(git.branch)").foregroundStyle(Palette.amber).lineLimit(1)
Text("+\(totals.added)").foregroundStyle(Palette.addedText)
Text("\u{2212}\(totals.removed)").foregroundStyle(Palette.removedText)
Text("\(git.stagedCount) staged · \(git.unstagedCount) unstaged").lineLimit(1)
Spacer(minLength: 0)
if let path {
Text(path).lineLimit(1).truncationMode(.head)
.frame(maxWidth: 0.52 * model.layout.windowWidth, alignment: .trailing)
.fixedSize(horizontal: false, vertical: true)
Text("·")
Text(position(editor?.cursor, path: path))
Text("·")
}
Text("UTF-8")
Text("·")
Text("LF")
if let path {
Text("·")
Text(FileType.languageLabel(for: path)).foregroundStyle(Palette.text3)
}
}
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 14)
.frame(height: Metrics.statusBar)
.background(Palette.panel)
.hairline(.top)
}
private func position(_ cursor: Cursor?, path: String) -> String {
guard let cursor, cursor.path == path else { return "Ln 1, Col 1" }
return "Ln \(cursor.line), Col \(cursor.column)"
}
}
@@ -0,0 +1,92 @@
import AppKit
import HelderCore
import HelderServices
/// The AppKit side effects a workspace triggers: dialogs, the pasteboard, Finder and the log file.
@MainActor
public protocol SystemActing: AnyObject {
/// The folder picker; nil when cancelled.
func chooseFolder() async -> URL?
func copy(_ text: String)
func pasteboardText() -> String?
func revealInFinder(_ url: URL)
/// Asked before a file with unsaved edits closes.
func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice
func openLog()
func revealLog()
/// Starts another Helder process on `root`, or on the launcher when nil; each project runs in its own process.
func openNewInstance(_ root: URL?)
}
public final class LiveSystemActions: SystemActing {
public nonisolated init() {}
public func chooseFolder() async -> URL? {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.prompt = "Open"
panel.message = "Choose a project folder"
let response = await panel.begin()
return response == .OK ? panel.url : nil
}
public func copy(_ text: String) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
public func pasteboardText() -> String? {
NSPasteboard.general.string(forType: .string)
}
public func revealInFinder(_ url: URL) {
NSWorkspace.shared.activateFileViewerSelecting([url])
}
public func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice {
let alert = NSAlert()
alert.messageText = "Save changes to \(PathUtils.basename(path))?"
alert.informativeText = "\(path) has unsaved edits. They are lost if you close without saving."
alert.alertStyle = .warning
alert.addButton(withTitle: "Save")
alert.addButton(withTitle: "Don’t Save")
alert.addButton(withTitle: "Cancel")
switch alert.runModal() {
case .alertFirstButtonReturn: return .save
case .alertSecondButtonReturn: return .discard
default: return .cancel
}
}
public func openLog() {
NSWorkspace.shared.open(Self.logURL)
}
public func revealLog() {
revealInFinder(Self.logURL)
}
public func openNewInstance(_ root: URL?) {
let bundle = Bundle.main.bundleURL
guard bundle.pathExtension == "app" else {
guard let executable = Bundle.main.executableURL else { return }
do {
try InstanceLauncher.spawn(executable, root: root)
} catch {
Log.error("window", "could not start a new instance: \(error.localizedDescription)")
}
return
}
let configuration = NSWorkspace.OpenConfiguration()
configuration.createsNewApplicationInstance = true
configuration.activates = true
configuration.arguments = InstanceLauncher.arguments(for: root)
NSWorkspace.shared.openApplication(at: bundle, configuration: configuration) { _, error in
if let error { Log.error("window", "could not start a new instance: \(error.localizedDescription)") }
}
}
private static var logURL: URL { FileLogger.defaultDirectory.appendingPathComponent("helder.log") }
}
+117
View File
@@ -0,0 +1,117 @@
import HelderCore
import SwiftUI
/// 44pt bar: traffic-light inset, wordmark, project · branch, the open file's breadcrumb, and the toolbar.
struct TitleBarView: View {
let model: WorkspaceModel
var body: some View {
HStack(spacing: Metrics.titleBarGap) {
HStack(alignment: .firstTextBaseline, spacing: Metrics.titleClusterGap) {
Wordmark()
ProjectName(name: model.name) { model.perform(.openFolder) }
Text("·").typeRole(Typography.path).foregroundStyle(Palette.text4)
Text(model.sourceControl?.state.branch ?? "—")
.typeRole(Typography.branch)
.foregroundStyle(Palette.amber)
.lineLimit(1)
}
.fixedSize()
Breadcrumb(path: model.editor?.activePath, isDirty: model.editor.map { e in e.activePath.map(e.isDirty) ?? false } ?? false)
.frame(maxWidth: .infinity, alignment: .leading)
TitleToolbar(model: model)
}
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
.padding(.trailing, 14)
.frame(height: Metrics.titleBar)
.background(Palette.panel)
.hairline(.bottom)
}
}
private struct ProjectName: View {
let name: String
let action: () -> Void
@State private var isHovered = false
var body: some View {
Text(name)
.typeRole(Typography.path)
.foregroundStyle(isHovered ? Palette.text2 : Palette.text4)
.lineLimit(1)
.onHover { isHovered = $0 }
.onTapGesture(perform: action)
.help("Open folder…")
.animation(Metrics.colorTransition, value: isHovered)
}
}
/// `resources › views › form.blade.php`: segments in text-4, the file name in text-1 600, a dot when unsaved.
private struct Breadcrumb: View {
let path: String?
let isDirty: Bool
var body: some View {
if let path {
let segments = path.split(separator: "/").map(String.init)
HStack(spacing: Metrics.crumbGap) {
ForEach(Array(segments.enumerated()), id: \.offset) { index, segment in
if index > 0 { Text("›").foregroundStyle(Palette.text4) }
if index == segments.count - 1 {
Text(segment).typeRole(Typography.crumbLeaf).foregroundStyle(Palette.text1)
} else {
Text(segment).foregroundStyle(Palette.text4)
}
}
if isDirty {
Text("●").font(.system(size: 10)).foregroundStyle(Palette.amber).padding(.leading, 4).help("Unsaved changes")
}
}
.typeRole(Typography.path)
.lineLimit(1)
.truncationMode(.head)
} else {
Spacer(minLength: 0)
}
}
}
/// Search ⌘F · Fluid ⌘L · Hidden ⌘. · Note ⌘N · Git ⌘G · `?`, each with a tooltip that names its state.
private struct TitleToolbar: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
let overlay = model.overlay.current
HStack(spacing: Metrics.toolbarGap) {
ToolbarToggle("Search", keys: "⌘F", isOn: isSearch(overlay)) { model.perform(.showSearch(seed: "")) }
.tip("Search the open file, the project and the file names.", edge: .trailing)
ToolbarToggle("Fluid", keys: "⌘L", isOn: layout.fluid) { model.perform(.toggleAutoFit) }
.tip(layout.fluid
? Tooltip.stated("Column widths: ", "fluid", " — the columns re-fit on resize and focus. Click to lock them.")
: Tooltip.stated("Column widths: ", "locked", " — the columns keep their size. Click to make them fluid."),
edge: .trailing)
ToolbarToggle("Hidden", keys: "⌘.", isOn: layout.showHidden, muted: !layout.showHidden) { model.perform(.toggleHidden) }
.tip(layout.showHidden
? Tooltip.stated("Hidden files: ", "shown", " — dotfiles appear in the tree and the search. Click to hide them.")
: Tooltip.stated("Hidden files: ", "hidden", " — dotfiles are excluded from the tree and the search. Click to show them."),
edge: .trailing)
ToolbarToggle("Note", keys: "⌘N", isOn: overlay == .note) { model.perform(.showNote) }
.tip("Project note (.notes.txt) — kept next to this project.", edge: .trailing)
ToolbarToggle("Git", keys: "⌘G", isOn: layout.gitVisible) { model.perform(.toggleGit) }
.tip(layout.gitVisible
? Tooltip.stated("Source Control column: ", "shown", ". Click to hide it.")
: Tooltip.stated("Source Control column: ", "hidden", ". Click to show it."),
edge: .trailing)
ToolbarIconButton("?") { model.perform(.showShortcuts) }
.padding(.leading, 6)
.tip("Keyboard shortcuts.", edge: .trailing)
}
.fixedSize()
}
private func isSearch(_ overlay: Overlay) -> Bool {
if case .search = overlay { return true }
return false
}
}
+50
View File
@@ -0,0 +1,50 @@
import SwiftUI
/// Short confirmations, bottom-centred 44pt above the window edge. They may sit over an overlay.
struct ToastStack: View {
let toasts: ToastStore
var body: some View {
VStack(spacing: 8) {
ForEach(toasts.toasts) { toast in
ToastView(toast: toast)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
.padding(.bottom, Metrics.toastBottom)
.allowsHitTesting(false)
}
}
private struct ToastView: View {
let toast: Toast
var body: some View {
HStack(spacing: 12) {
Image(systemName: "doc.on.doc").font(.system(size: 12, weight: .light)).foregroundStyle(Palette.amber)
Text(toast.title).typeRole(Typography.toastTitle).foregroundStyle(Palette.text1)
if let detail = toast.detail, !detail.isEmpty {
Text(detail)
.typeRole(Typography.toastReference)
.foregroundStyle(Palette.ink)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 7)
.padding(.vertical, 3)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
.frame(maxWidth: 560)
.fixedSize()
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.overlay(alignment: .leading) {
UnevenRoundedRectangle(topLeadingRadius: Metrics.radiusMedium, bottomLeadingRadius: Metrics.radiusMedium)
.fill(Palette.amber)
.frame(width: Metrics.accentRule)
}
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
}
+364
View File
@@ -0,0 +1,364 @@
import AppKit
import SwiftTerm
import SwiftUI
/// Reaches the hosting NSWindow for what SwiftUI cannot do: title bar geometry, the key router and window events.
struct WindowBridge: NSViewRepresentable {
let model: WorkspaceModel
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
let title: String
let hasProject: Bool
func makeCoordinator() -> WindowCoordinator {
WindowCoordinator(model: model)
}
func makeNSView(context: Context) -> BridgeView {
let view = BridgeView()
view.coordinator = context.coordinator
return view
}
func updateNSView(_ view: BridgeView, context: Context) {
context.coordinator.updateTitle(title, hasProject: hasProject)
context.coordinator.guardClose()
}
static func dismantleNSView(_ view: BridgeView, coordinator: WindowCoordinator) {
coordinator.detach()
}
final class BridgeView: NSView {
weak var coordinator: WindowCoordinator?
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window { coordinator?.attach(to: window) }
}
}
}
@MainActor
final class WindowCoordinator: NSObject {
let model: WorkspaceModel
private weak var window: NSWindow?
private var monitors: [Any] = []
private var observers: [NSObjectProtocol] = []
private let closeGuard = WindowCloseGuard()
/// Set once the unsaved prompt said yes, so the second close goes through.
private var closeApproved = false
private var isAskingToClose = false
init(model: WorkspaceModel) {
self.model = model
}
func attach(to window: NSWindow) {
guard self.window !== window else { return }
detach()
self.window = window
configure(window)
installMonitors()
observe(window)
closeGuard.shouldClose = { [weak self] window in self?.shouldClose(window) ?? true }
guardClose()
WorkspaceRegistry.register(model, window: window)
model.hooks.closeWindow = { [weak window] in window?.performClose(nil) }
layoutTrafficLights()
}
/// Puts the close guard in front of SwiftUI's window delegate; SwiftUI may set its own again later.
func guardClose() {
guard let window, window.delegate !== closeGuard else { return }
closeGuard.original = window.delegate
window.delegate = closeGuard
}
/// The first close only asks: unsaved files prompt, the note and session are written, then the window closes.
private func shouldClose(_ window: NSWindow) -> Bool {
if closeApproved { return true }
guard !isAskingToClose else { return false }
isAskingToClose = true
Task { @MainActor [weak self, weak window] in
guard let self else { return }
let approved = await self.model.prepareToClose()
self.isAskingToClose = false
guard approved, let window else { return }
self.closeApproved = true
window.close()
}
return false
}
func detach() {
monitors.forEach(NSEvent.removeMonitor)
monitors = []
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
}
/// The launcher keeps the app's own name.
func updateTitle(_ title: String, hasProject: Bool) {
window?.title = title
AppName.set(hasProject ? title : AppName.standard)
}
private func configure(_ window: NSWindow) {
window.title = model.title
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.styleMask.insert(.fullSizeContentView)
window.isMovableByWindowBackground = false
window.backgroundColor = NSColor(hex: 0x101720)
window.appearance = NSAppearance(named: .darkAqua)
window.minSize = Metrics.minimumWindow
window.tabbingMode = .disallowed
// A restored window would be a second project in this process.
window.isRestorable = false
}
// MARK: Traffic lights
/// Places the traffic lights at (14, 12) and grows the title-bar container to match, so the whole strip drags the window.
/// AppKit resets both on resize and full-screen changes, hence the repeat calls.
func layoutTrafficLights() {
guard let window,
let close = window.standardWindowButton(.closeButton),
let zoom = window.standardWindowButton(.zoomButton),
let container = close.superview?.superview else { return }
let buttons = [close, window.standardWindowButton(.miniaturizeButton), zoom].compactMap { $0 }
let spacing = zoom.frame.minX - (window.standardWindowButton(.miniaturizeButton)?.frame.maxX ?? close.frame.maxX)
let origin = Metrics.trafficLightOrigin
var frame = container.frame
frame.size.height = close.frame.height + origin.y * 2
frame.origin.y = window.frame.height - frame.height
container.frame = frame
for (index, button) in buttons.enumerated() {
button.setFrameOrigin(NSPoint(x: origin.x + CGFloat(index) * (button.frame.width + spacing),
y: (frame.height - button.frame.height) / 2))
}
}
private func observe(_ window: NSWindow) {
let center = NotificationCenter.default
let relayout: [Notification.Name] = [NSWindow.didResizeNotification, NSWindow.didEndLiveResizeNotification,
NSWindow.didExitFullScreenNotification, NSWindow.didBecomeKeyNotification]
for name in relayout {
observers.append(center.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.layoutTrafficLights() }
})
}
observers.append(center.addObserver(forName: NSWindow.willEnterFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = true }
})
observers.append(center.addObserver(forName: NSWindow.didExitFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = false }
})
observers.append(center.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.windowDidResignKey() }
})
observers.append(center.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.becameKey(self.model)
self.model.windowDidBecomeKey()
}
})
observers.append(center.addObserver(forName: NSWindow.willCloseNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.unregister(self.model)
if WorkspaceRegistry.models.isEmpty { AppName.set(AppName.standard) }
self.model.windowWillClose()
self.detach()
}
})
}
// MARK: Keyboard and pointer
private func installMonitors() {
if let keys = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: { [weak self] event in
let consumed = MainActor.assumeIsolated { self?.handleKey(event) ?? false }
return consumed ? nil : event
}) { monitors.append(keys) }
if let mouse = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown], handler: { [weak self] event in
MainActor.assumeIsolated { self?.handleMouseDown(event) }
return event
}) { monitors.append(mouse) }
}
/// Returns true when the key ran a command and must not reach the responder chain.
private func handleKey(_ event: NSEvent) -> Bool {
guard let window, event.window === window, window.attachedSheet == nil else { return false }
switch KeyRouter.route(KeyPress(event), context(in: window)) {
case .pass:
return false
case let .perform(command):
model.perform(command)
if case let .focus(panel) = command { takeFocus(for: panel, in: window) }
if case .focusNeighbour = command, let panel = model.layout.activePanel { takeFocus(for: panel, in: window) }
return true
}
}
/// Source Control and Explorer have no text view to focus, so they hold the keyboard by clearing first responder.
private func takeFocus(for panel: Panel, in window: NSWindow) {
if panel == .sourceControl || panel == .explorer { window.makeFirstResponder(nil) }
}
private func handleMouseDown(_ event: NSEvent) {
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented 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 }
// 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,
view is NSText || view is TerminalView else { return }
if self.column(of: view) != panel { window.makeFirstResponder(nil) }
}
}
private func column(of view: NSView) -> Panel? {
let frame = view.convert(view.visibleRect, to: nil)
return model.layout.panel(atX: frame.midX)
}
private func context(in window: NSWindow) -> KeyContext {
let responder = window.firstResponder
var owner = KeyboardOwner.workspace
var hasSelection = false
var editorSelection: TextSelectionInfo?
var seed = ""
if let text = responder as? NSTextView {
let column = column(of: text)
owner = .text(in: column)
let range = text.selectedRange()
hasSelection = range.length > 0
if hasSelection {
let string = text.string as NSString
let selected = string.substring(with: range)
seed = selected.split(separator: "\n", omittingEmptySubsequences: false).first.map(String.init)?
.trimmingCharacters(in: .whitespaces) ?? ""
if column == .editor {
editorSelection = TextSelectionInfo(text: selected, startLine: Self.line(at: range.location, in: string),
endLine: Self.line(at: range.location + range.length - 1, in: string))
}
}
} else if let terminal = responder as? TerminalView {
owner = .terminal
hasSelection = terminal.selectionActive
} else if let canvas = responder as? DiffCanvasView {
hasSelection = canvas.hasSelection
}
let editor = model.editor
let lineSelection = editor.flatMap { editor in
editor.selection.flatMap { $0.path == editor.activePath && $0.start != $0.end ? $0 : nil }
}
return KeyContext(
hasProject: model.root != nil,
overlay: OverlayKind(model.overlay.current, diffBusy: editor?.diffOverlayBusy ?? false),
owner: owner,
hasTextSelection: hasSelection,
editorTextSelection: editorSelection,
hasEditorLineSelection: lineSelection != nil,
activePanel: model.layout.activePanel,
focusZone: model.layout.focusZone,
recentFileCount: editor?.history.count ?? 0,
searchSeed: seed
)
}
private static func line(at location: Int, in string: NSString) -> Int {
let end = min(max(location, 0), string.length)
var line = 1
var index = 0
while index < end {
let range = string.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
guard range.location != NSNotFound else { break }
line += 1
index = range.location + 1
}
return line
}
}
extension KeyPress {
/// Reads `.` by key code, so ⌘. works on every keyboard layout.
init(_ event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let key: Key
switch event.keyCode {
case 126: key = .up
case 125: key = .down
case 123: key = .left
case 124: key = .right
case 36, 76: key = .enter
case 53: key = .escape
case 47: key = .character(".")
default:
let typed = flags.contains(.command) ? event.charactersIgnoringModifiers : event.characters
key = typed.flatMap { $0.isEmpty ? nil : Key.character($0.lowercased()) } ?? .other
}
self.init(key, command: flags.contains(.command), shift: flags.contains(.shift),
option: flags.contains(.option), control: flags.contains(.control))
}
}
/// Stands in as the window's delegate to ask before a close, and hands every other message to SwiftUI's delegate.
final class WindowCloseGuard: NSObject, NSWindowDelegate {
weak var original: NSWindowDelegate?
var shouldClose: @MainActor (NSWindow) -> Bool = { _ in true }
override func responds(to selector: Selector!) -> Bool {
super.responds(to: selector) || original?.responds(to: selector) == true
}
override func forwardingTarget(for selector: Selector!) -> Any? {
original?.responds(to: selector) == true ? original : nil
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
let allowed = MainActor.assumeIsolated { shouldClose(sender) }
guard allowed else { return false }
return original?.windowShouldClose?(sender) ?? true
}
}
/// Every open workspace window, for ⌘Q and the Dock menu.
@MainActor
enum WorkspaceRegistry {
private struct Entry {
weak var model: WorkspaceModel?
weak var window: NSWindow?
}
private static var entries: [Entry] = []
private static weak var lastKey: WorkspaceModel?
static var models: [WorkspaceModel] { entries.compactMap(\.model) }
static func register(_ model: WorkspaceModel, window: NSWindow) {
entries.removeAll { $0.model == nil || $0.model === model }
entries.append(Entry(model: model, window: window))
}
static func unregister(_ model: WorkspaceModel) {
entries.removeAll { $0.model == nil || $0.model === model }
if lastKey === model { lastKey = nil }
}
static func becameKey(_ model: WorkspaceModel) {
lastKey = model
}
/// The key window's workspace, else the one that was key last.
static var current: WorkspaceModel? {
if let key = NSApp.keyWindow, let entry = entries.first(where: { $0.window === key }) { return entry.model }
return lastKey
}
}
@@ -0,0 +1,93 @@
import SwiftUI
/// The launcher without a project; with one, the title bar, four columns and status bar, overlays above.
struct WorkspaceView: View {
let model: WorkspaceModel
var body: some View {
ZStack {
if model.root == nil {
if model.isReady { LauncherScreen(model: model) } else { Palette.editor }
} else {
workspace
}
ToastStack(toasts: model.toasts)
if model.isFocusFlashVisible { FocusFlash(model: model) }
}
.ignoresSafeArea()
}
private var workspace: some View {
GeometryReader { proxy in
VStack(spacing: 0) {
TitleBarView(model: model)
.zIndex(2)
Columns(model: model)
.frame(maxHeight: .infinity)
.zIndex(1)
StatusBarView(model: model)
}
.overlay { OverlayHost(model: model) }
.overlay {
if model.overlay.current == .launcher { RecentProjectsOverlay(model: model) }
}
.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. The agent column is keyed by the project so its terminals respawn on a switch.
private struct Columns: View {
let model: WorkspaceModel
var body: some View {
let layout = model.layout
HStack(spacing: 0) {
if layout.gitVisible {
SourceControlColumn(model: model)
.frame(width: layout.widths.sourceControl)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragSourceControl(by: $0) }, onEnd: layout.endDrag)
}
ExplorerColumn(model: model)
.frame(width: layout.widths.explorer)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragExplorer(by: $0) }, onEnd: layout.endDrag)
EditorColumn(model: model)
.frame(minWidth: Metrics.minEditorWidth, maxWidth: .infinity)
.refreshFlash(model.refreshTick)
Splitter(onDrag: { layout.dragAgent(by: $0) }, onEnd: layout.endDrag)
AgentColumn(model: model)
.frame(width: layout.widths.agent)
.id(model.root)
}
.clipped()
}
}
/// ⌘R lightens a column for a moment and lets it settle back; each new tick replays it.
private struct RefreshFlash: ViewModifier {
let tick: Int
@State private var strength = 0.0
func body(content: Content) -> some View {
content
.overlay {
Palette.refreshFlash
.blendMode(.plusLighter)
.opacity(strength)
.allowsHitTesting(false)
}
.onChange(of: tick) {
strength = 1
withAnimation(.easeOut(duration: Metrics.refreshFlashDuration)) { strength = 0 }
}
}
}
extension View {
fileprivate func refreshFlash(_ tick: Int) -> some View {
modifier(RefreshFlash(tick: tick))
}
}
@@ -0,0 +1,33 @@
import AppKit
import SwiftUI
/// The root view of one window: owns the WorkspaceModel and wires it to the NSWindow and the menus.
public struct WorkspaceWindow: View {
@State private var model: WorkspaceModel
public init(root: URL?) {
_model = State(initialValue: WorkspaceModel(root: root, app: .live))
}
public var body: some 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))
.preferredColorScheme(.dark)
.focusedSceneValue(\.workspace, model)
.task { await model.start() }
}
}
struct WorkspaceFocusKey: FocusedValueKey {
typealias Value = WorkspaceModel
}
extension FocusedValues {
/// The key window's workspace, for menu commands.
var workspace: WorkspaceModel? {
get { self[WorkspaceFocusKey.self] }
set { self[WorkspaceFocusKey.self] = newValue }
}
}
@@ -0,0 +1,238 @@
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)
.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)
.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
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: NSTextView {
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
}
}
@@ -0,0 +1,290 @@
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())
.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
}
}
@@ -0,0 +1,227 @@
import Foundation
import HelderCore
import HelderServices
extension EditorStore {
// MARK: Reading from disk
/// ⌘R: re-reads a file; disk wins over an unsaved buffer, because the agent may have rewritten it.
public func reloadFromDisk(_ path: String) async {
await load(path, discardEdits: true)
}
public func reloadActiveFromDisk() async {
guard let path = activePath else { return }
await reloadFromDisk(path)
}
/// The watcher saw files change (nil: anything may have). The open file and every unsaved buffer pick up
/// the new disk text; a dirty buffer is kept, so a background write never eats the user's typing.
public func filesChanged(_ paths: [String]?) async {
let watched = (activePath.map { [$0] } ?? []) + dirtyPaths.filter { $0 != activePath }
let targets = watched.filter { path in
guard let state = states[path], state.disk != nil || state.image != nil || state.isBinary else { return false }
return paths.map { $0.contains(path) } ?? true
}
for path in targets { await load(path, discardEdits: false) }
}
/// Bytes of an image a Markdown document shows; project-relative, read through the file service.
public func readImage(_ path: String) async -> Data? {
await files.readImage(path)
}
func load(_ path: String, discardEdits: Bool) async {
let generation = nextGeneration(path)
switch EditorFileKind.of(path) {
case .image:
let data = await files.readImage(path)
guard loadGeneration[path] == generation else { return }
states[path, default: FileState()].image = data
states[path]?.imageUnreadable = data == nil
case .binary:
return
case .text:
let contents: FileContents
do {
contents = try await files.readText(path)
} catch {
guard loadGeneration[path] == generation else { return }
Log.warn("editor", "read failed for \(path): \(error.localizedDescription)")
if Self.isMissing(error) {
markDeleted(path, discardEdits: discardEdits)
} else if states[path]?.disk == nil {
states[path, default: FileState()].disk = ""
}
return
}
guard loadGeneration[path] == generation else { return }
switch contents {
case let .text(text):
states[path, default: FileState()].isBinary = false
applyDisk(text, for: path, discardEdits: discardEdits)
case .binary:
states[path, default: FileState()].isBinary = true
}
}
}
private func nextGeneration(_ path: String) -> Int {
let next = (loadGeneration[path] ?? 0) + 1
loadGeneration[path] = next
return next
}
private func applyDisk(_ text: String, for path: String, discardEdits: Bool) {
var state = states[path] ?? FileState()
let previous = state.disk
let wasDeleted = state.isDeleted
state.disk = text
state.isDeleted = false
states[path] = state
if let buffer = state.buffer {
if discardEdits {
states[path]?.buffer = nil
bumpRevision(path)
} else if buffer == text {
states[path]?.buffer = nil
}
} else if previous != text || wasDeleted {
bumpRevision(path)
}
}
/// The file is gone: its last text stays on screen as unsaved edits, so nothing is lost and
/// only an explicit save writes it back. A forced reload lets the empty disk win.
private func markDeleted(_ path: String, discardEdits: Bool) {
var state = states[path] ?? FileState()
cancelAutoSave(path)
if discardEdits {
state.buffer = nil
state.disk = ""
state.isDeleted = false
states[path] = state
bumpRevision(path)
return
}
guard !state.isDeleted else { return }
state.isDeleted = true
if state.buffer == nil { state.buffer = state.disk ?? "" }
if state.disk == nil { state.disk = "" }
states[path] = state
}
static func isMissing(_ error: Error) -> Bool {
if let cocoa = error as? CocoaError {
return cocoa.code == .fileReadNoSuchFile || cocoa.code == .fileNoSuchFile
}
let ns = error as NSError
return ns.domain == NSPOSIXErrorDomain && ns.code == Int(ENOENT)
}
// MARK: Saving
/// ⌘S: writes the active buffer when it differs from disk, then re-reads the disk copy.
public func save() async throws {
guard let path = activePath else { return }
try await save(path: path)
}
/// `announce` is off for auto-save, which would otherwise toast on every pause in typing.
public func save(path: String, announce: Bool = true) async throws {
guard let text = states[path]?.buffer, isDirty(path) else { return }
cancelAutoSave(path)
let generation = nextGeneration(path)
do {
try await files.write(path, contents: text)
} catch {
Log.error("save", "write failed for \(path): \(error.localizedDescription)")
showToast?("Save failed", path)
throw error
}
let disk = (try? await files.read(path)) ?? text
if loadGeneration[path] == generation, states[path] != nil {
states[path]?.disk = disk
states[path]?.isDeleted = false
if states[path]?.buffer == disk { states[path]?.buffer = nil }
}
if announce { showToast?("Saved", path) }
fileSaved?(path)
}
func scheduleAutoSave(_ path: String) {
cancelAutoSave(path)
let id = UUID()
let task = Task { [weak self] in
try? await Task.sleep(for: .milliseconds(600))
guard let self, !Task.isCancelled, self.autoSaves[path]?.id == id else { return }
self.autoSaves[path] = nil
try? await self.save(path: path, announce: false)
}
autoSaves[path] = (id, task)
}
func cancelAutoSave(_ path: String) {
autoSaves.removeValue(forKey: path)?.task.cancel()
}
/// Writes every auto-save still waiting on its pause, so nothing typed is left behind.
public func flushAutoSaves() async {
for path in Array(autoSaves.keys) {
cancelAutoSave(path)
try? await save(path: path, announce: false)
}
}
/// Before a window closes or switches project: each dirty file asks save, discard or cancel.
/// Returns false on cancel, and then no discard is applied.
public func resolveUnsaved() async -> Bool {
await flushAutoSaves()
var discarded: [String] = []
for path in dirtyPaths {
switch confirmUnsavedClose?(path) ?? .cancel {
case .cancel:
return false
case .save:
do { try await save(path: path) } catch { return false }
case .discard:
discarded.append(path)
}
}
for path in discarded where states[path]?.buffer != nil {
states[path]?.buffer = nil
bumpRevision(path)
}
return true
}
// MARK: Session
/// Restores the last session and the recent-files list for this project.
public func restore(restoreSession: Bool) async {
history = await recentFiles.load()
sessionEnabled = restoreSession
defer { hasRestored = true }
guard restoreSession, let saved = session.loadSession(root: root) else { return }
let usable = { (p: String) in !FileType.tooBigNames.contains(PathUtils.basename(p)) }
for (path, mode) in saved.modes { states[path, default: FileState()].mode = mode == .diff ? .actual : mode }
for (path, side) in saved.sides { states[path, default: FileState()].side = side }
activePath = saved.active.flatMap { usable($0) ? $0 : nil }
if let active = activePath { await load(active, discardEdits: true) }
}
/// Writes the session and the recent-files list.
public func persist() async {
if sessionEnabled {
let state = SessionState(active: activePath, modes: modes.filter { $0.key == activePath },
sides: sides.filter { $0.key == activePath })
session.saveSession(state, root: root)
}
await recentFiles.save(history)
}
func persistSoon() {
guard hasRestored else { return }
track { await $0.persist() }
}
}
+460
View File
@@ -0,0 +1,460 @@
import Foundation
import HelderCore
import HelderServices
import Observation
/// A highlight on the line a jump landed on; `id` restarts it for a repeat jump.
public struct LineFlash: Equatable {
public var path: String
public var line: Int
public var id = UUID()
}
/// The answer to "close a file with unsaved edits?".
public enum UnsavedCloseChoice: Equatable, Sendable {
case save
case discard
case cancel
}
/// A file that never opens (`composer.lock`): the column flashes "Too big." instead.
public struct TooBigNotice: Equatable {
public var path: String
public var id = UUID()
}
/// Everything the editor keeps for one path, so a rename or a delete moves or drops it in one step.
/// It outlives the file being open, so switching back finds unsaved edits where they were.
struct FileState: Equatable {
/// The mode the file asked for; `presentation(for:)` resolves it against the file.
var mode: ViewMode?
/// Which git row opened the file; only the Diff overlay follows it.
var side: DiffSide?
/// Unsaved edits; nil means the buffer equals disk.
var buffer: String?
/// The last text read from disk.
var disk: String?
/// Moves whenever the shown text changes from outside the text view; unique across paths.
var revision = 0
var image: Data?
var imageUnreadable = false
/// The contents turned out binary; the pane shows the "cannot display" placeholder.
var isBinary = false
/// The file vanished from disk while open; its last text is kept as unsaved edits.
var isDeleted = false
}
@Observable
@MainActor
public final class EditorStore {
/// The one open file; nil shows the empty state.
public internal(set) var activePath: String?
var states: [String: FileState] = [:]
public var cursor: Cursor?
/// The lines of the live text selection in the active pane.
public var selection: LineSelection?
/// The selected text itself, for "Pass on selection".
public private(set) var selectedCode: String?
public private(set) var flash: LineFlash?
public private(set) var tooBig: TooBigNotice?
/// Recently opened files, newest first; persisted per project.
public internal(set) var history: [String] = []
/// The config's `git.defaultDiffMode`, as a view mode.
public var defaultMode = ViewMode.actual
public var editorConfig = HelderConfig.Editor()
/// The mode to return to when the Diff overlay closes.
public private(set) var modeBeforeDiff = ViewMode.actual
/// The code pane's text view takes keyboard focus whenever this moves.
public private(set) var textFocusRequest = 0
/// ⌘A outside a text field: the code pane selects everything when this moves.
public private(set) var selectAllRequest = 0
/// Declared PHP class names; decides which tokens ⌘-click may follow.
public private(set) var knownSymbols: Set<String> = []
/// Moves whenever `knownSymbols` changes, so views can compare an Int instead of the set.
public private(set) var knownSymbolsVersion = 0
public private(set) var symbolName: String?
/// nil while the lookup for `symbolName` runs.
public private(set) var symbolLookup: SymbolLookup?
// MARK: Hooks WorkspaceModel (or the editor column) wires to the other stores.
@ObservationIgnored public var presentOverlay: ((Overlay) -> Void)?
/// 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.
@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)?
@ObservationIgnored public var symbols: SymbolServicing?
/// The Diff overlay's own menu or pass-on prompt is open; the window's shortcuts then stand back.
@ObservationIgnored public var diffOverlayBusy = false
@ObservationIgnored public let root: String
@ObservationIgnored let files: FileServicing
@ObservationIgnored private let gitState: @MainActor () -> GitWorkingState
@ObservationIgnored let session: SessionStoring
@ObservationIgnored let recentFiles: RecentFilesStoring
@ObservationIgnored private var pending: [UUID: Task<Void, Never>] = [:]
@ObservationIgnored var autoSaves: [String: (id: UUID, task: Task<Void, Never>)] = [:]
/// Bumped per path by every read and save, so an older read that lands late is dropped.
@ObservationIgnored var loadGeneration: [String: Int] = [:]
@ObservationIgnored private var revisionCounter = 0
@ObservationIgnored private var flashTask: Task<Void, Never>?
/// Nothing is written back until the saved state was read, so an early write never clobbers it.
@ObservationIgnored var hasRestored = false
@ObservationIgnored var sessionEnabled = false
public convenience init(root: String, files: FileServicing, sourceControl: SourceControlStore,
session: SessionStoring, recentFiles: RecentFilesStoring) {
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.
public init(root: String, files: FileServicing, gitState: @escaping @MainActor () -> GitWorkingState,
session: SessionStoring, recentFiles: RecentFilesStoring) {
self.root = root
self.files = files
self.gitState = gitState
self.session = session
self.recentFiles = recentFiles
}
// MARK: Reading
public var modes: [String: ViewMode] { states.compactMapValues(\.mode) }
public var sides: [String: DiffSide] { states.compactMapValues(\.side) }
public var buffers: [String: String] { states.compactMapValues(\.buffer) }
public var diskText: [String: String] { states.compactMapValues(\.disk) }
public var images: [String: Data] { states.compactMapValues(\.image) }
public var unreadableImages: Set<String> { Set(states.filter(\.value.imageUnreadable).keys) }
public var binaryPaths: Set<String> { Set(states.filter(\.value.isBinary).keys) }
public func side(for path: String) -> DiffSide? { states[path]?.side }
public func revision(for path: String) -> Int { states[path]?.revision ?? 0 }
public func image(for path: String) -> Data? { states[path]?.image }
public func isUnreadableImage(_ path: String) -> Bool { states[path]?.imageUnreadable ?? false }
public func isDeleted(_ path: String) -> Bool { states[path]?.isDeleted ?? false }
/// HEAD vs disk for a changed file; nil for an unchanged one.
public func diff(for path: String) -> Diff? {
gitState().fileDiffs[path]
}
/// The pair the Diff overlay compares: the git row that opened the file, else HEAD vs disk.
public func overlayDiff(for path: String, side: DiffSide?) -> Diff? {
let state = gitState()
if let side, let row = state.rowDiffs[Change.rowID(path: path, staged: side == .staged)] { return row }
return state.fileDiffs[path]
}
/// True when a file is both staged and edited again, so the Diff must say which half it shows.
public func hasBothSides(_ path: String) -> Bool {
let rows = gitState().rowDiffs
return rows[Change.rowID(path: path, staged: true)] != nil && rows[Change.rowID(path: path, staged: false)] != nil
}
public func presentation(for path: String) -> EditorPresentation {
EditorPresentation(path: path, requested: states[path]?.mode, diff: diff(for: path), defaultMode: defaultMode,
isBinary: states[path]?.isBinary ?? false)
}
/// The effective mode of a file.
public func mode(for path: String) -> ViewMode {
presentation(for: path).mode
}
/// What the editable view shows: the unsaved buffer, else the disk text.
public func text(for path: String) -> String {
states[path]?.buffer ?? states[path]?.disk ?? ""
}
/// A vanished file is dirty while it holds any text, so closing it asks and saving it is a choice.
public func isDirty(_ path: String) -> Bool {
guard let state = states[path], let buffer = state.buffer else { return false }
return state.isDeleted || buffer != (state.disk ?? "")
}
public func isLoaded(_ path: String) -> Bool {
states[path]?.disk != nil
}
/// Every path holding unsaved edits, the open file first.
public var dirtyPaths: [String] {
let others = states.keys.filter { $0 != activePath && isDirty($0) }.sorted()
return (activePath.map { isDirty($0) ? [$0] : [] } ?? []) + others
}
// MARK: Status bar and breadcrumb
public var activeMode: ViewMode? { activePath.map(mode(for:)) }
public var activeLanguage: String? {
activePath.map { EditorFileKind.of($0) == .image ? "Image" : FileType.languageLabel(for: $0) }
}
public var indentationLabel: String { "Spaces: \(editorConfig.tabSize)" }
public var cursorLine: Int { cursorOnActive?.line ?? 1 }
public var cursorColumn: Int { cursorOnActive?.column ?? 1 }
public var activeIsDirty: Bool { activePath.map(isDirty) ?? false }
private var cursorOnActive: Cursor? {
guard let cursor, cursor.path == activePath else { return nil }
return cursor
}
// MARK: Editing
/// Records an edit to the active buffer; with `editor.autoSave` it is written 600ms after the last keystroke.
public func edit(_ text: String) {
guard let path = activePath else { return }
var state = states[path] ?? FileState()
state.buffer = (text == state.disk && !state.isDeleted) ? nil : text
states[path] = state
if editorConfig.autoSave && !state.isDeleted { scheduleAutoSave(path) }
}
public func updateCursor(line: Int, column: Int) {
guard let path = activePath else { return }
let next = Cursor(path: path, line: line, column: column)
if cursor != next { cursor = next }
}
/// The live selection of the active pane; nil lines or empty code clears it.
public func updateSelection(lines: ClosedRange<Int>?, code: String?) {
guard let path = activePath, let lines, let code, !code.isEmpty else {
if selection != nil { selection = nil }
selectedCode = nil
return
}
let next = LineSelection(path: path, start: lines.lowerBound, end: lines.upperBound, anchor: lines.lowerBound)
if selection != next { selection = next }
selectedCode = code
}
/// Hands keyboard focus to the code pane's text view.
public func requestTextFocus() {
textFocusRequest += 1
}
/// Selects the whole open file in its pane; false when no file is open.
@discardableResult
public func selectAll() -> Bool {
guard activePath != nil else { return false }
selectAllRequest += 1
return true
}
// MARK: Modes
public func setMode(_ mode: ViewMode, for path: String) {
let current = self.mode(for: path)
if mode == .diff {
guard diff(for: path) != nil else { return }
if current != .diff { modeBeforeDiff = current }
states[path, default: FileState()].mode = .diff
presentOverlay?(.diff(DiffOverlayRequest(path: path, side: states[path]?.side)))
} else {
states[path, default: FileState()].mode = mode
if current == .diff {
dismissDiffOverlay?()
requestTextFocus()
}
}
persistSoon()
}
/// ⌘M and the bar's Preview button: Markdown flips between its code view and the rendered preview.
/// Any other file has nothing to flip.
public func togglePreview() {
guard let path = activePath, presentation(for: path).barButtons.contains(.preview) else { return }
setMode(mode(for: path) == .preview ? .code : .preview, for: path)
track { await $0.load(path, discardEdits: false) }
}
/// A click on a marked line in Actual: the Diff opens on HEAD vs disk, centred on that line.
public func openDiff(atLine line: Int) {
guard let path = activePath, diff(for: path) != nil else { return }
let current = mode(for: path)
if current != .diff { modeBeforeDiff = current }
states[path, default: FileState()].mode = .diff
presentOverlay?(.diff(DiffOverlayRequest(path: path, side: nil, focusLine: line)))
}
/// The Diff overlay went away (Esc, Collapse, or another overlay took its place): back to the mode it covered.
public func closeDiff() {
guard let path = activePath, states[path]?.mode == .diff else { return }
states[path]?.mode = modeBeforeDiff == .diff ? .actual : modeBeforeDiff
requestTextFocus()
persistSoon()
}
/// The Collapse button: restore the mode and close the overlay.
public func collapseDiff() {
closeDiff()
dismissDiffOverlay?()
}
// MARK: References and pass-on
/// The reference for the current selection, else the caret line.
public func currentReference() -> AgentReference? {
guard let path = activePath else { return nil }
if let selection, selection.path == path { return selection.reference }
return AgentReference(path: path, startLine: cursorOnActive?.line ?? 1)
}
/// ⌘→: the pass-on prompt for the selected code; nil without a selection, so the key keeps its native meaning.
public func passOnSelectionRequest(anchor: CGPoint) -> PassOnRequest? {
guard let path = activePath, let selection, selection.path == path, let code = selectedCode, !code.isEmpty else { return nil }
return PassOnRequest(reference: selection.reference.description, code: code, anchor: anchor)
}
/// The right-click menu for a line or selection in the code: exactly Pass on and Copy reference.
public func contextMenuRequest(reference: AgentReference, code: String?, anchor: CGPoint) -> ContextMenuRequest {
let target = ContextTarget.editor(reference: reference, code: code)
return ContextMenuRequest(target: target, header: ContextActions.header(for: target, projectName: PathUtils.basename(root)),
entries: ContextActions.entries(for: target), anchor: anchor)
}
// MARK: Symbols
public func loadKnownSymbols() async {
guard let symbols else { return }
let names = await symbols.names()
guard names != knownSymbols else { return }
knownSymbols = names
knownSymbolsVersion += 1
}
/// ⌘-click on a class name: the popup opens at once with "Searching…", the lookup fills it.
public func lookupSymbol(_ name: String) {
symbolName = name
symbolLookup = nil
presentOverlay?(.symbol(name: name))
guard let symbols else { return }
track { store in
let result = await symbols.lookup(name)
if store.symbolName == name { store.symbolLookup = result }
}
}
// MARK: The open file
/// Opens a file in place of the current one: history, mode, side, a read from disk, and a line jump with a flash.
/// A changed file lands in Actual unless `showDiff`; `defaultMode` only covers a file without a stored mode.
public func open(_ path: String, _ options: OpenOptions = OpenOptions()) {
if FileType.tooBigNames.contains(PathUtils.basename(path)) {
tooBig = TooBigNotice(path: path)
return
}
history = RecentLists.pushing(path, onto: history)
activePath = path
selection = nil
selectedCode = nil
let changed = diff(for: path) != nil && EditorFileKind.of(path) == .text
var state = states[path] ?? FileState()
state.mode = changed ? .actual : .code
state.side = options.side
states[path] = state
if let line = options.line {
cursor = Cursor(path: path, line: line, column: 1)
flashLine(path: path, line: line)
}
if options.showDiff && changed { setMode(.diff, for: path) }
track { await $0.load(path, discardEdits: false) }
persistSoon()
}
/// Drops a file's unsaved edits without asking and, when it is the open file, shows the empty state.
/// `requestCloseActive` asks first.
public func close(_ path: String) {
cancelAutoSave(path)
if states[path]?.buffer != nil {
states[path]?.buffer = nil
bumpRevision(path)
}
if states[path]?.isDeleted == true { states[path] = nil }
if cursor?.path == path { cursor = nil }
if selection?.path == path { selection = nil; selectedCode = nil }
if activePath == path { activePath = nil }
persistSoon()
}
/// ⌘W and the context menu's Close: a dirty file asks save, discard or cancel. Returns true when the file closed.
@discardableResult
public func requestCloseActive() async -> Bool {
guard let path = activePath else { return false }
if isDirty(path) {
switch confirmUnsavedClose?(path) ?? .cancel {
case .cancel:
return false
case .save:
do { try await save(path: path) } catch { return false }
case .discard:
break
}
}
close(path)
return true
}
/// Carries every path-keyed piece of state over a rename; a read still in flight for the old name is dropped.
public func remap(from old: String, to new: String, isDirectory: Bool) {
let move = { (p: String) in PathUtils.remap(p, from: old, to: new, isDirectory: isDirectory) }
activePath = activePath.map(move)
history = history.map(move)
states = Dictionary(states.map { (move($0.key), $0.value) }, uniquingKeysWith: { $1 })
for path in Array(loadGeneration.keys) where move(path) != path { loadGeneration[path] = nil }
for path in Array(autoSaves.keys) where move(path) != path {
cancelAutoSave(path)
scheduleAutoSave(move(path))
}
if let c = cursor { cursor = Cursor(path: move(c.path), line: c.line, column: c.column) }
if let s = selection { selection = LineSelection(path: move(s.path), start: s.start, end: s.end, anchor: s.anchor) }
persistSoon()
}
/// Drops every piece of state for a deleted file or folder.
public func forget(_ path: String, isDirectory: Bool) {
let gone = { (p: String) in PathUtils.isInside(p, path, isDirectory: isDirectory) }
if activePath.map(gone) == true { activePath = nil }
history.removeAll(where: gone)
for key in states.keys where gone(key) { states[key] = nil }
for key in loadGeneration.keys where gone(key) { loadGeneration[key] = nil }
for key in autoSaves.keys where gone(key) { cancelAutoSave(key) }
if let c = cursor, gone(c.path) { cursor = nil }
if let s = selection, gone(s.path) { selection = nil; selectedCode = nil }
persistSoon()
}
/// Waits for every read and lookup this store started; tests use it to settle.
public func settle() async {
while let task = pending.values.first ?? autoSaves.values.first?.task {
await task.value
}
}
func bumpRevision(_ path: String) {
revisionCounter += 1
states[path, default: FileState()].revision = revisionCounter
}
private func flashLine(path: String, line: Int) {
flash = LineFlash(path: path, line: line)
let id = flash?.id
flashTask?.cancel()
flashTask = Task { [weak self] in
try? await Task.sleep(for: .seconds(1))
guard let self, !Task.isCancelled, self.flash?.id == id else { return }
self.flash = nil
}
}
func track(_ work: @escaping @MainActor (EditorStore) async -> Void) {
let id = UUID()
pending[id] = Task { [weak self] in
guard let self else { return }
await work(self)
self.pending[id] = nil
}
}
}
+230
View File
@@ -0,0 +1,230 @@
import Foundation
import HelderCore
import HelderServices
import Observation
@Observable
@MainActor
public final class ExplorerStore {
public private(set) var tree: FileNode?
/// Expanded folders; a newly opened project starts fully collapsed.
public private(set) var expanded: Set<String> = []
/// The keyboard cursor, by path.
public var selectedPath: String?
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
@ObservationIgnored private let files: FileServicing
@ObservationIgnored private let system: SystemActing
@ObservationIgnored private var reloadGeneration = 0
public init(files: FileServicing, system: SystemActing) {
self.files = files
self.system = system
}
public func rows(showHidden: Bool) -> [TreeRow] {
tree.map { FileTree.visibleRows($0, expanded: expanded, showHidden: showHidden) } ?? []
}
/// Expands or collapses a folder and re-reads its children, so files the agent added show up.
@discardableResult
public func toggle(_ directory: String) -> Task<Void, Never> {
if expanded.contains(directory) { expanded.remove(directory) } else { expanded.insert(directory) }
return Task { await refreshChildren(of: directory) }
}
/// Expands every ancestor of a path so its row is visible.
public func reveal(_ path: String) {
expanded.formUnion(PathUtils.ancestors(path))
}
/// Reveals a path and puts the cursor on it: what opening a file does to the tree.
public func select(_ path: String) {
reveal(path)
selectedPath = path
}
public func moveSelection(by step: Int, showHidden: Bool) {
let list = rows(showHidden: showHidden)
guard !list.isEmpty else { return }
guard let index = list.firstIndex(where: { $0.path == selectedPath }) else {
selectedPath = list[0].path
return
}
selectedPath = list[min(max(index + step, 0), list.count - 1)].path
}
/// Carries expanded folders and the cursor over a rename.
public func remap(from old: String, to new: String, isDirectory: Bool) {
expanded = Set(expanded.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) })
selectedPath = selectedPath.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) }
}
// MARK: Loading
/// Reloads the whole tree, keeping the expansion.
public func reload() async {
reloadGeneration += 1
let generation = reloadGeneration
let fresh = await files.tree()
guard generation == reloadGeneration else { return }
tree = fresh
}
/// Loads once for a column that appears before `WorkspaceModel` loaded the tree.
public func loadIfNeeded() async {
if tree == nil { await reload() }
}
public func refreshChildren(of directory: String) async {
let generation = reloadGeneration
let children = await files.children(of: directory)
// A full reload that started meanwhile already carries these children.
guard generation == reloadGeneration, let tree else { return }
self.tree = FileTree.replacingChildren(of: directory, with: children, in: tree)
}
// MARK: Disk changes
/// Creates an empty file and returns its path; expands the parent folder.
public func createFile(in directory: String, name: String) async throws -> String {
let path = try newEntryPath(in: directory, name: name)
try await files.createFile(path)
reveal(path)
await reload()
return path
}
/// Creates a folder and returns its path; expands the parent and the new folder.
public func createFolder(in directory: String, name: String) async throws -> String {
let path = try newEntryPath(in: directory, name: name)
try await files.createDirectory(path)
reveal(path)
expanded.insert(path)
await reload()
return path
}
/// Renames on disk and returns the new path; callers must also remap the editor.
public func rename(_ path: String, to name: String, isDirectory: Bool) async throws -> String {
guard let clean = PathUtils.validatedName(name) else { throw FileServiceError.invalidName(name) }
let next = try await files.rename(path, to: clean)
guard next != path else { return path }
remap(from: path, to: next, isDirectory: isDirectory)
await reload()
return next
}
public func delete(_ path: String) async throws {
let isDirectory = tree.flatMap { FileTree.find(path, in: $0) }?.isDirectory ?? false
try await files.delete(path)
expanded = expanded.filter { !PathUtils.isInside($0, path, isDirectory: true) }
if let selected = selectedPath, PathUtils.isInside(selected, path, isDirectory: isDirectory) { selectedPath = nil }
await reload()
}
// MARK: Prompt and menu flows
/// Finishes the name prompt: creates or renames, toasts, and returns the resulting path (nil on failure or no-op).
public func submitName(_ name: String, for purpose: NamePromptRequest.Purpose) async -> String? {
do {
switch purpose {
case let .newFile(directory):
let path = try await createFile(in: directory, name: name)
notify("Created file", path)
return path
case let .newFolder(directory):
let path = try await createFolder(in: directory, name: name)
notify("Created folder", path)
return path
case let .rename(path, isDirectory):
let next = try await rename(path, to: name, isDirectory: isDirectory)
guard next != path else { return nil }
notify(isDirectory ? "Renamed folder" : "Renamed file", next)
return next
}
} catch {
Log.error("fs", "\(purpose) failed: \(error)")
switch purpose {
case .rename: notify("Rename failed", name)
case let .newFile(directory), let .newFolder(directory):
notify("Create failed", PathUtils.newEntryPath(inDirectory: directory, name: name.trimmingCharacters(in: .whitespaces)))
}
return nil
}
}
/// The prompt's preview line: the path a submit would create or rename to, or nil while the name is unusable.
nonisolated public static func promptTarget(for purpose: NamePromptRequest.Purpose, name: String) -> String? {
let trimmed = name.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { return nil }
switch purpose {
case let .newFile(directory):
return PathUtils.newEntryPath(inDirectory: directory, name: trimmed)
case let .newFolder(directory):
return PathUtils.newEntryPath(inDirectory: directory, name: trimmed) + "/"
case let .rename(path, isDirectory):
guard let clean = PathUtils.validatedName(trimmed), clean != PathUtils.basename(path) else { return nil }
return PathUtils.reference(PathUtils.join(PathUtils.dirname(path), clean), isDirectory: isDirectory)
}
}
/// Deletes after the confirm dialog, toasts, and returns whether it worked; callers must also drop editor state.
public func deleteEntry(_ path: String, isDirectory: Bool) async -> Bool {
do {
try await delete(path)
} catch {
Log.error("fs", "delete failed: \(error)")
notify("Delete failed", path)
return false
}
notify(isDirectory ? "Deleted folder" : "Deleted file", path)
return true
}
/// Delete always asks first; nothing else in the Explorer menu does.
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
guard case let .delete(path, isDirectory) = action else { return nil }
return ConfirmRequest(
title: isDirectory ? "Delete folder?" : "Delete file?",
body: isDirectory ? "\(path)/ and everything inside it will be permanently deleted."
: "\(path) will be permanently deleted.",
confirmLabel: "Delete", action: action)
}
/// Runs the actions that need no prompt: copy, Show in Finder, and an already confirmed delete.
/// False for actions this store does not own (pass on, new, rename, git).
@discardableResult
public func perform(_ action: ContextAction) async -> Bool {
switch action {
case let .copyReference(text):
system.copy(text)
notify("Copied reference", text)
case let .copyFileName(name):
system.copy(name)
notify("Copied", name)
case let .revealInFinder(path):
guard let url = files.absoluteURL(for: path) else { return true }
system.revealInFinder(url)
case let .delete(path, isDirectory):
_ = await deleteEntry(path, isDirectory: isDirectory)
default:
return false
}
return true
}
/// The menu target for a visible row.
public static func target(for row: TreeRow) -> ContextTarget {
row.kind == .directory ? .directory(path: row.path) : .file(path: row.path)
}
private func newEntryPath(in directory: String, name: String) throws -> String {
let trimmed = name.trimmingCharacters(in: .whitespaces)
let path = PathUtils.newEntryPath(inDirectory: directory, name: trimmed)
guard !trimmed.isEmpty, path != directory else { throw FileServiceError.invalidName(name) }
return path
}
}
+263
View File
@@ -0,0 +1,263 @@
import Foundation
import HelderCore
import HelderServices
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
}
/// 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 init(sourceControlWidth: Double, explorerWidth: Double, agentWidth: Double, fluid: Bool, gitVisible: Bool) {
self.sourceControlWidth = sourceControlWidth
self.explorerWidth = explorerWidth
self.agentWidth = agentWidth
self.fluid = fluid
self.gitVisible = gitVisible
}
public static func key(root: String) -> String { "helder.layout:" + root }
}
/// Where column layouts are kept, one per project root.
public protocol LayoutPersisting: Sendable {
func load(root: String) -> ColumnLayoutSnapshot?
func save(_ snapshot: ColumnLayoutSnapshot, root: String)
/// View → Zoom, shared by every project.
func loadZoom() -> Double
func saveZoom(_ level: Double)
}
extension LayoutPersisting {
public func loadZoom() -> Double { 0 }
public func saveZoom(_ level: Double) {}
}
/// UserDefaults-backed layouts, next to the session and the agent split.
public struct UserDefaultsLayoutStore: LayoutPersisting, @unchecked Sendable {
private let defaults: UserDefaults
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
public func load(root: String) -> ColumnLayoutSnapshot? {
defaults.data(forKey: ColumnLayoutSnapshot.key(root: root)).flatMap { try? JSONDecoder().decode(ColumnLayoutSnapshot.self, from: $0) }
}
public func save(_ snapshot: ColumnLayoutSnapshot, root: String) {
if let data = try? JSONEncoder().encode(snapshot) { defaults.set(data, forKey: ColumnLayoutSnapshot.key(root: root)) }
}
public func loadZoom() -> Double { defaults.double(forKey: "helder.zoom") }
public func saveZoom(_ level: Double) { defaults.set(level, forKey: "helder.zoom") }
}
@Observable
@MainActor
public final class LayoutStore {
public private(set) var widths = ColumnWidths(sourceControl: 236, 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
/// ⌘G: the Source Control column is shown.
public private(set) var gitVisible = true
/// ⌘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.
public private(set) var showHidden = false
public private(set) var focusZone = FocusZone.neutral
public private(set) var activePanel: Panel?
/// macOS hides the traffic lights in full screen, so the title bar reclaims their inset.
public var isFullScreen = false
/// View → Zoom: half steps, each whole step 20% larger, as Chromium zooms.
public private(set) var zoomLevel: Double = 0
@ObservationIgnored private let session: SessionStoring
@ObservationIgnored private let persistence: LayoutPersisting?
@ObservationIgnored private var root: String?
public init(session: SessionStoring, persistence: LayoutPersisting? = nil) {
self.session = session
self.persistence = persistence
agentFraction = session.loadLayout().agentFraction
zoomLevel = Self.clampZoom(persistence?.loadZoom() ?? 0)
}
public static let zoomRange: ClosedRange<Double> = -3...5
/// The factor the code and terminal text sizes are multiplied by.
public var textScale: Double { pow(1.2, zoomLevel) }
public func zoom(_ step: ZoomStep) {
let next: Double = switch step {
case .reset: 0
case .bigger: zoomLevel + 0.5
case .smaller: zoomLevel - 0.5
}
let clamped = Self.clampZoom(next)
guard clamped != zoomLevel else { return }
zoomLevel = clamped
persistence?.saveZoom(clamped)
}
private static func clampZoom(_ level: Double) -> Double {
min(max(level, zoomRange.lowerBound), zoomRange.upperBound)
}
/// Loads the project's saved columns; a project without one starts fluid with every column shown.
public func restore(root: String) {
self.root = root
activePanel = nil
focusZone = .neutral
let saved = persistence?.load(root: root)
gitVisible = saved?.gitVisible ?? true
fluid = saved?.fluid ?? true
if let saved, !saved.fluid {
widths = ColumnWidths(sourceControl: clamp(saved.sourceControlWidth, ColumnLayout.sourceControlRange),
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, gitVisible: gitVisible)
}
public func toggleGit() {
gitVisible.toggle()
if !gitVisible && activePanel == .sourceControl { activePanel = nil }
refit()
save()
}
public func toggleFluid() {
fluid.toggle()
refit()
save()
}
public func toggleHidden() {
showHidden.toggle()
}
public func windowResized(width: Double) {
windowWidth = width
refit()
}
/// Focus moves the fluid widths below 1600pt: the editor or the terminals get more room.
public func focus(_ panel: Panel) {
if panel == .sourceControl && !gitVisible { return }
activePanel = panel
switch panel {
case .editor: focusZone = .editor
case .terminal: focusZone = .terminal
default: break
}
refit()
}
/// Opening a file widens the editor without moving the keyboard cursor out of the list it came from.
public func setFocusZone(_ zone: FocusZone) {
focusZone = zone
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)
}
/// The agent splitter sits on the column's left edge, so dragging right shrinks it.
public func dragAgent(by delta: Double) {
fluid = false
let maxWidth = ColumnLayout.maxAgentWidth(windowWidth: windowWidth, widths: widths, sourceControlVisible: gitVisible)
widths.agent = clamp(widths.agent - delta, ColumnLayout.minEditorWidth...maxWidth)
}
/// Call when a splitter drag ends: the locked widths are saved for this project.
public func endDrag() {
save()
}
public func setAgentFraction(_ fraction: Double) {
agentFraction = LayoutState.clampAgentFraction(fraction)
session.saveLayout(LayoutState(agentFraction: agentFraction))
}
/// Moves the agent/shell divider by `delta` points in a right column `height` points tall.
public func dragAgentSplit(by delta: Double, height: Double) {
guard height > 0 else { return }
setAgentFraction((agentFraction * height + delta) / height)
}
// MARK: Column geometry
/// The visible columns, left to right.
public var columns: [Panel] {
gitVisible ? Panel.allCases : [.explorer, .editor, .terminal]
}
/// The horizontal extent of a column in window coordinates; nil for a hidden column.
public func span(of panel: Panel) -> ClosedRange<Double>? {
let splitter = ColumnLayout.splitterWidth
let sc = gitVisible ? widths.sourceControl + splitter : 0
let editorStart = sc + widths.explorer + splitter
let agentStart = max(editorStart, windowWidth - widths.agent)
switch panel {
case .sourceControl: return gitVisible ? 0...widths.sourceControl : nil
case .explorer: return sc...(sc + widths.explorer)
case .editor: return editorStart...max(editorStart, agentStart - splitter)
case .terminal: return agentStart...max(agentStart, windowWidth)
}
}
/// The column under a window x; nil within `splitterMargin` of a divider, so a splitter drag never refocuses.
public func panel(atX x: Double, splitterMargin: Double = 0) -> Panel? {
columns.first { panel in
guard let span = span(of: panel) else { return false }
return x >= span.lowerBound + splitterMargin && x <= span.upperBound - splitterMargin
}
}
/// The column `step` places left (−1) or right (+1) of `panel`, clamped at the ends. No focus counts as the editor.
public func neighbour(of panel: Panel?, step: Int) -> Panel {
let list = columns
let index = list.firstIndex(of: panel ?? .editor) ?? list.firstIndex(of: .editor) ?? 0
return list[min(max(index + step, 0), list.count - 1)]
}
private func refit() {
var next = fluid ? ColumnLayout.fluid(windowWidth: windowWidth, focus: focusZone) : widths
next = ColumnLayout.fitted(next, windowWidth: windowWidth, sourceControlVisible: gitVisible)
if next != widths { widths = next }
}
private func save() {
guard let root else { return }
persistence?.save(snapshot, root: root)
}
private func clamp(_ value: Double, _ range: ClosedRange<Double>) -> Double {
min(max(value, range.lowerBound), range.upperBound)
}
}
+66
View File
@@ -0,0 +1,66 @@
import Foundation
import HelderServices
import Observation
@Observable
@MainActor
public final class NoteStore {
public static let fileName = NotesService.fileName
public var text = ""
/// What is on disk, so a save without edits does not touch the file and wake the watcher.
public private(set) var savedText = ""
/// Raises a toast; the model wires it to `ToastStore`.
@ObservationIgnored public var notify: ((String, String?) -> Void)?
@ObservationIgnored private let notes: NotesServicing
public init(notes: NotesServicing) {
self.notes = notes
}
public var isDirty: Bool { text != savedText }
public var characterCount: Int { text.count }
public func load() async {
let loaded = await notes.read()
text = loaded
savedText = loaded
}
/// Picks up an outside edit of the note file; unsaved typing always wins.
public func reloadIfClean() async {
guard !isDirty else { return }
let loaded = await notes.read()
guard !isDirty, loaded != savedText else { return }
text = loaded
savedText = loaded
}
/// Saves when the text changed; called on window blur, on close and when the overlay closes.
/// Returns false when the write failed.
@discardableResult
public func save() async -> Bool {
guard isDirty else { return true }
let snapshot = text
// Marked saved before the write, so a second blur during the write does not write again.
let previous = savedText
savedText = snapshot
do {
try await notes.write(snapshot)
return true
} catch {
if savedText == snapshot { savedText = previous }
Log.error("notes", "save failed: \(error.localizedDescription)")
notify?("Save failed", Self.fileName)
return false
}
}
/// The trimmed note for ⌘P, or nil when it is empty.
public var passableText: String? {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
+134
View File
@@ -0,0 +1,134 @@
import CoreGraphics
import Foundation
import HelderCore
import Observation
/// The full-screen side-by-side diff: which file, which git half, and an optional line to centre.
public struct DiffOverlayRequest: Equatable {
public var path: String
/// nil compares HEAD with disk; a click in Actual always does that.
public var side: DiffSide?
public var focusLine: Int?
public init(path: String, side: DiffSide?, focusLine: Int? = nil) {
self.path = path
self.side = side
self.focusLine = focusLine
}
}
/// The pass-on prompt: a note field over the reference it will insert.
public struct PassOnRequest: Equatable {
public var reference: String
/// Selected code, sent as a fenced block under the reference.
public var code: String?
/// Window coordinates the prompt anchors to.
public var anchor: CGPoint
public init(reference: String, code: String? = nil, anchor: CGPoint) {
self.reference = reference
self.code = code
self.anchor = anchor
}
}
public struct ContextMenuRequest: Equatable {
public var target: ContextTarget
public var header: String
public var entries: [ContextMenuEntry]
/// Row menus anchor to the column's right edge so they never cover the rows.
public var anchor: CGPoint
public init(target: ContextTarget, header: String, entries: [ContextMenuEntry], anchor: CGPoint) {
self.target = target
self.header = header
self.entries = entries
self.anchor = anchor
}
}
/// The new-file, new-folder and rename prompt.
public struct NamePromptRequest: Equatable {
public enum Purpose: Equatable {
case newFile(inDirectory: String)
case newFolder(inDirectory: String)
case rename(path: String, isDirectory: Bool)
}
public var purpose: Purpose
public var initialName: String
public var anchor: CGPoint
public init(purpose: Purpose, initialName: String = "", anchor: CGPoint) {
self.purpose = purpose
self.initialName = initialName
self.anchor = anchor
}
}
/// A destructive action waiting for a yes.
public struct ConfirmRequest: Equatable {
public var title: String
public var body: String?
public var confirmLabel: String
public var action: ContextAction
public init(title: String, body: String? = nil, confirmLabel: String, action: ContextAction) {
self.title = title
self.body = body
self.confirmLabel = confirmLabel
self.action = action
}
}
/// Everything that floats over the workspace. Exactly one at a time: presenting one replaces the other.
public enum Overlay: Equatable {
case none
/// ⌘F; the seed is the editor selection's first line.
case search(seed: String)
/// `?`: the keyboard reference.
case shortcuts
/// ⌘N: the project note.
case note
case diff(DiffOverlayRequest)
/// ⇧⌘O: the other recent projects. The bare window's launcher is not an overlay.
case launcher
/// ⌘↑/⌘↓ from the editor: the recent-files navigator.
case recentFiles(initialSelection: Int)
case passOn(PassOnRequest)
/// ⌘-click on a PHP class name.
case symbol(name: String)
case contextMenu(ContextMenuRequest)
case namePrompt(NamePromptRequest)
case confirm(ConfirmRequest)
}
@Observable
@MainActor
public final class OverlayStore {
public private(set) var current = Overlay.none
/// Called with the old and new overlay on every change, however it happened, so closing
/// behaviour (the note saves, the Diff restores the mode) runs even when another overlay takes over.
@ObservationIgnored public var onChange: ((_ old: Overlay, _ new: Overlay) -> Void)?
public init() {}
public var isPresented: Bool { current != .none }
/// Shows an overlay, closing whatever was open.
public func present(_ overlay: Overlay) {
set(overlay)
}
/// Esc: closes the one open overlay.
public func dismiss() {
set(.none)
}
private func set(_ next: Overlay) {
let old = current
guard old != next else { return }
current = next
onChange?(old, next)
}
}
@@ -0,0 +1,243 @@
import Foundation
import HelderCore
import HelderServices
import Observation
@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 hasLoaded = false
/// The commit box 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.
public var config = HelderConfig.Git() {
didSet {
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
}
}
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
@ObservationIgnored private let git: GitServicing
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
@ObservationIgnored private var refreshGeneration = 0
@ObservationIgnored private var pollTask: Task<Void, Never>?
/// `derive` runs off the main actor, since it diffs every changed file.
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
self.git = git
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)
}
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
public var fileStatuses: [String: GitStatus] {
var out: [String: GitStatus] = [:]
for change in state.changes where out[change.path] == nil || !change.staged {
out[change.path] = change.status
}
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
}
// MARK: Commit box
public var canCommit: Bool {
state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
}
public func setCommitMessage(_ value: String) {
commitMessage = SourceControlText.normalizeCommitMessage(value)
}
// MARK: Git
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
public func refresh() async {
refreshGeneration += 1
let generation = refreshGeneration
let snapshot: GitSnapshot?
do {
snapshot = try await git.load()
} catch {
Log.warn("git", "status failed: \(error)")
return
}
guard generation == refreshGeneration else { return }
let derive = self.derive
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
guard generation == refreshGeneration else { return }
state = derived
hasLoaded = true
}
/// Loads once for a column 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 unstage(_ path: String) async {
await run("Unstage failed", detail: path) { try await self.git.unstage([path]) }
}
/// Stages every path with an unstaged row, including ones that also have a staged row.
public func stageAll() async {
let paths = state.unstagedPaths
guard !paths.isEmpty else { return }
await run("Stage failed", detail: nil) { try await self.git.stage(paths) }
}
public func unstageAll() async {
let paths = stagedPaths
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
}
await refresh()
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
return count
}
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)
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
}
await refresh()
notify("Discarded changes", path)
}
// 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
}
}
/// 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
}
return true
}
// MARK: Polling
/// Re-reads git every `config.refreshInterval` ms as a backstop for a missed watcher event; 0 disables it.
public func startPolling() {
pollTask?.cancel()
pollTask = nil
let interval = config.refreshInterval
guard interval > 0 else { return }
pollTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(interval))
guard !Task.isCancelled, let self else { return }
await self.refresh()
}
}
}
public func stopPolling() {
pollTask?.cancel()
pollTask = nil
}
public var isPolling: Bool { pollTask != nil }
private func run(_ failure: String, detail: String?, _ operation: () async throws -> Void) async {
do {
try await operation()
} catch {
Log.error("git", "\(failure): \(error)")
notify(failure, detail ?? Self.failureDetail(error))
}
await refresh()
}
private static func failureDetail(_ error: Error) -> String {
if case let GitError.commandFailed(_, _, stderr) = error, !stderr.isEmpty { return stderr }
return String(describing: error)
}
}
+181
View File
@@ -0,0 +1,181 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
import Observation
import SwiftTerm
/// A live terminal pane, as the store talks to it. The Terminal views implement this over SwiftTerm.
@MainActor
public protocol TerminalSessionHandle: AnyObject {
/// Writes raw bytes to the child process, as if typed.
func send(_ text: String)
func terminate()
/// Spawns the child process in a pseudo-terminal.
func start(_ launch: TerminalLaunch, argv0: String)
/// The child's pid once spawned; the store reaps it after `terminate()`, which only signals it.
var processID: pid_t? { get }
/// The selected text, if any.
var selectedText: String? { get }
/// Pastes as the terminal would from the clipboard, then takes the keyboard.
func paste(_ text: String)
}
/// Handles that never spawn a process, such as test doubles, need not implement `start` or `processID`.
extension TerminalSessionHandle {
public func start(_ launch: TerminalLaunch, argv0: String) {}
public var processID: pid_t? { nil }
public var selectedText: String? { nil }
public func paste(_ text: String) { send(BracketedPaste.wrap(text, composerHasText: false)) }
}
extension HelderTerminalView {
var processID: pid_t? {
let pid = process?.shellPid ?? 0
return pid > 0 ? pid : nil
}
}
@Observable
@MainActor
public final class TerminalStore {
/// Set by the workspace once the project config is resolved; panes wait for it before spawning.
public var config = HelderConfig.defaults {
didSet { isConfigured = true }
}
public private(set) var isConfigured = false
public private(set) var agentExited = false
public private(set) var shellExited = false
/// True while the agent's composer holds typed or pasted text, so the next paste starts on a new line.
public private(set) var agentComposerHasText = false
@ObservationIgnored public let projectRoot: String?
@ObservationIgnored public private(set) var agent: TerminalSessionHandle?
@ObservationIgnored public private(set) var shell: TerminalSessionHandle?
@ObservationIgnored private let environment: [String: String]
/// A right-click in a pane: its kind, whether it holds a selection, the click in window coordinates.
@ObservationIgnored public var contextMenuRequested: ((TerminalKind, Bool, CGPoint) -> Void)?
public init(projectRoot: String? = nil, environment: [String: String] = ProcessInfo.processInfo.environment) {
self.projectRoot = projectRoot
self.environment = environment
}
/// Executable, arguments, environment and cwd for a pane.
public func launch(for kind: TerminalKind) -> TerminalLaunch {
TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
}
/// argv[0] with a leading dash, which makes the shell a login shell: a Finder-launched app
/// inherits launchd's bare PATH, and only the login profile (Homebrew, nvm) repairs it.
public static func loginArgv0(for executable: String) -> String {
"-" + ((executable as NSString).lastPathComponent)
}
public func session(_ kind: TerminalKind) -> TerminalSessionHandle? {
switch kind {
case .agent: agent
case .shell: shell
}
}
/// Writes observed flags only when they change: panes attach during a SwiftUI update pass.
public func attach(_ handle: TerminalSessionHandle, as kind: TerminalKind) {
switch kind {
case .agent:
agent = handle
if agentExited { agentExited = false }
if agentComposerHasText { agentComposerHasText = false }
case .shell:
shell = handle
if shellExited { shellExited = false }
}
}
/// Attaches a pane and spawns its process.
public func start(_ kind: TerminalKind, on handle: TerminalSessionHandle) {
attach(handle, as: kind)
let launch = launch(for: kind)
Log.info("pty", "spawn \(kind.rawValue): \(launch.executable) \(launch.arguments.joined(separator: " ")) in \(launch.workingDirectory)")
handle.start(launch, argv0: Self.loginArgv0(for: launch.executable))
}
/// Kills whatever runs in the pane and spawns it again with the current config.
public func restart(_ kind: TerminalKind) {
guard let handle = session(kind) else { return }
Self.terminate(handle)
start(kind, on: handle)
}
/// The process ended on its own; an exit we asked for never reports here.
public func processExited(_ kind: TerminalKind, exitCode: Int32? = nil) {
switch kind {
case .agent: agentExited = true
case .shell: shellExited = true
}
if let exitCode, exitCode != 0 {
Log.warn("pty", "\(kind.rawValue) exited unexpectedly with code \(exitCode)")
} else {
Log.info("pty", "\(kind.rawValue) exited")
}
}
public func hasExited(_ kind: TerminalKind) -> Bool {
kind == .agent ? agentExited : shellExited
}
/// Feed every keystroke the user sends to the agent: Enter empties the composer, printable text fills it.
public func agentReceivedInput(_ data: String) {
if data.contains("\r") {
agentComposerHasText = false
} else if let scalar = data.unicodeScalars.first, scalar.value >= 0x20 {
agentComposerHasText = true
}
}
/// Pastes into the agent's composer as a bracketed paste, so the CLI does not submit it.
public func insertIntoAgent(text: String) {
guard let agent else { return }
agent.send(BracketedPaste.wrap(text, composerHasText: agentComposerHasText))
agentComposerHasText = true
}
public func selection(_ kind: TerminalKind) -> String? {
guard let text = session(kind)?.selectedText, !text.isEmpty else { return nil }
return text
}
public func paste(_ text: String, into kind: TerminalKind) {
guard !text.isEmpty, let handle = session(kind) else { return }
handle.paste(text)
if kind == .agent { agentComposerHasText = true }
}
/// A pane's window closed: ends its process once, unless `terminateAll` already did.
public func release(_ handle: TerminalSessionHandle) {
if agent === handle {
agent = nil
} else if shell === handle {
shell = nil
} else {
return
}
Self.terminate(handle)
}
/// Kills both processes; call it before the window closes or the store is replaced.
public func terminateAll() {
agent.map(Self.terminate)
shell.map(Self.terminate)
agent = nil
shell = nil
}
private static func terminate(_ handle: TerminalSessionHandle) {
let pid = handle.processID
handle.terminate()
if let pid {
Task.detached(priority: .utility) { await ChildReaper.reap(pid) }
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import Foundation
import Observation
public struct Toast: Identifiable, Equatable {
public let id = UUID()
public var title: String
/// A path or reference, shown in mono under the title.
public var detail: String?
}
/// Short confirmations in a corner. They may sit over an overlay; they are not one.
@Observable
@MainActor
public final class ToastStore {
public static let lifetime: Duration = .milliseconds(2300)
public private(set) var toasts: [Toast] = []
public init() {}
public func show(_ title: String, detail: String? = nil) {
let toast = Toast(title: title, detail: detail)
toasts.append(toast)
Task { [weak self] in
try? await Task.sleep(for: Self.lifetime)
self?.toasts.removeAll { $0.id == toast.id }
}
}
}
@@ -0,0 +1,99 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
extension WorkspaceModel {
// MARK: Overlays
func overlayChanged(from old: Overlay, to new: Overlay) {
switch old {
case .note:
if let note { track { await note.save() } }
case .diff:
editor?.closeDiff()
default:
break
}
}
/// The recent projects other than this one, for ⇧⌘O.
public var otherRecentProjects: [RecentProject] {
recentProjects.filter { $0.path != root?.path }
}
/// ⇧⌘O: the recent-project list; the recents are re-read, since another window may have added one.
func showRecentProjects() {
overlay.present(.launcher)
track {
self.recentProjects = await self.app.recentProjects.list()
}
}
func activateLauncher() {
switch launcher.selectedChoice {
case .chooseFolder: perform(.openFolder)
case let .open(path): perform(.openRecentProject(path))
case nil: break
}
}
// 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
}
}
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
}
}
// MARK: Editor and the note
func passSelection(_ info: TextSelectionInfo?) {
guard let editor, let path = editor.activePath else { return }
if let info {
let reference = AgentReference(path: path, lines: info.startLine...max(info.startLine, info.endLine))
overlay.present(.passOn(PassOnRequest(reference: reference.description, code: info.text, anchor: defaultAnchor)))
} else if let request = editor.passOnSelectionRequest(anchor: defaultAnchor) {
overlay.present(.passOn(request))
}
}
/// ⌘P with the note open: the whole note goes to the agent, and the note closes so the text is seen landing.
func passNote() {
guard let note, let text = note.passableText else { return }
terminal.insertIntoAgent(text: text)
overlay.dismiss()
toasts.show("Note passed to agent", detail: NoteStore.fileName)
}
func editorSelectionFirstLine() -> String {
guard let editor, let path = editor.activePath, let selection = editor.selection, selection.path == path else { return "" }
let lines = editor.text(for: path).split(separator: "\n", omittingEmptySubsequences: false)
guard selection.start >= 1, selection.start <= lines.count else { return "" }
return lines[selection.start - 1].trimmingCharacters(in: .whitespaces)
}
}
@@ -0,0 +1,143 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
extension WorkspaceModel {
/// Runs a context-menu action; one the config or the Explorer guards asks first through the confirm overlay.
public func perform(_ action: ContextAction) {
let anchor = takeMenuAnchor()
if let request = sourceControl?.confirmation(for: action) ?? explorer?.confirmation(for: action) {
overlay.present(.confirm(request))
} else {
execute(action, anchor: anchor)
}
}
func showContextMenu(_ target: ContextTarget, anchor: CGPoint) {
overlay.present(.contextMenu(ContextMenuRequest(
target: target,
header: ContextActions.header(for: target, projectName: name),
entries: ContextActions.entries(for: target),
anchor: anchor
)))
}
/// Closes an open context menu and returns where it stood, so a prompt it opens appears in the same place.
private func takeMenuAnchor() -> CGPoint {
guard case let .contextMenu(menu) = overlay.current else { return defaultAnchor }
overlay.dismiss()
return menu.anchor
}
var defaultAnchor: CGPoint {
CGPoint(x: (layout.span(of: .editor)?.lowerBound ?? 0) + 60, y: 150)
}
func confirmPending() {
guard case let .confirm(request) = overlay.current else { return }
overlay.dismiss()
execute(request.action, anchor: defaultAnchor)
}
// MARK: Row menus
/// ⌘→ in Source Control or 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)
}
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
guard let explorer else { return nil }
let rows = explorer.rows(showHidden: layout.showHidden)
guard let index = rows.firstIndex(where: { $0.path == explorer.selectedPath }) else { return nil }
return (rows[index], index)
}
/// Row menus open beside the column, never over its rows, level with the row; a row that never
/// reported its frame is placed by its index, which is off once the list scrolls.
func rowMenuAnchor(_ panel: Panel, frame: CGRect?, estimate index: Int, rowHeight: CGFloat) -> CGPoint {
let x = layout.span(of: panel)?.upperBound ?? 220
let y = frame.map { $0.minY + 4 } ?? Metrics.titleBar + Metrics.panelHeader + CGFloat(index) * rowHeight + 4
return CGPoint(x: x, y: y)
}
// MARK: Running actions
/// Runs an action that needs no (more) confirmation. The stores are read before any await,
/// so an action still running after a project switch never lands in the new project.
func execute(_ action: ContextAction, anchor: CGPoint) {
let sourceControl = sourceControl, explorer = explorer, editor = editor
switch action {
case let .passOnReference(reference, code):
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
case let .passOnFileName(name):
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
case let .newFile(directory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFile(inDirectory: directory), anchor: anchor)))
case let .newFolder(directory):
overlay.present(.namePrompt(NamePromptRequest(purpose: .newFolder(inDirectory: directory), anchor: anchor)))
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 .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):
track {
await sourceControl?.discard(path)
await editor?.reloadFromDisk(path)
}
case let .delete(path, isDirectory):
track {
guard await explorer?.deleteEntry(path, isDirectory: isDirectory) == true else { return }
editor?.forget(path, isDirectory: isDirectory)
await sourceControl?.refresh()
}
default:
track {
if await sourceControl?.perform(action) == true { return }
await explorer?.perform(action)
}
}
}
func submitName(_ name: String) {
guard case let .namePrompt(request) = overlay.current else { return }
overlay.dismiss()
guard let explorer else { return }
let sourceControl = sourceControl, editor = editor
track {
guard let path = await explorer.submitName(name, for: request.purpose) else { return }
switch request.purpose {
case .newFile: if self.editor === editor { self.open(path) }
case .newFolder: break
case let .rename(old, isDirectory): editor?.remap(from: old, to: path, isDirectory: isDirectory)
}
await sourceControl?.refresh()
}
}
}
@@ -0,0 +1,166 @@
import Foundation
import HelderCore
import HelderServices
extension WorkspaceModel {
/// Switches this window to another project folder and remembers it in the recents.
/// Unsaved edits are asked about first; a cancel keeps the current project.
public func openProject(_ url: URL) async {
let url = url.standardizedFileURL
overlay.dismiss()
if url == root { return }
guard await prepareToClose() else { return }
await closeProject()
root = url
attach(url)
await loadProject()
isReady = true
}
/// Asks about every unsaved file, then writes the note and the session.
/// False when the user cancelled: the window or project must stay.
public func prepareToClose() async -> Bool {
if let editor, !(await editor.resolveUnsaved()) { return false }
await note?.save()
await editor?.persist()
return true
}
/// The window is closing: the unsaved prompt already ran, so this only winds the project down.
public func windowWillClose() {
guard lifecycleTask == nil else { return }
lifecycleTask = Task { [weak self] in
await self?.closeProject()
self?.lifecycleTask = nil
}
}
/// Runs a project switch outside `work`, since the switch waits for `work` to drain.
func switchProject(_ operation: @escaping @MainActor () async -> Void) {
guard lifecycleTask == nil else { return }
lifecycleTask = Task { [weak self] in
await operation()
self?.lifecycleTask = nil
}
}
func attach(_ root: URL) {
generation += 1
let services = app.makeWorkspace(root)
self.services = services
name = ProjectLocator.name(of: root)
title = ProjectLocator.title(of: root)
rowFrames = [:]
let notify: (String, String?) -> Void = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
let sourceControl = SourceControlStore(git: services.git)
sourceControl.notify = notify
self.sourceControl = sourceControl
let explorer = ExplorerStore(files: services.files, system: app.system)
explorer.notify = notify
self.explorer = explorer
let editor = EditorStore(root: root.path, files: services.files, sourceControl: sourceControl,
session: app.session, recentFiles: services.recentFiles)
wire(editor, symbols: services.symbols)
self.editor = editor
let note = NoteStore(notes: services.notes)
note.notify = notify
self.note = note
terminal = TerminalStore(projectRoot: root.path)
wireTerminal()
launcher = LauncherList(recents: recentProjects, excluding: root.path)
}
private func wire(_ editor: EditorStore, symbols: SymbolServicing) {
editor.presentOverlay = { [weak self] in self?.overlay.present($0) }
editor.dismissDiffOverlay = { [weak self] in
guard let self, case .diff = self.overlay.current else { return }
self.overlay.dismiss()
}
editor.showToast = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
editor.fileSaved = { [weak self, weak editor] _ in
guard let self, self.editor === editor else { return }
self.scheduleRefresh(.git)
}
editor.confirmUnsavedClose = { [weak self] path in self?.app.system.confirmUnsavedClose(path) ?? .cancel }
editor.symbols = symbols
}
func loadProject() async {
guard let root, let services else { return }
let current = generation
layout.restore(root: root.path)
config = await services.config.resolve()
guard generation == current else { return }
applyConfig()
await app.recentProjects.add(root.path)
recentProjects = await app.recentProjects.list()
guard generation == current else { return }
launcher = LauncherList(recents: recentProjects, excluding: root.path)
let sourceControl = sourceControl, explorer = explorer, note = note, editor = editor
async let git: Void = sourceControl?.refresh() ?? ()
async let tree: Void = explorer?.reload() ?? ()
async let loaded: Void = note?.load() ?? ()
_ = await (git, tree, loaded)
await editor?.restore(restoreSession: config.session.restoreOnLaunch)
guard generation == current else { return }
startWatcher(root)
sourceControl?.startPolling()
scheduleSymbolLoad(after: timings.symbolsAfterLaunch)
}
/// Stops the watchers and polling, waits for the work still running against this project,
/// then saves the note and the session and ends the terminals.
func closeProject() async {
watcher?.stop()
watcher = nil
sourceControl?.stopPolling()
pendingRefresh = []
let refresh = refreshTask, symbols = symbolsTask
refreshTask = nil
symbolsTask = nil
refreshID = UUID()
refresh?.cancel()
symbols?.cancel()
let running = Array(work.values)
running.forEach { $0.cancel() }
await refresh?.value
await symbols?.value
for task in running { await task.value }
await editor?.flushAutoSaves()
await note?.save()
await editor?.persist()
terminal.terminateAll()
}
/// Pushes the config into every store that reads it; runs on load and whenever `.helder/config.json` changes.
func applyConfig() {
terminal.config = config
sourceControl?.config = config.git
guard let editor else { return }
if editor.editorConfig != config.editor { editor.editorConfig = config.editor }
let mode = ViewMode(config.git.defaultDiffMode)
if editor.defaultMode != mode { editor.defaultMode = mode }
}
func reloadConfig() async {
guard let services else { return }
let current = generation
let resolved = await services.config.resolve()
guard generation == current else { return }
config = resolved
applyConfig()
}
private func startWatcher(_ root: URL) {
watcher?.stop()
let watcher = app.makeWatcher()
watcher.start(root: root) { [weak self] event in
Task { @MainActor in await self?.handle(event) }
}
self.watcher = watcher
}
}
@@ -0,0 +1,86 @@
import Foundation
import HelderCore
import HelderServices
extension WorkspaceModel {
/// ⌘R: reloads git, the tree and the open file from disk (disk wins over unsaved edits), and flashes the columns.
public func refresh() async {
refreshTick += 1
let editor = editor
async let reread: Void = run([.git, .tree])
async let active: Void = editor?.reloadActiveFromDisk() ?? ()
_ = await (reread, active)
}
/// Reacts to a disk change from the watcher: project and git events gather into one debounced refresh.
public func handle(_ event: WatchEvent) async {
switch event {
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .note])
case .git: scheduleRefresh(.git)
case .config: await reloadConfig()
}
}
/// Waits until every scheduled refresh, symbol load, command and project switch has finished; tests use it to settle.
public func settle() async {
while true {
if let task = lifecycleTask {
await task.value
} else if let task = refreshTask {
await task.value
} else if let task = symbolsTask {
await task.value
if symbolsTask == task { symbolsTask = nil }
} else if let task = work.values.first {
await task.value
} else {
break
}
}
await editor?.settle()
}
func scheduleRefresh(_ scope: RefreshScope) {
pendingRefresh.formUnion(scope)
guard refreshTask == nil, !pendingRefresh.isEmpty else { return }
let id = UUID()
refreshID = id
refreshTask = Task { [weak self] in
guard let self else { return }
try? await Task.sleep(for: self.timings.refreshDebounce)
guard !Task.isCancelled, self.refreshID == id else { return }
let scope = self.pendingRefresh
self.pendingRefresh = []
await self.run(scope)
guard self.refreshID == id else { return }
self.refreshTask = nil
self.scheduleRefresh([])
}
}
/// Reads the stores once up front, so a pass that outlives a project switch only touches the old project.
func run(_ scope: RefreshScope) async {
let sourceControl = sourceControl, explorer = explorer, editor = editor, note = note
let current = generation
if scope.contains(.symbols) {
await services?.symbols.invalidate()
if generation == current { scheduleSymbolLoad(after: timings.symbolsAfterChange) }
}
async let git: Void = scope.contains(.git) ? (sourceControl?.refresh() ?? ()) : ()
async let tree: Void = scope.contains(.tree) ? (explorer?.reload() ?? ()) : ()
async let files: Void = scope.contains(.openFiles) ? (editor?.filesChanged(nil) ?? ()) : ()
async let notes: Void = scope.contains(.note) ? (note?.reloadIfClean() ?? ()) : ()
_ = await (git, tree, files, notes)
}
/// Restarts the countdown on every change, so a burst of writes loads the class list once.
func scheduleSymbolLoad(after delay: Duration) {
symbolsTask?.cancel()
let editor = editor
symbolsTask = Task {
try? await Task.sleep(for: delay)
guard !Task.isCancelled else { return }
await editor?.loadKnownSymbols()
}
}
}
+273
View File
@@ -0,0 +1,273 @@
import CoreGraphics
import Foundation
import HelderCore
import HelderServices
import Observation
/// What the model asks of the window it lives in; the shell fills these in.
public struct WindowHooks {
public var closeWindow: () -> Void = {}
public init() {}
}
/// Timings the model waits on; tests shorten them.
public struct WorkspaceTimings: Sendable {
/// How long watcher events are gathered into one refresh.
public var refreshDebounce: Duration = .milliseconds(100)
/// The declared-class list loads late on purpose: it only decides which tokens may underline.
public var symbolsAfterLaunch: Duration = .milliseconds(1500)
public var symbolsAfterChange: Duration = .milliseconds(2000)
public init() {}
public static let immediate: WorkspaceTimings = {
var timings = WorkspaceTimings()
timings.refreshDebounce = .zero
timings.symbolsAfterLaunch = .zero
timings.symbolsAfterChange = .zero
return timings
}()
}
/// What one refresh pass re-reads.
public struct RefreshScope: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let git = RefreshScope(rawValue: 1)
public static let tree = RefreshScope(rawValue: 2)
/// A changed file may add or remove a PHP class.
public static let symbols = RefreshScope(rawValue: 4)
/// The open file and every unsaved buffer pick up the disk text; unsaved edits are kept.
public static let openFiles = RefreshScope(rawValue: 8)
/// The project note picks up an outside edit when it has no unsaved typing.
public static let note = RefreshScope(rawValue: 16)
}
/// 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)
}
/// One window, one project. Composes the stores and runs the actions that span several of them.
/// Views read the stores directly; anything that changes more than one store goes through `perform`.
@Observable
@MainActor
public final class WorkspaceModel {
/// nil until a project is opened; the window then shows the launcher.
public internal(set) var root: URL?
public internal(set) var name = ""
/// `APP_NAME` from the project's `.env`, else the folder name.
public internal(set) var title = "Helder"
public internal(set) var config = HelderConfig.defaults
public internal(set) var recentProjects: [RecentProject] = []
/// True once the first load finished, so the window never flashes the launcher on a slow disk.
public internal(set) var isReady = false
/// The bare window's launcher rows and cursor.
public internal(set) var launcher = LauncherList()
/// The latest request to move keyboard focus; views take first responder when it names them.
public internal(set) var focusRequest: FocusRequest?
/// Bumped by ⌘R; the columns flash once per bump so a refresh that changed nothing still reads.
public internal(set) var refreshTick = 0
/// The branch · project card shown briefly when the window becomes key again.
public internal(set) var isFocusFlashVisible = false
public let layout: LayoutStore
public let overlay: OverlayStore
public let toasts: ToastStore
public internal(set) var sourceControl: SourceControlStore?
public internal(set) var explorer: ExplorerStore?
public internal(set) var editor: EditorStore?
public internal(set) var terminal: TerminalStore
public internal(set) var note: NoteStore?
@ObservationIgnored public let app: AppServices
@ObservationIgnored public internal(set) var services: WorkspaceServices?
@ObservationIgnored public var hooks = WindowHooks()
@ObservationIgnored public var timings: WorkspaceTimings
@ObservationIgnored var watcher: FileWatching?
@ObservationIgnored var pendingRefresh: RefreshScope = []
@ObservationIgnored var refreshTask: Task<Void, Never>?
@ObservationIgnored var refreshID = UUID()
@ObservationIgnored var symbolsTask: Task<Void, Never>?
@ObservationIgnored var flashTask: Task<Void, Never>?
/// Fire-and-forget work started by commands; `settle()` waits for it and a project switch drains it.
@ObservationIgnored var work: [UUID: Task<Void, Never>] = [:]
/// A project switch or window close; kept apart from `work` because it drains `work`.
@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.
@ObservationIgnored var rowFrames: [RowKey: CGRect] = [:]
@ObservationIgnored var hasStarted = false
@ObservationIgnored var resignedKey = false
public init(root: URL?, app: AppServices, timings: WorkspaceTimings = WorkspaceTimings()) {
self.app = app
self.timings = timings
self.root = root?.standardizedFileURL
layout = LayoutStore(session: app.session, persistence: app.layouts)
overlay = OverlayStore()
toasts = ToastStore()
terminal = TerminalStore()
wireTerminal()
overlay.onChange = { [weak self] old, new in self?.overlayChanged(from: old, to: new) }
if let root = self.root { attach(root) }
}
/// Loads the recents and, with a project, its config, git, tree, note and session; then starts the watchers.
public func start() async {
guard !hasStarted else { return }
hasStarted = true
recentProjects = await app.recentProjects.list()
launcher = LauncherList(recents: recentProjects, excluding: root?.path)
if root != nil { await loadProject() }
isReady = true
}
/// Runs any command: the one entry point for views, menus and the keyboard.
public func perform(_ command: Command) {
switch command {
case let .showSearch(seed): overlay.present(.search(seed: seed.isEmpty ? editorSelectionFirstLine() : seed))
case .showNote: overlay.present(.note)
case .showShortcuts: overlay.present(.shortcuts)
case .showRecentProjects: showRecentProjects()
case let .showRecentFiles(index): overlay.present(.recentFiles(initialSelection: index))
case let .showContextMenu(target, anchor): showContextMenu(target, anchor: anchor)
case .dismissOverlay: overlay.dismiss()
case .confirmPending: confirmPending()
case let .submitName(name): submitName(name)
case let .passToAgent(text, reference):
overlay.dismiss()
passToAgent(text, toast: reference)
case let .launcherMove(step): launcher.move(by: step)
case let .launcherSelect(index): launcher.select(index)
case .launcherActivate: activateLauncher()
case .toggleGit: layout.toggleGit()
case .toggleAutoFit: layout.toggleFluid()
case .toggleHidden: layout.toggleHidden()
case let .focus(panel): focus(panel)
case let .focusNeighbour(step): focus(layout.neighbour(of: layout.activePanel, step: step))
case let .moveRowCursor(step): moveRowCursor(by: step)
case .openSelectedRow: openSelectedRow()
case .openRowMenu: openRowMenu()
case let .open(path, options): open(path, options)
case .save:
guard let editor, editor.activeIsDirty else { return }
track { try? await editor.save() }
case .closeFileOrWindow:
if let editor, editor.activePath != nil {
track { await editor.requestCloseActive() }
} else {
hooks.closeWindow()
}
case .cycleMode: editor?.togglePreview()
case let .passSelection(info): passSelection(info)
case .selectAllInFile: editor?.selectAll()
case .commit:
guard let sourceControl, sourceControl.canCommit else { return }
track { _ = await sourceControl.commit() }
case .push:
guard let sourceControl else { return }
track { _ = await sourceControl.push() }
case .focusCommitMessage:
if !layout.gitVisible { layout.toggleGit() }
layout.focus(.sourceControl)
focusRequest = FocusRequest(.commitMessage)
case .passNote: passNote()
case .openFolder:
switchProject {
guard let url = await self.app.system.chooseFolder() else { return }
await self.openProject(url)
}
case let .openRecentProject(path): switchProject { await self.openProject(URL(fileURLWithPath: path)) }
case .refresh: track { await self.refresh() }
case .newWindow: app.system.openNewInstance(nil)
case let .zoom(step): layout.zoom(step)
case let .context(action): perform(action)
}
}
/// Opens a file in the editor, reveals it in the Explorer and gives the editor the wide columns.
public func open(_ path: String, _ options: OpenOptions = OpenOptions()) {
guard let editor else { return }
explorer?.select(path)
editor.open(path, options)
layout.setFocusZone(.editor)
}
/// Inserts text into the agent's composer without submitting it, and confirms with a toast.
public func passToAgent(_ text: String, toast reference: String? = nil) {
terminal.insertIntoAgent(text: text)
toasts.show("Passed to agent", detail: reference)
}
/// Paths with a git change; the file lists mark them with a dot.
public var changedPaths: Set<String> {
Set(sourceControl?.state.changes.map(\.path) ?? [])
}
/// A view took the keyboard: the request is spent, so a view rebuilt later never grabs focus for it again.
public func focusTaken(_ target: FocusTarget) {
if focusRequest?.target == target { focusRequest = nil }
}
/// 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() {
terminal.contextMenuRequested = { [weak self] kind, hasSelection, point in
self?.showContextMenu(.terminal(kind, hasSelection: hasSelection), anchor: point)
}
}
/// A Source Control or Explorer row reports where it sits (nil when it leaves the screen).
public func rowFrameChanged(_ key: RowKey, _ frame: CGRect?) {
rowFrames[key] = frame
}
/// Saves the note when the window loses focus.
public func windowDidResignKey() {
resignedKey = true
guard let note else { return }
track { await note.save() }
}
/// Coming back to a window flashes branch · project, so the right window is obvious; launch never does.
public func windowDidBecomeKey() {
guard resignedKey else { return }
resignedKey = false
guard root != nil else { return }
flashTask?.cancel()
isFocusFlashVisible = true
flashTask = Task { [weak self] in
try? await Task.sleep(for: Metrics.focusFlashDuration)
guard !Task.isCancelled else { return }
self?.isFocusFlashVisible = false
}
}
func track(_ operation: @escaping @MainActor () async -> Void) {
let id = UUID()
work[id] = Task { [weak self] in
await operation()
self?.work[id] = nil
}
}
}
@@ -0,0 +1,72 @@
import Foundation
import HelderCore
import HelderServices
/// Every service one project window needs. Tests pass fakes; the app uses `live(root:)`.
public struct WorkspaceServices {
public var git: GitServicing
public var files: FileServicing
public var search: SearchServicing
public var symbols: SymbolServicing
public var config: ConfigServicing
public var notes: NotesServicing
public var recentFiles: RecentFilesStoring
public init(git: GitServicing, files: FileServicing, search: SearchServicing, symbols: SymbolServicing,
config: ConfigServicing, notes: NotesServicing, recentFiles: RecentFilesStoring) {
self.git = git
self.files = files
self.search = search
self.symbols = symbols
self.config = config
self.notes = notes
self.recentFiles = recentFiles
}
public static func live(root: URL) -> WorkspaceServices {
let config = ConfigService(root: root)
let search = RipgrepSearchService(root: root, config: config)
return WorkspaceServices(
git: GitService(root: root),
files: FileService(root: root, search: search),
search: search,
symbols: SymbolService(root: root, config: config),
config: config,
notes: NotesService(root: root),
recentFiles: RecentFilesStore(root: root)
)
}
}
/// Services shared by every window: what outlives one project.
public struct AppServices {
public var recentProjects: RecentProjectsStoring
public var session: SessionStoring
/// Column widths and toggles, per project.
public var layouts: LayoutPersisting
/// Dialogs, pasteboard, Finder.
public var system: SystemActing
/// Builds the services for a project folder.
public var makeWorkspace: (URL) -> WorkspaceServices
public var makeWatcher: () -> FileWatching
/// Every store is passed in, so a test can never reach the user's real recents, sessions or layouts.
public init(recentProjects: RecentProjectsStoring, session: SessionStoring, layouts: LayoutPersisting, system: SystemActing,
makeWorkspace: @escaping (URL) -> WorkspaceServices, makeWatcher: @escaping () -> FileWatching) {
self.recentProjects = recentProjects
self.session = session
self.layouts = layouts
self.system = system
self.makeWorkspace = makeWorkspace
self.makeWatcher = makeWatcher
}
public static let live = AppServices(
recentProjects: RecentProjectsStore(),
session: SessionStore(),
layouts: UserDefaultsLayoutStore(),
system: LiveSystemActions(),
makeWorkspace: WorkspaceServices.live(root:),
makeWatcher: { FSEventsWatcher() }
)
}
@@ -0,0 +1,30 @@
import AppKit
import SwiftUI
/// Column D: the agent terminal over a plain shell, split at `layout.agentFraction`.
public struct AgentColumn: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
GeometryReader { proxy in
VStack(spacing: 0) {
TerminalPane(kind: .agent, store: model.terminal, scale: model.layout.textScale)
.frame(height: proxy.size.height * model.layout.agentFraction)
Splitter(.horizontal) { model.layout.dragAgentSplit(by: $0, height: proxy.size.height) }
TerminalPane(kind: .shell, store: model.terminal, scale: model.layout.textScale)
}
}
// A new project brings a new store, and with it fresh panes and processes.
.id(ObjectIdentifier(model.terminal))
.background(Palette.panel)
.onChange(of: model.focusRequest) { _, request in
guard request?.target == .panel(.terminal), let view = model.terminal.agent as? NSView else { return }
view.window?.makeFirstResponder(view)
model.focusTaken(.panel(.terminal))
}
}
}
@@ -0,0 +1,131 @@
import AppKit
import HelderCore
import SwiftTerm
/// One pane's terminal: a SwiftTerm view bound to a PTY child, reporting to the `TerminalStore`.
final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle {
let kind: TerminalKind
private weak var store: TerminalStore?
private(set) var hasStarted = false
var appliedSettings: HelderConfig.Terminal?
var appliedScale = 1.0
private var closeObserver: NSObjectProtocol?
private let events = ProcessEvents()
init(kind: TerminalKind, store: TerminalStore) {
self.kind = kind
self.store = store
super.init(frame: NSRect(x: 0, y: 0, width: 480, height: 320),
font: TerminalAppearance.font(store.config.terminal),
options: TerminalAppearance.options(store.config.terminal))
events.owner = self
processDelegate = events
appliedSettings = store.config.terminal
TerminalAppearance.apply(store.config.terminal, to: self)
}
required init?(coder: NSCoder) {
fatalError("HelderTerminalView is built in code")
}
// MARK: TerminalSessionHandle
func start(_ launch: TerminalLaunch, argv0: String) {
hasStarted = true
let environment = launch.environment.map { "\($0.key)=\($0.value)" }
startProcess(executable: launch.executable, args: launch.arguments, environment: environment,
execName: argv0, currentDirectory: launch.workingDirectory)
}
/// Programmatic input (the agent paste) goes straight to the PTY, so it never counts as typing.
func send(_ text: String) {
guard process.running else { return }
process.send(data: Array(text.utf8)[...])
window?.makeFirstResponder(self)
}
// MARK: Input, selection, menu
/// After the child exited, the next keystroke starts a fresh one instead of reaching the dead PTY.
override func send(source: TerminalView, data: ArraySlice<UInt8>) {
if let store, store.hasExited(kind) {
store.start(kind, on: self)
return
}
if kind == .agent {
store?.agentReceivedInput(String(decoding: data, as: UTF8.self))
}
super.send(source: source, data: data)
}
/// Selecting text copies it, in both panes.
override func selectionChanged(source: Terminal) {
super.selectionChanged(source: source)
guard selection.active, let text = getSelection(), !text.isEmpty else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
var selectedText: String? {
selection.active ? getSelection() : nil
}
/// Bracketed only when the program asked for it, as a clipboard paste would be.
func paste(_ text: String) {
if terminal.bracketedPasteMode {
send(BracketedPaste.wrap(text, composerHasText: false))
} else {
send(text.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r"))
}
}
/// The app's own menu, drawn by the workspace, replaces the native one.
override func menu(for event: NSEvent) -> NSMenu? {
guard let store, let content = window?.contentView else { return nil }
let p = content.convert(event.locationInWindow, from: nil)
store.contextMenuRequested?(kind, selection.active, CGPoint(x: p.x, y: content.isFlipped ? p.y : content.bounds.height - p.y))
return nil
}
// MARK: Lifetime
/// Closing the window kills the child; moving the view between containers does not.
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let closeObserver { NotificationCenter.default.removeObserver(closeObserver) }
closeObserver = nil
guard let window else { return }
closeObserver = NotificationCenter.default.addObserver(
forName: NSWindow.willCloseNotification, object: window, queue: .main
) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
self.store?.release(self)
}
}
}
/// The child ended on its own: say so in the pane and tell the store.
fileprivate func childExited(exitCode: Int32?) {
feed(text: "\r\n\u{1b}[90m[process exited] · press any key to restart\u{1b}[0m\r\n")
store?.processExited(kind, exitCode: exitCode)
}
}
/// A separate delegate object: the view itself cannot be one, because the base class forwards
/// `hostCurrentDirectoryUpdate` to its `processDelegate`, which would then call itself.
private final class ProcessEvents: LocalProcessTerminalViewDelegate {
weak var owner: HelderTerminalView?
func sizeChanged(source: LocalProcessTerminalView, newCols: Int, newRows: Int) {}
func setTerminalTitle(source: LocalProcessTerminalView, title: String) {}
func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {}
func processTerminated(source: TerminalView, exitCode: Int32?) {
DispatchQueue.main.async { [weak self] in
MainActor.assumeIsolated { self?.owner?.childExited(exitCode: exitCode) }
}
}
}
@@ -0,0 +1,79 @@
import AppKit
import HelderCore
import SwiftTerm
/// Maps the config's CSS colour table onto SwiftTerm's ANSI palette.
enum TerminalColors {
/// Channels are 16-bit in SwiftTerm; a colour the config cannot parse falls back to the default theme's.
static func ansi(_ theme: TerminalTheme) -> [SwiftTerm.Color] {
let fallback = TerminalTheme().ansi
return zip(theme.ansi, fallback).map { value, backup in
let ns = (NSColor(css: value) ?? NSColor(css: backup) ?? .white).usingColorSpace(.sRGB) ?? .white
return SwiftTerm.Color(red: UInt16(ns.redComponent * 65535),
green: UInt16(ns.greenComponent * 65535),
blue: UInt16(ns.blueComponent * 65535))
}
}
/// One theme entry as an AppKit colour, with the default theme's value as fallback.
static func color(_ value: String, fallback: String) -> NSColor {
NSColor(css: value) ?? NSColor(css: fallback) ?? .white
}
}
/// Everything in `config.terminal` that SwiftTerm can express. Line height and letter
/// spacing have no SwiftTerm equivalent, so they are not applied.
enum TerminalAppearance {
static func cursorStyle(_ style: TerminalCursorStyle, blink: Bool) -> CursorStyle {
switch (style, blink) {
case (.bar, true): .blinkBar
case (.bar, false): .steadyBar
case (.block, true): .blinkBlock
case (.block, false): .steadyBlock
case (.underline, true): .blinkUnderline
case (.underline, false): .steadyUnderline
}
}
/// The configured family, else the bundled IBM Plex Mono at the terminal type size, times the window zoom.
static func font(_ settings: HelderConfig.Terminal, scale: Double = 1) -> NSFont {
FontRegistry.registerBundledFonts()
let size = CGFloat((settings.fontSize ?? Double(Typography.terminal.size)) * scale)
if let family = settings.fontFamily?.trimmingCharacters(in: .whitespaces), !family.isEmpty {
if let named = NSFont(name: family, size: size) { return named }
if let fromFamily = NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: size) {
return fromFamily
}
}
return NSFont(name: PlexFace.monoRegular.rawValue, size: size) ?? .monospacedSystemFont(ofSize: size, weight: .regular)
}
static func options(_ settings: HelderConfig.Terminal) -> TerminalOptions {
TerminalOptions(termName: "xterm-256color",
cursorStyle: cursorStyle(settings.cursorStyle, blink: settings.cursorBlink),
scrollback: max(0, settings.scrollback))
}
/// Restyles a running terminal; the buffer and the process are untouched.
@MainActor
static func apply(_ settings: HelderConfig.Terminal, scale: Double = 1, to view: TerminalView) {
let theme = settings.theme
let base = TerminalTheme()
let newFont = font(settings, scale: scale)
if view.font.fontName != newFont.fontName || view.font.pointSize != newFont.pointSize {
view.font = newFont
}
view.nativeBackgroundColor = TerminalColors.color(theme.background, fallback: base.background)
view.nativeForegroundColor = TerminalColors.color(theme.foreground, fallback: base.foreground)
view.caretColor = TerminalColors.color(theme.cursor, fallback: base.cursor)
view.caretTextColor = TerminalColors.color(theme.cursorAccent, fallback: base.cursorAccent)
view.selectedTextBackgroundColor = TerminalColors.color(theme.selectionBackground, fallback: base.selectionBackground)
view.installColors(TerminalColors.ansi(theme))
view.useBrightColors = settings.boldIsBright
view.optionAsMetaKey = settings.optionIsMeta
view.terminal.setCursorStyle(cursorStyle(settings.cursorStyle, blink: settings.cursorBlink))
if view.terminal.options.scrollback != settings.scrollback {
view.terminal.changeScrollback(max(0, settings.scrollback))
}
}
}
@@ -0,0 +1,49 @@
import AppKit
import HelderCore
import SwiftUI
/// One terminal pane: the live terminal fills it, with no header.
struct TerminalPane: View {
let kind: TerminalKind
let store: TerminalStore
/// The window zoom (⌘+ ⌘− ⌘0).
var scale: Double = 1
var body: some View {
TerminalHost(kind: kind, store: store, settings: store.config.terminal, scale: scale, isConfigured: store.isConfigured)
.padding(12)
.background(Color(nsColor: TerminalColors.color(store.config.terminal.theme.background,
fallback: TerminalTheme().background)))
}
}
/// Hosts the pane's `HelderTerminalView`. The view lives in the store, so SwiftUI rebuilding
/// this representable never restarts the process.
private struct TerminalHost: NSViewRepresentable {
let kind: TerminalKind
let store: TerminalStore
let settings: HelderConfig.Terminal
let scale: Double
let isConfigured: Bool
func makeNSView(context: Context) -> HelderTerminalView {
if let existing = store.session(kind) as? HelderTerminalView { return existing }
let view = HelderTerminalView(kind: kind, store: store)
store.attach(view, as: kind)
return view
}
func updateNSView(_ view: HelderTerminalView, context: Context) {
if view.appliedSettings != settings || view.appliedScale != scale {
view.appliedSettings = settings
view.appliedScale = scale
TerminalAppearance.apply(settings, scale: scale, to: view)
}
if isConfigured && !view.hasStarted {
store.start(kind, on: view)
if kind == .agent {
DispatchQueue.main.async { view.window?.makeFirstResponder(view) }
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
import CoreText
import Foundation
import HelderServices
/// Registers the bundled IBM Plex faces for this process. CoreText reads WOFF2 directly.
public enum FontRegistry {
public static let resourceBundleName = "Helder_HelderUI.bundle"
/// The Fonts folder, found without `Bundle.module`: its generated accessor looks next to
/// the .app (not in Contents/Resources) and falls back to an absolute build path.
public static func fontsDirectory() -> URL? {
let fm = FileManager.default
let candidates = [
Bundle.main.resourceURL,
Bundle.main.bundleURL,
Bundle.main.executableURL?.deletingLastPathComponent(),
// Under `swift test` the code lives in an .xctest bundle beside the resource bundle.
Bundle(for: BundleToken.self).bundleURL.deletingLastPathComponent(),
]
for base in candidates.compactMap({ $0 }) {
let fonts = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Fonts")
if fm.fileExists(atPath: fonts.path) { return fonts }
let flat = base.appendingPathComponent(resourceBundleName).appendingPathComponent("Contents/Resources/Fonts")
if fm.fileExists(atPath: flat.path) { return flat }
}
return nil
}
/// Registers every font file once; returns the PostScript names now available. Safe to call repeatedly.
@discardableResult
public static func registerBundledFonts() -> Set<String> {
lock.lock()
defer { lock.unlock() }
if let done = registered { return done }
var names = Set<String>()
guard let dir = fontsDirectory(),
let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else {
Log.warn("fonts", "bundled fonts not found; using the system fonts")
registered = names
return names
}
for url in files where ["woff2", "woff", "ttf", "otf"].contains(url.pathExtension.lowercased()) {
var error: Unmanaged<CFError>?
let ok = CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error)
let already = (error?.takeRetainedValue()).map { CFErrorGetCode($0) == CTFontManagerError.alreadyRegistered.rawValue } ?? false
if ok || already {
let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []
for d in descriptors {
if let name = CTFontDescriptorCopyAttribute(d, kCTFontNameAttribute) as? String { names.insert(name) }
}
} else {
Log.warn("fonts", "cannot register \(url.lastPathComponent)")
}
}
Log.info("fonts", "registered \(names.sorted().joined(separator: ", "))")
registered = names
return names
}
private final class BundleToken {}
private static let lock = NSLock()
nonisolated(unsafe) private static var registered: Set<String>?
}
+105
View File
@@ -0,0 +1,105 @@
import SwiftUI
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.
public static let panelHeader: CGFloat = 34
/// The bar above the code: the open file, its change counts, Preview and Diff.
public static let editorBar: CGFloat = 34
public static let titleBar: CGFloat = 44
public static let codeLine: CGFloat = 20
public static let searchHitLine: CGFloat = 24
public static let diffOverlayLine: CGFloat = 22
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
/// Buttons, inputs, tags, keycaps, menu rows, code blocks.
public static let radiusSmall: CGFloat = 2
/// Panels, cards, menus.
public static let radiusMedium: CGFloat = 4
/// Overlays only.
public static let radiusOverlay: CGFloat = 8
// MARK: Lines
public static let hairline: CGFloat = 1
/// Selection rule, focus border, pull-quote.
public static let accentRule: CGFloat = 2
/// The focus ring drawn outside the 2px amber border.
public static let focusRingWidth: CGFloat = 2
// 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
public static let explorerIndent: CGFloat = 16
public static let explorerBaseIndent: CGFloat = 12
/// Gutter of the code grid in the editor.
public static let codeGutter: CGFloat = 56
public static let diffOverlayGutter: CGFloat = 52
public static let searchHitGutter: CGFloat = 64
/// Room the hidden-inset title bar leaves for the traffic lights.
public static let trafficLightInset: CGFloat = 82
/// Where the traffic lights sit, measured from the window's top-left corner.
public static let trafficLightOrigin = CGPoint(x: 14, y: 12)
/// The pointer target of a 1pt splitter: 3pt either side of the line.
public static let splitterHitArea: CGFloat = 7
// MARK: Title bar and toolbar
public static let titleBarGap: CGFloat = 18
public static let titleClusterGap: CGFloat = 10
public static let crumbGap: CGFloat = 7
public static let toolbarGap: CGFloat = 4
public static let toolbarPadding = EdgeInsets(top: 6, leading: 9, bottom: 6, trailing: 9)
/// The `?` button: a square with a hairline border.
public static let toolbarIconButton: CGFloat = 26
public static let statusBarGap: CGFloat = 16
// MARK: Window
public static let defaultWindow = CGSize(width: 1680, height: 1040)
public static let minimumWindow = CGSize(width: 1100, height: 680)
// MARK: Overlays
public static let overlayInset: CGFloat = 34
public static let contextMenuWidth: CGFloat = 320
public static let passOnWidth: CGFloat = 460
public static let launcherWidth: CGFloat = 520
public static let launcherTopPadding: CGFloat = 40
public static let launcherFooter: CGFloat = 36
public static let tooltipMaxWidth: CGFloat = 300
public static let tooltipDelay: Duration = .milliseconds(350)
/// Toasts stack this far above the window's bottom edge.
public static let toastBottom: CGFloat = 44
// MARK: Elevation (only two shadows exist)
public static let menuShadowRadius: CGFloat = 16
public static let menuShadowY: CGFloat = 4
public static let overlayShadowRadius: CGFloat = 48
public static let overlayShadowY: CGFloat = 16
// MARK: Motion: colour transitions only
public static let colorTransition = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.16)
public static let smallControlTransition = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.12)
/// Stepped on/off blink of the caret, terminal cursor and wordmark period; no fade.
public static let blinkInterval: TimeInterval = 1.1
public static let refreshFlashDuration: TimeInterval = 0.26
/// How long the branch · project card shows when a window becomes key again.
public static let focusFlashDuration: Duration = .milliseconds(500)
}
+170
View File
@@ -0,0 +1,170 @@
// Dark only: there is no light mode by decision.
import AppKit
import HelderCore
import SwiftUI
public enum Palette {
// MARK: Surfaces (four, no more)
/// Editor canvas, terminal, launcher backdrop, code blocks.
public static let editor = Color(hex: 0x101720)
/// Title bar, side panels, status bar, overlays, menus.
public static let panel = Color(hex: 0x18202B)
/// Selected row, hairline borders, tooltip surface, keycap borders.
public static let raised = Color(hex: 0x232C39)
/// Row hover fill only.
public static let hover = Color(hex: 0x1E2733)
/// A side column with keyboard focus: one step of fill, nothing else.
public static let panelActive = Color(hex: 0x1B242F)
/// The editor column with keyboard focus.
public static let editorActive = Color(hex: 0x131B25)
/// What ⌘R adds on top of a column for a moment, so a refresh that changes nothing still reads.
public static let refreshFlash = Color(hex: 0x0F1113)
// MARK: Text on dark
/// Active file, dialog titles, selected row.
public static let text1 = Color(hex: 0xF4F5F4)
/// Body copy, code plain text.
public static let text2 = Color(hex: 0xE4E7E6)
/// Inactive rows, identifiers, secondary copy.
public static let text3 = Color(hex: 0xBAC0C0)
/// Labels, paths, meta, comments.
public static let text4 = Color(hex: 0x6C7783)
/// Line numbers, disabled.
public static let text5 = Color(hex: 0x3A424C)
/// Label on a destructive (amber-deep) button.
public static let onDeep = Color(hex: 0xF4F5F4)
/// Tooltip border.
public static let tooltipBorder = Color(hex: 0x3A424C)
// MARK: Accent: amber, reserved for the uses listed in the design README
public static let amber = Color(hex: 0xE8913A)
public static let amberDeep = Color(hex: 0xC4741F)
public static let amberSoft = Color(hex: 0xF0B476)
public static let amberTint = Color(hex: 0xE8913A, alpha: 0.10)
public static let focusRing = Color(hex: 0xE8913A, alpha: 0.22)
/// Border of an active toolbar toggle's keycap.
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)
// MARK: Syntax: six muted colours, weight 400, no italics
public static let syntaxPlain = Color(hex: 0xE4E7E6)
public static let syntaxVariable = Color(hex: 0xBAC0C0)
public static let syntaxComment = Color(hex: 0x6C7783)
public static let syntaxKeyword = Color(hex: 0xC3A6CE)
public static let syntaxString = Color(hex: 0x8FBFB4)
public static let syntaxNumber = Color(hex: 0xF0B476)
public static func syntax(_ role: TokenRole) -> Color {
switch role {
case .plain, .symbol: syntaxPlain
case .variable: syntaxVariable
case .comment: syntaxComment
case .keyword: syntaxKeyword
case .string: syntaxString
case .number: syntaxNumber
}
}
// MARK: Diff: no green, no red; it reads on shape and the 2px rule
public static let addedText = Color(hex: 0x8FBFB4)
public static let addedFill = Color(hex: 0x8FBFB4, alpha: 0.12)
public static let addedRule = Color(hex: 0x8FBFB4)
public static let removedText = Color(hex: 0xC4741F)
public static let removedFill = Color(hex: 0xC4741F, alpha: 0.14)
public static let removedRule = Color(hex: 0xC4741F)
// MARK: Overlays and elevation
/// Flat ink scrim behind every overlay; no blur.
public static let scrim = Color(hex: 0x101720, alpha: 0.72)
public static let menuShadow = Color(hex: 0x171C22, alpha: 0.10)
public static let overlayShadow = Color(hex: 0x171C22, alpha: 0.18)
// MARK: Type badges
public static let badgePurple = Color(hex: 0xC3A6CE)
public static let badgeAmber = Color(hex: 0xF0B476)
public static let badgeTeal = Color(hex: 0x8FBFB4)
public static let badgeGrey = Color(hex: 0xBAC0C0)
/// Badge text: ink on the fill.
public static let badgeText = Color(hex: 0x101720)
/// The fill of a workspace column: every column rests on `panel`; a focused one steps once.
public static func column(_ column: Panel, active: Bool) -> Color {
guard active else { return panel }
return column == .editor ? editorActive : panelActive
}
public static func badge(_ tint: BadgeTint) -> Color {
switch tint {
case .purple: badgePurple
case .amber: badgeAmber
case .teal: badgeTeal
case .grey: badgeGrey
}
}
/// The dot on a file with a git change in Search and Recent files.
public static let changedDot = Color(hex: 0x8FBFB4)
/// Menu icon tints: teal adds, amber-soft modifies or leaves the app, grey renames or passes on.
public static let menuIconAdd = Color(hex: 0x8FBFB4)
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)
}
extension Color {
/// A colour from a 0xRRGGBB literal.
public init(hex: UInt32, alpha: Double = 1) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xFF) / 255,
green: Double((hex >> 8) & 0xFF) / 255,
blue: Double(hex & 0xFF) / 255,
opacity: alpha
)
}
}
extension NSColor {
/// A colour from a 0xRRGGBB literal, for AppKit and SwiftTerm.
public convenience init(hex: UInt32, alpha: CGFloat = 1) {
self.init(
srgbRed: CGFloat((hex >> 16) & 0xFF) / 255,
green: CGFloat((hex >> 8) & 0xFF) / 255,
blue: CGFloat(hex & 0xFF) / 255,
alpha: alpha
)
}
/// Parses the config's CSS colours: `#RGB`, `#RRGGBB` and `rgba(r,g,b,a)`; nil for anything else.
public convenience init?(css: String) {
let s = css.trimmingCharacters(in: .whitespaces).lowercased()
if s.hasPrefix("#") {
var hex = String(s.dropFirst())
if hex.count == 3 { hex = hex.map { "\($0)\($0)" }.joined() }
guard hex.count == 6, let value = UInt32(hex, radix: 16) else { return nil }
self.init(hex: value)
return
}
guard s.hasPrefix("rgb"), let open = s.firstIndex(of: "("), let close = s.lastIndex(of: ")") else { return nil }
let parts = s[s.index(after: open)..<close].split(separator: ",").compactMap {
Double($0.trimmingCharacters(in: .whitespaces))
}
guard parts.count == 3 || parts.count == 4 else { return nil }
self.init(srgbRed: parts[0] / 255, green: parts[1] / 255, blue: parts[2] / 255, alpha: parts.count == 4 ? parts[3] : 1)
}
}
+108
View File
@@ -0,0 +1,108 @@
import AppKit
import SwiftUI
/// The bundled faces by PostScript name, as registered by `FontRegistry`.
public enum PlexFace: String, CaseIterable, Sendable {
case monoRegular = "IBMPlexMono-Regular"
case monoMedium = "IBMPlexMono-Medium"
case monoSemiBold = "IBMPlexMono-SemiBold"
case monoBold = "IBMPlexMono-Bold"
case sansRegular = "IBMPlexSans-Regular"
case sansMedium = "IBMPlexSans-Medium"
case sansSemiBold = "IBMPlexSans-SemiBold"
case sansBold = "IBMPlexSans-Bold"
case sansItalic = "IBMPlexSans-Italic"
public var isMono: Bool { rawValue.hasPrefix("IBMPlexMono") }
}
/// One typographic role: face, size, line box and tracking.
public struct TypeRole: Sendable {
public var face: PlexFace
public var size: CGFloat
/// Line box height in points; nil keeps the font's own.
public var lineHeight: CGFloat?
/// Tracking in points (the design's em values times the size).
public var tracking: CGFloat
public var uppercase: Bool
public init(_ face: PlexFace, _ size: CGFloat, lineHeight: CGFloat? = nil, trackingEm: CGFloat = 0, uppercase: Bool = false) {
self.face = face
self.size = size
self.lineHeight = lineHeight
self.tracking = trackingEm * size
self.uppercase = uppercase
}
/// Falls back to the system monospaced or UI font when the bundled face did not register.
public var nsFont: NSFont {
if let font = NSFont(name: face.rawValue, size: size) { return font }
let weight: NSFont.Weight = switch face {
case .monoMedium, .sansMedium: .medium
case .monoSemiBold, .sansSemiBold: .semibold
case .monoBold, .sansBold: .bold
default: .regular
}
return face.isMono ? .monospacedSystemFont(ofSize: size, weight: weight) : .systemFont(ofSize: size, weight: weight)
}
public var font: Font { Font(nsFont) }
}
public enum Typography {
public static let sectionTitle = TypeRole(.monoBold, 20, lineHeight: 24, trackingEm: -0.02)
public static let dialogTitle = TypeRole(.monoBold, 14, lineHeight: 14)
/// Section and panel labels: 10px mono, uppercase, text-4.
public static let panelLabel = TypeRole(.monoBold, 10, trackingEm: 0.14, uppercase: true)
public static let wordmark = TypeRole(.monoBold, 13, trackingEm: 0.02)
public static let launcherWordmark = TypeRole(.monoBold, 14, trackingEm: 0.02)
/// The last breadcrumb segment in the title bar.
public static let crumbLeaf = TypeRole(.monoSemiBold, 12)
/// The `esc`/`↵` chip and overlay footers.
public static let chip = TypeRole(.monoRegular, 11)
public static let keycapSmall = TypeRole(.monoSemiBold, 11)
public static let toastTitle = TypeRole(.sansRegular, 13)
public static let toastReference = TypeRole(.monoRegular, 12)
public static let focusFlash = TypeRole(.monoRegular, 19)
public static let focusFlashName = TypeRole(.monoBold, 19, trackingEm: -0.01)
public static let code = TypeRole(.monoRegular, 13, lineHeight: 20)
public static let searchHit = TypeRole(.monoRegular, 12, lineHeight: 24)
public static let path = TypeRole(.monoRegular, 12)
public static let meta = TypeRole(.monoRegular, 11)
public static let branch = TypeRole(.monoMedium, 12)
public static let keycap = TypeRole(.monoSemiBold, 12)
public static let statusLetter = TypeRole(.monoSemiBold, 10)
public static let badge = TypeRole(.monoSemiBold, 8)
public static let searchQuery = TypeRole(.monoMedium, 16)
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 body = TypeRole(.sansRegular, 14, lineHeight: 23.8)
public static let tooltip = TypeRole(.sansRegular, 12, lineHeight: 18)
public static let button = TypeRole(.sansMedium, 12)
public static let commitButton = TypeRole(.sansSemiBold, 12)
/// The editor bar's Preview and Diff buttons.
public static let segment = TypeRole(.sansRegular, 11)
public static let segmentOn = TypeRole(.sansMedium, 11)
public static let toolbarLabel = TypeRole(.sansRegular, 12)
public static let toolbarLabelOn = TypeRole(.sansMedium, 12)
public static let menuItem = TypeRole(.sansRegular, 13)
public static let menuItemHighlighted = TypeRole(.sansMedium, 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)
}
extension View {
/// Applies a type role: font, tracking, line spacing and case.
public func typeRole(_ role: TypeRole) -> some View {
let natural = role.nsFont.ascender - role.nsFont.descender + role.nsFont.leading
return self
.font(role.font)
.tracking(role.tracking)
.lineSpacing(max(0, (role.lineHeight ?? natural) - natural))
.textCase(role.uppercase ? .uppercase : nil)
}
}