diff --git a/spike/codeedit/Package.resolved b/spike/codeedit/Package.resolved new file mode 100644 index 0000000..a7b4a32 --- /dev/null +++ b/spike/codeedit/Package.resolved @@ -0,0 +1,96 @@ +{ + "originHash" : "453562669f1231fef7eb30ffcd1db6224d44e963de82930718a931775a8d93bd", + "pins" : [ + { + "identity" : "codeeditlanguages", + "kind" : "remoteSourceControl", + "location" : "https://github.com/CodeEditApp/CodeEditLanguages.git", + "state" : { + "revision" : "331d5dbc5fc8513be5848fce8a2a312908f36a11", + "version" : "0.1.20" + } + }, + { + "identity" : "codeeditsourceeditor", + "kind" : "remoteSourceControl", + "location" : "https://github.com/AlexKucera/CodeEditSourceEditor.git", + "state" : { + "revision" : "3ce600768d4cb9a4f65f5a106ffa193f9fd861d9", + "version" : "0.15.8-helm" + } + }, + { + "identity" : "codeeditsymbols", + "kind" : "remoteSourceControl", + "location" : "https://github.com/CodeEditApp/CodeEditSymbols.git", + "state" : { + "revision" : "ae69712b08571c4469c2ed5cd38ad9f19439793e", + "version" : "0.2.3" + } + }, + { + "identity" : "codeedittextview", + "kind" : "remoteSourceControl", + "location" : "https://github.com/AlexKucera/CodeEditTextView.git", + "state" : { + "revision" : "fe1e34d90f10660c8e91688b0b2be383300b815e", + "version" : "0.12.3-helm" + } + }, + { + "identity" : "rearrange", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ChimeHQ/Rearrange", + "state" : { + "revision" : "4de8be41dba304192e87dc0a11e0aa39e72aa2e8", + "version" : "2.1.1" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "98ef3c98609a1e31b7e157b5b619579001a789d6", + "version" : "1.7.1" + } + }, + { + "identity" : "swifttreesitter", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ChimeHQ/SwiftTreeSitter.git", + "state" : { + "revision" : "08ef81eb8620617b55b08868126707ad72bf754f", + "version" : "0.25.0" + } + }, + { + "identity" : "textformation", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ChimeHQ/TextFormation", + "state" : { + "revision" : "b1ce9a14bd86042bba4de62236028dc4ce9db6a1", + "version" : "0.9.0" + } + }, + { + "identity" : "textstory", + "kind" : "remoteSourceControl", + "location" : "https://github.com/ChimeHQ/TextStory", + "state" : { + "revision" : "a52db1a2eca74d37c8c19bf3165416941632ed45", + "version" : "0.9.2" + } + }, + { + "identity" : "tree-sitter", + "kind" : "remoteSourceControl", + "location" : "https://github.com/tree-sitter/tree-sitter", + "state" : { + "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406", + "version" : "0.25.10" + } + } + ], + "version" : 3 +} diff --git a/spike/codeedit/Package.swift b/spike/codeedit/Package.swift new file mode 100644 index 0000000..a834327 --- /dev/null +++ b/spike/codeedit/Package.swift @@ -0,0 +1,12 @@ +// swift-tools-version:6.2 +import PackageDescription + +let package = Package( + name: "CodeEditSpike", + platforms: [.macOS(.v26)], + dependencies: [ + // Fork fact from map #16: same fork + revision as Classis (0.15.8-helm = 3ce6007). + .package(url: "https://github.com/AlexKucera/CodeEditSourceEditor.git", exact: "0.15.8-helm"), + ], + targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])] +) diff --git a/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift b/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift new file mode 100644 index 0000000..1be4684 --- /dev/null +++ b/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift @@ -0,0 +1,391 @@ +// Spike A (#52) — THROWAWAY. CodeEditSourceEditor fork as prose editor (mode B), anchor proof. +// Question: can the presumptive-leader code substrate present prose source as calm writing? +// Run: spike/codeedit/run.sh (from repo root, branch spike/editor-presentation) +import AppKit +@preconcurrency import CodeEditLanguages +@preconcurrency import CodeEditSourceEditor +@preconcurrency import CodeEditTextView +import SwiftUI + +// MARK: - Prose theme (uniform-font compromise documented in the resolution) + +enum ProseTheme { + // Iowan Old Style like Spike B / the web proto; falls back to system serif. + static var bodyFont: NSFont { + NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) + ?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard) + } + + static let ink = NSColor(srgbRed: 0.10, green: 0.10, blue: 0.09, alpha: 1) + static let dim = NSColor(srgbRed: 0.55, green: 0.55, blue: 0.55, alpha: 1) + static let paper = NSColor(srgbRed: 0.98, green: 0.98, blue: 0.98, alpha: 1) + static let accent = NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 1) + + static var theme: EditorTheme { + EditorTheme( + text: .init(color: ink), + insertionPoint: ink, + invisibles: .init(color: dim), + background: paper, + lineHighlight: NSColor(srgbRed: 0.955, green: 0.955, blue: 0.955, alpha: 1), + selection: NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), + keywords: .init(color: dim), // markdown markers route here via prosePass below + commands: .init(color: ink), + types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit) + attributes: .init(color: ink), + variables: .init(color: ink), + values: .init(color: ink), + numbers: .init(color: ink), + strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint + characters: .init(color: ink), + comments: .init(color: dim) + ) + } +} + +// MARK: - Prose highlight pass (helm's MonokaiHighlighter pattern: wrap tree-sitter, add regex passes) + +/// Wraps the stock TreeSitterClient; after its captures, adds prose passes over markdown: +/// heading lines → bold capture, marker+inline-syntax runs → dim capture. Emphasis/anchor is NOT +/// done here — layer-backed Emphasis handles it. +final class ProseHighlighter: HighlightProviding { + private let wrapped = TreeSitterClient() + + func setUp(textView: TextView, codeLanguage: CodeLanguage) { + wrapped.setUp(textView: textView, codeLanguage: codeLanguage) + } + + func applyEdit( + textView: TextView, + range: NSRange, + delta: Int, + completion: @escaping @MainActor (Result) -> Void + ) { + wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion) + } + + func queryHighlightsFor( + textView: TextView, + range: NSRange, + completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void + ) { + wrapped.queryHighlightsFor(textView: textView, range: range) { result in + switch result { + case .failure(let error): + completion(.failure(error)) + case .success(let tsRanges): + var out = tsRanges + let ns = textView.string as NSString + let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range + out += Self.proseRanges(in: ns, range: safe) + completion(.success(out)) + } + } + } + + /// Pure: heading text → .type (bold via theme), heading marker + inline marks → .keyword (dim). + /// ponytail: line-scan regex, not an AST — corpus is plain prose markdown; enough for the spike. + static func proseRanges(in ns: NSString, range: NSRange) -> [HighlightRange] { + var out: [HighlightRange] = [] + ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in + guard let line, !line.isEmpty else { return } + if let markerLen = Self.headingMarkerLen(line) { + // heading text (after marker, same line) → bold capture + let textLen = lineRange.length - markerLen + if textLen > 0 { + out.append(HighlightRange( + range: NSRange(location: lineRange.location + markerLen, length: textLen), + capture: .type + )) + } + // marker → dim + out.append(HighlightRange( + range: NSRange(location: lineRange.location, length: markerLen), + capture: .keyword + )) + } else if line.hasPrefix(">") { + // quote line: text → tinted .string, markers dimmed + let textLen = lineRange.length - 1 + if textLen > 0 { + out.append(HighlightRange(range: NSRange(location: lineRange.location + 1, length: textLen), capture: .string)) + } + out.append(HighlightRange(range: NSRange(location: lineRange.location, length: 1), capture: .keyword)) + } else { + // inline syntax chars → dim, one run per char (runs merge at render) + let marks: Set = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < > + for (off, ch) in line.utf16.enumerated() where marks.contains(ch) { + out.append(HighlightRange( + range: NSRange(location: lineRange.location + off, length: 1), + capture: .keyword + )) + } + } + } + return out + } + + private static func headingMarkerLen(_ line: String) -> Int? { + guard line.hasPrefix("#") else { return nil } + let hashes = line.prefix { $0 == "#" }.count + guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil } + return hashes + 1 + } +} + +// MARK: - Quote anchor (identical algorithm to Spike B — same feasibility question) + +nonisolated enum AnchorSearch { + private struct Word { let norm: String; let range: Range } + private static func words(_ s: String) -> [Word] { + s.split(whereSeparator: \.isWhitespace).map { sub in + Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex) + } + } + + /// Word-tokenized whitespace/punctuation-tolerant search. nil = stale anchor. + static func range(of quote: String, in text: String) -> NSRange? { + let textWords = words(text) + let quoteWords = words(quote) + guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil } + for start in 0...(textWords.count - quoteWords.count) { + if (start..= 3, "FAIL: expected headings, got \(headingTexts.count)") + assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound }, + "FAIL: marker leaked into heading text") + // markers dimmed + assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") }, + "FAIL: heading marker not dimmed") + // anchor: live quote found; stale → nil; whitespace-tolerant + let quote = "\"I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.\"" + guard let r = AnchorSearch.range(of: quote, in: text) else { assert(false, "FAIL: live quote not found"); return } + assert((ns.substring(with: r) as NSString).length > 50) + let squished = quote.components(separatedBy: .newlines).joined(separator: " ") + assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance") + assert(AnchorSearch.range(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil") + // perf smoke: PERF-3k anchor timing + let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md") + if let perf = try? String(contentsOf: perfURL, encoding: .utf8) { + let t0 = DispatchTime.now() + _ = AnchorSearch.range(of: "The odds are better than they look", in: perf) + let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6 + print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms") + } else { + print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found") + } + } +} + +struct ContentView: View { + @State private var text: String + @State private var editorState = SourceEditorState() + @State private var reading = false + @State private var staleShown = false + @State private var loadMs: Double = 0 + @State private var anchorNote: String? + /// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern). + /// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox). + private let box = ControllerBox() + + init() { + // Repo root from compile-time path — launchd cwd is "/", so relative paths never hit. + let repoRoot = URL(fileURLWithPath: #filePath) // /spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md") + let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") }) + let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus + let t = (try? String(contentsOf: url, encoding: .utf8)) + ?? (try? String(contentsOf: corpus, encoding: .utf8)) + ?? "# Spike A\n\n(No corpus file found at \(corpus.path).)" + _text = State(initialValue: t) + } + + var body: some View { + VStack(spacing: 0) { + bar + Divider() + if reading { + // Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference) + ScrollView(.vertical) { + VStack(alignment: .leading, spacing: 14) { + ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in + Text(block.text) + .font(block.level > 0 + ? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif) + : .system(size: 17)) + } + } + .frame(maxWidth: 720, alignment: .leading) + .padding(.horizontal, 40) + .padding(.vertical, 24) + } + } else { + editor + } + } + .alert("Anchor not found", isPresented: $staleShown) { + Button("OK", role: .cancel) {} + } message: { + Text("The Post changed after this Fix Card was issued; no text was selected or changed.") + } + } + + private var editor: some View { + // Centered measure via maxWidth (iA-Writer approach; no GeometryReader — it proposes + // 0×0 to the AppKit leaf on first pass and the window never places in this shell). + SourceEditor( + $text, + language: .markdown, + configuration: config, + state: $editorState, + highlightProviders: [ProseHighlighter()], + coordinators: [ControllerCapture(onCapture: { box.controller = $0 })] + ) + .frame(maxWidth: 720) + .frame(maxWidth: .infinity) + .padding(.horizontal, 24) + } + + private var config: SourceEditorConfiguration { + SourceEditorConfiguration( + appearance: .init( + theme: ProseTheme.theme, + font: ProseTheme.bodyFont, + lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate) + wrapLines: true + ), + behavior: .init(reformatAtColumn: 10_000), // never hard-wrap prose + peripherals: .init( + showGutter: false, // no line numbers in a writing app + showMinimap: false, + showReformattingGuide: false, + showFoldingRibbon: false, + invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false), + warningCharacters: [] + ) + ) + } + + private var bar: some View { + HStack(spacing: 12) { + Toggle("Reading", isOn: $reading) + Divider().frame(height: 14) + Button("Anchor: DM quote") { applyAnchor("\"I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.\"") } + Button("Stale anchor") { applyAnchor("this quote was deleted from the text") } + if let note = anchorNote { Text(note).foregroundStyle(.secondary).font(.caption) } + Spacer() + Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + + private func applyAnchor(_ quote: String) { + let controller = box.controller + let t0 = DispatchTime.now() + let r = AnchorSearch.range(of: quote, in: text) + loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000 + guard let r else { + anchorNote = nil + staleShown = true + return + } + anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")" + guard let controller else { return } + // Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection. + controller.textView.emphasisManager?.replaceEmphases( + [Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))], + for: "fix-card-anchor" + ) + controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true) + } +} + +/// Captures the live TextViewController at prepareCoordinator (helm #160's captured-controller pattern). +/// Reference box, NOT @State: prepareCoordinator fires inside makeNSViewController — during SwiftUI's +/// view update — and @State writes there are silently dropped (root cause of the "(no ctrl!)" case). +final class ControllerBox: @unchecked Sendable { + var controller: TextViewController? +} +final class ControllerCapture: TextViewCoordinator { + let onCapture: (TextViewController) -> Void + init(onCapture: @escaping (TextViewController) -> Void) { self.onCapture = onCapture } + func prepareCoordinator(controller: TextViewController) { + onCapture(controller) + } +} + +// MARK: - Reading blocks (Spike B's proven per-block renderer; .full syntax) + +extension SpikeApp { + // ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none. + static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] { + md.components(separatedBy: "\n\n").map { para in + var level = 0 + var p = para.trimmingCharacters(in: .whitespacesAndNewlines) + if p.hasPrefix("#") { + let hashes = p.prefix { $0 == "#" }.count + p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces) + level = hashes + } + let attr = (try? AttributedString( + markdown: p, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + )) ?? AttributedString(p) + return (level, attr) + } + } +} + +// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build. +final class AppDelegate: NSObject, NSApplicationDelegate { + func applicationWillFinishLaunching(_ notification: Notification) { + NSApp.setActivationPolicy(.regular) + } + func applicationDidFinishLaunching(_ notification: Notification) { + NSApp.activate(ignoringOtherApps: true) + } +} diff --git a/spike/codeedit/assets/spikeA-anchor.png b/spike/codeedit/assets/spikeA-anchor.png new file mode 100644 index 0000000..878033f Binary files /dev/null and b/spike/codeedit/assets/spikeA-anchor.png differ diff --git a/spike/codeedit/assets/spikeA-calibration.png b/spike/codeedit/assets/spikeA-calibration.png new file mode 100644 index 0000000..b0b6449 Binary files /dev/null and b/spike/codeedit/assets/spikeA-calibration.png differ diff --git a/spike/codeedit/assets/spikeA-reading.png b/spike/codeedit/assets/spikeA-reading.png new file mode 100644 index 0000000..349319d Binary files /dev/null and b/spike/codeedit/assets/spikeA-reading.png differ diff --git a/spike/codeedit/assets/spikeA-stale.png b/spike/codeedit/assets/spikeA-stale.png new file mode 100644 index 0000000..17952e8 Binary files /dev/null and b/spike/codeedit/assets/spikeA-stale.png differ diff --git a/spike/codeedit/run.sh b/spike/codeedit/run.sh new file mode 100755 index 0000000..278efb9 --- /dev/null +++ b/spike/codeedit/run.sh @@ -0,0 +1,28 @@ +#!/bin/zsh +# ponytail: wrap the SPM binary in a minimal .app — SwiftUI needs a bundle to make windows, +# and CodeEditLanguages/Symbols resource bundles must ship inside it (NSBundle.module crash otherwise). +set -e +cd "$(dirname "$0")" +swift build 2>&1 | tail -1 +APP=.build/CodeEditSpike.app +rm -rf "$APP" && mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp .build/debug/CodeEditSpike "$APP/Contents/MacOS/" +for b in .build/debug/CodeEditLanguages_CodeEditLanguages.bundle .build/debug/CodeEditSymbols_CodeEditSymbols.bundle; do + cp -R "$b" "$APP/Contents/Resources/" 2>/dev/null || echo "warn: $b missing" +done +cat > "$APP/Contents/Info.plist" <<'PLIST' + + + + + CFBundleExecutableCodeEditSpike + CFBundleIdentifierde.babylondreams.museion.spike-a + CFBundleNameSpike A — CodeEdit fork + CFBundlePackageTypeAPPL + LSMinimumSystemVersion26.0 + NSHighResolutionCapable + + +PLIST +echo "built: $APP" +exec "$APP/Contents/MacOS/CodeEditSpike" "${@:-}"