restores Helder in all its glory
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -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() } }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user