diff --git a/spike/apexhtml/Package.swift b/spike/apexhtml/Package.swift new file mode 100644 index 0000000..eb53cd9 --- /dev/null +++ b/spike/apexhtml/Package.swift @@ -0,0 +1,8 @@ +// swift-tools-version:6.2 +import PackageDescription + +let package = Package( + name: "ApexHTMLSpike", + platforms: [.macOS(.v26)], + targets: [.executableTarget(name: "ApexHTMLSpike")] +) diff --git a/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift b/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift new file mode 100644 index 0000000..471f318 --- /dev/null +++ b/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift @@ -0,0 +1,406 @@ +// Spike (#74) — THROWAWAY. apex → HTML → WKWebView reading surface. +// Proves: data-source-line mapping, CSS-var typography, ⌘-click links, in-app apex latency, first paint. +import AppKit +import SwiftUI +import WebKit + +// MARK: - Mapping (pure, self-checked) + +/// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after. +enum MarkdownChunker { + /// Prepend `` (N = 1-based source line) before every blank-line chunk. + nonisolated static func stamp(_ source: String) -> String { + let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } } + let lines = source.split(separator: "\n", omittingEmptySubsequences: false) + var out: [String] = [] + var i = 0 + while i < lines.count { + if isBlank(lines[i]) { i += 1; continue } + if !out.isEmpty { out.append("") } + out.append("") + while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 } + } + return out.joined(separator: "\n") + } +} + +/// Rewrites `` into `data-source-line="N"` on the element that follows. +enum HTMLStamper { + nonisolated static func stamp(_ html: String) -> String { + let re = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#) + let ms = NSMutableString(string: html) + re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"") + return ms as String + } +} + +// MARK: - Apex runner + +enum Apex { + nonisolated static func binaryPath() -> String? { + if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env } + for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) { return p } + return nil + } + + /// markdown → HTML fragment with images embedded (base64). Returns (html, milliseconds). + nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) { + guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) } + let t0 = DispatchTime.now() + let p = Process() + p.executableURL = URL(fileURLWithPath: bin) + // --no-mixed-lists: apex default merges an ordered list after a bullet list into one