chore: swiftformat drift + xcode 27 settings leftovers
Format-only pass over spikes, the gate prototype, and three app
files (brace style, wrapping — no semantic change), plus the 4-line
pbxproj alignment finishing the Xcode 27 settings pass (test-target
deployment target parity with 8e70f69).
[Generated by AI]
This commit is contained in:
1 parent
8e70f69945
commit
d722820fc8
17 files changed
+1910
-1791
No files matched your search
@@ -331,7 +331,7 @@
|
|||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 26.5;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||||
MTL_FAST_MATH = YES;
|
MTL_FAST_MATH = YES;
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
@@ -391,7 +391,7 @@
|
|||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 26.5;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
MTL_FAST_MATH = YES;
|
MTL_FAST_MATH = YES;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
@@ -481,7 +481,7 @@
|
|||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 26.5;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 1.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
@@ -503,7 +503,7 @@
|
|||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
DEVELOPMENT_TEAM = 3M7APDAAC5;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 26.5;
|
MACOSX_DEPLOYMENT_TARGET = 27.0;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 1.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
|||||||
@@ -70,7 +70,8 @@ nonisolated enum ProfileBackup {
|
|||||||
// Age check against the newest existing snapshot (#15: skips record no
|
// Age check against the newest existing snapshot (#15: skips record no
|
||||||
// state; the normal age check governs retry).
|
// state; the normal age check governs retry).
|
||||||
if let newest = sortedSnapshots(in: backupsRoot).first,
|
if let newest = sortedSnapshots(in: backupsRoot).first,
|
||||||
now.timeIntervalSince(newest.timestamp) < snapshotInterval {
|
now.timeIntervalSince(newest.timestamp) < snapshotInterval
|
||||||
|
{
|
||||||
return .skippedFresh
|
return .skippedFresh
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -176,12 +176,12 @@ nonisolated enum ReadingPresenter {
|
|||||||
/// the bundle without any config).
|
/// the bundle without any config).
|
||||||
static func styleSheet() -> String {
|
static func styleSheet() -> String {
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
|
let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
|
||||||
.deletingLastPathComponent()
|
.deletingLastPathComponent()
|
||||||
.appendingPathComponent("Resources/reading.css")
|
.appendingPathComponent("Resources/reading.css")
|
||||||
if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
|
if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
|
||||||
return live
|
return live
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
return Bundle.main.path(forResource: "reading", ofType: "css").flatMap {
|
return Bundle.main.path(forResource: "reading", ofType: "css").flatMap {
|
||||||
try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8)
|
try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8)
|
||||||
|
|||||||
@@ -162,7 +162,6 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
|
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// MARK: WKNavigationDelegate
|
// MARK: WKNavigationDelegate
|
||||||
|
|
||||||
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
|
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
|
||||||
|
|||||||
@@ -29,13 +29,13 @@ func makeProfileFixture(at root: String) -> String {
|
|||||||
for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] {
|
for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] {
|
||||||
try? fileManager.createDirectory(
|
try? fileManager.createDirectory(
|
||||||
atPath: (profile as NSString).appendingPathComponent(dir),
|
atPath: (profile as NSString).appendingPathComponent(dir),
|
||||||
withIntermediateDirectories: true
|
withIntermediateDirectories: true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
func write(_ text: String, _ rel: String) {
|
func write(_ text: String, _ rel: String) {
|
||||||
try? text.write(
|
try? text.write(
|
||||||
toFile: (profile as NSString).appendingPathComponent(rel),
|
toFile: (profile as NSString).appendingPathComponent(rel),
|
||||||
atomically: true, encoding: .utf8
|
atomically: true, encoding: .utf8,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
write("{\"token\": \"secret\"}", "auth.json")
|
write("{\"token\": \"secret\"}", "auth.json")
|
||||||
|
|||||||
+442
-430
@@ -11,522 +11,534 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
// MARK: - Tokens (from ref/Web-Prototype/museion-workspace.html)
|
// MARK: - Tokens (from ref/Web-Prototype/museion-workspace.html)
|
||||||
enum Tok {
|
|
||||||
static let bg = Color(hex: 0xFAFAF7)
|
|
||||||
static let surface = Color(hex: 0xFFFFFF)
|
|
||||||
static let fg = Color(hex: 0x1A1916)
|
|
||||||
static let muted = Color(hex: 0x6B6964)
|
|
||||||
static let border = Color(hex: 0xE8E5DF)
|
|
||||||
static let accent = Color(hex: 0xC96442)
|
|
||||||
static let fgSoft = Color(hex: 0x1A1916).opacity(0.06)
|
|
||||||
static let accentSoft = Color(hex: 0xC96442).opacity(0.14)
|
|
||||||
|
|
||||||
static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
|
enum Tok {
|
||||||
.custom("Iowan Old Style", size: size).weight(weight)
|
static let bg = Color(hex: 0xFAFAF7)
|
||||||
}
|
static let surface = Color(hex: 0xFFFFFF)
|
||||||
static func mono(_ size: CGFloat) -> Font {
|
static let fg = Color(hex: 0x1A1916)
|
||||||
.system(size: size, design: .monospaced)
|
static let muted = Color(hex: 0x6B6964)
|
||||||
}
|
static let border = Color(hex: 0xE8E5DF)
|
||||||
|
static let accent = Color(hex: 0xC96442)
|
||||||
|
static let fgSoft = Color(hex: 0x1A1916).opacity(0.06)
|
||||||
|
static let accentSoft = Color(hex: 0xC96442).opacity(0.14)
|
||||||
|
|
||||||
|
static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
|
||||||
|
.custom("Iowan Old Style", size: size).weight(weight)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func mono(_ size: CGFloat) -> Font {
|
||||||
|
.system(size: size, design: .monospaced)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Color {
|
extension Color {
|
||||||
init(hex: UInt32) {
|
init(hex: UInt32) {
|
||||||
self.init(.sRGB,
|
self.init(.sRGB,
|
||||||
red: Double((hex >> 16) & 0xFF) / 255,
|
red: Double((hex >> 16) & 0xFF) / 255,
|
||||||
green: Double((hex >> 8) & 0xFF) / 255,
|
green: Double((hex >> 8) & 0xFF) / 255,
|
||||||
blue: Double(hex & 0xFF) / 255)
|
blue: Double(hex & 0xFF) / 255)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Mock state
|
// MARK: - Mock state
|
||||||
final class GateModel: ObservableObject {
|
|
||||||
enum Phase: Equatable { case checking, passed, failed }
|
|
||||||
@Published var phase: Phase = .checking
|
|
||||||
@Published var firstRun = true
|
|
||||||
@Published var nextPass = false // outcome of the NEXT check (scenario control)
|
|
||||||
let version = "0.42.1"
|
|
||||||
private var token = 0
|
|
||||||
|
|
||||||
func check() {
|
final class GateModel: ObservableObject {
|
||||||
token += 1
|
enum Phase: Equatable { case checking, passed, failed }
|
||||||
let myToken = token
|
@Published var phase: Phase = .checking
|
||||||
phase = .checking
|
@Published var firstRun = true
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
|
@Published var nextPass = false // outcome of the NEXT check (scenario control)
|
||||||
guard let self, self.token == myToken else { return }
|
let version = "0.42.1"
|
||||||
self.phase = self.nextPass ? .passed : .failed
|
private var token = 0
|
||||||
}
|
|
||||||
}
|
func check() {
|
||||||
|
token += 1
|
||||||
|
let myToken = token
|
||||||
|
phase = .checking
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
|
||||||
|
guard let self, token == myToken else { return }
|
||||||
|
phase = nextPass ? .passed : .failed
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Shared pieces
|
// MARK: - Shared pieces
|
||||||
|
|
||||||
struct EnginePill: View {
|
struct EnginePill: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
HStack(spacing: 7) {
|
HStack(spacing: 7) {
|
||||||
Circle()
|
Circle()
|
||||||
.fill(dotColor)
|
.fill(dotColor)
|
||||||
.frame(width: 7, height: 7)
|
.frame(width: 7, height: 7)
|
||||||
.modifier(Pulse(active: model.phase == .checking))
|
.modifier(Pulse(active: model.phase == .checking))
|
||||||
Text("Hermes")
|
Text("Hermes")
|
||||||
.font(Tok.mono(11))
|
.font(Tok.mono(11))
|
||||||
.foregroundStyle(Tok.fg)
|
.foregroundStyle(Tok.fg)
|
||||||
if model.phase == .passed {
|
if model.phase == .passed {
|
||||||
Text(model.version)
|
Text(model.version)
|
||||||
.font(Tok.mono(11))
|
.font(Tok.mono(11))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 10)
|
.padding(.horizontal, 10)
|
||||||
.frame(minHeight: 30)
|
.frame(minHeight: 30)
|
||||||
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
|
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
|
||||||
.overlay(
|
.overlay(
|
||||||
RoundedRectangle(cornerRadius: 10)
|
RoundedRectangle(cornerRadius: 10)
|
||||||
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1)
|
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var dotColor: Color {
|
private var dotColor: Color {
|
||||||
switch model.phase {
|
switch model.phase {
|
||||||
case .checking: Tok.accent
|
case .checking: Tok.accent
|
||||||
case .passed: Tok.fg
|
case .passed: Tok.fg
|
||||||
case .failed: Tok.accent
|
case .failed: Tok.accent
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Pulse: ViewModifier {
|
struct Pulse: ViewModifier {
|
||||||
let active: Bool
|
let active: Bool
|
||||||
func body(content: Content) -> some View {
|
func body(content: Content) -> some View {
|
||||||
if active {
|
if active {
|
||||||
content.opacity(0.35).animation(
|
content.opacity(0.35).animation(
|
||||||
Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
|
Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
|
||||||
value: active)
|
value: active,
|
||||||
} else {
|
)
|
||||||
content
|
} else {
|
||||||
}
|
content
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Placeholder install steps — the real copy is a graduated ticket, not this one.
|
/// Placeholder install steps — the real copy is a graduated ticket, not this one.
|
||||||
struct InstallSteps: View {
|
struct InstallSteps: View {
|
||||||
var numbered = true
|
var numbered = true
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(alignment: .leading, spacing: 7) {
|
VStack(alignment: .leading, spacing: 7) {
|
||||||
ForEach(Array(steps.enumerated()), id: \.offset) { idx, step in
|
ForEach(Array(steps.enumerated()), id: \.offset) { idx, step in
|
||||||
HStack(alignment: .top, spacing: 8) {
|
HStack(alignment: .top, spacing: 8) {
|
||||||
if numbered {
|
if numbered {
|
||||||
Text("\(idx + 1).").font(Tok.mono(11)).foregroundStyle(Tok.muted)
|
Text("\(idx + 1).").font(Tok.mono(11)).foregroundStyle(Tok.muted)
|
||||||
}
|
}
|
||||||
Text(step)
|
Text(step)
|
||||||
.font(.system(size: 12))
|
.font(.system(size: 12))
|
||||||
.foregroundStyle(Tok.fg)
|
.foregroundStyle(Tok.fg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
.padding(12)
|
.padding(12)
|
||||||
.background(Tok.bg, in: RoundedRectangle(cornerRadius: 10))
|
.background(Tok.bg, in: RoundedRectangle(cornerRadius: 10))
|
||||||
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Tok.border))
|
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Tok.border))
|
||||||
}
|
}
|
||||||
|
|
||||||
private var steps: [String] {
|
private var steps: [String] {
|
||||||
[
|
[
|
||||||
"Install Hermes: brew install hermes",
|
"Install Hermes: brew install hermes",
|
||||||
"Check the install: hermes acp --check",
|
"Check the install: hermes acp --check",
|
||||||
"Then click Re-check below.",
|
"Then click Re-check below.",
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct RecheckButton: View {
|
struct RecheckButton: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
var label = "Re-check"
|
var label = "Re-check"
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Button {
|
Button {
|
||||||
model.check()
|
model.check()
|
||||||
} label: {
|
} label: {
|
||||||
HStack(spacing: 6) {
|
HStack(spacing: 6) {
|
||||||
if model.phase == .checking {
|
if model.phase == .checking {
|
||||||
ProgressView().controlSize(.small)
|
ProgressView().controlSize(.small)
|
||||||
}
|
}
|
||||||
Text(model.phase == .checking ? "Checking…" : label)
|
Text(model.phase == .checking ? "Checking…" : label)
|
||||||
}
|
}
|
||||||
.frame(maxWidth: 180)
|
.frame(maxWidth: 180)
|
||||||
}
|
}
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
.tint(Tok.accent)
|
.tint(Tok.accent)
|
||||||
.disabled(model.phase == .checking)
|
.disabled(model.phase == .checking)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Mock workspace (context for the gate to sit over)
|
// MARK: - Mock workspace (context for the gate to sit over)
|
||||||
|
|
||||||
struct MockWorkspace: View {
|
struct MockWorkspace: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
var banner: AnyView? = nil
|
var banner: AnyView?
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
toolbar
|
toolbar
|
||||||
if let banner { banner }
|
if let banner {
|
||||||
HStack(spacing: 0) {
|
banner
|
||||||
rail
|
}
|
||||||
editor
|
HStack(spacing: 0) {
|
||||||
}
|
rail
|
||||||
}
|
editor
|
||||||
.background(Tok.bg)
|
}
|
||||||
}
|
}
|
||||||
|
.background(Tok.bg)
|
||||||
|
}
|
||||||
|
|
||||||
private var toolbar: some View {
|
private var toolbar: some View {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
Text("M")
|
Text("M")
|
||||||
.font(Tok.display(17, .semibold))
|
.font(Tok.display(17, .semibold))
|
||||||
.foregroundStyle(Tok.accent)
|
.foregroundStyle(Tok.accent)
|
||||||
.frame(width: 26, height: 26)
|
.frame(width: 26, height: 26)
|
||||||
.background(Tok.accentSoft, in: RoundedRectangle(cornerRadius: 7))
|
.background(Tok.accentSoft, in: RoundedRectangle(cornerRadius: 7))
|
||||||
Text("On rereading Orwell")
|
Text("On rereading Orwell")
|
||||||
.font(.system(size: 13))
|
.font(.system(size: 13))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
Spacer()
|
Spacer()
|
||||||
EnginePill()
|
EnginePill()
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 14)
|
.padding(.horizontal, 14)
|
||||||
.frame(height: 48)
|
.frame(height: 48)
|
||||||
.background(Tok.surface)
|
.background(Tok.surface)
|
||||||
.overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
|
.overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private var rail: some View {
|
private var rail: some View {
|
||||||
VStack(spacing: 6) {
|
VStack(spacing: 6) {
|
||||||
ForEach(["square.stack.3d.up", "bubble.left.and.bubble.right", "sparkles", "gearshape"], id: \.self) { icon in
|
ForEach(["square.stack.3d.up", "bubble.left.and.bubble.right", "sparkles", "gearshape"], id: \.self) { icon in
|
||||||
Image(systemName: icon)
|
Image(systemName: icon)
|
||||||
.font(.system(size: 15))
|
.font(.system(size: 15))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
.frame(width: 40, height: 40)
|
.frame(width: 40, height: 40)
|
||||||
}
|
}
|
||||||
Spacer()
|
Spacer()
|
||||||
}
|
}
|
||||||
.padding(.top, 10)
|
.padding(.top, 10)
|
||||||
.frame(width: 56)
|
.frame(width: 56)
|
||||||
.background(Tok.bg)
|
.background(Tok.bg)
|
||||||
.overlay(alignment: .trailing) { Divider().overlay(Tok.border) }
|
.overlay(alignment: .trailing) { Divider().overlay(Tok.border) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private var editor: some View {
|
private var editor: some View {
|
||||||
ScrollView {
|
ScrollView {
|
||||||
VStack(alignment: .leading, spacing: 18) {
|
VStack(alignment: .leading, spacing: 18) {
|
||||||
Text("On rereading Orwell")
|
Text("On rereading Orwell")
|
||||||
.font(Tok.display(26, .semibold))
|
.font(Tok.display(26, .semibold))
|
||||||
Text(previewText)
|
Text(previewText)
|
||||||
.font(.system(size: 14))
|
.font(.system(size: 14))
|
||||||
.foregroundStyle(Tok.fg)
|
.foregroundStyle(Tok.fg)
|
||||||
.lineSpacing(5)
|
.lineSpacing(5)
|
||||||
}
|
}
|
||||||
.padding(36)
|
.padding(36)
|
||||||
.frame(maxWidth: 720, alignment: .leading)
|
.frame(maxWidth: 720, alignment: .leading)
|
||||||
.frame(maxWidth: .infinity, alignment: .center)
|
.frame(maxWidth: .infinity, alignment: .center)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var previewText: String {
|
private var previewText: String {
|
||||||
String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6)
|
String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Variant A — blocking sheet, every launch
|
// MARK: - Variant A — blocking sheet, every launch
|
||||||
|
|
||||||
struct VariantA: View {
|
struct VariantA: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
@State private var showSteps = false
|
@State private var showSteps = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ZStack {
|
ZStack {
|
||||||
MockWorkspace().disabled(true)
|
MockWorkspace().disabled(true)
|
||||||
Rectangle().fill(Tok.fg.opacity(0.28)).ignoresSafeArea()
|
Rectangle().fill(Tok.fg.opacity(0.28)).ignoresSafeArea()
|
||||||
card
|
card
|
||||||
.padding(30)
|
.padding(30)
|
||||||
.frame(maxWidth: 430)
|
.frame(maxWidth: 430)
|
||||||
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
|
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
|
||||||
.overlay(
|
.overlay(
|
||||||
RoundedRectangle(cornerRadius: 14)
|
RoundedRectangle(cornerRadius: 14)
|
||||||
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1)
|
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
|
||||||
)
|
)
|
||||||
.shadow(radius: 24, y: 8)
|
.shadow(radius: 24, y: 8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var card: some View {
|
private var card: some View {
|
||||||
VStack(spacing: 14) {
|
VStack(spacing: 14) {
|
||||||
Image(systemName: model.phase == .failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
|
Image(systemName: model.phase == .failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
|
||||||
.font(.system(size: 30))
|
.font(.system(size: 30))
|
||||||
.foregroundStyle(model.phase == .failed ? Tok.accent : Tok.fg)
|
.foregroundStyle(model.phase == .failed ? Tok.accent : Tok.fg)
|
||||||
.opacity(model.phase == .checking ? 0 : 1)
|
.opacity(model.phase == .checking ? 0 : 1)
|
||||||
|
|
||||||
Text(title)
|
Text(title)
|
||||||
.font(Tok.display(19, .semibold))
|
.font(Tok.display(19, .semibold))
|
||||||
.multilineTextAlignment(.center)
|
.multilineTextAlignment(.center)
|
||||||
|
|
||||||
Text(subtitle)
|
Text(subtitle)
|
||||||
.font(.system(size: 12.5))
|
.font(.system(size: 12.5))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
.multilineTextAlignment(.center)
|
.multilineTextAlignment(.center)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
|
||||||
if model.phase == .failed {
|
if model.phase == .failed {
|
||||||
if showSteps {
|
if showSteps {
|
||||||
InstallSteps()
|
InstallSteps()
|
||||||
} else {
|
} else {
|
||||||
Button("How do I install Hermes?") { showSteps = true }
|
Button("How do I install Hermes?") { showSteps = true }
|
||||||
.buttonStyle(.link)
|
.buttonStyle(.link)
|
||||||
.font(.system(size: 12))
|
.font(.system(size: 12))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
RecheckButton(label: model.phase == .passed ? "Re-check anyway" : "Re-check")
|
RecheckButton(label: model.phase == .passed ? "Re-check anyway" : "Re-check")
|
||||||
|
|
||||||
if model.phase == .passed {
|
if model.phase == .passed {
|
||||||
Text("Checked on launch · Hermes \(model.version)")
|
Text("Checked on launch · Hermes \(model.version)")
|
||||||
.font(Tok.mono(10))
|
.font(Tok.mono(10))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(24)
|
.padding(24)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var title: String {
|
private var title: String {
|
||||||
switch model.phase {
|
switch model.phase {
|
||||||
case .checking: "Checking the engine…"
|
case .checking: "Checking the engine…"
|
||||||
case .passed: "Engine ready"
|
case .passed: "Engine ready"
|
||||||
case .failed: "Museion needs its engine"
|
case .failed: "Museion needs its engine"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var subtitle: String {
|
private var subtitle: String {
|
||||||
switch model.phase {
|
switch model.phase {
|
||||||
case .checking: "Running hermes acp --check."
|
case .checking: "Running hermes acp --check."
|
||||||
case .passed: "Hermes \(model.version) answered the health check. The mentor is available."
|
case .passed: "Hermes \(model.version) answered the health check. The mentor is available."
|
||||||
case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available."
|
case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Variant B — gate window (first run), pill (repeat runs)
|
// MARK: - Variant B — gate window (first run), pill (repeat runs)
|
||||||
struct VariantB: View {
|
|
||||||
@EnvironmentObject var model: GateModel
|
|
||||||
|
|
||||||
var body: some View {
|
struct VariantB: View {
|
||||||
if model.firstRun {
|
@EnvironmentObject var model: GateModel
|
||||||
GateWindow()
|
|
||||||
} else {
|
var body: some View {
|
||||||
MockWorkspace()
|
if model.firstRun {
|
||||||
}
|
GateWindow()
|
||||||
}
|
} else {
|
||||||
|
MockWorkspace()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private struct GateWindow: View {
|
private struct GateWindow: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
Spacer(minLength: 40)
|
Spacer(minLength: 40)
|
||||||
VStack(spacing: 16) {
|
VStack(spacing: 16) {
|
||||||
Text("Museion")
|
Text("Museion")
|
||||||
.font(Tok.display(34, .semibold))
|
.font(Tok.display(34, .semibold))
|
||||||
Text("The Agentic Writing Environment")
|
Text("The Agentic Writing Environment")
|
||||||
.font(Tok.mono(11))
|
.font(Tok.mono(11))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
.textCase(.uppercase)
|
.textCase(.uppercase)
|
||||||
|
|
||||||
Divider().frame(width: 60).overlay(Tok.border)
|
Divider().frame(width: 60).overlay(Tok.border)
|
||||||
|
|
||||||
status
|
status
|
||||||
|
|
||||||
if model.phase == .failed {
|
if model.phase == .failed {
|
||||||
InstallSteps()
|
InstallSteps()
|
||||||
}
|
}
|
||||||
if model.phase == .passed {
|
if model.phase == .passed {
|
||||||
Text("First run complete — the workspace opens next.")
|
Text("First run complete — the workspace opens next.")
|
||||||
.font(.system(size: 12))
|
.font(.system(size: 12))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(34)
|
.padding(34)
|
||||||
.frame(maxWidth: 470)
|
.frame(maxWidth: 470)
|
||||||
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
|
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
|
||||||
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tok.border))
|
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tok.border))
|
||||||
.shadow(radius: 18, y: 6)
|
.shadow(radius: 18, y: 6)
|
||||||
Spacer(minLength: 40)
|
Spacer(minLength: 40)
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
.background(Tok.bg)
|
.background(Tok.bg)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder private var status: some View {
|
@ViewBuilder private var status: some View {
|
||||||
switch model.phase {
|
switch model.phase {
|
||||||
case .checking:
|
case .checking:
|
||||||
VStack(spacing: 10) {
|
VStack(spacing: 10) {
|
||||||
ProgressView().controlSize(.regular)
|
ProgressView().controlSize(.regular)
|
||||||
Text("Looking for the Hermes engine…")
|
Text("Looking for the Hermes engine…")
|
||||||
.font(.system(size: 13))
|
.font(.system(size: 13))
|
||||||
.foregroundStyle(Tok.muted)
|
.foregroundStyle(Tok.muted)
|
||||||
}
|
}
|
||||||
case .passed:
|
case .passed:
|
||||||
VStack(spacing: 10) {
|
VStack(spacing: 10) {
|
||||||
Image(systemName: "checkmark.circle.fill")
|
Image(systemName: "checkmark.circle.fill")
|
||||||
.font(.system(size: 26))
|
.font(.system(size: 26))
|
||||||
.foregroundStyle(Tok.fg)
|
.foregroundStyle(Tok.fg)
|
||||||
Text("Engine ready — Hermes \(model.version)")
|
Text("Engine ready — Hermes \(model.version)")
|
||||||
.font(Tok.display(15, .semibold))
|
.font(Tok.display(15, .semibold))
|
||||||
}
|
}
|
||||||
case .failed:
|
case .failed:
|
||||||
VStack(spacing: 10) {
|
VStack(spacing: 10) {
|
||||||
Image(systemName: "exclamationmark.triangle.fill")
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
.font(.system(size: 26))
|
.font(.system(size: 26))
|
||||||
.foregroundStyle(Tok.accent)
|
.foregroundStyle(Tok.accent)
|
||||||
Text("Engine missing")
|
Text("Engine missing")
|
||||||
.font(Tok.display(15, .semibold))
|
.font(Tok.display(15, .semibold))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Variant C — inline banner, never blocks
|
// MARK: - Variant C — inline banner, never blocks
|
||||||
|
|
||||||
struct VariantC: View {
|
struct VariantC: View {
|
||||||
@EnvironmentObject var model: GateModel
|
@EnvironmentObject var model: GateModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
MockWorkspace(banner: AnyView(banner))
|
MockWorkspace(banner: AnyView(banner))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder private var banner: some View {
|
@ViewBuilder private var banner: some View {
|
||||||
if model.phase == .failed {
|
if model.phase == .failed {
|
||||||
failBanner
|
failBanner
|
||||||
} else if model.firstRun, model.phase == .passed {
|
} else if model.firstRun, model.phase == .passed {
|
||||||
passBanner
|
passBanner
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var failBanner: some View {
|
private var failBanner: some View {
|
||||||
HStack(alignment: .top, spacing: 12) {
|
HStack(alignment: .top, spacing: 12) {
|
||||||
Image(systemName: "exclamationmark.triangle.fill")
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
.foregroundStyle(Tok.accent)
|
.foregroundStyle(Tok.accent)
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
(Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold))
|
Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold))
|
||||||
+ Text("Passes and Sessions need Hermes; the editor keeps working.")
|
+ Text("Passes and Sessions need Hermes; the editor keeps working.")
|
||||||
.font(.system(size: 12.5))
|
.font(.system(size: 12.5))
|
||||||
.foregroundStyle(Tok.muted))
|
.foregroundStyle(Tok.muted)
|
||||||
InstallSteps()
|
InstallSteps()
|
||||||
}
|
}
|
||||||
Spacer(minLength: 12)
|
Spacer(minLength: 12)
|
||||||
RecheckButton()
|
RecheckButton()
|
||||||
}
|
}
|
||||||
.padding(14)
|
.padding(14)
|
||||||
.background(Tok.accent.opacity(0.08))
|
.background(Tok.accent.opacity(0.08))
|
||||||
.overlay(alignment: .bottom) { Rectangle().fill(Tok.accent).frame(height: 1) }
|
.overlay(alignment: .bottom) { Rectangle().fill(Tok.accent).frame(height: 1) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private var passBanner: some View {
|
private var passBanner: some View {
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
Image(systemName: "checkmark.circle.fill").foregroundStyle(Tok.fg)
|
Image(systemName: "checkmark.circle.fill").foregroundStyle(Tok.fg)
|
||||||
Text("Engine ready — Hermes \(model.version)")
|
Text("Engine ready — Hermes \(model.version)")
|
||||||
.font(.system(size: 12.5))
|
.font(.system(size: 12.5))
|
||||||
Spacer()
|
Spacer()
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 14).padding(.vertical, 8)
|
.padding(.horizontal, 14).padding(.vertical, 8)
|
||||||
.background(Tok.surface)
|
.background(Tok.surface)
|
||||||
.overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
|
.overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Root + switcher
|
// MARK: - Root + switcher
|
||||||
|
|
||||||
struct GatePrototypeRoot: View {
|
struct GatePrototypeRoot: View {
|
||||||
@StateObject private var model = GateModel()
|
@StateObject private var model = GateModel()
|
||||||
@State private var variant = "A"
|
@State private var variant = "A"
|
||||||
let variants: [(String, String)] = [
|
let variants: [(String, String)] = [
|
||||||
("A", "Blocking sheet"),
|
("A", "Blocking sheet"),
|
||||||
("B", "Gate window"),
|
("B", "Gate window"),
|
||||||
("C", "Inline banner"),
|
("C", "Inline banner"),
|
||||||
]
|
]
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ZStack(alignment: .bottom) {
|
ZStack(alignment: .bottom) {
|
||||||
currentView.environmentObject(model)
|
currentView.environmentObject(model)
|
||||||
SwitcherBar(variant: $variant, model: model)
|
SwitcherBar(variant: $variant, model: model)
|
||||||
}
|
}
|
||||||
.frame(minWidth: 1100, minHeight: 680)
|
.frame(minWidth: 1100, minHeight: 680)
|
||||||
.background(Tok.bg)
|
.background(Tok.bg)
|
||||||
.onAppear { model.check() }
|
.onAppear { model.check() }
|
||||||
}
|
}
|
||||||
|
|
||||||
private var currentView: some View {
|
private var currentView: some View {
|
||||||
switch variant {
|
switch variant {
|
||||||
case "A": AnyView(VariantA())
|
case "A": AnyView(VariantA())
|
||||||
case "B": AnyView(VariantB())
|
case "B": AnyView(VariantB())
|
||||||
default: AnyView(VariantC())
|
default: AnyView(VariantC())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct SwitcherBar: View {
|
struct SwitcherBar: View {
|
||||||
@Binding var variant: String
|
@Binding var variant: String
|
||||||
@ObservedObject var model: GateModel
|
@ObservedObject var model: GateModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
HStack(spacing: 14) {
|
HStack(spacing: 14) {
|
||||||
arrow("chevron.left") { cycle(-1) }
|
arrow("chevron.left") { cycle(-1) }
|
||||||
.keyboardShortcut(.leftArrow, modifiers: [])
|
.keyboardShortcut(.leftArrow, modifiers: [])
|
||||||
Text("\(variant) — \(variants.first { $0.0 == variant }?.1 ?? "")")
|
Text("\(variant) — \(variants.first { $0.0 == variant }?.1 ?? "")")
|
||||||
.font(Tok.mono(12))
|
.font(Tok.mono(12))
|
||||||
arrow("chevron.right") { cycle(1) }
|
arrow("chevron.right") { cycle(1) }
|
||||||
.keyboardShortcut(.rightArrow, modifiers: [])
|
.keyboardShortcut(.rightArrow, modifiers: [])
|
||||||
|
|
||||||
Divider().frame(height: 16).overlay(Tok.border)
|
Divider().frame(height: 16).overlay(Tok.border)
|
||||||
Toggle("First run", isOn: $model.firstRun)
|
Toggle("First run", isOn: $model.firstRun)
|
||||||
.toggleStyle(.checkbox).font(Tok.mono(11))
|
.toggleStyle(.checkbox).font(Tok.mono(11))
|
||||||
Toggle("Next check passes", isOn: $model.nextPass)
|
Toggle("Next check passes", isOn: $model.nextPass)
|
||||||
.toggleStyle(.checkbox).font(Tok.mono(11))
|
.toggleStyle(.checkbox).font(Tok.mono(11))
|
||||||
Divider().frame(height: 16).overlay(Tok.border)
|
Divider().frame(height: 16).overlay(Tok.border)
|
||||||
Text(phaseLabel)
|
Text(phaseLabel)
|
||||||
.font(Tok.mono(11)).foregroundStyle(.tertiary)
|
.font(Tok.mono(11)).foregroundStyle(.tertiary)
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 14).padding(.vertical, 9)
|
.padding(.horizontal, 14).padding(.vertical, 9)
|
||||||
.background(Tok.fg, in: RoundedRectangle(cornerRadius: 10))
|
.background(Tok.fg, in: RoundedRectangle(cornerRadius: 10))
|
||||||
.foregroundStyle(Tok.bg)
|
.foregroundStyle(Tok.bg)
|
||||||
.padding(.bottom, 14)
|
.padding(.bottom, 14)
|
||||||
.shadow(radius: 12, y: 4)
|
.shadow(radius: 12, y: 4)
|
||||||
.onAppear { NSApp.appearance = NSAppearance(named: .aqua) } // prototype: force light so tokens read as designed
|
.onAppear { NSApp.appearance = NSAppearance(named: .aqua) } // prototype: force light so tokens read as designed
|
||||||
}
|
}
|
||||||
|
|
||||||
private var variants: [(String, String)] {
|
private var variants: [(String, String)] {
|
||||||
[("A", "Blocking sheet"), ("B", "Gate window"), ("C", "Inline banner")]
|
[("A", "Blocking sheet"), ("B", "Gate window"), ("C", "Inline banner")]
|
||||||
}
|
}
|
||||||
|
|
||||||
private var phaseLabel: String {
|
private var phaseLabel: String {
|
||||||
switch model.phase {
|
switch model.phase {
|
||||||
case .checking: "checking"
|
case .checking: "checking"
|
||||||
case .passed: "passed · hermes \(model.version)"
|
case .passed: "passed · hermes \(model.version)"
|
||||||
case .failed: "failed"
|
case .failed: "failed"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func cycle(_ dir: Int) {
|
private func cycle(_ dir: Int) {
|
||||||
let idx = variants.firstIndex { $0.0 == variant } ?? 0
|
let idx = variants.firstIndex { $0.0 == variant } ?? 0
|
||||||
variant = variants[(idx + dir + variants.count) % variants.count].0
|
variant = variants[(idx + dir + variants.count) % variants.count].0
|
||||||
}
|
}
|
||||||
|
|
||||||
private func arrow(_ system: String, action: @escaping () -> Void) -> some View {
|
private func arrow(_ system: String, action: @escaping () -> Void) -> some View {
|
||||||
Button(action: action) {
|
Button(action: action) {
|
||||||
Image(systemName: system).font(.system(size: 11, weight: .semibold))
|
Image(systemName: system).font(.system(size: 11, weight: .semibold))
|
||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@main
|
@main
|
||||||
struct GateUIPrototypeApp: App {
|
struct GateUIPrototypeApp: App {
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup { GatePrototypeRoot() }
|
WindowGroup { GatePrototypeRoot() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "ApexHTMLSpike",
|
name: "ApexHTMLSpike",
|
||||||
platforms: [.macOS(.v26)],
|
platforms: [.macOS(.v26)],
|
||||||
targets: [.executableTarget(name: "ApexHTMLSpike")]
|
targets: [.executableTarget(name: "ApexHTMLSpike")],
|
||||||
)
|
)
|
||||||
@@ -8,399 +8,444 @@ import WebKit
|
|||||||
|
|
||||||
/// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after.
|
/// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after.
|
||||||
enum MarkdownChunker {
|
enum MarkdownChunker {
|
||||||
/// Prepend `<!--S:N-->` (N = 1-based source line) before every blank-line chunk.
|
/// Prepend `<!--S:N-->` (N = 1-based source line) before every blank-line chunk.
|
||||||
nonisolated static func stamp(_ source: String) -> String {
|
nonisolated static func stamp(_ source: String) -> String {
|
||||||
let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
|
let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
|
||||||
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
|
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
|
||||||
var out: [String] = []
|
var out: [String] = []
|
||||||
var i = 0
|
var i = 0
|
||||||
while i < lines.count {
|
while i < lines.count {
|
||||||
if isBlank(lines[i]) { i += 1; continue }
|
if isBlank(lines[i]) {
|
||||||
if !out.isEmpty { out.append("") }
|
i += 1; continue
|
||||||
out.append("<!--S:\(i + 1)-->")
|
}
|
||||||
while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 }
|
if !out.isEmpty {
|
||||||
}
|
out.append("")
|
||||||
return out.joined(separator: "\n")
|
}
|
||||||
}
|
out.append("<!--S:\(i + 1)-->")
|
||||||
|
while i < lines.count, !isBlank(lines[i]) {
|
||||||
|
out.append(String(lines[i])); i += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.joined(separator: "\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rewrites `<!--S:N-->` into `data-source-line="N"` on the element that follows.
|
/// Rewrites `<!--S:N-->` into `data-source-line="N"` on the element that follows.
|
||||||
enum HTMLStamper {
|
enum HTMLStamper {
|
||||||
nonisolated static func stamp(_ html: String) -> String {
|
nonisolated static func stamp(_ html: String) -> String {
|
||||||
let re = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
|
let re = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
|
||||||
let ms = NSMutableString(string: html)
|
let ms = NSMutableString(string: html)
|
||||||
re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
||||||
return ms as String
|
return ms as String
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Apex runner
|
// MARK: - Apex runner
|
||||||
|
|
||||||
enum Apex {
|
enum Apex {
|
||||||
nonisolated static func binaryPath() -> String? {
|
nonisolated static func binaryPath() -> String? {
|
||||||
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env }
|
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
|
||||||
for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) { return p }
|
return env
|
||||||
return nil
|
}
|
||||||
}
|
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).
|
/// markdown → HTML fragment with images embedded (base64). Returns (html, milliseconds).
|
||||||
nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) {
|
nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) {
|
||||||
guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) }
|
guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) }
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
let p = Process()
|
let p = Process()
|
||||||
p.executableURL = URL(fileURLWithPath: bin)
|
p.executableURL = URL(fileURLWithPath: bin)
|
||||||
// --no-mixed-lists: apex default merges an ordered list after a bullet list into one <ul> — kills `1. 1. 1.` renumbering.
|
// --no-mixed-lists: apex default merges an ordered list after a bullet list into one <ul> — kills `1. 1. 1.` renumbering.
|
||||||
// --embed-images: apex inlines images as base64 data URLs (base-dir resolves the
|
// --embed-images: apex inlines images as base64 data URLs (base-dir resolves the
|
||||||
// relative paths on our stdin flow) — WKWebView then needs NO file access at all.
|
// relative paths on our stdin flow) — WKWebView then needs NO file access at all.
|
||||||
p.arguments = ["-t", "html", "--no-mixed-lists", "--embed-images", "--base-dir", baseDir.path]
|
p.arguments = ["-t", "html", "--no-mixed-lists", "--embed-images", "--base-dir", baseDir.path]
|
||||||
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
||||||
p.standardInput = stdin; p.standardOutput = stdout; p.standardError = stderr
|
p.standardInput = stdin; p.standardOutput = stdout; p.standardError = stderr
|
||||||
try p.run()
|
try p.run()
|
||||||
stdin.fileHandleForWriting.write(Data(markdown.utf8))
|
stdin.fileHandleForWriting.write(Data(markdown.utf8))
|
||||||
stdin.fileHandleForWriting.closeFile()
|
stdin.fileHandleForWriting.closeFile()
|
||||||
let data = stdout.fileHandleForReading.readDataToEndOfFile()
|
let data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||||
// stdout EOF = conversion done (~18 ms). The ~65 ms after is apex's own teardown —
|
// stdout EOF = conversion done (~18 ms). The ~65 ms after is apex's own teardown —
|
||||||
// don't wait for it: reap via terminationHandler, hand the HTML over immediately.
|
// don't wait for it: reap via terminationHandler, hand the HTML over immediately.
|
||||||
guard !data.isEmpty else {
|
guard !data.isEmpty else {
|
||||||
p.waitUntilExit()
|
p.waitUntilExit()
|
||||||
throw NSError(domain: "apex", code: Int(p.terminationStatus),
|
throw NSError(domain: "apex", code: Int(p.terminationStatus),
|
||||||
userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"])
|
userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"])
|
||||||
}
|
}
|
||||||
p.terminationHandler = { _ in }
|
p.terminationHandler = { _ in }
|
||||||
return (String(decoding: data, as: UTF8.self), ms)
|
return (String(decoding: data, as: UTF8.self), ms)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Reading surface
|
// MARK: - Reading surface
|
||||||
|
|
||||||
struct ReadingWebView: NSViewRepresentable {
|
struct ReadingWebView: NSViewRepresentable {
|
||||||
let fileURL: URL
|
let fileURL: URL
|
||||||
var onStats: (Stats) -> Void
|
var onStats: (Stats) -> Void
|
||||||
var onSourceLine: (String, Int) -> Void // ("click"|"top", line)
|
var onSourceLine: (String, Int) -> Void // ("click"|"top", line)
|
||||||
|
|
||||||
struct Stats: Equatable {
|
struct Stats: Equatable {
|
||||||
var apexMS: Double = 0
|
var apexMS: Double = 0
|
||||||
var paintMS: Double = 0
|
var paintMS: Double = 0
|
||||||
var htmlBytes: Int = 0
|
var htmlBytes: Int = 0
|
||||||
var error: String?
|
var error: String?
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeNSView(context: Context) -> WKWebView {
|
func makeNSView(context: Context) -> WKWebView {
|
||||||
let cfg = WKWebViewConfiguration()
|
let cfg = WKWebViewConfiguration()
|
||||||
let ucc = cfg.userContentController
|
let ucc = cfg.userContentController
|
||||||
ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
|
ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
|
||||||
ucc.add(context.coordinator, name: "sourceClick")
|
ucc.add(context.coordinator, name: "sourceClick")
|
||||||
ucc.add(context.coordinator, name: "sourceScroll")
|
ucc.add(context.coordinator, name: "sourceScroll")
|
||||||
ucc.add(context.coordinator, name: "openLink")
|
ucc.add(context.coordinator, name: "openLink")
|
||||||
let wv = WKWebView(frame: .zero, configuration: cfg)
|
let wv = WKWebView(frame: .zero, configuration: cfg)
|
||||||
wv.navigationDelegate = context.coordinator
|
wv.navigationDelegate = context.coordinator
|
||||||
// Kill the white reload flash: paint the page bg while loading instead of AppKit white.
|
// Kill the white reload flash: paint the page bg while loading instead of AppKit white.
|
||||||
wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1) // #fbfbfd
|
wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1) // #fbfbfd
|
||||||
context.coordinator.webView = wv
|
context.coordinator.webView = wv
|
||||||
return wv
|
return wv
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateNSView(_ wv: WKWebView, context: Context) {
|
func updateNSView(_ wv: WKWebView, context: Context) {
|
||||||
guard context.coordinator.loadedURL != fileURL else { return }
|
guard context.coordinator.loadedURL != fileURL else { return }
|
||||||
context.coordinator.loadedURL = fileURL
|
context.coordinator.loadedURL = fileURL
|
||||||
render(into: wv, coordinator: context.coordinator)
|
render(into: wv, coordinator: context.coordinator)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func render(into wv: WKWebView, coordinator: Coordinator) {
|
private func render(into wv: WKWebView, coordinator: Coordinator) {
|
||||||
let url = fileURL
|
let url = fileURL
|
||||||
Task {
|
Task {
|
||||||
var stats = Stats()
|
var stats = Stats()
|
||||||
do {
|
do {
|
||||||
let source = try String(contentsOf: url, encoding: .utf8)
|
let source = try String(contentsOf: url, encoding: .utf8)
|
||||||
let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
|
let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
|
||||||
stats.apexMS = ms
|
stats.apexMS = ms
|
||||||
stats.htmlBytes = html.utf8.count
|
stats.htmlBytes = html.utf8.count
|
||||||
// loadHTMLString fast path is safe again: images are base64 data URLs now,
|
// loadHTMLString fast path is safe again: images are base64 data URLs now,
|
||||||
// no file:// subresources → no restricted-origin block, no sandbox negotiation.
|
// no file:// subresources → no restricted-origin block, no sandbox negotiation.
|
||||||
coordinator.paintStart = DispatchTime.now()
|
coordinator.paintStart = DispatchTime.now()
|
||||||
wv.loadHTMLString(Self.page(html: HTMLStamper.stamp(html)), baseURL: nil)
|
wv.loadHTMLString(Self.page(html: HTMLStamper.stamp(html)), baseURL: nil)
|
||||||
} catch {
|
} catch {
|
||||||
stats.error = String(describing: error)
|
stats.error = String(describing: error)
|
||||||
}
|
}
|
||||||
onStats(stats)
|
onStats(stats)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71).
|
/// CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71).
|
||||||
static let css = """
|
static let css = """
|
||||||
:root {
|
:root {
|
||||||
--body-face: "Concourse OT", "Iowan Old Style", serif;
|
--body-face: "Concourse OT", "Iowan Old Style", serif;
|
||||||
--body-size: 17px;
|
--body-size: 17px;
|
||||||
--headings-face: "Iowan Old Style", serif;
|
--headings-face: "Iowan Old Style", serif;
|
||||||
--headings-size: 26px;
|
--headings-size: 26px;
|
||||||
--code-face: "UbuntuMono Nerd Font Mono", "UbuntuMonoNFM", monospace;
|
--code-face: "UbuntuMono Nerd Font Mono", "UbuntuMonoNFM", monospace;
|
||||||
--code-size: 13px;
|
--code-size: 13px;
|
||||||
--lh: 1.25;
|
--lh: 1.25;
|
||||||
--para-space: 17px; /* 1 line */
|
--para-space: 17px; /* 1 line */
|
||||||
--head-space: 34px; /* 2 lines */
|
--head-space: 34px; /* 2 lines */
|
||||||
--measure: 640px;
|
--measure: 640px;
|
||||||
--ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
|
--ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
|
||||||
}
|
}
|
||||||
html { background: #fbfbfd; }
|
html { background: #fbfbfd; }
|
||||||
body {
|
body {
|
||||||
margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
|
margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
|
||||||
color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
|
color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
|
||||||
line-height: var(--lh); -webkit-font-smoothing: antialiased;
|
line-height: var(--lh); -webkit-font-smoothing: antialiased;
|
||||||
}
|
}
|
||||||
p { margin: var(--para-space) 0 0; }
|
p { margin: var(--para-space) 0 0; }
|
||||||
h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
|
h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
|
||||||
h1 { font-size: var(--headings-size); }
|
h1 { font-size: var(--headings-size); }
|
||||||
h2 { font-size: calc(var(--headings-size) * 0.77); }
|
h2 { font-size: calc(var(--headings-size) * 0.77); }
|
||||||
h3 { font-size: calc(var(--body-size) + 1px); }
|
h3 { font-size: calc(var(--body-size) + 1px); }
|
||||||
h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
|
h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
|
||||||
ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
|
ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
|
||||||
li { margin: 0; }
|
li { margin: 0; }
|
||||||
li > ul, li > ol { margin: 0; }
|
li > ul, li > ol { margin: 0; }
|
||||||
pre { font-family: var(--code-face); font-size: var(--code-size); margin: var(--para-space) 0 0;
|
pre { font-family: var(--code-face); font-size: var(--code-size); margin: var(--para-space) 0 0;
|
||||||
padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
|
padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
|
||||||
code { font-family: var(--code-face); font-size: var(--code-size); }
|
code { font-family: var(--code-face); font-size: var(--code-size); }
|
||||||
blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
|
blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
|
||||||
blockquote p { margin: 0; }
|
blockquote p { margin: 0; }
|
||||||
hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
|
hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
|
||||||
a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
|
a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
|
||||||
table { border-collapse: collapse; margin: var(--para-space) 0 0; }
|
table { border-collapse: collapse; margin: var(--para-space) 0 0; }
|
||||||
th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
|
th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
|
||||||
figure { margin: var(--para-space) 0 0; }
|
figure { margin: var(--para-space) 0 0; }
|
||||||
figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
|
figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
|
||||||
figure:hover img { max-height: 420px; }
|
figure:hover img { max-height: 420px; }
|
||||||
figcaption { display: none; }
|
figcaption { display: none; }
|
||||||
[data-source-line]:hover { background: rgba(0,122,255,.05); }
|
[data-source-line]:hover { background: rgba(0,122,255,.05); }
|
||||||
"""
|
"""
|
||||||
|
|
||||||
static func page(html: String) -> String {
|
static func page(html: String) -> String {
|
||||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(css)</style></head><body>\(html)</body></html>"
|
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(css)</style></head><body>\(html)</body></html>"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line.
|
/// Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line.
|
||||||
static let probeJS = """
|
static let probeJS = """
|
||||||
function stamped(el){ return el.closest('[data-source-line]'); }
|
function stamped(el){ return el.closest('[data-source-line]'); }
|
||||||
document.addEventListener('click', function(e){
|
document.addEventListener('click', function(e){
|
||||||
const a = e.target.closest('a');
|
const a = e.target.closest('a');
|
||||||
if (a) {
|
if (a) {
|
||||||
e.preventDefault(); // reading never navigates in-app
|
e.preventDefault(); // reading never navigates in-app
|
||||||
if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
|
if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
|
||||||
else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
|
else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const s = stamped(e.target);
|
const s = stamped(e.target);
|
||||||
if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
|
if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
|
||||||
}, true);
|
}, true);
|
||||||
let ticking = false;
|
let ticking = false;
|
||||||
addEventListener('scroll', function(){
|
addEventListener('scroll', function(){
|
||||||
if (ticking) return; ticking = true;
|
if (ticking) return; ticking = true;
|
||||||
requestAnimationFrame(function(){
|
requestAnimationFrame(function(){
|
||||||
ticking = false;
|
ticking = false;
|
||||||
for (const el of document.querySelectorAll('[data-source-line]')) {
|
for (const el of document.querySelectorAll('[data-source-line]')) {
|
||||||
const r = el.getBoundingClientRect();
|
const r = el.getBoundingClientRect();
|
||||||
if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
|
if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, {passive: true});
|
}, {passive: true});
|
||||||
"""
|
"""
|
||||||
|
|
||||||
// @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements are MainActor in the SDK.
|
// @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements are MainActor in the SDK.
|
||||||
@MainActor
|
@MainActor
|
||||||
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
|
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
|
||||||
weak var webView: WKWebView?
|
weak var webView: WKWebView?
|
||||||
var loadedURL: URL?
|
var loadedURL: URL?
|
||||||
var paintStart: DispatchTime?
|
var paintStart: DispatchTime?
|
||||||
var onStats: (Stats) -> Void
|
var onStats: (Stats) -> Void
|
||||||
var onSourceLine: (String, Int) -> Void
|
var onSourceLine: (String, Int) -> Void
|
||||||
|
|
||||||
init(onStats: @escaping (Stats) -> Void, onSourceLine: @escaping (String, Int) -> Void) {
|
init(onStats: @escaping (Stats) -> Void, onSourceLine: @escaping (String, Int) -> Void) {
|
||||||
self.onStats = onStats
|
self.onStats = onStats
|
||||||
self.onSourceLine = onSourceLine
|
self.onSourceLine = onSourceLine
|
||||||
}
|
}
|
||||||
|
|
||||||
func webView(_ wv: WKWebView, didFinish: WKNavigation!) {
|
func webView(_: WKWebView, didFinish _: WKNavigation!) {
|
||||||
if let t0 = paintStart {
|
if let t0 = paintStart {
|
||||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||||
onStats(Stats(paintMS: ms))
|
onStats(Stats(paintMS: ms))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Spike diagnostics: surface the silent-load failure path.
|
/// Spike diagnostics: surface the silent-load failure path.
|
||||||
func webView(_ wv: WKWebView, didFail na: WKNavigation!, withError error: Error) {
|
func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
|
||||||
FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
|
FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
func webView(_ wv: WKWebView, didFailProvisionalNavigation na: WKNavigation!, withError error: Error) {
|
func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
|
||||||
FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
|
FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
nonisolated func webViewWebContentProcessDidTerminate(_ wv: WKWebView) {
|
nonisolated func webViewWebContentProcessDidTerminate(_: WKWebView) {
|
||||||
FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8))
|
FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow our own loadHTMLString (file:// baseURL / about:blank main frame); cancel the rest.
|
/// Allow our own loadHTMLString (file:// baseURL / about:blank main frame); cancel the rest.
|
||||||
// The initial load is a navigation too — a blanket .cancel kills the page before it paints.
|
/// The initial load is a navigation too — a blanket .cancel kills the page before it paints.
|
||||||
func webView(_ wv: WKWebView, decidePolicyFor na: WKNavigationAction,
|
func webView(_: WKWebView, decidePolicyFor na: WKNavigationAction,
|
||||||
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
|
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void)
|
||||||
if na.targetFrame?.isMainFrame == true,
|
{
|
||||||
let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank" {
|
if na.targetFrame?.isMainFrame == true,
|
||||||
decisionHandler(.allow); return
|
let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank"
|
||||||
}
|
{
|
||||||
if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true {
|
decisionHandler(.allow); return
|
||||||
NSWorkspace.shared.open(url)
|
}
|
||||||
}
|
if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true {
|
||||||
decisionHandler(.cancel)
|
NSWorkspace.shared.open(url)
|
||||||
}
|
}
|
||||||
|
decisionHandler(.cancel)
|
||||||
|
}
|
||||||
|
|
||||||
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
|
func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||||
switch message.name {
|
switch message.name {
|
||||||
case "openLink":
|
case "openLink":
|
||||||
if let s = message.body as? String, let url = URL(string: s) { NSWorkspace.shared.open(url) }
|
if let s = message.body as? String, let url = URL(string: s) {
|
||||||
case "sourceClick", "sourceScroll":
|
NSWorkspace.shared.open(url)
|
||||||
if let s = message.body as? String, let n = Int(s) { onSourceLine(message.name == "sourceClick" ? "click" : "top", n) }
|
}
|
||||||
default: break
|
case "sourceClick", "sourceScroll":
|
||||||
}
|
if let s = message.body as? String, let n = Int(s) {
|
||||||
}
|
onSourceLine(message.name == "sourceClick" ? "click" : "top", n)
|
||||||
}
|
}
|
||||||
|
default: break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator(onStats: onStats, onSourceLine: onSourceLine) }
|
func makeCoordinator() -> Coordinator {
|
||||||
|
Coordinator(onStats: onStats, onSourceLine: onSourceLine)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Shell
|
// MARK: - Shell
|
||||||
|
|
||||||
@main
|
@main
|
||||||
struct SpikeApp: App {
|
struct SpikeApp: App {
|
||||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
Window("Spike — apex HTML reading", id: "main") {
|
Window("Spike — apex HTML reading", id: "main") {
|
||||||
ContentView()
|
ContentView()
|
||||||
.frame(minWidth: 960, minHeight: 720)
|
.frame(minWidth: 960, minHeight: 720)
|
||||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check`
|
// ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check`
|
||||||
init() {
|
init() {
|
||||||
let args = CommandLine.arguments
|
let args = CommandLine.arguments
|
||||||
if args.contains("--check") { Self.selfCheck(); exit(0) }
|
if args.contains("--check") {
|
||||||
if let i = args.firstIndex(of: "--pipeline"), args.count > i + 1 { Self.pipeline(path: args[i + 1]); exit(0) }
|
Self.selfCheck(); exit(0)
|
||||||
}
|
}
|
||||||
|
if let i = args.firstIndex(of: "--pipeline"), args.count > i + 1 {
|
||||||
|
Self.pipeline(path: args[i + 1]); exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Headless end-to-end: chunk → apex → stamp → validate coverage. Prints per-file numbers.
|
/// Headless end-to-end: chunk → apex → stamp → validate coverage. Prints per-file numbers.
|
||||||
static func pipeline(path: String) {
|
static func pipeline(path: String) {
|
||||||
let url = URL(fileURLWithPath: path)
|
let url = URL(fileURLWithPath: path)
|
||||||
guard let source = try? String(contentsOf: url, encoding: .utf8) else { print("unreadable: \(path)"); exit(1) }
|
guard let source = try? String(contentsOf: url, encoding: .utf8) else { print("unreadable: \(path)"); exit(1) }
|
||||||
let lines = source.split(separator: "\n", omittingEmptySubsequences: false) as [Substring]
|
let lines = source.split(separator: "\n", omittingEmptySubsequences: false) as [Substring]
|
||||||
do {
|
do {
|
||||||
let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
|
let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
|
||||||
let stamped = HTMLStamper.stamp(html)
|
let stamped = HTMLStamper.stamp(html)
|
||||||
// coverage: every data-source-line points at a non-blank source line
|
// coverage: every data-source-line points at a non-blank source line
|
||||||
let re = try NSRegularExpression(pattern: #"data-source-line="(\d+)""#)
|
let re = try NSRegularExpression(pattern: #"data-source-line="(\d+)""#)
|
||||||
var bad = 0, count = 0, lineSum = 0
|
var bad = 0, count = 0, lineSum = 0
|
||||||
re.enumerateMatches(in: stamped, range: NSMakeRange(0, (stamped as NSString).length)) { m, _, _ in
|
re.enumerateMatches(in: stamped, range: NSMakeRange(0, (stamped as NSString).length)) { m, _, _ in
|
||||||
guard let m else { return }
|
guard let m else { return }
|
||||||
let n = Int((stamped as NSString).substring(with: m.range(at: 1)))!
|
let n = Int((stamped as NSString).substring(with: m.range(at: 1)))!
|
||||||
count += 1; lineSum += n
|
count += 1; lineSum += n
|
||||||
let idx = n - 1
|
let idx = n - 1
|
||||||
if idx < 0 || idx >= lines.count || lines[idx].allSatisfy({ $0 == " " || $0 == "\t" || $0 == "\r" }) { bad += 1 }
|
if idx < 0 || idx >= lines.count || lines[idx].allSatisfy({ $0 == " " || $0 == "\t" || $0 == "\r" }) {
|
||||||
}
|
bad += 1
|
||||||
print("\(url.lastPathComponent): apex \(String(format: "%.1f", ms)) ms, html \(html.utf8.count) B, \(count) blocks stamped, \(bad) mis-stamped, avg line \(count > 0 ? lineSum / count : 0)")
|
}
|
||||||
exit(bad == 0 ? 0 : 2)
|
}
|
||||||
} catch {
|
print("\(url.lastPathComponent): apex \(String(format: "%.1f", ms)) ms, html \(html.utf8.count) B, \(count) blocks stamped, \(bad) mis-stamped, avg line \(count > 0 ? lineSum / count : 0)")
|
||||||
print("apex failed: \(error)"); exit(1)
|
exit(bad == 0 ? 0 : 2)
|
||||||
}
|
} catch {
|
||||||
}
|
print("apex failed: \(error)"); exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static func selfCheck() {
|
static func selfCheck() {
|
||||||
// chunker: sentinels before chunks, blank structure preserved
|
// chunker: sentinels before chunks, blank structure preserved
|
||||||
let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
|
let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
|
||||||
let stamped = MarkdownChunker.stamp(md)
|
let stamped = MarkdownChunker.stamp(md)
|
||||||
assert(stamped == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC", stamped)
|
assert(stamped == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC", stamped)
|
||||||
// stamper: sentinel → attribute on following element; multi-digit lines
|
// stamper: sentinel → attribute on following element; multi-digit lines
|
||||||
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
|
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
|
||||||
let out = HTMLStamper.stamp(html)
|
let out = HTMLStamper.stamp(html)
|
||||||
assert(out == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>", out)
|
assert(out == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>", out)
|
||||||
print("self-check OK")
|
print("self-check OK")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
nonisolated func applicationDidFinishLaunching(_ n: Notification) {}
|
nonisolated func applicationDidFinishLaunching(_: Notification) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
@State private var files: [URL] = []
|
@State private var files: [URL] = []
|
||||||
@State private var selected: URL?
|
@State private var selected: URL?
|
||||||
@State private var stats = ReadingWebView.Stats()
|
@State private var stats = ReadingWebView.Stats()
|
||||||
@State private var clickedLine: Int?
|
@State private var clickedLine: Int?
|
||||||
@State private var topLine: Int?
|
@State private var topLine: Int?
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Group {
|
Group {
|
||||||
if files.isEmpty {
|
if files.isEmpty {
|
||||||
Text("pass a corpus .md path (or use Open…)").padding()
|
Text("pass a corpus .md path (or use Open…)").padding()
|
||||||
} else {
|
} else {
|
||||||
HStack(spacing: 0) {
|
HStack(spacing: 0) {
|
||||||
List(selection: $selected) {
|
List(selection: $selected) {
|
||||||
ForEach(files, id: \.self) { f in
|
ForEach(files, id: \.self) { f in
|
||||||
Text(f.deletingPathExtension().lastPathComponent).tag(f)
|
Text(f.deletingPathExtension().lastPathComponent).tag(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.listStyle(.sidebar).frame(width: 220)
|
.listStyle(.sidebar).frame(width: 220)
|
||||||
Divider()
|
Divider()
|
||||||
if let sel = selected {
|
if let sel = selected {
|
||||||
// No .id(sel) remount: ONE WKWebView, reloaded in place. Remounting per
|
// No .id(sel) remount: ONE WKWebView, reloaded in place. Remounting per
|
||||||
// document re-spawns the web view (~hundreds of ms) and blanks the pane —
|
// document re-spawns the web view (~hundreds of ms) and blanks the pane —
|
||||||
// the dominant switch cost, far bigger than apex itself.
|
// the dominant switch cost, far bigger than apex itself.
|
||||||
ReadingWebView(fileURL: sel, onStats: { s in
|
ReadingWebView(fileURL: sel, onStats: { s in
|
||||||
if s.apexMS > 0 || s.error != nil { stats = s } else { stats.paintMS = s.paintMS }
|
if s.apexMS > 0 || s.error != nil {
|
||||||
}, onSourceLine: { kind, line in
|
stats = s
|
||||||
if kind == "click" { clickedLine = line } else { topLine = line }
|
} else {
|
||||||
})
|
stats.paintMS = s.paintMS
|
||||||
} else { Text("pick a post").frame(maxWidth: .infinity) }
|
}
|
||||||
}
|
}, onSourceLine: { kind, line in
|
||||||
}
|
if kind == "click" {
|
||||||
}
|
clickedLine = line
|
||||||
.safeAreaInset(edge: .bottom) { statsBar }
|
} else {
|
||||||
.toolbar {
|
topLine = line
|
||||||
Button("Open…") { openPanel() }
|
}
|
||||||
if let apex = Apex.binaryPath() { Text("apex: \(apex)") }
|
})
|
||||||
}
|
} else {
|
||||||
.onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) }
|
Text("pick a post").frame(maxWidth: .infinity)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.safeAreaInset(edge: .bottom) { statsBar }
|
||||||
|
.toolbar {
|
||||||
|
Button("Open…") { openPanel() }
|
||||||
|
if let apex = Apex.binaryPath() {
|
||||||
|
Text("apex: \(apex)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) }
|
||||||
|
}
|
||||||
|
|
||||||
private var statsBar: some View {
|
private var statsBar: some View {
|
||||||
HStack(spacing: 16) {
|
HStack(spacing: 16) {
|
||||||
Text(selected?.lastPathComponent ?? "—").lineLimit(1).truncationMode(.middle)
|
Text(selected?.lastPathComponent ?? "—").lineLimit(1).truncationMode(.middle)
|
||||||
Text(String(format: "apex %.0f ms", stats.apexMS))
|
Text(String(format: "apex %.0f ms", stats.apexMS))
|
||||||
Text(String(format: "paint %.0f ms", stats.paintMS))
|
Text(String(format: "paint %.0f ms", stats.paintMS))
|
||||||
Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file))
|
Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file))
|
||||||
if let t = topLine { Text("top src line \(t)") }
|
if let t = topLine {
|
||||||
if let c = clickedLine { Text("click → src line \(c)") }
|
Text("top src line \(t)")
|
||||||
if let e = stats.error { Text(e).foregroundStyle(.red).lineLimit(1) }
|
}
|
||||||
Spacer()
|
if let c = clickedLine {
|
||||||
}
|
Text("click → src line \(c)")
|
||||||
.font(.system(size: 11, design: .monospaced)).padding(6)
|
}
|
||||||
.background(.bar)
|
if let e = stats.error {
|
||||||
}
|
Text(e).foregroundStyle(.red).lineLimit(1)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
.font(.system(size: 11, design: .monospaced)).padding(6)
|
||||||
|
.background(.bar)
|
||||||
|
}
|
||||||
|
|
||||||
private func load(arg: String?) {
|
private func load(arg: String?) {
|
||||||
if let a = arg {
|
if let a = arg {
|
||||||
let u = URL(fileURLWithPath: a).standardizedFileURL
|
let u = URL(fileURLWithPath: a).standardizedFileURL
|
||||||
files = (try? FileManager.default.contentsOfDirectory(
|
files = (try? FileManager.default.contentsOfDirectory(
|
||||||
at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil
|
at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil,
|
||||||
).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u]
|
).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u]
|
||||||
selected = files.first(where: { $0 == u }) ?? u
|
selected = files.first(where: { $0 == u }) ?? u
|
||||||
} else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?,
|
} else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?,
|
||||||
let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) {
|
let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
|
||||||
files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
|
{
|
||||||
selected = files.first
|
files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
|
||||||
}
|
selected = files.first
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func openPanel() {
|
private func openPanel() {
|
||||||
let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false
|
let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false
|
||||||
p.allowedContentTypes = [.init(filenameExtension: "md")!]
|
p.allowedContentTypes = [.init(filenameExtension: "md")!]
|
||||||
if p.runModal() == .OK, let u = p.url { files.append(u); selected = u }
|
if p.runModal() == .OK, let u = p.url {
|
||||||
}
|
files.append(u); selected = u
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "BlocksSpike",
|
name: "BlocksSpike",
|
||||||
platforms: [.macOS(.v26)],
|
platforms: [.macOS(.v26)],
|
||||||
targets: [.executableTarget(name: "BlocksSpike")]
|
targets: [.executableTarget(name: "BlocksSpike")],
|
||||||
)
|
)
|
||||||
@@ -5,80 +5,88 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
struct Block: Identifiable, Equatable {
|
struct Block: Identifiable, Equatable {
|
||||||
var id = UUID()
|
var id = UUID()
|
||||||
var raw: String // markdown source incl. marker; kind is derived, never stored
|
var raw: String // markdown source incl. marker; kind is derived, never stored
|
||||||
}
|
}
|
||||||
|
|
||||||
nonisolated enum BlockModel {
|
nonisolated enum BlockModel {
|
||||||
enum Kind { case heading1, heading2, paragraph, quote, hr }
|
enum Kind { case heading1, heading2, paragraph, quote, hr }
|
||||||
|
|
||||||
/// Blank-line split — identical strategy to Spike B's readingBlocks, so the
|
/// Blank-line split — identical strategy to Spike B's readingBlocks, so the
|
||||||
/// spikes differ by substrate, not by parse. ponytail: no AST, no lists/setext (corpus has none, #51).
|
/// spikes differ by substrate, not by parse. ponytail: no AST, no lists/setext (corpus has none, #51).
|
||||||
static func parse(_ md: String) -> [Block] {
|
static func parse(_ md: String) -> [Block] {
|
||||||
md.components(separatedBy: "\n\n")
|
md.components(separatedBy: "\n\n")
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||||
.filter { !$0.isEmpty }
|
.filter { !$0.isEmpty }
|
||||||
.map { Block(raw: $0) }
|
.map { Block(raw: $0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
static func kind(of raw: String) -> Kind {
|
static func kind(of raw: String) -> Kind {
|
||||||
if raw.hasPrefix("## ") { return .heading2 }
|
if raw.hasPrefix("## ") {
|
||||||
if raw.hasPrefix("# ") { return .heading1 }
|
return .heading2
|
||||||
if raw.hasPrefix("> ") { return .quote }
|
}
|
||||||
if raw.count <= 6, !raw.isEmpty, raw.allSatisfy({ $0 == "*" || $0 == "-" || $0 == "_" || $0.isWhitespace }) { return .hr }
|
if raw.hasPrefix("# ") {
|
||||||
return .paragraph
|
return .heading1
|
||||||
}
|
}
|
||||||
|
if raw.hasPrefix("> ") {
|
||||||
|
return .quote
|
||||||
|
}
|
||||||
|
if raw.count <= 6, !raw.isEmpty, raw.allSatisfy({ $0 == "*" || $0 == "-" || $0 == "_" || $0.isWhitespace }) {
|
||||||
|
return .hr
|
||||||
|
}
|
||||||
|
return .paragraph
|
||||||
|
}
|
||||||
|
|
||||||
/// Rendered text: marker stripped, inline markdown parsed (inline-only — block
|
/// Rendered text: marker stripped, inline markdown parsed (inline-only — block
|
||||||
/// structure is ours, exactly like Spike B's reading mode).
|
/// structure is ours, exactly like Spike B's reading mode).
|
||||||
static func rendered(_ raw: String) -> AttributedString {
|
static func rendered(_ raw: String) -> AttributedString {
|
||||||
var p = raw
|
var p = raw
|
||||||
let k = kind(of: raw)
|
let k = kind(of: raw)
|
||||||
switch k {
|
switch k {
|
||||||
case .heading1: p = String(p.dropFirst(2))
|
case .heading1: p = String(p.dropFirst(2))
|
||||||
case .heading2: p = String(p.dropFirst(3))
|
case .heading2: p = String(p.dropFirst(3))
|
||||||
case .quote: p = String(p.dropFirst(2))
|
case .quote: p = String(p.dropFirst(2))
|
||||||
case .hr: return AttributedString("⁂")
|
case .hr: return AttributedString("⁂")
|
||||||
case .paragraph: break
|
case .paragraph: break
|
||||||
}
|
}
|
||||||
var opts = AttributedString.MarkdownParsingOptions()
|
var opts = AttributedString.MarkdownParsingOptions()
|
||||||
opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
|
opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
|
||||||
return (try? AttributedString(markdown: p, options: opts)) ?? AttributedString(p)
|
return (try? AttributedString(markdown: p, options: opts)) ?? AttributedString(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Marker-stripped plain text (anchor search runs over this).
|
/// Marker-stripped plain text (anchor search runs over this).
|
||||||
static func plainText(_ raw: String) -> String {
|
static func plainText(_ raw: String) -> String {
|
||||||
switch kind(of: raw) {
|
switch kind(of: raw) {
|
||||||
case .heading1: return String(raw.dropFirst(2))
|
case .heading1: String(raw.dropFirst(2))
|
||||||
case .heading2: return String(raw.dropFirst(3))
|
case .heading2: String(raw.dropFirst(3))
|
||||||
case .quote: return String(raw.dropFirst(2))
|
case .quote: String(raw.dropFirst(2))
|
||||||
case .hr: return ""
|
case .hr: ""
|
||||||
case .paragraph: return raw
|
case .paragraph: raw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Within-block UTF-16 range of `quote` (word-tokenized, whitespace-tolerant — same
|
/// Within-block UTF-16 range of `quote` (word-tokenized, whitespace-tolerant — same
|
||||||
/// strategy as Spike B's anchorRange, scoped to one block). nil = stale.
|
/// strategy as Spike B's anchorRange, scoped to one block). nil = stale.
|
||||||
static func anchorRange(of quote: String, in raw: String) -> NSRange? {
|
static func anchorRange(of quote: String, in raw: String) -> NSRange? {
|
||||||
let text = plainText(raw)
|
let text = plainText(raw)
|
||||||
let textWords = words(text), quoteWords = words(quote)
|
let textWords = words(text), quoteWords = words(quote)
|
||||||
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
|
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
|
||||||
for start in 0 ... textWords.count - quoteWords.count {
|
for start in 0 ... textWords.count - quoteWords.count {
|
||||||
if (start ..< start + quoteWords.count).allSatisfy({ textWords[$0].norm == quoteWords[$0 - start].norm }) {
|
if (start ..< start + quoteWords.count).allSatisfy({ textWords[$0].norm == quoteWords[$0 - start].norm }) {
|
||||||
let from = textWords[start].range.lowerBound
|
let from = textWords[start].range.lowerBound
|
||||||
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
||||||
return NSRange(location: text.utf16.distance(from: text.startIndex, to: from),
|
return NSRange(location: text.utf16.distance(from: text.startIndex, to: from),
|
||||||
length: text.utf16.distance(from: from, to: to))
|
length: text.utf16.distance(from: from, to: to))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
private struct Word { let norm: String; let range: Range<String.Index> }
|
private struct Word { let norm: String; let range: Range<String.Index> }
|
||||||
private static func words(_ s: String) -> [Word] {
|
private static func words(_ s: String) -> [Word] {
|
||||||
s.split(whereSeparator: \.isWhitespace).map { sub in
|
s.split(whereSeparator: \.isWhitespace).map { sub in
|
||||||
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters),
|
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters),
|
||||||
range: sub.startIndex ..< sub.endIndex)
|
range: sub.startIndex ..< sub.endIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,345 +6,365 @@ import SwiftUI
|
|||||||
|
|
||||||
@main
|
@main
|
||||||
struct SpikeApp: App {
|
struct SpikeApp: App {
|
||||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
Window("Spike C — Blocks", id: "main") {
|
Window("Spike C — Blocks", id: "main") {
|
||||||
ContentView()
|
ContentView()
|
||||||
.frame(minWidth: 900, minHeight: 640)
|
.frame(minWidth: 900, minHeight: 640)
|
||||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||||
}
|
}
|
||||||
.windowStyle(.hiddenTitleBar)
|
.windowStyle(.hiddenTitleBar)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: one runnable check — `swift run --package-path spike/blocks --check`
|
// ponytail: one runnable check — `swift run --package-path spike/blocks --check`
|
||||||
init() {
|
init() {
|
||||||
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
|
if CommandLine.arguments.contains("--check") {
|
||||||
}
|
Self.selfCheck(); exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static func selfCheck() {
|
static func selfCheck() {
|
||||||
let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
|
let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
|
||||||
let blocks = BlockModel.parse(text)
|
let blocks = BlockModel.parse(text)
|
||||||
assert(blocks.count > 10, "FAIL: parse produced \(blocks.count) blocks")
|
assert(blocks.count > 10, "FAIL: parse produced \(blocks.count) blocks")
|
||||||
assert(BlockModel.kind(of: blocks[0].raw) == .heading2, "FAIL: first block not a heading (## in corpus)")
|
assert(BlockModel.kind(of: blocks[0].raw) == .heading2, "FAIL: first block not a heading (## in corpus)")
|
||||||
let kinds = blocks.map { BlockModel.kind(of: $0.raw) }
|
let kinds = blocks.map { BlockModel.kind(of: $0.raw) }
|
||||||
assert(kinds.contains(.heading2), "FAIL: no ## blocks")
|
assert(kinds.contains(.heading2), "FAIL: no ## blocks")
|
||||||
assert(kinds.contains(.hr), "FAIL: corpus hr (* * *) not detected")
|
assert(kinds.contains(.hr), "FAIL: corpus hr (* * *) not detected")
|
||||||
// rendered text must hide block markup
|
// rendered text must hide block markup
|
||||||
let rendered = blocks.map { String(BlockModel.rendered($0.raw).characters) }
|
let rendered = blocks.map { String(BlockModel.rendered($0.raw).characters) }
|
||||||
assert(rendered.allSatisfy { !$0.hasPrefix("# ") && !$0.hasPrefix("## ") && !$0.hasPrefix("> ") },
|
assert(rendered.allSatisfy { !$0.hasPrefix("# ") && !$0.hasPrefix("## ") && !$0.hasPrefix("> ") },
|
||||||
"FAIL: markup leaked into rendered view")
|
"FAIL: markup leaked into rendered view")
|
||||||
assert(rendered.contains { $0.contains("expected value") }, "FAIL: body text missing")
|
assert(rendered.contains { $0.contains("expected value") }, "FAIL: body text missing")
|
||||||
// anchor feasibility: block containing the DM quote
|
// anchor feasibility: block containing the DM quote
|
||||||
let anchor = ContentView.findAnchorBlock(quote: "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”", in: blocks)
|
let anchor = ContentView.findAnchorBlock(quote: "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”", in: blocks)
|
||||||
assert(anchor != nil, "FAIL: anchor block not found")
|
assert(anchor != nil, "FAIL: anchor block not found")
|
||||||
// within-block range feasibility: same word search as Spike B, scoped to one block
|
// within-block range feasibility: same word search as Spike B, scoped to one block
|
||||||
if let a = anchor {
|
if let a = anchor {
|
||||||
let r = BlockModel.anchorRange(of: "the expected value of joining", in: a.raw)
|
let r = BlockModel.anchorRange(of: "the expected value of joining", in: a.raw)
|
||||||
assert(r != nil, "FAIL: within-block anchor range")
|
assert(r != nil, "FAIL: within-block anchor range")
|
||||||
}
|
}
|
||||||
// paste-split: multi-paragraph raw splits into blocks
|
// paste-split: multi-paragraph raw splits into blocks
|
||||||
assert(BlockModel.parse("one\n\ntwo\n\nthree").count == 3, "FAIL: paste-split")
|
assert(BlockModel.parse("one\n\ntwo\n\nthree").count == 3, "FAIL: paste-split")
|
||||||
// perf: block-ify PERF-3k
|
// perf: block-ify PERF-3k
|
||||||
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
||||||
var ms = 0.0
|
var ms = 0.0
|
||||||
for _ in 0..<3 {
|
for _ in 0 ..< 3 {
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
_ = BlockModel.parse(perf)
|
_ = BlockModel.parse(perf)
|
||||||
ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
||||||
}
|
}
|
||||||
print("PASS: \(blocks.count) blocks; anchor block found; PERF-3k block-ify \(String(format: "%.1f", ms)) ms")
|
print("PASS: \(blocks.count) blocks; anchor block found; PERF-3k block-ify \(String(format: "%.1f", ms)) ms")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Content
|
// MARK: - Content
|
||||||
|
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
@State private var blocks: [Block]
|
@State private var blocks: [Block]
|
||||||
@State private var focusedID: UUID?
|
@State private var focusedID: UUID?
|
||||||
@State private var anchorID: UUID?
|
@State private var anchorID: UUID?
|
||||||
@State private var staleShown = false
|
@State private var staleShown = false
|
||||||
@State private var loadMs: Double = 0
|
@State private var loadMs: Double = 0
|
||||||
@State private var hint = "Click a block to edit its source. Enter splits, ⌫ at start merges. IME probe: type ⌥U a in a block."
|
@State private var hint = "Click a block to edit its source. Enter splits, ⌫ at start merges. IME probe: type ⌥U a in a block."
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
let args = CommandLine.arguments
|
let args = CommandLine.arguments
|
||||||
let arg = args.count > 1 && args[1] != "--check" ? args[1] : nil
|
let arg = args.count > 1 && args[1] != "--check" ? args[1] : nil
|
||||||
let t = Self.loadCorpus(arg)
|
let t = Self.loadCorpus(arg)
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
_blocks = State(initialValue: BlockModel.parse(t))
|
_blocks = State(initialValue: BlockModel.parse(t))
|
||||||
_loadMs = State(initialValue: Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6)
|
_loadMs = State(initialValue: Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Arg as given, then the default piece (run.sh passes absolute paths).
|
/// Arg as given, then the default piece (run.sh passes absolute paths).
|
||||||
static func loadCorpus(_ arg: String?) -> String {
|
static func loadCorpus(_ arg: String?) -> String {
|
||||||
for c in [arg, "spike/prose/the-expected-value-of-showing.md"].compactMap({ $0 }) {
|
for c in [arg, "spike/prose/the-expected-value-of-showing.md"].compactMap(\.self) {
|
||||||
if let s = try? String(contentsOfFile: c, encoding: .utf8) { return s }
|
if let s = try? String(contentsOfFile: c, encoding: .utf8) {
|
||||||
}
|
return s
|
||||||
return "# Spike C\n\n(No corpus file found — run from repo root.)"
|
}
|
||||||
}
|
}
|
||||||
|
return "# Spike C\n\n(No corpus file found — run from repo root.)"
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
bar
|
bar
|
||||||
Divider()
|
Divider()
|
||||||
ScrollViewReader { proxy in
|
ScrollViewReader { proxy in
|
||||||
ScrollView([.vertical]) {
|
ScrollView([.vertical]) {
|
||||||
LazyVStack(alignment: .leading, spacing: 18) {
|
LazyVStack(alignment: .leading, spacing: 18) {
|
||||||
ForEach(blocks) { block in
|
ForEach(blocks) { block in
|
||||||
BlockRow(
|
BlockRow(
|
||||||
block: block,
|
block: block,
|
||||||
isFocused: focusedID == block.id,
|
isFocused: focusedID == block.id,
|
||||||
isAnchored: anchorID == block.id,
|
isAnchored: anchorID == block.id,
|
||||||
onEdit: { raw in edit(block.id, raw: raw) },
|
onEdit: { raw in edit(block.id, raw: raw) },
|
||||||
onSplit: { at in split(block.id, at: at) },
|
onSplit: { at in split(block.id, at: at) },
|
||||||
onMerge: { merge(block.id) },
|
onMerge: { merge(block.id) },
|
||||||
onFocus: {
|
onFocus: {
|
||||||
focusedID = block.id
|
focusedID = block.id
|
||||||
hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
|
hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
.id(block.id)
|
.id(block.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: 720, alignment: .leading)
|
.frame(maxWidth: 720, alignment: .leading)
|
||||||
.padding(.horizontal, 40)
|
.padding(.horizontal, 40)
|
||||||
.padding(.vertical, 24)
|
.padding(.vertical, 24)
|
||||||
.onChange(of: anchorID) { id in
|
.onChange(of: anchorID) { id in
|
||||||
if let id { proxy.scrollTo(id, anchor: .center) }
|
if let id {
|
||||||
}
|
proxy.scrollTo(id, anchor: .center)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Divider()
|
}
|
||||||
Text(hint).font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
|
}
|
||||||
.padding(.horizontal, 16).padding(.vertical, 6)
|
Divider()
|
||||||
}
|
Text(hint).font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
|
||||||
.alert("Anchor not found", isPresented: $staleShown) {
|
.padding(.horizontal, 16).padding(.vertical, 6)
|
||||||
Button("OK", role: .cancel) {}
|
}
|
||||||
} message: {
|
.alert("Anchor not found", isPresented: $staleShown) {
|
||||||
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
Button("OK", role: .cancel) {}
|
||||||
}
|
} message: {
|
||||||
}
|
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private var bar: some View {
|
private var bar: some View {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
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("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") }
|
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||||||
if anchorID != nil { Text("anchored").foregroundStyle(.secondary).font(.caption) }
|
if anchorID != nil {
|
||||||
Spacer()
|
Text("anchored").foregroundStyle(.secondary).font(.caption)
|
||||||
Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
|
}
|
||||||
}
|
Spacer()
|
||||||
.padding(.horizontal, 16)
|
Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
|
||||||
.padding(.vertical, 8)
|
}
|
||||||
}
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: block ops
|
// MARK: block ops
|
||||||
|
|
||||||
private func edit(_ id: UUID, raw: String) {
|
private func edit(_ id: UUID, raw: String) {
|
||||||
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
||||||
// paste-split: multi-paragraph raw explodes into blocks at the same position
|
// paste-split: multi-paragraph raw explodes into blocks at the same position
|
||||||
if raw.contains("\n\n") {
|
if raw.contains("\n\n") {
|
||||||
let parts = BlockModel.parse(raw)
|
let parts = BlockModel.parse(raw)
|
||||||
guard !parts.isEmpty else { return }
|
guard !parts.isEmpty else { return }
|
||||||
blocks.replaceSubrange(i ... i, with: parts)
|
blocks.replaceSubrange(i ... i, with: parts)
|
||||||
focusedID = parts[parts.count - 1].id
|
focusedID = parts[parts.count - 1].id
|
||||||
} else {
|
} else {
|
||||||
blocks[i].raw = raw
|
blocks[i].raw = raw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func split(_ id: UUID, at location: Int) {
|
private func split(_ id: UUID, at location: Int) {
|
||||||
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
||||||
let ns = blocks[i].raw as NSString
|
let ns = blocks[i].raw as NSString
|
||||||
let loc = max(0, min(location, ns.length))
|
let loc = max(0, min(location, ns.length))
|
||||||
let before = ns.substring(to: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
let before = ns.substring(to: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
let after = ns.substring(from: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
let after = ns.substring(from: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
blocks[i].raw = before
|
blocks[i].raw = before
|
||||||
blocks.insert(Block(raw: after), at: i + 1)
|
blocks.insert(Block(raw: after), at: i + 1)
|
||||||
focusedID = blocks[i + 1].id
|
focusedID = blocks[i + 1].id
|
||||||
}
|
}
|
||||||
|
|
||||||
private func merge(_ id: UUID) {
|
private func merge(_ id: UUID) {
|
||||||
guard let i = blocks.firstIndex(where: { $0.id == id }), i > 0 else { return }
|
guard let i = blocks.firstIndex(where: { $0.id == id }), i > 0 else { return }
|
||||||
blocks[i - 1].raw += " " + blocks[i].raw
|
blocks[i - 1].raw += " " + blocks[i].raw
|
||||||
blocks.remove(at: i)
|
blocks.remove(at: i)
|
||||||
focusedID = blocks[i - 1].id
|
focusedID = blocks[i - 1].id
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: anchor (block-granular Fix-Card feasibility)
|
// MARK: anchor (block-granular Fix-Card feasibility)
|
||||||
|
|
||||||
static func findAnchorBlock(quote: String, in blocks: [Block]) -> Block? {
|
static func findAnchorBlock(quote: String, in blocks: [Block]) -> Block? {
|
||||||
let qw = normWords(quote)
|
let qw = normWords(quote)
|
||||||
guard !qw.isEmpty else { return nil }
|
guard !qw.isEmpty else { return nil }
|
||||||
for b in blocks {
|
for b in blocks {
|
||||||
let bw = normWords(BlockModel.plainText(b.raw))
|
let bw = normWords(BlockModel.plainText(b.raw))
|
||||||
guard bw.count >= qw.count else { continue }
|
guard bw.count >= qw.count else { continue }
|
||||||
if (0 ... bw.count - qw.count).contains(where: { s in
|
if (0 ... bw.count - qw.count).contains(where: { s in
|
||||||
(s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
|
(s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
|
||||||
}) { return b }
|
}) {
|
||||||
}
|
return b
|
||||||
return nil
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
static func normWords(_ s: String) -> [String] {
|
static func normWords(_ s: String) -> [String] {
|
||||||
s.split(whereSeparator: \.isWhitespace).map { $0.lowercased().trimmingCharacters(in: .punctuationCharacters) }
|
s.split(whereSeparator: \.isWhitespace).map { $0.lowercased().trimmingCharacters(in: .punctuationCharacters) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private func applyAnchor(_ quote: String) {
|
private func applyAnchor(_ quote: String) {
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
let hit = ContentView.findAnchorBlock(quote: quote, in: blocks)
|
let hit = ContentView.findAnchorBlock(quote: quote, in: blocks)
|
||||||
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
||||||
if let hit {
|
if let hit {
|
||||||
anchorID = hit.id
|
anchorID = hit.id
|
||||||
} else {
|
} else {
|
||||||
anchorID = nil
|
anchorID = nil
|
||||||
staleShown = true
|
staleShown = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - One block: rendered, or raw source when focused
|
// MARK: - One block: rendered, or raw source when focused
|
||||||
|
|
||||||
private struct BlockRow: View {
|
private struct BlockRow: View {
|
||||||
let block: Block
|
let block: Block
|
||||||
let isFocused: Bool
|
let isFocused: Bool
|
||||||
let isAnchored: Bool
|
let isAnchored: Bool
|
||||||
let onEdit: (String) -> Void
|
let onEdit: (String) -> Void
|
||||||
let onSplit: (Int) -> Void
|
let onSplit: (Int) -> Void
|
||||||
let onMerge: () -> Void
|
let onMerge: () -> Void
|
||||||
let onFocus: () -> Void
|
let onFocus: () -> Void
|
||||||
@State private var raw: String
|
@State private var raw: String
|
||||||
|
|
||||||
init(block: Block, isFocused: Bool, isAnchored: Bool,
|
init(block: Block, isFocused: Bool, isAnchored: Bool,
|
||||||
onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
|
onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
|
||||||
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void) {
|
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void)
|
||||||
self.block = block
|
{
|
||||||
self.isFocused = isFocused
|
self.block = block
|
||||||
self.isAnchored = isAnchored
|
self.isFocused = isFocused
|
||||||
self.onEdit = onEdit
|
self.isAnchored = isAnchored
|
||||||
self.onSplit = onSplit
|
self.onEdit = onEdit
|
||||||
self.onMerge = onMerge
|
self.onSplit = onSplit
|
||||||
self.onFocus = onFocus
|
self.onMerge = onMerge
|
||||||
_raw = State(initialValue: block.raw)
|
self.onFocus = onFocus
|
||||||
}
|
_raw = State(initialValue: block.raw)
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Group {
|
Group {
|
||||||
if isFocused {
|
if isFocused {
|
||||||
SingleBlockEditor(text: $raw, onEdit: onEdit, onSplit: onSplit, onMerge: onMerge)
|
SingleBlockEditor(text: $raw, onEdit: onEdit, onSplit: onSplit, onMerge: onMerge)
|
||||||
.frame(height: max(28, SingleBlockEditor.height(for: raw)))
|
.frame(height: max(28, SingleBlockEditor.height(for: raw)))
|
||||||
} else {
|
} else {
|
||||||
rendered.padding(.vertical, 1)
|
rendered.padding(.vertical, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
.background(isAnchored ? Color(nsColor: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18)) : Color.clear)
|
.background(isAnchored ? Color(nsColor: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18)) : Color.clear)
|
||||||
.contentShape(Rectangle())
|
.contentShape(Rectangle())
|
||||||
.onTapGesture { onFocus() }
|
.onTapGesture { onFocus() }
|
||||||
.onChange(of: block.raw) { raw = $0 } // external change (undo of split/merge)
|
.onChange(of: block.raw) { raw = $0 } // external change (undo of split/merge)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder private var rendered: some View {
|
@ViewBuilder private var rendered: some View {
|
||||||
let k = BlockModel.kind(of: block.raw)
|
let k = BlockModel.kind(of: block.raw)
|
||||||
switch k {
|
switch k {
|
||||||
case .heading1:
|
case .heading1:
|
||||||
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 26).bold())
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 26).bold())
|
||||||
case .heading2:
|
case .heading2:
|
||||||
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 20).bold())
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 20).bold())
|
||||||
case .quote:
|
case .quote:
|
||||||
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
|
||||||
.padding(.leading, 14).overlay(alignment: .leading) { Rectangle().fill(.quaternary).frame(width: 3) }
|
.padding(.leading, 14).overlay(alignment: .leading) { Rectangle().fill(.quaternary).frame(width: 3) }
|
||||||
case .hr:
|
case .hr:
|
||||||
Text("⁂").font(.system(size: 17)).frame(maxWidth: .infinity, alignment: .center).foregroundStyle(.secondary)
|
Text("⁂").font(.system(size: 17)).frame(maxWidth: .infinity, alignment: .center).foregroundStyle(.secondary)
|
||||||
case .paragraph:
|
case .paragraph:
|
||||||
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Focused block = one non-scrolling NSTextView (native IME/undo/select/cut-paste)
|
// MARK: - Focused block = one non-scrolling NSTextView (native IME/undo/select/cut-paste)
|
||||||
|
|
||||||
struct SingleBlockEditor: NSViewRepresentable {
|
struct SingleBlockEditor: NSViewRepresentable {
|
||||||
@Binding var text: String
|
@Binding var text: String
|
||||||
var onEdit: (String) -> Void
|
var onEdit: (String) -> Void
|
||||||
var onSplit: (Int) -> Void
|
var onSplit: (Int) -> Void
|
||||||
var onMerge: () -> Void
|
var onMerge: () -> Void
|
||||||
|
|
||||||
static func height(for raw: String) -> CGFloat {
|
static func height(for raw: String) -> CGFloat {
|
||||||
let s = NSAttributedString(string: raw, attributes: [.font: NSFontManager.shared
|
let s = NSAttributedString(string: raw, attributes: [.font: NSFontManager.shared
|
||||||
.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17)])
|
.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17)])
|
||||||
return ceil(s.boundingRect(with: CGSize(width: 640, height: CGFloat.greatestFiniteMagnitude),
|
return ceil(s.boundingRect(with: CGSize(width: 640, height: CGFloat.greatestFiniteMagnitude),
|
||||||
options: [.usesLineFragmentOrigin]).height) + 8
|
options: [.usesLineFragmentOrigin]).height) + 8
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSTextView {
|
func makeNSView(context: Context) -> NSTextView {
|
||||||
let tv = NSTextView()
|
let tv = NSTextView()
|
||||||
tv.isRichText = false
|
tv.isRichText = false
|
||||||
tv.allowsUndo = true // per-block native undo — across-block undo is an honest spike finding
|
tv.allowsUndo = true // per-block native undo — across-block undo is an honest spike finding
|
||||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
tv.isAutomaticDashSubstitutionEnabled = false
|
tv.isAutomaticDashSubstitutionEnabled = false
|
||||||
tv.isAutomaticTextReplacementEnabled = false
|
tv.isAutomaticTextReplacementEnabled = false
|
||||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||||
tv.drawsBackground = true
|
tv.drawsBackground = true
|
||||||
tv.backgroundColor = NSColor(calibratedRed: 0.99, green: 0.965, blue: 0.88, alpha: 1) // "source mode" tint
|
tv.backgroundColor = NSColor(calibratedRed: 0.99, green: 0.965, blue: 0.88, alpha: 1) // "source mode" tint
|
||||||
tv.typingAttributes = Self.typing
|
tv.typingAttributes = Self.typing
|
||||||
tv.string = text
|
tv.string = text
|
||||||
tv.delegate = context.coordinator
|
tv.delegate = context.coordinator
|
||||||
tv.isEditable = true
|
tv.isEditable = true
|
||||||
tv.isSelectable = true
|
tv.isSelectable = true
|
||||||
tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
|
tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
|
||||||
tv.textContainer?.widthTracksTextView = false
|
tv.textContainer?.widthTracksTextView = false
|
||||||
tv.textContainer?.lineFragmentPadding = 4
|
tv.textContainer?.lineFragmentPadding = 4
|
||||||
tv.isVerticallyResizable = false
|
tv.isVerticallyResizable = false
|
||||||
tv.isHorizontallyResizable = false
|
tv.isHorizontallyResizable = false
|
||||||
context.coordinator.textView = tv
|
context.coordinator.textView = tv
|
||||||
DispatchQueue.main.async { tv.window?.makeFirstResponder(tv) }
|
DispatchQueue.main.async { tv.window?.makeFirstResponder(tv) }
|
||||||
return tv
|
return tv
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateNSView(_ tv: NSTextView, context: Context) {
|
func updateNSView(_ tv: NSTextView, context _: Context) {
|
||||||
if tv.string != text { tv.string = text }
|
if tv.string != text {
|
||||||
}
|
tv.string = text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
func makeCoordinator() -> Coordinator {
|
||||||
|
Coordinator(self)
|
||||||
|
}
|
||||||
|
|
||||||
static var typing: [NSAttributedString.Key: Any] { [
|
static var typing: [NSAttributedString.Key: Any] {
|
||||||
.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
|
[
|
||||||
] }
|
.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
let parent: SingleBlockEditor
|
let parent: SingleBlockEditor
|
||||||
weak var textView: NSTextView?
|
weak var textView: NSTextView?
|
||||||
init(_ parent: SingleBlockEditor) { self.parent = parent }
|
init(_ parent: SingleBlockEditor) {
|
||||||
|
self.parent = parent
|
||||||
|
}
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
func textDidChange(_ notification: Notification) {
|
||||||
guard let tv = notification.object as? NSTextView else { return }
|
guard let tv = notification.object as? NSTextView else { return }
|
||||||
parent.text = tv.string
|
parent.text = tv.string
|
||||||
parent.onEdit(tv.string)
|
parent.onEdit(tv.string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
|
/// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
|
||||||
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
|
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
|
||||||
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
|
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
|
||||||
parent.onSplit(textView.selectedRange().location)
|
parent.onSplit(textView.selectedRange().location)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if commandSelector == #selector(NSResponder.deleteBackward(_:)) {
|
if commandSelector == #selector(NSResponder.deleteBackward(_:)) {
|
||||||
if textView.selectedRange().location == 0, textView.selectedRange().length == 0 {
|
if textView.selectedRange().location == 0, textView.selectedRange().length == 0 {
|
||||||
parent.onMerge()
|
parent.onMerge()
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
func applicationWillFinishLaunching(_: Notification) {
|
||||||
NSApp.setActivationPolicy(.regular)
|
NSApp.setActivationPolicy(.regular)
|
||||||
}
|
}
|
||||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
||||||
NSApp.activate(ignoringOtherApps: true)
|
func applicationDidFinishLaunching(_: Notification) {
|
||||||
}
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,11 +2,11 @@
|
|||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "CodeEditSpike",
|
name: "CodeEditSpike",
|
||||||
platforms: [.macOS(.v26)],
|
platforms: [.macOS(.v26)],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
// Fork fact from map #16: same fork + revision as Classis (0.15.8-helm = 3ce6007).
|
// 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"),
|
.package(url: "https://github.com/AlexKucera/CodeEditSourceEditor.git", exact: "0.15.8-helm"),
|
||||||
],
|
],
|
||||||
targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])]
|
targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])],
|
||||||
)
|
)
|
||||||
@@ -10,37 +10,37 @@ import SwiftUI
|
|||||||
// MARK: - Prose theme (uniform-font compromise documented in the resolution)
|
// MARK: - Prose theme (uniform-font compromise documented in the resolution)
|
||||||
|
|
||||||
enum ProseTheme {
|
enum ProseTheme {
|
||||||
// Iowan Old Style like Spike B / the web proto; falls back to system serif.
|
/// Iowan Old Style like Spike B / the web proto; falls back to system serif.
|
||||||
static var bodyFont: NSFont {
|
static var bodyFont: NSFont {
|
||||||
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
||||||
?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
|
?? 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 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 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 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 let accent = NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 1)
|
||||||
|
|
||||||
static var theme: EditorTheme {
|
static var theme: EditorTheme {
|
||||||
EditorTheme(
|
EditorTheme(
|
||||||
text: .init(color: ink),
|
text: .init(color: ink),
|
||||||
insertionPoint: ink,
|
insertionPoint: ink,
|
||||||
invisibles: .init(color: dim),
|
invisibles: .init(color: dim),
|
||||||
background: paper,
|
background: paper,
|
||||||
lineHighlight: NSColor(srgbRed: 0.955, green: 0.955, blue: 0.955, alpha: 1),
|
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),
|
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
|
keywords: .init(color: dim), // markdown markers route here via prosePass below
|
||||||
commands: .init(color: ink),
|
commands: .init(color: ink),
|
||||||
types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit)
|
types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit)
|
||||||
attributes: .init(color: ink),
|
attributes: .init(color: ink),
|
||||||
variables: .init(color: ink),
|
variables: .init(color: ink),
|
||||||
values: .init(color: ink),
|
values: .init(color: ink),
|
||||||
numbers: .init(color: ink),
|
numbers: .init(color: ink),
|
||||||
strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
|
strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
|
||||||
characters: .init(color: ink),
|
characters: .init(color: ink),
|
||||||
comments: .init(color: dim)
|
comments: .init(color: dim),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Prose highlight pass (helm's MonokaiHighlighter pattern: wrap tree-sitter, add regex passes)
|
// MARK: - Prose highlight pass (helm's MonokaiHighlighter pattern: wrap tree-sitter, add regex passes)
|
||||||
@@ -49,343 +49,352 @@ enum ProseTheme {
|
|||||||
/// heading lines → bold capture, marker+inline-syntax runs → dim capture. Emphasis/anchor is NOT
|
/// heading lines → bold capture, marker+inline-syntax runs → dim capture. Emphasis/anchor is NOT
|
||||||
/// done here — layer-backed Emphasis handles it.
|
/// done here — layer-backed Emphasis handles it.
|
||||||
final class ProseHighlighter: HighlightProviding {
|
final class ProseHighlighter: HighlightProviding {
|
||||||
private let wrapped = TreeSitterClient()
|
private let wrapped = TreeSitterClient()
|
||||||
|
|
||||||
func setUp(textView: TextView, codeLanguage: CodeLanguage) {
|
func setUp(textView: TextView, codeLanguage: CodeLanguage) {
|
||||||
wrapped.setUp(textView: textView, codeLanguage: codeLanguage)
|
wrapped.setUp(textView: textView, codeLanguage: codeLanguage)
|
||||||
}
|
}
|
||||||
|
|
||||||
func applyEdit(
|
func applyEdit(
|
||||||
textView: TextView,
|
textView: TextView,
|
||||||
range: NSRange,
|
range: NSRange,
|
||||||
delta: Int,
|
delta: Int,
|
||||||
completion: @escaping @MainActor (Result<IndexSet, Error>) -> Void
|
completion: @escaping @MainActor (Result<IndexSet, Error>) -> Void,
|
||||||
) {
|
) {
|
||||||
wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
|
wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
|
||||||
}
|
}
|
||||||
|
|
||||||
func queryHighlightsFor(
|
func queryHighlightsFor(
|
||||||
textView: TextView,
|
textView: TextView,
|
||||||
range: NSRange,
|
range: NSRange,
|
||||||
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void
|
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void,
|
||||||
) {
|
) {
|
||||||
wrapped.queryHighlightsFor(textView: textView, range: range) { result in
|
wrapped.queryHighlightsFor(textView: textView, range: range) { result in
|
||||||
switch result {
|
switch result {
|
||||||
case .failure(let error):
|
case let .failure(error):
|
||||||
completion(.failure(error))
|
completion(.failure(error))
|
||||||
case .success(let tsRanges):
|
case let .success(tsRanges):
|
||||||
var out = tsRanges
|
var out = tsRanges
|
||||||
let ns = textView.string as NSString
|
let ns = textView.string as NSString
|
||||||
let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
|
let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
|
||||||
out += Self.proseRanges(in: ns, range: safe)
|
out += Self.proseRanges(in: ns, range: safe)
|
||||||
completion(.success(out))
|
completion(.success(out))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pure: heading text → .type (bold via theme), heading marker + inline marks → .keyword (dim).
|
/// 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.
|
/// 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] {
|
static func proseRanges(in ns: NSString, range: NSRange) -> [HighlightRange] {
|
||||||
var out: [HighlightRange] = []
|
var out: [HighlightRange] = []
|
||||||
ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in
|
ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in
|
||||||
guard let line, !line.isEmpty else { return }
|
guard let line, !line.isEmpty else { return }
|
||||||
if let markerLen = Self.headingMarkerLen(line) {
|
if let markerLen = Self.headingMarkerLen(line) {
|
||||||
// heading text (after marker, same line) → bold capture
|
// heading text (after marker, same line) → bold capture
|
||||||
let textLen = lineRange.length - markerLen
|
let textLen = lineRange.length - markerLen
|
||||||
if textLen > 0 {
|
if textLen > 0 {
|
||||||
out.append(HighlightRange(
|
out.append(HighlightRange(
|
||||||
range: NSRange(location: lineRange.location + markerLen, length: textLen),
|
range: NSRange(location: lineRange.location + markerLen, length: textLen),
|
||||||
capture: .type
|
capture: .type,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
// marker → dim
|
// marker → dim
|
||||||
out.append(HighlightRange(
|
out.append(HighlightRange(
|
||||||
range: NSRange(location: lineRange.location, length: markerLen),
|
range: NSRange(location: lineRange.location, length: markerLen),
|
||||||
capture: .keyword
|
capture: .keyword,
|
||||||
))
|
))
|
||||||
} else if line.hasPrefix(">") {
|
} else if line.hasPrefix(">") {
|
||||||
// quote line: text → tinted .string, markers dimmed
|
// quote line: text → tinted .string, markers dimmed
|
||||||
let textLen = lineRange.length - 1
|
let textLen = lineRange.length - 1
|
||||||
if textLen > 0 {
|
if textLen > 0 {
|
||||||
out.append(HighlightRange(range: NSRange(location: lineRange.location + 1, length: textLen), capture: .string))
|
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))
|
out.append(HighlightRange(range: NSRange(location: lineRange.location, length: 1), capture: .keyword))
|
||||||
} else {
|
} else {
|
||||||
// inline syntax chars → dim, one run per char (runs merge at render)
|
// inline syntax chars → dim, one run per char (runs merge at render)
|
||||||
let marks: Set<UInt16> = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < >
|
let marks: Set<UInt16> = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < >
|
||||||
for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
|
for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
|
||||||
out.append(HighlightRange(
|
out.append(HighlightRange(
|
||||||
range: NSRange(location: lineRange.location + off, length: 1),
|
range: NSRange(location: lineRange.location + off, length: 1),
|
||||||
capture: .keyword
|
capture: .keyword,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
private static func headingMarkerLen(_ line: String) -> Int? {
|
private static func headingMarkerLen(_ line: String) -> Int? {
|
||||||
guard line.hasPrefix("#") else { return nil }
|
guard line.hasPrefix("#") else { return nil }
|
||||||
let hashes = line.prefix { $0 == "#" }.count
|
let hashes = line.prefix { $0 == "#" }.count
|
||||||
guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil }
|
guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil }
|
||||||
return hashes + 1
|
return hashes + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Quote anchor (identical algorithm to Spike B — same feasibility question)
|
// MARK: - Quote anchor (identical algorithm to Spike B — same feasibility question)
|
||||||
|
|
||||||
nonisolated enum AnchorSearch {
|
nonisolated enum AnchorSearch {
|
||||||
private struct Word { let norm: String; let range: Range<String.Index> }
|
private struct Word { let norm: String; let range: Range<String.Index> }
|
||||||
private static func words(_ s: String) -> [Word] {
|
private static func words(_ s: String) -> [Word] {
|
||||||
s.split(whereSeparator: \.isWhitespace).map { sub in
|
s.split(whereSeparator: \.isWhitespace).map { sub in
|
||||||
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex)
|
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Word-tokenized whitespace/punctuation-tolerant search. nil = stale anchor.
|
/// Word-tokenized whitespace/punctuation-tolerant search. nil = stale anchor.
|
||||||
static func range(of quote: String, in text: String) -> NSRange? {
|
static func range(of quote: String, in text: String) -> NSRange? {
|
||||||
let textWords = words(text)
|
let textWords = words(text)
|
||||||
let quoteWords = words(quote)
|
let quoteWords = words(quote)
|
||||||
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
|
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
|
||||||
for start in 0...(textWords.count - quoteWords.count) {
|
for start in 0 ... (textWords.count - quoteWords.count) {
|
||||||
if (start..<start + quoteWords.count).allSatisfy({
|
if (start ..< start + quoteWords.count).allSatisfy({
|
||||||
textWords[$0].norm == quoteWords[$0 - start].norm
|
textWords[$0].norm == quoteWords[$0 - start].norm
|
||||||
}) {
|
}) {
|
||||||
let from = textWords[start].range.lowerBound
|
let from = textWords[start].range.lowerBound
|
||||||
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
||||||
return NSRange(
|
return NSRange(
|
||||||
location: text.utf16.distance(from: text.startIndex, to: from),
|
location: text.utf16.distance(from: text.startIndex, to: from),
|
||||||
length: text.utf16.distance(from: from, to: to)
|
length: text.utf16.distance(from: from, to: to),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - App shell
|
// MARK: - App shell
|
||||||
|
|
||||||
@main
|
@main
|
||||||
struct SpikeApp: App {
|
struct SpikeApp: App {
|
||||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
Window("Spike A — CodeEdit fork", id: "main") {
|
Window("Spike A — CodeEdit fork", id: "main") {
|
||||||
ContentView()
|
ContentView()
|
||||||
.frame(minWidth: 900, minHeight: 640)
|
.frame(minWidth: 900, minHeight: 640)
|
||||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||||
}
|
}
|
||||||
.windowStyle(.hiddenTitleBar)
|
.windowStyle(.hiddenTitleBar)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
|
// ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
|
||||||
init() {
|
init() {
|
||||||
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
|
if CommandLine.arguments.contains("--check") {
|
||||||
}
|
Self.selfCheck(); exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static func selfCheck() {
|
static func selfCheck() {
|
||||||
// Repo root from compile-time path (self-check must not depend on cwd).
|
// Repo root from compile-time path (self-check must not depend on cwd).
|
||||||
let root = URL(fileURLWithPath: #filePath)
|
let root = URL(fileURLWithPath: #filePath)
|
||||||
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||||
let text = (try? String(contentsOf: root.appendingPathComponent("spike/prose/the-expected-value-of-showing.md"), encoding: .utf8)) ?? ""
|
let text = (try? String(contentsOf: root.appendingPathComponent("spike/prose/the-expected-value-of-showing.md"), encoding: .utf8)) ?? ""
|
||||||
assert(!text.isEmpty, "FAIL: corpus missing — run from repo root")
|
assert(!text.isEmpty, "FAIL: corpus missing — run from repo root")
|
||||||
let ns = text as NSString
|
let ns = text as NSString
|
||||||
let full = NSRange(location: 0, length: ns.length)
|
let full = NSRange(location: 0, length: ns.length)
|
||||||
let ranges = ProseHighlighter.proseRanges(in: ns, range: full)
|
let ranges = ProseHighlighter.proseRanges(in: ns, range: full)
|
||||||
// headings detected (calibration piece has H1 + H2s)
|
// headings detected (calibration piece has H1 + H2s)
|
||||||
let headingTexts = ranges.filter { $0.capture == .type }
|
let headingTexts = ranges.filter { $0.capture == .type }
|
||||||
assert(headingTexts.count >= 3, "FAIL: expected headings, got \(headingTexts.count)")
|
assert(headingTexts.count >= 3, "FAIL: expected headings, got \(headingTexts.count)")
|
||||||
assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound },
|
assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound },
|
||||||
"FAIL: marker leaked into heading text")
|
"FAIL: marker leaked into heading text")
|
||||||
// markers dimmed
|
// markers dimmed
|
||||||
assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") },
|
assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") },
|
||||||
"FAIL: heading marker not dimmed")
|
"FAIL: heading marker not dimmed")
|
||||||
// anchor: live quote found; stale → nil; whitespace-tolerant
|
// 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.\""
|
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 }
|
guard let r = AnchorSearch.range(of: quote, in: text) else { assertionFailure("FAIL: live quote not found"); return }
|
||||||
assert((ns.substring(with: r) as NSString).length > 50)
|
assert((ns.substring(with: r) as NSString).length > 50)
|
||||||
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
||||||
assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance")
|
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")
|
assert(AnchorSearch.range(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
||||||
// perf smoke: PERF-3k anchor timing
|
// perf smoke: PERF-3k anchor timing
|
||||||
let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md")
|
let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md")
|
||||||
if let perf = try? String(contentsOf: perfURL, encoding: .utf8) {
|
if let perf = try? String(contentsOf: perfURL, encoding: .utf8) {
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
_ = AnchorSearch.range(of: "The odds are better than they look", in: perf)
|
_ = AnchorSearch.range(of: "The odds are better than they look", in: perf)
|
||||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
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")
|
print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
|
||||||
} else {
|
} else {
|
||||||
print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found")
|
print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
@State private var text: String
|
@State private var text: String
|
||||||
@State private var editorState = SourceEditorState()
|
@State private var editorState = SourceEditorState()
|
||||||
@State private var reading = false
|
@State private var reading = false
|
||||||
@State private var staleShown = false
|
@State private var staleShown = false
|
||||||
@State private var loadMs: Double = 0
|
@State private var loadMs: Double = 0
|
||||||
@State private var anchorNote: String?
|
@State private var anchorNote: String?
|
||||||
/// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern).
|
/// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern).
|
||||||
/// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox).
|
/// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox).
|
||||||
private let box = ControllerBox()
|
private let box = ControllerBox()
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
// Repo root from compile-time path — launchd cwd is "/", so relative paths never hit.
|
// Repo root from compile-time path — launchd cwd is "/", so relative paths never hit.
|
||||||
let repoRoot = URL(fileURLWithPath: #filePath) // <root>/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
|
let repoRoot = URL(fileURLWithPath: #filePath) // <root>/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
|
||||||
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||||
let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md")
|
let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md")
|
||||||
let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") })
|
let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") })
|
||||||
let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus
|
let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus
|
||||||
let t = (try? String(contentsOf: url, encoding: .utf8))
|
let t = (try? String(contentsOf: url, encoding: .utf8))
|
||||||
?? (try? String(contentsOf: corpus, encoding: .utf8))
|
?? (try? String(contentsOf: corpus, encoding: .utf8))
|
||||||
?? "# Spike A\n\n(No corpus file found at \(corpus.path).)"
|
?? "# Spike A\n\n(No corpus file found at \(corpus.path).)"
|
||||||
_text = State(initialValue: t)
|
_text = State(initialValue: t)
|
||||||
}
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
bar
|
bar
|
||||||
Divider()
|
Divider()
|
||||||
if reading {
|
if reading {
|
||||||
// Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference)
|
// Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference)
|
||||||
ScrollView(.vertical) {
|
ScrollView(.vertical) {
|
||||||
VStack(alignment: .leading, spacing: 14) {
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
||||||
Text(block.text)
|
Text(block.text)
|
||||||
.font(block.level > 0
|
.font(block.level > 0
|
||||||
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
||||||
: .system(size: 17))
|
: .system(size: 17))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: 720, alignment: .leading)
|
.frame(maxWidth: 720, alignment: .leading)
|
||||||
.padding(.horizontal, 40)
|
.padding(.horizontal, 40)
|
||||||
.padding(.vertical, 24)
|
.padding(.vertical, 24)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
editor
|
editor
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.alert("Anchor not found", isPresented: $staleShown) {
|
.alert("Anchor not found", isPresented: $staleShown) {
|
||||||
Button("OK", role: .cancel) {}
|
Button("OK", role: .cancel) {}
|
||||||
} message: {
|
} message: {
|
||||||
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var editor: some View {
|
private var editor: some View {
|
||||||
// Centered measure via maxWidth (iA-Writer approach; no GeometryReader — it proposes
|
// 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).
|
// 0×0 to the AppKit leaf on first pass and the window never places in this shell).
|
||||||
SourceEditor(
|
SourceEditor(
|
||||||
$text,
|
$text,
|
||||||
language: .markdown,
|
language: .markdown,
|
||||||
configuration: config,
|
configuration: config,
|
||||||
state: $editorState,
|
state: $editorState,
|
||||||
highlightProviders: [ProseHighlighter()],
|
highlightProviders: [ProseHighlighter()],
|
||||||
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })]
|
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })],
|
||||||
)
|
)
|
||||||
.frame(maxWidth: 720)
|
.frame(maxWidth: 720)
|
||||||
.frame(maxWidth: .infinity)
|
.frame(maxWidth: .infinity)
|
||||||
.padding(.horizontal, 24)
|
.padding(.horizontal, 24)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var config: SourceEditorConfiguration {
|
private var config: SourceEditorConfiguration {
|
||||||
SourceEditorConfiguration(
|
SourceEditorConfiguration(
|
||||||
appearance: .init(
|
appearance: .init(
|
||||||
theme: ProseTheme.theme,
|
theme: ProseTheme.theme,
|
||||||
font: ProseTheme.bodyFont,
|
font: ProseTheme.bodyFont,
|
||||||
lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
|
lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
|
||||||
wrapLines: true
|
wrapLines: true,
|
||||||
),
|
),
|
||||||
behavior: .init(reformatAtColumn: 10_000), // never hard-wrap prose
|
behavior: .init(reformatAtColumn: 10000), // never hard-wrap prose
|
||||||
peripherals: .init(
|
peripherals: .init(
|
||||||
showGutter: false, // no line numbers in a writing app
|
showGutter: false, // no line numbers in a writing app
|
||||||
showMinimap: false,
|
showMinimap: false,
|
||||||
showReformattingGuide: false,
|
showReformattingGuide: false,
|
||||||
showFoldingRibbon: false,
|
showFoldingRibbon: false,
|
||||||
invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
|
invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
|
||||||
warningCharacters: []
|
warningCharacters: [],
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var bar: some View {
|
private var bar: some View {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
Toggle("Reading", isOn: $reading)
|
Toggle("Reading", isOn: $reading)
|
||||||
Divider().frame(height: 14)
|
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("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") }
|
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||||||
if let note = anchorNote { Text(note).foregroundStyle(.secondary).font(.caption) }
|
if let note = anchorNote {
|
||||||
Spacer()
|
Text(note).foregroundStyle(.secondary).font(.caption)
|
||||||
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
}
|
||||||
}
|
Spacer()
|
||||||
.padding(.horizontal, 16)
|
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
||||||
.padding(.vertical, 8)
|
}
|
||||||
}
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
}
|
||||||
|
|
||||||
private func applyAnchor(_ quote: String) {
|
private func applyAnchor(_ quote: String) {
|
||||||
let controller = box.controller
|
let controller = box.controller
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
let r = AnchorSearch.range(of: quote, in: text)
|
let r = AnchorSearch.range(of: quote, in: text)
|
||||||
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||||
guard let r else {
|
guard let r else {
|
||||||
anchorNote = nil
|
anchorNote = nil
|
||||||
staleShown = true
|
staleShown = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")"
|
anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")"
|
||||||
guard let controller else { return }
|
guard let controller else { return }
|
||||||
// Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
|
// Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
|
||||||
controller.textView.emphasisManager?.replaceEmphases(
|
controller.textView.emphasisManager?.replaceEmphases(
|
||||||
[Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
|
[Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
|
||||||
for: "fix-card-anchor"
|
for: "fix-card-anchor",
|
||||||
)
|
)
|
||||||
controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
|
controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Captures the live TextViewController at prepareCoordinator (helm #160's captured-controller pattern).
|
/// Captures the live TextViewController at prepareCoordinator (helm #160's captured-controller pattern).
|
||||||
/// Reference box, NOT @State: prepareCoordinator fires inside makeNSViewController — during SwiftUI's
|
/// 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).
|
/// view update — and @State writes there are silently dropped (root cause of the "(no ctrl!)" case).
|
||||||
final class ControllerBox: @unchecked Sendable {
|
final class ControllerBox: @unchecked Sendable {
|
||||||
var controller: TextViewController?
|
var controller: TextViewController?
|
||||||
}
|
}
|
||||||
|
|
||||||
final class ControllerCapture: TextViewCoordinator {
|
final class ControllerCapture: TextViewCoordinator {
|
||||||
let onCapture: (TextViewController) -> Void
|
let onCapture: (TextViewController) -> Void
|
||||||
init(onCapture: @escaping (TextViewController) -> Void) { self.onCapture = onCapture }
|
init(onCapture: @escaping (TextViewController) -> Void) {
|
||||||
func prepareCoordinator(controller: TextViewController) {
|
self.onCapture = onCapture
|
||||||
onCapture(controller)
|
}
|
||||||
}
|
|
||||||
|
func prepareCoordinator(controller: TextViewController) {
|
||||||
|
onCapture(controller)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Reading blocks (Spike B's proven per-block renderer; .full syntax)
|
// MARK: - Reading blocks (Spike B's proven per-block renderer; .full syntax)
|
||||||
|
|
||||||
extension SpikeApp {
|
extension SpikeApp {
|
||||||
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
|
// 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)] {
|
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
|
||||||
md.components(separatedBy: "\n\n").map { para in
|
md.components(separatedBy: "\n\n").map { para in
|
||||||
var level = 0
|
var level = 0
|
||||||
var p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
var p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
if p.hasPrefix("#") {
|
if p.hasPrefix("#") {
|
||||||
let hashes = p.prefix { $0 == "#" }.count
|
let hashes = p.prefix { $0 == "#" }.count
|
||||||
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
||||||
level = hashes
|
level = hashes
|
||||||
}
|
}
|
||||||
let attr = (try? AttributedString(
|
let attr = (try? AttributedString(
|
||||||
markdown: p,
|
markdown: p,
|
||||||
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
|
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
|
||||||
)) ?? AttributedString(p)
|
)) ?? AttributedString(p)
|
||||||
return (level, attr)
|
return (level, attr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
func applicationWillFinishLaunching(_: Notification) {
|
||||||
NSApp.setActivationPolicy(.regular)
|
NSApp.setActivationPolicy(.regular)
|
||||||
}
|
}
|
||||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
||||||
NSApp.activate(ignoringOtherApps: true)
|
func applicationDidFinishLaunching(_: Notification) {
|
||||||
}
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
import PackageDescription
|
import PackageDescription
|
||||||
|
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "TextKit2Spike",
|
name: "TextKit2Spike",
|
||||||
platforms: [.macOS(.v26)],
|
platforms: [.macOS(.v26)],
|
||||||
targets: [.executableTarget(name: "TextKit2Spike")]
|
targets: [.executableTarget(name: "TextKit2Spike")],
|
||||||
)
|
)
|
||||||
@@ -7,79 +7,83 @@ import SwiftUI
|
|||||||
/// NSViewRepresentable wrapper around a scrollable NSTextView, restyling the edited
|
/// NSViewRepresentable wrapper around a scrollable NSTextView, restyling the edited
|
||||||
/// paragraph after each edit burst (textDidChange), preserving undo/IME natively.
|
/// paragraph after each edit burst (textDidChange), preserving undo/IME natively.
|
||||||
struct EditorPane: NSViewRepresentable {
|
struct EditorPane: NSViewRepresentable {
|
||||||
let attributed: NSAttributedString
|
let attributed: NSAttributedString
|
||||||
var onEdit: ((String) -> Void)?
|
var onEdit: ((String) -> Void)?
|
||||||
/// When set, highlight this range (Fix-Card anchor).
|
/// When set, highlight this range (Fix-Card anchor).
|
||||||
var anchorHighlight: NSRange?
|
var anchorHighlight: NSRange?
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSScrollView {
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
let tv = NSTextView()
|
let tv = NSTextView()
|
||||||
tv.isRichText = false // plain source of truth; attributes are presentation-only
|
tv.isRichText = false // plain source of truth; attributes are presentation-only
|
||||||
tv.allowsUndo = true
|
tv.allowsUndo = true
|
||||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
tv.isAutomaticDashSubstitutionEnabled = false
|
tv.isAutomaticDashSubstitutionEnabled = false
|
||||||
tv.isAutomaticTextReplacementEnabled = false
|
tv.isAutomaticTextReplacementEnabled = false
|
||||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||||
tv.usesFindBar = true
|
tv.usesFindBar = true
|
||||||
tv.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
tv.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||||
tv.delegate = context.coordinator
|
tv.delegate = context.coordinator
|
||||||
tv.layoutManager?.allowsNonContiguousLayout = true
|
tv.layoutManager?.allowsNonContiguousLayout = true
|
||||||
let scroll = NSScrollView()
|
let scroll = NSScrollView()
|
||||||
scroll.documentView = tv
|
scroll.documentView = tv
|
||||||
scroll.hasVerticalScroller = true
|
scroll.hasVerticalScroller = true
|
||||||
scroll.autohidesScrollers = true
|
scroll.autohidesScrollers = true
|
||||||
scroll.drawsBackground = true
|
scroll.drawsBackground = true
|
||||||
scroll.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
scroll.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||||
// centered measure: text container inset
|
// centered measure: text container inset
|
||||||
let containerWidth: CGFloat = 640
|
let containerWidth: CGFloat = 640
|
||||||
tv.minSize = NSSize(width: 0, height: 0)
|
tv.minSize = NSSize(width: 0, height: 0)
|
||||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||||
tv.isVerticallyResizable = true
|
tv.isVerticallyResizable = true
|
||||||
tv.isHorizontallyResizable = false
|
tv.isHorizontallyResizable = false
|
||||||
tv.autoresizingMask = [.width]
|
tv.autoresizingMask = [.width]
|
||||||
tv.textContainer?.containerSize = NSSize(width: containerWidth, height: .greatestFiniteMagnitude)
|
tv.textContainer?.containerSize = NSSize(width: containerWidth, height: .greatestFiniteMagnitude)
|
||||||
tv.textContainer?.widthTracksTextView = false
|
tv.textContainer?.widthTracksTextView = false
|
||||||
tv.textContainer?.lineFragmentPadding = 12
|
tv.textContainer?.lineFragmentPadding = 12
|
||||||
context.coordinator.textView = tv
|
context.coordinator.textView = tv
|
||||||
return scroll
|
return scroll
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||||
guard let tv = scroll.documentView as? NSTextView else { return }
|
guard let tv = scroll.documentView as? NSTextView else { return }
|
||||||
if context.coordinator.loadedHash != attributed.hash {
|
if context.coordinator.loadedHash != attributed.hash {
|
||||||
context.coordinator.loadedHash = attributed.hash
|
context.coordinator.loadedHash = attributed.hash
|
||||||
tv.textStorage?.setAttributedString(attributed)
|
tv.textStorage?.setAttributedString(attributed)
|
||||||
}
|
}
|
||||||
applyAnchor(to: tv)
|
applyAnchor(to: tv)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func applyAnchor(to tv: NSTextView) {
|
private func applyAnchor(to tv: NSTextView) {
|
||||||
let storage = tv.textStorage!
|
let storage = tv.textStorage!
|
||||||
storage.removeAttribute(.backgroundColor, range: NSRange(location: 0, length: storage.length))
|
storage.removeAttribute(.backgroundColor, range: NSRange(location: 0, length: storage.length))
|
||||||
guard let anchorHighlight else { return }
|
guard let anchorHighlight else { return }
|
||||||
storage.addAttribute(.backgroundColor, value: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), range: anchorHighlight)
|
storage.addAttribute(.backgroundColor, value: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), range: anchorHighlight)
|
||||||
tv.scrollRangeToVisible(anchorHighlight)
|
tv.scrollRangeToVisible(anchorHighlight)
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator(onEdit: onEdit) }
|
func makeCoordinator() -> Coordinator {
|
||||||
|
Coordinator(onEdit: onEdit)
|
||||||
|
}
|
||||||
|
|
||||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
let onEdit: ((String) -> Void)?
|
let onEdit: ((String) -> Void)?
|
||||||
weak var textView: NSTextView?
|
weak var textView: NSTextView?
|
||||||
var loadedHash: Int = 0
|
var loadedHash: Int = 0
|
||||||
|
|
||||||
init(onEdit: ((String) -> Void)?) { self.onEdit = onEdit }
|
init(onEdit: ((String) -> Void)?) {
|
||||||
|
self.onEdit = onEdit
|
||||||
|
}
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
func textDidChange(_ notification: Notification) {
|
||||||
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
||||||
let sel = tv.selectedRange()
|
let sel = tv.selectedRange()
|
||||||
// Re-attribute the paragraph(s) touching the selection — one paragraph, one pass.
|
// Re-attribute the paragraph(s) touching the selection — one paragraph, one pass.
|
||||||
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
|
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
|
||||||
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
|
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
|
||||||
// re-dim inline syntax across the edited line (already done in reattribute)
|
// re-dim inline syntax across the edited line (already done in reattribute)
|
||||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||||
onEdit?(storage.string)
|
onEdit?(storage.string)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,120 +9,136 @@ import AppKit
|
|||||||
/// Line-based markdown presenter for prose: dimmed syntax, heading scale, paragraph spacing.
|
/// Line-based markdown presenter for prose: dimmed syntax, heading scale, paragraph spacing.
|
||||||
/// Pure functions over text; no AppKit state. Applied post-load and re-applied per edited paragraph.
|
/// Pure functions over text; no AppKit state. Applied post-load and re-applied per edited paragraph.
|
||||||
nonisolated enum ProsePresenter {
|
nonisolated enum ProsePresenter {
|
||||||
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
|
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
|
||||||
|
|
||||||
static func lineKind(_ line: String) -> LineKind {
|
static func lineKind(_ line: String) -> LineKind {
|
||||||
let t = line.drop(while: { $0 == " " })
|
let t = line.drop(while: { $0 == " " })
|
||||||
if t.hasPrefix("## ") { return .heading2 }
|
if t.hasPrefix("## ") {
|
||||||
if t.hasPrefix("# ") { return .heading1 }
|
return .heading2
|
||||||
if t.hasPrefix("> ") { return .quote }
|
}
|
||||||
if !t.isEmpty && t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { return .syntaxOnly }
|
if t.hasPrefix("# ") {
|
||||||
return .body
|
return .heading1
|
||||||
}
|
}
|
||||||
|
if t.hasPrefix("> ") {
|
||||||
|
return .quote
|
||||||
|
}
|
||||||
|
if !t.isEmpty, t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||||
|
return .syntaxOnly
|
||||||
|
}
|
||||||
|
return .body
|
||||||
|
}
|
||||||
|
|
||||||
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
||||||
|
|
||||||
/// Paragraph spacing + font for a line kind, applied via NSParagraphStyle.
|
/// Paragraph spacing + font for a line kind, applied via NSParagraphStyle.
|
||||||
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
||||||
let p = NSMutableParagraphStyle()
|
let p = NSMutableParagraphStyle()
|
||||||
switch kind {
|
switch kind {
|
||||||
case .heading1: p.paragraphSpacing = 18; p.paragraphSpacingBefore = 26
|
case .heading1: p.paragraphSpacing = 18; p.paragraphSpacingBefore = 26
|
||||||
case .heading2: p.paragraphSpacing = 12; p.paragraphSpacingBefore = 20
|
case .heading2: p.paragraphSpacing = 12; p.paragraphSpacingBefore = 20
|
||||||
case .quote: p.paragraphSpacing = 10; p.paragraphSpacingBefore = 10
|
case .quote: p.paragraphSpacing = 10; p.paragraphSpacingBefore = 10
|
||||||
case .syntaxOnly, .body: p.paragraphSpacing = 10
|
case .syntaxOnly, .body: p.paragraphSpacing = 10
|
||||||
}
|
}
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed inline syntax.
|
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed inline syntax.
|
||||||
static func attribute(_ text: String) -> NSAttributedString {
|
static func attribute(_ text: String) -> NSAttributedString {
|
||||||
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
||||||
let ns = text as NSString
|
let ns = text as NSString
|
||||||
ns.enumerateSubstrings(in: NSRange(location: 0, length: ns.length), options: [.byLines]) { line, range, _, _ in
|
ns.enumerateSubstrings(in: NSRange(location: 0, length: ns.length), options: [.byLines]) { line, range, _, _ in
|
||||||
guard let line else { return }
|
guard let line else { return }
|
||||||
let kind = lineKind(line)
|
let kind = lineKind(line)
|
||||||
out.setAttributes(Self.attributes(for: kind), range: range)
|
out.setAttributes(Self.attributes(for: kind), range: range)
|
||||||
dimSyntax(in: out, range: range)
|
dimSyntax(in: out, range: range)
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
||||||
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
||||||
let line = (out.string as NSString).substring(with: paragraphRange)
|
let line = (out.string as NSString).substring(with: paragraphRange)
|
||||||
let kind = lineKind(line)
|
let kind = lineKind(line)
|
||||||
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
|
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
|
||||||
dimSyntax(in: out, range: paragraphRange)
|
dimSyntax(in: out, range: paragraphRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Typography: system serif for prose (New York), 17pt body, scaled headings — the web proto's Iowan/Charter stance.
|
// Typography: system serif for prose (New York), 17pt body, scaled headings — the web proto's Iowan/Charter stance.
|
||||||
static var serif: NSFont { NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed) }
|
static var serif: NSFont {
|
||||||
static var bodyFont: NSFont { NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed)
|
||||||
?? NSFont.systemFont(ofSize: 17) }
|
}
|
||||||
|
|
||||||
static var bodyAttributes: [NSAttributedString.Key: Any] { [
|
static var bodyFont: NSFont {
|
||||||
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
|
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
||||||
] }
|
?? NSFont.systemFont(ofSize: 17)
|
||||||
|
}
|
||||||
|
|
||||||
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
|
static var bodyAttributes: [NSAttributedString.Key: Any] {
|
||||||
switch kind {
|
[
|
||||||
case .heading1: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 9, size: 26) ?? .boldSystemFont(ofSize: 26), .paragraphStyle: paragraph(.heading1)]
|
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
|
||||||
case .heading2: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 8, size: 20) ?? .boldSystemFont(ofSize: 20), .paragraphStyle: paragraph(.heading2)]
|
]
|
||||||
case .quote: bodyAttributes
|
}
|
||||||
case .syntaxOnly, .body: bodyAttributes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
|
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
|
||||||
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
|
switch kind {
|
||||||
let ns = out.string as NSString
|
case .heading1: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 9, size: 26) ?? .boldSystemFont(ofSize: 26), .paragraphStyle: paragraph(.heading1)]
|
||||||
guard range.length > 0 else { return }
|
case .heading2: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 8, size: 20) ?? .boldSystemFont(ofSize: 20), .paragraphStyle: paragraph(.heading2)]
|
||||||
let line = ns.substring(with: range)
|
case .quote: bodyAttributes
|
||||||
let kind = lineKind(line)
|
case .syntaxOnly, .body: bodyAttributes
|
||||||
// prefix markers
|
}
|
||||||
let markerLen: Int
|
}
|
||||||
switch kind {
|
|
||||||
case .heading1: markerLen = 2
|
|
||||||
case .heading2: markerLen = 3
|
|
||||||
case .quote: markerLen = 2
|
|
||||||
default: markerLen = 0
|
|
||||||
}
|
|
||||||
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
|
|
||||||
if markerLen > 0 { out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length))) }
|
|
||||||
// inline marks in body/quote
|
|
||||||
if kind == .body || kind == .quote {
|
|
||||||
for (offset, ch) in line.utf16.enumerated() {
|
|
||||||
if let c = Unicode.Scalar(ch).map({ Character($0) }), inlineSyntax.contains(c) {
|
|
||||||
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Quote anchor (Fix-Card feasibility note for the ADR)
|
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
|
||||||
|
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
|
||||||
|
let ns = out.string as NSString
|
||||||
|
guard range.length > 0 else { return }
|
||||||
|
let line = ns.substring(with: range)
|
||||||
|
let kind = lineKind(line)
|
||||||
|
// prefix markers
|
||||||
|
let markerLen = switch kind {
|
||||||
|
case .heading1: 2
|
||||||
|
case .heading2: 3
|
||||||
|
case .quote: 2
|
||||||
|
default: 0
|
||||||
|
}
|
||||||
|
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
|
||||||
|
if markerLen > 0 {
|
||||||
|
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
|
||||||
|
}
|
||||||
|
// inline marks in body/quote
|
||||||
|
if kind == .body || kind == .quote {
|
||||||
|
for (offset, ch) in line.utf16.enumerated() {
|
||||||
|
if let c = Unicode.Scalar(ch).map({ Character($0) }), inlineSyntax.contains(c) {
|
||||||
|
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Word-tokenized, whitespace/punctuation-tolerant search for `quote` in `text`.
|
// MARK: Quote anchor (Fix-Card feasibility note for the ADR)
|
||||||
/// Returns nil when not found — the stale-anchor case. O(n·m) worst case, fine at 3k words.
|
|
||||||
static func anchorRange(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..<start + quoteWords.count).allSatisfy({ textWords[$0].norm == quoteWords[$0 - start].norm }) {
|
|
||||||
let from = textWords[start].range.lowerBound
|
|
||||||
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
|
||||||
let loc = text.utf16.distance(from: text.startIndex, to: from)
|
|
||||||
let len = text.utf16.distance(from: from, to: to)
|
|
||||||
return NSRange(location: loc, length: len)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct Word { let norm: String; let range: Range<String.Index> }
|
/// Word-tokenized, whitespace/punctuation-tolerant search for `quote` in `text`.
|
||||||
private static func words(_ s: String) -> [Word] {
|
/// Returns nil when not found — the stale-anchor case. O(n·m) worst case, fine at 3k words.
|
||||||
s.split(whereSeparator: \.isWhitespace).map { sub in
|
static func anchorRange(of quote: String, in text: String) -> NSRange? {
|
||||||
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex)
|
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 ..< start + quoteWords.count).allSatisfy({ textWords[$0].norm == quoteWords[$0 - start].norm }) {
|
||||||
|
let from = textWords[start].range.lowerBound
|
||||||
|
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
||||||
|
let loc = text.utf16.distance(from: text.startIndex, to: from)
|
||||||
|
let len = text.utf16.distance(from: from, to: to)
|
||||||
|
return NSRange(location: loc, length: len)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct Word { let norm: String; let range: Range<String.Index> }
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,145 +4,150 @@ import SwiftUI
|
|||||||
|
|
||||||
@main
|
@main
|
||||||
struct SpikeApp: App {
|
struct SpikeApp: App {
|
||||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
Window("Spike B — TextKit2", id: "main") {
|
Window("Spike B — TextKit2", id: "main") {
|
||||||
ContentView()
|
ContentView()
|
||||||
.frame(minWidth: 900, minHeight: 640)
|
.frame(minWidth: 900, minHeight: 640)
|
||||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||||
}
|
}
|
||||||
.windowStyle(.hiddenTitleBar)
|
.windowStyle(.hiddenTitleBar)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check`
|
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check`
|
||||||
init() {
|
init() {
|
||||||
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
|
if CommandLine.arguments.contains("--check") {
|
||||||
}
|
Self.selfCheck(); exit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static func selfCheck() {
|
static func selfCheck() {
|
||||||
let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
|
let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
|
||||||
let quote = "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”"
|
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 = ProsePresenter.anchorRange(of: quote, in: text) else {
|
guard let r = ProsePresenter.anchorRange(of: quote, in: text) else {
|
||||||
print("FAIL: live quote not found"); return
|
print("FAIL: live quote not found"); return
|
||||||
}
|
}
|
||||||
let found = (text as NSString).substring(with: r)
|
let found = (text as NSString).substring(with: r)
|
||||||
assert(found.count > 50 && text.contains(found.trimmingCharacters(in: .whitespacesAndNewlines)))
|
assert(found.count > 50 && text.contains(found.trimmingCharacters(in: .whitespacesAndNewlines)))
|
||||||
// whitespace-tolerant: join with single spaces, must still match
|
// whitespace-tolerant: join with single spaces, must still match
|
||||||
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
||||||
assert(ProsePresenter.anchorRange(of: squished, in: text) != nil, "FAIL: whitespace-tolerant match")
|
assert(ProsePresenter.anchorRange(of: squished, in: text) != nil, "FAIL: whitespace-tolerant match")
|
||||||
// stale anchor: deleted text
|
// stale anchor: deleted text
|
||||||
assert(ProsePresenter.anchorRange(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
assert(ProsePresenter.anchorRange(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
||||||
// reading blocks: heading detected, markup hidden
|
// reading blocks: heading detected, markup hidden
|
||||||
let blocks = SpikeApp.readingBlocks(text)
|
let blocks = SpikeApp.readingBlocks(text)
|
||||||
assert(String(blocks[0].text.characters).hasPrefix("The expected value"), "FAIL: H1 block")
|
assert(String(blocks[0].text.characters).hasPrefix("The expected value"), "FAIL: H1 block")
|
||||||
assert(blocks.allSatisfy { !String($0.text.characters).contains("#") }, "FAIL: markup leaked into reading view")
|
assert(blocks.allSatisfy { !String($0.text.characters).contains("#") }, "FAIL: markup leaked into reading view")
|
||||||
// perf smoke: PERF-3k anchor timing
|
// perf smoke: PERF-3k anchor timing
|
||||||
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
_ = ProsePresenter.anchorRange(of: "The odds are better than they look", in: perf)
|
_ = ProsePresenter.anchorRange(of: "The odds are better than they look", in: perf)
|
||||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
||||||
print("PASS: anchor found @ \(r.location), len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
|
print("PASS: anchor found @ \(r.location), len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
|
// 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)] {
|
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
|
||||||
md.components(separatedBy: "\n\n").map { para in
|
md.components(separatedBy: "\n\n").map { para in
|
||||||
var level = 0, p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
var level = 0, p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
if p.hasPrefix("#") {
|
if p.hasPrefix("#") {
|
||||||
let hashes = p.prefix { $0 == "#" }.count
|
let hashes = p.prefix { $0 == "#" }.count
|
||||||
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
||||||
level = hashes
|
level = hashes
|
||||||
}
|
}
|
||||||
let attr = (try? AttributedString(markdown: p)) ?? AttributedString(p)
|
let attr = (try? AttributedString(markdown: p)) ?? AttributedString(p)
|
||||||
return (level, attr)
|
return (level, attr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
@State private var text: String
|
@State private var text: String
|
||||||
@State private var reading = false
|
@State private var reading = false
|
||||||
@State private var anchor: NSRange?
|
@State private var anchor: NSRange?
|
||||||
@State private var staleShown = false
|
@State private var staleShown = false
|
||||||
@State private var loadMs: Double = 0
|
@State private var loadMs: Double = 0
|
||||||
@State private var doc: NSAttributedString
|
@State private var doc: NSAttributedString
|
||||||
|
|
||||||
// calibration piece default; PERF-3k via arg
|
/// calibration piece default; PERF-3k via arg
|
||||||
init() {
|
init() {
|
||||||
let args = CommandLine.arguments
|
let args = CommandLine.arguments
|
||||||
let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md"
|
let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md"
|
||||||
let t = (try? String(contentsOfFile: path, encoding: .utf8))
|
let t = (try? String(contentsOfFile: path, encoding: .utf8))
|
||||||
?? (try? String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8))
|
?? (try? String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8))
|
||||||
?? "# Spike B\n\n(No corpus file found — run from repo root.)"
|
?? "# Spike B\n\n(No corpus file found — run from repo root.)"
|
||||||
_text = State(initialValue: t)
|
_text = State(initialValue: t)
|
||||||
_doc = State(initialValue: ProsePresenter.attribute(t))
|
_doc = State(initialValue: ProsePresenter.attribute(t))
|
||||||
}
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
bar
|
bar
|
||||||
Divider()
|
Divider()
|
||||||
if reading {
|
if reading {
|
||||||
ScrollView([.vertical]) {
|
ScrollView([.vertical]) {
|
||||||
VStack(alignment: .leading, spacing: 14) {
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
||||||
Text(block.text)
|
Text(block.text)
|
||||||
.font(block.level > 0
|
.font(block.level > 0
|
||||||
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
||||||
: .system(size: 17))
|
: .system(size: 17))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: 720, alignment: .leading)
|
.frame(maxWidth: 720, alignment: .leading)
|
||||||
.padding(.horizontal, 40)
|
.padding(.horizontal, 40)
|
||||||
.padding(.vertical, 24)
|
.padding(.vertical, 24)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
EditorPane(attributed: doc, onEdit: { newText in
|
EditorPane(attributed: doc, onEdit: { newText in
|
||||||
text = newText
|
text = newText
|
||||||
}, anchorHighlight: anchor)
|
}, anchorHighlight: anchor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.alert("Anchor not found", isPresented: $staleShown) {
|
.alert("Anchor not found", isPresented: $staleShown) {
|
||||||
Button("OK", role: .cancel) {}
|
Button("OK", role: .cancel) {}
|
||||||
} message: {
|
} message: {
|
||||||
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var bar: some View {
|
private var bar: some View {
|
||||||
HStack(spacing: 12) {
|
HStack(spacing: 12) {
|
||||||
Toggle("Reading", isOn: $reading)
|
Toggle("Reading", isOn: $reading)
|
||||||
Divider().frame(height: 14)
|
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("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") }
|
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||||||
if let a = anchor { Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption) }
|
if let a = anchor {
|
||||||
Spacer()
|
Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption)
|
||||||
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
}
|
||||||
}
|
Spacer()
|
||||||
.padding(.horizontal, 16)
|
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
||||||
.padding(.vertical, 8)
|
}
|
||||||
}
|
.padding(.horizontal, 16)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
}
|
||||||
|
|
||||||
private func applyAnchor(_ quote: String) {
|
private func applyAnchor(_ quote: String) {
|
||||||
let t0 = DispatchTime.now()
|
let t0 = DispatchTime.now()
|
||||||
let r = ProsePresenter.anchorRange(of: quote, in: text)
|
let r = ProsePresenter.anchorRange(of: quote, in: text)
|
||||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||||
loadMs = ms
|
loadMs = ms
|
||||||
if let r {
|
if let r {
|
||||||
anchor = r
|
anchor = r
|
||||||
} else {
|
} else {
|
||||||
anchor = nil
|
anchor = nil
|
||||||
staleShown = true
|
staleShown = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
func applicationWillFinishLaunching(_: Notification) {
|
||||||
NSApp.setActivationPolicy(.regular)
|
NSApp.setActivationPolicy(.regular)
|
||||||
}
|
}
|
||||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
||||||
NSApp.activate(ignoringOtherApps: true)
|
func applicationDidFinishLaunching(_: Notification) {
|
||||||
}
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user