diff --git a/spike/blocks/Package.swift b/spike/blocks/Package.swift new file mode 100644 index 0000000..89431fb --- /dev/null +++ b/spike/blocks/Package.swift @@ -0,0 +1,8 @@ +// swift-tools-version:6.2 +import PackageDescription + +let package = Package( + name: "BlocksSpike", + platforms: [.macOS(.v26)], + targets: [.executableTarget(name: "BlocksSpike")] +) diff --git a/spike/blocks/Sources/BlocksSpike/BlockModel.swift b/spike/blocks/Sources/BlocksSpike/BlockModel.swift new file mode 100644 index 0000000..f887b9e --- /dev/null +++ b/spike/blocks/Sources/BlocksSpike/BlockModel.swift @@ -0,0 +1,84 @@ +// Spike C (#54): SwiftUI block editor (live preview, mode C) — THROWAWAY, answers a question, not product code. +// Question: can a block editor reach live-preview mode C without becoming the project? +// Run: spike/blocks/run.sh (from repo root, branch spike/editor-presentation) + +import Foundation + +struct Block: Identifiable, Equatable { + var id = UUID() + var raw: String // markdown source incl. marker; kind is derived, never stored +} + +nonisolated enum BlockModel { + enum Kind { case heading1, heading2, paragraph, quote, hr } + + /// 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). + static func parse(_ md: String) -> [Block] { + md.components(separatedBy: "\n\n") + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .map { Block(raw: $0) } + } + + static func kind(of raw: String) -> Kind { + if raw.hasPrefix("## ") { return .heading2 } + if raw.hasPrefix("# ") { 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 + /// structure is ours, exactly like Spike B's reading mode). + static func rendered(_ raw: String) -> AttributedString { + var p = raw + let k = kind(of: raw) + switch k { + case .heading1: p = String(p.dropFirst(2)) + case .heading2: p = String(p.dropFirst(3)) + case .quote: p = String(p.dropFirst(2)) + case .hr: return AttributedString("⁂") + case .paragraph: break + } + var opts = AttributedString.MarkdownParsingOptions() + opts.interpretedSyntax = .inlineOnlyPreservingWhitespace + return (try? AttributedString(markdown: p, options: opts)) ?? AttributedString(p) + } + + /// Marker-stripped plain text (anchor search runs over this). + static func plainText(_ raw: String) -> String { + switch kind(of: raw) { + case .heading1: return String(raw.dropFirst(2)) + case .heading2: return String(raw.dropFirst(3)) + case .quote: return String(raw.dropFirst(2)) + case .hr: return "" + case .paragraph: return raw + } + } + + /// Within-block UTF-16 range of `quote` (word-tokenized, whitespace-tolerant — same + /// strategy as Spike B's anchorRange, scoped to one block). nil = stale. + static func anchorRange(of quote: String, in raw: String) -> NSRange? { + let text = plainText(raw) + let textWords = words(text), 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 + return NSRange(location: text.utf16.distance(from: text.startIndex, to: from), + length: text.utf16.distance(from: from, to: to)) + } + } + return nil + } + + private struct Word { let norm: String; let range: Range } + private static func words(_ s: String) -> [Word] { + s.split(whereSeparator: \.isWhitespace).map { sub in + Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), + range: sub.startIndex ..< sub.endIndex) + } + } +} diff --git a/spike/blocks/Sources/BlocksSpike/SpikeApp.swift b/spike/blocks/Sources/BlocksSpike/SpikeApp.swift new file mode 100644 index 0000000..ec24119 --- /dev/null +++ b/spike/blocks/Sources/BlocksSpike/SpikeApp.swift @@ -0,0 +1,350 @@ +// 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({ $0 }) { + 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: Notification) { + NSApp.setActivationPolicy(.regular) + } + func applicationDidFinishLaunching(_ notification: Notification) { + NSApp.activate(ignoringOtherApps: true) + } +} diff --git a/spike/blocks/assets/spikeC-anchor.png b/spike/blocks/assets/spikeC-anchor.png new file mode 100644 index 0000000..e8deab4 Binary files /dev/null and b/spike/blocks/assets/spikeC-anchor.png differ diff --git a/spike/blocks/assets/spikeC-calibration.png b/spike/blocks/assets/spikeC-calibration.png new file mode 100644 index 0000000..4fd5aa5 Binary files /dev/null and b/spike/blocks/assets/spikeC-calibration.png differ diff --git a/spike/blocks/assets/spikeC-editing.png b/spike/blocks/assets/spikeC-editing.png new file mode 100644 index 0000000..4b60228 Binary files /dev/null and b/spike/blocks/assets/spikeC-editing.png differ diff --git a/spike/blocks/assets/spikeC-ime.png b/spike/blocks/assets/spikeC-ime.png new file mode 100644 index 0000000..3524d7d Binary files /dev/null and b/spike/blocks/assets/spikeC-ime.png differ diff --git a/spike/blocks/assets/spikeC-paste.png b/spike/blocks/assets/spikeC-paste.png new file mode 100644 index 0000000..ec5cf82 Binary files /dev/null and b/spike/blocks/assets/spikeC-paste.png differ diff --git a/spike/blocks/assets/spikeC-perf.png b/spike/blocks/assets/spikeC-perf.png new file mode 100644 index 0000000..9d23bad Binary files /dev/null and b/spike/blocks/assets/spikeC-perf.png differ diff --git a/spike/blocks/assets/spikeC-selection.png b/spike/blocks/assets/spikeC-selection.png new file mode 100644 index 0000000..9d54551 Binary files /dev/null and b/spike/blocks/assets/spikeC-selection.png differ diff --git a/spike/blocks/assets/spikeC-split.png b/spike/blocks/assets/spikeC-split.png new file mode 100644 index 0000000..980c85b Binary files /dev/null and b/spike/blocks/assets/spikeC-split.png differ diff --git a/spike/blocks/assets/spikeC-stale.png b/spike/blocks/assets/spikeC-stale.png new file mode 100644 index 0000000..bc64616 Binary files /dev/null and b/spike/blocks/assets/spikeC-stale.png differ diff --git a/spike/blocks/assets/spikeC-typed.png b/spike/blocks/assets/spikeC-typed.png new file mode 100644 index 0000000..aa5d865 Binary files /dev/null and b/spike/blocks/assets/spikeC-typed.png differ diff --git a/spike/blocks/run.sh b/spike/blocks/run.sh new file mode 100755 index 0000000..937f203 --- /dev/null +++ b/spike/blocks/run.sh @@ -0,0 +1,28 @@ +#!/bin/zsh +# ponytail: wrap the SPM binary in a minimal .app — SwiftUI needs a bundle to make windows. +set -e +ROOT="$PWD" +cd "$(dirname "$0")" +swift build 2>&1 | tail -1 +APP=.build/BlocksSpike.app +rm -rf "$APP" && mkdir -p "$APP/Contents/MacOS" +cp .build/debug/BlocksSpike "$APP/Contents/MacOS/" +cat > "$APP/Contents/Info.plist" <<'PLIST' + + + + + CFBundleExecutableBlocksSpike + CFBundleIdentifierde.babylondreams.museion.spike-c + CFBundleNameSpike C — Blocks + CFBundlePackageTypeAPPL + LSMinimumSystemVersion26.0 + NSHighResolutionCapable + NSSupportsAutomaticWindowRestoration + + +PLIST +# ponytail: always hand the binary an ABSOLUTE corpus path — its cwd here is spike/blocks +ARG="${1:-$ROOT/spike/prose/the-expected-value-of-showing.md}" +case "$ARG" in /*) ;; *) ARG="$ROOT/$ARG" ;; esac +exec "$APP/Contents/MacOS/BlocksSpike" "$ARG"