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