adds Clean Copy Support

This commit is contained in:
2026-10-12 09:43:57 +02:00
parent 188e078055
commit 281f5465a6
28 changed files with 579 additions and 120 deletions
@@ -0,0 +1,43 @@
import SwiftUI
/// Text the agent wrote to `.clean-copy`: edit it, then copy it as plain text.
struct CleanCopyOverlay: View {
let store: CleanCopyStore
var onCopy: () -> Void
var onClose: () -> Void
var body: some View {
OverlayShell(.sized(width: 780), onDismiss: onClose) {
VStack(spacing: 0) {
OverlayHeader(systemImage: "doc.on.clipboard", title: "From Claude", detail: CleanCopyStore.fileName) {
Button(action: onCopy) {
HStack(spacing: 8) {
Text("Copy")
Keycap("⌘↩", style: .onAmber, small: true)
}
}
.buttonStyle(.primary)
}
OverlayTextEditor(text: Binding(get: { store.text }, set: { store.text = $0 }), onKey: handle)
.frame(maxWidth: .infinity, maxHeight: .infinity)
Text("copied as plain text · \(store.characterCount) characters")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 34)
.hairline(.top)
}
.frame(maxHeight: .infinity)
}
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .commandEnter: onCopy()
case .escape: onClose()
default: return false
}
return true
}
}
+2 -97
View File
@@ -1,4 +1,3 @@
import AppKit
import SwiftUI
/// ⌘N: the project's plain-text note. Closing it in any way saves it.
@@ -19,7 +18,8 @@ struct NoteOverlay: View {
}
.buttonStyle(.primary)
}
NoteEditor(text: Binding(get: { note.text }, set: { note.text = $0 }), onKey: handle)
OverlayTextEditor(text: Binding(get: { note.text }, set: { note.text = $0 }),
placeholder: "Anything you want to keep next to this project…", onKey: handle)
.frame(maxWidth: .infinity, maxHeight: .infinity)
Text("saved on focus loss · \(note.characterCount) characters")
.typeRole(Typography.meta)
@@ -43,98 +43,3 @@ struct NoteOverlay: View {
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.pointerLayer = .overlay
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
textView.autoresizingMask = [.width]
textView.textContainer?.widthTracksTextView = true
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
textView.fillsClipView = true
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: PointerBoundTextView {
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)
}
}
@@ -36,6 +36,10 @@ public struct OverlayHost: View {
if let note = model.note {
NoteOverlay(note: note, onPassOn: { model.perform(.passNote) }, onClose: dismiss)
}
case .cleanCopy:
if let cleanCopy = model.cleanCopy {
CleanCopyOverlay(store: cleanCopy, onCopy: { model.perform(.copyCleanCopy) }, onClose: dismiss)
}
case let .recentFiles(initialSelection):
RecentFilesOverlay(history: model.editor?.history ?? [], initialSelection: initialSelection,
changedPaths: model.changedPaths,
+14 -1
View File
@@ -4,7 +4,7 @@ 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
case commandP, commandEnter
/// Maps the text system's commands back to the keys that produced them.
init?(selector: Selector) {
@@ -21,6 +21,19 @@ enum OverlayKey: Equatable {
}
}
/// ⌘P or ⌘↩ from a text view, which sees them as key equivalents before any key handling.
init?(equivalent event: NSEvent) {
let modifiers = event.modifierFlags.intersection([.command, .shift, .option, .control])
guard modifiers == .command else { return nil }
if event.keyCode == 36 || event.keyCode == 76 {
self = .commandEnter
} else if event.charactersIgnoringModifiers?.lowercased() == "p" {
self = .commandP
} else {
return nil
}
}
/// Maps a raw key event, for overlays without a text field.
init?(event: NSEvent) {
let command = event.modifierFlags.contains(.command)
@@ -0,0 +1,98 @@
import AppKit
import SwiftUI
/// Mono 14/1.7 plain-text editor with an amber caret, focused with the caret at the end.
struct OverlayTextEditor: NSViewRepresentable {
@Binding var text: String
var placeholder = ""
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 = OverlayTextView(frame: .zero)
textView.pointerLayer = .overlay
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
textView.autoresizingMask = [.width]
textView.textContainer?.widthTracksTextView = true
textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
textView.fillsClipView = true
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 = placeholder
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? OverlayTextView else { return }
textView.onKey = onKey
if textView.string != text { textView.string = text }
}
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: OverlayTextEditor
init(_ parent: OverlayTextEditor) {
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 and ⌘↩ before the menu bar sees them, and draws the placeholder.
private final class OverlayTextView: PointerBoundTextView {
var onKey: (OverlayKey) -> Bool = { _ in false }
var placeholder = ""
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if window?.firstResponder === self, let key = OverlayKey(equivalent: event), onKey(key) { 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)
}
}
@@ -310,7 +310,7 @@ struct SearchOverlay: View {
case .down, .commandDown: park(); model.moveRow(by: 1)
case .enter: if let target = model.target() { open(target) }
case .escape: onClose()
case .commandP: return false
case .commandP, .commandEnter: return false
}
return true
}
+5
View File
@@ -124,6 +124,11 @@ public enum Command: Equatable, Sendable {
/// ⌘P while the note is open.
case passNote
// MARK: Clean copy
/// The clean-copy popup's Copy and ⌘↩: copies its text and closes it.
case copyCleanCopy
// MARK: Project and window
/// ⌘O
@@ -0,0 +1,63 @@
import Foundation
import HelderCore
import HelderServices
import Observation
/// The clean-copy popup: text the agent wrote to `.clean-copy`, editable before it is copied.
@Observable
@MainActor
public final class CleanCopyStore {
public static let fileName = CleanCopy.fileName
/// The popup's text, with the user's edits.
public var text = ""
/// The text as it arrived, so an edit can be told apart.
public private(set) var received = ""
/// The newest text waiting for the popup, while another overlay is open.
public private(set) var pending: String?
/// The file's last contents Helder saw; nil before the first read or while the file is missing.
@ObservationIgnored private var lastSeen: String?
@ObservationIgnored private let files: FileServicing
public init(files: FileServicing) {
self.files = files
}
public var isEdited: Bool { text != received }
public var characterCount: Int { text.count }
/// Project open: the file's current text is the baseline and never shows.
public func loadBaseline() async {
lastSeen = await read()
}
/// The file changed: returns true when it holds new text, which then waits in `pending`.
@discardableResult
public func fileChanged() async -> Bool {
guard let contents = await read() else { return false }
let isNew = CleanCopy.isNew(contents, lastSeen: lastSeen)
lastSeen = contents
if isNew { pending = contents }
return isNew
}
/// Moves the pending text into the popup that is about to open.
public func takePending() {
guard let pending else { return }
text = pending
received = pending
self.pending = nil
}
/// New text while the popup is open replaces it only when the user has not edited it.
public func refreshOpenPopup() {
if !isEdited { takePending() }
pending = nil
}
private func read() async -> String? {
try? await files.read(Self.fileName)
}
}
@@ -90,6 +90,8 @@ public enum Overlay: Equatable {
case shortcuts
/// ⌘N: the project note.
case note
/// Text the agent wrote to `.clean-copy`, to edit and copy.
case cleanCopy
case diff(DiffOverlayRequest)
/// ⇧⌘O: the other recent projects. The bare window's launcher is not an overlay.
case launcher
@@ -15,6 +15,39 @@ extension WorkspaceModel {
default:
break
}
if new == .none, cleanCopy?.pending != nil {
Task { @MainActor [weak self] in self?.showCleanCopy() }
}
}
/// `.clean-copy` changed on disk: new text opens the popup, or waits for the open overlay to close.
func cleanCopyChanged() async {
guard let cleanCopy else { return }
let current = generation
guard await cleanCopy.fileChanged(), generation == current, self.cleanCopy === cleanCopy else { return }
showCleanCopy()
}
/// Shows the pending clean-copy text when nothing else floats over the workspace.
func showCleanCopy() {
guard let cleanCopy, cleanCopy.pending != nil else { return }
switch overlay.current {
case .none:
cleanCopy.takePending()
overlay.present(.cleanCopy)
case .cleanCopy:
cleanCopy.refreshOpenPopup()
default:
break
}
}
/// Copies the popup's text as plain text, closes it and confirms with a toast.
func copyCleanCopy() {
guard let cleanCopy, overlay.current == .cleanCopy else { return }
app.system.copy(cleanCopy.text)
overlay.dismiss()
toasts.show("Copied", detail: "\(cleanCopy.characterCount) characters")
}
/// The recent projects other than this one, for ⇧⌘O.
@@ -69,6 +69,7 @@ extension WorkspaceModel {
let note = NoteStore(notes: services.notes)
note.notify = notify
self.note = note
cleanCopy = CleanCopyStore(files: services.files)
terminal = TerminalStore(projectRoot: root.path)
wireTerminal()
launcher = LauncherList(recents: recentProjects, excluding: root.path)
@@ -100,11 +101,12 @@ extension WorkspaceModel {
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
let sourceControl = sourceControl, explorer = explorer, note = note, editor = editor, cleanCopy = cleanCopy
async let git: Void = sourceControl?.refresh() ?? ()
async let tree: Void = explorer?.reload() ?? ()
async let loaded: Void = note?.load() ?? ()
_ = await (git, tree, loaded)
async let baseline: Void = cleanCopy?.loadBaseline() ?? ()
_ = await (git, tree, loaded, baseline)
await editor?.restore(restoreSession: config.session.restoreOnLaunch)
guard generation == current else { return }
startWatcher(root)
@@ -18,6 +18,7 @@ extension WorkspaceModel {
case .project: scheduleRefresh([.git, .tree, .symbols, .openFiles, .note])
case .git: scheduleRefresh(.git)
case .config: await reloadConfig()
case .cleanCopy: await cleanCopyChanged()
}
}
@@ -84,6 +84,7 @@ public final class WorkspaceModel {
public internal(set) var editor: EditorStore?
public internal(set) var terminal: TerminalStore
public internal(set) var note: NoteStore?
public internal(set) var cleanCopy: CleanCopyStore?
@ObservationIgnored public let app: AppServices
@ObservationIgnored public internal(set) var services: WorkspaceServices?
@@ -186,6 +187,7 @@ public final class WorkspaceModel {
focusRequest = FocusRequest(.commitMessage)
case .passNote: passNote()
case .copyCleanCopy: copyCleanCopy()
case .openFolder:
switchProject {
@@ -10,6 +10,7 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle,
var appliedSettings: HelderConfig.Terminal?
var appliedScale = 1.0
private var closeObserver: NSObjectProtocol?
private var keyMonitor: Any?
private lazy var pointerTracker = PointerTracker(view: self)
private let events = ProcessEvents()
@@ -24,6 +25,7 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle,
processDelegate = events
appliedSettings = store.config.terminal
TerminalAppearance.apply(store.config.terminal, to: self)
syncMouseReporting()
}
required init?(coder: NSCoder) {
@@ -60,18 +62,28 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle,
super.send(source: source, data: data)
}
/// ⌥← and ⌥→ jump by word (ESC b / ESC f, as Terminal.app does) while Option is not the Meta key.
override func interpretKeyEvents(_ events: [NSEvent]) {
if !optionAsMetaKey, events.count == 1, let event = events.first, event.type == .keyDown,
event.modifierFlags.intersection([.shift, .control, .option, .command]) == .option,
let key = event.charactersIgnoringModifiers?.unicodeScalars.first.map({ Int($0.value) }) {
switch key {
case NSLeftArrowFunctionKey: return send(EscapeSequences.emacsBack)
case NSRightArrowFunctionKey: return send(EscapeSequences.emacsForward)
default: break
}
}
super.interpretKeyEvents(events)
/// ⌥← and ⌥→ jump by word (ESC b / ESC f, as Terminal.app does) while Option is not the Meta key;
/// caught before SwiftTerm, whose kitty-keyboard path would drop the Option and whose `keyDown` is not open.
private func handleWordJump(_ event: NSEvent) -> Bool {
guard !optionAsMetaKey, let window, event.window === window, window.firstResponder === self,
event.modifierFlags.intersection([.shift, .control, .option, .command]) == .option,
let key = event.charactersIgnoringModifiers?.unicodeScalars.first.map({ Int($0.value) }),
key == NSLeftArrowFunctionKey || key == NSRightArrowFunctionKey else { return false }
selection.active = false
send(key == NSLeftArrowFunctionKey ? EscapeSequences.emacsBack : EscapeSequences.emacsForward)
return true
}
/// Mouse reporting is on only while the program asked for it; SwiftTerm clears the selection on every output
/// while it is on, so a redrawing program like Claude Code could never keep one.
override func dataReceived(slice: ArraySlice<UInt8>) {
syncMouseReporting()
super.dataReceived(slice: slice)
syncMouseReporting()
}
private func syncMouseReporting() {
allowMouseReporting = terminal.mouseMode != .off
}
/// Selecting text copies it, in both panes.
@@ -181,7 +193,12 @@ final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle,
super.viewDidMoveToWindow()
if let closeObserver { NotificationCenter.default.removeObserver(closeObserver) }
closeObserver = nil
if let keyMonitor { NSEvent.removeMonitor(keyMonitor) }
keyMonitor = nil
guard let window else { return }
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
MainActor.assumeIsolated { self?.handleWordJump(event) ?? false } ? nil : event
}
closeObserver = NotificationCenter.default.addObserver(
forName: NSWindow.willCloseNotification, object: window, queue: .main
) { [weak self] _ in