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]
371 lines
13 KiB
Swift
371 lines
13 KiB
Swift
// Spike C (#54) — THROWAWAY. Block editor shell: ScrollView of blocks, focused block = raw source,
|
|
// unfocused = rendered live. Anchor demo at block granularity. Also: --check self-check.
|
|
// Run: spike/blocks/run.sh (from repo root, branch spike/editor-presentation)
|
|
import AppKit
|
|
import SwiftUI
|
|
|
|
@main
|
|
struct SpikeApp: App {
|
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
|
var body: some Scene {
|
|
Window("Spike C — Blocks", id: "main") {
|
|
ContentView()
|
|
.frame(minWidth: 900, minHeight: 640)
|
|
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
|
}
|
|
.windowStyle(.hiddenTitleBar)
|
|
}
|
|
|
|
// ponytail: one runnable check — `swift run --package-path spike/blocks --check`
|
|
init() {
|
|
if CommandLine.arguments.contains("--check") {
|
|
Self.selfCheck(); exit(0)
|
|
}
|
|
}
|
|
|
|
static func selfCheck() {
|
|
let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
|
|
let blocks = BlockModel.parse(text)
|
|
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)")
|
|
let kinds = blocks.map { BlockModel.kind(of: $0.raw) }
|
|
assert(kinds.contains(.heading2), "FAIL: no ## blocks")
|
|
assert(kinds.contains(.hr), "FAIL: corpus hr (* * *) not detected")
|
|
// rendered text must hide block markup
|
|
let rendered = blocks.map { String(BlockModel.rendered($0.raw).characters) }
|
|
assert(rendered.allSatisfy { !$0.hasPrefix("# ") && !$0.hasPrefix("## ") && !$0.hasPrefix("> ") },
|
|
"FAIL: markup leaked into rendered view")
|
|
assert(rendered.contains { $0.contains("expected value") }, "FAIL: body text missing")
|
|
// 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)
|
|
assert(anchor != nil, "FAIL: anchor block not found")
|
|
// within-block range feasibility: same word search as Spike B, scoped to one block
|
|
if let a = anchor {
|
|
let r = BlockModel.anchorRange(of: "the expected value of joining", in: a.raw)
|
|
assert(r != nil, "FAIL: within-block anchor range")
|
|
}
|
|
// paste-split: multi-paragraph raw splits into blocks
|
|
assert(BlockModel.parse("one\n\ntwo\n\nthree").count == 3, "FAIL: paste-split")
|
|
// perf: block-ify PERF-3k
|
|
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
|
var ms = 0.0
|
|
for _ in 0 ..< 3 {
|
|
let t0 = DispatchTime.now()
|
|
_ = BlockModel.parse(perf)
|
|
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")
|
|
}
|
|
}
|
|
|
|
// MARK: - Content
|
|
|
|
struct ContentView: View {
|
|
@State private var blocks: [Block]
|
|
@State private var focusedID: UUID?
|
|
@State private var anchorID: UUID?
|
|
@State private var staleShown = false
|
|
@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."
|
|
|
|
init() {
|
|
let args = CommandLine.arguments
|
|
let arg = args.count > 1 && args[1] != "--check" ? args[1] : nil
|
|
let t = Self.loadCorpus(arg)
|
|
let t0 = DispatchTime.now()
|
|
_blocks = State(initialValue: BlockModel.parse(t))
|
|
_loadMs = State(initialValue: Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6)
|
|
}
|
|
|
|
/// Arg as given, then the default piece (run.sh passes absolute paths).
|
|
static func loadCorpus(_ arg: String?) -> String {
|
|
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
|
|
}
|
|
}
|
|
return "# Spike C\n\n(No corpus file found — run from repo root.)"
|
|
}
|
|
|
|
var body: some View {
|
|
VStack(spacing: 0) {
|
|
bar
|
|
Divider()
|
|
ScrollViewReader { proxy in
|
|
ScrollView([.vertical]) {
|
|
LazyVStack(alignment: .leading, spacing: 18) {
|
|
ForEach(blocks) { block in
|
|
BlockRow(
|
|
block: block,
|
|
isFocused: focusedID == block.id,
|
|
isAnchored: anchorID == block.id,
|
|
onEdit: { raw in edit(block.id, raw: raw) },
|
|
onSplit: { at in split(block.id, at: at) },
|
|
onMerge: { merge(block.id) },
|
|
onFocus: {
|
|
focusedID = block.id
|
|
hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
|
|
},
|
|
)
|
|
.id(block.id)
|
|
}
|
|
}
|
|
.frame(maxWidth: 720, alignment: .leading)
|
|
.padding(.horizontal, 40)
|
|
.padding(.vertical, 24)
|
|
.onChange(of: anchorID) { id in
|
|
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)
|
|
}
|
|
.alert("Anchor not found", isPresented: $staleShown) {
|
|
Button("OK", role: .cancel) {}
|
|
} message: {
|
|
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
|
}
|
|
}
|
|
|
|
private var bar: some View {
|
|
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("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
|
if anchorID != nil {
|
|
Text("anchored").foregroundStyle(.secondary).font(.caption)
|
|
}
|
|
Spacer()
|
|
Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
|
|
}
|
|
.padding(.horizontal, 16)
|
|
.padding(.vertical, 8)
|
|
}
|
|
|
|
// MARK: block ops
|
|
|
|
private func edit(_ id: UUID, raw: String) {
|
|
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
|
// paste-split: multi-paragraph raw explodes into blocks at the same position
|
|
if raw.contains("\n\n") {
|
|
let parts = BlockModel.parse(raw)
|
|
guard !parts.isEmpty else { return }
|
|
blocks.replaceSubrange(i ... i, with: parts)
|
|
focusedID = parts[parts.count - 1].id
|
|
} else {
|
|
blocks[i].raw = raw
|
|
}
|
|
}
|
|
|
|
private func split(_ id: UUID, at location: Int) {
|
|
guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
|
|
let ns = blocks[i].raw as NSString
|
|
let loc = max(0, min(location, ns.length))
|
|
let before = ns.substring(to: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let after = ns.substring(from: loc).trimmingCharacters(in: .whitespacesAndNewlines)
|
|
blocks[i].raw = before
|
|
blocks.insert(Block(raw: after), at: i + 1)
|
|
focusedID = blocks[i + 1].id
|
|
}
|
|
|
|
private func merge(_ id: UUID) {
|
|
guard let i = blocks.firstIndex(where: { $0.id == id }), i > 0 else { return }
|
|
blocks[i - 1].raw += " " + blocks[i].raw
|
|
blocks.remove(at: i)
|
|
focusedID = blocks[i - 1].id
|
|
}
|
|
|
|
// MARK: anchor (block-granular Fix-Card feasibility)
|
|
|
|
static func findAnchorBlock(quote: String, in blocks: [Block]) -> Block? {
|
|
let qw = normWords(quote)
|
|
guard !qw.isEmpty else { return nil }
|
|
for b in blocks {
|
|
let bw = normWords(BlockModel.plainText(b.raw))
|
|
guard bw.count >= qw.count else { continue }
|
|
if (0 ... bw.count - qw.count).contains(where: { s in
|
|
(s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
|
|
}) {
|
|
return b
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
static func normWords(_ s: String) -> [String] {
|
|
s.split(whereSeparator: \.isWhitespace).map { $0.lowercased().trimmingCharacters(in: .punctuationCharacters) }
|
|
}
|
|
|
|
private func applyAnchor(_ quote: String) {
|
|
let t0 = DispatchTime.now()
|
|
let hit = ContentView.findAnchorBlock(quote: quote, in: blocks)
|
|
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
|
if let hit {
|
|
anchorID = hit.id
|
|
} else {
|
|
anchorID = nil
|
|
staleShown = true
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - One block: rendered, or raw source when focused
|
|
|
|
private struct BlockRow: View {
|
|
let block: Block
|
|
let isFocused: Bool
|
|
let isAnchored: Bool
|
|
let onEdit: (String) -> Void
|
|
let onSplit: (Int) -> Void
|
|
let onMerge: () -> Void
|
|
let onFocus: () -> Void
|
|
@State private var raw: String
|
|
|
|
init(block: Block, isFocused: Bool, isAnchored: Bool,
|
|
onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
|
|
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void)
|
|
{
|
|
self.block = block
|
|
self.isFocused = isFocused
|
|
self.isAnchored = isAnchored
|
|
self.onEdit = onEdit
|
|
self.onSplit = onSplit
|
|
self.onMerge = onMerge
|
|
self.onFocus = onFocus
|
|
_raw = State(initialValue: block.raw)
|
|
}
|
|
|
|
var body: some View {
|
|
Group {
|
|
if isFocused {
|
|
SingleBlockEditor(text: $raw, onEdit: onEdit, onSplit: onSplit, onMerge: onMerge)
|
|
.frame(height: max(28, SingleBlockEditor.height(for: raw)))
|
|
} else {
|
|
rendered.padding(.vertical, 1)
|
|
}
|
|
}
|
|
.frame(maxWidth: .infinity, alignment: .leading)
|
|
.background(isAnchored ? Color(nsColor: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18)) : Color.clear)
|
|
.contentShape(Rectangle())
|
|
.onTapGesture { onFocus() }
|
|
.onChange(of: block.raw) { raw = $0 } // external change (undo of split/merge)
|
|
}
|
|
|
|
@ViewBuilder private var rendered: some View {
|
|
let k = BlockModel.kind(of: block.raw)
|
|
switch k {
|
|
case .heading1:
|
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 26).bold())
|
|
case .heading2:
|
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 20).bold())
|
|
case .quote:
|
|
Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
|
|
.padding(.leading, 14).overlay(alignment: .leading) { Rectangle().fill(.quaternary).frame(width: 3) }
|
|
case .hr:
|
|
Text("⁂").font(.system(size: 17)).frame(maxWidth: .infinity, alignment: .center).foregroundStyle(.secondary)
|
|
case .paragraph:
|
|
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)
|
|
|
|
struct SingleBlockEditor: NSViewRepresentable {
|
|
@Binding var text: String
|
|
var onEdit: (String) -> Void
|
|
var onSplit: (Int) -> Void
|
|
var onMerge: () -> Void
|
|
|
|
static func height(for raw: String) -> CGFloat {
|
|
let s = NSAttributedString(string: raw, attributes: [.font: NSFontManager.shared
|
|
.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17)])
|
|
return ceil(s.boundingRect(with: CGSize(width: 640, height: CGFloat.greatestFiniteMagnitude),
|
|
options: [.usesLineFragmentOrigin]).height) + 8
|
|
}
|
|
|
|
func makeNSView(context: Context) -> NSTextView {
|
|
let tv = NSTextView()
|
|
tv.isRichText = false
|
|
tv.allowsUndo = true // per-block native undo — across-block undo is an honest spike finding
|
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
|
tv.isAutomaticDashSubstitutionEnabled = false
|
|
tv.isAutomaticTextReplacementEnabled = false
|
|
tv.isAutomaticSpellingCorrectionEnabled = false
|
|
tv.drawsBackground = true
|
|
tv.backgroundColor = NSColor(calibratedRed: 0.99, green: 0.965, blue: 0.88, alpha: 1) // "source mode" tint
|
|
tv.typingAttributes = Self.typing
|
|
tv.string = text
|
|
tv.delegate = context.coordinator
|
|
tv.isEditable = true
|
|
tv.isSelectable = true
|
|
tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
|
|
tv.textContainer?.widthTracksTextView = false
|
|
tv.textContainer?.lineFragmentPadding = 4
|
|
tv.isVerticallyResizable = false
|
|
tv.isHorizontallyResizable = false
|
|
context.coordinator.textView = tv
|
|
DispatchQueue.main.async { tv.window?.makeFirstResponder(tv) }
|
|
return tv
|
|
}
|
|
|
|
func updateNSView(_ tv: NSTextView, context _: Context) {
|
|
if tv.string != text {
|
|
tv.string = text
|
|
}
|
|
}
|
|
|
|
func makeCoordinator() -> Coordinator {
|
|
Coordinator(self)
|
|
}
|
|
|
|
static var typing: [NSAttributedString.Key: Any] {
|
|
[
|
|
.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
|
|
]
|
|
}
|
|
|
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
|
let parent: SingleBlockEditor
|
|
weak var textView: NSTextView?
|
|
init(_ parent: SingleBlockEditor) {
|
|
self.parent = parent
|
|
}
|
|
|
|
func textDidChange(_ notification: Notification) {
|
|
guard let tv = notification.object as? NSTextView else { return }
|
|
parent.text = tv.string
|
|
parent.onEdit(tv.string)
|
|
}
|
|
|
|
/// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
|
|
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
|
|
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
|
|
parent.onSplit(textView.selectedRange().location)
|
|
return true
|
|
}
|
|
if commandSelector == #selector(NSResponder.deleteBackward(_:)) {
|
|
if textView.selectedRange().location == 0, textView.selectedRange().length == 0 {
|
|
parent.onMerge()
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
|
func applicationWillFinishLaunching(_: Notification) {
|
|
NSApp.setActivationPolicy(.regular)
|
|
}
|
|
|
|
func applicationDidFinishLaunching(_: Notification) {
|
|
NSApp.activate(ignoringOtherApps: true)
|
|
}
|
|
}
|