restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
+5
View File
@@ -0,0 +1,5 @@
.build/
build/
.swiftpm/
screenshots/*
!screenshots/.gitignore
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "f18733abbc475ad9967fc14270c950518a6b14bcf4ea7cfaa6cd11f7916bc628",
"pins" : [
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser",
"state" : {
"revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
"version" : "1.8.2"
}
},
{
"identity" : "swiftterm",
"kind" : "remoteSourceControl",
"location" : "https://github.com/migueldeicaza/SwiftTerm",
"state" : {
"revision" : "5d14406844143538cd8f8851d2d8a67c1fe443e5",
"version" : "1.20.0"
}
}
],
"version" : 3
}
+42
View File
@@ -0,0 +1,42 @@
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "Helder",
platforms: [.macOS(.v14)],
products: [
.executable(name: "Helder", targets: ["Helder"]),
],
dependencies: [
.package(url: "https://github.com/migueldeicaza/SwiftTerm", from: "1.9.0"),
],
targets: [
.target(
name: "HelderCore",
swiftSettings: [.swiftLanguageMode(.v6)]
),
.target(
name: "HelderServices",
dependencies: ["HelderCore"],
swiftSettings: [.swiftLanguageMode(.v5)]
),
.target(
name: "HelderUI",
dependencies: [
"HelderCore",
"HelderServices",
.product(name: "SwiftTerm", package: "SwiftTerm"),
],
resources: [.copy("Resources/Fonts")],
swiftSettings: [.swiftLanguageMode(.v5)]
),
.executableTarget(
name: "Helder",
dependencies: ["HelderUI"],
swiftSettings: [.swiftLanguageMode(.v5)]
),
.testTarget(name: "HelderCoreTests", dependencies: ["HelderCore"]),
.testTarget(name: "HelderServicesTests", dependencies: ["HelderServices"]),
.testTarget(name: "HelderUITests", dependencies: ["HelderUI"]),
]
)
+7 -7
View File
@@ -1,6 +1,6 @@
# Claude Storm.
# Helder.
Claude Storm is the dark workbench for reviewing the code Claude Code writes: a native macOS rewrite (Swift, SwiftUI and AppKit) of the Electron app in `old-app/`, which was called Helder. That original stays the behavioural and visual reference; see [docs/architecture.md](docs/architecture.md).
Helder is the dark workbench for reviewing the code Claude Code writes: a native macOS app in Swift, SwiftUI and AppKit. See [docs/index.md](docs/index.md) for the architecture, the design tokens and the behaviour spec.
## Build, test, run
@@ -8,10 +8,10 @@ Claude Storm is the dark workbench for reviewing the code Claude Code writes: a
scripts/build.sh # debug build (--release for release)
scripts/test.sh # all three test targets; e.g. --filter WorkspaceModel
scripts/run.sh [project] # build and run; the optional folder opens in the first window
scripts/bundle.sh # "build/Claude Storm.app", ad-hoc signed, with ripgrep inside (--install copies it to ~/Applications)
scripts/bundle.sh # "build/Helder.app", ad-hoc signed, with ripgrep inside (--install copies it to ~/Applications)
```
Always use the scripts: they select the toolchain this machine needs. Search uses ripgrep when it can find one (`Contents/Helpers/rg` in the bundle, or `$RG_BINARY`) and a slower Swift walk otherwise.
Always use the scripts: they select the toolchain this machine needs. Search uses ripgrep when it can find one (`Contents/Helpers/rg` in the bundle, copied from `vendor/ripgrep/rg`, or `$RG_BINARY`) and a slower Swift walk otherwise.
## What it does
@@ -53,7 +53,7 @@ Closing a window, switching project or quitting (⌘Q) first asks about every un
## Testing
Three test targets mirror the three library targets: `Tests/ClaudeStormCoreTests`, `Tests/ClaudeStormServicesTests` and `Tests/ClaudeStormUITests`. Inside each target, the folders mirror `Sources/<Target>/` (a test for `Sources/ClaudeStormUI/State/EditorStore.swift` sits in `Tests/ClaudeStormUITests/State/`).
Three test targets mirror the three library targets: `Tests/HelderCoreTests`, `Tests/HelderServicesTests` and `Tests/HelderUITests`. Inside each target, the folders mirror `Sources/<Target>/` (a test for `Sources/HelderUI/State/EditorStore.swift` sits in `Tests/HelderUITests/State/`).
The tests use Swift Testing. For a PHPUnit reader:
@@ -66,8 +66,8 @@ The tests use Swift Testing. For a PHPUnit reader:
| `@dataProvider` | `@Test(arguments: [...]) func x(_ value: …)` |
| `setUp()` | the suite's `init()`, or a helper that builds the fixture |
- **Fakes and harnesses** live in `Tests/ClaudeStormUITests/Support/`: one fake per service protocol in `Fakes/` (`FakeGit`, `FakeFiles`, `FakeSystem`, `FakeTerminal`, …), and `WorkspaceHarness`, which wires a whole window to those fakes. UI tests never touch the disk, git, the user's defaults or the log.
- **Integration tests** in `ClaudeStormServicesTests` run the real `git` and file system. `TempGitRepo` creates a throwaway repository (`commit`, `write`, `run`); `TempDirectory` a throwaway folder.
- **Fakes and harnesses** live in `Tests/HelderUITests/Support/`: one fake per service protocol in `Fakes/` (`FakeGit`, `FakeFiles`, `FakeSystem`, `FakeTerminal`, …), and `WorkspaceHarness`, which wires a whole window to those fakes. UI tests never touch the disk, git, the user's defaults or the log.
- **Integration tests** in `HelderServicesTests` run the real `git` and file system. `TempGitRepo` creates a throwaway repository (`commit`, `write`, `run`); `TempDirectory` a throwaway folder.
- **Waiting**: `await model.settle()` or `eventually { … }`, never a sleep.
```bash
+11
View File
@@ -0,0 +1,11 @@
import HelderUI
import SwiftUI
@main
struct HelderApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
HelderScene()
}
}
@@ -0,0 +1,57 @@
import Foundation
/// A pointer at code the agent understands: `path`, `path:42` or `path:42-58`.
public struct AgentReference: Sendable, Equatable, CustomStringConvertible {
public var path: String
/// First line, 1-based; nil for a whole-file (or folder) reference.
public var startLine: Int?
/// Last line; equal to `startLine` for a single line.
public var endLine: Int?
public init(path: String, startLine: Int? = nil, endLine: Int? = nil) {
self.path = path
self.startLine = startLine
self.endLine = endLine ?? startLine
}
/// A reference to a line range.
public init(path: String, lines: ClosedRange<Int>) {
self.init(path: path, startLine: lines.lowerBound, endLine: lines.upperBound)
}
public var description: String {
guard let start = startLine else { return path }
guard let end = endLine, end != start else { return "\(path):\(start)" }
return "\(path):\(start)-\(end)"
}
}
public enum PassOn {
/// The exact text a "Pass on …" action inserts into the agent.
///
/// With code: `note ref` then the code in a fenced block. Without: `note => ref`,
/// or just `ref` when the note is empty.
public static func compose(note: String, reference: String, code: String? = nil) -> String {
let n = note.trimmingCharacters(in: .whitespacesAndNewlines)
if let code {
let head = (n.isEmpty ? "" : n + " ") + reference
return head + "\n```\n" + code + "\n```"
}
return n.isEmpty ? reference : "\(n) => \(reference)"
}
}
public enum BracketedPaste {
public static let start = "\u{1b}[200~"
public static let end = "\u{1b}[201~"
/// Wraps text so the CLI treats it as pasted and does not submit it.
///
/// ESC and the 8-bit CSI are stripped from the payload: a file or note holding `ESC[201~`
/// would otherwise end the paste early and let the rest run as typed input.
public static func wrap(_ text: String, composerHasText: Bool) -> String {
var payload = String.UnicodeScalarView()
payload.append(contentsOf: text.unicodeScalars.lazy.filter { $0 != "\u{1b}" && $0 != "\u{9b}" })
return start + (composerHasText ? "\n" : "") + String(payload) + end
}
}
@@ -0,0 +1,45 @@
import Foundation
public enum TerminalKind: String, Sendable, Equatable, CaseIterable {
/// The top pane: a shell that runs the `claude` CLI.
case agent
/// The bottom pane: a plain login shell.
case shell
}
/// Executable, arguments and environment for one terminal pane.
public struct TerminalLaunch: Sendable, Equatable {
public var executable: String
public var arguments: [String]
public var environment: [String: String]
public var workingDirectory: String
public init(executable: String, arguments: [String], environment: [String: String], workingDirectory: String) {
self.executable = executable
self.arguments = arguments
self.environment = environment
self.workingDirectory = workingDirectory
}
/// The launch for a pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
/// files (nvm etc.) but leaves no prompt line or echoed command behind.
public static func make(kind: TerminalKind, config: HelderConfig, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
let shell = config.terminal.shell ?? base["SHELL"] ?? "/bin/zsh"
let args = kind == .agent && config.ai.autoLaunch ? ["-i", "-c", config.ai.command] : []
let cwd = projectRoot ?? base["HOME"] ?? "/"
return TerminalLaunch(executable: shell, arguments: args, environment: environment(from: base), workingDirectory: cwd)
}
/// The child environment. A GUI launch inherits no locale and no COLORTERM, which turns
/// multibyte output into mojibake and shifts the CLI's 24-bit colours; npm's prefix
/// variables make nvm refuse to load.
public static func environment(from base: [String: String]) -> [String: String] {
var env = base
env["npm_config_prefix"] = nil
env["npm_config_globalconfig"] = nil
if env["LC_ALL"] == nil && env["LC_CTYPE"] == nil && env["LANG"] == nil { env["LANG"] = "en_US.UTF-8" }
if env["COLORTERM"] == nil { env["COLORTERM"] = "truecolor" }
env["TERM"] = "xterm-256color"
return env
}
}
@@ -0,0 +1,25 @@
import Foundation
extension HelderConfig {
/// Folder in the project root that holds Helder's per-project state.
public static let folderName = ".helder"
public static let overridesFileName = "config.json"
public static let defaultsFileName = "config.default.json"
/// The whole `.helder` folder is machine-local state, so it ignores itself.
public static let gitignoreBody = "# Helder — local, machine-specific state (do not commit).\n*\n"
/// The effective config for a sparse `config.json`; nil, empty or invalid JSON yields the defaults.
public static func resolved(overrides data: Data?) -> HelderConfig {
guard let data, !data.isEmpty else { return .defaults }
return (try? JSONDecoder().decode(HelderConfig.self, from: data)) ?? .defaults
}
/// Pretty JSON of every default, rewritten to `config.default.json` on each launch as documentation.
public static func defaultsJSON() -> Data {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
var data = (try? encoder.encode(HelderConfig.defaults)) ?? Data()
data.append(0x0A)
return data
}
}
@@ -0,0 +1,291 @@
import Foundation
/// The view a changed file opens in. Raw values are what config files on disk hold;
/// an unknown value, such as an older config's "original", falls back to `.updated`.
public enum DefaultDiffMode: String, Codable, Sendable, CaseIterable {
case updated
case diff
}
/// Soft wrap of long lines: never, always, or only in Markdown files.
public enum WordWrap: String, Codable, Sendable, CaseIterable {
case off
case on
case markdown
}
public enum TerminalCursorStyle: String, Codable, Sendable, CaseIterable {
case bar
case block
case underline
}
/// The terminal colour table. Every value is a CSS colour string; only the selection entries may carry alpha.
public struct TerminalTheme: Codable, Sendable, Equatable {
public var background = "#101720"
public var foreground = "#E4E7E6"
public var cursor = "#E8913A"
public var cursorAccent = "#101720"
public var selectionBackground = "rgba(232,145,58,0.22)"
public var selectionInactiveBackground = "rgba(232,145,58,0.12)"
public var black = "#232C39"
public var red = "#C4741F"
public var green = "#8FBFB4"
public var yellow = "#F0B476"
public var blue = "#8FA9C4"
public var magenta = "#C3A6CE"
public var cyan = "#8FC4C4"
public var white = "#BAC0C0"
public var brightBlack = "#6C7783"
public var brightRed = "#E8913A"
public var brightGreen = "#A6D2C7"
public var brightYellow = "#F5C79A"
public var brightBlue = "#A9BFD6"
public var brightMagenta = "#D6BFDF"
public var brightCyan = "#A9D6D6"
public var brightWhite = "#F4F5F4"
public init() {}
/// The sixteen ANSI colours in SGR order (black … brightWhite).
public var ansi: [String] {
[black, red, green, yellow, blue, magenta, cyan, white,
brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite]
}
}
/// Effective project settings: `.helder/config.json` merged key by key over these defaults.
public struct HelderConfig: Codable, Sendable, Equatable {
public struct AI: Codable, Sendable, Equatable {
public var command = "claude"
public var autoLaunch = true
public init() {}
}
public struct Editor: Codable, Sendable, Equatable {
public var autoSave = false
public var tabSize = 4
public var wordWrap = WordWrap.markdown
public init() {}
}
public struct Git: Codable, Sendable, Equatable {
public var confirmDiscard = true
public var confirmStage = false
public var confirmUnstage = false
public var defaultDiffMode = DefaultDiffMode.updated
/// Milliseconds between git status polls; 0 disables the poll.
public var refreshInterval = 10_000
public init() {}
}
public struct Files: Codable, Sendable, Equatable {
/// Extra ripgrep globs to leave out of the tree and the search.
public var exclude: [String] = []
/// False on purpose: the tree and the search show git-ignored files such as `.env` unless a project opts in.
public var followGitignore = false
public init() {}
}
public struct Terminal: Codable, Sendable, Equatable {
/// Login shell for both panes; nil means `$SHELL`.
public var shell: String?
/// nil means the bundled IBM Plex Mono.
public var fontFamily: String?
/// nil means the Typography default for terminals.
public var fontSize: Double?
public var lineHeight = 1.7
public var letterSpacing = 0.0
public var cursorStyle = TerminalCursorStyle.bar
public var cursorBlink = true
/// Off keeps bold text in its own hue, so a CLI's bold labels do not wash out.
public var boldIsBright = false
public var scrollback = 8000
/// Needed for a CLI's ⌥↵ binding, but it stops Option from typing accents, hence off.
public var optionIsMeta = false
public var theme = TerminalTheme()
public init() {}
}
public struct Session: Codable, Sendable, Equatable {
public var restoreOnLaunch = true
public init() {}
}
public var ai = AI()
public var editor = Editor()
public var git = Git()
public var files = Files()
public var terminal = Terminal()
public var session = Session()
public init() {}
public static let defaults = HelderConfig()
}
// MARK: - Tolerant decoding
//
// A key that is missing, null or of the wrong type keeps its default, so a
// sparse or half-broken config.json never throws the whole file away.
extension KeyedDecodingContainer {
fileprivate func value<T: Decodable>(_ key: Key, _ fallback: T) -> T {
(try? decodeIfPresent(T.self, forKey: key)) ?? fallback
}
/// For optional settings, where an explicit `null` means "use the default behaviour".
fileprivate func optional<T: Decodable>(_ key: Key, _ fallback: T?) -> T? {
guard contains(key) else { return fallback }
if (try? decodeNil(forKey: key)) == true { return nil }
return (try? decode(T.self, forKey: key)) ?? fallback
}
}
extension HelderConfig {
private enum CodingKeys: String, CodingKey { case ai, editor, git, files, terminal, session }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = HelderConfig.defaults
ai = c.value(.ai, d.ai)
editor = c.value(.editor, d.editor)
git = c.value(.git, d.git)
files = c.value(.files, d.files)
terminal = c.value(.terminal, d.terminal)
session = c.value(.session, d.session)
}
}
extension HelderConfig.AI {
private enum CodingKeys: String, CodingKey { case command, autoLaunch }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
command = c.value(.command, d.command)
autoLaunch = c.value(.autoLaunch, d.autoLaunch)
}
}
extension HelderConfig.Editor {
private enum CodingKeys: String, CodingKey { case autoSave, tabSize, wordWrap }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
autoSave = c.value(.autoSave, d.autoSave)
tabSize = c.value(.tabSize, d.tabSize)
wordWrap = c.value(.wordWrap, d.wordWrap)
}
}
extension HelderConfig.Git {
private enum CodingKeys: String, CodingKey {
case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
confirmStage = c.value(.confirmStage, d.confirmStage)
confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage)
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
}
}
extension HelderConfig.Files {
private enum CodingKeys: String, CodingKey { case exclude, followGitignore }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
exclude = c.value(.exclude, d.exclude)
followGitignore = c.value(.followGitignore, d.followGitignore)
}
}
extension HelderConfig.Terminal {
private enum CodingKeys: String, CodingKey {
case shell, fontFamily, fontSize, lineHeight, letterSpacing, cursorStyle
case cursorBlink, boldIsBright, scrollback, optionIsMeta, theme
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
shell = c.optional(.shell, d.shell)
fontFamily = c.optional(.fontFamily, d.fontFamily)
fontSize = c.optional(.fontSize, d.fontSize)
lineHeight = c.value(.lineHeight, d.lineHeight)
letterSpacing = c.value(.letterSpacing, d.letterSpacing)
cursorStyle = c.value(.cursorStyle, d.cursorStyle)
cursorBlink = c.value(.cursorBlink, d.cursorBlink)
boldIsBright = c.value(.boldIsBright, d.boldIsBright)
scrollback = c.value(.scrollback, d.scrollback)
optionIsMeta = c.value(.optionIsMeta, d.optionIsMeta)
theme = c.value(.theme, d.theme)
}
/// Writes explicit nulls, because config.default.json documents every key.
public func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(shell, forKey: .shell)
try c.encode(fontFamily, forKey: .fontFamily)
try c.encode(fontSize, forKey: .fontSize)
try c.encode(lineHeight, forKey: .lineHeight)
try c.encode(letterSpacing, forKey: .letterSpacing)
try c.encode(cursorStyle, forKey: .cursorStyle)
try c.encode(cursorBlink, forKey: .cursorBlink)
try c.encode(boldIsBright, forKey: .boldIsBright)
try c.encode(scrollback, forKey: .scrollback)
try c.encode(optionIsMeta, forKey: .optionIsMeta)
try c.encode(theme, forKey: .theme)
}
}
extension HelderConfig.Session {
private enum CodingKeys: String, CodingKey { case restoreOnLaunch }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
restoreOnLaunch = c.value(.restoreOnLaunch, Self().restoreOnLaunch)
}
}
extension TerminalTheme {
private enum CodingKeys: String, CodingKey {
case background, foreground, cursor, cursorAccent, selectionBackground, selectionInactiveBackground
case black, red, green, yellow, blue, magenta, cyan, white
case brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite
}
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = Self()
background = c.value(.background, d.background)
foreground = c.value(.foreground, d.foreground)
cursor = c.value(.cursor, d.cursor)
cursorAccent = c.value(.cursorAccent, d.cursorAccent)
selectionBackground = c.value(.selectionBackground, d.selectionBackground)
selectionInactiveBackground = c.value(.selectionInactiveBackground, d.selectionInactiveBackground)
black = c.value(.black, d.black)
red = c.value(.red, d.red)
green = c.value(.green, d.green)
yellow = c.value(.yellow, d.yellow)
blue = c.value(.blue, d.blue)
magenta = c.value(.magenta, d.magenta)
cyan = c.value(.cyan, d.cyan)
white = c.value(.white, d.white)
brightBlack = c.value(.brightBlack, d.brightBlack)
brightRed = c.value(.brightRed, d.brightRed)
brightGreen = c.value(.brightGreen, d.brightGreen)
brightYellow = c.value(.brightYellow, d.brightYellow)
brightBlue = c.value(.brightBlue, d.brightBlue)
brightMagenta = c.value(.brightMagenta, d.brightMagenta)
brightCyan = c.value(.brightCyan, d.brightCyan)
brightWhite = c.value(.brightWhite, d.brightWhite)
}
}
@@ -0,0 +1,27 @@
import Foundation
public enum ProjectTitle {
/// `APP_NAME` from a project's `.env` text, unquoted; nil when absent or empty. The last assignment wins.
public static func appName(fromEnv contents: String) -> String? {
var raw: String?
for line in contents.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
if trimmed.hasPrefix("#") { continue }
guard trimmed.hasPrefix("APP_NAME") else { continue }
let rest = trimmed.dropFirst("APP_NAME".count).drop(while: { $0 == " " || $0 == "\t" })
guard rest.first == "=" else { continue }
raw = String(rest.dropFirst())
}
guard var value = raw?.trimmingCharacters(in: .whitespaces) else { return nil }
if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first {
value = String(value.dropFirst().dropLast())
}
value = value.trimmingCharacters(in: .whitespaces)
return value.isEmpty ? nil : value
}
/// The title a window shows: `APP_NAME` when the project sets one, else the folder name.
public static func title(folderName: String, envContents: String?) -> String {
envContents.flatMap(appName(fromEnv:)) ?? folderName
}
}
+122
View File
@@ -0,0 +1,122 @@
import Foundation
/// One line of a unified diff: unchanged, removed or added.
public enum DiffSign: String, Sendable, Equatable {
case same = " "
case removed = "-"
case added = "+"
}
public struct DiffRow: Sendable, Equatable {
public var sign: DiffSign
/// 1-based line number in the original; nil for an added line.
public var oldNo: Int?
/// 1-based line number in the updated text; nil for a removed line.
public var newNo: Int?
public var text: String
public init(sign: DiffSign, oldNo: Int?, newNo: Int?, text: String) {
self.sign = sign
self.oldNo = oldNo
self.newNo = newNo
self.text = text
}
}
public enum LineMark: String, Sendable, Equatable {
case added
case removed
}
/// One line of one side of the diff, with its 1-based number in that side.
public struct SideLine: Sendable, Equatable {
public var no: Int
public var text: String
public var mark: LineMark?
public init(no: Int, text: String, mark: LineMark? = nil) {
self.no = no
self.text = text
self.mark = mark
}
}
/// A row of the side-by-side view; a nil side is the filler opposite an unpaired add or remove.
public struct SplitRow: Sendable, Equatable {
public var left: SideLine?
public var right: SideLine?
public init(left: SideLine?, right: SideLine?) {
self.left = left
self.right = right
}
}
/// Everything the Actual view and the Diff need, derived from one (original, updated) pair.
public struct Diff: Sendable, Equatable {
public var rows: [DiffRow]
public var left: [SideLine]
public var right: [SideLine]
public var split: [SplitRow]
public var added: Int
public var removed: Int
public var isDeletedFile: Bool
public var isAddedFile: Bool
public var original: String
public var updated: String
/// Built from a change over the diff cap: the texts are empty, not the file.
public var isTooBig = false
public init(
rows: [DiffRow], left: [SideLine], right: [SideLine], split: [SplitRow],
added: Int, removed: Int, isDeletedFile: Bool, isAddedFile: Bool,
original: String, updated: String
) {
self.rows = rows
self.left = left
self.right = right
self.split = split
self.added = added
self.removed = removed
self.isDeletedFile = isDeletedFile
self.isAddedFile = isAddedFile
self.original = original
self.updated = updated
}
}
/// Which half of a file's changes a Diff shows: HEAD vs index, or index vs disk.
/// Absent (nil) means the whole file, HEAD vs disk, which Actual always shows.
public enum DiffSide: String, Codable, Sendable, Equatable {
case staged
case unstaged
}
/// How a line is painted in the read-only editor panes.
public enum ViewLineStyle: String, Sendable, Equatable {
/// Full tint: a line the change added (Actual view).
case added
}
/// Where a removed run's rule sits, since removed lines own no line of their own in Actual.
public enum GapEdge: String, Sendable, Equatable {
case above
case below
}
/// A line descriptor for the editor panes.
public struct ViewLine: Sendable, Equatable {
public var no: Int?
public var text: String
public var sign: DiffSign?
public var style: ViewLineStyle?
public var gap: GapEdge?
public init(no: Int?, text: String, sign: DiffSign? = nil, style: ViewLineStyle? = nil, gap: GapEdge? = nil) {
self.no = no
self.text = text
self.sign = sign
self.style = style
self.gap = gap
}
}
+40
View File
@@ -0,0 +1,40 @@
import Foundation
public enum DiffViews {
/// The Actual view: the updated file with added lines tinted.
///
/// A run of removed lines with no added line beside it puts its rule on the edge of
/// the next surviving line (`gap: .above`), or under the last line when the run ends
/// the file (`gap: .below`). A run that also added lines gets no gap rule.
public static func actual(_ diff: Diff) -> [ViewLine] {
var above = Set<Int>()
var endsWithRemoval = false
var removed = 0, added = 0
func flush(nextNew: Int?) {
if removed > 0 && added == 0 {
if let nextNew { above.insert(nextNew) } else { endsWithRemoval = true }
}
removed = 0
added = 0
}
for row in diff.rows {
switch row.sign {
case .removed: removed += 1
case .added: added += 1
case .same: flush(nextNew: row.newNo)
}
}
flush(nextNew: nil)
let last = diff.right.last?.no
return diff.right.map { line in
let gap: GapEdge? = above.contains(line.no) ? .above : (endsWithRemoval && line.no == last ? .below : nil)
return ViewLine(no: line.no, text: line.text, style: line.mark == .added ? .added : nil, gap: gap)
}
}
/// A plain file with no diff, numbered from 1.
public static func plain(_ text: String) -> [ViewLine] {
LineDiff.droppingTrailingNewline(text).components(separatedBy: "\n").enumerated().map { ViewLine(no: $0.offset + 1, text: $0.element) }
}
}
+205
View File
@@ -0,0 +1,205 @@
import Foundation
public enum LineDiff {
/// Largest LCS matrix built in one go (4M cells); bigger regions are split on unique anchor lines.
public static let maxCells = 4_000_000
/// "" is zero lines, and one trailing "\n" is dropped.
public static func lines(_ text: String) -> [String] {
if text.isEmpty { return [] }
return droppingTrailingNewline(text).components(separatedBy: "\n")
}
/// Drops one final "\n". `hasSuffix("\n")` misses it after a "\r", where "\r\n" is one Character.
static func droppingTrailingNewline(_ text: String) -> String {
text.utf8.last == 10 ? String(decoding: text.utf8.dropLast(), as: UTF8.self) : text
}
/// Line-based LCS diff of two texts into rows, both sides and aligned split rows.
///
/// On a tie the DP takes the deletion before the addition; flipping that reorders
/// removed and added lines in every view.
public static func build(original: String, updated: String, status: GitStatus? = nil) -> Diff {
let a = lines(original)
let b = lines(updated)
let (ia, ib) = intern(a, b)
var ops: [Op] = []
ops.reserveCapacity(max(a.count, b.count))
region(ia, ib, 0, ia.count, 0, ib.count, &ops)
var rows: [DiffRow] = []
rows.reserveCapacity(ops.count)
var removedLines = Set<Int>(), addedLines = Set<Int>()
for op in ops {
switch op {
case let .same(i, j): rows.append(DiffRow(sign: .same, oldNo: i + 1, newNo: j + 1, text: a[i]))
case let .del(i):
rows.append(DiffRow(sign: .removed, oldNo: i + 1, newNo: nil, text: a[i]))
removedLines.insert(i)
case let .add(j):
rows.append(DiffRow(sign: .added, oldNo: nil, newNo: j + 1, text: b[j]))
addedLines.insert(j)
}
}
let left = a.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: removedLines.contains($0.offset) ? .removed : nil) }
let right = b.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: addedLines.contains($0.offset) ? .added : nil) }
return Diff(
rows: rows, left: left, right: right, split: splitRows(ops, a, b),
added: addedLines.count, removed: removedLines.count,
isDeletedFile: status == .deleted, isAddedFile: status == .added,
original: original, updated: updated
)
}
private enum Op {
case same(Int, Int)
case del(Int)
case add(Int)
}
/// Maps every distinct line to an integer so the DP compares ints, not strings.
private static func intern(_ a: [String], _ b: [String]) -> ([Int], [Int]) {
var ids: [String: Int] = [:]
func id(_ line: String) -> Int {
if let known = ids[line] { return known }
let next = ids.count
ids[line] = next
return next
}
return (a.map(id), b.map(id))
}
/// Removed and added runs between two unchanged lines pair up side by side.
private static func splitRows(_ ops: [Op], _ a: [String], _ b: [String]) -> [SplitRow] {
var split: [SplitRow] = []
var removed: [SideLine] = [], added: [SideLine] = []
func flush() {
for k in 0..<max(removed.count, added.count) {
split.append(SplitRow(left: k < removed.count ? removed[k] : nil, right: k < added.count ? added[k] : nil))
}
removed.removeAll(keepingCapacity: true)
added.removeAll(keepingCapacity: true)
}
for op in ops {
switch op {
case let .same(i, j):
flush()
split.append(SplitRow(left: SideLine(no: i + 1, text: a[i]), right: SideLine(no: j + 1, text: b[j])))
case let .del(i): removed.append(SideLine(no: i + 1, text: a[i], mark: .removed))
case let .add(j): added.append(SideLine(no: j + 1, text: b[j], mark: .added))
}
}
flush()
return split
}
private static func region(_ a: [Int], _ b: [Int], _ a0In: Int, _ a1In: Int, _ b0In: Int, _ b1In: Int, _ ops: inout [Op]) {
var a0 = a0In, a1 = a1In, b0 = b0In, b1 = b1In
while a0 < a1 && b0 < b1 && a[a0] == b[b0] {
ops.append(.same(a0, b0))
a0 += 1
b0 += 1
}
var tail: [Op] = []
while a1 > a0 && b1 > b0 && a[a1 - 1] == b[b1 - 1] {
a1 -= 1
b1 -= 1
tail.append(.same(a1, b1))
}
let n = a1 - a0, m = b1 - b0
func replaceAll() {
for i in a0..<a1 { ops.append(.del(i)) }
for j in b0..<b1 { ops.append(.add(j)) }
}
if n == 0 || m == 0 {
replaceAll()
} else if n * m <= maxCells {
dynamicProgram(a, b, a0, a1, b0, b1, &ops)
} else {
let pins = anchors(a, b, a0, a1, b0, b1)
if pins.isEmpty {
replaceAll()
} else {
var ai = a0, bi = b0
for (ax, bx) in pins {
region(a, b, ai, ax, bi, bx, &ops)
ops.append(.same(ax, bx))
ai = ax + 1
bi = bx + 1
}
region(a, b, ai, a1, bi, b1, &ops)
}
}
ops.append(contentsOf: tail.reversed())
}
private static func dynamicProgram(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int, _ ops: inout [Op]) {
let n = a1 - a0, m = b1 - b0
let width = m + 1
var dp = [Int32](repeating: 0, count: (n + 1) * width)
for i in stride(from: n - 1, through: 0, by: -1) {
for j in stride(from: m - 1, through: 0, by: -1) {
dp[i * width + j] = a[a0 + i] == b[b0 + j]
? dp[(i + 1) * width + j + 1] + 1
: max(dp[(i + 1) * width + j], dp[i * width + j + 1])
}
}
var i = 0, j = 0
while i < n && j < m {
if a[a0 + i] == b[b0 + j] {
ops.append(.same(a0 + i, b0 + j))
i += 1
j += 1
} else if dp[(i + 1) * width + j] >= dp[i * width + j + 1] {
ops.append(.del(a0 + i))
i += 1
} else {
ops.append(.add(b0 + j))
j += 1
}
}
while i < n { ops.append(.del(a0 + i)); i += 1 }
while j < m { ops.append(.add(b0 + j)); j += 1 }
}
/// Lines that appear exactly once on each side, in an order both sides share.
private static func anchors(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int) -> [(Int, Int)] {
var countA: [Int: Int] = [:], countB: [Int: Int] = [:], atB: [Int: Int] = [:]
for i in a0..<a1 { countA[a[i], default: 0] += 1 }
for j in b0..<b1 {
countB[b[j], default: 0] += 1
atB[b[j]] = j
}
var pairs: [(Int, Int)] = []
for i in a0..<a1 where countA[a[i]] == 1 && countB[a[i]] == 1 {
if let j = atB[a[i]] { pairs.append((i, j)) }
}
return longestRun(pairs)
}
/// Longest strictly increasing subsequence over the b-index of each pair.
private static func longestRun(_ pairs: [(Int, Int)]) -> [(Int, Int)] {
var tails: [Int] = []
var prev = [Int](repeating: -1, count: pairs.count)
for k in pairs.indices {
let v = pairs[k].1
var lo = 0, hi = tails.count
while lo < hi {
let mid = (lo + hi) / 2
if pairs[tails[mid]].1 < v { lo = mid + 1 } else { hi = mid }
}
prev[k] = lo > 0 ? tails[lo - 1] : -1
if lo == tails.count { tails.append(k) } else { tails[lo] = k }
}
var out: [(Int, Int)] = []
var k = tails.last ?? -1
while k >= 0 {
out.append(pairs[k])
k = prev[k]
}
return out.reversed()
}
}
+21
View File
@@ -0,0 +1,21 @@
import Foundation
/// The view the editor shows for the open file. Raw values are stored in sessions, so `.actual` stays "updated".
///
/// `.diff` is the full-screen side-by-side overlay, not a pane mode.
public enum ViewMode: String, Codable, Sendable, CaseIterable {
/// The live buffer with changed lines marked.
case actual = "updated"
case diff
/// An unchanged file: the plain editable buffer.
case code
/// Rendered Markdown.
case preview
public init(_ mode: DefaultDiffMode) {
switch mode {
case .updated: self = .actual
case .diff: self = .diff
}
}
}
@@ -0,0 +1,126 @@
import Foundation
/// What was right-clicked.
public enum ContextTarget: Sendable, Equatable {
/// A line or selection in the editor; `code` is the selected text, if any.
case editor(reference: AgentReference, code: String?)
case file(path: String)
case directory(path: String)
/// A git row; the row carries its own half, since one file can have two rows.
case gitRow(path: String, staged: Bool)
/// The empty space under the tree: the project folder itself.
case projectRoot
case terminal(TerminalKind, hasSelection: Bool)
public var path: String {
switch self {
case let .editor(reference, _): reference.path
case let .file(path), let .directory(path), let .gitRow(path, _): path
case .projectRoot, .terminal: ""
}
}
}
public enum ContextAction: Sendable, Equatable {
/// Opens the pass-on prompt; with code for an editor selection.
case passOnReference(String, code: String?)
case copyReference(String)
case passOnFileName(String)
case copyFileName(String)
case newFile(inDirectory: String)
case newFolder(inDirectory: String)
case stage(String)
case unstage(String)
case openDiff(String)
case discard(String)
case rename(String, isDirectory: Bool)
case revealInFinder(String)
case delete(String, isDirectory: Bool)
case copyTerminalSelection(TerminalKind)
case pasteIntoTerminal(TerminalKind)
/// Destructive items read in amber-deep.
public var isDestructive: Bool {
switch self {
case .discard, .delete: true
default: false
}
}
}
/// A menu entry, or a separator between groups.
public enum ContextMenuEntry: Sendable, Equatable {
case action(ContextAction, label: String)
case separator
}
public enum ContextActions {
/// The header line of the menu: the reference, or `project/` for the root.
public static func header(for target: ContextTarget, projectName: String) -> String {
switch target {
case let .editor(reference, _): reference.description
case let .directory(path): path + "/"
case let .file(path), let .gitRow(path, _): path
case .projectRoot: projectName + "/"
case .terminal: ""
}
}
/// Menu entries: every "Pass on …" item has its "Copy …" twin directly below.
public static func entries(for target: ContextTarget) -> [ContextMenuEntry] {
switch target {
case let .editor(reference, code):
let ref = reference.description
let hasCode = !(code ?? "").isEmpty
return [
.action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"),
.action(.copyReference(ref), label: "Copy reference"),
]
case .projectRoot:
return [
.action(.newFile(inDirectory: ""), label: "New file"),
.action(.revealInFinder(""), label: "Show in Finder"),
]
case let .file(path):
return fileHead(path) + [
.separator,
.action(.rename(path, isDirectory: false), label: "Rename file"),
.action(.revealInFinder(path), label: "Show in Finder"),
.action(.delete(path, isDirectory: false), label: "Delete file"),
]
case let .directory(path):
let ref = path + "/"
return [
.action(.passOnReference(ref, code: nil), label: "Pass on reference"),
.action(.copyReference(ref), label: "Copy reference"),
.separator,
.action(.newFile(inDirectory: path), label: "New file"),
.action(.newFolder(inDirectory: path), label: "New folder"),
.separator,
.action(.rename(path, isDirectory: true), label: "Rename folder"),
.action(.revealInFinder(path), label: "Show in Finder"),
.action(.delete(path, isDirectory: true), label: "Delete folder"),
]
case let .terminal(kind, hasSelection):
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
+ [.action(.pasteIntoTerminal(kind), label: "Paste")]
case let .gitRow(path, staged):
return fileHead(path) + [
.separator,
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
.action(.openDiff(path), label: "Open diff"),
.action(.discard(path), label: "Discard changes"),
]
}
}
private static func fileHead(_ path: String) -> [ContextMenuEntry] {
let name = PathUtils.basename(path)
return [
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
.action(.copyReference(path), label: "Copy reference"),
.action(.passOnFileName(name), label: "Pass on file name"),
.action(.copyFileName(name), label: "Copy file name"),
]
}
}
+202
View File
@@ -0,0 +1,202 @@
import Foundation
public enum FileLimits {
/// Files above this size are left out of the content index.
public static let maxIndexedFileBytes = 300_000
public static let maxIndexedFiles = 6000
public static let maxImageBytes = 25_000_000
/// Git reads a file above this size as having no text, so one dump or lock file cannot stall the column.
public static let maxDiffFileBytes = 1_000_000
/// How deep the fallback directory walk goes.
public static let maxWalkDepth = 12
/// A NUL byte in the first 8000 bytes marks a file as binary, like git does.
public static func looksBinary(_ data: Data) -> Bool {
data.prefix(8000).contains(0)
}
public static let imageMimeTypes: [String: String] = [
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg",
"gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml", "bmp": "image/bmp",
"ico": "image/x-icon", "avif": "image/avif", "apng": "image/apng",
]
}
public enum IgnoreRules {
/// Folders the fallback walk and the watcher never enter.
public static let walkIgnoredNames: Set<String> = [
"node_modules", ".git", "out", "dist", "build", ".next", ".nuxt",
".cache", "coverage", "vendor", ".idea", ".vscode", ".helder", ".turbo",
]
/// Always passed to ripgrep as `!glob`, on top of gitignore and `files.exclude`.
/// `.DS_Store` is here because `followGitignore` defaults to false (rg runs with --no-ignore).
public static let ripgrepBaseIgnore = [
"node_modules", ".git", "out", "dist", "build", ".cache",
"vendor", "coverage", ".helder", ".next", ".nuxt", ".turbo", ".idea", ".vscode",
".DS_Store",
]
/// Declarations are indexed inside `vendor/` too, so framework classes stay clickable.
public static let symbolDeclarationIgnore = ripgrepBaseIgnore.filter { $0 != "vendor" && $0 != ".DS_Store" }
/// References skip `vendor/`: nobody wants to read how a framework uses a class.
public static let symbolReferenceIgnore = ripgrepBaseIgnore.filter { $0 != ".DS_Store" }
/// True for a name the fallback walk skips.
public static func isWalkIgnored(_ name: String) -> Bool {
walkIgnoredNames.contains(name) || name == ".DS_Store"
}
/// True when any segment of a relative path is an ignored folder; the watcher drops such events.
public static func isWatchIgnored(_ relativePath: String) -> Bool {
relativePath.split(separator: "/").contains { walkIgnoredNames.contains(String($0)) }
}
/// Framework caches rewritten on every request or test run; watching them refreshes the project in a loop.
public static let watchIgnoredPrefixes = [
"storage/framework/", "bootstrap/cache/", ".phpunit.result.cache", ".phpunit.cache/",
]
/// `isWatchIgnored`, plus the framework caches and the project's `files.exclude` globs.
public static func isWatchIgnored(_ relativePath: String, exclude: [String]) -> Bool {
if isWatchIgnored(relativePath) { return true }
if watchIgnoredPrefixes.contains(where: { relativePath == $0 || relativePath.hasPrefix($0) || $0 == relativePath + "/" }) {
return true
}
return exclude.contains { !$0.isEmpty && globMatches($0, path: relativePath) }
}
/// The `--glob !x` pairs plus `--no-ignore` that make ripgrep honour the project's file settings.
public static func ripgrepArguments(files: HelderConfig.Files, base: [String] = ripgrepBaseIgnore) -> [String] {
var args: [String] = []
for glob in base { args += ["--glob", "!" + glob] }
for glob in files.exclude where !glob.isEmpty { args += ["--glob", "!" + glob] }
if !files.followGitignore { args.append("--no-ignore") }
return args
}
/// Gitignore-style glob match of a relative path, with ripgrep's `--glob` semantics.
///
/// A pattern without a slash matches a basename at any depth; `**` crosses folders, `*` and `?`
/// stop at a slash. A matching folder matches everything under it, as in ripgrep.
public static func globMatches(_ glob: String, path: String) -> Bool {
var pattern = Substring(glob)
while pattern.hasSuffix("/") { pattern = pattern.dropLast() }
let rooted = pattern.hasPrefix("/")
if rooted { pattern = pattern.dropFirst() }
guard !pattern.isEmpty else { return false }
let anchored = rooted || pattern.contains("/")
let candidates = PathUtils.ancestors(path) + [path]
for alternative in expandBraces(String(pattern)) {
let chars = Array(alternative)
for candidate in candidates {
let subject = Array(anchored ? candidate : PathUtils.basename(candidate))
var matcher = WildcardMatcher(pattern: chars, subject: subject)
if matcher.matches() { return true }
}
}
return false
}
/// `{a,b}` alternation expanded into plain patterns; nested braces expand recursively.
static func expandBraces(_ pattern: String) -> [String] {
let chars = Array(pattern)
guard let open = chars.firstIndex(of: "{") else { return [pattern] }
var depth = 0
var parts: [String] = []
var current = ""
for k in (open + 1)..<chars.count {
let c = chars[k]
if c == "{" { depth += 1 }
if c == "}" {
if depth == 0 {
parts.append(current)
let head = String(chars[..<open]), rest = String(chars[(k + 1)...])
return parts.flatMap { expandBraces(head + $0 + rest) }
}
depth -= 1
}
if c == "," && depth == 0 {
parts.append(current)
current = ""
} else {
current.append(c)
}
}
return [pattern]
}
}
/// Glob matcher: `**` crosses folders, `*` and `?` stop at a slash, `[...]` is a character class.
private struct WildcardMatcher {
let pattern: [Character]
let subject: [Character]
private var memo: [Bool?]
init(pattern: [Character], subject: [Character]) {
self.pattern = pattern
self.subject = subject
memo = Array(repeating: nil, count: (pattern.count + 1) * (subject.count + 1))
}
mutating func matches() -> Bool { match(0, 0) }
private mutating func match(_ p: Int, _ s: Int) -> Bool {
let key = p * (subject.count + 1) + s
if let known = memo[key] { return known }
let result = compute(p, s)
memo[key] = result
return result
}
private mutating func compute(_ p: Int, _ s: Int) -> Bool {
guard p < pattern.count else { return s == subject.count }
switch pattern[p] {
case "*":
if p + 1 < pattern.count && pattern[p + 1] == "*" {
let afterStars = p + 2
if afterStars < pattern.count && pattern[afterStars] == "/" && match(afterStars + 1, s) { return true }
for k in s...subject.count where match(afterStars, k) { return true }
return false
}
var k = s
while true {
if match(p + 1, k) { return true }
if k == subject.count || subject[k] == "/" { return false }
k += 1
}
case "?":
return s < subject.count && subject[s] != "/" && match(p + 1, s + 1)
case "[":
guard s < subject.count, subject[s] != "/", let (hit, next) = classMatch(p, subject[s]) else {
return s < subject.count && subject[s] == "[" && match(p + 1, s + 1)
}
return hit && match(next, s + 1)
case "\\" where p + 1 < pattern.count:
return s < subject.count && subject[s] == pattern[p + 1] && match(p + 2, s + 1)
default:
return s < subject.count && subject[s] == pattern[p] && match(p + 1, s + 1)
}
}
/// Whether `c` is in the class opening at `p`, and the index after it; nil for an unclosed `[`.
private func classMatch(_ p: Int, _ c: Character) -> (Bool, Int)? {
var k = p + 1
let negated = k < pattern.count && (pattern[k] == "!" || pattern[k] == "^")
if negated { k += 1 }
var hit = false
var first = true
while k < pattern.count {
if pattern[k] == "]" && !first { return (hit != negated, k + 1) }
first = false
if k + 2 < pattern.count && pattern[k + 1] == "-" && pattern[k + 2] != "]" {
if pattern[k] <= c && c <= pattern[k + 2] { hit = true }
k += 3
} else {
if pattern[k] == c { hit = true }
k += 1
}
}
return nil
}
}
+125
View File
@@ -0,0 +1,125 @@
import Foundation
public struct FileNode: Sendable, Equatable, Identifiable {
public enum Kind: String, Sendable, Equatable {
case directory
case file
}
public var name: String
public var kind: Kind
/// Project-relative, "/"-separated; "" is the project root.
public var path: String
/// nil for files; an empty array for an empty folder.
public var children: [FileNode]?
public var id: String { path }
public var isDirectory: Bool { kind == .directory }
public var isHidden: Bool { name.hasPrefix(".") }
public init(name: String, kind: Kind, path: String, children: [FileNode]? = nil) {
self.name = name
self.kind = kind
self.path = path
self.children = kind == .directory ? (children ?? []) : nil
}
}
/// One visible row of the Explorer, in render order.
public struct TreeRow: Sendable, Equatable {
public var path: String
public var kind: FileNode.Kind
/// 0 for a top-level entry; the Explorer indents 16px per level.
public var depth: Int
public init(path: String, kind: FileNode.Kind, depth: Int) {
self.path = path
self.kind = kind
self.depth = depth
}
}
public enum FileTree {
/// Nested tree from relative file paths: folders first, then files, each sorted by name.
///
/// `emptyDirs` adds the folders that hold no file, which `rg --files` never lists.
/// Names sort case-insensitively, not in byte order.
public static func build(rootName: String, paths: [String], emptyDirs: [String] = []) -> FileNode {
var folders: [String: Set<String>] = ["": []]
var files: [String: Set<String>] = [:]
func ensureFolder(_ parts: ArraySlice<Substring>) -> String {
var parent = ""
for part in parts {
let path = PathUtils.join(parent, String(part))
if folders[path] == nil {
folders[path] = []
folders[parent, default: []].insert(path)
}
parent = path
}
return parent
}
for path in paths {
let parts = path.split(separator: "/")
guard let name = parts.last else { continue }
let parent = ensureFolder(parts.dropLast())
files[parent, default: []].insert(PathUtils.join(parent, String(name)))
}
for dir in emptyDirs {
_ = ensureFolder(dir.split(separator: "/")[...])
}
func node(folder path: String, name: String) -> FileNode {
let subfolders = (folders[path] ?? []).map { node(folder: $0, name: PathUtils.basename($0)) }
let leaves = (files[path] ?? []).map { FileNode(name: PathUtils.basename($0), kind: .file, path: $0) }
return FileNode(name: name, kind: .directory, path: path, children: sortedByName(subfolders) + sortedByName(leaves))
}
return node(folder: "", name: rootName)
}
/// Case-insensitive, locale-aware order.
static func sortedByName(_ nodes: [FileNode]) -> [FileNode] {
nodes.sorted { $0.name.compare($1.name, locale: sortLocale) == .orderedAscending }
}
private static let sortLocale = Locale(identifier: "en_US")
/// The node at a relative path ("" is the root), or nil.
public static func find(_ path: String, in tree: FileNode) -> FileNode? {
if path.isEmpty { return tree }
var node = tree
for part in path.split(separator: "/") {
guard let next = node.children?.first(where: { $0.name == part }) else { return nil }
node = next
}
return node
}
/// A copy of the tree with the children of the node at `path` replaced; unchanged when the path is absent.
public static func replacingChildren(of path: String, with children: [FileNode], in tree: FileNode) -> FileNode {
if tree.path == path {
var copy = tree
copy.children = children
return copy
}
guard let kids = tree.children, path.hasPrefix(tree.path) else { return tree }
var copy = tree
copy.children = kids.map { replacingChildren(of: path, with: children, in: $0) }
return copy
}
/// The visible rows under the root, honouring expanded folders and the hidden-files toggle.
public static func visibleRows(_ tree: FileNode, expanded: Set<String>, showHidden: Bool) -> [TreeRow] {
var rows: [TreeRow] = []
func walk(_ node: FileNode, depth: Int) {
for child in node.children ?? [] where showHidden || !child.isHidden {
rows.append(TreeRow(path: child.path, kind: child.kind, depth: depth))
if child.isDirectory && expanded.contains(child.path) { walk(child, depth: depth + 1) }
}
}
walk(tree, depth: 0)
return rows
}
}
+100
View File
@@ -0,0 +1,100 @@
import Foundation
/// A highlighter grammar.
public enum Language: String, Sendable, CaseIterable {
case php, javascript, jsx, typescript, tsx, python, markup, css, json, markdown, bash, yaml
}
/// One of the four badge fills; the UI maps each to a Palette colour.
public enum BadgeTint: String, Sendable {
case purple
case amber
case teal
case grey
}
/// The small extension chip in rows and headers: ink text on a tinted fill.
public struct FileBadge: Sendable, Equatable {
public var text: String
public var tint: BadgeTint
public init(_ text: String, _ tint: BadgeTint) {
self.text = text
self.tint = tint
}
}
public enum FileType {
/// Lowercased extension; any `.env*` file reads as `env`.
public static func ext(_ path: String) -> String {
let base = PathUtils.basename(path)
if base.hasPrefix(".env") { return "env" }
guard let dot = base.lastIndex(of: ".") else { return "" }
return base[base.index(after: dot)...].lowercased()
}
private static let languages: [String: Language] = [
"php": .php, "js": .javascript, "mjs": .javascript, "cjs": .javascript,
"jsx": .jsx, "ts": .typescript, "tsx": .tsx, "py": .python,
"html": .markup, "xml": .markup, "svg": .markup, "vue": .markup,
"css": .css, "scss": .css, "json": .json, "md": .markdown,
"sh": .bash, "bash": .bash, "yml": .yaml, "yaml": .yaml, "env": .bash,
]
public static func language(for path: String) -> Language? {
languages[ext(path)]
}
public static func isMarkdown(_ path: String) -> Bool {
language(for: path) == .markdown
}
private static let labels: [String: String] = [
"php": "PHP", "js": "JavaScript", "mjs": "JavaScript", "ts": "TypeScript",
"tsx": "TypeScript", "jsx": "JavaScript", "py": "Python", "html": "HTML",
"css": "CSS", "json": "JSON", "md": "Markdown", "sh": "Shell", "env": "Dotenv",
"yml": "YAML", "yaml": "YAML",
]
/// The status-bar language name.
public static func languageLabel(for path: String) -> String {
let e = ext(path)
return labels[e] ?? (e.isEmpty ? "Plain Text" : e.uppercased())
}
public static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "apng", "jfif"]
/// Files the viewer shows as a picture instead of text.
public static func isImage(_ path: String) -> Bool {
imageExtensions.contains(ext(path))
}
/// Files that never open: the viewer flashes "Too big." instead.
public static let tooBigNames: Set<String> = ["composer.lock"]
private static let badges: [String: FileBadge] = [
"php": FileBadge("php", .purple), "blade": FileBadge("php", .purple),
"ts": FileBadge("ts", .purple), "tsx": FileBadge("tsx", .purple), "vue": FileBadge("vue", .purple),
"js": FileBadge("js", .amber), "mjs": FileBadge("js", .amber), "cjs": FileBadge("js", .amber),
"jsx": FileBadge("jsx", .amber), "json": FileBadge("json", .amber),
"yml": FileBadge("yml", .amber), "yaml": FileBadge("yml", .amber),
"css": FileBadge("css", .teal), "scss": FileBadge("scss", .teal), "pcss": FileBadge("css", .teal),
"html": FileBadge("html", .teal), "sh": FileBadge("sh", .teal), "env": FileBadge("env", .teal),
"py": FileBadge("py", .teal), "sql": FileBadge("sql", .teal),
"md": FileBadge("md", .grey), "txt": FileBadge("txt", .grey),
"lock": FileBadge("lock", .grey), "svg": FileBadge("svg", .grey),
]
private static let nameBadges: [String: FileBadge] = [
"composer.json": FileBadge("json", .purple),
"package.json": FileBadge("json", .amber),
".env": FileBadge("env", .teal),
]
/// The badge for a path; unknown extensions get a grey chip with up to four letters, or "·".
public static func badge(for path: String) -> FileBadge {
if let named = nameBadges[PathUtils.basename(path)] { return named }
let e = ext(path)
return badges[e] ?? FileBadge(e.isEmpty ? "·" : String(e.prefix(4)), .grey)
}
}
+63
View File
@@ -0,0 +1,63 @@
import Foundation
public enum PathUtils {
public static func basename(_ path: String) -> String {
path.split(separator: "/").last.map(String.init) ?? ""
}
/// Everything before the last segment; "" for a top-level entry.
public static func dirname(_ path: String) -> String {
guard let slash = path.lastIndex(of: "/") else { return "" }
return String(path[..<slash])
}
/// `dir/name`, or just `name` when `dir` is the root.
public static func join(_ dir: String, _ name: String) -> String {
dir.isEmpty ? name : dir + "/" + name
}
/// Every ancestor folder of a path, outermost first: `a/b/c.txt` → [a, a/b].
public static func ancestors(_ path: String) -> [String] {
let parts = path.split(separator: "/").map(String.init)
guard parts.count > 1 else { return [] }
return (1..<parts.count).map { parts[0..<$0].joined(separator: "/") }
}
/// True when any segment is a dotfile or dot-folder.
public static func isHidden(_ path: String) -> Bool {
path.split(separator: "/").contains { $0.hasPrefix(".") }
}
/// True for `path` itself and, when it is a folder, for everything under it.
public static func isInside(_ candidate: String, _ path: String, isDirectory: Bool) -> Bool {
candidate == path || (isDirectory && candidate.hasPrefix(path + "/"))
}
/// Carries a path over a rename of `from` to `to`; folders move everything under them.
public static func remap(_ candidate: String, from: String, to: String, isDirectory: Bool) -> String {
if candidate == from { return to }
if isDirectory && candidate.hasPrefix(from + "/") { return to + candidate.dropFirst(from.count) }
return candidate
}
/// A cleaned basename for a rename, or nil when it is empty, has a slash, or is `.`/`..`.
public static func validatedName(_ name: String) -> String? {
var clean = name.trimmingCharacters(in: .whitespacesAndNewlines)
while clean.hasSuffix("/") { clean.removeLast() }
if clean.isEmpty || clean.contains("/") || clean == "." || clean == ".." { return nil }
return clean
}
/// The relative path a create-in-folder action targets; leading and trailing slashes are dropped.
public static func newEntryPath(inDirectory dir: String, name: String) -> String {
var clean = Substring(name)
while clean.hasPrefix("/") { clean = clean.dropFirst() }
while clean.hasSuffix("/") { clean = clean.dropLast() }
return join(dir, String(clean))
}
/// A reference to a project entry: folders end in a slash.
public static func reference(_ path: String, isDirectory: Bool) -> String {
isDirectory ? path + "/" : path
}
}
@@ -0,0 +1,93 @@
import Foundation
public enum GitDerivation {
/// Turns a snapshot into rows plus per-row and per-file diffs; nil means "not a repository".
///
/// Per file, HEAD comes from the staged row's original and disk from the unstaged row's
/// updated; with one row both come from it. The unstaged row owns the file-level status,
/// so a file staged as modified but deleted on disk reads as deleted.
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
guard let snapshot else { return .empty }
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true)
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
var tooBig = Set<String>()
for change in snapshot.changes {
var diff = LineDiff.build(original: change.original, updated: change.updated, status: change.status)
diff.isTooBig = change.isTooBig
if change.isTooBig { tooBig.insert(change.path) }
let row = Change(path: change.path, status: change.status, added: diff.added, removed: diff.removed,
staged: change.staged, originalPath: change.originalPath)
state.rowDiffs[row.id] = diff
state.changes.append(row)
if change.staged { state.stagedPaths.insert(change.path) }
if let previous = wholeFile[change.path] {
wholeFile[change.path] = change.staged
? (change.original, previous.disk, previous.status, previous.rows + 1, previous.rowID)
: (previous.head, change.updated, change.status, previous.rows + 1, previous.rowID)
} else {
wholeFile[change.path] = (change.original, change.updated, change.status, 1, row.id)
}
}
for (path, whole) in wholeFile {
var diff = whole.rows == 1
? state.rowDiffs[whole.rowID]
: LineDiff.build(original: whole.head, updated: whole.disk, status: whole.status)
diff?.isTooBig = tooBig.contains(path)
state.fileDiffs[path] = diff
}
return state
}
}
/// Rows of one folder in the Source Control list.
public struct ChangeGroup: Sendable, Equatable {
/// Folder path; "" is the project root.
public var dir: String
public var rows: [Change]
public init(dir: String, rows: [Change]) {
self.dir = dir
self.rows = rows
}
}
public enum SourceControlText {
/// Groups rows by folder in order of first appearance; keyboard navigation walks this same order.
public static func groupByDir(_ list: [Change]) -> [ChangeGroup] {
var groups: [ChangeGroup] = []
var indexByDir: [String: Int] = [:]
for change in list {
let dir = PathUtils.dirname(change.path)
if let index = indexByDir[dir] {
groups[index].rows.append(change)
} else {
indexByDir[dir] = groups.count
groups.append(ChangeGroup(dir: dir, rows: [change]))
}
}
return groups
}
/// The row order of the list: staged groups first, then unstaged, each folder by folder.
public static func navigationOrder(_ changes: [Change]) -> [Change] {
let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows)
let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows)
return staged + unstaged
}
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
public static func normalizeCommitMessage(_ value: String) -> String {
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
}
public static func pushTooltip(canPush: Bool, ahead: Int) -> String {
if !canPush { return "Nothing to push (⌘P)" }
if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" }
return "Push the branch to remote (⌘P)"
}
/// Git rows under `tests/` or `cypress/` render dimmed.
public static func isTestFile(_ path: String) -> Bool {
path.hasPrefix("tests/") || path.hasPrefix("cypress/")
}
}
+140
View File
@@ -0,0 +1,140 @@
import Foundation
/// The status letter a git row shows. Copies and untracked files read as `A`, conflicts as `M`.
public enum GitStatus: String, Codable, Sendable, CaseIterable {
case added = "A"
case modified = "M"
case deleted = "D"
case renamed = "R"
case unmerged = "U"
}
/// One file half as `git load` reads it: the text on each side of that half.
public struct GitFileChange: Sendable, Equatable {
public var path: String
public var status: GitStatus
/// True for the HEAD→index half, false for the index→disk half.
public var staged: Bool
public var original: String
public var updated: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
/// A side was over the diff cap, so both texts are left empty.
public var isTooBig: Bool
public init(path: String, status: GitStatus, staged: Bool, original: String, updated: String, originalPath: String? = nil,
isTooBig: Bool = false) {
self.path = path
self.status = status
self.staged = staged
self.original = original
self.updated = updated
self.originalPath = originalPath
self.isTooBig = isTooBig
}
}
/// What one `git status` read of the working tree returns.
public struct GitSnapshot: Sendable, Equatable {
public var branch: String
/// Commits the remote does not have yet; 0 when unknown.
public var ahead: Int
/// True when a push would send something, including a branch without an upstream.
public var canPush: Bool
public var changes: [GitFileChange]
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
}
}
/// A row in the Source Control column. A file staged and then edited again has two rows.
public struct Change: Sendable, Equatable, Identifiable {
/// Row identity; the path alone is not unique (see `staged`).
public var id: String
public var path: String
public var status: GitStatus
public var added: Int
public var removed: Int
public var isDeleted: Bool
public var staged: Bool
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(path: String, status: GitStatus, added: Int, removed: Int, staged: Bool, originalPath: String? = nil) {
self.id = Change.rowID(path: path, staged: staged)
self.path = path
self.status = status
self.added = added
self.removed = removed
self.isDeleted = status == .deleted
self.staged = staged
self.originalPath = originalPath
}
/// `s:path` for the staged half, `w:path` for the working-tree half.
public static func rowID(path: String, staged: Bool) -> String {
(staged ? "s:" : "w:") + path
}
}
/// The git slice of the workspace, derived from one snapshot.
public struct GitWorkingState: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var changes: [Change]
/// Per path: HEAD vs disk. Drives the Actual view.
public var fileDiffs: [String: Diff]
/// Per row id: that row's own pair. Drives the Diff overlay.
public var rowDiffs: [String: Diff]
/// Paths that have a staged row.
public var stagedPaths: Set<String>
/// False when the project is not a git repository.
public var isRepository: Bool
public init(
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
stagedPaths: Set<String> = [], isRepository: Bool = false
) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.changes = changes
self.fileDiffs = fileDiffs
self.rowDiffs = rowDiffs
self.stagedPaths = stagedPaths
self.isRepository = isRepository
}
public static let empty = GitWorkingState()
/// Whole-project line counts for the status bar.
public var totals: (added: Int, removed: Int) {
changes.reduce((0, 0)) { ($0.0 + $1.added, $0.1 + $1.removed) }
}
public var stagedCount: Int { changes.filter(\.staged).count }
public var unstagedCount: Int { changes.count - stagedCount }
/// Distinct paths with an unstaged row, in row order: what "stage all" sends to git.
public var unstagedPaths: [String] {
var seen = Set<String>()
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
}
}
/// The outcome of a push, shown in a toast.
public struct PushResult: Sendable, Equatable {
public var ok: Bool
public var message: String
public init(ok: Bool, message: String) {
self.ok = ok
self.message = message
}
}
+146
View File
@@ -0,0 +1,146 @@
import Foundation
public struct StatusEntry: Sendable, Equatable {
/// The index column of the porcelain XY code (" " when clean).
public var index: Character
/// The working-tree column of the porcelain XY code.
public var working: Character
/// The destination path for renames and copies.
public var path: String
/// The source path of a rename or copy; nil otherwise.
public var originalPath: String?
public init(index: Character, working: Character, path: String, originalPath: String? = nil) {
self.index = index
self.working = working
self.path = path
self.originalPath = originalPath
}
/// True when the index column records a rename, whose source is gone from the index.
public var isStagedRename: Bool { index == "R" && originalPath != nil }
}
public struct ParsedStatus: Sendable, Equatable {
public var branch: String
public var ahead: Int
public var canPush: Bool
public var entries: [StatusEntry]
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
self.branch = branch
self.ahead = ahead
self.canPush = canPush
self.entries = entries
}
}
/// One row a porcelain entry turns into.
public struct GitRowSpec: Sendable, Equatable {
public var status: GitStatus
public var staged: Bool
public init(status: GitStatus, staged: Bool) {
self.status = status
self.staged = staged
}
}
public enum Porcelain {
/// The arguments `GitService.load` passes to git; `-z` keeps paths unquoted.
public static let statusArguments = ["status", "--porcelain", "-b", "--untracked-files=all", "-z"]
/// Parses `git status --porcelain -b -z`: NUL-separated, the `## ` header first.
///
/// For a rename or copy (R or C in either column) the next NUL field is the source
/// path, not an entry of its own. A missing header leaves the branch at "HEAD".
public static func parseStatus(_ raw: String) -> ParsedStatus {
let parts = raw.split(separator: "\0", omittingEmptySubsequences: false)
var result = ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: [])
var sourceFollows = false
for part in parts {
if sourceFollows {
sourceFollows = false
result.entries[result.entries.count - 1].originalPath = String(part)
continue
}
if part.isEmpty { continue }
if part.hasPrefix("## ") {
let header = String(part.dropFirst(3))
result.branch = parseBranch(header: header)
(result.ahead, result.canPush) = parseAhead(header: header)
continue
}
let chars = Array(part.prefix(2))
let index = chars.first ?? " "
let working = chars.count > 1 ? chars[1] : " "
let path = String(part.dropFirst(3))
if index == "R" || index == "C" || working == "R" || working == "C" { sourceFollows = true }
result.entries.append(StatusEntry(index: index, working: working, path: path))
}
return result
}
/// The display branch of a header such as `main...origin/main [ahead 1]`,
/// `No commits yet on main` (→ "main") or `HEAD (no branch)` (→ "HEAD").
public static func parseBranch(header: String) -> String {
let noCommits = "No commits yet on "
if header.hasPrefix(noCommits) { return header.dropFirst(noCommits.count).trimmingCharacters(in: .whitespaces) }
if header.hasPrefix("HEAD ") { return "HEAD" }
let head = header.range(of: "...").map { header[..<$0.lowerBound] } ?? Substring(header)
let name = head.split(separator: " ", omittingEmptySubsequences: false).first.map(String.init) ?? ""
let trimmed = name.trimmingCharacters(in: .whitespaces)
return trimmed.isEmpty ? "HEAD" : trimmed
}
/// Push state from a header. `[ahead N]` → (N, true); no `...` upstream → (0, true),
/// because a first push still sends every commit; "No commits yet" or detached → (0, false).
public static func parseAhead(header: String) -> (ahead: Int, canPush: Bool) {
if header.hasPrefix("No commits yet on ") || header.hasPrefix("HEAD ") { return (0, false) }
if let match = header.firstMatch(of: /\[[^\]]*\bahead (\d+)/), let count = Int(match.1) { return (count, true) }
return (0, !header.contains("..."))
}
/// Maps one porcelain column letter to the letter the row shows.
public static func status(for code: Character) -> GitStatus {
switch code {
case "A", "C", "?": .added
case "D": .deleted
case "R": .renamed
default: .modified
}
}
/// A merge conflict. Neither half can be staged on its own, so it stays one row.
public static func isConflict(index: Character, working: Character) -> Bool {
index == "U" || working == "U" || (index == "A" && working == "A") || (index == "D" && working == "D")
}
/// Splits an XY pair into rows: "MM" is a staged row plus an unstaged row, never one folded row.
public static func classify(index: Character, working: Character) -> [GitRowSpec] {
if isConflict(index: index, working: working) { return [GitRowSpec(status: .modified, staged: true)] }
var rows: [GitRowSpec] = []
if index != " " && index != "?" { rows.append(GitRowSpec(status: status(for: index), staged: true)) }
if working != " " { rows.append(GitRowSpec(status: status(for: working), staged: false)) }
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
}
/// The toast line for a push: git reports on stderr, so the summary is pulled from there.
public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult {
let source = stderr.isEmpty ? stdout : stderr
var lines = source.split(whereSeparator: \.isNewline)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") }
let summary = lines.first { line in
line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date")
|| line.localizedCaseInsensitiveContains("new branch")
}
return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed")
}
/// True when a failed `git push` only needs `-u origin <branch>`.
public static func needsUpstream(stderr: String) -> Bool {
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
}
}
@@ -0,0 +1,155 @@
import Foundation
/// CSS, and SCSS too: nesting, `$vars` and `//` comments.
enum CSSGrammar {
private enum Context {
case selector, property, value
}
private static let important = Unit.literal("important")
private static let url = Unit.literal("url(")
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var context: Context = st.mode == .cssValue ? .value : statementContext(lx, depth: st.depth)
if st.mode == .cssValue { st.mode = .code }
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
if lx.stop != nil && lx.atStop() { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where lx.peek(1) == Unit.slash && (start == lineStart || Unit.isSpace(lx.unit(at: start - 1))):
lx.lineComment()
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
case Unit.lbrace:
lx.i += 1
st.depth += 1
context = statementContext(lx, depth: st.depth)
case Unit.rbrace:
lx.i += 1
st.depth = max(0, st.depth - 1)
context = statementContext(lx, depth: st.depth)
case Unit.semicolon:
lx.i += 1
context = statementContext(lx, depth: st.depth)
case Unit.at where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
context = .value
case Unit.dollar where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
if lx.nextNonSpace() == Unit.colon { context = .value }
case Unit.bang where lx.startsIgnoringCase(with: important, at: start + 1):
lx.i += 1 + important.count
lx.emit(start, lx.i, .keyword)
default:
switch context {
case .selector: selectorPart(&lx)
case .property:
if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.nextNonSpace() == Unit.colon {
lx.emit(start, lx.i, .variable)
lx.skipSpaces()
lx.i += 1
context = .value
} else {
lx.emit(start, lx.i, .number)
}
} else {
selectorPart(&lx)
}
case .value: valuePart(&lx)
}
}
}
if context == .value && st.depth > 0 && st.mode == .code { st.mode = .cssValue }
}
/// Whether what follows is a selector or a declaration: at the top level always a selector,
/// inside a block a selector only when a `{` comes before any `;` or `}` on the line.
private static func statementContext(_ lx: Lexer, depth: Int) -> Context {
if depth == 0 { return .selector }
var k = lx.i
while k < lx.end {
switch lx.u[k] {
case Unit.lbrace: return .selector
case Unit.semicolon, Unit.rbrace: return .property
default: k += 1
}
}
return .property
}
private static func selectorPart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.colon:
lx.i += 1
if lx.peek() == Unit.colon { lx.i += 1 }
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
case Unit.amp, Unit.greater, Unit.plus, Unit.tilde:
lx.i += 1
lx.emit(start, lx.i, .keyword)
case Unit.lbracket:
while lx.i < lx.end && lx.u[lx.i] != Unit.rbracket { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(start, lx.i, .number)
case Unit.dot, Unit.hash, Unit.star, Unit.percent:
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
case _ where Unit.isIdentStart(c) || c == Unit.minus:
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
default:
lx.i += 1
}
}
private static func valuePart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
if c == Unit.hash && Unit.isHexDigit(lx.peek(1)) {
lx.i += 1
lx.identifier()
lx.emit(start, lx.i, .number)
} else if Unit.isDigit(c) || ((c == Unit.dot || c == Unit.minus || c == Unit.plus) && (Unit.isDigit(lx.peek(1)) || (lx.peek(1) == Unit.dot && Unit.isDigit(lx.peek(2))))) {
lx.i += 1
while lx.i < lx.end && (Unit.isDigit(lx.u[lx.i]) || lx.u[lx.i] == Unit.dot) { lx.i += 1 }
if lx.peek() == Unit.percent { lx.i += 1 } else { lx.identifier() }
lx.emit(start, lx.i, .number)
} else if lx.startsIgnoringCase(with: url) {
lx.i += url.count
let body = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.emit(body, lx.i, .string)
} else if c == Unit.minus && lx.peek(1) == Unit.minus {
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
} else if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.peek() != Unit.lparen { lx.emit(start, lx.i, .string) }
} else {
lx.i += 1
}
}
}
@@ -0,0 +1,44 @@
import Foundation
/// JSON with comments allowed, since tsconfig-style files carry them.
enum JSONGrammar {
private static let literals: Set<String> = ["true", "false", "null"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.quote:
lx.i += 1
var closed = false
while lx.i < lx.end && !closed {
if lx.u[lx.i] == Unit.backslash { lx.i += 1 } else if lx.u[lx.i] == Unit.quote { closed = true }
lx.i += 1
}
lx.i = min(lx.i, lx.end)
lx.emit(start, lx.i, lx.nextNonSpace() == Unit.colon ? .variable : .string)
case _ where Unit.isDigit(c) || (c == Unit.minus && Unit.isDigit(lx.peek(1))):
if c == Unit.minus {
lx.i += 1
lx.emit(start, lx.i, .number)
}
lx.number()
case _ where Unit.isAlpha(c):
lx.identifier()
if literals.contains(lx.text(start, lx.i)) { lx.emit(start, lx.i, .number) }
default:
lx.i += 1
}
}
}
}
@@ -0,0 +1,256 @@
import Foundation
enum JavaScriptGrammar {
static let keywords: Set<String> = [
"as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger",
"default", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "from",
"function", "get", "if", "implements", "import", "in", "instanceof", "interface", "let", "new",
"of", "package", "private", "protected", "public", "return", "set", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield",
]
static let typeScriptKeywords: Set<String> = [
"abstract", "declare", "is", "keyof", "module", "namespace", "readonly", "type", "infer",
"satisfies", "override", "unique", "asserts", "accessor",
]
/// Painted as builtins, in the number colour.
static let typeScriptBuiltins: Set<String> = [
"string", "number", "boolean", "any", "void", "never", "unknown", "object", "symbol", "bigint",
]
static let constants: Set<String> = ["true", "false", "null", "undefined", "NaN", "Infinity"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = ["class", "extends", "implements", "new", "instanceof", "interface"]
/// Keywords after which a `/` starts a regex rather than a division.
private static let valueKeywords: Set<String> = ["this", "super"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, typescript: Bool, jsx: Bool) {
var expectsValue = true
var classNext = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case .template:
template(&lx, &st)
expectsValue = false
continue
case let .jsxTag(level, closing):
jsxTag(&lx, &st, level: level, closing: closing)
expectsValue = true
continue
case let .jsxText(level):
jsxText(&lx, &st, level: level)
expectsValue = true
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where expectsValue && regex(&lx):
expectsValue = false
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
expectsValue = false
case Unit.backtick:
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .template
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
expectsValue = false
case _ where Unit.isIdentStart(c) || c == Unit.dollar || (c == Unit.hash && Unit.isIdentStart(lx.peek(1))):
lx.i += 1
lx.identifier { $0 == Unit.dollar }
let word = lx.text(start, lx.i)
if keywords.contains(word) || (typescript && typeScriptKeywords.contains(word)) {
lx.emit(start, lx.i, .keyword)
classNext = classIntroducers.contains(word)
expectsValue = !valueKeywords.contains(word)
continue
}
if constants.contains(word) || (typescript && typeScriptBuiltins.contains(word)) {
lx.emit(start, lx.i, .number)
} else if classNext {
lx.emit(start, lx.i, .variable)
} else if isConstantName(lx, start, lx.i) {
lx.emit(start, lx.i, .number)
}
classNext = false
expectsValue = false
continue
case Unit.lbrace:
lx.i += 1
if !st.resumes.isEmpty { st.depth += 1 }
expectsValue = true
case Unit.rbrace:
lx.i += 1
if let resume = st.resumes.last, resume.depth == st.depth {
st.resumes.removeLast()
st.mode = resume.mode
} else if !st.resumes.isEmpty {
st.depth -= 1
}
expectsValue = true
case Unit.lparen, Unit.lbracket, Unit.comma, Unit.semicolon:
lx.i += 1
expectsValue = true
case Unit.rparen, Unit.rbracket:
lx.i += 1
expectsValue = false
case Unit.less where jsx && (expectsValue || lx.peek(1) == Unit.slash):
if !openJSX(&lx, &st, level: 0) { lx.operatorRun() }
case Unit.dot:
lx.i += 1
while lx.peek() == Unit.dot { lx.i += 1 }
if lx.i - start > 1 { lx.emit(start, lx.i, .keyword) }
expectsValue = lx.i - start > 1
case _ where Unit.isOperator(c):
lx.operatorRun()
expectsValue = true
default:
lx.i += 1
}
classNext = false
}
}
/// `FOO_BAR`: an all-caps name of two or more characters, painted as a constant.
static func isConstantName(_ lx: Lexer, _ from: Int, _ to: Int) -> Bool {
guard to - from >= 2, Unit.isUpper(lx.u[from]) else { return false }
for k in from..<to where Unit.isLower(lx.u[k]) { return false }
return true
}
/// A regex literal from the `/` at `lx.i`; false (nothing consumed) when the line ends before it closes.
private static func regex(_ lx: inout Lexer) -> Bool {
let start = lx.i
var k = start + 1
var inClass = false
while k < lx.end {
let c = lx.u[k]
if c == Unit.backslash {
k += 2
continue
}
if c == Unit.lbracket { inClass = true }
if c == Unit.rbracket { inClass = false }
if c == Unit.slash && !inClass { break }
k += 1
}
guard k < lx.end, k > start + 1 else { return false }
k += 1
while k < lx.end && Unit.isAlpha(lx.u[k]) { k += 1 }
lx.i = k
lx.emit(start, k, .string)
return true
}
/// Template-literal text up to the closing backtick, a `${`, or the end of the line.
private static func template(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == Unit.backtick {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
if c == Unit.dollar && lx.peek(1) == Unit.lbrace {
lx.emit(start, lx.i, .string)
lx.i += 2
st.resumes.append(Resume(depth: st.depth, mode: .template))
st.mode = .code
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
}
/// `<Name`, `</Name`, `<>` or `</>`; false (nothing consumed) for anything else.
private static func openJSX(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) -> Bool {
var k = lx.i + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
let first = lx.unit(at: k)
if first == Unit.greater {
lx.i = k + 1
st.mode = children(closing ? level - 1 : level + 1)
return true
}
guard Unit.isAlpha(first) else { return false }
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.dot || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon) { k += 1 }
lx.emit(nameStart, k, .number)
lx.i = k
st.mode = .jsxTag(level: level, closing: closing)
return true
}
private static func children(_ open: Int) -> Mode {
open > 0 ? .jsxText(level: open) : .code
}
/// Attributes inside a JSX tag, up to `>` or `/>`; a `{` hands over to code until its `}`.
private static func jsxTag(_ lx: inout Lexer, _ st: inout GrammarState, level: Int, closing: Bool) {
while lx.i < lx.end {
let c = lx.u[lx.i]
let start = lx.i
if c == Unit.greater {
lx.i += 1
st.mode = children(closing ? level - 1 : level + 1)
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = children(level)
return
} else if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxTag(level: level, closing: closing)))
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
_ = lx.quoted(from: start, quote: c, escapes: false)
} else if Unit.isIdentStart(c) {
lx.identifier { $0 == Unit.minus || $0 == Unit.colon }
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
}
}
/// Children text: plain up to the next tag or `{` expression.
private static func jsxText(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) {
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.less && openJSX(&lx, &st, level: level) { return }
if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxText(level: level)))
st.mode = .code
return
}
lx.i += 1
}
}
}
+206
View File
@@ -0,0 +1,206 @@
import Foundation
/// Where an embedded grammar hands control back to its host.
enum Terminator: Hashable, Sendable {
/// `?>` closes a PHP island inside markup.
case phpClose
/// `</name` closes a `<script>` or `<style>` body; the name is lowercase.
case closingTag(String)
/// A Markdown fence closes on a line of its own, which the Markdown grammar checks itself.
case fence
}
/// A cursor over UTF-16 units that collects non-plain tokens for one line at a time.
///
/// Grammars scan `i..<end` and must return when `i` reaches `end`, or when `atStop()`
/// is true at a code position, so the host grammar can take over.
struct Lexer {
let u: [UInt16]
var i: Int
var end: Int
var stop: Terminator?
let symbols: Set<String>
private(set) var tokens: [Token] = []
init(units: [UInt16], symbols: Set<String>) {
u = units
i = 0
end = units.count
self.symbols = symbols
}
/// The unit `k` places ahead, or 0 past the end of the line.
@inline(__always) func peek(_ k: Int = 0) -> UInt16 {
let j = i + k
return j < end ? u[j] : 0
}
func unit(at j: Int) -> UInt16 {
j >= 0 && j < end ? u[j] : 0
}
mutating func emit(_ from: Int, _ to: Int, _ role: TokenRole) {
guard to > from, role != .plain else { return }
if let last = tokens.last, last.role == role, last.location + last.length == from {
tokens[tokens.count - 1].length += to - from
} else {
tokens.append(Token(location: from, length: to - from, role: role))
}
}
func text(_ from: Int, _ to: Int) -> String {
String(decoding: u[from..<to], as: UTF16.self)
}
func starts(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where u[at + k] != literal[k] { return false }
return true
}
/// ASCII case-insensitive `starts(with:)`; `literal` must be lowercase.
func startsIgnoringCase(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where Unit.lower(u[at + k]) != literal[k] { return false }
return true
}
func atStop() -> Bool {
switch stop {
case .phpClose: return peek() == Unit.question && peek(1) == Unit.greater
case let .closingTag(name):
guard peek() == Unit.less, peek(1) == Unit.slash else { return false }
return startsIgnoringCase(with: Array(name.utf16), at: i + 2)
case .fence, nil: return false
}
}
mutating func skipSpaces() {
while i < end && Unit.isSpace(u[i]) { i += 1 }
}
/// The first non-space unit from `j` on, or 0.
func nextNonSpace(from j: Int? = nil) -> UInt16 {
var k = j ?? i
while k < end && Unit.isSpace(u[k]) { k += 1 }
return k < end ? u[k] : 0
}
mutating func identifier(extra: (UInt16) -> Bool = { _ in false }) {
while i < end && (Unit.isIdentPart(u[i]) || extra(u[i])) { i += 1 }
}
/// A comment to the end of the line, or to the stop marker a PHP `?>` or `</script` sets.
mutating func lineComment() {
let start = i
if stop == nil {
i = end
} else {
while i < end && !atStop() { i += 1 }
}
emit(start, i, .comment)
}
/// Consumes up to and including `close`; returns false when the line ends first.
mutating func blockComment(from start: Int, close: [UInt16]) -> Bool {
while i < end {
if starts(with: close) {
i += close.count
emit(start, i, .comment)
return true
}
i += 1
}
emit(start, i, .comment)
return false
}
/// A string body up to the closing `quote`, with backslash escapes; false when the line ends first.
mutating func quoted(from start: Int, quote: UInt16, escapes: Bool = true, role: TokenRole = .string) -> Bool {
while i < end {
let c = u[i]
if escapes && c == Unit.backslash {
i += 2
continue
}
i += 1
if c == quote {
emit(start, i, role)
return true
}
}
i = min(i, end)
emit(start, i, role)
return false
}
/// A numeric literal: hex/octal/binary prefixes, `_` separators, fraction, exponent and a letter suffix.
mutating func number() {
let start = i
if peek() == Unit.zero && Unit.isAlpha(peek(1)) && "xXoObB".utf16.contains(peek(1)) {
i += 2
while i < end && (Unit.isHexDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
} else {
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
if peek() == Unit.dot && Unit.isDigit(peek(1)) {
i += 1
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
}
if (peek() == Unit.lowerE || peek() == Unit.upperE)
&& (Unit.isDigit(peek(1)) || ((peek(1) == Unit.plus || peek(1) == Unit.minus) && Unit.isDigit(peek(2)))) {
i += 2
while i < end && Unit.isDigit(u[i]) { i += 1 }
}
}
while i < end && Unit.isAlpha(u[i]) { i += 1 }
emit(start, i, .number)
}
/// Consumes a run of operator characters and paints it as a keyword.
mutating func operatorRun(_ isOperator: (UInt16) -> Bool = Unit.isOperator) {
let start = i
while i < end && isOperator(u[i]) { i += 1 }
emit(start, i, .keyword)
}
}
enum Literals {
static let blockClose = Unit.literal("*/")
static let heredoc = Unit.literal("<<<")
}
/// UTF-16 character classes. Every unit at or above 0x80 counts as an identifier letter,
/// which keeps surrogate pairs and non-ASCII names in one token.
enum Unit {
static let tab: UInt16 = 9, space: UInt16 = 32, bang: UInt16 = 33, quote: UInt16 = 34
static let hash: UInt16 = 35, dollar: UInt16 = 36, percent: UInt16 = 37, amp: UInt16 = 38
static let apostrophe: UInt16 = 39, lparen: UInt16 = 40, rparen: UInt16 = 41, star: UInt16 = 42
static let plus: UInt16 = 43, comma: UInt16 = 44, minus: UInt16 = 45, dot: UInt16 = 46
static let slash: UInt16 = 47, zero: UInt16 = 48, colon: UInt16 = 58, semicolon: UInt16 = 59
static let less: UInt16 = 60, equals: UInt16 = 61, greater: UInt16 = 62, question: UInt16 = 63
static let at: UInt16 = 64, upperE: UInt16 = 69, lbracket: UInt16 = 91, backslash: UInt16 = 92
static let rbracket: UInt16 = 93, caret: UInt16 = 94, underscore: UInt16 = 95, backtick: UInt16 = 96
static let lowerE: UInt16 = 101, lbrace: UInt16 = 123, pipe: UInt16 = 124, rbrace: UInt16 = 125
static let tilde: UInt16 = 126
@inline(__always) static func isDigit(_ c: UInt16) -> Bool { c &- 48 < 10 }
@inline(__always) static func isUpper(_ c: UInt16) -> Bool { c &- 65 < 26 }
@inline(__always) static func isLower(_ c: UInt16) -> Bool { c &- 97 < 26 }
@inline(__always) static func isAlpha(_ c: UInt16) -> Bool { isUpper(c) || isLower(c) }
@inline(__always) static func isHexDigit(_ c: UInt16) -> Bool { isDigit(c) || (c | 0x20) &- 97 < 6 }
@inline(__always) static func isIdentStart(_ c: UInt16) -> Bool { isAlpha(c) || c == underscore || c >= 0x80 }
@inline(__always) static func isIdentPart(_ c: UInt16) -> Bool { isIdentStart(c) || isDigit(c) }
@inline(__always) static func isSpace(_ c: UInt16) -> Bool { c == space || c == tab || c == 13 || c == 12 || c == 11 }
@inline(__always) static func lower(_ c: UInt16) -> UInt16 { isUpper(c) ? c + 32 : c }
static func isOperator(_ c: UInt16) -> Bool {
switch c {
case plus, minus, star, slash, percent, equals, amp, pipe, caret, bang, tilde, less, greater, question, colon: true
default: false
}
}
static func literal(_ text: String) -> [UInt16] { Array(text.utf16) }
}
@@ -0,0 +1,156 @@
import Foundation
/// Markdown, with fenced code in a known language highlighted by that language.
enum MarkdownGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
if case let .fence(marker, count) = st.mode {
fencedLine(&lx, &st, marker: marker, count: count)
return
}
lx.skipSpaces()
let c = lx.peek()
if (c == Unit.backtick || c == Unit.tilde), let count = run(lx, of: c), count >= 3 {
let info = lx.text(lx.i + count, lx.end).trimmingCharacters(in: .whitespaces)
let word = String(info.prefix { !$0.isWhitespace })
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .fence(marker: c, count: count)
if let grammar = Grammar(MarkdownParser.fenceLanguage(word), text: "") {
st.child = .grammar(grammar, GrammarState(), until: .fence)
}
return
}
if c == Unit.hash, let count = run(lx, of: c), count <= 6, lx.unit(at: lx.i + count) == 0 || Unit.isSpace(lx.unit(at: lx.i + count)) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .keyword)
return
}
if isRule(lx) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
return
}
while lx.peek() == Unit.greater {
lx.emit(lx.i, lx.i + 1, .comment)
lx.i += 1
lx.skipSpaces()
}
listMarker(&lx)
inline(&lx)
}
private static func fencedLine(_ lx: inout Lexer, _ st: inout GrammarState, marker: UInt16, count: Int) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
var closing = k
while closing < lx.end && lx.u[closing] == marker { closing += 1 }
var rest = closing
while rest < lx.end && Unit.isSpace(lx.u[rest]) { rest += 1 }
if closing - k >= count && rest == lx.end {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .code
st.child = nil
return
}
if case let .grammar(grammar, inner, _)? = st.child {
var state = inner
Grammars.scan(grammar, &lx, &state)
st.child = .grammar(grammar, state, until: .fence)
}
lx.i = lx.end
}
/// How many `c` in a row start at the cursor.
private static func run(_ lx: Lexer, of c: UInt16) -> Int? {
var k = lx.i
while k < lx.end && lx.u[k] == c { k += 1 }
return k - lx.i
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ lx: Lexer) -> Bool {
let first = lx.peek()
guard first == Unit.minus || first == Unit.star || first == Unit.underscore else { return false }
var marks = 0
for k in lx.i..<lx.end {
if lx.u[k] == first {
marks += 1
} else if !Unit.isSpace(lx.u[k]) {
return false
}
}
return marks >= 3
}
/// `-`, `*`, `+` or `1.`/`1)` followed by a space.
private static func listMarker(_ lx: inout Lexer) {
var k = lx.i
let c = lx.peek()
if c == Unit.minus || c == Unit.star || c == Unit.plus {
k += 1
} else {
while k < lx.end && Unit.isDigit(lx.u[k]) { k += 1 }
guard k > lx.i, lx.unit(at: k) == Unit.dot || lx.unit(at: k) == Unit.rparen else { return }
k += 1
}
guard Unit.isSpace(lx.unit(at: k)) else { return }
lx.emit(lx.i, k, .comment)
lx.i = k
}
/// Code spans, link targets and autolinks in running text.
private static func inline(_ lx: inout Lexer) {
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
} else if c == Unit.backtick {
let ticks = run(lx, of: c) ?? 1
if let close = findRun(lx, of: c, count: ticks, from: start + ticks) {
lx.i = close + ticks
lx.emit(start, lx.i, .keyword)
} else {
lx.i += ticks
}
} else if c == Unit.rbracket && lx.peek(1) == Unit.lparen {
lx.i += 1
let open = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(open, lx.i, .variable)
} else if c == Unit.less && Unit.isAlpha(lx.peek(1)) {
var k = start + 1
while k < lx.end && lx.u[k] != Unit.greater && !Unit.isSpace(lx.u[k]) { k += 1 }
if lx.unit(at: k) == Unit.greater && lx.text(start + 1, k).contains(":") {
lx.i = k + 1
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
} else {
lx.i += 1
}
}
}
/// The start of the next run of exactly `count` × `c` from `from`, or nil.
private static func findRun(_ lx: Lexer, of c: UInt16, count: Int, from: Int) -> Int? {
var k = from
while k < lx.end {
if lx.u[k] == c {
var e = k
while e < lx.end && lx.u[e] == c { e += 1 }
if e - k == count { return k }
k = e
} else {
k += 1
}
}
return nil
}
}
@@ -0,0 +1,155 @@
import Foundation
/// HTML, XML, SVG and Vue, plus the markup around `<?php` blocks in PHP files.
enum MarkupGrammar {
private static let commentOpen = Unit.literal("<!--")
private static let commentClose = Unit.literal("-->")
private static let cdataOpen = Unit.literal("<![cdata[")
private static let cdataClose = Unit.literal("]]>")
private static let phpOpenTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, phpIslands: Bool) {
while lx.i < lx.end {
switch st.mode {
case .markupComment:
if lx.blockComment(from: lx.i, close: commentClose) { st.mode = .code }
continue
case .cdata:
if lx.blockComment(from: lx.i, close: cdataClose) { st.mode = .code }
continue
case let .markupTag(name):
tag(&lx, &st, name: name, phpIslands: phpIslands)
if st.child != nil { return }
continue
case let .markupValue(quote, name):
value(&lx, &st, quote: quote, tag: name, from: lx.i, phpIslands: phpIslands)
if st.child != nil { return }
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if c == Unit.less {
openTag(&lx, &st)
} else if c == Unit.amp {
lx.i += 1
while lx.i < lx.end && (Unit.isIdentPart(lx.u[lx.i]) || lx.u[lx.i] == Unit.hash) { lx.i += 1 }
if lx.peek() == Unit.semicolon && lx.i > start + 1 {
lx.i += 1
lx.emit(start, lx.i, .variable)
}
} else {
lx.i += 1
while lx.i < lx.end && lx.u[lx.i] != Unit.less && lx.u[lx.i] != Unit.amp { lx.i += 1 }
}
}
}
/// Everything that starts with `<` in text: comments, CDATA, doctype, prolog and tags.
private static func openTag(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
if lx.starts(with: commentOpen) {
lx.i += commentOpen.count
if !lx.blockComment(from: start, close: commentClose) { st.mode = .markupComment }
return
}
if lx.startsIgnoringCase(with: cdataOpen) {
lx.i += cdataOpen.count
if !lx.blockComment(from: start, close: cdataClose) { st.mode = .cdata }
return
}
let next = lx.peek(1)
if next == Unit.bang || next == Unit.question {
let close = next == Unit.bang ? [Unit.greater] : [Unit.question, Unit.greater]
lx.i += 2
_ = lx.blockComment(from: start, close: close)
return
}
var k = start + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
guard Unit.isAlpha(lx.unit(at: k)) else {
lx.i += 1
return
}
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon || lx.u[k] == Unit.dot) { k += 1 }
lx.emit(nameStart, k, .number)
let name = lx.text(nameStart, k).lowercased()
lx.i = k
st.mode = .markupTag(closing ? "/" + name : name)
}
/// Attributes up to `>`; a `>` that closes `<script>` or `<style>` hands the body to JavaScript or CSS.
private static func tag(_ lx: inout Lexer, _ st: inout GrammarState, name: String, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) || c == Unit.equals {
lx.i += 1
} else if c == Unit.greater {
lx.i += 1
st.mode = .code
switch name {
case "script": st.child = .grammar(.javascript(typescript: false, jsx: false), GrammarState(), until: .closingTag("script"))
case "style": st.child = .grammar(.css, GrammarState(), until: .closingTag("style"))
default: break
}
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
value(&lx, &st, quote: c, tag: name, from: start, phpIslands: phpIslands)
if st.child != nil || st.mode != .markupTag(name) { return }
} else if c == Unit.slash {
lx.i += 1
} else {
while lx.i < lx.end && !isAttributeEnd(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, lx.unit(at: start - 1) == Unit.equals ? .string : .variable)
}
}
}
private static func isAttributeEnd(_ c: UInt16) -> Bool {
Unit.isSpace(c) || c == Unit.equals || c == Unit.greater || c == Unit.slash || c == Unit.quote || c == Unit.apostrophe
}
/// A quoted attribute value; it may run over lines and may hold a PHP island.
private static func value(_ lx: inout Lexer, _ st: inout GrammarState, quote: UInt16, tag: String, from start: Int, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && lx.peek() == Unit.less && lx.peek(1) == Unit.question {
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
_ = openIsland(&lx, &st)
return
}
if lx.u[lx.i] == quote {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .markupTag(tag)
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
}
/// `<?php`, `<?=` or `<?` starts a PHP island that runs until `?>`.
private static func openIsland(_ lx: inout Lexer, _ st: inout GrammarState) -> Bool {
guard lx.peek() == Unit.less, lx.peek(1) == Unit.question else { return false }
let start = lx.i
let open = phpOpenTags.first { lx.startsIgnoringCase(with: $0) } ?? phpOpenTags[2]
lx.i += open.count
lx.emit(start, lx.i, .keyword)
st.child = .grammar(.php, GrammarState(), until: .phpClose)
return true
}
}
@@ -0,0 +1,265 @@
import Foundation
enum PHPGrammar {
/// Matched lowercase: PHP keywords are case-insensitive.
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare",
"endfor", "endforeach", "endif", "endswitch", "endwhile", "enum", "eval", "exit", "extends",
"final", "finally", "fn", "for", "foreach", "from", "function", "global", "goto", "if",
"implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list",
"match", "namespace", "new", "or", "parent", "print", "private", "protected", "public", "readonly",
"require", "require_once", "return", "self", "static", "switch", "throw", "trait", "try", "unset",
"use", "var", "while", "xor", "yield",
"int", "float", "string", "bool", "void", "mixed", "never", "iterable", "object",
]
static let constants: Set<String> = ["true", "false", "null"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = [
"class", "interface", "trait", "enum", "extends", "implements", "instanceof", "insteadof", "new",
]
private static let scopeKeywords: Set<String> = ["self", "static", "parent"]
private static let openTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
var namespaceNext = false
var afterArrow = false
var afterDoubleColon = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case let .quoted(quote):
if interpolated(&lx, from: lx.i, close: quote, interpolates: quote != Unit.apostrophe) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where lx.peek(1) == Unit.lbracket:
lx.i += 2
classNext = true
continue
case Unit.hash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.apostrophe, Unit.quote, Unit.backtick:
lx.i += 1
if !interpolated(&lx, from: start, close: c, interpolates: c != Unit.apostrophe) { st.mode = .quoted(c) }
case Unit.less where lx.starts(with: Literals.heredoc):
heredocStart(&lx, &st)
case Unit.less where lx.peek(1) == Unit.question:
let tag = openTags.first { lx.startsIgnoringCase(with: $0) } ?? openTags[2]
lx.i += tag.count
lx.emit(start, lx.i, .keyword)
case Unit.question where lx.peek(1) == Unit.greater:
lx.i += 2
lx.emit(start, lx.i, .keyword)
case Unit.dollar where Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.dollar:
while lx.peek() == Unit.dollar { lx.i += 1 }
lx.identifier()
lx.emit(start, lx.i, .variable)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case Unit.minus where lx.peek(1) == Unit.greater, Unit.question where lx.peek(1) == Unit.minus && lx.peek(2) == Unit.greater:
lx.i += c == Unit.question ? 3 : 2
lx.emit(start, lx.i, .keyword)
afterArrow = true
continue
case Unit.colon where lx.peek(1) == Unit.colon:
lx.i += 2
lx.emit(start, lx.i, .keyword)
afterDoubleColon = true
continue
case _ where Unit.isIdentStart(c) || (c == Unit.backslash && Unit.isIdentStart(lx.peek(1))):
name(&lx, classNext: &classNext, namespaceNext: &namespaceNext, afterArrow: afterArrow, afterDoubleColon: afterDoubleColon)
case _ where Unit.isOperator(c) || c == Unit.dot || c == Unit.at:
lx.operatorRun { Unit.isOperator($0) || $0 == Unit.dot || $0 == Unit.at }
default:
lx.i += 1
}
afterArrow = false
afterDoubleColon = false
}
}
/// A name, possibly qualified (`\App\Models\Agent`): the namespace path reads as a string,
/// the last segment as a keyword, class, constant or function.
private static func name(_ lx: inout Lexer, classNext: inout Bool, namespaceNext: inout Bool, afterArrow: Bool, afterDoubleColon: Bool) {
let start = lx.i
var lastSegment = start
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash && Unit.isIdentStart(lx.peek(1)) {
lx.i += 1
lastSegment = lx.i
} else if Unit.isIdentPart(lx.u[lx.i]) {
lx.i += 1
} else {
break
}
}
if lx.peek() == Unit.backslash {
// A group import, `use App\Models\{A, B}`: the whole prefix is a path.
lx.i += 1
lx.emit(start, lx.i, .string)
return
}
let end = lx.i
let qualified = lastSegment > start
if namespaceNext {
namespaceNext = false
lx.emit(start, end, .string)
return
}
lx.emit(start, lastSegment, .string)
let word = lx.text(lastSegment, end)
let next = lx.nextNonSpace()
let callsNext = next == Unit.lparen
if afterArrow {
lx.emit(lastSegment, end, callsNext ? .plain : .variable)
return
}
if afterDoubleColon {
let lower = word.lowercased()
if lower == "class" {
lx.emit(lastSegment, end, .keyword)
} else if !callsNext && JavaScriptGrammar.isConstantName(lx, lastSegment, end) {
lx.emit(lastSegment, end, .number)
}
return
}
if !qualified {
let lower = word.lowercased()
if constants.contains(lower) {
lx.emit(lastSegment, end, .number)
return
}
if scopeKeywords.contains(lower) {
lx.emit(lastSegment, end, .keyword)
return
}
if keywords.contains(lower) && !(lx.peek() == Unit.colon && lx.peek(1) == Unit.colon) {
lx.emit(lastSegment, end, .keyword)
classNext = classIntroducers.contains(lower)
namespaceNext = lower == "namespace"
return
}
}
let followedByScope = lx.peek() == Unit.colon && lx.peek(1) == Unit.colon
let isConstant = JavaScriptGrammar.isConstantName(lx, lastSegment, end)
let looksLikeClass = Unit.isUpper(lx.u[lastSegment]) && !isConstant && !callsNext
if classNext || followedByScope || looksLikeClass {
lx.emit(lastSegment, end, lx.symbols.contains(word) ? .symbol : .variable)
} else if isConstant && !callsNext {
lx.emit(lastSegment, end, .number)
}
classNext = false
}
/// A string body with `$var`, `$var->prop` and `{$…}` interpolation; false when the line ends first.
/// With `close` 0 it runs to the end of the line, for heredoc bodies.
static func interpolated(_ lx: inout Lexer, from start: Int, close: UInt16, interpolates: Bool) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash && close != 0 {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == close {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if interpolates && c == Unit.dollar && Unit.isIdentStart(lx.peek(1)) {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
lx.i += 1
lx.identifier()
if lx.peek() == Unit.minus && lx.peek(1) == Unit.greater && Unit.isIdentStart(lx.peek(2)) {
lx.i += 2
lx.identifier()
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
if interpolates && c == Unit.lbrace && lx.peek(1) == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
var depth = 0
while lx.i < lx.end {
if lx.u[lx.i] == Unit.lbrace { depth += 1 }
if lx.u[lx.i] == Unit.rbrace {
depth -= 1
if depth == 0 {
lx.i += 1
break
}
}
lx.i += 1
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` (nowdoc): the rest of the line and every line up to the marker.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 3
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 3
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.i = k
lx.emit(start, k, .string)
st.mode = .heredoc(id: id, interpolates: quote != Unit.apostrophe)
}
/// One heredoc body line; the closing marker may be indented and followed by code.
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && !Unit.isIdentPart(lx.unit(at: k + marker.count)) {
lx.i = k + marker.count
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
_ = interpolated(&lx, from: start, close: 0, interpolates: interpolates)
}
}
@@ -0,0 +1,109 @@
import Foundation
enum PythonGrammar {
static let keywords: Set<String> = [
"and", "as", "assert", "async", "await", "break", "case", "class", "continue", "def", "del",
"elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is",
"lambda", "match", "nonlocal", "not", "or", "pass", "print", "raise", "return", "try", "while",
"with", "yield",
]
/// Builtins and the three constants, painted in the number colour.
static let builtins: Set<String> = [
"True", "False", "None", "abs", "all", "any", "ascii", "bin", "bool", "bytearray", "bytes",
"callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr",
"hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list",
"locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow",
"property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted",
"staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
while lx.i < lx.end {
if case let .triple(quote) = st.mode {
if triple(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
if let quote = stringQuote(lx) {
lx.i = quote.bodyStart
if quote.isTriple {
if !triple(&lx, from: start, quote: quote.unit) { st.mode = .triple(quote.unit) }
} else {
_ = lx.quoted(from: start, quote: quote.unit)
}
classNext = false
continue
}
switch c {
case Unit.hash:
lx.lineComment()
case Unit.at where Unit.isIdentStart(lx.peek(1)) && isLineStart(lx, start):
lx.i += 1
lx.identifier { $0 == Unit.dot }
lx.emit(start, lx.i, .keyword)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case _ where Unit.isIdentStart(c):
lx.identifier()
let word = lx.text(start, lx.i)
if keywords.contains(word) {
lx.emit(start, lx.i, .keyword)
classNext = word == "class"
continue
}
if classNext {
lx.emit(start, lx.i, .variable)
} else if builtins.contains(word) {
lx.emit(start, lx.i, .number)
}
case _ where Unit.isOperator(c) && c != Unit.colon:
lx.operatorRun { Unit.isOperator($0) && $0 != Unit.colon }
default:
lx.i += 1
}
classNext = false
}
}
private static func isLineStart(_ lx: Lexer, _ j: Int) -> Bool {
var k = j - 1
while k >= 0 && Unit.isSpace(lx.u[k]) { k -= 1 }
return k < 0 || lx.u[k] == 10
}
/// A string opener at the cursor, with its `r`/`b`/`f`/`u` prefix.
private static func stringQuote(_ lx: Lexer) -> (unit: UInt16, isTriple: Bool, bodyStart: Int)? {
var k = lx.i
while k - lx.i < 2 && k < lx.end && "rRbBuUfF".utf16.contains(lx.u[k]) { k += 1 }
if k > lx.i && Unit.isIdentPart(lx.unit(at: lx.i - 1)) { return nil }
let q = lx.unit(at: k)
guard q == Unit.quote || q == Unit.apostrophe else { return nil }
if lx.unit(at: k + 1) == q && lx.unit(at: k + 2) == q { return (q, true, k + 3) }
return (q, false, k + 1)
}
/// A triple-quoted body up to its closing three quotes; false when the line ends first.
private static func triple(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if lx.u[lx.i] == quote && lx.peek(1) == quote && lx.peek(2) == quote {
lx.i += 3
lx.emit(start, lx.i, .string)
return true
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
return false
}
}
@@ -0,0 +1,187 @@
import Foundation
/// Shell scripts, and `.env` files.
enum ShellGrammar {
static let keywords: Set<String> = [
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "in",
"function", "select", "time", "return", "local", "export", "readonly", "declare", "unset", "shift",
"break", "continue", "exit", "source", "alias", "typeset", "let", "eval",
]
/// Painted in the number colour.
static let builtins: Set<String> = [
"echo", "cd", "pwd", "printf", "read", "test", "set", "trap", "wait", "kill", "exec", "true",
"false", "type", "hash", "getopts", "umask", "ulimit", "command", "builtin", "jobs", "fg", "bg",
"pushd", "popd", "dirs", "history", "shopt", "mapfile",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
while lx.i < lx.end {
switch st.mode {
case let .quoted(quote):
if string(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || isWordBreak(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.apostrophe, Unit.quote:
lx.i += 1
if !string(&lx, from: start, quote: c) { st.mode = .quoted(c) }
case Unit.dollar:
variable(&lx)
case Unit.less where lx.peek(1) == Unit.less && lx.peek(2) != Unit.less:
heredocStart(&lx, &st)
case _ where isOperator(c):
lx.operatorRun(isOperator)
case _ where isWordBreak(c):
lx.i += 1
default:
word(&lx, atCommandStart: start == lineStart || isWordBreak(lx.unit(at: start - 1)))
}
}
}
private static func isOperator(_ c: UInt16) -> Bool {
c == Unit.less || c == Unit.greater || c == Unit.equals || c == Unit.bang || c == Unit.amp || c == Unit.pipe
}
private static func isWordBreak(_ c: UInt16) -> Bool {
switch c {
case Unit.space, Unit.tab, Unit.pipe, Unit.amp, Unit.semicolon, Unit.lparen, Unit.rparen,
Unit.less, Unit.greater, Unit.lbrace, Unit.rbrace, Unit.backtick, 13: true
default: false
}
}
/// One shell word: `NAME=` assigns, a bare keyword or builtin is coloured, digits are a number.
private static func word(_ lx: inout Lexer, atCommandStart: Bool) {
let start = lx.i
while lx.i < lx.end && Unit.isIdentPart(lx.u[lx.i]) { lx.i += 1 }
let identEnd = lx.i
if identEnd > start && atCommandStart && lx.peek() == Unit.equals && !Unit.isDigit(lx.u[start]) {
lx.emit(start, identEnd, .variable)
return
}
while lx.i < lx.end && !isWordBreak(lx.u[lx.i]) && !isQuoteOrDollar(lx.u[lx.i]) { lx.i += 1 }
guard lx.i == identEnd, identEnd > start else {
if lx.i == start { lx.i += 1 }
return
}
let text = lx.text(start, identEnd)
if keywords.contains(text) {
lx.emit(start, identEnd, .keyword)
} else if builtins.contains(text) || text.utf16.allSatisfy(Unit.isDigit) {
lx.emit(start, identEnd, .number)
}
}
private static func isQuoteOrDollar(_ c: UInt16) -> Bool {
c == Unit.quote || c == Unit.apostrophe || c == Unit.dollar
}
/// `$name`, `$1`, `$@`, `${…}`; `$(` is left plain for the command inside it.
private static func variable(_ lx: inout Lexer) {
let start = lx.i
lx.i += 1
let next = lx.peek()
if next == Unit.lbrace {
while lx.i < lx.end && lx.u[lx.i] != Unit.rbrace { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
} else if Unit.isIdentStart(next) {
lx.identifier()
} else if Unit.isDigit(next) || "@*#?$!-".utf16.contains(next) {
lx.i += 1
} else {
return
}
lx.emit(start, lx.i, .variable)
}
/// A quoted body; double quotes interpolate `$…`. False when the line ends first.
private static func string(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if quote == Unit.quote && c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == quote {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if quote == Unit.quote && c == Unit.dollar && (Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.lbrace) {
lx.emit(runStart, lx.i, .string)
variable(&lx)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<ID`, `<<-ID`, `<<'ID'` or `<<"ID"`; a quoted marker turns interpolation off.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 2
if lx.unit(at: k) == Unit.minus { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 2
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.emit(start, idStart - (quoted ? 1 : 0), .keyword)
lx.emit(idStart - (quoted ? 1 : 0), k, .string)
lx.i = k
st.mode = .heredoc(id: id, interpolates: !quoted)
}
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && k + marker.count == lx.end {
lx.i = lx.end
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
var runStart = start
while lx.i < lx.end {
if interpolates && lx.u[lx.i] == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let before = lx.i
variable(&lx)
if lx.i == before { lx.i += 1 }
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
}
}
@@ -0,0 +1,236 @@
import Foundation
/// The six syntax roles of the design, plus the ⌘-clickable class name.
public enum TokenRole: String, Sendable, Equatable {
/// Plain text and function names.
case plain
/// Variables and properties.
case variable
case comment
/// Keywords, operators, pseudo-classes.
case keyword
/// Strings, values, type paths.
case string
/// Numbers, tags, hex literals.
case number
/// A class name the project declares, underlined while ⌘ is held (PHP only).
case symbol
}
/// A run of one role, as a UTF-16 range into the highlighted text (NSAttributedString-friendly).
public struct Token: Sendable, Equatable {
public var location: Int
public var length: Int
public var role: TokenRole
public init(location: Int, length: Int, role: TokenRole) {
self.location = location
self.length = length
self.role = role
}
}
/// What the tokenizer carries from the end of one line to the start of the next.
///
/// An editor keeps the state after every line; after an edit it re-tokenizes from the
/// edited line until the state it computes equals the one it stored.
public struct HighlightState: Sendable, Hashable {
let grammar: Grammar?
var state = GrammarState()
/// The state before the first line. A PHP buffer containing `<?` reads as HTML with PHP islands.
public init(language: Language?, text: String = "") {
grammar = Grammar(language, text: text)
}
/// True when a construct is still open, such as a block comment or a heredoc.
public var isInsideConstruct: Bool {
state.mode != .code || state.child != nil || !state.resumes.isEmpty
}
}
public enum SyntaxHighlighter {
/// Tokenises a whole buffer; unmarked stretches are `.plain`.
///
/// Runs on every keystroke in the editable view, so it must stay linear in the text
/// length. Multi-line constructs (block comments, heredocs, template strings) carry
/// state across lines. PHP class-name tokens found in `knownSymbols` become `.symbol`.
/// The tokens cover the text end to end, in order, adjacent runs of one role merged.
public static func tokens(for text: String, language: Language?, knownSymbols: Set<String> = []) -> [Token] {
let units = Array(text.utf16)
var state = HighlightState(language: language, text: text)
var lexer = Lexer(units: units, symbols: knownSymbols)
if state.grammar != nil {
var lineStart = 0
while lineStart <= units.count {
var lineEnd = lineStart
while lineEnd < units.count && units[lineEnd] != 10 { lineEnd += 1 }
lexer.i = lineStart
lexer.end = lineEnd
scanLine(&lexer, &state)
lineStart = lineEnd + 1
}
}
return filled(lexer.tokens, length: units.count)
}
/// Tokenises one line on its own, for the diff panes where every line stands alone.
public static func lineTokens(for line: String, language: Language?, knownSymbols: Set<String> = []) -> [Token] {
var state = HighlightState(language: language, text: line)
return lineTokens(for: line, state: &state, knownSymbols: knownSymbols)
}
/// Tokenises one line (without its newline) starting from `state`, and advances `state` past it.
public static func lineTokens(for line: String, state: inout HighlightState, knownSymbols: Set<String> = []) -> [Token] {
let units = Array(line.utf16)
var lexer = Lexer(units: units, symbols: knownSymbols)
scanLine(&lexer, &state)
return filled(lexer.tokens, length: units.count)
}
private static func scanLine(_ lexer: inout Lexer, _ state: inout HighlightState) {
guard let grammar = state.grammar else { return }
Grammars.scan(grammar, &lexer, &state.state)
}
/// Fills the gaps between role tokens with `.plain`, so the tokens tile the text.
private static func filled(_ tokens: [Token], length: Int) -> [Token] {
var out: [Token] = []
out.reserveCapacity(tokens.count * 2 + 1)
var position = 0
for token in tokens {
let start = max(token.location, position)
let end = min(token.location + token.length, length)
guard end > start else { continue }
if start > position { out.append(Token(location: position, length: start - position, role: .plain)) }
out.append(Token(location: start, length: end - start, role: token.role))
position = end
}
if position < length { out.append(Token(location: position, length: length - position, role: .plain)) }
return out
}
}
/// One tokenizer; several `Language`s share one (the JavaScript family), and PHP has two.
enum Grammar: Hashable, Sendable {
case javascript(typescript: Bool, jsx: Bool)
case php
/// HTML with `<?php … ?>` islands.
case phpTemplate
case markup
case css
case json
case markdown
case bash
case python
case yaml
init?(_ language: Language?, text: String) {
switch language {
case nil: return nil
case .php: self = text.contains("<?") ? .phpTemplate : .php
case .javascript: self = .javascript(typescript: false, jsx: false)
case .jsx: self = .javascript(typescript: false, jsx: true)
case .typescript: self = .javascript(typescript: true, jsx: false)
case .tsx: self = .javascript(typescript: true, jsx: true)
case .markup: self = .markup
case .css: self = .css
case .json: self = .json
case .markdown: self = .markdown
case .bash: self = .bash
case .python: self = .python
case .yaml: self = .yaml
}
}
}
/// The construct a grammar is inside at a line break.
enum Mode: Hashable, Sendable {
case code
case blockComment
/// A string that may run over lines: PHP and shell quotes.
case quoted(UInt16)
/// A JavaScript template literal.
case template
/// A Python triple-quoted string.
case triple(UInt16)
/// PHP `<<<ID` or shell `<<ID`; `interpolates` is false for nowdoc and quoted shell markers.
case heredoc(id: String, interpolates: Bool)
case markupComment
case cdata
/// Inside `<name …` before its `>`; closing tags keep their leading slash.
case markupTag(String)
case markupValue(quote: UInt16, tag: String)
/// Inside a JSX tag; `level` counts the elements open around it, a closing tag included.
case jsxTag(level: Int, closing: Bool)
/// JSX children text inside `level` open elements.
case jsxText(level: Int)
/// A CSS declaration value that did not end on its line.
case cssValue
/// A YAML `|` or `>` block, holding the indent of its key.
case yamlBlock(indent: Int)
/// A Markdown fence, closed by `count` or more `marker` characters.
case fence(marker: UInt16, count: Int)
}
struct GrammarState: Hashable, Sendable {
var mode: Mode = .code
/// Brace depth: CSS nesting, or the braces inside a `${…}` or JSX `{…}` expression.
var depth = 0
/// For each open `${` or JSX `{`, where its closing `}` returns to.
var resumes: [Resume] = []
var child: Embedded?
}
/// The brace depth at which a `}` ends an embedded expression, and the mode it returns to.
struct Resume: Hashable, Sendable {
var depth: Int
var mode: Mode
}
/// A grammar running inside another: PHP in HTML, a `<script>` body, a fenced block.
indirect enum Embedded: Hashable, Sendable {
case grammar(Grammar, GrammarState, until: Terminator)
}
enum Grammars {
/// Scans the rest of the line, handing over to and back from embedded grammars.
static func scan(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
while true {
if case let .grammar(inner, innerState, terminator)? = st.child, terminator != .fence {
var state = innerState
let outerStop = lx.stop
lx.stop = terminator
scan(inner, &lx, &state)
lx.stop = outerStop
guard lx.i < lx.end else {
st.child = .grammar(inner, state, until: terminator)
return
}
if terminator == .phpClose {
lx.emit(lx.i, lx.i + 2, .keyword)
lx.i += 2
}
st.child = nil
}
guard lx.i < lx.end else { return }
scanOwn(grammar, &lx, &st)
guard case let .grammar(_, _, terminator)? = st.child, terminator != .fence, lx.i <= lx.end else { return }
}
}
private static func scanOwn(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
switch grammar {
case let .javascript(typescript, jsx): JavaScriptGrammar.scan(&lx, &st, typescript: typescript, jsx: jsx)
case .php: PHPGrammar.scan(&lx, &st)
case .phpTemplate: MarkupGrammar.scan(&lx, &st, phpIslands: true)
case .markup: MarkupGrammar.scan(&lx, &st, phpIslands: false)
case .css: CSSGrammar.scan(&lx, &st)
case .json: JSONGrammar.scan(&lx, &st)
case .markdown: MarkdownGrammar.scan(&lx, &st)
case .bash: ShellGrammar.scan(&lx, &st)
case .python: PythonGrammar.scan(&lx, &st)
case .yaml: YAMLGrammar.scan(&lx, &st)
}
}
}
@@ -0,0 +1,113 @@
import Foundation
enum YAMLGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let indent = k - lineStart
if case let .yamlBlock(parent) = st.mode {
if k == lx.end { return }
if indent > parent {
lx.i = lx.end
lx.emit(k, lx.end, .string)
return
}
st.mode = .code
}
var flow = 0
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || Unit.isSpace(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.minus where isIndicator(lx, start + 1):
lx.i += 1
case Unit.quote, Unit.apostrophe:
var k = start + 1
while k < lx.end && lx.u[k] != c {
k += c == Unit.quote && lx.u[k] == Unit.backslash ? 2 : 1
}
lx.i = min(k + 1, lx.end)
lx.emit(start, lx.i, isKeyColon(lx, lx.i) ? .keyword : .string)
case Unit.amp, Unit.star:
lx.i += 1
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) && !isFlowPunctuation(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .keyword)
case Unit.bang:
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .number)
case Unit.lbracket, Unit.lbrace:
flow += 1
lx.i += 1
case Unit.rbracket, Unit.rbrace:
flow = max(0, flow - 1)
lx.i += 1
case Unit.comma where flow > 0:
lx.i += 1
case Unit.pipe where isBlockIndicator(lx, start), Unit.greater where isBlockIndicator(lx, start):
lx.i = lx.end
st.mode = .yamlBlock(indent: indent)
default:
scalar(&lx, inFlow: flow > 0)
}
}
}
/// A `-` or `?` followed by a space or the line end.
private static func isIndicator(_ lx: Lexer, _ next: Int) -> Bool {
next >= lx.end || Unit.isSpace(lx.u[next])
}
private static func isFlowPunctuation(_ c: UInt16) -> Bool {
c == Unit.comma || c == Unit.rbracket || c == Unit.rbrace
}
/// A `:` right at `j` that ends a key.
private static func isKeyColon(_ lx: Lexer, _ j: Int) -> Bool {
lx.unit(at: j) == Unit.colon && isIndicator(lx, j + 1)
}
/// `|` or `>` with optional chomping/indent flags, then only a comment or nothing.
private static func isBlockIndicator(_ lx: Lexer, _ j: Int) -> Bool {
var k = j + 1
while k < lx.end && (lx.u[k] == Unit.minus || lx.u[k] == Unit.plus || Unit.isDigit(lx.u[k])) { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
return k == lx.end || lx.u[k] == Unit.hash
}
/// A plain scalar: a key when a `: ` follows, else a boolean, null, number or plain text.
private static func scalar(_ lx: inout Lexer, inFlow: Bool) {
let start = lx.i
var lastSolid = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.colon && isIndicator(lx, lx.i + 1) { break }
if c == Unit.hash && lx.i > start && Unit.isSpace(lx.u[lx.i - 1]) { break }
if inFlow && isFlowPunctuation(c) { break }
if !Unit.isSpace(c) { lastSolid = lx.i + 1 }
lx.i += 1
}
if lx.i == start {
lx.i += 1
return
}
if isKeyColon(lx, lx.i) {
lx.emit(start, lastSolid, .keyword)
lx.i += 1
return
}
let value = lx.text(start, lastSolid).lowercased()
if value == "true" || value == "false" || value == "null" || value == "~" {
lx.emit(start, lastSolid, .keyword)
} else if value.wholeMatch(of: /[+-]?(?:0x[0-9a-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/) != nil {
lx.emit(start, lastSolid, .number)
}
}
}
@@ -0,0 +1,94 @@
import Foundation
/// The inline pass: a fixed order of rewrite rules that build nodes.
///
/// Each rule swaps its match for a placeholder that points at the node it built, so a later
/// rule can wrap earlier nodes (`**[a](b)**`) but never re-reads their text.
enum MarkdownInlineParser {
private static let open: Character = "\u{E000}"
private static let close: Character = "\u{E001}"
static func parse(_ source: String, baseDir: String) -> [MarkdownInline] {
var held: [MarkdownInline] = []
func hold(_ node: MarkdownInline) -> String {
held.append(node)
return "\(open)\(held.count - 1)\(close)"
}
func expand(_ text: Substring) -> [MarkdownInline] {
expandPlaceholders(text, held)
}
var s = source.replacing(/`([^`]+)`/) { hold(.code(String($0.1))) }
s = s.replacing(/!\[([^\]]*)\]\(([^)]*)\)/) { match in
let alt = plainText(expand(match.1))
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return alt }
let source: ImageSource
if MarkdownParser.isLocalURL(safe) {
source = .local(path: MarkdownParser.resolveRelative(baseDir: baseDir, url: safe))
} else if let remote = URL(string: safe) {
source = .remote(remote)
} else {
return alt
}
return hold(.image(alt: alt, source: source, title: title))
}
s = s.replacing(/\[([^\]]+)\]\(([^)]*)\)/) { match in
let (url, title) = destination(match.2)
guard let safe = MarkdownParser.safeURL(url), !safe.isEmpty else { return String(match.1) }
return hold(.link(text: expand(match.1), url: safe, title: title))
}
s = s.replacing(/\*\*([^*]+)\*\*/) { hold(.strong(expand($0.1))) }
s = s.replacing(/__([^_]+)__/) { hold(.strong(expand($0.1))) }
s = s.replacing(/\*([^*]+)\*/) { hold(.emphasis(expand($0.1))) }
s = s.replacing(/(^|[^a-zA-Z0-9_])_([^_]+)_(?=[^a-zA-Z0-9_]|$)/) { String($0.1) + hold(.emphasis(expand($0.2))) }
s = s.replacing(/~~([^~]+)~~/) { hold(.strikethrough(expand($0.1))) }
return expand(Substring(s))
}
/// Splits `(url)`, `(url "title")` or `(<url> 'title')` into the URL and the optional title.
static func destination(_ raw: Substring) -> (url: String, title: String?) {
guard let match = raw.wholeMatch(of: /\s*(?:<([^>]*)>|([^\s)]*))(?:\s+["'(]([^"')]*)["')])?\s*/) else {
return (raw.trimmingCharacters(in: .whitespaces), nil)
}
let url = (match.1 ?? match.2 ?? "").trimmingCharacters(in: .whitespaces)
let title = match.3.map(String.init).flatMap { $0.isEmpty ? nil : $0 }
return (url, title)
}
/// Text with placeholders turned back into the nodes they stand for.
private static func expandPlaceholders(_ text: Substring, _ held: [MarkdownInline]) -> [MarkdownInline] {
var nodes: [MarkdownInline] = []
var plain = ""
var index = text.startIndex
while index < text.endIndex {
let c = text[index]
if c == open, let end = text[index...].firstIndex(of: close),
let slot = Int(text[text.index(after: index)..<end]), held.indices.contains(slot) {
if !plain.isEmpty {
nodes.append(.text(plain))
plain = ""
}
nodes.append(held[slot])
index = text.index(after: end)
continue
}
plain.append(c)
index = text.index(after: index)
}
if !plain.isEmpty { nodes.append(.text(plain)) }
return nodes
}
/// The visible text of nodes, for an image's alt text.
static func plainText(_ nodes: [MarkdownInline]) -> String {
nodes.map { node in
switch node {
case let .text(text), let .code(text): text
case let .strong(children), let .emphasis(children), let .strikethrough(children): plainText(children)
case let .link(children, _, _): plainText(children)
case let .image(alt, _, _): alt
}
}.joined()
}
}
@@ -0,0 +1,33 @@
import Foundation
public enum TableAlignment: String, Sendable, Equatable {
case left, center, right
}
public enum ImageSource: Sendable, Equatable {
/// A project-relative file, read through FileServicing.
case local(path: String)
case remote(URL)
}
public indirect enum MarkdownInline: Sendable, Equatable {
case text(String)
case code(String)
case strong([MarkdownInline])
case emphasis([MarkdownInline])
case strikethrough([MarkdownInline])
case link(text: [MarkdownInline], url: String, title: String?)
case image(alt: String, source: ImageSource, title: String?)
}
public indirect enum MarkdownBlock: Sendable, Equatable {
case heading(level: Int, content: [MarkdownInline])
case paragraph([MarkdownInline])
/// A fenced block; `language` is nil when the info string is unknown.
case code(language: Language?, text: String)
case quote([MarkdownBlock])
case list(ordered: Bool, items: [[MarkdownInline]])
/// Header cells, per-column alignment, then body rows padded to the header width.
case table(header: [[MarkdownInline]], alignments: [TableAlignment?], rows: [[[MarkdownInline]]])
case rule
}
@@ -0,0 +1,215 @@
import Foundation
public enum MarkdownParser {
/// Parses a subset of Markdown: ATX headings, fenced code, rules, GFM
/// tables, block quotes (recursive), bullet and ordered lists, paragraphs, and inline
/// code, images, links, strong, emphasis and strikethrough.
///
/// Code spans are protected before any other inline rule runs. `baseDir` is the
/// document's folder, used to resolve local image paths. Unsafe URL schemes are dropped.
public static func parse(_ text: String, baseDir: String = "") -> [MarkdownBlock] {
let normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
func flushParagraph() {
guard !paragraph.isEmpty else { return }
blocks.append(.paragraph(MarkdownInlineParser.parse(paragraph.joined(separator: " "), baseDir: baseDir)))
paragraph = []
}
func inline(_ text: String) -> [MarkdownInline] {
MarkdownInlineParser.parse(text, baseDir: baseDir)
}
var i = 0
while i < lines.count {
let line = lines[i]
if let fence = line.wholeMatch(of: /```\s*([\w+-]*)\s*/) {
flushParagraph()
var code: [String] = []
i += 1
while i < lines.count && lines[i].wholeMatch(of: /```\s*/) == nil {
code.append(lines[i])
i += 1
}
i += 1
blocks.append(.code(language: fenceLanguage(String(fence.1)), text: code.joined(separator: "\n")))
continue
}
if isBlank(line) {
flushParagraph()
i += 1
continue
}
if let heading = line.wholeMatch(of: /(#{1,6})\s+(.*)/) {
flushParagraph()
blocks.append(.heading(level: heading.1.count, content: inline(trimmed(heading.2))))
i += 1
continue
}
if isRule(line) {
flushParagraph()
blocks.append(.rule)
i += 1
continue
}
if line.contains("|") && i + 1 < lines.count {
let header = splitRow(line)
if let alignments = tableAlignments(lines[i + 1]), alignments.count == header.count {
flushParagraph()
i += 2
var rows: [[[MarkdownInline]]] = []
while i < lines.count && lines[i].contains("|") && !isBlank(lines[i]) {
let cells = splitRow(lines[i])
rows.append(header.indices.map { inline($0 < cells.count ? cells[$0] : "") })
i += 1
}
blocks.append(.table(header: header.map(inline), alignments: alignments, rows: rows))
continue
}
}
if line.prefixMatch(of: /\s*>/) != nil {
flushParagraph()
var quoted: [String] = []
while i < lines.count, let marker = lines[i].prefixMatch(of: /\s*>\s?/) {
quoted.append(String(lines[i][marker.range.upperBound...]))
i += 1
}
blocks.append(.quote(parse(quoted.joined(separator: "\n"), baseDir: baseDir)))
continue
}
if let items = listItems(lines, &i, marker: /\s*[-*+]\s+/) {
flushParagraph()
blocks.append(.list(ordered: false, items: items.map(inline)))
continue
}
if let items = listItems(lines, &i, marker: /\s*\d+[.)]\s+/) {
flushParagraph()
blocks.append(.list(ordered: true, items: items.map(inline)))
continue
}
paragraph.append(trimmed(line))
i += 1
}
flushParagraph()
return blocks
}
/// The consecutive lines that start with `marker`, stripped of it; nil when line `i` does not.
private static func listItems(_ lines: [String], _ i: inout Int, marker: Regex<Substring>) -> [String]? {
var items: [String] = []
while i < lines.count, let match = lines[i].prefixMatch(of: marker) {
items.append(String(lines[i][match.range.upperBound...]))
i += 1
}
return items.isEmpty ? nil : items
}
private static func isBlank(_ line: String) -> Bool {
line.allSatisfy(\.isWhitespace)
}
private static func trimmed<S: StringProtocol>(_ text: S) -> String {
text.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ line: String) -> Bool {
let marks = line.filter { !$0.isWhitespace }
guard marks.count >= 3, let first = marks.first, "-*_".contains(first) else { return false }
return marks.allSatisfy { $0 == first }
}
/// One GFM table row split into trimmed cells; `\\|` is a literal pipe, not a divider.
static func splitRow(_ line: String) -> [String] {
var row = Substring(trimmed(line))
if row.hasPrefix("|") { row = row.dropFirst() }
if row.hasSuffix("|") && !row.dropLast().hasSuffix("\\") { row = row.dropLast() }
var cells: [String] = []
var current = ""
var index = row.startIndex
while index < row.endIndex {
let c = row[index]
let next = row.index(after: index)
if c == "\\" && next < row.endIndex && row[next] == "|" {
current.append("|")
index = row.index(after: next)
continue
}
if c == "|" {
cells.append(current)
current = ""
} else {
current.append(c)
}
index = next
}
cells.append(current)
return cells.map { trimmed($0) }
}
/// The `---`/`:---:` row under a table header, as per-column alignments; nil when the line is not one.
static func tableAlignments(_ line: String) -> [TableAlignment?]? {
if !line.contains("|") && line.wholeMatch(of: /\s*:?-+:?\s*/) == nil { return nil }
var alignments: [TableAlignment?] = []
for cell in splitRow(line) {
guard cell.wholeMatch(of: /:?-+:?/) != nil else { return nil }
let left = cell.hasPrefix(":"), right = cell.hasSuffix(":")
alignments.append(left && right ? .center : right ? .right : left ? .left : nil)
}
return alignments
}
private static let fenceLanguages: [String: Language] = [
"php": .php, "js": .javascript, "javascript": .javascript, "mjs": .javascript,
"jsx": .jsx, "ts": .typescript, "typescript": .typescript, "tsx": .tsx,
"py": .python, "python": .python, "html": .markup, "xml": .markup, "vue": .markup,
"css": .css, "scss": .css, "json": .json, "sh": .bash, "bash": .bash, "shell": .bash,
"yml": .yaml, "yaml": .yaml, "md": .markdown, "markdown": .markdown,
]
/// The highlighter grammar for a fence info string.
public static func fenceLanguage(_ info: String) -> Language? {
fenceLanguages[info.lowercased()]
}
/// Keeps http(s), mailto, anchors and relative paths; returns nil for any other scheme (e.g. `javascript:`).
public static func safeURL(_ url: String) -> String? {
let u = url.trimmingCharacters(in: .whitespaces)
if u.range(of: "^(https?:|mailto:|#|\\.?\\.?/)", options: [.regularExpression, .caseInsensitive]) != nil { return u }
if u.range(of: "^[a-z][a-z0-9+.-]*:", options: [.regularExpression, .caseInsensitive]) != nil { return nil }
return u
}
/// True when a URL names a file next to the document rather than a remote resource.
public static func isLocalURL(_ url: String) -> Bool {
url.range(of: "^(https?:|data:|mailto:|#)", options: [.regularExpression, .caseInsensitive]) == nil
}
/// Resolves a document link to a project-relative path; a leading `/` means the project root.
public static func resolveRelative(baseDir: String, url: String) -> String {
var u = String(url.split(separator: "#", omittingEmptySubsequences: false).first ?? "")
u = String(u.split(separator: "?", omittingEmptySubsequences: false).first ?? "")
u = u.removingPercentEncoding ?? u
let joined = u.hasPrefix("/") ? u : baseDir + "/" + u
var out: [Substring] = []
for segment in joined.split(separator: "/", omittingEmptySubsequences: true) {
if segment == "." { continue }
if segment == ".." {
_ = out.popLast()
continue
}
out.append(segment)
}
return out.joined(separator: "/")
}
}
+62
View File
@@ -0,0 +1,62 @@
import Foundation
public enum Fuzzy {
/// Case-insensitive subsequence match: the matched character offsets in `text`, or nil.
public static func match(_ query: String, in text: String) -> [Int]? {
let q = Array(query.lowercased())
var indices: [Int] = []
var qi = 0
for (offset, ch) in text.lowercased().enumerated() where qi < q.count {
if ch == q[qi] {
indices.append(offset)
qi += 1
}
}
return qi == q.count ? indices : nil
}
/// File-name results: basename matches before path matches, then earlier first hit, then shorter path.
public static func rankFileNames(query: String, paths: [String], showHidden: Bool) -> [FileNameMatch] {
let term = query.trimmingCharacters(in: .whitespaces)
guard !term.isEmpty else { return [] }
var out: [FileNameMatch] = []
for path in paths {
if !showHidden && PathUtils.isHidden(path) { continue }
if let indices = match(term, in: PathUtils.basename(path)) {
out.append(FileNameMatch(path: path, nameIndices: indices, rank: 0, position: indices[0]))
} else if let indices = match(term, in: path) {
out.append(FileNameMatch(path: path, nameIndices: nil, rank: 1, position: indices[0]))
}
}
return out.sorted {
($0.rank, $0.position, $0.path.count) < ($1.rank, $1.position, $1.path.count)
}
}
}
public enum InFileSearch {
/// Case-insensitive substring hits in one buffer, for the search overlay's "this file" column.
public static func hits(query: String, in text: String) -> [ContentHit] {
let term = query.trimmingCharacters(in: .whitespaces)
guard !term.isEmpty else { return [] }
var hits: [ContentHit] = []
for (index, line) in text.components(separatedBy: "\n").enumerated() {
if let range = line.range(of: term, options: .caseInsensitive) {
hits.append(ContentHit(line: index + 1, text: line, matchOffset: line.utf16.distance(from: line.startIndex, to: range.lowerBound)))
}
}
return hits
}
/// Extension chips for the result set: most matches first, then alphabetical, capped at 12.
public static func extensionCounts(paths: [String]) -> [(ext: String, count: Int)] {
var counts: [String: Int] = [:]
for path in paths {
let e = FileType.ext(path)
if !e.isEmpty { counts[e, default: 0] += 1 }
}
return counts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
.prefix(SearchLimits.maxExtensionChips)
.map { (ext: $0.key, count: $0.value) }
}
}
+114
View File
@@ -0,0 +1,114 @@
import Foundation
/// One `"type":"match"` event from `rg --json`.
public struct RipgrepMatch: Sendable, Equatable {
/// The path as ripgrep printed it (absolute when the search root was absolute).
public var path: String
public var line: Int
/// The line text without its trailing newline.
public var text: String
/// Byte offset of the first submatch, as ripgrep reports it.
public var byteOffset: Int
public init(path: String, line: Int, text: String, byteOffset: Int) {
self.path = path
self.line = line
self.text = text
self.byteOffset = byteOffset
}
}
public enum RipgrepJSON {
/// Decodes one line of `rg --json` output; nil for every event that is not a match.
///
/// An event carrying `path.bytes` or `lines.bytes` (base64, non-UTF-8 data) is skipped.
/// Offsets stay in bytes here; `ContentGrouper` turns them into UTF-16.
public static func parseLine(_ line: String) -> RipgrepMatch? {
guard line.contains("\"match\""),
let event = try? JSONDecoder().decode(Event.self, from: Data(line.utf8)),
event.type == "match",
let data = event.data,
let path = data.path?.text,
var text = data.lines?.text
else { return nil }
if text.unicodeScalars.last == "\n" { text.unicodeScalars.removeLast() }
if text.unicodeScalars.last == "\r" { text.unicodeScalars.removeLast() }
return RipgrepMatch(path: path, line: data.line_number ?? 0, text: text, byteOffset: data.submatches?.first?.start ?? 0)
}
/// The slice of an `rg --json` event this reader needs; a `bytes` field decodes as a nil `text`.
private struct Event: Decodable {
struct TextField: Decodable {
var text: String?
}
struct Submatch: Decodable {
var start: Int
}
struct Payload: Decodable {
var path: TextField?
var lines: TextField?
var line_number: Int?
var submatches: [Submatch]?
}
var type: String
var data: Payload?
}
/// Makes a ripgrep path relative to the project root, "/"-separated.
public static func relativePath(_ path: String, root: String) -> String {
let base = root.hasSuffix("/") ? root : root + "/"
return path.hasPrefix(base) ? String(path.dropFirst(base.count)) : path
}
}
/// Collects matches into per-file groups in first-seen order, honouring the search limits.
public struct ContentGrouper: Sendable {
public let root: String
public private(set) var groups: [ContentGroup] = []
public init(root: String) {
self.root = root
}
/// Adds a match: new files beyond `SearchLimits.maxFiles` are dropped, the line text is
/// capped at `maxLineLength`, and the byte offset becomes a clamped UTF-16 `matchOffset`.
public mutating func add(_ match: RipgrepMatch) {
let path = RipgrepJSON.relativePath(match.path, root: root)
let index: Int
if let existing = indexByPath[path] {
index = existing
} else {
guard groups.count < SearchLimits.maxFiles else { return }
index = groups.count
indexByPath[path] = index
groups.append(ContentGroup(path: path, hits: []))
}
guard groups[index].hits.count < SearchLimits.maxHitsPerFile else { return }
let text = ContentGrouper.capped(match.text)
let offset = ContentGrouper.utf16Offset(ofByte: match.byteOffset, in: match.text)
groups[index].hits.append(ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count)))
}
private var indexByPath: [String: Int] = [:]
/// The line cut to `SearchLimits.maxLineLength` UTF-16 units, never inside a surrogate pair.
static func capped(_ text: String) -> String {
let utf16 = text.utf16
guard utf16.count > SearchLimits.maxLineLength else { return text }
var end = utf16.index(utf16.startIndex, offsetBy: SearchLimits.maxLineLength)
while end > utf16.startIndex && UTF16.isTrailSurrogate(utf16[end]) { end = utf16.index(before: end) }
return String(utf16[..<end]) ?? String(text.prefix(SearchLimits.maxLineLength))
}
/// ripgrep counts UTF-8 bytes; the views count UTF-16 units.
static func utf16Offset(ofByte byteOffset: Int, in text: String) -> Int {
let utf8 = text.utf8
guard byteOffset > 0 else { return 0 }
guard byteOffset < utf8.count else { return text.utf16.count }
var index = utf8.index(utf8.startIndex, offsetBy: byteOffset)
while index > utf8.startIndex && UTF8.isContinuation(utf8[index]) {
index = utf8.index(before: index)
}
return text.utf16.distance(from: text.utf16.startIndex, to: index)
}
}
@@ -0,0 +1,60 @@
import Foundation
/// One matching line.
public struct ContentHit: Sendable, Equatable {
/// 1-based line number.
public var line: Int
/// The line text, capped at `SearchLimits.maxLineLength` characters.
public var text: String
/// UTF-16 offset of the first match in `text`, clamped to its length.
public var matchOffset: Int
public init(line: Int, text: String, matchOffset: Int) {
self.line = line
self.text = text
self.matchOffset = matchOffset
}
}
/// All hits in one file, in the order ripgrep reported them.
public struct ContentGroup: Sendable, Equatable, Identifiable {
public var path: String
public var hits: [ContentHit]
public var id: String { path }
public init(path: String, hits: [ContentHit]) {
self.path = path
self.hits = hits
}
}
/// A file-name match in the search overlay's right column.
public struct FileNameMatch: Sendable, Equatable {
public var path: String
/// Matched character offsets in the basename; nil when only the full path matched.
public var nameIndices: [Int]?
/// 0 = basename match, 1 = path-only match; lower sorts first.
public var rank: Int
/// Offset of the first matched character; lower sorts first.
public var position: Int
public init(path: String, nameIndices: [Int]?, rank: Int, position: Int) {
self.path = path
self.nameIndices = nameIndices
self.rank = rank
self.position = position
}
}
public enum SearchLimits {
/// Content search starts at two characters; the in-file column at one.
public static let minContentQuery = 2
public static let maxFiles = 400
public static let maxLineLength = 1000
public static let maxHitsPerFile = 50
public static let maxFileNameResults = 40
public static let maxInFileResults = 200
public static let maxExtensionChips = 12
/// Keystroke debounce before a content search runs.
public static let debounceMilliseconds = 120
}
@@ -0,0 +1,62 @@
import Foundation
/// Which side of the window has focus; drives the fluid widths below 1600pt.
public enum FocusZone: String, Sendable, Equatable {
case neutral
case editor
case terminal
}
/// Pixel widths of the three fixed columns; the editor takes the remainder.
public struct ColumnWidths: Sendable, Equatable {
public var sourceControl: Double
public var explorer: Double
public var agent: Double
public init(sourceControl: Double, explorer: Double, agent: Double) {
self.sourceControl = sourceControl
self.explorer = explorer
self.agent = agent
}
}
public enum ColumnLayout {
/// At and above this width every column fits and focus changes nothing.
public static let roomyWidth = 1600.0
public static let minEditorWidth = 280.0
public static let splitterWidth = 1.0
public static let sourceControlRange = 160.0...460.0
public static let explorerRange = 160.0...520.0
/// Fluid widths for a window. Roomy: 13.4% · 16.4% · flex · 27.3% (the design's
/// 236 · 288 · flex · 480 on a 1760 frame). Tight: 15% · 15%, and the agent column
/// takes 30%, or 20% with the editor focused, or 50% with a terminal focused.
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
if w >= roomyWidth {
return ColumnWidths(sourceControl: (w * 0.134).rounded(), explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
}
let agentShare = focus == .terminal ? 0.5 : focus == .editor ? 0.2 : 0.3
return ColumnWidths(sourceControl: (w * 0.15).rounded(), explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
}
/// Scales the fixed columns down so the editor keeps `minEditorWidth`; unchanged when they fit.
public static func fitted(_ widths: ColumnWidths, windowWidth: Double, sourceControlVisible: Bool) -> ColumnWidths {
let splitters = (sourceControlVisible ? 3.0 : 2.0) * splitterWidth
let budget = windowWidth - splitters - minEditorWidth
let total = (sourceControlVisible ? widths.sourceControl : 0) + widths.explorer + widths.agent
guard total > budget, total > 0 else { return widths }
let k = max(0, budget) / total
return ColumnWidths(
sourceControl: sourceControlVisible ? (widths.sourceControl * k).rounded(.down) : widths.sourceControl,
explorer: (widths.explorer * k).rounded(.down),
agent: (widths.agent * k).rounded(.down)
)
}
/// The widest the agent column may be dragged: until the editor would drop below its minimum.
public static func maxAgentWidth(windowWidth: Double, widths: ColumnWidths, sourceControlVisible: Bool) -> Double {
let splitters = (sourceControlVisible ? 3.0 : 2.0) * splitterWidth
let others = (sourceControlVisible ? widths.sourceControl : 0) + widths.explorer
return max(minEditorWidth, windowWidth - splitters - others - minEditorWidth)
}
}
@@ -0,0 +1,44 @@
import Foundation
/// Caret position shown in the status bar; 1-based.
public struct Cursor: Sendable, Equatable {
public var path: String
public var line: Int
public var column: Int
public init(path: String, line: Int, column: Int) {
self.path = path
self.line = line
self.column = column
}
}
/// A line-range selection in a read-only pane; `anchor` is where the drag started.
public struct LineSelection: Sendable, Equatable {
public var path: String
public var start: Int
public var end: Int
public var anchor: Int
public init(path: String, start: Int, end: Int, anchor: Int) {
self.path = path
self.start = min(start, end)
self.end = max(start, end)
self.anchor = anchor
}
public var reference: AgentReference { AgentReference(path: path, startLine: start, endLine: end) }
}
/// How a file is opened: from a git row (`side`), at a line (search hit, symbol), or straight into Diff.
public struct OpenOptions: Sendable, Equatable {
public var side: DiffSide?
public var line: Int?
public var showDiff: Bool
public init(side: DiffSide? = nil, line: Int? = nil, showDiff: Bool = false) {
self.side = side
self.line = line
self.showDiff = showDiff
}
}
@@ -0,0 +1,78 @@
/// Per-project editor session, restored on launch when `session.restoreOnLaunch` is on.
public struct SessionState: Codable, Sendable, Equatable {
public var active: String?
public var modes: [String: ViewMode]
/// Which git row opened each file; only the Diff overlay follows it.
public var sides: [String: DiffSide]
public init(active: String? = nil, modes: [String: ViewMode] = [:], sides: [String: DiffSide] = [:]) {
self.active = active
self.modes = modes
self.sides = sides
}
private enum CodingKeys: String, CodingKey {
case active
case modes = "tabMode"
case sides = "tabSide"
}
/// A stored mode this build does not know is dropped, not the whole map.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
active = try? c.decodeIfPresent(String.self, forKey: .active)
let raw = (try? c.decodeIfPresent([String: String].self, forKey: .modes)) ?? [:]
modes = raw.compactMapValues(ViewMode.init(rawValue:))
sides = (try? c.decodeIfPresent([String: DiffSide].self, forKey: .sides)) ?? [:]
}
/// The storage key; one session per project root.
public static func key(root: String) -> String { "helder.session:" + root }
}
/// Window-wide layout that survives a restart.
public struct LayoutState: Codable, Sendable, Equatable {
/// The agent pane's share of the right column's height.
public var agentFraction: Double
public init(agentFraction: Double = LayoutState.defaultAgentFraction) {
self.agentFraction = LayoutState.clampAgentFraction(agentFraction)
}
public static let key = "helder.topFrac"
public static let defaultAgentFraction = 0.52
public static let agentFractionRange = 0.18...0.82
public static func clampAgentFraction(_ value: Double) -> Double {
min(max(value, agentFractionRange.lowerBound), agentFractionRange.upperBound)
}
}
public struct RecentProject: Codable, Sendable, Equatable, Identifiable {
public var path: String
public var name: String
public var id: String { path }
public init(path: String, name: String) {
self.path = path
self.name = name
}
}
public enum RecentLists {
/// Recent files per project, in `.helder/recent.json`.
public static let maxFiles = 100
/// Recent projects, machine-wide.
public static let maxProjects = 20
public static let recentFilesName = "recent.json"
/// Moves `path` to the front, de-duplicated and capped.
public static func pushing(_ path: String, onto list: [String], limit: Int = maxFiles) -> [String] {
Array(([path] + list.filter { $0 != path }).prefix(limit))
}
/// Moves a project to the front, keyed on its path, capped at 20.
public static func pushing(_ project: RecentProject, onto list: [RecentProject]) -> [RecentProject] {
Array(([project] + list.filter { $0.path != project.path }).prefix(maxProjects))
}
}
@@ -0,0 +1,97 @@
import Foundation
public struct PHPDeclaration: Sendable, Equatable {
public var kind: String
public var name: String
public var parents: [String]
public var interfaces: [String]
public init(kind: String, name: String, parents: [String], interfaces: [String]) {
self.kind = kind
self.name = name
self.parents = parents
self.interfaces = interfaces
}
}
public enum PHPSymbols {
/// ripgrep pattern for declarations and `namespace X;` lines in one pass.
public static let declarationPattern = #"^\s*(namespace\s+[A-Za-z_\\][\w\\]*\s*;|(final\s+|abstract\s+|readonly\s+)*(class|interface|trait|enum)\s+\w+)"#
/// ripgrep pattern for an indented `use` inside a class body.
public static let traitUsePattern = #"^\s+use\s+[A-Za-z_\\][\w\\ \t,]*[;{]"#
/// The declaration on one line, or nil. `final`/`abstract`/`readonly` may precede the keyword.
///
/// Only this line is read, so an `implements` list wrapped onto the next line yields
/// fewer interfaces, never wrong ones. Namespaced parents are reduced to short names.
public static func parseDeclaration(_ line: String) -> PHPDeclaration? {
let declaration = /^[ \t]*(?:(?:final|abstract|readonly)[ \t]+)*(class|interface|trait|enum)[ \t]+([A-Za-z_]\w*)(.*)$/
guard let match = line.firstMatch(of: declaration) else { return nil }
let rest = match.3
let extends = rest.firstMatch(of: /\bextends\s+([^{]*?)(?:\s+implements\b|\s*\{|$)/)
let implements = rest.firstMatch(of: /\bimplements\s+([^{]*?)(?:\s*\{|$)/)
return PHPDeclaration(
kind: String(match.1), name: String(match.2),
parents: extends.map { clauseNames($0.1) } ?? [],
interfaces: implements.map { clauseNames($0.1) } ?? []
)
}
/// The namespace a `namespace X;` line declares, without a leading backslash, or nil.
public static func parseNamespace(_ line: String) -> String? {
guard let match = line.firstMatch(of: /^[ \t]*namespace[ \t]+([A-Za-z_\\][\w\\]*)[ \t]*;/) else { return nil }
let name = match.1
return String(name.hasPrefix("\\") ? name.dropFirst() : name)
}
/// The traits an indented `use A, B;` mixes in; `use function`, `use const` and anything else give [].
public static func parseTraitUse(_ line: String) -> [String] {
guard let match = line.firstMatch(of: /^[ \t]+use[ \t]+([A-Za-z_\\][\w\\ \t,]*?)[ \t]*[;{]/),
line.firstMatch(of: /^\s*use\s+(function|const)\b/) == nil
else { return [] }
return clauseNames(match.1)
}
/// Short class names out of an `extends`/`implements`/`use` clause.
private static func clauseNames(_ clause: Substring) -> [String] {
clause.split(separator: ",", omittingEmptySubsequences: false).compactMap { part in
let last = part.trimmingCharacters(in: .whitespaces).split(separator: "\\", omittingEmptySubsequences: false).last ?? ""
let name = last.trimmingCharacters(in: .whitespaces)
return isIdentifier(name) ? name : nil
}
}
/// A column-0 `use` line: a namespace import, which reference search drops as noise.
public static func isImportLine(_ line: String) -> Bool {
line.range(of: #"^use[ \t]+[^;]*;?[ \t\r]*$"#, options: .regularExpression) != nil
}
/// True for a bare PHP identifier, the only thing a lookup accepts.
public static func isIdentifier(_ name: String) -> Bool {
name.range(of: #"^[A-Za-z_]\w*$"#, options: .regularExpression) != nil
}
/// Project declarations before `vendor/` ones, then by path, capped at `SymbolLimits.maxDefinitions`.
public static func sortDefinitions(_ defs: [SymbolDef]) -> [SymbolDef] {
let sorted = defs.sorted {
let lv = $0.path.hasPrefix("vendor/"), rv = $1.path.hasPrefix("vendor/")
return lv != rv ? !lv : $0.path < $1.path
}
return Array(sorted.prefix(SymbolLimits.maxDefinitions))
}
/// The identifier around a UTF-16 offset, or "" when the caret is not on one.
public static func word(in text: String, at offset: Int) -> String {
let units = Array(text.utf16)
guard offset >= 0, offset <= units.count else { return "" }
func isWord(_ u: UInt16) -> Bool {
(u >= 48 && u <= 57) || (u >= 65 && u <= 90) || (u >= 97 && u <= 122) || u == 95
}
var start = offset
while start > 0 && isWord(units[start - 1]) { start -= 1 }
var end = offset
while end < units.count && isWord(units[end]) { end += 1 }
let word = String(decoding: units[start..<end], as: UTF16.self)
return isIdentifier(word) ? word : ""
}
}
@@ -0,0 +1,66 @@
import Foundation
/// One class, interface, trait or enum declaration.
public struct SymbolDef: Sendable, Equatable, Codable {
public var name: String
public var path: String
public var line: Int
/// `class`, `interface`, `trait` or `enum`.
public var kind: String
/// The file's namespace, for the fully qualified name; "" when none.
public var namespace: String
/// `extends` on the declaration line, short names.
public var parents: [String]
/// `implements` on the declaration line, short names.
public var interfaces: [String]
/// Traits mixed in by an indented `use` in the body.
public var traits: [String]
public init(name: String, path: String, line: Int, kind: String, namespace: String = "",
parents: [String] = [], interfaces: [String] = [], traits: [String] = []) {
self.name = name
self.path = path
self.line = line
self.kind = kind
self.namespace = namespace
self.parents = parents
self.interfaces = interfaces
self.traits = traits
}
public var qualifiedName: String { namespace.isEmpty ? name : namespace + "\\" + name }
}
/// References to one name within one file.
public struct RefGroup: Sendable, Equatable {
public var path: String
public var hits: [ContentHit]
public init(path: String, hits: [ContentHit]) {
self.path = path
self.hits = hits
}
}
/// What a ⌘-click on a class name returns: where it is declared and where it is used.
public struct SymbolLookup: Sendable, Equatable {
public var name: String
public var definitions: [SymbolDef]
public var references: [RefGroup]
public var referenceCount: Int
public init(name: String, definitions: [SymbolDef] = [], references: [RefGroup] = [], referenceCount: Int = 0) {
self.name = name
self.definitions = definitions
self.references = references
self.referenceCount = referenceCount
}
public static func empty(_ name: String) -> SymbolLookup { SymbolLookup(name: name) }
}
public enum SymbolLimits {
public static let maxDefinitions = 25
public static let maxReferenceFiles = 300
public static let maxLineLength = 1000
}
@@ -0,0 +1,27 @@
import Foundation
enum DirectoryListing {
struct Entry {
enum Kind { case file, directory }
let name: String
let url: URL
let kind: Kind
}
/// Regular files and real folders of one folder in byte order of their names, dotfiles
/// included. Symlinks are left out, as ripgrep without `--follow` leaves them out.
static func entries(of directory: URL) -> [Entry] {
let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isRegularFileKey, .isDirectoryKey]
guard let urls = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: keys) else {
return []
}
return urls.compactMap { url -> Entry? in
guard let values = try? url.resourceValues(forKeys: Set(keys)), values.isSymbolicLink != true else { return nil }
if values.isDirectory == true { return Entry(name: url.lastPathComponent, url: url, kind: .directory) }
if values.isRegularFile == true { return Entry(name: url.lastPathComponent, url: url, kind: .file) }
return nil
}
.sorted { $0.name < $1.name }
}
}
@@ -0,0 +1,200 @@
import Foundation
import HelderCore
public struct FileService: FileServicing {
public let root: URL
private let search: SearchServicing
public init(root: URL, search: SearchServicing) {
self.root = root
self.search = search
}
/// Ripgrep's file list plus the empty folders it cannot see; without ripgrep, a walk.
public func tree() async -> FileNode {
if await search.isAvailable() {
async let paths = search.listFiles(under: nil)
async let empty = emptyDirectories()
let (files, folders) = await (paths, empty)
if !files.isEmpty || !folders.isEmpty {
return FileTree.build(rootName: rootName, paths: files, emptyDirs: folders)
}
}
return FileNode(name: rootName, kind: .directory, path: "", children: walk(""))
}
public func children(of directory: String) async -> [FileNode] {
guard absoluteURL(for: directory) != nil else { return [] }
guard await search.isAvailable() else { return walk(directory) }
async let paths = search.listFiles(under: directory)
async let empty = emptyDirectories(under: directory)
let tree = FileTree.build(rootName: rootName, paths: await paths, emptyDirs: await empty)
return FileTree.find(directory, in: tree)?.children ?? []
}
/// Folders under `scope` (or the root) whose whole subtree holds no file, relative to the root.
public func emptyDirectories(under scope: String? = nil) async -> [String] {
let start = scope ?? ""
guard let url = absoluteURL(for: start) else { return [] }
var out: [String] = []
/// Whether the subtree holds a file; empty folders are recorded on the way back up.
func hasFile(_ url: URL, rel: String, depth: Int) -> Bool {
var found = false
for entry in DirectoryListing.entries(of: url) where !IgnoreRules.isWalkIgnored(entry.name) {
switch entry.kind {
case .file:
found = true
case .directory:
let childRel = PathUtils.join(rel, entry.name)
if depth < FileLimits.maxWalkDepth && hasFile(entry.url, rel: childRel, depth: depth + 1) {
found = true
} else {
out.append(childRel)
}
}
}
return found
}
_ = hasFile(url, rel: start, depth: 0)
return out
}
public func read(_ path: String) async throws -> String {
switch try await readText(path) {
case let .text(text): text
case .binary: ""
}
}
public func readText(_ path: String) async throws -> FileContents {
guard let url = absoluteURL(for: path) else { throw FileServiceError.outsideProject }
let data = try Data(contentsOf: url)
return FileLimits.looksBinary(data) ? .binary : .text(String(decoding: data, as: UTF8.self))
}
public func readImage(_ path: String) async -> Data? {
guard FileLimits.imageMimeTypes[FileType.ext(path)] != nil, let url = absoluteURL(for: path),
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize,
size <= FileLimits.maxImageBytes else { return nil }
return try? Data(contentsOf: url)
}
public func write(_ path: String, contents: String) async throws {
guard let url = absoluteURL(for: path) else { throw FileServiceError.outsideProject }
let data = Data(contents.utf8)
guard exists(url) else {
guard let fresh = containedURL(for: path) else { throw FileServiceError.outsideProject }
try data.write(to: fresh, options: .withoutOverwriting)
return
}
try Self.replace(url.resolvingSymlinksInPath(), with: data)
}
public func createFile(_ path: String) async throws {
let url = try newEntryURL(path)
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
do {
try Data().write(to: url, options: .withoutOverwriting)
} catch CocoaError.fileWriteFileExists {
throw FileServiceError.alreadyExists(path)
}
}
public func createDirectory(_ path: String) async throws {
let url = try newEntryURL(path)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
}
/// A case-only rename (foo.md → Foo.md) is allowed only when both names reach the same file,
/// as on a case-insensitive disk; on a case-sensitive one `Foo.md` may be another file.
public func rename(_ path: String, to name: String) async throws -> String {
guard let clean = PathUtils.validatedName(name) else { throw FileServiceError.invalidName(name) }
let next = PathUtils.join(PathUtils.dirname(path), clean)
guard !path.isEmpty, let from = containedURL(for: path), let to = containedURL(for: next) else {
throw FileServiceError.outsideProject
}
if from.path == to.path { return path }
if Self.isSameFile(from, to) {
// rename(2): FileManager.moveItem refuses a case-only rename as "already exists".
guard Darwin.rename(from.path, to.path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
return next
}
if exists(to) { throw FileServiceError.alreadyExists(next) }
guard renamex_np(from.path, to.path, UInt32(RENAME_EXCL)) == 0 else {
if errno == EEXIST { throw FileServiceError.alreadyExists(next) }
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
return next
}
public func delete(_ path: String) async throws {
guard let url = containedURL(for: path), url.standardizedFileURL != root.standardizedFileURL else {
throw FileServiceError.outsideProject
}
guard (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil else { return }
try FileManager.default.removeItem(at: url)
}
/// Writes a sibling temp file with the old file's permissions, then renames it over the old one.
private static func replace(_ target: URL, with data: Data) throws {
let mode = (try? FileManager.default.attributesOfItem(atPath: target.path)[.posixPermissions] as? NSNumber)?.uint16Value ?? 0o644
let temp = target.deletingLastPathComponent().appendingPathComponent(".\(target.lastPathComponent).helder-\(UUID().uuidString)")
let fd = open(temp.path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode_t(mode))
guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
do {
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
try handle.write(contentsOf: data)
try handle.synchronize()
guard fchmod(fd, mode_t(mode)) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
try handle.close()
guard Darwin.rename(temp.path, target.path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
} catch {
unlink(temp.path)
throw error
}
}
/// True when both URLs name one existing file, as a case-only rename does on a case-insensitive disk.
private static func isSameFile(_ a: URL, _ b: URL) -> Bool {
guard a.path.lowercased() == b.path.lowercased() else { return false }
var first = stat(), second = stat()
guard lstat(a.path, &first) == 0, lstat(b.path, &second) == 0 else { return false }
return first.st_dev == second.st_dev && first.st_ino == second.st_ino
}
private var rootName: String {
root.lastPathComponent.isEmpty ? root.path : root.lastPathComponent
}
private func exists(_ url: URL) -> Bool {
(try? url.checkResourceIsReachable()) == true || FileManager.default.fileExists(atPath: url.path)
}
/// The URL for a file or folder about to be created; refuses the root, escapes and taken names.
private func newEntryURL(_ path: String) throws -> URL {
guard !path.isEmpty, let url = containedURL(for: path) else { throw FileServiceError.outsideProject }
if exists(url) { throw FileServiceError.alreadyExists(path) }
return url
}
/// The fallback tree below `directory`: ignored names skipped, folders first, then files.
private func walk(_ directory: String, depth: Int = 0) -> [FileNode] {
guard let url = absoluteURL(for: directory) else { return [] }
var folders: [FileNode] = []
var files: [FileNode] = []
for entry in DirectoryListing.entries(of: url) where !IgnoreRules.isWalkIgnored(entry.name) {
let rel = PathUtils.join(directory, entry.name)
switch entry.kind {
case .directory:
let children = depth < FileLimits.maxWalkDepth ? walk(rel, depth: depth + 1) : []
folders.append(FileNode(name: entry.name, kind: .directory, path: rel, children: children))
case .file:
files.append(FileNode(name: entry.name, kind: .file, path: rel))
}
}
let byName: (FileNode, FileNode) -> Bool = { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
return folders.sorted(by: byName) + files.sorted(by: byName)
}
}
@@ -0,0 +1,82 @@
import Foundation
import HelderCore
public enum FileServiceError: Error, Equatable {
case outsideProject
case alreadyExists(String)
case invalidName(String)
}
/// What a file holds, as far as the editor cares.
public enum FileContents: Equatable, Sendable {
case text(String)
/// A NUL byte in the first 8000 bytes.
case binary
}
public protocol FileServicing: Sendable {
var root: URL { get }
/// The project tree: ripgrep's file list (honouring the config) plus empty folders; a plain walk without ripgrep.
func tree() async -> FileNode
/// Fresh children of one folder ("" is the root), re-read on every expand and collapse.
func children(of directory: String) async -> [FileNode]
/// A text file's contents; "" for a binary file.
func read(_ path: String) async throws -> String
/// A file's text, or `.binary`, so an empty file and a binary one can be told apart.
func readText(_ path: String) async throws -> FileContents
/// An image's bytes; nil for a non-image, a file over 25 MB, or a path outside the project.
func readImage(_ path: String) async -> Data?
/// Replaces the file in one step; a symlinked file is written at its target and keeps its permissions.
func write(_ path: String, contents: String) async throws
/// Creates an empty file and its parent folders; throws `alreadyExists` rather than overwrite.
func createFile(_ path: String) async throws
func createDirectory(_ path: String) async throws
/// Renames within the same folder and returns the new relative path.
func rename(_ path: String, to name: String) async throws -> String
/// Deletes a file or a whole folder.
func delete(_ path: String) async throws
}
extension FileServicing {
/// Built on `read`, which cannot see binary files; only conformers that never meet them should rely on it.
public func readText(_ path: String) async throws -> FileContents {
.text(try await read(path))
}
/// The absolute URL for a relative path, or nil when it escapes the project root.
///
/// The check is on the spelling only, so a symlinked folder can still lead outside; anything
/// that creates, renames or deletes goes through `containedURL(for:)` instead.
public func absoluteURL(for path: String) -> URL? {
let base = root.standardizedFileURL
let target = (path.isEmpty ? base : base.appendingPathComponent(path)).standardizedFileURL
return Self.isInside(target.path, base.path) ? target : nil
}
/// `absoluteURL(for:)`, but nil unless the entry's folder, with every symlink resolved, lies inside the resolved root.
///
/// The entry itself is not resolved: deleting or renaming a symlink acts on the link, not on its target.
public func containedURL(for path: String) -> URL? {
guard let url = absoluteURL(for: path) else { return nil }
let realRoot = Self.realPath(root.standardizedFileURL.path)
if url.path == root.standardizedFileURL.path { return url }
let parent = Self.realPath(url.deletingLastPathComponent().path)
return Self.isInside(parent, realRoot) || parent == realRoot ? url : nil
}
private static func isInside(_ path: String, _ base: String) -> Bool {
let prefix = base.hasSuffix("/") ? base : base + "/"
return path == base || path.hasPrefix(prefix)
}
/// Resolves every symlink; a path that does not exist yet keeps its resolved existing ancestor.
static func realPath(_ path: String) -> String {
if let resolved = realpath(path, nil) {
defer { free(resolved) }
return String(cString: resolved)
}
let parent = (path as NSString).deletingLastPathComponent
guard !parent.isEmpty, parent != path else { return path }
return (realPath(parent) as NSString).appendingPathComponent((path as NSString).lastPathComponent)
}
}
@@ -0,0 +1,273 @@
import Foundation
import CoreServices
import HelderCore
public enum WatchEvent: Sendable, Equatable {
/// A project file changed. Also invalidates the symbol index.
case project
/// Git state moved (see `GitDirectory.watchedEntries`).
case git
/// `.helder/config.json` changed.
case config
}
public protocol FileWatching: AnyObject {
/// Starts watching; `handler` is called on an arbitrary queue. Calling again restarts the watch.
func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void)
func stop()
}
/// Quiet periods before each event fires; every new change inside the period restarts it.
public struct WatchDebounce: Sendable, Equatable {
public var project: TimeInterval
public var git: TimeInterval
public var config: TimeInterval
public init(project: TimeInterval, git: TimeInterval, config: TimeInterval) {
self.project = project
self.git = git
self.config = config
}
public static let standard = WatchDebounce(project: 0.25, git: 0.2, config: 0.1)
func interval(for event: WatchEvent) -> TimeInterval {
switch event {
case .project: project
case .git: git
case .config: config
}
}
}
/// FSEvents-backed watcher: one stream over the project root, sorted into the three events.
///
/// Project changes honour the project's `files.exclude`, and its `.gitignore` when `files.followGitignore`
/// is on; the watcher reads `.helder/config.json` itself and again whenever it changes.
public final class FSEventsWatcher: FileWatching {
private let debounce: WatchDebounce
private let latency: TimeInterval
private let runner: ProcessRunning
private let queue = DispatchQueue(label: "nl.blijnder.helder.watcher")
private var stream: FSEventStreamRef?
private var router: EventRouter?
/// `latency` is how long FSEvents itself gathers changes before it calls back.
public init(debounce: WatchDebounce = .standard, latency: TimeInterval = 0.05, runner: ProcessRunning = ProcessRunner()) {
self.debounce = debounce
self.latency = latency
self.runner = runner
}
deinit {
stop()
}
public func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void) {
stop()
let router = EventRouter(root: root, debounce: debounce, queue: queue, runner: runner, handler: handler)
var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(router).toOpaque(),
retain: nil, release: nil, copyDescription: nil)
let callback: FSEventStreamCallback = { _, info, count, paths, flags, _ in
guard let info else { return }
let router = Unmanaged<EventRouter>.fromOpaque(info).takeUnretainedValue()
let list = unsafeBitCast(paths, to: NSArray.self)
for i in 0..<count {
guard let path = list[i] as? String else { continue }
router.route(path: path, flags: flags[i])
}
}
let flags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents
| kFSEventStreamCreateFlagNoDefer)
guard let stream = FSEventStreamCreate(nil, callback, &context, router.watchedPaths as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, flags) else {
Log.error("watch", "cannot watch \(root.path)")
return
}
FSEventStreamSetDispatchQueue(stream, queue)
guard FSEventStreamStart(stream) else {
Log.error("watch", "cannot start watching \(root.path)")
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
return
}
self.stream = stream
self.router = router
}
public func stop() {
if let stream {
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
}
stream = nil
router?.cancel()
router = nil
}
}
/// Sorts raw FSEvents paths into watch events and debounces them; lives on the watcher's queue.
final class EventRouter: @unchecked Sendable {
private let root: String
private let rootURL: URL
private let gitDirectory: String
private let debounce: WatchDebounce
private let queue: DispatchQueue
private let runner: ProcessRunning
private let handler: @Sendable (WatchEvent) -> Void
private var pending: [WatchEvent: DispatchWorkItem] = [:]
private var cancelled = false
private var files: HelderConfig.Files
/// Project paths changed since the last `.project` fired; nil when the batch must fire unchecked.
private var changedPaths: Set<String>? = []
/// Git's verdict per path; cleared whenever git state or a `.gitignore` changes.
private var ignoredCache: [String: Bool] = [:]
/// Paths per `git check-ignore` call, well under the argument-length limit.
private static let checkIgnoreBatch = 200
init(root: URL, debounce: WatchDebounce, queue: DispatchQueue, runner: ProcessRunning,
handler: @escaping @Sendable (WatchEvent) -> Void) {
self.root = Self.realPath(root.path)
self.rootURL = root
self.gitDirectory = Self.realPath(GitDirectory.resolve(root: root).path)
self.debounce = debounce
self.queue = queue
self.runner = runner
self.handler = handler
self.files = Self.readFiles(root: root)
}
/// The root, plus the git directory when it lives outside the root (worktrees, submodules).
var watchedPaths: [String] {
Self.relative(gitDirectory, to: root) == nil ? [root, gitDirectory] : [root]
}
func route(path: String, flags: FSEventStreamEventFlags) {
guard let event = Self.classify(path: path, root: root, gitDirectory: gitDirectory, flags: flags, exclude: files.exclude) else {
return
}
switch event {
case .project:
let rel = Self.relative(path, to: root) ?? ""
let rescan = flags & FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) != 0
if rescan || rel.isEmpty || PathUtils.basename(rel) == ".gitignore" {
ignoredCache = [:]
changedPaths = nil
} else {
changedPaths?.insert(rel)
}
case .git:
ignoredCache = [:]
case .config:
files = Self.readFiles(root: rootURL)
ignoredCache = [:]
}
schedule(event)
}
func cancel() {
queue.async { [self] in
cancelled = true
pending.values.forEach { $0.cancel() }
pending = [:]
}
}
private func schedule(_ event: WatchEvent) {
guard !cancelled else { return }
pending[event]?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, !self.cancelled else { return }
self.pending[event] = nil
if event == .project {
self.fireProject()
} else {
self.handler(event)
}
}
pending[event] = item
queue.asyncAfter(deadline: .now() + debounce.interval(for: event), execute: item)
}
/// Fires `.project` unless every changed path is git-ignored and the project hides ignored files.
private func fireProject() {
let paths = changedPaths
changedPaths = []
guard files.followGitignore, let paths, !paths.isEmpty else { return handler(.project) }
if paths.contains(where: { ignoredCache[$0] == false }) { return handler(.project) }
let unknown = paths.filter { ignoredCache[$0] == nil }.sorted()
guard !unknown.isEmpty else { return }
let runner = self.runner, root = self.rootURL
Task {
let verdict = await Self.allIgnored(unknown, root: root, runner: runner)
self.queue.async { [self] in
guard !cancelled else { return }
if let verdict {
for path in unknown { ignoredCache[path] = verdict }
if verdict { return }
}
handler(.project)
}
}
}
/// True when git ignores every path, false when it ignores none, nil for a mix or when git cannot tell.
static func allIgnored(_ paths: [String], root: URL, runner: ProcessRunning) async -> Bool? {
var ignored = 0
var start = 0
while start < paths.count {
let batch = Array(paths[start..<min(start + checkIgnoreBatch, paths.count)])
start += batch.count
guard let result = try? await runner.run("git", ["check-ignore", "--"] + batch, in: root),
result.exitCode == 0 || result.exitCode == 1 else { return nil }
// One line per ignored path; git quotes odd names but never splits one over two lines.
ignored += result.stdout.split(separator: "\n").count
}
if ignored == paths.count { return true }
return ignored == 0 ? false : nil
}
private static func readFiles(root: URL) -> HelderConfig.Files {
let url = root.appendingPathComponent(HelderConfig.folderName).appendingPathComponent(HelderConfig.overridesFileName)
return HelderConfig.resolved(overrides: try? Data(contentsOf: url)).files
}
/// The event one changed path stands for, or nil when it is noise.
static func classify(path: String, root: String, gitDirectory: String, flags: FSEventStreamEventFlags,
exclude: [String] = []) -> WatchEvent? {
if flags & FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) != 0 { return .project }
if let rel = relative(path, to: gitDirectory) {
return isGitStateEntry(rel) ? .git : nil
}
guard let rel = relative(path, to: root), !rel.isEmpty else { return nil }
if rel == HelderConfig.folderName + "/" + HelderConfig.overridesFileName { return .config }
return IgnoreRules.isWatchIgnored(rel, exclude: exclude) ? nil : .project
}
/// True for the entries `GitDirectory.watchedEntries` names, including what lies under the ref folders.
static func isGitStateEntry(_ rel: String) -> Bool {
let entries = GitDirectory.watchedEntries(gitDirectory: URL(fileURLWithPath: "/")).map { String($0.path.dropFirst()) }
return entries.contains { rel == $0 || rel.hasPrefix($0 + "/") }
}
/// `path` relative to `base` ("" for `base` itself), or nil when it lies outside.
static func relative(_ path: String, to base: String) -> String? {
if path == base { return "" }
let prefix = base.hasSuffix("/") ? base : base + "/"
return path.hasPrefix(prefix) ? String(path.dropFirst(prefix.count)) : nil
}
/// FSEvents reports resolved paths (/private/var, not /var), so the watched folders are resolved too.
/// A path that does not exist yet keeps its resolved parent.
static func realPath(_ path: String) -> String {
if let resolved = realpath(path, nil) {
defer { free(resolved) }
return String(cString: resolved)
}
let parent = (path as NSString).deletingLastPathComponent
guard !parent.isEmpty, parent != path else { return path }
return (realPath(parent) as NSString).appendingPathComponent((path as NSString).lastPathComponent)
}
}
@@ -0,0 +1,20 @@
import Foundation
public enum GitDirectory {
/// The real git directory: `<root>/.git`, or the `gitdir:` target when `.git` is a file (worktrees, submodules).
public static func resolve(root: URL) -> URL {
let dot = root.appendingPathComponent(".git")
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: dot.path, isDirectory: &isDir), !isDir.boolValue,
let text = try? String(contentsOf: dot, encoding: .utf8) else { return dot }
let line = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard line.hasPrefix("gitdir:") else { return dot }
let target = line.dropFirst("gitdir:".count).trimmingCharacters(in: .whitespaces)
return URL(fileURLWithPath: target, relativeTo: root).standardizedFileURL
}
/// The entries whose change means "git state moved": branch switch, staging, commits, pushes, merges.
public static func watchedEntries(gitDirectory dir: URL) -> [URL] {
["HEAD", "index", "refs/heads", "refs/remotes", "logs/HEAD", "MERGE_HEAD"].map { dir.appendingPathComponent($0) }
}
}
+312
View File
@@ -0,0 +1,312 @@
import Foundation
import HelderCore
public actor GitService: GitServicing {
public nonisolated let root: URL
private let runner: ProcessRunning
private let statusAttempts: Int
private let statusRetryDelay: TimeInterval
private let pushTimeout: TimeInterval
private let maxDiffBytes: Int
/// Enough overlapping `git show`s to hide process start-up, well under macOS's open-file limit.
private static let maxConcurrentReads = 12
private var inFlight: (id: Int, task: Task<GitSnapshot?, Error>)?
private var trailing: Task<GitSnapshot?, Error>?
private var readCount = 0
/// Loads that joined the trailing read instead of starting their own.
private(set) var coalescedLoads = 0
/// `statusAttempts` and `statusRetryDelay` ride out an external tool holding `.git/index.lock`.
public init(root: URL, runner: ProcessRunning = ProcessRunner(), statusAttempts: Int = 6,
statusRetryDelay: TimeInterval = 0.12, pushTimeout: TimeInterval = 120,
maxDiffBytes: Int = FileLimits.maxDiffFileBytes) {
self.root = root
self.runner = runner
self.statusAttempts = statusAttempts
self.statusRetryDelay = statusRetryDelay
self.pushTimeout = pushTimeout
self.maxDiffBytes = maxDiffBytes
}
/// Reads status plus each changed file's text on both sides of its row.
///
/// Overlapping calls share one read in flight plus one trailing read, because a branch switch
/// fires several watcher pings. Binary files read as ""; a file over `maxDiffBytes` is flagged `isTooBig`.
public func load() async throws -> GitSnapshot? {
if let trailing {
coalescedLoads += 1
return try await trailing.value
}
if let running = inFlight?.task {
let next = Task { () async throws -> GitSnapshot? in
_ = try? await running.value
return try await self.startRead()
}
trailing = next
coalescedLoads += 1
return try await next.value
}
return try await startRead()
}
/// The text of `path` in HEAD or in the index; "" when that side has no such file or it is binary.
public func contents(of path: String, at revision: GitRevision) async -> String {
await Self.blob(revision.prefix + path, root: root, runner: runner, maxBytes: .max).text
}
/// True inside a work tree; falls back to a `.git` on disk so a branch switch mid-probe does not blank the column.
public func isRepository() async -> Bool {
if let result = try? await Self.run(["rev-parse", "--is-inside-work-tree"], root: root, runner: runner),
result.succeeded, result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "true" {
return true
}
return FileManager.default.fileExists(atPath: root.appendingPathComponent(".git").path)
}
public func stage(_ paths: [String]) async throws {
guard !paths.isEmpty else { return }
try await git(["add", "--"] + paths)
}
public func unstage(_ paths: [String]) async throws {
guard !paths.isEmpty else { return }
let reset = try await Self.run(["reset", "--"] + paths, root: root, runner: runner)
if !reset.succeeded {
// A repository without commits has no HEAD to reset to.
try await git(["rm", "--cached", "-r", "--"] + paths)
}
}
public func commit(message: String) async throws {
try await git(["commit", "-m", message])
}
/// Pushes; retries once with `-u origin <branch>` when the branch has no upstream.
/// Credential prompts are switched off and the whole push gives up after `pushTimeout`.
public func push() async -> PushResult {
let environment = Self.environment(adding: ["GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"])
let runner = self.runner, root = self.root
let attempt = Task { () async throws -> ProcessResult in
var result = try await runner.run("git", arguments: ["push"], in: root, environment: environment)
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) {
let head = try await runner.run("git", arguments: ["rev-parse", "--abbrev-ref", "HEAD"], in: root, environment: environment)
let branch = head.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
if !branch.isEmpty && branch != "HEAD" {
result = try await runner.run("git", arguments: ["push", "-u", "origin", branch], in: root, environment: environment)
}
}
return result
}
let timeout = Task {
try await Task.sleep(nanoseconds: UInt64(pushTimeout * 1_000_000_000))
attempt.cancel()
}
defer { timeout.cancel() }
do {
let result = try await attempt.value
return Porcelain.pushSummary(exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr)
} catch is CancellationError {
return PushResult(ok: false, message: "push timed out")
} catch {
return PushResult(ok: false, message: "\(error)")
}
}
/// A path HEAD has is checked out from HEAD (index and disk); any other path is unstaged
/// and its file deleted. A staged rename also gets its source back. Folders are never deleted.
public func discard(_ paths: [String]) async throws {
let renames = paths.isEmpty ? [:] : try await stagedRenameSources()
for path in paths {
if let source = renames[path] {
_ = try await Self.run(["reset", "-q", "HEAD", "--", source, path], root: root, runner: runner)
try await git(["checkout", "HEAD", "--", source])
}
let known = try await Self.run(["cat-file", "-e", "HEAD:" + path], root: root, runner: runner)
if known.succeeded {
try await git(["checkout", "HEAD", "--", path])
continue
}
_ = try await Self.run(["reset", "-q", "HEAD", "--", path], root: root, runner: runner)
guard let url = fileURL(path) else { continue }
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue {
try FileManager.default.removeItem(at: url)
}
}
}
/// Rename target → source for every rename in the index.
private func stagedRenameSources() async throws -> [String: String] {
let parsed = Porcelain.parseStatus(try await statusWithRetry())
var sources: [String: String] = [:]
for entry in parsed.entries where entry.isStagedRename {
sources[entry.path] = entry.originalPath
}
return sources
}
// MARK: - load
private func startRead() async throws -> GitSnapshot? {
trailing = nil
readCount += 1
let id = readCount
let task = Task { try await self.read() }
inFlight = (id, task)
defer { if inFlight?.id == id { inFlight = nil } }
return try await task.value
}
private func read() async throws -> GitSnapshot? {
guard await isRepository() else { return nil }
let raw = try await statusWithRetry()
let parsed = Porcelain.parseStatus(raw)
let root = self.root, runner = self.runner, maxBytes = self.maxDiffBytes
let perEntry = try await Self.mapLimited(parsed.entries, limit: Self.maxConcurrentReads) { entry in
await Self.changes(for: entry, root: root, runner: runner, maxBytes: maxBytes)
}
return GitSnapshot(branch: parsed.branch, ahead: parsed.ahead, canPush: parsed.canPush, changes: perEntry.flatMap { $0 })
}
/// An external checkout briefly holds `.git/index.lock`; a status landing then fails, so retry.
private func statusWithRetry() async throws -> String {
var attempt = 0
while true {
attempt += 1
let result = try await Self.run(Porcelain.statusArguments, root: root, runner: runner, adding: ["GIT_OPTIONAL_LOCKS": "0"])
if result.succeeded { return result.stdout }
if attempt >= statusAttempts {
throw GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: result.exitCode,
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
}
try await Task.sleep(nanoseconds: UInt64(statusRetryDelay * 1_000_000_000))
}
}
/// The rows of one porcelain entry, each with the text on both sides of its half.
///
/// The index blob is only read when the file has both rows: with one row the index equals
/// HEAD (unstaged only) or the disk (staged only), which saves a `git show` per file.
private static func changes(for entry: StatusEntry, root: URL, runner: ProcessRunning, maxBytes: Int) async -> [GitFileChange] {
let rows = Porcelain.classify(index: entry.index, working: entry.working)
let stagedRow = rows.first { $0.staged }
let workRow = rows.first { !$0.staged }
let both = stagedRow != nil && workRow != nil
let path = entry.path
let head = { await blob(GitRevision.head.prefix + path, root: root, runner: runner, maxBytes: maxBytes) }
let index = both ? await blob(GitRevision.index.prefix + path, root: root, runner: runner, maxBytes: maxBytes) : .text("")
var out: [GitFileChange] = []
if let row = stagedRow {
let original: Side = row.status == .added ? .text("") : await head()
let updated: Side = row.status == .deleted ? .text("") : both ? index : diskText(path, root: root, maxBytes: maxBytes)
out.append(change(path, row, staged: true, original, updated, originalPath: entry.originalPath))
}
if let row = workRow {
let original: Side = entry.index == "?" ? .text("") : both ? index : await head()
let updated: Side = row.status == .deleted ? .text("") : diskText(path, root: root, maxBytes: maxBytes)
out.append(change(path, row, staged: false, original, updated,
originalPath: stagedRow == nil ? entry.originalPath : nil))
}
return out
}
/// One side of a change: its text, or over the cap (and never read into memory as text).
private enum Side {
case text(String)
case tooBig
var text: String {
if case let .text(value) = self { return value }
return ""
}
}
private static func change(_ path: String, _ row: GitRowSpec, staged: Bool,
_ original: Side, _ updated: Side, originalPath: String?) -> GitFileChange {
let tooBig = if case .tooBig = original { true } else if case .tooBig = updated { true } else { false }
return GitFileChange(path: path, status: row.status, staged: staged,
original: tooBig ? "" : original.text, updated: tooBig ? "" : updated.text,
originalPath: originalPath, isTooBig: tooBig)
}
private static func blob(_ spec: String, root: URL, runner: ProcessRunning, maxBytes: Int) async -> Side {
guard let result = try? await run(["show", spec], root: root, runner: runner), result.succeeded else { return .text("") }
guard result.stdout.utf8.count <= maxBytes else { return .tooBig }
return .text(result.stdout.prefix(8000).contains("\0") ? "" : result.stdout)
}
/// The file's text, or "" when it is binary or missing; an oversized file is never read.
private static func diskText(_ path: String, root: URL, maxBytes: Int) -> Side {
let url = root.appendingPathComponent(path)
guard let size = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.intValue else {
return .text("")
}
guard size <= maxBytes else { return .tooBig }
guard let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return .text("") }
return .text(String(decoding: data, as: UTF8.self))
}
/// Maps with at most `limit` operations running at once, keeping the input order.
private static func mapLimited<T: Sendable, R: Sendable>(_ items: [T], limit: Int,
_ transform: @escaping @Sendable (T) async -> R) async throws -> [R] {
var results = [R?](repeating: nil, count: items.count)
try await withThrowingTaskGroup(of: (Int, R).self) { group in
var next = 0
func launch() {
let index = next
let item = items[index]
group.addTask { (index, await transform(item)) }
next += 1
}
while next < min(limit, items.count) { launch() }
while let (index, value) = try await group.next() {
results[index] = value
if next < items.count { launch() }
}
}
return results.map { $0! }
}
/// Paths reach git as literal pathspecs: `pages/[id].vue` must never also match `pages/i.vue`.
private static func environment(adding extra: [String: String] = [:]) -> [String: String] {
var environment = ProcessInfo.processInfo.environment.merging(extra) { _, new in new }
environment["GIT_LITERAL_PATHSPECS"] = "1"
return environment
}
private static func run(_ arguments: [String], root: URL, runner: ProcessRunning,
adding extra: [String: String] = [:]) async throws -> ProcessResult {
try await runner.run("git", arguments: arguments, in: root, environment: environment(adding: extra))
}
/// The file for a repository path, or nil for the root itself or a path that escapes it.
private func fileURL(_ path: String) -> URL? {
let base = root.standardizedFileURL.path
let url = root.appendingPathComponent(path).standardizedFileURL
return url.path.hasPrefix(base + "/") ? url : nil
}
@discardableResult
private func git(_ arguments: [String]) async throws -> String {
let result = try await Self.run(arguments, root: root, runner: runner)
guard result.succeeded else {
throw GitError.commandFailed(arguments: arguments, exitCode: result.exitCode,
stderr: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))
}
return result.stdout
}
}
/// Which stored copy of a file `GitService.contents(of:at:)` reads.
public enum GitRevision: Sendable {
case head
case index
var prefix: String {
switch self {
case .head: "HEAD:"
case .index: ":0:"
}
}
}
@@ -0,0 +1,20 @@
import Foundation
import HelderCore
public enum GitError: Error, Equatable {
/// A git command exited non-zero; `stderr` is trimmed.
case commandFailed(arguments: [String], exitCode: Int32, stderr: String)
}
public protocol GitServicing: Sendable {
/// The working state, or nil when the project is not a git repository.
func load() async throws -> GitSnapshot?
/// Stages modifications, additions and deletions of the paths.
func stage(_ paths: [String]) async throws
func unstage(_ paths: [String]) async throws
func commit(message: String) async throws
/// Never throws: a failed push is a toast, not an error.
func push() async -> PushResult
/// Reverts each path to HEAD; a file HEAD does not have is unstaged and deleted, and a staged rename gets its source back.
func discard(_ paths: [String]) async throws
}
@@ -0,0 +1,79 @@
import Foundation
/// Plain-text log at `~/Library/Logs/Helder/helder.log`, written synchronously so a line
/// survives a crash moments later. Rotates at 2 MB and keeps 3 old files.
public final class FileLogger: LogSink, @unchecked Sendable {
public static let maxBytes = 2 * 1024 * 1024
public static let keep = 3
public let fileURL: URL
public let minimumLevel: LogLevel
private let directory: URL
private let lock = NSLock()
/// Tracked here so the common path needs no stat per line; nil until the first write.
private var size: Int?
public init(directory: URL, minimumLevel: LogLevel = .debug) {
self.directory = directory
self.fileURL = directory.appendingPathComponent("helder.log")
self.minimumLevel = minimumLevel
}
public static var defaultDirectory: URL {
FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0].appendingPathComponent("Logs/Helder")
}
/// One line per call: ISO timestamp, level, scope, message.
///
/// Never throws and never waits on another lock: it is called from failure paths everywhere.
public func write(level: LogLevel, scope: String, message: String) {
guard level >= minimumLevel else { return }
let line = Data(Self.formatLine(level: level, scope: scope, message: message,
pid: ProcessInfo.processInfo.processIdentifier, date: Date()).utf8)
lock.lock()
defer { lock.unlock() }
if size == nil {
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
size = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? Int) ?? 0
}
if (size ?? 0) + line.count > Self.maxBytes { rotate() }
// O_APPEND keeps lines from sibling Helder processes sharing this file whole.
let fd = open(fileURL.path, O_WRONLY | O_APPEND | O_CREAT, 0o644)
guard fd >= 0 else { return }
defer { close(fd) }
let written = line.withUnsafeBytes { Darwin.write(fd, $0.baseAddress, $0.count) }
if written > 0 { size = (size ?? 0) + written }
}
/// `helder.log` becomes `helder.1.log`, and so on; the oldest beyond `keep` is dropped.
/// Another process may rotate first, so every step is best effort.
private func rotate() {
let fm = FileManager.default
func old(_ n: Int) -> String { directory.appendingPathComponent("helder.\(n).log").path }
try? fm.removeItem(atPath: old(Self.keep))
for n in stride(from: Self.keep - 1, through: 1, by: -1) {
Darwin.rename(old(n), old(n + 1))
}
Darwin.rename(fileURL.path, old(1))
size = 0
}
/// `2026-07-15T10:00:00.000Z INFO 42 git loaded`; continuation lines are indented
/// so a message with newlines never looks like a second entry.
public static func formatLine(level: LogLevel, scope: String, message: String, pid: Int32, date: Date) -> String {
let stamp = timestampFormatter.string(from: date)
let indented = message.replacingOccurrences(of: "\r?\n", with: "\n ", options: .regularExpression)
return "\(stamp) \(pad(level.rawValue.uppercased(), 5)) \(pad(String(pid), 5, left: true)) \(pad(scope, 9)) \(indented)\n"
}
private static func pad(_ text: String, _ width: Int, left: Bool = false) -> String {
let fill = String(repeating: " ", count: max(0, width - text.count))
return left ? fill + text : text + fill
}
private static let timestampFormatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()
}
+41
View File
@@ -0,0 +1,41 @@
import Foundation
import os
public enum LogLevel: String, Sendable, Comparable {
case debug, info, warn, error
private var rank: Int { [.debug: 0, .info: 1, .warn: 2, .error: 3][self] ?? 0 }
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { lhs.rank < rhs.rank }
}
/// A destination besides the unified log, such as `FileLogger`.
public protocol LogSink: Sendable {
func write(level: LogLevel, scope: String, message: String)
}
public enum Log {
private static let logger = Logger(subsystem: "nl.blijnder.helder", category: "app")
private static let sinkBox = OSAllocatedUnfairLock<LogSink?>(initialState: nil)
/// Installs the extra sink; nil removes it.
public static func setSink(_ sink: LogSink?) {
sinkBox.withLock { $0 = sink }
}
public static func debug(_ scope: String, _ message: String) { write(.debug, scope, message) }
public static func info(_ scope: String, _ message: String) { write(.info, scope, message) }
public static func warn(_ scope: String, _ message: String) { write(.warn, scope, message) }
public static func error(_ scope: String, _ message: String) { write(.error, scope, message) }
private static func write(_ level: LogLevel, _ scope: String, _ message: String) {
let line = "[\(scope)] \(message)"
switch level {
case .debug: logger.debug("\(line, privacy: .public)")
// Notice, not info: the unified log only persists notice and above.
case .info: logger.notice("\(line, privacy: .public)")
case .warn: logger.warning("\(line, privacy: .public)")
case .error: logger.error("\(line, privacy: .public)")
}
sinkBox.withLock { $0 }?.write(level: level, scope: scope, message: message)
}
}
@@ -0,0 +1,27 @@
import Darwin
import Foundation
/// Collects the exit status of a child we signalled, so it does not linger as a zombie.
public enum ChildReaper {
/// Waits for `pid` without blocking a thread, sends SIGKILL once `grace` has passed, and returns once it is reaped.
///
/// Stops at once when `pid` is not an unreaped child of ours (someone else reaped it), so a
/// recycled pid is never signalled.
public static func reap(_ pid: pid_t, grace: TimeInterval = 2) async {
guard pid > 0 else { return }
let deadline = Date().addingTimeInterval(grace)
var killed = false
while true {
var status: Int32 = 0
let result = waitpid(pid, &status, WNOHANG)
if result == pid { return }
if result == -1 && errno != EINTR { return }
if result == 0 && !killed && Date() >= deadline {
kill(pid, SIGKILL)
killed = true
}
if Task.isCancelled { return }
try? await Task.sleep(nanoseconds: 20_000_000)
}
}
}
@@ -0,0 +1,38 @@
import Foundation
/// Finds command-line tools for a GUI app, whose PATH is only /usr/bin:/bin:/usr/sbin:/sbin.
public struct ExecutableLocator: Sendable {
/// Directories searched in order.
public var directories: [String]
public init(directories: [String]) {
self.directories = directories
}
/// The app's own Helpers folder (where bundle.sh puts ripgrep), then PATH, then Homebrew.
public static var standard: ExecutableLocator {
var dirs: [String] = []
dirs.append(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers").path)
let path = ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin"
dirs += path.split(separator: ":").map(String.init)
dirs += ["/opt/homebrew/bin", "/usr/local/bin"]
var seen = Set<String>()
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
}
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
public func locate(_ name: String) -> URL? {
let fm = FileManager.default
if name.contains("/") {
return fm.isExecutableFile(atPath: name) ? URL(fileURLWithPath: name) : nil
}
for dir in directories {
let candidate = (dir as NSString).appendingPathComponent(name)
var isDir: ObjCBool = false
if fm.fileExists(atPath: candidate, isDirectory: &isDir), !isDir.boolValue, fm.isExecutableFile(atPath: candidate) {
return URL(fileURLWithPath: candidate)
}
}
return nil
}
}
@@ -0,0 +1,46 @@
import Foundation
/// Starts another Helder process, for a launch outside an app bundle (`swift run`).
public enum InstanceLauncher {
/// Passed as `-HelderProject <folder>`: AppKit reads a `-Key value` pair as a default, not as a file to open.
public static func arguments(for root: URL?) -> [String] {
root.map { ["-HelderProject", $0.path] } ?? []
}
/// Runs `executable` on `root` (nil shows the launcher) and reaps it when it exits.
/// `HELDER_PROJECT` is dropped from the child's environment, since it wins over the argument.
public static func spawn(_ executable: URL, root: URL?,
environment: [String: String] = ProcessInfo.processInfo.environment) throws {
var environment = environment
environment["HELDER_PROJECT"] = nil
let process = Process()
process.executableURL = executable
process.arguments = arguments(for: root)
process.environment = environment
let id = ObjectIdentifier(process)
process.terminationHandler = { _ in children.remove(id) }
children.insert(process)
do {
try process.run()
} catch {
children.remove(id)
throw error
}
}
private static let children = Children()
/// Keeps each child's `Process` alive until it exits, so its exit status is always collected.
private final class Children: @unchecked Sendable {
private let lock = NSLock()
private var running: [ObjectIdentifier: Process] = [:]
func insert(_ process: Process) {
lock.withLock { running[ObjectIdentifier(process)] = process }
}
func remove(_ id: ObjectIdentifier) {
_ = lock.withLock { running.removeValue(forKey: id) }
}
}
}
@@ -0,0 +1,132 @@
import Foundation
public struct ProcessResult: Sendable, Equatable {
public var exitCode: Int32
public var stdout: String
public var stderr: String
public init(exitCode: Int32, stdout: String, stderr: String) {
self.exitCode = exitCode
self.stdout = stdout
self.stderr = stderr
}
public var succeeded: Bool { exitCode == 0 }
}
public enum ProcessRunnerError: Error, Equatable {
case executableNotFound(String)
case launchFailed(String)
}
/// Runs a command to completion. Services depend on this protocol so tests can script the output.
public protocol ProcessRunning: Sendable {
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
}
extension ProcessRunning {
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
try await run(executable, arguments: arguments, in: directory, environment: nil)
}
}
public struct ProcessRunner: ProcessRunning {
public let locator: ExecutableLocator
public init(locator: ExecutableLocator = .standard) {
self.locator = locator
}
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
job.start(continuation)
}
} onCancel: {
job.cancel()
}
}
}
/// One child process. Both pipes are drained on their own threads, because a child that
/// fills one pipe while we wait on the other would deadlock.
private final class Job: @unchecked Sendable {
private let process = Process()
private let lock = NSLock()
private var cancelled = false
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
process.executableURL = url
process.arguments = arguments
if let directory { process.currentDirectoryURL = directory }
if let environment { process.environment = environment }
process.standardInput = FileHandle.nullDevice
}
func start(_ continuation: CheckedContinuation<ProcessResult, Error>) {
let out = Pipe()
let err = Pipe()
process.standardOutput = out
process.standardError = err
let group = DispatchGroup()
var outData = Data()
var errData = Data()
group.enter()
process.terminationHandler = { _ in group.leave() }
lock.lock()
let alreadyCancelled = cancelled
do {
if !alreadyCancelled { try process.run() }
} catch {
lock.unlock()
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
return
}
lock.unlock()
if alreadyCancelled {
continuation.resume(throwing: CancellationError())
return
}
group.enter()
DispatchQueue.global().async {
outData = out.fileHandleForReading.readDataToEndOfFile()
group.leave()
}
group.enter()
DispatchQueue.global().async {
errData = err.fileHandleForReading.readDataToEndOfFile()
group.leave()
}
group.notify(queue: .global()) { [self, process] in
if wasCancelled {
continuation.resume(throwing: CancellationError())
return
}
continuation.resume(returning: ProcessResult(
exitCode: process.terminationStatus,
stdout: String(decoding: outData, as: UTF8.self),
stderr: String(decoding: errData, as: UTF8.self)
))
}
}
private var wasCancelled: Bool {
lock.lock()
defer { lock.unlock() }
return cancelled
}
func cancel() {
lock.lock()
defer { lock.unlock() }
cancelled = true
if process.isRunning { process.terminate() }
}
}
@@ -0,0 +1,44 @@
import Foundation
import HelderCore
public protocol ConfigServicing: Sendable {
/// Rewrites `config.default.json`, re-reads `config.json`, and returns the effective config.
@discardableResult
func resolve() async -> HelderConfig
/// The last resolved config; the defaults before the first `resolve()`.
func current() async -> HelderConfig
}
public actor ConfigService: ConfigServicing {
public nonisolated let root: URL
private var config = HelderConfig.defaults
public init(root: URL) {
self.root = root
}
public nonisolated var folder: URL { root.appendingPathComponent(HelderConfig.folderName) }
public nonisolated var overridesURL: URL { folder.appendingPathComponent(HelderConfig.overridesFileName) }
/// A read-only or missing project folder yields the defaults instead of an error.
@discardableResult
public func resolve() async -> HelderConfig {
let fm = FileManager.default
do {
try fm.createDirectory(at: folder, withIntermediateDirectories: true)
try HelderConfig.defaultsJSON().write(to: folder.appendingPathComponent(HelderConfig.defaultsFileName))
let gitignore = folder.appendingPathComponent(".gitignore")
if (try? String(contentsOf: gitignore, encoding: .utf8)) != HelderConfig.gitignoreBody {
try Data(HelderConfig.gitignoreBody.utf8).write(to: gitignore)
}
} catch {
Log.warn("config", "cannot write \(folder.path): \(error.localizedDescription)")
}
config = HelderConfig.resolved(overrides: try? Data(contentsOf: overridesURL))
return config
}
public func current() async -> HelderConfig {
config
}
}
@@ -0,0 +1,28 @@
import Foundation
public protocol NotesServicing: Sendable {
/// The note's text; "" when the project has none yet.
func read() async -> String
func write(_ text: String) async throws
}
/// The note is a plain `.notes.txt` in the project root, not JSON and not in `.helder/`,
/// so it stays readable and editable outside Helder.
public struct NotesService: NotesServicing {
public static let fileName = ".notes.txt"
public let root: URL
public init(root: URL) {
self.root = root
}
private var url: URL { root.appendingPathComponent(Self.fileName) }
public func read() async -> String {
(try? String(contentsOf: url, encoding: .utf8)) ?? ""
}
public func write(_ text: String) async throws {
try Data(text.utf8).write(to: url, options: .atomic)
}
}
@@ -0,0 +1,31 @@
import Foundation
import HelderCore
public enum ProjectLocator {
/// The folder a fresh window opens: `$HELDER_PROJECT`, else the first directory argument; nil shows the launcher.
/// A bare "." is ignored, so a development launch lands on the launcher too.
public static func initialRoot(environment: [String: String] = ProcessInfo.processInfo.environment,
arguments: [String] = CommandLine.arguments) -> URL? {
if let env = environment["HELDER_PROJECT"], isDirectory(env) {
return URL(fileURLWithPath: env).standardizedFileURL
}
let candidate = arguments.dropFirst().first { $0 != "." && !$0.hasPrefix("-") && isDirectory($0) }
return candidate.map { URL(fileURLWithPath: $0).standardizedFileURL }
}
/// The folder name, used for recents and the Explorer header.
public static func name(of root: URL) -> String {
root.lastPathComponent.isEmpty ? root.path : root.lastPathComponent
}
/// The window title: `APP_NAME` from the project's `.env`, else the folder name.
public static func title(of root: URL) -> String {
let env = try? String(contentsOf: root.appendingPathComponent(".env"), encoding: .utf8)
return ProjectTitle.title(folderName: name(of: root), envContents: env)
}
private static func isDirectory(_ path: String) -> Bool {
var isDir: ObjCBool = false
return FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue
}
}
@@ -0,0 +1,76 @@
import Foundation
import HelderCore
public protocol RecentProjectsStoring: Sendable {
/// Newest first; projects whose folder no longer exists are left out.
func list() async -> [RecentProject]
/// Moves a project folder to the front of the list.
func add(_ path: String) async
}
/// Machine-wide list in `~/Library/Application Support/Helder/recent-projects.json`.
public struct RecentProjectsStore: RecentProjectsStoring {
public let fileURL: URL
public init(fileURL: URL = RecentProjectsStore.defaultURL) {
self.fileURL = fileURL
}
public static var defaultURL: URL {
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")
return support.appendingPathComponent("Helder/recent-projects.json")
}
public func list() async -> [RecentProject] {
guard let data = try? Data(contentsOf: fileURL),
let list = try? JSONDecoder().decode([RecentProject].self, from: data) else { return [] }
return Array(list.filter { FileManager.default.fileExists(atPath: $0.path) }.prefix(RecentLists.maxProjects))
}
public func add(_ path: String) async {
let abs = URL(fileURLWithPath: path).standardizedFileURL.path
let entry = RecentProject(path: abs, name: PathUtils.basename(abs).isEmpty ? abs : PathUtils.basename(abs))
let next = RecentLists.pushing(entry, onto: await list())
do {
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
try encoder.encode(next).write(to: fileURL, options: .atomic)
} catch {
Log.warn("recent", "cannot save recent projects: \(error.localizedDescription)")
}
}
}
public protocol RecentFilesStoring: Sendable {
/// Recently opened files of this project, newest first.
func load() async -> [String]
func save(_ paths: [String]) async
}
/// Per-project list in `.helder/recent.json`; drives the ⌘↑/⌘↓ recent-files navigator.
public struct RecentFilesStore: RecentFilesStoring {
public let fileURL: URL
public init(root: URL) {
fileURL = root.appendingPathComponent(HelderConfig.folderName).appendingPathComponent(RecentLists.recentFilesName)
}
public func load() async -> [String] {
guard let data = try? Data(contentsOf: fileURL),
let list = try? JSONDecoder().decode([String].self, from: data) else { return [] }
return Array(list.prefix(RecentLists.maxFiles))
}
public func save(_ paths: [String]) async {
do {
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
try encoder.encode(Array(paths.prefix(RecentLists.maxFiles))).write(to: fileURL, options: .atomic)
} catch {
Log.warn("recent", "cannot save recent files: \(error.localizedDescription)")
}
}
}
@@ -0,0 +1,35 @@
import Foundation
import HelderCore
public protocol SessionStoring: Sendable {
func loadSession(root: String) -> SessionState?
func saveSession(_ session: SessionState, root: String)
func loadLayout() -> LayoutState
func saveLayout(_ layout: LayoutState)
}
/// Never throws: storage that cannot be read gives the defaults, one that cannot be written is skipped.
public struct SessionStore: SessionStoring, @unchecked Sendable {
private let defaults: UserDefaults
public init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
public func loadSession(root: String) -> SessionState? {
defaults.data(forKey: SessionState.key(root: root)).flatMap { try? JSONDecoder().decode(SessionState.self, from: $0) }
}
public func saveSession(_ session: SessionState, root: String) {
if let data = try? JSONEncoder().encode(session) { defaults.set(data, forKey: SessionState.key(root: root)) }
}
public func loadLayout() -> LayoutState {
guard defaults.object(forKey: LayoutState.key) != nil else { return LayoutState() }
return LayoutState(agentFraction: defaults.double(forKey: LayoutState.key))
}
public func saveLayout(_ layout: LayoutState) {
defaults.set(layout.agentFraction, forKey: LayoutState.key)
}
}
@@ -0,0 +1,235 @@
import Foundation
import HelderCore
/// Which files a scan may enter: ripgrep's `!glob` names plus the project's file settings.
struct ScanFilter: Sendable, Equatable {
var base: [String]
var files: HelderConfig.Files
}
/// One line search, answered the same way by ripgrep and by the walk.
struct LineQuery: Sendable, Equatable {
enum Pattern: Sendable, Equatable {
/// Fixed string; case-insensitive unless it holds an uppercase letter.
case smartCaseLiteral(String)
/// Case-sensitive regular expression in the subset ripgrep and ICU share.
case regex(String)
/// Case-sensitive literal that must stand as a whole word.
case word(String)
}
var pattern: Pattern
/// Only files with this extension, e.g. "php".
var fileExtension: String? = nil
var maxPerFile: Int? = nil
var maxColumns: Int? = nil
/// Lets the walk stop early; ripgrep has no such flag, so callers still cap themselves.
var maxFiles: Int? = nil
}
/// Lists and searches project files; the relative paths use "/".
protocol ProjectScanning: Sendable {
/// Relative paths of the files under `scope` (nil is the root), sorted.
func files(under scope: String?, filter: ScanFilter) async -> [String]
/// Matching lines with absolute paths, grouped per file and in line order within a file.
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch]
}
enum ProjectScanner {
/// `$RG_BINARY` when it names an executable, else `rg` through the locator.
static func ripgrep(locator: ExecutableLocator, environment: [String: String]) -> URL? {
if let override = environment["RG_BINARY"], !override.isEmpty,
FileManager.default.isExecutableFile(atPath: override) {
return URL(fileURLWithPath: override)
}
return locator.locate("rg")
}
static func make(root: URL, runner: ProcessRunning, locator: ExecutableLocator,
environment: [String: String]) -> ProjectScanning {
if let binary = ripgrep(locator: locator, environment: environment) {
return RipgrepScanner(root: root, binary: binary, runner: runner)
}
return WalkScanner(root: root, runner: runner)
}
}
// MARK: - ripgrep
struct RipgrepScanner: ProjectScanning {
let root: URL
let binary: URL
let runner: ProcessRunning
func files(under scope: String?, filter: ScanFilter) async -> [String] {
let target = scope.flatMap { $0.isEmpty ? nil : root.appendingPathComponent($0).path } ?? root.path
let args = Self.fileArguments(filter: filter, target: target)
guard let result = await run(args) else { return [] }
return result.stdout.split(separator: "\n")
.map { RipgrepJSON.relativePath(String($0), root: root.path) }
.sorted()
}
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
guard let result = await run(Self.searchArguments(query, filter: filter, target: root.path)) else { return [] }
return result.stdout.split(separator: "\n").compactMap { RipgrepJSON.parseLine(String($0)) }
}
static func fileArguments(filter: ScanFilter, target: String) -> [String] {
["--files", "--hidden"] + IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base) + ["--", target]
}
static func searchArguments(_ query: LineQuery, filter: ScanFilter, target: String) -> [String] {
var args = ["--json"]
let needle: String
switch query.pattern {
case .smartCaseLiteral(let text):
args += ["--fixed-strings", "--smart-case"]
needle = text
case .regex(let pattern):
needle = pattern
case .word(let text):
args += ["--fixed-strings", "--word-regexp"]
needle = text
}
args.append("--hidden")
if let max = query.maxPerFile { args += ["--max-count", String(max)] }
if let columns = query.maxColumns { args += ["--max-columns", String(columns)] }
if let ext = query.fileExtension { args += ["--glob", "*." + ext] }
args += IgnoreRules.ripgrepArguments(files: filter.files, base: filter.base)
return args + ["-e", needle, "--", target]
}
/// Exit 1 means "nothing found" and 2 means "some files were unreadable"; both keep their output.
private func run(_ arguments: [String]) async -> ProcessResult? {
do {
return try await runner.run(binary.path, arguments: arguments, in: root, environment: nil)
} catch {
Log.error("search", "ripgrep failed: \(error)")
return nil
}
}
}
// MARK: - walk
/// The ripgrep fallback: walks the tree in name order, never follows symlinks, and skips
/// binary files and files over `maxFileBytes` when searching.
struct WalkScanner: ProjectScanning {
let root: URL
let runner: ProcessRunning
var maxFileBytes = FileLimits.maxIndexedFileBytes
func files(under scope: String?, filter: ScanFilter) async -> [String] {
var out: [String] = []
await walk(from: scope ?? "", filter: filter) { rel, _ in
out.append(rel)
return true
}
return out.sorted()
}
func matches(_ query: LineQuery, filter: ScanFilter) async -> [RipgrepMatch] {
guard let matcher = LineMatcher(query.pattern) else { return [] }
var out: [RipgrepMatch] = []
var filesWithHits = 0
await walk(from: "", filter: filter) { rel, url in
if let ext = query.fileExtension, (rel as NSString).pathExtension != ext { return true }
guard let text = readText(url) else { return true }
var hits = 0
var lineNumber = 0
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
lineNumber += 1
guard let offset = matcher.firstByteOffset(in: line) else { continue }
out.append(RipgrepMatch(path: root.path + "/" + rel, line: lineNumber, text: String(line), byteOffset: offset))
hits += 1
if let max = query.maxPerFile, hits >= max { break }
}
if hits > 0 { filesWithHits += 1 }
if let max = query.maxFiles, filesWithHits >= max { return false }
return true
}
return out
}
private func readText(_ url: URL) -> String? {
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size <= maxFileBytes,
let data = try? Data(contentsOf: url), !FileLimits.looksBinary(data) else { return nil }
return String(decoding: data, as: UTF8.self)
}
/// Calls `visit` for every file in scope until it returns false.
private func walk(from scope: String, filter: ScanFilter, visit: (String, URL) -> Bool) async {
let base = Set(filter.base)
let excludes = filter.files.exclude.filter { !$0.isEmpty }
let gitIgnored = filter.files.followGitignore ? await ignoredByGit() : []
func skipped(_ rel: String, name: String, isDirectory: Bool) -> Bool {
if base.contains(name) { return true }
if excludes.contains(where: { IgnoreRules.globMatches($0, path: rel) }) { return true }
return gitIgnored.contains(isDirectory ? rel + "/" : rel)
}
var stack: [String] = [scope]
while let dir = stack.popLast() {
let url = dir.isEmpty ? root : root.appendingPathComponent(dir)
var subdirectories: [String] = []
for entry in DirectoryListing.entries(of: url) {
let rel = PathUtils.join(dir, entry.name)
if skipped(rel, name: entry.name, isDirectory: entry.kind == .directory) { continue }
switch entry.kind {
case .directory: subdirectories.append(rel)
case .file: if !visit(rel, entry.url) { return }
}
}
stack += subdirectories.reversed()
}
}
/// Untracked paths git ignores, folders with a trailing slash; empty outside a repository.
private func ignoredByGit() async -> Set<String> {
let args = ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]
guard let result = try? await runner.run("git", args, in: root), result.succeeded else { return [] }
return Set(result.stdout.split(separator: "\0").map(String.init))
}
}
/// Finds the first match in one line and reports its UTF-8 offset, the unit ripgrep uses.
private struct LineMatcher {
private enum Kind {
case literal(String, String.CompareOptions)
case regex(NSRegularExpression)
}
private let kind: Kind
init?(_ pattern: LineQuery.Pattern) {
switch pattern {
case .smartCaseLiteral(let text):
guard !text.isEmpty else { return nil }
let caseSensitive = text.contains { $0.isUppercase }
kind = .literal(text, caseSensitive ? [.literal] : [.literal, .caseInsensitive])
case .regex(let pattern):
guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil }
kind = .regex(regex)
case .word(let text):
let escaped = NSRegularExpression.escapedPattern(for: text)
guard let regex = try? NSRegularExpression(pattern: "(?<!\\w)" + escaped + "(?!\\w)") else { return nil }
kind = .regex(regex)
}
}
func firstByteOffset(in line: Substring) -> Int? {
let text = String(line)
switch kind {
case .literal(let needle, let options):
guard let range = text.range(of: needle, options: options) else { return nil }
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
case .regex(let regex):
let whole = NSRange(text.startIndex..., in: text)
guard let match = regex.firstMatch(in: text, range: whole),
let range = Range(match.range, in: text) else { return nil }
return text.utf8.distance(from: text.startIndex, to: range.lowerBound)
}
}
}
@@ -0,0 +1,65 @@
import Foundation
import HelderCore
public protocol SearchServicing: Sendable {
/// False when no ripgrep binary was found; callers then fall back to a walk.
func isAvailable() async -> Bool
/// Fixed-string, smart-case content search; [] below `SearchLimits.minContentQuery` characters.
func searchContent(_ query: String) async -> [ContentGroup]
/// Relative paths of every project file, dotfiles included, honouring gitignore and excludes.
/// `directory` limits the list to one subtree; paths stay relative to the root.
func listFiles(under directory: String?) async -> [String]
}
/// Answers through ripgrep when it can be found, else through a walk with the same filters.
public struct RipgrepSearchService: SearchServicing {
public let root: URL
private let config: ConfigServicing
private let runner: ProcessRunning
private let locator: ExecutableLocator
private let environment: [String: String]
/// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path.
public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .standard,
environment: [String: String] = ProcessInfo.processInfo.environment) {
self.root = root
self.config = config
self.runner = runner
self.locator = locator
self.environment = environment
}
public func isAvailable() async -> Bool {
ProjectScanner.ripgrep(locator: locator, environment: environment) != nil
}
public func searchContent(_ query: String) async -> [ContentGroup] {
guard query.trimmingCharacters(in: .whitespacesAndNewlines).count >= SearchLimits.minContentQuery else { return [] }
let search = LineQuery(pattern: .smartCaseLiteral(query), maxPerFile: SearchLimits.maxHitsPerFile,
maxColumns: 2000, maxFiles: SearchLimits.maxFiles)
var grouper = ContentGrouper(root: root.path)
for match in await scanner.matches(search, filter: await filter()) {
grouper.add(match)
}
return grouper.groups
}
public func listFiles(under directory: String?) async -> [String] {
if let directory, !directory.isEmpty, !isInsideRoot(directory) { return [] }
return await scanner.files(under: directory, filter: await filter())
}
private var scanner: ProjectScanning {
ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment)
}
private func filter() async -> ScanFilter {
ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: await config.current().files)
}
private func isInsideRoot(_ path: String) -> Bool {
let base = root.standardizedFileURL.path
let target = root.appendingPathComponent(path).standardizedFileURL.path
return target.hasPrefix(base + "/")
}
}
@@ -0,0 +1,144 @@
import Foundation
import HelderCore
public protocol SymbolServicing: Sendable {
/// Every declared PHP class-like name; decides which tokens ⌘-click may underline.
func names() async -> Set<String>
/// Declarations of `name` plus every reference, grouped by file.
func lookup(_ name: String) async -> SymbolLookup
/// Drops the index after a file change; the next caller rebuilds it.
func invalidate() async
}
/// Ripgrep-backed, with the same walk fallback as search when ripgrep is missing.
public actor SymbolService: SymbolServicing {
public nonisolated let root: URL
private let runner: ProcessRunning
private let config: ConfigServicing
private let locator: ExecutableLocator
private let environment: [String: String]
private var index: [String: [SymbolDef]]?
private var building: Task<[String: [SymbolDef]], Never>?
/// Bumped by `invalidate()`, so a build that started before a file change is not cached.
private var generation = 0
/// `environment` is read for `RG_BINARY`, which points at a ripgrep outside the search path.
public init(root: URL, config: ConfigServicing, runner: ProcessRunning = ProcessRunner(),
locator: ExecutableLocator = .standard, environment: [String: String] = ProcessInfo.processInfo.environment) {
self.root = root
self.config = config
self.runner = runner
self.locator = locator
self.environment = environment
}
/// Builds lazily on first use; concurrent callers share one build. Two ripgrep passes over
/// `*.php` (vendor included): `PHPSymbols.declarationPattern`, then `traitUsePattern`, where
/// a trait belongs to the nearest declaration above it in the same file.
public func names() async -> Set<String> {
Set(await currentIndex().keys)
}
/// Word-regexp ripgrep over `*.php` without vendor; drops import lines and the declaration
/// lines themselves; caps at `SymbolLimits.maxReferenceFiles` files. Non-identifiers return empty.
public func lookup(_ name: String) async -> SymbolLookup {
guard PHPSymbols.isIdentifier(name) else { return .empty(name) }
let definitions = PHPSymbols.sortDefinitions(await currentIndex()[name] ?? [])
let declared = Set(definitions.map { "\($0.path):\($0.line)" })
let query = LineQuery(pattern: .word(name), fileExtension: "php")
let matches = await scanner.matches(query, filter: await filter(base: IgnoreRules.symbolReferenceIgnore))
var groups: [RefGroup] = []
var groupIndex: [String: Int] = [:]
var count = 0
for match in matches {
let path = RipgrepJSON.relativePath(match.path, root: root.path)
if declared.contains("\(path):\(match.line)") || PHPSymbols.isImportLine(match.text) { continue }
let hit = Self.hit(match)
if let i = groupIndex[path] {
groups[i].hits.append(hit)
} else {
guard groups.count < SymbolLimits.maxReferenceFiles else { continue }
groupIndex[path] = groups.count
groups.append(RefGroup(path: path, hits: [hit]))
}
count += 1
}
return SymbolLookup(name: name, definitions: definitions, references: groups, referenceCount: count)
}
public func invalidate() async {
index = nil
building = nil
generation += 1
}
private func currentIndex() async -> [String: [SymbolDef]] {
if let index { return index }
if let building { return await building.value }
let started = generation
let task = Task { await self.build() }
building = task
let built = await task.value
if generation == started {
index = built
building = nil
}
return built
}
private func build() async -> [String: [SymbolDef]] {
let started = Date()
let filter = await filter(base: IgnoreRules.symbolDeclarationIgnore)
let scanner = self.scanner
var defs: [SymbolDef] = []
var defsByFile: [String: [Int]] = [:]
var namespaces: [String: String] = [:]
// A file's matches arrive together and in line order, and `namespace` precedes the
// declarations it covers, so the last namespace seen is the right one.
let declarations = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php"), filter: filter)
for match in declarations {
let path = RipgrepJSON.relativePath(match.path, root: root.path)
if let namespace = PHPSymbols.parseNamespace(match.text) {
namespaces[path] = namespace
continue
}
guard let parsed = PHPSymbols.parseDeclaration(match.text) else { continue }
defsByFile[path, default: []].append(defs.count)
defs.append(SymbolDef(name: parsed.name, path: path, line: match.line, kind: parsed.kind,
namespace: namespaces[path] ?? "", parents: parsed.parents, interfaces: parsed.interfaces))
}
let traitUses = await scanner.matches(LineQuery(pattern: .regex(PHPSymbols.traitUsePattern), fileExtension: "php"), filter: filter)
for match in traitUses {
let traits = PHPSymbols.parseTraitUse(match.text)
let path = RipgrepJSON.relativePath(match.path, root: root.path)
let candidates = (defsByFile[path] ?? []).filter { defs[$0].line < match.line }
guard !traits.isEmpty, let owner = candidates.max(by: { defs[$0].line < defs[$1].line }) else { continue }
for trait in traits where !defs[owner].traits.contains(trait) {
defs[owner].traits.append(trait)
}
}
let byName = Dictionary(grouping: defs, by: \.name)
Log.info("symbols", "index built: \(byName.count) classes in \(Int(Date().timeIntervalSince(started) * 1000)) ms")
return byName
}
private var scanner: ProjectScanning {
ProjectScanner.make(root: root, runner: runner, locator: locator, environment: environment)
}
private func filter(base: [String]) async -> ScanFilter {
ScanFilter(base: base, files: await config.current().files)
}
/// A reference hit; ripgrep's byte offset becomes a UTF-16 offset clamped to the capped line.
private static func hit(_ match: RipgrepMatch) -> ContentHit {
let text = String(match.text.prefix(SymbolLimits.maxLineLength))
let bytes = Array(match.text.utf8.prefix(match.byteOffset))
let offset = String(decoding: bytes, as: UTF8.self).utf16.count
return ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count))
}
}
+47
View File
@@ -0,0 +1,47 @@
import SwiftUI
/// The stepped on/off blink of the caret, terminal cursor and wordmark period: no fade.
struct BlinkModifier: ViewModifier {
var isActive: Bool
func body(content: Content) -> some View {
if isActive {
TimelineView(.periodic(from: .now, by: Metrics.blinkInterval / 2)) { context in
content.opacity(Self.isOn(at: context.date) ? 1 : 0)
}
} else {
content
}
}
/// On for the first half of each 1.1s cycle, off for the second.
static func isOn(at date: Date) -> Bool {
let half = Metrics.blinkInterval / 2
return Int(date.timeIntervalSinceReferenceDate / half).isMultiple(of: 2)
}
}
extension View {
/// Blinks the view with the design's stepped 1.1s cycle.
public func blinking(_ isActive: Bool = true) -> some View {
modifier(BlinkModifier(isActive: isActive))
}
}
/// `Helder` with the blinking amber period.
public struct Wordmark: View {
var role: TypeRole
public init(role: TypeRole = Typography.wordmark) {
self.role = role
}
public var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 0) {
Text("Helder").foregroundStyle(Palette.text1)
Text(".").foregroundStyle(Palette.amber).blinking()
}
.typeRole(role)
.fixedSize()
}
}
+89
View File
@@ -0,0 +1,89 @@
import SwiftUI
/// The one primary action on a surface: amber fill, ink Sans 500 12 label, radius 2, padding 6×10.
/// `destructive` switches to amber-deep with a light label (Delete, Discard).
public struct PrimaryButtonStyle: ButtonStyle {
var destructive: Bool
public init(destructive: Bool = false) {
self.destructive = destructive
}
public func makeBody(configuration: Configuration) -> some View {
configuration.label
.typeRole(Typography.button)
.foregroundStyle(destructive ? Palette.onDeep : Palette.ink)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(destructive ? Palette.amberDeep : Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
}
/// A secondary action beside a primary one (Cancel): hairline border, text-3 label, hover fill.
public struct SecondaryButtonStyle: ButtonStyle {
public init() {}
public func makeBody(configuration: Configuration) -> some View {
SecondaryButtonBody(configuration: configuration)
}
}
private struct SecondaryButtonBody: View {
let configuration: ButtonStyleConfiguration
@State private var isHovered = false
var body: some View {
configuration.label
.typeRole(Typography.button)
.foregroundStyle(isHovered || configuration.isPressed ? Palette.text1 : Palette.text3)
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(isHovered || configuration.isPressed ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
extension ButtonStyle where Self == PrimaryButtonStyle {
public static var primary: PrimaryButtonStyle { PrimaryButtonStyle() }
public static var destructive: PrimaryButtonStyle { PrimaryButtonStyle(destructive: true) }
}
extension ButtonStyle where Self == SecondaryButtonStyle {
public static var secondary: SecondaryButtonStyle { SecondaryButtonStyle() }
}
/// The focus treatment used everywhere: a 2pt amber border plus a 2pt 22% amber ring outside it.
struct FocusRingModifier: ViewModifier {
var isFocused: Bool
var cornerRadius: CGFloat
func body(content: Content) -> some View {
content
.overlay(
RoundedRectangle(cornerRadius: cornerRadius)
.strokeBorder(isFocused ? Palette.amber : Palette.raised, lineWidth: isFocused ? Metrics.accentRule : Metrics.hairline)
)
.background(
RoundedRectangle(cornerRadius: cornerRadius + Metrics.focusRingWidth)
.fill(isFocused ? Palette.focusRing : .clear)
.padding(-Metrics.focusRingWidth)
)
.animation(Metrics.smallControlTransition, value: isFocused)
}
}
extension View {
/// Draws the field border: a hairline at rest, the amber border and ring when focused. Never remove it.
public func focusRing(_ isFocused: Bool, cornerRadius: CGFloat = Metrics.radiusSmall) -> some View {
modifier(FocusRingModifier(isFocused: isFocused, cornerRadius: cornerRadius))
}
/// Disabled is 40% opacity and nothing else: no recolouring.
public func disabledLook(_ isDisabled: Bool) -> some View {
opacity(isDisabled ? 0.4 : 1).allowsHitTesting(!isDisabled)
}
}
@@ -0,0 +1,116 @@
import SwiftUI
/// The context-menu surface: 320pt, `panel`, hairline border, radius 4, menu shadow, 8pt vertical padding.
/// Fill it with a `ContextMenuHeader`, then `ContextMenuRow`s and `ContextMenuSeparator`s.
public struct ContextMenuPanel<Content: View>: View {
var content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
VStack(alignment: .leading, spacing: 0) { content }
.padding(.vertical, 8)
.frame(width: Metrics.contextMenuWidth, alignment: .leading)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
}
/// The path line at the top of a context menu: mono 11, text-4, hairline below.
public struct ContextMenuHeader: View {
var text: String
public init(_ text: String) {
self.text = text
}
public var body: some View {
Text(text)
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 14)
.padding(.bottom, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.hairline(.bottom)
.padding(.bottom, 8)
}
}
/// One 30pt menu item. Highlighted: `raised` fill, 2pt amber left rule, text-1 500 label, amber icon.
/// A tinted icon keeps its tint when highlighted; destructive items stay amber-deep in every state.
public struct ContextMenuRow: View {
var label: String
var systemImage: String?
var iconTint: Color?
var shortcut: String?
var isHighlighted: Bool
var isDestructive: Bool
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
isHighlighted: Bool, isDestructive: Bool = false) {
self.label = label
self.systemImage = systemImage
self.iconTint = iconTint
self.shortcut = shortcut
self.isHighlighted = isHighlighted
self.isDestructive = isDestructive
}
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
nonisolated public static let spark = "helder.spark"
public var body: some View {
HStack(spacing: 10) {
if systemImage == Self.spark {
SparkGlyph()
.stroke(iconColor, style: StrokeStyle(lineWidth: 1.1 * 13 / 16, lineJoin: .round))
.frame(width: 13, height: 13)
.frame(width: 15)
} else if let systemImage {
Image(systemName: systemImage)
.font(.system(size: 12, weight: .light))
.foregroundStyle(iconColor)
.frame(width: 15)
}
Text(label).typeRole(isHighlighted ? Typography.menuItemHighlighted : Typography.menuItem)
.foregroundStyle(labelColor)
Spacer(minLength: 8)
if let shortcut {
Text(shortcut).typeRole(Typography.chip).foregroundStyle(Palette.text4)
}
}
.padding(.leading, 16)
.padding(.trailing, 14)
.frame(height: Metrics.contextMenuItem)
.background(isHighlighted ? Palette.raised : .clear)
.overlay(alignment: .leading) {
Rectangle().fill(isHighlighted ? Palette.amber : .clear).frame(width: Metrics.accentRule)
}
.contentShape(Rectangle())
}
private var labelColor: Color {
if isDestructive { return Palette.removedText }
return isHighlighted ? Palette.text1 : Palette.text3
}
private var iconColor: Color {
if isDestructive { return Palette.removedText }
if let iconTint { return iconTint }
return isHighlighted ? Palette.amber : Palette.text4
}
}
/// The 1pt rule between menu groups, with 6pt above and below.
public struct ContextMenuSeparator: View {
public init() {}
public var body: some View {
Hairline().padding(.vertical, 6)
}
}
@@ -0,0 +1,38 @@
import SwiftUI
/// The 1pt `raised` divider. Use it for every border between panels, rows and bars.
public struct Hairline: View {
var axis: Axis
/// `.horizontal` draws a line across (a row divider); `.vertical` draws a column divider.
public init(_ axis: Axis = .horizontal) {
self.axis = axis
}
public var body: some View {
Rectangle()
.fill(Palette.raised)
.frame(width: axis == .vertical ? Metrics.hairline : nil,
height: axis == .horizontal ? Metrics.hairline : nil)
}
}
extension View {
/// Draws a hairline along one edge without changing the layout.
public func hairline(_ edge: Edge) -> some View {
overlay(alignment: edge.alignment) {
Hairline(edge == .top || edge == .bottom ? .horizontal : .vertical)
}
}
}
extension Edge {
fileprivate var alignment: Alignment {
switch self {
case .top: .top
case .bottom: .bottom
case .leading: .leading
case .trailing: .trailing
}
}
}
+78
View File
@@ -0,0 +1,78 @@
import SwiftUI
/// A key hint: 12pt mono 600, amber glyph, 1pt border, radius 2. Use it for every shortcut shown in the UI.
public struct Keycap: View {
public enum Style {
/// Amber glyph, raised border.
case normal
/// On an active toolbar toggle: the border turns amber.
case active
/// On a toggle that is off by meaning: glyph and border step back to text-4.
case muted
/// On an amber fill (primary button): ink glyph, ink border.
case onAmber
/// On an amber-deep fill (destructive button): light glyph, light border.
case onDeep
}
var keys: String
var style: Style
var role: TypeRole
public init(_ keys: String, style: Style = .normal, small: Bool = false) {
self.keys = keys
self.style = style
role = small ? Typography.keycapSmall : Typography.keycap
}
public init(_ keys: String, highlighted: Bool) {
self.init(keys, style: highlighted ? .active : .normal)
}
public var body: some View {
Text(keys)
.typeRole(role)
.foregroundStyle(glyph)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(border, lineWidth: Metrics.hairline))
.fixedSize()
}
private var glyph: Color {
switch style {
case .normal, .active: Palette.amber
case .muted: Palette.text4
case .onAmber: Palette.ink
case .onDeep: Palette.onDeep
}
}
private var border: Color {
switch style {
case .normal, .muted: Palette.raised
case .active: Palette.amberKeycapBorder
case .onAmber: Palette.inkKeycapBorder
case .onDeep: Palette.onDeep.opacity(0.4)
}
}
}
/// The `esc` (or `↵`) chip at the right of an overlay header or footer: mono 11, text-4, hairline border.
public struct EscChip: View {
var label: String
public init(_ label: String = "esc") {
self.label = label
}
public var body: some View {
Text(label)
.typeRole(Typography.chip)
.foregroundStyle(Palette.text4)
.padding(.horizontal, 6)
.padding(.vertical, 4)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.fixedSize()
}
}
@@ -0,0 +1,146 @@
import SwiftUI
/// The frame every overlay sits in: a flat ink scrim (no blur) and a `panel` card with a hairline border,
/// radius 8 and the overlay shadow. `.inset` fills the window minus 34pt; `.sized` centres a fixed-width card
/// at the top. A click on the scrim calls `onDismiss`.
public struct OverlayShell<Content: View>: View {
public enum Placement {
/// Search, Diff: the whole window minus the 34pt inset.
case inset
/// A card of this width, top-aligned inside the inset.
case sized(width: CGFloat)
}
var placement: Placement
var onDismiss: () -> Void
var content: Content
public init(_ placement: Placement = .inset, onDismiss: @escaping () -> Void, @ViewBuilder content: () -> Content) {
self.placement = placement
self.onDismiss = onDismiss
self.content = content()
}
public var body: some View {
ZStack(alignment: .top) {
Palette.scrim
.contentShape(Rectangle())
.onTapGesture(perform: onDismiss)
card
.padding(Metrics.overlayInset)
}
}
@ViewBuilder
private var card: some View {
switch placement {
case .inset:
OverlayCard { content }
.frame(maxWidth: .infinity, maxHeight: .infinity)
case let .sized(width):
OverlayCard { content }
.frame(width: width)
}
}
}
/// The overlay card alone, for surfaces that place themselves (the launcher, the pass-on prompt).
public struct OverlayCard<Content: View>: View {
var content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
content
.background(Palette.panel)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusOverlay).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius / 2, y: Metrics.overlayShadowY)
}
}
/// An overlay's header row: glyph (amber by default), mono 700 14 title, an optional mono detail right after it,
/// optional trailing content, then the `esc` chip unless `showsEscChip` is false.
public struct OverlayHeader<Trailing: View>: View {
var systemImage: String
var title: String
var detail: String?
var iconColor: Color
var showsEscChip: Bool
var height: CGFloat
var trailing: Trailing
public init(systemImage: String, title: String, detail: String? = nil, iconColor: Color = Palette.amber,
showsEscChip: Bool = true, height: CGFloat = 50, @ViewBuilder trailing: () -> Trailing) {
self.systemImage = systemImage
self.title = title
self.detail = detail
self.iconColor = iconColor
self.showsEscChip = showsEscChip
self.height = height
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 12) {
Image(systemName: systemImage).font(.system(size: 14, weight: .light)).foregroundStyle(iconColor)
Text(title).typeRole(Typography.dialogTitle).foregroundStyle(Palette.text1)
if let detail {
Text(detail).typeRole(Typography.path).foregroundStyle(Palette.text4).lineLimit(1)
}
Spacer(minLength: 12)
trailing
if showsEscChip { EscChip() }
}
.padding(.horizontal, 18)
.frame(height: height)
.hairline(.bottom)
}
}
extension OverlayHeader where Trailing == EmptyView {
public init(systemImage: String, title: String, detail: String? = nil, iconColor: Color = Palette.amber,
showsEscChip: Bool = true, height: CGFloat = 50) {
self.init(systemImage: systemImage, title: title, detail: detail, iconColor: iconColor,
showsEscChip: showsEscChip, height: height) { EmptyView() }
}
}
/// An overlay footer (38pt): mono 11 key hints with amber glyphs. Build the hints with `OverlayFooter.hint`.
public struct OverlayFooter<Trailing: View>: View {
var hints: Text
var trailing: Trailing
public init(_ hints: Text, @ViewBuilder trailing: () -> Trailing) {
self.hints = hints
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 14) {
hints.typeRole(Typography.chip)
Spacer(minLength: 0)
trailing
}
.padding(.horizontal, 18)
.frame(height: 38)
.hairline(.top)
}
}
extension OverlayFooter where Trailing == EmptyView {
public init(_ hints: Text) {
self.init(hints) { EmptyView() }
}
/// "⌘↑↓ navigate · ↵ open": pass pairs of (keys, action).
public static func hint(_ pairs: [(keys: String, action: String)]) -> Text {
pairs.enumerated().reduce(Text("")) { text, item in
let (index, pair) = item
let separator = index == 0 ? Text("") : Text(" · ").foregroundColor(Palette.text4)
return text + separator + Text(pair.keys).foregroundColor(Palette.amber) + Text(" " + pair.action).foregroundColor(Palette.text4)
}
}
}
@@ -0,0 +1,53 @@
import SwiftUI
/// The 10pt uppercase mono label over a panel or section, with an optional amber count.
public struct PanelLabel: View {
var title: String
var count: Int?
public init(_ title: String, count: Int? = nil) {
self.title = title
self.count = count
}
public var body: some View {
HStack {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer()
if let count {
Text("\(count)").typeRole(Typography.panelLabel).foregroundStyle(Palette.amber)
}
}
}
}
/// A column's header bar: the panel label left, optional trailing content, hairline below.
/// Use it at the top of Explorer, Source Control groups and code panels.
public struct PanelHeader<Trailing: View>: View {
var title: String
var height: CGFloat
var trailing: Trailing
public init(_ title: String, height: CGFloat = Metrics.panelHeader, @ViewBuilder trailing: () -> Trailing) {
self.title = title
self.height = height
self.trailing = trailing()
}
public var body: some View {
HStack(spacing: 8) {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer(minLength: 8)
trailing
}
.padding(.horizontal, 12)
.frame(height: height)
.hairline(.bottom)
}
}
extension PanelHeader where Trailing == EmptyView {
public init(_ title: String, height: CGFloat = Metrics.panelHeader) {
self.init(title, height: height) { EmptyView() }
}
}
@@ -0,0 +1,34 @@
import SwiftUI
/// A framed segment button: hairline frame, radius 2; while on, an amber fill with ink text.
public struct SegmentButton: View {
var label: String
var isOn: Bool
var action: () -> Void
@State private var isHovered = false
public init(_ label: String, isOn: Bool, action: @escaping () -> Void) {
self.label = label
self.isOn = isOn
self.action = action
}
public var body: some View {
Button(action: action) {
Text(label)
.typeRole(isOn ? Typography.segmentOn : Typography.segment)
.foregroundStyle(isOn ? Palette.ink : isHovered ? Palette.text1 : Palette.text3)
.padding(.horizontal, 12)
.padding(.vertical, 5)
.background(isOn ? Palette.amber : isHovered ? Palette.hover : .clear)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.fixedSize()
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.accessibilityAddTraits(isOn ? .isSelected : [])
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
@@ -0,0 +1,24 @@
import SwiftUI
/// Row states shared by every list (git rows, tree rows, launcher, search hits): hover is one fill step,
/// selected is `raised` with the 2pt amber rule on the left. Nothing lifts, scales or fades.
struct SelectableRowModifier: ViewModifier {
var isSelected: Bool
var isHovered: Bool
func body(content: Content) -> some View {
content
.background(isSelected ? Palette.raised : isHovered ? Palette.hover : .clear)
.overlay(alignment: .leading) {
Rectangle().fill(isSelected ? Palette.amber : .clear).frame(width: Metrics.accentRule)
}
.animation(Metrics.colorTransition, value: isHovered)
}
}
extension View {
/// Applies the selected and hover fills plus the amber selection rule.
public func selectableRow(isSelected: Bool, isHovered: Bool = false) -> some View {
modifier(SelectableRowModifier(isSelected: isSelected, isHovered: isHovered))
}
}
@@ -0,0 +1,66 @@
import AppKit
import SwiftUI
/// A 1pt hairline divider that resizes what is next to it. The pointer target reaches 3pt past the line
/// on both sides; hover and drag turn the line amber. `onDrag` receives the movement since the last call.
public struct Splitter: View {
var axis: Axis
var onDrag: (Double) -> Void
var onEnd: () -> Void
@State private var isHovered = false
@State private var isDragging = false
@State private var last: CGFloat = 0
/// `.vertical` is a column divider dragged left and right; `.horizontal` a row divider dragged up and down.
public init(_ axis: Axis = .vertical, onDrag: @escaping (Double) -> Void, onEnd: @escaping () -> Void = {}) {
self.axis = axis
self.onDrag = onDrag
self.onEnd = onEnd
}
public var body: some View {
Rectangle()
.fill(isHovered || isDragging ? Palette.amber : Palette.raised)
.frame(width: axis == .vertical ? Metrics.hairline : nil, height: axis == .horizontal ? Metrics.hairline : nil)
.overlay {
Color.clear
.frame(width: axis == .vertical ? Metrics.splitterHitArea : nil,
height: axis == .horizontal ? Metrics.splitterHitArea : nil)
.contentShape(Rectangle())
.onHover(perform: hover)
.gesture(drag)
}
.zIndex(5)
.animation(Metrics.smallControlTransition, value: isHovered || isDragging)
}
private var drag: some Gesture {
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
let position = axis == .vertical ? value.translation.width : value.translation.height
if !isDragging {
isDragging = true
last = 0
}
onDrag(Double(position - last))
last = position
}
.onEnded { _ in
isDragging = false
last = 0
if !isHovered { NSCursor.pop() }
onEnd()
}
}
private func hover(_ inside: Bool) {
guard inside != isHovered else { return }
isHovered = inside
if isDragging { return }
if inside {
(axis == .vertical ? NSCursor.resizeLeftRight : NSCursor.resizeUpDown).push()
} else {
NSCursor.pop()
}
}
}
@@ -0,0 +1,75 @@
import SwiftUI
/// A title-bar toggle: Sans 12 label plus keycap. Off has no fill; on gets the amber tint and an amber keycap border;
/// `muted` is for a toggle that is off by meaning (hidden files), where label and keycap step back to text-4.
public struct ToolbarToggle: View {
var label: String
var keys: String
var isOn: Bool
var isMuted: Bool
var action: () -> Void
@State private var isHovered = false
public init(_ label: String, keys: String, isOn: Bool, muted: Bool = false, action: @escaping () -> Void) {
self.label = label
self.keys = keys
self.isOn = isOn
isMuted = muted
self.action = action
}
public var body: some View {
Button(action: action) {
HStack(spacing: 8) {
Text(label).typeRole(isOn ? Typography.toolbarLabelOn : Typography.toolbarLabel)
Keycap(keys, style: isOn ? .active : isMuted ? .muted : .normal)
}
.foregroundStyle(labelColor)
.padding(Metrics.toolbarPadding)
.background(fill, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
.animation(Metrics.smallControlTransition, value: isOn)
}
private var labelColor: Color {
if isOn { return Palette.text1 }
if isMuted { return isHovered ? Palette.text3 : Palette.text4 }
return isHovered ? Palette.text1 : Palette.text3
}
private var fill: Color {
if isOn { return Palette.amberTint }
return isHovered && !isMuted ? Palette.hover : .clear
}
}
/// The icon-only title-bar control (the `?`): a 26pt square with a hairline border.
public struct ToolbarIconButton: View {
var glyph: String
var action: () -> Void
@State private var isHovered = false
public init(_ glyph: String, action: @escaping () -> Void) {
self.glyph = glyph
self.action = action
}
public var body: some View {
Button(action: action) {
Text(glyph)
.typeRole(Typography.keycap)
.foregroundStyle(isHovered ? Palette.text1 : Palette.text4)
.frame(width: Metrics.toolbarIconButton, height: Metrics.toolbarIconButton)
.background(isHovered ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { isHovered = $0 }
.animation(Metrics.smallControlTransition, value: isHovered)
}
}
+76
View File
@@ -0,0 +1,76 @@
import SwiftUI
/// The design's tooltip: `raised` surface, text-5 border, radius 2, Sans 12/1.5, no arrow, no shadow.
/// Name the current state in amber with `Tooltip.stated`, then say what a click does.
public struct Tooltip: View {
var text: Text
public init(_ text: Text) {
self.text = text
}
public init(_ string: String) {
text = Text(string)
}
/// "Lead: *state* — rest", with the state word in amber.
public static func stated(_ lead: String, _ state: String, _ rest: String) -> Text {
Text(lead).foregroundColor(Palette.text2) + Text(state).foregroundColor(Palette.amber) + Text(rest).foregroundColor(Palette.text2)
}
public var body: some View {
text
.typeRole(Typography.tooltip)
.foregroundStyle(Palette.text2)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.frame(maxWidth: Metrics.tooltipMaxWidth, alignment: .leading)
.fixedSize()
.background(Palette.raised, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.tooltipBorder, lineWidth: Metrics.hairline))
}
}
struct TooltipModifier: ViewModifier {
var text: Text
var edge: HorizontalAlignment
@State private var isShown = false
@State private var pending: Task<Void, Never>?
func body(content: Content) -> some View {
content
.onHover { inside in
pending?.cancel()
if inside {
pending = Task { @MainActor in
try? await Task.sleep(for: Metrics.tooltipDelay)
if !Task.isCancelled { isShown = true }
}
} else {
isShown = false
}
}
.simultaneousGesture(TapGesture().onEnded { pending?.cancel(); isShown = false })
.overlay(alignment: Alignment(horizontal: edge, vertical: .bottom)) {
if isShown {
Tooltip(text)
.alignmentGuide(.bottom) { $0[.top] - 8 }
.allowsHitTesting(false)
}
}
}
}
extension View {
/// Shows a design tooltip 350ms after the pointer rests on the view, 8pt below it.
/// The host must sit above its neighbours (`zIndex`) so the tip is not drawn under them.
public func tip(_ text: Text, edge: HorizontalAlignment = .leading) -> some View {
modifier(TooltipModifier(text: text, edge: edge))
}
public func tip(_ string: String, edge: HorizontalAlignment = .leading) -> some View {
tip(Text(string), edge: edge)
}
}
@@ -0,0 +1,21 @@
import HelderCore
import SwiftUI
/// The per-extension chip: a fixed 28pt wide, mono 600 10 in ink on the badge fill, radius 2.
/// The fixed width keeps the file names beside it in one column.
public struct TypeBadge: View {
var badge: FileBadge
public init(path: String) {
badge = FileType.badge(for: path)
}
public var body: some View {
Text(badge.text)
.typeRole(TypeRole(.monoSemiBold, 10))
.foregroundStyle(Palette.badgeText)
.lineLimit(1)
.frame(width: 28, height: 16)
.background(Palette.badge(badge.tint), in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
+174
View File
@@ -0,0 +1,174 @@
import AppKit
import HelderCore
/// One file's text as the editor holds it: its own storage, undo history, line index and tokens,
/// so switching files swaps storages instead of re-reading and re-colouring the file.
@MainActor
final class CodeDocument: NSObject, NSTextStorageDelegate {
let id: String
let storage = NSTextStorage()
let undoManager = UndoManager()
var revision = -1
var language: Language?
var tabSize = 4
private(set) var scale: CGFloat = 1
private(set) var lineIndex = LineIndex("")
var selection = NSRange(location: 0, length: 0)
var scrollOrigin = NSPoint.zero
private(set) var tokens: [Token] = []
private var tokenTextLength = 0
private var knownSymbols: Set<String> = []
/// Which symbol list the colours were computed with.
private(set) var symbolsVersion = -1
private var generation = 0
/// What changed since the last paint, in current text coordinates.
private var dirty: NSRange?
/// Suppresses the edit bookkeeping while the document replaces its own text.
private var isLoading = false
init(id: String) {
self.id = id
super.init()
storage.delegate = self
}
var length: Int { storage.length }
/// Replaces the whole text from outside (load, reload); the undo history no longer applies.
func load(_ text: String, revision: Int, tabSize: Int) {
self.revision = revision
self.tabSize = tabSize
isLoading = true
storage.setAttributedString(NSAttributedString(string: text, attributes: EditorFonts.baseAttributes(tabSize: tabSize, scale: scale)))
isLoading = false
lineIndex = LineIndex(text)
undoManager.removeAllActions()
tokens = []
tokenTextLength = storage.length
dirty = nil
selection = NSRange(location: min(selection.location, storage.length), length: 0)
}
func setTabSize(_ size: Int) {
guard size != tabSize else { return }
tabSize = size
restyle()
}
/// View → Zoom: the font and row height change in place, keeping the text and its undo history.
func setScale(_ next: CGFloat) {
guard next != scale else { return }
scale = next
restyle()
}
private func restyle() {
let font = EditorFonts.code(scale: scale)
let whole = NSRange(location: 0, length: storage.length)
storage.beginEditing()
storage.addAttribute(.font, value: font, range: whole)
storage.addAttribute(.paragraphStyle, value: EditorFonts.paragraphStyle(tabSize: tabSize, font: font, scale: scale), range: whole)
storage.endEditing()
}
nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions,
range editedRange: NSRange, changeInLength delta: Int) {
guard editedMask.contains(.editedCharacters) else { return }
MainActor.assumeIsolated {
guard !isLoading else { return }
let inserted = (textStorage.string as NSString).substring(with: editedRange)
lineIndex.applyEdit(editedRange: editedRange, delta: delta, inserted: inserted)
markDirty(editedRange, delta: delta)
}
}
private func markDirty(_ range: NSRange, delta: Int) {
guard let previous = dirty else {
dirty = range
return
}
let shiftedEnd = NSMaxRange(previous) >= range.location ? NSMaxRange(previous) + delta : NSMaxRange(previous)
let start = min(previous.location, range.location)
let end = max(shiftedEnd, NSMaxRange(range))
dirty = NSRange(location: start, length: max(0, end - start))
}
// MARK: Highlighting
/// Colours the whole text off the main thread; the plain text shows at once, colours follow.
func highlightAll(symbols: Set<String>, version: Int) {
knownSymbols = symbols
symbolsVersion = version
dirty = nil
run(full: true, delay: nil)
}
/// After a keystroke: waits for a pause, re-tokenises, repaints only what changed.
func highlightEdits() {
run(full: false, delay: .milliseconds(40))
}
private func run(full: Bool, delay: Duration?) {
generation += 1
let mine = generation
guard let language else {
if full { paint(NSRange(location: 0, length: storage.length), with: []) }
return
}
Task { @MainActor [weak self] in
if let delay { try? await Task.sleep(for: delay) }
guard let self, mine == self.generation else { return }
let text = self.storage.string
let symbols = self.knownSymbols
let tokens = await Task.detached(priority: .userInitiated) {
SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
}.value
guard mine == self.generation, (text as NSString).length == self.storage.length else { return }
let length = self.storage.length
let range: NSRange
if full || self.tokens.isEmpty {
range = NSRange(location: 0, length: length)
} else {
let edited = self.dirty ?? NSRange(location: 0, length: 0)
range = HighlightDiff.repaintRange(old: self.tokens, new: tokens, edited: edited,
delta: length - self.tokenTextLength, newLength: length)
}
self.tokens = tokens
self.tokenTextLength = length
self.dirty = nil
self.paint(range, with: tokens)
}
}
private func paint(_ range: NSRange, with tokens: [Token]) {
guard range.length > 0 else { return }
storage.beginEditing()
storage.addAttribute(.foregroundColor, value: EditorColors.syntax(.plain), range: range)
var index = firstToken(endingAfter: range.location, in: tokens)
let end = NSMaxRange(range)
while index < tokens.count, tokens[index].location < end {
let token = tokens[index]
index += 1
guard token.role != .plain else { continue }
let hit = NSIntersectionRange(range, NSRange(location: token.location, length: token.length))
if hit.length > 0 { storage.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: hit) }
}
storage.endEditing()
}
private func firstToken(endingAfter location: Int, in tokens: [Token]) -> Int {
var low = 0
var high = tokens.count
while low < high {
let mid = (low + high) / 2
if tokens[mid].location + tokens[mid].length <= location { low = mid + 1 } else { high = mid }
}
return low
}
/// Ranges of the ⌘-clickable class names, for the underline while ⌘ is held.
var symbolRanges: [NSRange] {
tokens.filter { $0.role == .symbol }.map { NSRange(location: $0.location, length: $0.length) }
}
}
@@ -0,0 +1,130 @@
import AppKit
import HelderCore
/// The pane's own paint: change marks, the read-only caret row, the jump flash, the ⌘ underline and the gutter.
extension CodeEditorController {
/// The caret row is only tinted in the read-only panes; the editable buffer shows the caret alone.
private var caretLine: Int? {
guard !textView.isEditable, let doc = document else { return nil }
let selection = textView.selectedRange()
guard selection.length == 0 else { return nil }
return doc.lineIndex.line(containing: selection.location)
}
/// Behind the text, from the code edge: Actual's tint and teal rule, gap rules, the caret row, the flash.
func drawRowBackgrounds(in rect: NSRect) {
let width = max(textView.bounds.width, rect.maxX)
let caret = caretLine
let flash = flashStrength
forEachRow(in: rect) { row in
let band = NSRect(x: 0, y: row.rect.minY, width: width, height: row.rect.height)
let mark = marks[row.line]
if let mark, mark.tint, let tone = mark.tone {
EditorColors.fill(tone).setFill()
band.fill()
EditorColors.tone(tone).setFill()
NSRect(x: 0, y: band.minY, width: Metrics.accentRule, height: band.height).fill()
} else if mark == nil, row.line == caret {
EditorColors.activeLine.setFill()
band.fill()
}
if row.line == flashLine, flash > 0 {
EditorColors.flash.withAlphaComponent(EditorColors.flash.alphaComponent * flash).setFill()
band.fill(using: .sourceOver)
EditorColors.amber.withAlphaComponent(flash).setFill()
NSRect(x: 0, y: band.minY, width: Metrics.accentRule, height: band.height).fill(using: .sourceOver)
}
drawGapRule(mark, row: row, width: width)
}
}
private func drawGapRule(_ mark: CodeLineMark?, row: Row, width: CGFloat) {
guard let gap = mark?.gap else { return }
let y: CGFloat
switch gap {
case .above:
guard row.isFirst else { return }
y = row.rect.minY
case .below:
guard row.isLast else { return }
y = row.rect.maxY - Metrics.accentRule
}
EditorColors.removedText.setFill()
NSRect(x: 0, y: y, width: width, height: Metrics.accentRule).fill()
}
/// Over the text while ⌘ is held: an amber underline 3pt under the baseline of each clickable class name.
func drawSymbolUnderlines(in rect: NSRect) {
guard symbolsUnderlined, configuration?.knownSymbols.isEmpty == false, let doc = document else { return }
let origin = textView.textContainerOrigin
let visible = layout.glyphRange(forBoundingRect: rect.offsetBy(dx: -origin.x, dy: -origin.y), in: textContainer)
let characters = layout.characterRange(forGlyphRange: visible, actualGlyphRange: nil)
let baseline = EditorFonts.baseline(scale: fontScale)
EditorColors.amber.setFill()
for range in doc.symbolRanges where NSMaxRange(range) <= doc.length && NSIntersectionRange(range, characters).length > 0 {
let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
layout.enumerateEnclosingRects(forGlyphRange: glyphs, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
in: textContainer) { box, _ in
let fragment = self.layout.lineFragmentRect(forGlyphAt: glyphs.location, effectiveRange: nil)
let y = fragment.minY + baseline + 3 + origin.y
NSRect(x: box.minX + origin.x, y: y, width: box.width, height: 1).fill()
}
}
}
/// Numbers only: a changed line in Actual lifts its number to teal; the read-only caret row lifts its number.
func drawGutter(in rect: NSRect, of ruler: CodeGutterView) {
EditorColors.background.setFill()
rect.fill()
let font = EditorFonts.code(scale: fontScale)
let lineHeight = EditorFonts.lineHeight(scale: fontScale)
let caret = caretLine
let thickness = ruler.ruleThickness
forEachRow(in: textView.visibleRect) { row in
let y = ruler.convert(NSPoint(x: 0, y: row.rect.minY), from: textView).y
let band = NSRect(x: 0, y: y, width: thickness, height: row.rect.height)
guard band.intersects(rect) else { return }
let mark = marks[row.line]
var color = mark == nil && row.line == caret ? EditorColors.lineNumberActive : EditorColors.lineNumber
if let mark, mark.tint, let tone = mark.tone { color = EditorColors.tone(tone) }
guard row.isFirst else { return }
let label = String(row.line) as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color]
let size = label.size(withAttributes: attributes)
let baseline = (lineHeight - (font.ascender - font.descender)) / 2
label.draw(at: NSPoint(x: thickness - 14 - size.width, y: band.minY + baseline), withAttributes: attributes)
}
}
// MARK: The jump flash
/// Full strength for the first 65% of the flash, then fading out.
private var flashStrength: CGFloat {
guard flashLine != nil, let start = flashStart else { return 0 }
let elapsed = Date().timeIntervalSince(start) / EditorFonts.flashDuration
if elapsed < 0.65 { return 1 }
return max(0, 1 - (elapsed - 0.65) / 0.35)
}
func startFlash(on line: Int) {
flashLine = line
flashStart = Date()
flashTimer?.invalidate()
flashTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] timer in
MainActor.assumeIsolated {
guard let self else { return timer.invalidate() }
self.textView.needsDisplay = true
if let start = self.flashStart, Date().timeIntervalSince(start) >= EditorFonts.flashDuration { self.endFlash() }
}
}
textView.needsDisplay = true
}
func endFlash() {
flashTimer?.invalidate()
flashTimer = nil
flashLine = nil
flashStart = nil
textView.needsDisplay = true
}
}
@@ -0,0 +1,540 @@
import AppKit
import HelderCore
/// What the code pane shows; rebuilt by SwiftUI on every update, applied only where it changed.
struct CodeEditorConfiguration {
/// Identifies the document: the path plus the variant (`#original` for the HEAD text).
var documentID: String
var path: String
var text: String
/// Replace the view's text only when this moves; otherwise the user's typing is the truth.
var revision: Int
var language: Language?
var isEditable: Bool
var wrap: Bool
var tabSize: Int
/// Cheap identity of the marks; `makeMarks` runs only when it moves.
var marksKey: String
var makeMarks: () -> [Int: CodeLineMark]
var opensDiffOnClick: Bool
var knownSymbols: Set<String>
var symbolsVersion: Int
var flash: LineFlash?
/// The text view takes keyboard focus when this moves while the pane is shown.
var focusRequest: Int
/// ⌘A outside the text view: everything is selected when this moves while the pane is shown.
var selectAllRequest: Int
/// View → Zoom.
var fontScale: CGFloat
var isShown: Bool
}
struct CodeEditorActions {
var edited: (String) -> Void = { _ in }
var cursorMoved: (_ line: Int, _ column: Int) -> Void = { _, _ in }
var selectionChanged: (_ lines: ClosedRange<Int>?, _ code: String?) -> Void = { _, _ in }
var markedLineClicked: (Int) -> Void = { _ in }
/// Reference, selected code, and the anchor in top-left window coordinates.
var contextMenu: (AgentReference, String?, CGPoint) -> Void = { _, _, _ in }
var symbolClicked: (String) -> Void = { _ in }
/// ⌘→ with a selection; returns false when there was nothing to pass.
var passOnSelection: (CGPoint) -> Bool = { _ in false }
var command: (EditorKeyCommand) -> Void = { _ in }
}
@MainActor
final class CodeEditorController: NSObject, NSTextViewDelegate, NSLayoutManagerDelegate {
let scrollView = CodeScrollView()
let textView: CodeTextView
let gutter: CodeGutterView
var actions = CodeEditorActions()
private let layoutManager = NSLayoutManager()
private let container = NSTextContainer(size: NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
private var documents: [String: CodeDocument] = [:]
private var recent: [String] = []
private(set) var document: CodeDocument?
private(set) var configuration: CodeEditorConfiguration?
private(set) var marks: [Int: CodeLineMark] = [:]
private var wrap: Bool?
private var appliedFlash: UUID?
var flashLine: Int?
var flashStart: Date?
var flashTimer: Timer?
private(set) var symbolsUnderlined = false
private var appliedFocusRequest: Int?
private var appliedSelectAll: Int?
/// Read by the layout delegate, which AppKit calls off the main-actor annotation.
nonisolated(unsafe) private(set) var fontScale: CGFloat = 1
/// True inside `apply`: store updates then wait a turn, since SwiftUI is mid-update.
private var isApplying = false
var layout: NSLayoutManager { layoutManager }
var textContainer: NSTextContainer { container }
private static let documentCacheSize = 12
override init() {
let storage = NSTextStorage()
storage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(container)
layoutManager.allowsNonContiguousLayout = true
textView = CodeTextView(frame: .zero, textContainer: container)
gutter = CodeGutterView(scrollView: scrollView, orientation: .verticalRuler)
super.init()
layoutManager.delegate = self
configureTextView()
configureScrollView()
}
private func configureTextView() {
let tv = textView
tv.controller = self
tv.delegate = self
tv.isRichText = false
tv.importsGraphics = false
tv.allowsUndo = true
tv.usesFindBar = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.isContinuousSpellCheckingEnabled = false
tv.isGrammarCheckingEnabled = false
tv.isAutomaticLinkDetectionEnabled = false
tv.smartInsertDeleteEnabled = false
tv.drawsBackground = true
tv.backgroundColor = EditorColors.background
tv.insertionPointColor = EditorColors.amber
tv.selectedTextAttributes = [.backgroundColor: EditorColors.selection]
tv.font = EditorFonts.code
tv.textColor = EditorColors.syntax(.plain)
tv.typingAttributes = EditorFonts.baseAttributes(tabSize: 4)
tv.textContainerInset = NSSize(width: 0, height: EditorFonts.topInset)
tv.isVerticallyResizable = true
tv.minSize = .zero
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
container.lineFragmentPadding = 6
}
private func configureScrollView() {
scrollView.onTile = { [weak self] in self?.fitTextView() }
scrollView.documentView = textView
scrollView.drawsBackground = true
scrollView.backgroundColor = EditorColors.background
scrollView.hasVerticalScroller = true
scrollView.autohidesScrollers = true
scrollView.borderType = .noBorder
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: EditorFonts.bottomInset - EditorFonts.topInset, right: 0)
gutter.controller = self
gutter.ruleThickness = Metrics.codeGutter
// Since macOS 14 a view may draw outside its bounds; unclipped, the gutter paints over the columns around it.
gutter.clipsToBounds = true
gutter.clientView = textView
scrollView.verticalRulerView = gutter
scrollView.hasVerticalRuler = true
scrollView.rulersVisible = true
scrollView.contentView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(scrolled), name: NSView.boundsDidChangeNotification,
object: scrollView.contentView)
}
@objc private func scrolled() {
gutter.needsDisplay = true
}
// MARK: Applying the configuration
func apply(_ next: CodeEditorConfiguration) {
isApplying = true
defer { isApplying = false }
let previous = configuration
configuration = next
applyWrap(next.wrap)
applyScale(next.fontScale)
textView.isEditable = next.isEditable
textView.isSelectable = true
var reloaded = false
if document?.id != next.documentID {
reloaded = switchDocument(to: next)
} else if let doc = document, doc.revision != next.revision {
replaceText(of: doc, with: next)
reloaded = true
}
guard let doc = document else { return }
doc.setTabSize(next.tabSize)
doc.setScale(fontScale)
if reloaded || doc.language != next.language || doc.symbolsVersion != next.symbolsVersion {
doc.language = next.language
doc.highlightAll(symbols: next.knownSymbols, version: next.symbolsVersion)
}
if previous?.marksKey != next.marksKey || previous?.documentID != next.documentID {
marks = next.makeMarks()
textView.needsDisplay = true
gutter.needsDisplay = true
}
applyFlash(next.flash, path: next.path)
applyFocusRequest(next)
applySelectAll(next)
}
private func applySelectAll(_ next: CodeEditorConfiguration) {
defer { appliedSelectAll = next.selectAllRequest }
guard let applied = appliedSelectAll, applied != next.selectAllRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.focusTextView()
self.textView.selectAll(nil)
}
}
private func applyScale(_ scale: CGFloat) {
guard scale != fontScale else { return }
fontScale = scale
textView.font = EditorFonts.code(scale: scale)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: configuration?.tabSize ?? 4, scale: scale)
for doc in documents.values { doc.setScale(scale) }
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
textView.needsDisplay = true
gutter.needsDisplay = true
}
/// Waits a turn so an overlay that just closed has left the window, and never takes
/// focus from a text field another overlay is typing in.
private func applyFocusRequest(_ next: CodeEditorConfiguration) {
defer { appliedFocusRequest = next.focusRequest }
guard let applied = appliedFocusRequest, applied != next.focusRequest, next.isShown else { return }
DispatchQueue.main.async { [weak self] in
guard let self, let window = self.textView.window else { return }
if let field = window.firstResponder as? NSTextView, field.isFieldEditor { return }
self.focusTextView()
}
}
/// Returns true when the document's text was (re)loaded and needs colouring.
private func switchDocument(to next: CodeEditorConfiguration) -> Bool {
if let current = document {
current.selection = textView.selectedRange()
current.scrollOrigin = scrollView.contentView.bounds.origin
}
let doc = documents[next.documentID] ?? CodeDocument(id: next.documentID)
documents[next.documentID] = doc
recent.removeAll { $0 == next.documentID }
recent.insert(next.documentID, at: 0)
for evicted in recent.dropFirst(Self.documentCacheSize) { documents[evicted] = nil }
recent = Array(recent.prefix(Self.documentCacheSize))
let isNew = doc.revision != next.revision
if isNew {
doc.language = next.language
doc.setScale(fontScale)
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
}
document = doc
layoutManager.replaceTextStorage(doc.storage)
textView.typingAttributes = EditorFonts.baseAttributes(tabSize: next.tabSize, scale: fontScale)
textView.setSelectedRange(clamped(doc.selection, in: doc))
appliedFlash = nil
flashLine = nil
let clip = scrollView.contentView
// The ruler gives the clip view a left inset, so its resting origin is not .zero.
let home = NSPoint(x: -clip.contentInsets.left, y: -clip.contentInsets.top)
clip.scroll(to: isNew ? home : doc.scrollOrigin)
scrollView.reflectScrolledClipView(clip)
textView.needsDisplay = true
gutter.needsDisplay = true
reportSelection()
return isNew
}
private func replaceText(of doc: CodeDocument, with next: CodeEditorConfiguration) {
let selection = textView.selectedRange()
let origin = scrollView.contentView.bounds.origin
doc.load(next.text, revision: next.revision, tabSize: next.tabSize)
textView.setSelectedRange(NSRange(location: min(selection.location, doc.length), length: 0))
scrollView.contentView.scroll(to: origin)
scrollView.reflectScrolledClipView(scrollView.contentView)
gutter.needsDisplay = true
}
private func clamped(_ range: NSRange, in doc: CodeDocument) -> NSRange {
let location = min(range.location, doc.length)
return NSRange(location: location, length: min(range.length, doc.length - location))
}
/// The text view always fills the visible width; unwrapped it may grow wider.
private func fitTextView() {
let size = scrollView.contentSize
let width = visibleWidth
if textView.frame.origin != .zero { textView.setFrameOrigin(.zero) }
textView.minSize = NSSize(width: width, height: size.height)
if wrap == true || textView.frame.width < width {
textView.frame.size.width = width
}
if textView.frame.height < size.height { textView.frame.size.height = size.height }
}
/// The content width right of the gutter.
private var visibleWidth: CGFloat {
max(1, scrollView.contentSize.width - scrollView.contentView.contentInsets.left)
}
private func applyWrap(_ on: Bool) {
guard wrap != on else { return }
wrap = on
scrollView.hasHorizontalScroller = !on
textView.isHorizontallyResizable = !on
container.widthTracksTextView = on
textView.autoresizingMask = on ? [.width] : []
container.containerSize = NSSize(width: on ? visibleWidth : CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
fitTextView()
layoutManager.invalidateLayout(forCharacterRange: NSRange(location: 0, length: layoutManager.textStorage?.length ?? 0),
actualCharacterRange: nil)
gutter.needsDisplay = true
}
private func applyFlash(_ flash: LineFlash?, path: String) {
guard let flash, flash.path == path else {
if flashLine != nil { endFlash() }
return
}
guard appliedFlash != flash.id, let doc = document, doc.revision > 0 || doc.length > 0 else { return }
appliedFlash = flash.id
startFlash(on: flash.line)
scroll(toLine: flash.line)
let offset = doc.lineIndex.start(ofLine: flash.line)
textView.setSelectedRange(NSRange(location: min(offset, doc.length), length: 0))
textView.needsDisplay = true
}
/// Centres a line in the pane, as near as the file permits.
func scroll(toLine line: Int) {
guard let doc = document else { return }
let rect = rowRect(forLine: line, in: doc)
let clip = scrollView.contentView
let maxY = max(0, textView.frame.height - clip.bounds.height)
let y = min(max(0, rect.midY - clip.bounds.height / 2), maxY)
clip.scroll(to: NSPoint(x: clip.bounds.origin.x, y: y))
scrollView.reflectScrolledClipView(clip)
}
private func rowRect(forLine line: Int, in doc: CodeDocument) -> NSRect {
let offset = doc.lineIndex.start(ofLine: line)
let origin = textView.textContainerOrigin
guard offset < doc.length else {
return layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
}
let glyph = layoutManager.glyphIndexForCharacter(at: offset)
return layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil).offsetBy(dx: origin.x, dy: origin.y)
}
// MARK: Rows
struct Row {
var line: Int
var isFirst: Bool
var isLast: Bool
/// In text view coordinates.
var rect: NSRect
}
/// Every visual row that intersects `rect` (text view coordinates), wrapped rows included.
func forEachRow(in rect: NSRect, _ body: (Row) -> Void) {
guard let doc = document else { return }
let origin = textView.textContainerOrigin
let index = doc.lineIndex
let bounds = rect.offsetBy(dx: -origin.x, dy: -origin.y)
let glyphs = layoutManager.glyphRange(forBoundingRect: bounds, in: container)
var glyph = glyphs.location
while glyph < NSMaxRange(glyphs) {
var fragment = NSRange()
let frame = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &fragment)
let chars = layoutManager.characterRange(forGlyphRange: fragment, actualGlyphRange: nil)
let line = index.line(containing: chars.location)
body(Row(line: line, isFirst: index.isLineStart(chars.location),
isLast: NSMaxRange(chars) >= index.end(ofLine: line),
rect: frame.offsetBy(dx: origin.x, dy: origin.y)))
glyph = max(NSMaxRange(fragment), glyph + 1)
}
if layoutManager.extraLineFragmentTextContainer != nil {
let extra = layoutManager.extraLineFragmentRect.offsetBy(dx: origin.x, dy: origin.y)
if extra.intersects(rect.insetBy(dx: 0, dy: -1)) {
body(Row(line: index.lineCount, isFirst: true, isLast: true, rect: extra))
}
}
}
// MARK: Layout: fixed rows, 20pt at actual size
nonisolated func layoutManager(_ layoutManager: NSLayoutManager,
shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<NSRect>,
lineFragmentUsedRect: UnsafeMutablePointer<NSRect>,
baselineOffset: UnsafeMutablePointer<CGFloat>,
in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool {
let height = EditorFonts.lineHeight(scale: fontScale)
lineFragmentRect.pointee.size.height = height
lineFragmentUsedRect.pointee.size.height = height
baselineOffset.pointee = EditorFonts.baseline(scale: fontScale)
return true
}
// MARK: Text view delegate
nonisolated func undoManager(for view: NSTextView) -> UndoManager? {
MainActor.assumeIsolated { document?.undoManager }
}
nonisolated func textDidChange(_ notification: Notification) {
MainActor.assumeIsolated {
guard let doc = document else { return }
doc.highlightEdits()
actions.edited(textView.string)
gutter.needsDisplay = true
}
}
nonisolated func textViewDidChangeSelection(_ notification: Notification) {
MainActor.assumeIsolated {
reportSelection()
textView.needsDisplay = true
gutter.needsDisplay = true
}
}
private func reportSelection() {
if isApplying {
DispatchQueue.main.async { [weak self] in self?.reportSelection() }
return
}
guard let doc = document else { return }
let range = textView.selectedRange()
let caret = min(range.location + range.length, doc.length)
actions.cursorMoved(doc.lineIndex.line(containing: caret), doc.lineIndex.column(of: caret))
if range.length > 0 {
let code = (doc.storage.string as NSString).substring(with: clamped(range, in: doc))
actions.selectionChanged(EditorReference.lines(of: range, in: doc.lineIndex), code)
} else {
actions.selectionChanged(nil, nil)
}
}
// MARK: Gestures
private func characterIndex(atWindowPoint point: NSPoint) -> Int {
textView.characterIndexForInsertion(at: textView.convert(point, from: nil))
}
private func line(atWindowPoint point: NSPoint) -> Int? {
guard let doc = document else { return nil }
let local = textView.convert(point, from: nil)
let used = layoutManager.usedRect(for: container).offsetBy(dx: 0, dy: textView.textContainerOrigin.y)
guard local.y <= used.maxY else { return nil }
return doc.lineIndex.line(containing: characterIndex(atWindowPoint: point))
}
/// A plain click on a marked line in Actual opens the Diff there.
func plainClick(atWindowPoint point: NSPoint) {
guard configuration?.opensDiffOnClick == true,
let line = line(atWindowPoint: point), marks[line] != nil else { return }
let action = actions.markedLineClicked
DispatchQueue.main.async { action(line) }
}
/// ⌘-click: follows a class name the project declares.
func followSymbol(at event: NSEvent) -> Bool {
guard let name = symbol(atWindowPoint: event.locationInWindow) else { return false }
actions.symbolClicked(name)
return true
}
/// The known class name under the pointer; only a hit on the glyph itself counts, not the space after a line.
func symbol(atWindowPoint point: NSPoint) -> String? {
guard let configuration, !configuration.knownSymbols.isEmpty, let doc = document, doc.length > 0 else { return nil }
let origin = textView.textContainerOrigin
let local = textView.convert(point, from: nil)
let inContainer = NSPoint(x: local.x - origin.x, y: local.y - origin.y)
let glyph = layoutManager.glyphIndex(for: inContainer, in: container)
let box = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: container)
guard box.contains(inContainer) else { return nil }
let name = PHPSymbols.word(in: doc.storage.string, at: layoutManager.characterIndexForGlyph(at: glyph))
return configuration.knownSymbols.contains(name) ? name : nil
}
func showContextMenu(for event: NSEvent) {
guard let configuration, let doc = document else { return }
focusTextView()
let selection = textView.selectedRange()
let clicked = line(atWindowPoint: event.locationInWindow) ?? doc.lineIndex.lineCount
let lines = selection.length > 0 ? EditorReference.lines(of: selection, in: doc.lineIndex) : nil
let code = selection.length > 0 ? (doc.storage.string as NSString).substring(with: clamped(selection, in: doc)) : nil
let reference = EditorReference.make(path: configuration.path, selectedLines: lines, clickedLine: clicked)
actions.contextMenu(reference, code, topLeft(event.locationInWindow))
}
func passOnSelection() -> Bool {
let range = textView.selectedRange()
guard range.length > 0, let window = textView.window else { return false }
let screen = textView.firstRect(forCharacterRange: range, actualRange: nil)
let rect = window.convertFromScreen(screen)
return actions.passOnSelection(topLeft(NSPoint(x: rect.minX, y: rect.minY)))
}
func run(_ command: EditorKeyCommand) {
actions.command(command)
}
func indent(outdent: Bool) -> Bool {
guard textView.isEditable, let configuration, let doc = document,
let edit = Indentation.edit(doc.storage.string, selection: textView.selectedRange(),
tabSize: configuration.tabSize, outdent: outdent) else { return textView.isEditable }
guard textView.shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return true }
doc.storage.replaceCharacters(in: edit.range, with: NSAttributedString(string: edit.replacement, attributes: textView.typingAttributes))
textView.didChangeText()
textView.setSelectedRange(edit.selection)
textView.scrollRangeToVisible(edit.selection)
return true
}
func gutterClick(atWindowPoint point: NSPoint, extend: Bool) {
guard let doc = document else { return }
focusTextView()
let local = textView.convert(point, from: nil)
let line = doc.lineIndex.line(containing: textView.characterIndexForInsertion(at: NSPoint(x: 0, y: local.y)))
let start = doc.lineIndex.start(ofLine: line)
let end = doc.lineIndex.end(ofLine: line)
var range = NSRange(location: start, length: end - start)
if extend {
range = NSUnionRange(range, textView.selectedRange())
}
textView.setSelectedRange(range)
}
/// Underlines the class names while ⌘ is held, so the affordance shows exactly when a click would work.
func commandKeyChanged(_ down: Bool) {
guard down != symbolsUnderlined, document != nil else { return }
symbolsUnderlined = down
textView.needsDisplay = true
}
func focusTextView() {
if textView.window?.firstResponder !== textView { textView.window?.makeFirstResponder(textView) }
}
private func topLeft(_ point: NSPoint) -> CGPoint {
let height = textView.window?.contentView?.bounds.height ?? 0
return CGPoint(x: point.x, y: height - point.y)
}
}
/// Tells the controller when the visible size changes, so the text view can follow it.
final class CodeScrollView: NSScrollView {
var onTile: () -> Void = {}
override func tile() {
super.tile()
onTile()
}
}
@@ -0,0 +1,21 @@
import AppKit
import SwiftUI
/// SwiftUI face of the AppKit code pane; all the work happens in `CodeEditorController`.
struct CodeEditorView: NSViewRepresentable {
var configuration: CodeEditorConfiguration
var actions: CodeEditorActions
func makeCoordinator() -> CodeEditorController {
CodeEditorController()
}
func makeNSView(context: Context) -> NSScrollView {
context.coordinator.scrollView
}
func updateNSView(_ view: NSScrollView, context: Context) {
context.coordinator.actions = actions
context.coordinator.apply(configuration)
}
}
+225
View File
@@ -0,0 +1,225 @@
import CoreGraphics
import Foundation
import HelderCore
/// Line starts of a text as UTF-16 offsets, the unit NSTextView and the tokens use.
public struct LineIndex: Equatable, Sendable {
/// Offset of the first character of each line; always starts with 0.
public private(set) var starts: [Int]
public private(set) var length: Int
public init(_ text: String) {
var starts = [0]
var offset = 0
for unit in text.utf16 {
offset += 1
if unit == 10 { starts.append(offset) }
}
self.starts = starts
length = offset
}
/// A text ending in a newline has an empty last line, as the editor shows it.
public var lineCount: Int { starts.count }
/// The 1-based line holding a UTF-16 offset; offsets past the end land on the last line.
public func line(containing offset: Int) -> Int {
var low = 0
var high = starts.count - 1
while low < high {
let mid = (low + high + 1) / 2
if starts[mid] <= offset { low = mid } else { high = mid - 1 }
}
return low + 1
}
public func isLineStart(_ offset: Int) -> Bool {
starts[line(containing: offset) - 1] == offset
}
/// Offset of the first character of a 1-based line, clamped to the text.
public func start(ofLine line: Int) -> Int {
starts[min(max(line, 1), starts.count) - 1]
}
/// The 1-based column of an offset within its line.
public func column(of offset: Int) -> Int {
offset - start(ofLine: line(containing: offset)) + 1
}
/// Offset just past a line: the next line's start, or the end of the text for the last line.
public func end(ofLine line: Int) -> Int {
line < starts.count ? starts[line] : length
}
/// Follows one edit without rescanning the whole text: `editedRange` is in the new text,
/// `inserted` is the text now in that range, `delta` the change in length.
public mutating func applyEdit(editedRange: NSRange, delta: Int, inserted: String) {
let location = editedRange.location
let oldEnd = NSMaxRange(editedRange) - delta
var next = Array(starts.prefix { $0 <= location })
var offset = location
for unit in inserted.utf16 {
offset += 1
if unit == 10 { next.append(offset) }
}
next.append(contentsOf: starts.drop { $0 <= oldEnd }.map { $0 + delta })
starts = next
length += delta
}
}
/// How one line of an editor pane is marked.
public struct CodeLineMark: Equatable, Sendable {
public enum Tone: Equatable, Sendable {
/// Teal: what the file holds now.
case added
/// Amber-deep: what it held before.
case removed
}
/// Fill the whole row; false for a gap-only mark.
public var tint: Bool
/// The 2px left rule and the lifted number; nil for a gap-only mark.
public var tone: Tone?
/// A removed run owns no line in Actual, so its amber-deep rule sits on this line's edge.
public var gap: GapEdge?
public init(tint: Bool = false, tone: Tone? = nil, gap: GapEdge? = nil) {
self.tint = tint
self.tone = tone
self.gap = gap
}
}
public enum ChangeMarks {
/// Actual: tinted added lines plus the gap rules of pure deletions, keyed by line number.
public static func actual(_ lines: [ViewLine]) -> [Int: CodeLineMark] {
var marks: [Int: CodeLineMark] = [:]
for line in lines {
guard let no = line.no else { continue }
let added = line.style == .added
guard added || line.gap != nil else { continue }
marks[no] = CodeLineMark(tint: added, tone: added ? .added : nil, gap: line.gap)
}
return marks
}
}
public enum GutterNumbers {
/// The number each visual row shows: a wrapped line numbers only its first row.
public static func labels(rowStarts: [Int], index: LineIndex) -> [Int?] {
rowStarts.map { index.isLineStart($0) ? index.line(containing: $0) : nil }
}
}
public enum DiffOverlayLayout {
public static let rowHeight: CGFloat = 22
public static let topPadding: CGFloat = 6
/// The split row that shows an updated-side line.
public static func rowIndex(forUpdatedLine line: Int, in rows: [SplitRow]) -> Int? {
rows.firstIndex { $0.right?.no == line }
}
/// The scroll offset that puts a row in the middle of the viewport, as near as the file permits.
public static func centredOffset(rowIndex: Int, rowCount: Int, viewportHeight: CGFloat,
rowHeight: CGFloat = rowHeight, topPadding: CGFloat = topPadding) -> CGFloat {
let contentHeight = topPadding * 2 + CGFloat(rowCount) * rowHeight
let rowTop = topPadding + CGFloat(rowIndex) * rowHeight
let wanted = rowTop - (viewportHeight - rowHeight) / 2
return min(max(0, wanted), max(0, contentHeight - viewportHeight))
}
}
/// A replacement the Tab key makes, plus where the selection goes afterwards.
public struct TextEdit: Equatable, Sendable {
public var range: NSRange
public var replacement: String
public var selection: NSRange
}
public enum Indentation {
/// Tab inserts spaces on one line; over several lines, or with Shift, every touched line
/// moves by one level. A selection that stops at column 0 leaves that last line alone.
public static func edit(_ text: String, selection: NSRange, tabSize: Int, outdent: Bool) -> TextEdit? {
let ns = text as NSString
let size = max(1, tabSize)
let pad = String(repeating: " ", count: size)
let from = selection.location
let to = NSMaxRange(selection)
if !outdent && !ns.substring(with: selection).contains("\n") {
return TextEdit(range: selection, replacement: pad, selection: NSRange(location: from + size, length: 0))
}
let previousNewline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: from))
let start = previousNewline.location == NSNotFound ? 0 : previousNewline.location + 1
let tail = to > from && to > 0 && ns.character(at: to - 1) == 10 ? to - 1 : to
let newline = ns.range(of: "\n", options: [], range: NSRange(location: tail, length: ns.length - tail))
let end = newline.location == NSNotFound ? ns.length : newline.location
let block = ns.substring(with: NSRange(location: start, length: end - start))
let lines = block.components(separatedBy: "\n")
func cut(_ line: String) -> Int {
guard outdent else { return 0 }
if line.hasPrefix("\t") { return 1 }
return min(size, line.prefix { $0 == " " }.count)
}
let next = lines.map { outdent ? String($0.dropFirst(cut($0))) : pad + $0 }.joined(separator: "\n")
if next == block { return nil }
let head = outdent ? -cut(lines[0]) : size
let total = outdent ? -lines.reduce(0) { $0 + cut($1) } : size * lines.count
let newFrom = max(start, from + head)
let newTo = max(start, to + total)
return TextEdit(range: NSRange(location: start, length: end - start), replacement: next,
selection: NSRange(location: newFrom, length: max(0, newTo - newFrom)))
}
}
public enum EditorReference {
/// The lines a text selection touches, as the reference names them.
public static func lines(of range: NSRange, in index: LineIndex) -> ClosedRange<Int> {
let first = index.line(containing: range.location)
let last = index.line(containing: NSMaxRange(range))
return first...max(first, last)
}
/// `path:start-end` for a selection, else `path:line` for the clicked line.
public static func make(path: String, selectedLines: ClosedRange<Int>?, clickedLine: Int) -> AgentReference {
if let lines = selectedLines { return AgentReference(path: path, lines: lines) }
return AgentReference(path: path, startLine: max(1, clickedLine))
}
}
public enum HighlightDiff {
/// The part of the new text whose colours may be wrong after an edit: the edited range plus
/// every token that differs, so a keystroke repaints a line, not the file. An opened block
/// comment still repaints everything after it, because every later token differs.
public static func repaintRange(old: [Token], new: [Token], edited: NSRange, delta: Int, newLength: Int) -> NSRange {
let editedEndOld = NSMaxRange(edited) - delta
var prefix = 0
while prefix < old.count, prefix < new.count, old[prefix] == new[prefix],
old[prefix].location + old[prefix].length <= edited.location {
prefix += 1
}
var suffix = 0
while suffix < old.count - prefix, suffix < new.count - prefix {
let o = old[old.count - 1 - suffix]
let n = new[new.count - 1 - suffix]
guard o.location >= editedEndOld, o.location + delta == n.location, o.length == n.length, o.role == n.role else { break }
suffix += 1
}
var start = edited.location
var end = NSMaxRange(edited)
for t in old[prefix..<(old.count - suffix)] {
let tEnd = t.location + t.length
start = min(start, t.location < edited.location ? t.location : t.location + delta)
end = max(end, tEnd > editedEndOld ? tEnd + delta : min(tEnd, edited.location))
}
for t in new[prefix..<(new.count - suffix)] {
start = min(start, t.location)
end = max(end, t.location + t.length)
}
start = max(0, min(start, newLength))
end = max(start, min(end, newLength))
return NSRange(location: start, length: end - start)
}
}
+133
View File
@@ -0,0 +1,133 @@
import AppKit
/// The NSTextView that holds the code. It only forwards gestures; `CodeEditorController` decides.
final class CodeTextView: NSTextView {
weak var controller: CodeEditorController?
/// Pointer travel that still counts as a click and not as a text selection.
private static let dragSlop: CGFloat = 4
private var pointerTracking: NSTrackingArea?
override func drawBackground(in rect: NSRect) {
super.drawBackground(in: rect)
controller?.drawRowBackgrounds(in: rect)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
controller?.drawSymbolUnderlines(in: dirtyRect)
}
override func mouseDown(with event: NSEvent) {
if event.modifierFlags.contains(.command), controller?.followSymbol(at: event) == true { return }
let hadSelection = selectedRange().length > 0
let down = event.locationInWindow
super.mouseDown(with: event)
guard event.clickCount == 1, !hadSelection, selectedRange().length == 0,
event.modifierFlags.isDisjoint(with: [.shift, .option, .command, .control]),
let up = window?.mouseLocationOutsideOfEventStream,
abs(up.x - down.x) + abs(up.y - down.y) <= Self.dragSlop else { return }
controller?.plainClick(atWindowPoint: down)
}
override func menu(for event: NSEvent) -> NSMenu? {
controller?.showContextMenu(for: event)
return nil
}
override func keyDown(with event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting([.numericPad, .function])
if event.keyCode == 124, flags == .command, controller?.passOnSelection() == true { return }
super.keyDown(with: event)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard window?.firstResponder === self else { return super.performKeyEquivalent(with: event) }
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
if flags == .command, let key = event.charactersIgnoringModifiers?.lowercased(),
let command = EditorKeyCommand(key: key) {
controller?.run(command)
return true
}
return super.performKeyEquivalent(with: event)
}
override func flagsChanged(with event: NSEvent) {
super.flagsChanged(with: event)
let command = event.modifierFlags.contains(.command)
controller?.commandKeyChanged(command)
if let window { updatePointer(at: window.mouseLocationOutsideOfEventStream, command: command) }
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
guard pointerTracking == nil else { return }
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeInKeyWindow, .inVisibleRect], owner: self)
addTrackingArea(area)
pointerTracking = area
}
override func mouseMoved(with event: NSEvent) {
super.mouseMoved(with: event)
updatePointer(at: event.locationInWindow, command: event.modifierFlags.contains(.command))
}
override func cursorUpdate(with event: NSEvent) {
super.cursorUpdate(with: event)
updatePointer(at: event.locationInWindow, command: event.modifierFlags.contains(.command))
}
/// The pointing hand over a symbol ⌘-click would follow, the I-beam elsewhere in the text.
private func updatePointer(at windowPoint: NSPoint, command: Bool) {
guard visibleRect.contains(convert(windowPoint, from: nil)) else { return }
if command, controller?.symbol(atWindowPoint: windowPoint) != nil {
NSCursor.pointingHand.set()
} else {
NSCursor.iBeam.set()
}
}
override func resignFirstResponder() -> Bool {
controller?.commandKeyChanged(false)
return super.resignFirstResponder()
}
override func insertTab(_ sender: Any?) {
if controller?.indent(outdent: false) != true { super.insertTab(sender) }
}
override func insertBacktab(_ sender: Any?) {
if controller?.indent(outdent: true) != true { super.insertBacktab(sender) }
}
}
/// The editor shortcuts the text view answers itself while it has focus.
enum EditorKeyCommand {
case save
case close
case cycleMode
init?(key: String) {
switch key {
case "s": self = .save
case "w": self = .close
case "m": self = .cycleMode
default: return nil
}
}
}
/// The line-number column; a click selects the line, Shift-click extends to it.
final class CodeGutterView: NSRulerView {
weak var controller: CodeEditorController?
override var isFlipped: Bool { true }
override func drawHashMarksAndLabels(in rect: NSRect) {
controller?.drawGutter(in: rect, of: self)
}
override func mouseDown(with event: NSEvent) {
controller?.gutterClick(atWindowPoint: event.locationInWindow, extend: event.modifierFlags.contains(.shift))
}
}
+327
View File
@@ -0,0 +1,327 @@
import AppKit
import HelderCore
import SwiftUI
/// The keys the Diff answers while its canvas holds focus.
enum DiffCanvasKey {
case escape
case up
case down
case enter
init?(keyCode: UInt16) {
switch keyCode {
case 53: self = .escape
case 126: self = .up
case 125: self = .down
case 36, 76: self = .enter
default: return nil
}
}
}
/// Both halves of the side-by-side Diff: one vertical scroll, one shared sideways offset, never wraps.
/// Rows are drawn, not laid out, so a 5k-line diff costs only the rows on screen.
struct DiffCanvas: NSViewRepresentable {
let rows: [SplitRow]
let language: Language?
let knownSymbols: Set<String>
/// Identifies the pair shown; a new key redraws and re-centres.
let key: String
let focusLine: Int?
/// View → Zoom.
let scale: CGFloat
/// The canvas takes keyboard focus back whenever this moves.
let focusRequest: Int
/// Returns false for a key it leaves alone.
let onKey: (DiffCanvasKey) -> Bool
/// The clicked side's line number, and the click in top-left window coordinates.
let contextMenu: (_ line: Int, _ anchor: CGPoint) -> Void
func makeNSView(context: Context) -> DiffScrollView {
let scroll = DiffScrollView()
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
scroll.drawsBackground = true
scroll.backgroundColor = EditorColors.background
scroll.borderType = .noBorder
scroll.documentView = scroll.canvas
return scroll
}
func updateNSView(_ scroll: DiffScrollView, context: Context) {
let canvas = scroll.canvas
canvas.onKey = onKey
canvas.contextMenu = contextMenu
if canvas.focusRequest != focusRequest {
canvas.focusRequest = focusRequest
scroll.window?.makeFirstResponder(canvas)
}
let loadKey = "\(key)|\(scale)"
guard canvas.key != loadKey else { return }
canvas.key = loadKey
canvas.load(rows: rows, language: language, knownSymbols: knownSymbols, scale: scale)
scroll.centre(onUpdatedLine: focusLine)
}
}
final class DiffScrollView: NSScrollView {
let canvas = DiffCanvasView()
/// Sideways gestures move both halves together; the view itself only scrolls vertically.
override func scrollWheel(with event: NSEvent) {
if abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) {
canvas.shift(by: -event.scrollingDeltaX)
} else {
super.scrollWheel(with: event)
}
}
override func layout() {
super.layout()
canvas.frame.size.width = contentSize.width
canvas.frame.size.height = max(canvas.contentHeight, contentSize.height)
if let line = pendingFocus, contentSize.height > 0 {
pendingFocus = nil
centre(onUpdatedLine: line)
}
}
private var pendingFocus: Int?
/// Puts the clicked line in the middle of the window, as near as the file permits.
func centre(onUpdatedLine line: Int?) {
window?.makeFirstResponder(canvas)
guard let line else {
contentView.scroll(to: .zero)
reflectScrolledClipView(contentView)
return
}
guard contentSize.height > 0 else {
pendingFocus = line
needsLayout = true
return
}
guard let index = DiffOverlayLayout.rowIndex(forUpdatedLine: line, in: canvas.rows) else { return }
let y = DiffOverlayLayout.centredOffset(rowIndex: index, rowCount: canvas.rows.count, viewportHeight: contentSize.height,
rowHeight: canvas.rowHeight)
contentView.scroll(to: NSPoint(x: 0, y: y))
reflectScrolledClipView(contentView)
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
window?.makeFirstResponder(canvas)
}
}
final class DiffCanvasView: NSView {
enum Side { case left, right }
/// Whole lines dragged over on one side, as row indices; the other side stays out of it.
struct LineSelection: Equatable {
var side: Side
var anchor: Int
var head: Int
var rows: ClosedRange<Int> { min(anchor, head)...max(anchor, head) }
}
var key = ""
var focusRequest = 0
var onKey: (DiffCanvasKey) -> Bool = { _ in false }
var contextMenu: (Int, CGPoint) -> Void = { _, _ in }
private(set) var rows: [SplitRow] = []
private var language: Language?
private var knownSymbols: Set<String> = []
private var cache: [Int: NSAttributedString] = [:]
private var offsetX: CGFloat = 0
private var widestText: CGFloat = 0
private(set) var selection: LineSelection?
private var dragStart: (side: Side, row: Int)?
private(set) var rowHeight = DiffOverlayLayout.rowHeight
private var font = EditorFonts.code
private let top = DiffOverlayLayout.topPadding
private let gutter = Metrics.diffOverlayGutter
private let codeInset: CGFloat = 0
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { true }
var contentHeight: CGFloat { top * 2 + CGFloat(rows.count) * rowHeight }
func load(rows: [SplitRow], language: Language?, knownSymbols: Set<String>, scale: CGFloat) {
rowHeight = (DiffOverlayLayout.rowHeight * scale).rounded()
font = EditorFonts.code(scale: scale)
self.rows = rows
self.language = language
self.knownSymbols = knownSymbols
cache.removeAll()
offsetX = 0
selection = nil
let longest = rows.lazy.map { max($0.left?.text.utf16.count ?? 0, $0.right?.text.utf16.count ?? 0) }.max() ?? 0
widestText = CGFloat(longest) * (" " as NSString).size(withAttributes: [.font: font]).width + 24
superview?.superview?.needsLayout = true
frame.size.height = contentHeight
needsDisplay = true
}
func shift(by delta: CGFloat) {
let room = bounds.width / 2 - gutter - codeInset
offsetX = min(max(0, offsetX + delta), max(0, widestText - room))
needsDisplay = true
}
override func keyDown(with event: NSEvent) {
if let key = DiffCanvasKey(keyCode: event.keyCode), onKey(key) { return }
super.keyDown(with: event)
}
override func cancelOperation(_ sender: Any?) {
_ = onKey(.escape)
}
// MARK: Selection
var hasSelection: Bool { selection != nil }
/// The selected lines of one side; rows where that side has no line are skipped.
var selectedText: String? {
guard let selection else { return nil }
let lines = selection.rows.compactMap { index -> String? in
guard rows.indices.contains(index) else { return nil }
return (selection.side == .left ? rows[index].left : rows[index].right)?.text
}
return lines.isEmpty ? nil : lines.joined(separator: "\n")
}
@objc func copy(_ sender: Any?) {
guard let text = selectedText else { return }
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
}
/// ⌘A: the side that holds the selection, else the Original side.
override func selectAll(_ sender: Any?) {
guard !rows.isEmpty else { return }
selection = LineSelection(side: selection?.side ?? .left, anchor: 0, head: rows.count - 1)
needsDisplay = true
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard window?.firstResponder === self,
event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command else { return super.performKeyEquivalent(with: event) }
switch event.charactersIgnoringModifiers?.lowercased() {
case "c" where hasSelection:
copy(nil)
return true
case "a":
selectAll(nil)
return true
default:
return super.performKeyEquivalent(with: event)
}
}
private func hit(_ event: NSEvent) -> (side: Side, row: Int) {
let point = convert(event.locationInWindow, from: nil)
let row = Int(((point.y - top) / rowHeight).rounded(.down))
return (point.x < bounds.width / 2 ? .left : .right, min(max(row, 0), max(rows.count - 1, 0)))
}
override func mouseDown(with event: NSEvent) {
window?.makeFirstResponder(self)
dragStart = hit(event)
if selection != nil {
selection = nil
needsDisplay = true
}
}
override func mouseDragged(with event: NSEvent) {
guard let start = dragStart, !rows.isEmpty else { return }
autoscroll(with: event)
let next = LineSelection(side: start.side, anchor: start.row, head: hit(event).row)
guard next != selection else { return }
selection = next
needsDisplay = true
}
override func mouseUp(with event: NSEvent) {
dragStart = nil
}
/// An empty half of a row refers to line 1.
override func rightMouseDown(with event: NSEvent) {
let point = convert(event.locationInWindow, from: nil)
let index = Int(((point.y - top) / rowHeight).rounded(.down))
let row = rows.indices.contains(index) ? rows[index] : nil
let side = point.x < bounds.width / 2 ? row?.left : row?.right
let height = window?.contentView?.bounds.height ?? 0
contextMenu(side?.no ?? 1, CGPoint(x: event.locationInWindow.x, y: height - event.locationInWindow.y))
}
override func draw(_ dirtyRect: NSRect) {
EditorColors.background.setFill()
dirtyRect.fill()
guard !rows.isEmpty else { return }
let half = (bounds.width / 2).rounded(.down)
let first = max(0, Int((dirtyRect.minY - top) / rowHeight))
let last = min(rows.count - 1, Int((dirtyRect.maxY - top) / rowHeight))
if first <= last {
for index in first...last {
let y = top + CGFloat(index) * rowHeight
draw(side: rows[index].left, index: index * 2, x: 0, width: half, y: y, tone: .removed)
draw(side: rows[index].right, index: index * 2 + 1, x: half + 1, width: bounds.width - half - 1, y: y, tone: .added)
}
}
EditorColors.raised.setFill()
NSRect(x: half, y: dirtyRect.minY, width: Metrics.hairline, height: dirtyRect.height).fill()
}
private func draw(side line: SideLine?, index: Int, x: CGFloat, width: CGFloat, y: CGFloat, tone: CodeLineMark.Tone) {
guard let line else { return }
let changed = line.mark != nil
let row = NSRect(x: x, y: y, width: width, height: rowHeight)
if let selection, selection.side == (tone == .removed ? .left : .right), selection.rows.contains(index / 2) {
EditorColors.selection.setFill()
row.fill()
}
if changed {
EditorColors.fill(tone).setFill()
row.fill()
EditorColors.tone(tone).setFill()
NSRect(x: x, y: y, width: Metrics.accentRule, height: rowHeight).fill()
}
let textTop = y + (rowHeight - (font.ascender - font.descender + font.leading)) / 2
let number = String(line.no) as NSString
let numberAttributes: [NSAttributedString.Key: Any] = [
.font: font, .foregroundColor: changed ? EditorColors.tone(tone) : EditorColors.lineNumber,
]
let numberWidth = number.size(withAttributes: numberAttributes).width
number.draw(at: NSPoint(x: x + gutter - 14 - numberWidth, y: textTop), withAttributes: numberAttributes)
let codeX = x + gutter + codeInset
NSGraphicsContext.saveGraphicsState()
NSRect(x: codeX, y: y, width: max(0, x + width - codeX), height: rowHeight).clip()
text(for: line, index: index).draw(at: NSPoint(x: codeX - offsetX, y: textTop))
NSGraphicsContext.restoreGraphicsState()
}
private func text(for line: SideLine, index: Int) -> NSAttributedString {
if let cached = cache[index] { return cached }
let attributed = NSMutableAttributedString(string: line.text, attributes: [
.font: font, .foregroundColor: EditorColors.syntax(.plain),
])
if let language {
let length = attributed.length
for token in SyntaxHighlighter.lineTokens(for: line.text, language: language, knownSymbols: knownSymbols)
where token.role != .plain {
let range = NSIntersectionRange(NSRange(location: token.location, length: token.length), NSRange(location: 0, length: length))
attributed.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: range)
}
}
cache[index] = attributed
return attributed
}
}
@@ -0,0 +1,258 @@
import HelderCore
import SwiftUI
/// The full-screen side-by-side Diff: Original left, Actual right, over the whole window.
/// Its right-click menu and pass-on prompt are drawn inside it, since a second overlay would replace it.
struct DiffOverlayView: View {
let editor: EditorStore
/// Full screen hides the traffic lights, so the header reclaims their inset.
let isFullScreen: Bool
/// View → Zoom.
let scale: CGFloat
let request: DiffOverlayRequest
/// Every menu action except pass-on, which stays inside the Diff.
let perform: (ContextAction) -> Void
/// The composed text and the reference for the toast.
let passToAgent: (String, String) -> Void
@State private var menu: ContextMenuRequest?
@State private var highlighted: Int?
@State private var passOn: PassOnRequest?
@State private var canvasFocus = 0
var body: some View {
GeometryReader { geometry in
let origin = geometry.frame(in: .global).origin
ZStack(alignment: .topLeading) {
content
if let menu {
DiffContextMenu(request: menu, origin: origin, size: geometry.size, highlighted: $highlighted,
choose: choose, close: closeMenu)
}
if let passOn {
PassOnPanel(request: local(passOn, origin: origin),
insert: { text in
passToAgent(text, passOn.reference)
closePassOn()
},
cancel: closePassOn)
}
}
}
.onExitCommand(perform: escape)
.onChange(of: menu != nil || passOn != nil, initial: true) { _, busy in editor.diffOverlayBusy = busy }
.onDisappear { editor.diffOverlayBusy = false }
}
private var content: some View {
let diff = editor.overlayDiff(for: request.path, side: request.side)
return VStack(spacing: 0) {
header(diff)
HStack(spacing: 0) {
paneLabel("Original", note: "before", color: Palette.text4)
Rectangle().fill(Palette.raised).frame(width: Metrics.hairline)
paneLabel("Actual", note: "after", color: Palette.amber)
}
.frame(height: Metrics.panelHeader)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
if let diff, diff.isTooBig {
Text("Too big.")
.typeRole(Typography.body)
.foregroundStyle(Palette.text4)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if let diff {
DiffCanvas(rows: diff.split, language: FileType.language(for: request.path), knownSymbols: editor.knownSymbols,
key: key(diff), focusLine: request.focusLine, scale: scale, focusRequest: canvasFocus,
onKey: handle, contextMenu: openMenu)
} else {
Text("— No changes to compare.")
.typeRole(Typography.body)
.foregroundStyle(Palette.text3)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.background(Palette.editor)
}
// MARK: Menu and prompt
private func openMenu(line: Int, anchor: CGPoint) {
guard passOn == nil else { return }
let reference = AgentReference(path: request.path, startLine: line)
let next = editor.contextMenuRequest(reference: reference, code: nil, anchor: anchor)
menu = next
highlighted = MenuCursor.first(in: next.entries)
}
private func choose(_ action: ContextAction) {
let anchor = menu?.anchor ?? .zero
menu = nil
if case let .passOnReference(reference, code) = action {
passOn = PassOnRequest(reference: reference, code: code, anchor: anchor)
} else {
perform(action)
}
}
private func closeMenu() {
menu = nil
}
private func closePassOn() {
passOn = nil
canvasFocus += 1
}
/// Esc closes the innermost layer first: the menu, then the prompt, then the Diff itself.
private func escape() {
if menu != nil {
closeMenu()
} else if passOn != nil {
closePassOn()
} else {
editor.collapseDiff()
}
}
private func handle(_ key: DiffCanvasKey) -> Bool {
if key == .escape {
escape()
return true
}
guard let menu else { return false }
switch key {
case .up: highlighted = MenuCursor.step(highlighted ?? -1, by: -1, in: menu.entries)
case .down: highlighted = MenuCursor.step(highlighted ?? -1, by: 1, in: menu.entries)
case .enter:
if let highlighted, case let .action(action, _) = menu.entries[highlighted] { choose(action) }
case .escape: break
}
return true
}
/// The prompt lays itself out in this view's space, not the window's.
private func local(_ request: PassOnRequest, origin: CGPoint) -> PassOnRequest {
var moved = request
moved.anchor = CGPoint(x: request.anchor.x - origin.x, y: request.anchor.y - origin.y)
return moved
}
private func key(_ diff: Diff) -> String {
"\(request.path)|\(request.side?.rawValue ?? "file")|\(request.focusLine ?? 0)|\(diff.added).\(diff.removed).\(diff.split.count).\(diff.updated.utf8.count)"
}
private func header(_ diff: Diff?) -> some View {
HStack(spacing: 14) {
TypeBadge(path: request.path)
Text(request.path)
.typeRole(TypeRole(.monoMedium, 12))
.foregroundStyle(Palette.text1)
.lineLimit(1)
.truncationMode(.head)
if let diff {
let status = FileChangeStatus(diff)
Text(status.rawValue).typeRole(Typography.panelLabel).foregroundStyle(color(status))
if diff.added > 0 { Text("+\(diff.added)").typeRole(TypeRole(.monoMedium, 12)).foregroundStyle(Palette.addedText) }
if diff.removed > 0 { Text("\u{2212}\(diff.removed)").typeRole(TypeRole(.monoMedium, 12)).foregroundStyle(Palette.removedText) }
}
if editor.hasBothSides(request.path) {
Text(request.side == .unstaged ? "staged → actual" : "HEAD → staged")
.typeRole(Typography.meta)
.foregroundStyle(Palette.text4)
}
Spacer(minLength: 0)
CollapseButton { editor.collapseDiff() }
}
.padding(.leading, isFullScreen ? 16 : Metrics.trafficLightInset)
.padding(.trailing, 16)
.frame(height: 42)
.background(Palette.panel)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
private func paneLabel(_ title: String, note: String, color: Color) -> some View {
HStack(spacing: 10) {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(color)
Text(note).typeRole(Typography.meta).foregroundStyle(Palette.text5)
Spacer(minLength: 0)
}
.padding(.horizontal, 16)
.frame(maxWidth: .infinity)
}
private func color(_ status: FileChangeStatus) -> Color {
switch status {
case .added: Palette.addedText
case .deleted: Palette.removedText
case .modified: Palette.text4
}
}
}
/// The editor menu (Pass on reference, Copy reference) at the pointer, over the Diff.
private struct DiffContextMenu: View {
let request: ContextMenuRequest
/// The Diff's top-left corner in window coordinates.
let origin: CGPoint
let size: CGSize
@Binding var highlighted: Int?
let choose: (ContextAction) -> Void
let close: () -> Void
var body: some View {
ZStack(alignment: .topLeading) {
Color.clear
.contentShape(Rectangle())
.onTapGesture(perform: close)
ContextMenuPanel {
ContextMenuHeader(request.header)
ForEach(Array(request.entries.enumerated()), id: \.offset) { index, entry in
switch entry {
case .separator:
ContextMenuSeparator()
case let .action(action, label):
ContextMenuRow(label, systemImage: ContextMenuOverlay.symbol(for: action),
iconTint: ContextMenuOverlay.tint(for: action).color,
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { choose(action) }
}
}
}
.fixedSize()
.offset(position)
}
}
/// Keeps the menu inside the Diff.
private var position: CGSize {
let height = CGFloat(request.entries.count) * Metrics.contextMenuItem + 60
let x = min(request.anchor.x - origin.x, size.width - Metrics.contextMenuWidth - 8)
let y = min(request.anchor.y - origin.y, size.height - height)
return CGSize(width: max(8, x), height: max(8, y))
}
}
private struct CollapseButton: View {
let action: () -> Void
@State private var hovering = false
var body: some View {
HStack(spacing: 8) {
Image(systemName: "arrow.down.right.and.arrow.up.left")
.font(.system(size: 11, weight: .regular))
Text("Collapse").typeRole(Typography.toolbarLabel)
Keycap("Esc")
}
.foregroundStyle(hovering ? Palette.text1 : Palette.text3)
.padding(.leading, 9)
.padding(.trailing, 4)
.padding(.vertical, 3)
.background(hovering ? Palette.hover : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onTapGesture(perform: action)
.onHover { hovering = $0 }
.animation(Metrics.colorTransition, value: hovering)
}
}
+54
View File
@@ -0,0 +1,54 @@
import HelderCore
import SwiftUI
/// The bar above the code: which file is open, whether it is unsaved or changed, and its Preview and Diff buttons.
/// With no file open it stays as an empty bar, so the column's top edge lines up with its neighbours.
struct EditorBar: View {
var editor: EditorStore?
var presentation: EditorPresentation?
var body: some View {
HStack(spacing: 10) {
if let editor, let presentation {
content(editor, presentation)
}
}
.padding(.horizontal, 14)
.frame(height: Metrics.editorBar)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.editor)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
@ViewBuilder
private func content(_ editor: EditorStore, _ presentation: EditorPresentation) -> some View {
let path = presentation.path
TypeBadge(path: path)
Text(path)
.typeRole(Typography.path)
.foregroundStyle(Palette.text2)
.lineLimit(1)
.truncationMode(.head)
.help(path)
if editor.isDirty(path) {
Circle().fill(Palette.text2).frame(width: 7, height: 7)
.accessibilityLabel("Unsaved changes")
}
if let diff = editor.diff(for: path), presentation.hasDiff {
HStack(spacing: 8) {
if diff.added > 0 { Text("+\(diff.added)").foregroundStyle(Palette.addedText) }
if diff.removed > 0 { Text("\u{2212}\(diff.removed)").foregroundStyle(Palette.removedText) }
}
.typeRole(TypeRole(.monoMedium, 12))
}
Spacer(minLength: 0)
ForEach(presentation.barButtons, id: \.self) { button in
switch button {
case .preview:
SegmentButton("Preview", isOn: presentation.mode == .preview) { editor.togglePreview() }
case .diff:
SegmentButton("Diff", isOn: presentation.mode == .diff) { editor.setMode(.diff, for: path) }
}
}
}
}
@@ -0,0 +1,80 @@
import AppKit
import HelderCore
/// AppKit twins of the Palette tokens, for the NSTextView and the diff canvas.
enum EditorColors {
static let background = NSColor(hex: 0x101720)
static let raised = NSColor(hex: 0x232C39)
static let lineNumber = NSColor(hex: 0x3A424C)
/// The caret line's number, one step up from the rest.
static let lineNumberActive = NSColor(hex: 0xBAC0C0)
static let amber = NSColor(hex: 0xE8913A)
static let selection = NSColor(hex: 0xE8913A, alpha: 0.22)
static let flash = NSColor(hex: 0xE8913A, alpha: 0.10)
static let activeLine = NSColor(white: 1, alpha: 0.03)
static let addedText = NSColor(hex: 0x8FBFB4)
static let addedFill = NSColor(hex: 0x8FBFB4, alpha: 0.12)
static let removedText = NSColor(hex: 0xC4741F)
static let removedFill = NSColor(hex: 0xC4741F, alpha: 0.14)
static func syntax(_ role: TokenRole) -> NSColor {
switch role {
case .plain, .symbol: NSColor(hex: 0xE4E7E6)
case .variable: NSColor(hex: 0xBAC0C0)
case .comment: NSColor(hex: 0x6C7783)
case .keyword: NSColor(hex: 0xC3A6CE)
case .string: NSColor(hex: 0x8FBFB4)
case .number: NSColor(hex: 0xF0B476)
}
}
static func tone(_ tone: CodeLineMark.Tone) -> NSColor {
tone == .added ? addedText : removedText
}
static func fill(_ tone: CodeLineMark.Tone) -> NSColor {
tone == .added ? addedFill : removedFill
}
}
/// Code text at a View → Zoom scale; 1 is actual size.
enum EditorFonts {
/// 13pt Plex Mono 400: code stays flat, never bold or italic.
static let code: NSFont = Typography.code.nsFont
static let topInset: CGFloat = 10
/// Room under the last line, so it never sits on the pane's bottom edge.
static let bottomInset: CGFloat = 40
static let flashDuration: TimeInterval = 1
static func code(scale: CGFloat) -> NSFont {
scale == 1 ? code : NSFont(descriptor: code.fontDescriptor, size: code.pointSize * scale) ?? code
}
static func lineHeight(scale: CGFloat) -> CGFloat { (20 * scale).rounded() }
/// Baseline inside the row that centres the glyphs vertically.
static func baseline(scale: CGFloat) -> CGFloat {
let font = code(scale: scale)
return (lineHeight(scale: scale) - (font.ascender - font.descender)) / 2 + font.ascender
}
/// Fixed rows with the tab width of `tabSize` spaces.
static func paragraphStyle(tabSize: Int, font: NSFont, scale: CGFloat = 1) -> NSParagraphStyle {
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight(scale: scale)
style.maximumLineHeight = lineHeight(scale: scale)
style.tabStops = []
let space = (" " as NSString).size(withAttributes: [.font: font]).width
style.defaultTabInterval = space * CGFloat(max(1, tabSize))
return style
}
static func baseAttributes(tabSize: Int, scale: CGFloat = 1) -> [NSAttributedString.Key: Any] {
let font = code(scale: scale)
return [
.font: font,
.foregroundColor: EditorColors.syntax(.plain),
.paragraphStyle: paragraphStyle(tabSize: tabSize, font: font, scale: scale),
]
}
}
@@ -0,0 +1,99 @@
import HelderCore
import SwiftUI
/// Column C: the bar and the pane for the open file.
public struct EditorColumn: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
Group {
if let editor = model.editor {
EditorWorkspace(model: model, editor: editor)
} else {
VStack(spacing: 0) {
EditorBar()
EditorEmptyState()
}
}
}
.background(Palette.editor)
}
}
private struct EditorWorkspace: View {
let model: WorkspaceModel
let editor: EditorStore
var body: some View {
VStack(spacing: 0) {
if let path = editor.activePath {
let presentation = editor.presentation(for: path)
EditorBar(editor: editor, presentation: presentation)
EditorPane(editor: editor, presentation: presentation, fontScale: model.layout.textScale)
} else {
EditorBar()
EditorEmptyState()
}
}
.overlay { TooBigFlash(notice: editor.tooBig) }
}
}
/// What the column shows with no file open: only what works without one.
struct EditorEmptyState: View {
private let keys: [(String, String)] = [
("Open folder", "⌘O"), ("Recent projects", "⇧⌘O"), ("Search files & content", "⌘F"), ("Project note", "⌘N"),
]
var body: some View {
VStack(spacing: 18) {
Text("No file open")
.typeRole(Typography.body)
.foregroundStyle(Palette.text4)
VStack(spacing: 6) {
ForEach(keys, id: \.0) { label, key in
HStack {
Text(label).typeRole(Typography.row).foregroundStyle(Palette.text2)
Spacer(minLength: 14)
Keycap(key)
}
.frame(width: 260)
.padding(.vertical, 2)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
}
}
/// "Too big." for 1.6 seconds when a file like `composer.lock` is refused.
private struct TooBigFlash: View {
let notice: TooBigNotice?
@State private var visible: UUID?
var body: some View {
ZStack {
if let notice, visible == notice.id {
Text("Too big.")
.typeRole(Typography.path)
.foregroundStyle(Palette.amber)
.padding(.horizontal, 16)
.padding(.vertical, 10)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: 4))
.overlay(RoundedRectangle(cornerRadius: 4).stroke(Palette.raised, lineWidth: Metrics.hairline))
}
}
.allowsHitTesting(false)
.task(id: notice?.id) {
guard let id = notice?.id else { return }
visible = id
try? await Task.sleep(for: .milliseconds(1600))
if visible == id { visible = nil }
}
}
}
@@ -0,0 +1,42 @@
import HelderCore
import SwiftUI
/// The overlays the editor draws: the full-screen Diff, the pass-on prompt and the symbol popup.
/// `OverlayHost` shows this view whenever `handles` is true for the current overlay.
public struct EditorOverlayContent: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public static func handles(_ overlay: Overlay) -> Bool {
switch overlay {
case .diff, .passOn, .symbol: true
default: false
}
}
public var body: some View {
switch model.overlay.current {
case let .diff(request):
if let editor = model.editor {
DiffOverlayView(editor: editor, isFullScreen: model.layout.isFullScreen, scale: model.layout.textScale, request: request,
perform: { model.perform(.context($0)) },
passToAgent: { text, reference in model.passToAgent(text, toast: reference) })
}
case let .passOn(request):
PassOnPanel(request: request,
insert: { model.perform(.passToAgent(text: $0, reference: request.reference)) },
cancel: { model.perform(.dismissOverlay) })
case let .symbol(name):
if let editor = model.editor {
SymbolPopupView(editor: editor, name: name,
dismiss: { model.perform(.dismissOverlay) },
openAt: { path, line in model.perform(.open(path, OpenOptions(line: line))) })
}
default:
EmptyView()
}
}
}
+184
View File
@@ -0,0 +1,184 @@
import AppKit
import HelderCore
import SwiftUI
/// The pane under the bar: code, Markdown preview, image, or a placeholder.
struct EditorPane: View {
let editor: EditorStore
let presentation: EditorPresentation
/// View → Zoom.
var fontScale: CGFloat = 1
var body: some View {
let path = presentation.path
let showsCode = presentation.kind == .text && presentation.placeholder == nil && presentation.paneMode != .preview
ZStack {
// Kept alive while hidden, so a trip to Preview keeps each file's undo history and colours.
if presentation.kind == .text {
CodeEditorView(configuration: configuration(path, isShown: showsCode), actions: actions)
.opacity(showsCode ? 1 : 0)
.allowsHitTesting(showsCode)
}
if presentation.kind == .image {
ImagePreview(data: editor.image(for: path), failed: editor.isUnreadableImage(path), name: PathUtils.basename(path))
.overlay(RightClickCatcher { fileMenu(path, at: $0) })
} else if let placeholder = presentation.placeholder {
EditorPlaceholderView(placeholder: placeholder)
.background(Palette.editor)
} else if presentation.paneMode == .preview {
MarkdownPreviewView(editor: editor, path: path, text: editor.text(for: path))
.overlay(RightClickCatcher { fileMenu(path, at: $0) })
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.editor)
}
/// Views without lines refer to the file's first line.
private func fileMenu(_ path: String, at anchor: CGPoint) {
let request = editor.contextMenuRequest(reference: AgentReference(path: path, startLine: 1), code: nil, anchor: anchor)
editor.presentOverlay?(.contextMenu(request))
}
private func configuration(_ path: String, isShown: Bool) -> CodeEditorConfiguration {
let diff = editor.diff(for: path)
let wrap: Bool = switch editor.editorConfig.wordWrap {
case .on: true
case .off: false
case .markdown: presentation.isMarkdown
}
let marked = presentation.paneMode == .actual ? diff : nil
return CodeEditorConfiguration(
documentID: path, path: path, text: editor.text(for: path), revision: editor.revision(for: path),
language: FileType.language(for: path), isEditable: presentation.isEditable, wrap: wrap,
tabSize: editor.editorConfig.tabSize,
marksKey: marked.map { "actual:" + Self.stamp($0) } ?? "none",
makeMarks: { marked.map { ChangeMarks.actual(DiffViews.actual($0)) } ?? [:] },
opensDiffOnClick: presentation.opensDiffOnClick, knownSymbols: editor.knownSymbols,
symbolsVersion: editor.knownSymbolsVersion, flash: editor.flash,
focusRequest: editor.textFocusRequest, selectAllRequest: editor.selectAllRequest, fontScale: fontScale,
isShown: isShown)
}
/// Cheap identity of a diff: counts and byte lengths, never a full comparison.
private static func stamp(_ diff: Diff) -> String {
"\(diff.added).\(diff.removed).\(diff.rows.count).\(diff.original.utf8.count).\(diff.updated.utf8.count)"
}
private var actions: CodeEditorActions {
let editor = editor
return CodeEditorActions(
edited: { editor.edit($0) },
cursorMoved: { editor.updateCursor(line: $0, column: $1) },
selectionChanged: { editor.updateSelection(lines: $0, code: $1) },
markedLineClicked: { editor.openDiff(atLine: $0) },
contextMenu: { reference, code, anchor in
editor.presentOverlay?(.contextMenu(editor.contextMenuRequest(reference: reference, code: code, anchor: anchor)))
},
symbolClicked: { editor.lookupSymbol($0) },
passOnSelection: { anchor in
guard let request = editor.passOnSelectionRequest(anchor: anchor) else { return false }
editor.presentOverlay?(.passOn(request))
return true
},
command: { command in
switch command {
case .save: Task { try? await editor.save() }
case .close: Task { await editor.requestCloseActive() }
case .cycleMode: editor.togglePreview()
}
})
}
}
/// A short line in place of the code, with a note under it.
struct EditorPlaceholderView: View {
let placeholder: EditorPlaceholder
var body: some View {
VStack(spacing: 10) {
Text(placeholder.title)
.typeRole(Typography.body)
.foregroundStyle(color)
if let note = placeholder.note {
Text(note).typeRole(Typography.path).foregroundStyle(Palette.text4)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var color: Color {
switch placeholder {
case .noUpdated: Palette.removedText
case .cannotDisplay: Palette.text4
}
}
}
/// An image file, centred on the editor surface; read-only.
struct ImagePreview: View {
let data: Data?
let failed: Bool
let name: String
var body: some View {
Group {
if let data, let image = NSImage(data: data) {
Image(nsImage: image)
.resizable()
.interpolation(.high)
.aspectRatio(contentMode: .fit)
.background(Checkerboard())
.frame(maxWidth: image.size.width, maxHeight: image.size.height)
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.accessibilityLabel(name)
.padding(24)
} else if failed || data != nil {
Text("Can’t preview this image").typeRole(Typography.body).foregroundStyle(Palette.text4)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// 10pt squares behind an image, so a transparent PNG or SVG reads on the dark ground.
private struct Checkerboard: View {
var body: some View {
Canvas { context, size in
context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(Palette.panel))
let square: CGFloat = 10
for row in 0..<Int((size.height / square).rounded(.up)) {
for column in 0..<Int((size.width / square).rounded(.up)) where (row + column).isMultiple(of: 2) {
context.fill(Path(CGRect(x: CGFloat(column) * square, y: CGFloat(row) * square, width: square, height: square)),
with: .color(Palette.raised))
}
}
}
}
}
/// Takes only right-clicks, so the view under it keeps scrolling, selecting and following links.
struct RightClickCatcher: NSViewRepresentable {
/// Receives the click in top-left window coordinates.
let action: (CGPoint) -> Void
func makeNSView(context: Context) -> CatcherView { CatcherView() }
func updateNSView(_ view: CatcherView, context: Context) {
view.action = action
}
final class CatcherView: NSView {
var action: (CGPoint) -> Void = { _ in }
override func hitTest(_ point: NSPoint) -> NSView? {
NSApp.currentEvent?.type == .rightMouseDown ? super.hitTest(point) : nil
}
override func rightMouseDown(with event: NSEvent) {
let height = window?.contentView?.bounds.height ?? 0
action(CGPoint(x: event.locationInWindow.x, y: height - event.locationInWindow.y))
}
}
}
@@ -0,0 +1,119 @@
import Foundation
import HelderCore
/// How the editor can show a file at all.
public enum EditorFileKind: Equatable, Sendable {
case text
case image
/// Known binary formats: a placeholder, never a text buffer.
case binary
private static let binaryExtensions: Set<String> = [
"pdf", "zip", "gz", "tgz", "tar", "bz2", "xz", "7z", "rar", "jar", "war", "class",
"woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "m4a", "mov", "avi", "wav", "ogg", "webm",
"exe", "dll", "so", "dylib", "a", "o", "bin", "dat", "psd", "sqlite", "sqlite3", "db", "phar",
"heic", "tiff", "tif", "icns", "DS_Store",
]
public static func of(_ path: String) -> EditorFileKind {
if FileType.isImage(path) { return .image }
if PathUtils.basename(path) == ".DS_Store" { return .binary }
return binaryExtensions.contains(FileType.ext(path)) ? .binary : .text
}
}
/// The file-level change, taken from the whole-file diff rather than one git row.
public enum FileChangeStatus: String, Equatable, Sendable {
case added = "Added"
case modified = "Modified"
case deleted = "Deleted"
public init(_ diff: Diff) {
self = diff.isDeletedFile ? .deleted : diff.isAddedFile ? .added : .modified
}
}
/// A one-sentence empty state in place of the code.
public enum EditorPlaceholder: Equatable, Sendable {
/// Actual of a file the change deleted.
case noUpdated
case cannotDisplay
public var title: String {
switch self {
case .noUpdated: "No updated version"
case .cannotDisplay: "This file cannot be displayed"
}
}
public var note: String? {
switch self {
case .noUpdated: "This file was deleted in the change."
case .cannotDisplay: nil
}
}
}
/// A button on the bar above the code.
public enum EditorBarButton: Equatable, Sendable {
/// Toggles the rendered Markdown.
case preview
/// Opens the side-by-side Diff overlay.
case diff
}
/// Everything the column needs to decide what to draw for one file.
public struct EditorPresentation: Equatable, Sendable {
public var path: String
public var kind: EditorFileKind
public var hasDiff: Bool
public var isMarkdown: Bool
/// The requested mode resolved against what the file supports.
public var mode: ViewMode
/// What the pane under the Diff overlay shows: Diff falls back to Actual.
public var paneMode: ViewMode
public var status: FileChangeStatus?
public var placeholder: EditorPlaceholder?
/// A mode carried over from another state (or an unchanged file asked for a diff view)
/// falls back to a view the file has, so nothing renders blank. `isBinary` is what the read
/// found, for a binary file whose extension looks like text.
public init(path: String, requested: ViewMode?, diff: Diff?, defaultMode: ViewMode = .actual, isBinary: Bool = false) {
self.path = path
let byName = EditorFileKind.of(path)
kind = isBinary && byName == .text ? .binary : byName
hasDiff = kind == .text && diff != nil
isMarkdown = FileType.isMarkdown(path)
let wanted = requested ?? (hasDiff ? defaultMode : .code)
if wanted == .preview && isMarkdown {
mode = .preview
} else if hasDiff {
mode = wanted == .diff ? .diff : .actual
} else {
mode = .code
}
paneMode = mode == .diff ? .actual : mode
status = diff.map(FileChangeStatus.init)
if kind == .binary {
placeholder = .cannotDisplay
} else if paneMode == .actual && status == .deleted {
placeholder = .noUpdated
} else {
placeholder = nil
}
}
/// Preview only for Markdown, Diff only for a file with changes.
public var barButtons: [EditorBarButton] {
var buttons: [EditorBarButton] = []
if kind == .text && isMarkdown { buttons.append(.preview) }
if hasDiff { buttons.append(.diff) }
return buttons
}
/// Actual and Code edit the live buffer; Preview is a read-only view.
public var isEditable: Bool { kind == .text && placeholder == nil && (paneMode == .code || paneMode == .actual) }
/// A click on a marked line opens the Diff, except on a new file where every line is marked.
public var opensDiffOnClick: Bool { paneMode == .actual && hasDiff && status != .added }
}
@@ -0,0 +1,354 @@
import AppKit
import HelderCore
import SwiftUI
/// The rendered Markdown document: read-only, derived from the live buffer.
struct MarkdownPreviewView: View {
let editor: EditorStore
let path: String
let text: String
var body: some View {
let blocks = MarkdownParser.parse(text, baseDir: PathUtils.dirname(path))
ScrollView {
MarkdownBlocks(blocks: blocks, editor: editor)
.frame(maxWidth: MarkdownStyle.measure, alignment: .leading)
.padding(EdgeInsets(top: 18, leading: 20, bottom: 48, trailing: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
.background(Palette.editor)
.environment(\.openURL, OpenURLAction { url in open(url) })
}
/// Web links go to the browser; a link to a file in the project opens it in the editor.
private func open(_ url: URL) -> OpenURLAction.Result {
if url.scheme == MarkdownStyle.fileScheme {
let path = String(url.absoluteString.dropFirst(MarkdownStyle.fileScheme.count + 1)).removingPercentEncoding ?? ""
if !path.isEmpty { editor.open(path) }
return .handled
}
guard let scheme = url.scheme?.lowercased(), ["http", "https", "mailto"].contains(scheme) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
}
}
enum MarkdownStyle {
/// About 68 characters of 14pt Plex Sans.
static let measure: CGFloat = 580
static let fileScheme = "helder-file"
static let body = Typography.body
static let bodyLineSpacing: CGFloat = 14 * 1.7 - 18
static func heading(_ level: Int) -> TypeRole {
switch level {
case 1, 2: Typography.markdownH2
case 3: Typography.markdownH3
case 4: TypeRole(.monoBold, 15, lineHeight: 18)
default: TypeRole(.monoBold, 13, lineHeight: 16)
}
}
/// Block margins; neighbours collapse to the larger one.
static func margins(_ block: MarkdownBlock) -> (top: CGFloat, bottom: CGFloat) {
switch block {
case let .heading(level, _):
let size = heading(level).size
return (1.6 * size, 0.6 * size)
case .paragraph, .list, .table: return (14, 14)
case .quote, .code: return (16.8, 16.8)
case .rule: return (22.4, 22.4)
}
}
}
/// A run of blocks with collapsed margins between them.
struct MarkdownBlocks: View {
let blocks: [MarkdownBlock]
let editor: EditorStore
var quoted = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in
MarkdownBlockView(block: block, editor: editor, quoted: quoted)
.padding(.top, index == 0 ? firstTop(block) : max(MarkdownStyle.margins(blocks[index - 1]).bottom, MarkdownStyle.margins(block).top))
}
}
}
private func firstTop(_ block: MarkdownBlock) -> CGFloat {
if case let .heading(level, _) = block { return 0.2 * MarkdownStyle.heading(level).size }
return 0
}
}
private struct MarkdownBlockView: View {
let block: MarkdownBlock
let editor: EditorStore
let quoted: Bool
var body: some View {
switch block {
case let .heading(level, content):
let role = MarkdownStyle.heading(level)
VStack(alignment: .leading, spacing: 8) {
Text(MarkdownInlines.attributed(content, style: .heading(role)))
.typeRole(role)
.foregroundStyle(Palette.text1)
.fixedSize(horizontal: false, vertical: true)
if level == 3 { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
case let .paragraph(content):
if case let .image(alt, source, _)? = content.first, content.count == 1 {
MarkdownImage(alt: alt, source: source, editor: editor)
} else {
paragraph(content)
}
case let .code(language, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(MarkdownInlines.highlighted(text, language: language))
.font(Typography.code.font)
.lineSpacing(20 - 17)
.fixedSize()
.padding(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
case let .quote(blocks):
HStack(alignment: .top, spacing: 16) {
Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule)
MarkdownBlocks(blocks: blocks, editor: editor, quoted: true)
}
.fixedSize(horizontal: false, vertical: true)
case let .list(ordered, items):
VStack(alignment: .leading, spacing: 7) {
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(ordered ? "\(index + 1)." : "—")
.typeRole(MarkdownStyle.body)
.foregroundStyle(Palette.amber)
.frame(minWidth: 12, alignment: .leading)
paragraph(item)
}
}
}
case let .table(header, alignments, rows):
MarkdownTable(header: header, alignments: alignments, rows: rows)
case .rule:
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline)
}
}
private func paragraph(_ content: [MarkdownInline]) -> some View {
Text(MarkdownInlines.attributed(content, style: quoted ? .quote : .body))
.typeRole(quoted ? Typography.markdownQuote : MarkdownStyle.body)
.lineSpacing(MarkdownStyle.bodyLineSpacing)
.foregroundStyle(quoted ? Palette.amberSoft : Palette.text2)
.fixedSize(horizontal: false, vertical: true)
}
}
private struct MarkdownTable: View {
let header: [[MarkdownInline]]
let alignments: [TableAlignment?]
let rows: [[[MarkdownInline]]]
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {
GridRow {
ForEach(Array(header.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .tableHeader))
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
.background(Palette.panel)
.gridColumnAlignment(horizontal(column))
}
}
ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline).gridCellUnsizedAxes(.horizontal)
GridRow {
ForEach(Array(row.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .body))
.typeRole(Typography.row)
.foregroundStyle(Palette.text3)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
}
}
}
}
.fixedSize()
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
private func alignment(_ column: Int) -> Alignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
private func horizontal(_ column: Int) -> HorizontalAlignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
}
/// A block image: a project file read through the file service, or a remote URL.
private struct MarkdownImage: View {
let alt: String
let source: ImageSource
let editor: EditorStore
@State private var data: Data?
@State private var failed = false
var body: some View {
Group {
switch source {
case let .remote(url):
AsyncImage(url: url) { phase in
if let image = phase.image {
image.resizable().aspectRatio(contentMode: .fit)
} else {
altText
}
}
case let .local(path):
if let data, let image = NSImage(data: data) {
Image(nsImage: image).resizable().aspectRatio(contentMode: .fit)
.frame(maxWidth: image.size.width)
} else {
altText.task(id: path) {
data = await editor.readImage(path)
failed = data == nil
}
}
}
}
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.accessibilityLabel(alt)
}
private var altText: some View {
Text(alt.isEmpty ? "—" : alt).typeRole(Typography.path).foregroundStyle(Palette.text3)
}
}
/// Inline runs as one AttributedString, so a paragraph wraps and selects as a single text.
enum MarkdownInlines {
enum Style {
case body
case quote
case heading(TypeRole)
case tableHeader
var role: TypeRole {
switch self {
case .body: MarkdownStyle.body
case .quote: Typography.markdownQuote
case let .heading(role): role
case .tableHeader: Typography.panelLabel
}
}
}
static func attributed(_ inlines: [MarkdownInline], style: Style) -> AttributedString {
var out = AttributedString()
append(inlines, to: &out, style: style, strong: false, emphasis: false)
return out
}
private static func append(_ inlines: [MarkdownInline], to out: inout AttributedString, style: Style,
strong: Bool, emphasis: Bool, link: URL? = nil, strike: Bool = false) {
for inline in inlines {
switch inline {
case let .text(text):
var run = AttributedString(text)
run.font = font(style: style, strong: strong, emphasis: emphasis)
if strong { run.foregroundColor = Palette.text1 }
if let link {
run.link = link
run.foregroundColor = Palette.amber
}
if strike { run.strikethroughStyle = .single }
out += run
case let .code(code):
var run = AttributedString("\u{2009}" + code + "\u{2009}")
run.font = Typography.code.font
run.foregroundColor = Palette.amberSoft
run.backgroundColor = Palette.panel
if let link { run.link = link }
out += run
case let .strong(children):
append(children, to: &out, style: style, strong: true, emphasis: emphasis, link: link, strike: strike)
case let .emphasis(children):
append(children, to: &out, style: style, strong: strong, emphasis: true, link: link, strike: strike)
case let .strikethrough(children):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: link, strike: true)
case let .link(children, url, _):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: linkURL(url), strike: strike)
case let .image(alt, _, _):
var run = AttributedString(alt)
run.font = Typography.path.font
run.foregroundColor = Palette.text4
out += run
}
}
}
/// Relative links point into the project; they get a private scheme the preview opens in the editor.
static func linkURL(_ raw: String) -> URL? {
guard let safe = MarkdownParser.safeURL(raw), !safe.hasPrefix("#") else { return nil }
if MarkdownParser.isLocalURL(safe) {
let encoded = safe.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? safe
return URL(string: MarkdownStyle.fileScheme + ":" + encoded)
}
return URL(string: safe)
}
private static func font(style: Style, strong: Bool, emphasis: Bool) -> Font {
switch style {
case .heading, .tableHeader:
return style.role.font
case .quote:
return Typography.markdownQuote.font
case .body:
if emphasis { return Typography.markdownQuote.nsFont.withSize(14).swiftUIFont }
return (strong ? Typography.rowSelected.nsFont : MarkdownStyle.body.nsFont).withSize(14).swiftUIFont
}
}
/// Fenced code with the six syntax colours, flat weight.
static func highlighted(_ text: String, language: Language?) -> AttributedString {
let ns = text as NSString
let colored = NSMutableAttributedString(string: text, attributes: [.foregroundColor: EditorColors.syntax(.plain)])
if let language {
for token in SyntaxHighlighter.tokens(for: text, language: language) where token.role != .plain {
let range = NSIntersectionRange(NSRange(location: token.location, length: token.length), NSRange(location: 0, length: ns.length))
colored.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: range)
}
}
var out = AttributedString(text)
colored.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: ns.length)) { value, range, _ in
guard let color = value as? NSColor, let bounds = Range(range, in: out) else { return }
out[bounds].foregroundColor = Color(nsColor: color)
}
return out
}
}
private extension NSFont {
var swiftUIFont: Font { Font(self) }
}
+110
View File
@@ -0,0 +1,110 @@
import HelderCore
import SwiftUI
/// The 460pt prompt: an optional note over the reference it inserts into the agent's composer.
public struct PassOnPanel: View {
let request: PassOnRequest
let insert: (String) -> Void
let cancel: () -> Void
@State private var note = ""
@FocusState private var focused: Bool
public init(request: PassOnRequest, insert: @escaping (String) -> Void, cancel: @escaping () -> Void) {
self.request = request
self.insert = insert
self.cancel = cancel
}
private var composed: String {
PassOn.compose(note: note, reference: request.reference, code: request.code)
}
public var body: some View {
GeometryReader { geometry in
ZStack(alignment: .topLeading) {
Color.clear
.contentShape(Rectangle())
.onTapGesture(perform: cancel)
panel
.offset(x: min(max(8, request.anchor.x), geometry.size.width - Metrics.passOnWidth - 8),
y: min(max(8, request.anchor.y + 6), geometry.size.height - 170))
}
}
}
private var panel: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
SparkGlyph()
.stroke(Palette.amber, style: StrokeStyle(lineWidth: 1.1 * 13 / 16, lineJoin: .round))
.frame(width: 13, height: 13)
Text("Pass on to agent").typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
EscChip()
}
TextField("", text: $note, prompt: Text("Add a note (optional)…").foregroundStyle(Palette.text4))
.textFieldStyle(.plain)
.typeRole(TypeRole(.monoRegular, 13))
.foregroundStyle(Palette.text1)
.focused($focused)
.onSubmit { insert(composed) }
.onExitCommand(perform: cancel)
.padding(.horizontal, 10)
.frame(height: 38)
.background(Palette.editor, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.amber, lineWidth: Metrics.accentRule))
.padding(Metrics.focusRingWidth)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall + 2).stroke(Palette.focusRing, lineWidth: Metrics.focusRingWidth))
.padding(-Metrics.focusRingWidth)
HStack(alignment: .top, spacing: 10) {
Text("Inserts").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).padding(.top, 5)
preview
}
OverlayFooter.hint([("↵", "insert into agent"), ("esc", "cancel")])
.typeRole(Typography.meta)
}
.padding(14)
.frame(width: Metrics.passOnWidth)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).stroke(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius, y: Metrics.menuShadowY)
.onAppear { focused = true }
}
@ViewBuilder
private var preview: some View {
let chip = Text(composed)
.typeRole(Typography.path)
.foregroundStyle(Palette.ink)
.padding(.horizontal, 8)
.padding(.vertical, 4)
if request.code != nil {
ScrollView {
chip.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxHeight: 132)
.fixedSize(horizontal: false, vertical: true)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
} else {
chip.lineLimit(1)
.truncationMode(.tail)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
}
/// The four-point spark that marks every "Pass on" action, drawn on a 16-unit grid.
struct SparkGlyph: Shape {
func path(in rect: CGRect) -> Path {
let unit = min(rect.width, rect.height) / 16
let points: [(CGFloat, CGFloat)] = [(8, 1.5), (9.6, 6.4), (14.5, 8), (9.6, 9.6), (8, 14.5), (6.4, 9.6), (1.5, 8), (6.4, 6.4)]
var path = Path()
for (index, point) in points.enumerated() {
let p = CGPoint(x: rect.minX + point.0 * unit, y: rect.minY + point.1 * unit)
if index == 0 { path.move(to: p) } else { path.addLine(to: p) }
}
path.closeSubpath()
return path
}
}
@@ -0,0 +1,249 @@
import HelderCore
import SwiftUI
/// One row the keyboard can land on: a declaration or a reference line.
public struct SymbolTarget: Equatable, Sendable {
public var path: String
public var line: Int
}
public enum SymbolTargets {
/// Declarations first, then every reference line, as one flat list for ↑↓↵.
public static func flatten(_ lookup: SymbolLookup?) -> [SymbolTarget] {
guard let lookup else { return [] }
return lookup.definitions.map { SymbolTarget(path: $0.path, line: $0.line) }
+ lookup.references.flatMap { group in group.hits.map { SymbolTarget(path: group.path, line: $0.line) } }
}
/// One declaration is named in full, the way the file does; several share only the short name.
public static func title(_ name: String, _ lookup: SymbolLookup?) -> String {
guard let lookup, lookup.definitions.count == 1 else { return name }
return lookup.definitions[0].qualifiedName
}
}
/// ⌘-click on a PHP class name: where it is declared, then every reference. Centred on the window,
/// because the list is as long as the class is popular.
struct SymbolPopupView: View {
let editor: EditorStore
let name: String
let dismiss: () -> Void
/// Opens a file at a line (and reveals it in the Explorer).
let openAt: (String, Int) -> Void
@State private var highlighted = 0
@FocusState private var focused: Bool
private var lookup: SymbolLookup? { editor.symbolName == name ? editor.symbolLookup : nil }
var body: some View {
let targets = SymbolTargets.flatten(lookup)
GeometryReader { geometry in
ZStack {
Palette.scrim.onTapGesture(perform: dismiss)
panel(targets)
.frame(width: min(700, geometry.size.width * 0.82))
.frame(maxHeight: min(geometry.size.height * 0.72, 640))
.fixedSize(horizontal: false, vertical: true)
}
}
.focusable()
.focused($focused)
.focusEffectDisabled()
.onAppear { focused = true }
.onChange(of: lookup) { highlighted = 0 }
.onKeyPress(.downArrow) { highlighted = min(highlighted + 1, max(0, targets.count - 1)); return .handled }
.onKeyPress(.upArrow) { highlighted = max(highlighted - 1, 0); return .handled }
.onKeyPress(.return) {
if highlighted < targets.count { open(targets[highlighted]) }
return .handled
}
.onExitCommand(perform: dismiss)
}
private func panel(_ targets: [SymbolTarget]) -> some View {
VStack(spacing: 0) {
HStack(spacing: 10) {
Text(SymbolTargets.title(name, lookup)).typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
if let lookup {
Text("\(lookup.referenceCount) reference\(lookup.referenceCount == 1 ? "" : "s")")
.typeRole(TypeRole(.monoRegular, 10.5))
.foregroundStyle(Palette.text4)
}
}
.padding(.horizontal, 18)
.frame(height: 50)
.overlay(alignment: .bottom) { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
if let lookup {
ScrollViewReader { proxy in
ScrollView {
results(lookup)
.padding(.bottom, 6)
}
.onChange(of: highlighted) { _, index in proxy.scrollTo(index) }
}
} else {
empty("Searching…")
}
}
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.overlay(alignment: .leading) { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusOverlay).stroke(Palette.raised, lineWidth: Metrics.hairline))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusOverlay))
.shadow(color: Palette.overlayShadow, radius: Metrics.overlayShadowRadius, y: Metrics.overlayShadowY)
}
private func results(_ lookup: SymbolLookup) -> some View {
let definitionCount = lookup.definitions.count
return LazyVStack(alignment: .leading, spacing: 0) {
section("Defined in")
if lookup.definitions.isEmpty { empty("No declaration in this project") }
ForEach(Array(lookup.definitions.enumerated()), id: \.offset) { index, def in
SymbolRow(isHighlighted: highlighted == index) {
HStack(spacing: 8) {
TypeBadge(path: def.path)
Text(def.path).typeRole(Typography.path).foregroundStyle(Palette.text2).lineLimit(1).truncationMode(.head)
Text(def.kind)
.typeRole(TypeRole(.monoRegular, 10))
.foregroundStyle(Palette.text4)
.padding(.horizontal, 5)
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.tooltipBorder, lineWidth: Metrics.hairline))
Spacer()
Text("\(def.line)").typeRole(Typography.meta).foregroundStyle(Palette.text4)
}
.padding(.horizontal, 13)
.padding(.vertical, 4)
}
.id(index)
.onHover { if $0 { highlighted = index } }
.onTapGesture { open(SymbolTarget(path: def.path, line: def.line)) }
}
ForEach(Array(lookup.definitions.enumerated()), id: \.offset) { _, def in relations(def) }
if !lookup.references.isEmpty { section("Used in") }
ForEach(Array(referenceRows(lookup, offset: definitionCount).enumerated()), id: \.offset) { _, row in
switch row {
case let .file(group):
HStack(spacing: 8) {
TypeBadge(path: group.path)
Text(group.path).typeRole(Typography.path).foregroundStyle(Palette.text3).lineLimit(1).truncationMode(.head)
Spacer()
Text("\(group.hits.count)").typeRole(Typography.meta).foregroundStyle(Palette.text4)
}
.padding(.horizontal, 13)
.padding(.top, 8)
.padding(.bottom, 2)
.contentShape(Rectangle())
.onTapGesture { if let first = group.hits.first { open(SymbolTarget(path: group.path, line: first.line)) } }
case let .hit(path, hit, index):
SymbolRow(isHighlighted: highlighted == index) {
HStack(spacing: 12) {
Text("\(hit.line)").typeRole(Typography.searchHit).foregroundStyle(highlighted == index ? Palette.amber : Palette.text5)
.frame(width: 40, alignment: .trailing)
Text(String(hit.text.prefix(200))).typeRole(Typography.searchHit).foregroundStyle(Palette.text3).lineLimit(1)
Spacer(minLength: 0)
}
.padding(.leading, 13)
.frame(height: Metrics.searchHitLine)
}
.id(index)
.onHover { if $0 { highlighted = index } }
.onTapGesture { open(SymbolTarget(path: path, line: hit.line)) }
}
}
}
}
private enum ReferenceRow {
case file(RefGroup)
case hit(path: String, ContentHit, index: Int)
}
private func referenceRows(_ lookup: SymbolLookup, offset: Int) -> [ReferenceRow] {
var rows: [ReferenceRow] = []
var index = offset
for group in lookup.references {
rows.append(.file(group))
for hit in group.hits {
rows.append(.hit(path: group.path, hit, index: index))
index += 1
}
}
return rows
}
/// What a declaration extends, implements and uses; a name this project declares is a chip you can follow.
@ViewBuilder
private func relations(_ def: SymbolDef) -> some View {
let groups = [("extends", def.parents), ("implements", def.interfaces), ("uses", def.traits)].filter { !$0.1.isEmpty }
if !groups.isEmpty {
VStack(alignment: .leading, spacing: 3) {
ForEach(groups, id: \.0) { key, names in
HStack(spacing: 6) {
Text(key.uppercased()).typeRole(TypeRole(.sansRegular, 10)).foregroundStyle(Palette.text4)
.frame(minWidth: 66, alignment: .leading)
ForEach(names, id: \.self) { chip($0) }
}
}
}
.padding(EdgeInsets(top: 2, leading: 34, bottom: 6, trailing: 13))
}
}
private func chip(_ name: String) -> some View {
SymbolChip(name: name, known: editor.knownSymbols.contains(name)) { editor.lookupSymbol(name) }
}
private func section(_ title: String) -> some View {
Text(title).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 14, leading: 16, bottom: 6, trailing: 16))
}
private func empty(_ text: String) -> some View {
Text(text).typeRole(Typography.tooltip).foregroundStyle(Palette.text4)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.frame(maxWidth: .infinity, alignment: .leading)
}
private func open(_ target: SymbolTarget) {
dismiss()
openAt(target.path, target.line)
}
}
/// A selectable row: raised fill and the 2px amber rule when highlighted.
private struct SymbolRow<Content: View>: View {
let isHighlighted: Bool
@ViewBuilder let content: () -> Content
var body: some View {
content()
.frame(maxWidth: .infinity, alignment: .leading)
.background(isHighlighted ? Palette.raised : Color.clear)
.overlay(alignment: .leading) {
if isHighlighted { Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule) }
}
.contentShape(Rectangle())
}
}
/// A related class name; one the project declares lights amber under the pointer and reloads the popup on it.
private struct SymbolChip: View {
let name: String
let known: Bool
let follow: () -> Void
@State private var hovering = false
var body: some View {
let lit = known && hovering
Text(name)
.typeRole(TypeRole(.monoRegular, 11))
.foregroundStyle(lit ? Palette.amber : known ? Palette.text2 : Palette.text4)
.padding(.horizontal, 7)
.background(lit ? Palette.amberTint : .clear, in: RoundedRectangle(cornerRadius: 3))
.overlay(RoundedRectangle(cornerRadius: 3).stroke(lit ? Palette.amberKeycapBorder : Palette.raised, lineWidth: Metrics.hairline))
.contentShape(Rectangle())
.onHover { hovering = $0 }
.onTapGesture { if known { follow() } }
}
}
@@ -0,0 +1,170 @@
import HelderCore
import SwiftUI
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy.
public struct ExplorerColumn: View {
let model: WorkspaceModel
@State private var columnFrame = CGRect.zero
/// A cursor that follows the pointer must not scroll the list under it.
@State private var hoveredPath: String?
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
if let store = model.explorer {
tree(store)
} else {
Spacer()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Palette.column(.explorer, active: isActive))
.background(GlobalFrameReader(frame: $columnFrame))
.simultaneousGesture(TapGesture().onEnded { model.pointerFocused(.explorer) })
}
private var isActive: Bool { model.layout.activePanel == .explorer }
private var showHidden: Bool { model.layout.showHidden }
private var header: some View {
HStack(spacing: 8) {
Text("Explorer").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Spacer(minLength: 8)
Text(model.name)
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.lineLimit(1)
.truncationMode(.middle)
}
.padding(.horizontal, 12)
.frame(height: Metrics.panelHeader)
.hairline(.bottom)
}
private func tree(_ store: ExplorerStore) -> some View {
let statuses = model.sourceControl?.fileStatuses ?? [:]
return GeometryReader { viewport in
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(store.rows(showHidden: showHidden), id: \.path) { row in
TreeRowView(
row: row,
isOpen: store.expanded.contains(row.path),
selected: isSelected(row, store),
status: row.kind == .file ? statuses[row.path] : nil,
onClick: { click(row, store) },
onHover: { hoveredPath = row.path; store.selectedPath = row.path },
onContextMenu: { point in showMenu(for: ExplorerStore.target(for: row), at: point, store) }
)
.reportsRowFrame(.tree(row.path), to: model)
.id(row.path)
}
}
.padding(.top, 6)
.padding(.bottom, 14)
.frame(minHeight: viewport.size.height, alignment: .top)
// The bare space under the rows is the project folder itself.
.background(RightClickArea { point in showMenu(for: .projectRoot, at: point, store) })
}
.onChange(of: store.selectedPath) { _, path in
guard let path, path != hoveredPath else { return }
proxy.scrollTo(path)
}
}
}
.task { await store.loadIfNeeded() }
}
/// The open file, the keyboard cursor, or the row whose menu is open.
private func isSelected(_ row: TreeRow, _ store: ExplorerStore) -> Bool {
if case let .contextMenu(request) = model.overlay.current, request.target == ExplorerStore.target(for: row) {
return true
}
if isActive && store.selectedPath == row.path { return true }
return row.kind == .file && model.editor?.activePath == row.path
}
private func click(_ row: TreeRow, _ store: ExplorerStore) {
store.selectedPath = row.path
if row.kind == .directory {
store.toggle(row.path)
} else {
model.perform(.open(row.path, OpenOptions()))
}
}
/// Rows anchor the menu to the column's right edge; the empty space under them anchors it at the click.
private func showMenu(for target: ContextTarget, at point: CGPoint, _ store: ExplorerStore) {
model.pointerFocused(.explorer)
if target != .projectRoot { store.selectedPath = target.path }
let anchor = target == .projectRoot ? point : CGPoint(x: columnFrame.maxX, y: point.y)
model.perform(.showContextMenu(target, anchor: anchor))
}
}
/// One tree row: indent, chevron, folder glyph or type badge, name, change letter.
private struct TreeRowView: View {
let row: TreeRow
let isOpen: Bool
let selected: Bool
let status: GitStatus?
let onClick: () -> Void
let onHover: () -> Void
let onContextMenu: (CGPoint) -> Void
@State private var hovered = false
private var isDirectory: Bool { row.kind == .directory }
var body: some View {
HStack(spacing: 7) {
Group {
if isDirectory {
ChevronGlyph(open: isOpen).foregroundStyle(isOpen ? Palette.amber : Palette.text4)
} else {
Color.clear
}
}
.frame(width: 10, height: 10)
if isDirectory {
FolderGlyph(open: isOpen).frame(width: 16, height: 16)
} else {
TypeBadge(path: row.path)
}
Text(PathUtils.basename(row.path))
.typeRole(selected ? Typography.rowSelected : Typography.row)
.strikethrough(status == .deleted, color: Palette.text4)
.foregroundStyle(labelColor)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 0)
if let status {
Text(status.rawValue)
.typeRole(RowStyle.changeLetterRole)
.foregroundStyle(status == .deleted ? Palette.amberDeep : Palette.addedText)
.padding(.leading, 8)
}
}
.padding(.leading, Metrics.explorerBaseIndent + CGFloat(row.depth) * Metrics.explorerIndent)
.padding(.trailing, 12)
.frame(height: Metrics.explorerRow)
.selectableRow(isSelected: selected, isHovered: hovered)
.contentShape(Rectangle())
.onTapGesture(perform: onClick)
.onHover { inside in
hovered = inside
if inside { onHover() }
}
.overlay(RightClickArea(onRightClick: onContextMenu))
.help(isDirectory ? "" : row.path)
}
private var labelColor: Color {
if status == .deleted { return Palette.text4 }
return selected || (isDirectory && isOpen) ? Palette.text1 : Palette.text3
}
}
+209
View File
@@ -0,0 +1,209 @@
// Pieces shared by the Source Control and Explorer rows.
import AppKit
import HelderCore
import SwiftUI
enum RowStyle {
static let folderFill = Color(hex: 0x7A838C, alpha: 0.12)
static let openFolderFill = Color(hex: 0x7A838C, alpha: 0.16)
static let openFolderFrontFill = Color(hex: 0x7A838C, alpha: 0.22)
static let changeLetterRole = TypeRole(.monoSemiBold, 10)
static let gitLetterRole = TypeRole(.monoSemiBold, 11)
static let dirHeadRole = TypeRole(.monoRegular, 11)
static let groupLabelRole = Typography.panelLabel
}
// MARK: Glyphs (drawn on 16-unit grids)
struct ChevronGlyph: View {
let open: Bool
var body: some View {
Path { p in
p.move(to: CGPoint(x: 3.5, y: 2))
p.addLine(to: CGPoint(x: 7, y: 5))
p.addLine(to: CGPoint(x: 3.5, y: 8))
}
.stroke(style: StrokeStyle(lineWidth: 1.4, lineCap: .round, lineJoin: .round))
.frame(width: 10, height: 10)
.scaleEffect(0.9)
.rotationEffect(.degrees(open ? 90 : 0))
}
}
struct FolderGlyph: View {
let open: Bool
var size: CGFloat = 14
var body: some View {
Canvas { context, canvas in
let k = canvas.width / 16
func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: x * k, y: y * k) }
let line = StrokeStyle(lineWidth: 1.1, lineJoin: .round)
if open {
var back = Path()
back.move(to: pt(2, 12.5)); back.addLine(to: pt(2, 4.5)); back.addLine(to: pt(5.6, 4.5))
back.addLine(to: pt(6.8, 5.9)); back.addLine(to: pt(13.5, 5.9)); back.addLine(to: pt(13.5, 7.4))
context.fill(back, with: .color(RowStyle.openFolderFill))
context.stroke(back, with: .color(Palette.text4), style: line)
var front = Path()
front.move(to: pt(1.4, 12.6)); front.addLine(to: pt(3.3, 7.5)); front.addLine(to: pt(14.7, 7.5))
front.addLine(to: pt(12.8, 12.6)); front.closeSubpath()
context.fill(front, with: .color(RowStyle.openFolderFrontFill))
context.stroke(front, with: .color(Palette.text4), style: line)
} else {
var shape = Path()
shape.move(to: pt(1.5, 4.5)); shape.addLine(to: pt(5.5, 4.5)); shape.addLine(to: pt(6.7, 5.9))
shape.addLine(to: pt(14, 5.9)); shape.addLine(to: pt(14, 13)); shape.addLine(to: pt(1.5, 13))
shape.closeSubpath()
context.fill(shape, with: .color(RowStyle.folderFill))
context.stroke(shape, with: .color(Palette.text4), style: line)
}
}
.frame(width: size, height: size)
}
}
/// The plus, minus, push and arrow-up icons.
enum IconGlyph {
case plus, minus, push, arrowUp
func path(in size: CGFloat) -> Path {
switch self {
case .plus:
let k = size / 14
var p = Path()
p.move(to: CGPoint(x: 7 * k, y: 2.5 * k)); p.addLine(to: CGPoint(x: 7 * k, y: 11.5 * k))
p.move(to: CGPoint(x: 2.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
case .minus:
let k = size / 14
var p = Path()
p.move(to: CGPoint(x: 2.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
case .push:
let k = size / 16
var p = Path()
p.move(to: CGPoint(x: 8 * k, y: 13 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 4 * k))
p.move(to: CGPoint(x: 4.5 * k, y: 7.5 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 4 * k))
p.addLine(to: CGPoint(x: 11.5 * k, y: 7.5 * k))
p.move(to: CGPoint(x: 3.5 * k, y: 2.5 * k)); p.addLine(to: CGPoint(x: 12.5 * k, y: 2.5 * k))
return p
case .arrowUp:
let k = size / 16
var p = Path()
p.move(to: CGPoint(x: 8 * k, y: 13 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 3.5 * k))
p.move(to: CGPoint(x: 4.5 * k, y: 7 * k)); p.addLine(to: CGPoint(x: 8 * k, y: 3.5 * k))
p.addLine(to: CGPoint(x: 11.5 * k, y: 7 * k))
return p
}
}
}
struct IconView: View {
let glyph: IconGlyph
var size: CGFloat = 13
var body: some View {
glyph.path(in: size)
.stroke(style: StrokeStyle(lineWidth: glyph == .push || glyph == .arrowUp ? 1.4 : 1.5, lineCap: .round, lineJoin: .round))
.frame(width: size, height: size)
}
}
/// A borderless icon button that turns amber under the pointer.
struct QuickActionButton: View {
let glyph: IconGlyph
let help: String
let action: () -> Void
@State private var hovered = false
var body: some View {
Button(action: action) {
IconView(glyph: glyph)
.foregroundStyle(hovered ? Palette.amber : Palette.text4)
.frame(width: 18, height: 18)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hovered = $0 }
.help(help)
}
}
// MARK: Right click
/// Reports a right click (or control-click) with its point in window coordinates, top-left origin.
/// It only claims right clicks, so left clicks and hover still reach the SwiftUI row beneath.
struct RightClickArea: NSViewRepresentable {
let onRightClick: (CGPoint) -> Void
func makeNSView(context: Context) -> CatcherView {
let view = CatcherView()
view.onRightClick = onRightClick
return view
}
func updateNSView(_ view: CatcherView, context: Context) {
view.onRightClick = onRightClick
}
final class CatcherView: NSView {
var onRightClick: ((CGPoint) -> Void)?
override func hitTest(_ point: NSPoint) -> NSView? {
guard let event = NSApp.currentEvent, Self.isContextClick(event) else { return nil }
return super.hitTest(point)
}
override func rightMouseDown(with event: NSEvent) { report(event) }
override func mouseDown(with event: NSEvent) {
if Self.isContextClick(event) { report(event) } else { super.mouseDown(with: event) }
}
private func report(_ event: NSEvent) {
guard let content = window?.contentView else { return }
let p = content.convert(event.locationInWindow, from: nil)
onRightClick?(CGPoint(x: p.x, y: content.isFlipped ? p.y : content.bounds.height - p.y))
}
private static func isContextClick(_ event: NSEvent) -> Bool {
event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))
}
}
}
/// Reads a view's frame in window coordinates, for anchoring menus to a column's right edge.
struct GlobalFrameReader: View {
@Binding var frame: CGRect
var body: some View {
GeometryReader { proxy in
Color.clear
.onAppear { frame = proxy.frame(in: .global) }
.onChange(of: proxy.frame(in: .global)) { _, new in frame = new }
}
}
}
/// Tells the model where a list row sits in the window, for the ⌘→ menu; nil once the row is gone.
private struct RowFrameReporter: ViewModifier {
let key: RowKey
let model: WorkspaceModel
func body(content: Content) -> some View {
content.background(GeometryReader { proxy in
Color.clear
.onAppear { model.rowFrameChanged(key, proxy.frame(in: .global)) }
.onChange(of: proxy.frame(in: .global)) { _, frame in model.rowFrameChanged(key, frame) }
.onDisappear { model.rowFrameChanged(key, nil) }
})
}
}
extension View {
func reportsRowFrame(_ key: RowKey, to model: WorkspaceModel) -> some View {
modifier(RowFrameReporter(key: key, model: model))
}
}
@@ -0,0 +1,54 @@
import SwiftUI
/// A destructive action waiting for a yes: ↵ confirms, esc cancels.
struct ConfirmOverlay: View {
let request: ConfirmRequest
var onConfirm: () -> Void
var onClose: () -> Void
var body: some View {
OverlayShell(.sized(width: 460), onDismiss: onClose) {
VStack(alignment: .leading, spacing: 0) {
Text(request.title).typeRole(Typography.dialogTitle).foregroundStyle(Palette.text1)
if let body = request.body {
Text(body)
.typeRole(TypeRole(.monoRegular, 12, lineHeight: 19.2))
.foregroundStyle(Palette.text4)
.fixedSize(horizontal: false, vertical: true)
.padding(.top, 12)
}
HStack(spacing: 8) {
Spacer()
Button(action: onClose) {
HStack(spacing: 8) {
Text("Cancel")
Keycap("esc")
}
}
.buttonStyle(.secondary)
// The model dismisses the overlay itself; closing here first would drop the pending request.
Button(action: onConfirm) {
HStack(spacing: 8) {
Text(request.confirmLabel)
Keycap("↵", style: .onDeep)
}
}
.buttonStyle(.destructive)
}
.padding(.top, 20)
}
.padding(20)
.frame(maxWidth: .infinity, alignment: .leading)
.background(OverlayKeyCatcher(onKey: handle))
}
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .enter: onConfirm()
case .escape: onClose()
default: return false
}
return true
}
}
@@ -0,0 +1,180 @@
import AppKit
import HelderCore
import SwiftUI
enum MenuCursor {
static func first(in entries: [ContextMenuEntry]) -> Int? {
entries.firstIndex { $0 != .separator }
}
/// The next selectable entry in `step` direction, wrapping around and skipping separators.
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int {
guard !entries.isEmpty else { return current }
var index = current
for _ in entries.indices {
index = (index + step + entries.count) % entries.count
if entries[index] != .separator { return index }
}
return current
}
}
/// The colour an action's icon carries at rest.
enum MenuIconTint: Equatable {
/// text-4, amber when highlighted.
case plain
case add, modify, rename, danger
var color: Color? {
switch self {
case .plain: nil
case .add: Palette.menuIconAdd
case .modify: Palette.menuIconModify
case .rename: Palette.menuIconRename
case .danger: Palette.removedText
}
}
}
/// When a mouse-down closes the menu: anywhere in the menu's window outside the menu itself.
enum MenuDismissal {
static func closes(clickAt point: CGPoint, menuBounds: CGRect, sameWindow: Bool) -> Bool {
sameWindow && !menuBounds.contains(point)
}
}
/// A right-click menu at the pointer: path header, then the actions; the first one is pre-highlighted.
/// A click outside closes it and still reaches whatever was clicked.
/// `onPerform` alone runs an item: the model closes the menu itself and reads its anchor to place what opens next.
struct ContextMenuOverlay: View {
let request: ContextMenuRequest
var onPerform: (ContextAction) -> Void
var onClose: () -> Void
@State private var highlighted: Int?
init(request: ContextMenuRequest, onPerform: @escaping (ContextAction) -> Void, onClose: @escaping () -> Void) {
self.request = request
self.onPerform = onPerform
self.onClose = onClose
_highlighted = State(initialValue: MenuCursor.first(in: request.entries))
}
var body: some View {
GeometryReader { proxy in
menu
.background(OverlayKeyCatcher(onKey: handle))
.background(OutsideClickMonitor(onOutside: onClose))
.offset(position(in: proxy.size))
}
}
private var menu: some View {
ContextMenuPanel {
if !request.header.isEmpty { ContextMenuHeader(request.header) }
ForEach(Array(request.entries.enumerated()), id: \.offset) { index, entry in
switch entry {
case .separator:
ContextMenuSeparator()
case let .action(action, label):
ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color,
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
.onHover { inside in if inside { highlighted = index } }
.onTapGesture { onPerform(action) }
}
}
}
}
/// Keeps the menu inside the window.
private func position(in size: CGSize) -> CGSize {
let height = CGFloat(request.entries.count) * 34 + 60
let x = min(request.anchor.x, size.width - Metrics.contextMenuWidth - 8)
let y = min(request.anchor.y, size.height - height)
return CGSize(width: max(8, x), height: max(8, y))
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .up, .commandUp: highlighted = MenuCursor.step(highlighted ?? -1, by: -1, in: request.entries)
case .down, .commandDown: highlighted = MenuCursor.step(highlighted ?? -1, by: 1, in: request.entries)
case .enter:
if let highlighted, case let .action(action, _) = request.entries[highlighted] { onPerform(action) }
case .escape: onClose()
default: return false
}
return true
}
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
switch action {
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal: .plain
case .newFile, .newFolder, .stage: .add
case .copyFileName, .unstage, .revealInFinder: .modify
case .passOnReference, .passOnFileName, .openDiff, .rename: .rename
case .discard, .delete: .danger
}
}
nonisolated static func symbol(for action: ContextAction) -> String {
switch action {
case .passOnReference, .passOnFileName: ContextMenuRow.spark
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
case .pasteIntoTerminal: "doc.on.clipboard"
case .newFile: "doc.badge.plus"
case .newFolder: "folder.badge.plus"
case .stage: "plus"
case .unstage: "minus"
case .openDiff: "arrow.left.arrow.right"
case .discard: "arrow.uturn.backward"
case .rename: "pencil"
case .revealInFinder: "folder"
case .delete: "trash"
}
}
}
/// Watches mouse-downs in its window without consuming them; one outside its own bounds calls `onOutside`.
private struct OutsideClickMonitor: NSViewRepresentable {
var onOutside: () -> Void
func makeNSView(context: Context) -> MonitorView {
let view = MonitorView()
view.onOutside = onOutside
return view
}
func updateNSView(_ view: MonitorView, context: Context) {
view.onOutside = onOutside
}
static func dismantleNSView(_ view: MonitorView, coordinator: ()) {
view.stop()
}
final class MonitorView: NSView {
var onOutside: () -> Void = {}
private var monitor: Any?
override func hitTest(_ point: NSPoint) -> NSView? { nil }
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
stop()
guard window != nil else { return }
monitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { [weak self] event in
guard let self else { return event }
let point = self.convert(event.locationInWindow, from: nil)
if MenuDismissal.closes(clickAt: point, menuBounds: self.bounds, sameWindow: event.window === self.window) {
self.onOutside()
}
return event
}
}
func stop() {
if let monitor { NSEvent.removeMonitor(monitor) }
monitor = nil
}
}
}
@@ -0,0 +1,129 @@
import HelderCore
import SwiftUI
/// The words and target path of the new-file, new-folder and rename prompt.
struct NamePromptText: Equatable {
var purpose: NamePromptRequest.Purpose
var title: String
var placeholder: String
var previewLabel: String
/// The footer's "create file" / "rename folder".
var action: String
var initialName: String
var isFolder: Bool
var isRename: Bool
init(_ request: NamePromptRequest) {
purpose = request.purpose
switch request.purpose {
case .newFile: (isFolder, isRename) = (false, false)
case .newFolder: (isFolder, isRename) = (true, false)
case let .rename(_, isDirectory): (isFolder, isRename) = (isDirectory, true)
}
initialName = request.initialName
let noun = isFolder ? "folder" : "file"
title = isRename ? "Rename \(noun)" : (isFolder ? "New folder" : "New file")
placeholder = isFolder ? "folder name…" : "file name…"
previewLabel = isRename ? "renames to" : "creates"
action = (isRename ? "rename " : "create ") + noun
}
/// The path a submit would produce, from the same rule the Explorer applies.
func preview(for name: String) -> String {
ExplorerStore.promptTarget(for: purpose, name: name) ?? "…"
}
/// ↵ does nothing for an empty or invalid name, or an unchanged rename.
func canSubmit(_ name: String) -> Bool {
ExplorerStore.promptTarget(for: purpose, name: name) != nil
}
/// A rename selects the stem only, so typing keeps the extension.
var initialSelection: NSRange {
let name = initialName as NSString
let dot = name.range(of: ".", options: .backwards).location
let stem = isRename && dot != NSNotFound && dot > 0 ? dot : name.length
return NSRange(location: 0, length: stem)
}
}
/// A small anchored prompt for naming a new entry or renaming one.
struct NamePromptOverlay: View {
let request: NamePromptRequest
var onSubmit: (String) -> Void
var onClose: () -> Void
@State private var name: String
private let text: NamePromptText
init(request: NamePromptRequest, onSubmit: @escaping (String) -> Void, onClose: @escaping () -> Void) {
self.request = request
self.onSubmit = onSubmit
self.onClose = onClose
text = NamePromptText(request)
_name = State(initialValue: request.initialName)
}
var body: some View {
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
Color.clear.contentShape(Rectangle()).onTapGesture(perform: onClose)
prompt.offset(position(in: proxy.size))
}
}
}
private var prompt: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
Image(systemName: text.isFolder ? "folder" : "doc")
.font(.system(size: 13, weight: .light))
.foregroundStyle(Palette.amber)
Text(text.title).typeRole(TypeRole(.monoBold, 13)).foregroundStyle(Palette.text1)
Spacer()
EscChip()
}
OverlayCommandField(text: $name, placeholder: text.placeholder, font: TypeRole(.monoRegular, 13).nsFont,
initialSelection: text.initialSelection, onKey: handle)
.padding(.horizontal, 10)
.frame(height: 38)
.background(Palette.editor, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.focusRing(true)
HStack(spacing: 10) {
Text(text.previewLabel).typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
Text(text.preview(for: name))
.typeRole(Typography.path)
.foregroundStyle(Palette.ink)
.lineLimit(1)
.truncationMode(.middle)
.padding(.horizontal, 8)
.padding(.vertical, 4)
.background(Palette.amber, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
OverlayFooter.hint([("↵", text.action), ("esc", "cancel")])
.typeRole(Typography.chip)
}
.padding(14)
.frame(width: Metrics.passOnWidth)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusMedium))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusMedium).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
.shadow(color: Palette.menuShadow, radius: Metrics.menuShadowRadius / 2, y: Metrics.menuShadowY)
}
private func position(in size: CGSize) -> CGSize {
let x = min(request.anchor.x, size.width - Metrics.passOnWidth - 8)
let y = min(request.anchor.y + 6, size.height - 150)
return CGSize(width: max(8, x), height: max(8, y))
}
private func handle(_ key: OverlayKey) -> Bool {
switch key {
case .enter:
// The model closes the prompt itself; closing here first would drop the request it answers.
if text.canSubmit(name) { onSubmit(name.trimmingCharacters(in: .whitespacesAndNewlines)) }
case .escape: onClose()
default: return false
}
return true
}
}

Some files were not shown because too many files have changed in this diff Show More