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
@@ -7,79 +7,83 @@ import SwiftUI
|
||||
/// NSViewRepresentable wrapper around a scrollable NSTextView, restyling the edited
|
||||
/// paragraph after each edit burst (textDidChange), preserving undo/IME natively.
|
||||
struct EditorPane: NSViewRepresentable {
|
||||
let attributed: NSAttributedString
|
||||
var onEdit: ((String) -> Void)?
|
||||
/// When set, highlight this range (Fix-Card anchor).
|
||||
var anchorHighlight: NSRange?
|
||||
let attributed: NSAttributedString
|
||||
var onEdit: ((String) -> Void)?
|
||||
/// When set, highlight this range (Fix-Card anchor).
|
||||
var anchorHighlight: NSRange?
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = NSTextView()
|
||||
tv.isRichText = false // plain source of truth; attributes are presentation-only
|
||||
tv.allowsUndo = true
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.usesFindBar = true
|
||||
tv.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
tv.delegate = context.coordinator
|
||||
tv.layoutManager?.allowsNonContiguousLayout = true
|
||||
let scroll = NSScrollView()
|
||||
scroll.documentView = tv
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autohidesScrollers = true
|
||||
scroll.drawsBackground = true
|
||||
scroll.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||
// centered measure: text container inset
|
||||
let containerWidth: CGFloat = 640
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.textContainer?.containerSize = NSSize(width: containerWidth, height: .greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = false
|
||||
tv.textContainer?.lineFragmentPadding = 12
|
||||
context.coordinator.textView = tv
|
||||
return scroll
|
||||
}
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = NSTextView()
|
||||
tv.isRichText = false // plain source of truth; attributes are presentation-only
|
||||
tv.allowsUndo = true
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.usesFindBar = true
|
||||
tv.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
tv.delegate = context.coordinator
|
||||
tv.layoutManager?.allowsNonContiguousLayout = true
|
||||
let scroll = NSScrollView()
|
||||
scroll.documentView = tv
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autohidesScrollers = true
|
||||
scroll.drawsBackground = true
|
||||
scroll.backgroundColor = NSColor(white: 0.98, alpha: 1)
|
||||
// centered measure: text container inset
|
||||
let containerWidth: CGFloat = 640
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.textContainer?.containerSize = NSSize(width: containerWidth, height: .greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = false
|
||||
tv.textContainer?.lineFragmentPadding = 12
|
||||
context.coordinator.textView = tv
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? NSTextView else { return }
|
||||
if context.coordinator.loadedHash != attributed.hash {
|
||||
context.coordinator.loadedHash = attributed.hash
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
}
|
||||
applyAnchor(to: tv)
|
||||
}
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? NSTextView else { return }
|
||||
if context.coordinator.loadedHash != attributed.hash {
|
||||
context.coordinator.loadedHash = attributed.hash
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
}
|
||||
applyAnchor(to: tv)
|
||||
}
|
||||
|
||||
private func applyAnchor(to tv: NSTextView) {
|
||||
let storage = tv.textStorage!
|
||||
storage.removeAttribute(.backgroundColor, range: NSRange(location: 0, length: storage.length))
|
||||
guard let anchorHighlight else { return }
|
||||
storage.addAttribute(.backgroundColor, value: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), range: anchorHighlight)
|
||||
tv.scrollRangeToVisible(anchorHighlight)
|
||||
}
|
||||
private func applyAnchor(to tv: NSTextView) {
|
||||
let storage = tv.textStorage!
|
||||
storage.removeAttribute(.backgroundColor, range: NSRange(location: 0, length: storage.length))
|
||||
guard let anchorHighlight else { return }
|
||||
storage.addAttribute(.backgroundColor, value: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), range: anchorHighlight)
|
||||
tv.scrollRangeToVisible(anchorHighlight)
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(onEdit: onEdit) }
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator(onEdit: onEdit)
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
let onEdit: ((String) -> Void)?
|
||||
weak var textView: NSTextView?
|
||||
var loadedHash: Int = 0
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
let onEdit: ((String) -> Void)?
|
||||
weak var textView: NSTextView?
|
||||
var loadedHash: Int = 0
|
||||
|
||||
init(onEdit: ((String) -> Void)?) { self.onEdit = onEdit }
|
||||
init(onEdit: ((String) -> Void)?) {
|
||||
self.onEdit = onEdit
|
||||
}
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
||||
let sel = tv.selectedRange()
|
||||
// Re-attribute the paragraph(s) touching the selection — one paragraph, one pass.
|
||||
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
|
||||
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
|
||||
// re-dim inline syntax across the edited line (already done in reattribute)
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
onEdit?(storage.string)
|
||||
}
|
||||
}
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
|
||||
let sel = tv.selectedRange()
|
||||
// Re-attribute the paragraph(s) touching the selection — one paragraph, one pass.
|
||||
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
|
||||
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
|
||||
// re-dim inline syntax across the edited line (already done in reattribute)
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
onEdit?(storage.string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,120 +9,136 @@ import AppKit
|
||||
/// 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.
|
||||
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 {
|
||||
let t = line.drop(while: { $0 == " " })
|
||||
if t.hasPrefix("## ") { return .heading2 }
|
||||
if t.hasPrefix("# ") { return .heading1 }
|
||||
if t.hasPrefix("> ") { return .quote }
|
||||
if !t.isEmpty && t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { return .syntaxOnly }
|
||||
return .body
|
||||
}
|
||||
static func lineKind(_ line: String) -> LineKind {
|
||||
let t = line.drop(while: { $0 == " " })
|
||||
if t.hasPrefix("## ") {
|
||||
return .heading2
|
||||
}
|
||||
if t.hasPrefix("# ") {
|
||||
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.
|
||||
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
||||
let p = NSMutableParagraphStyle()
|
||||
switch kind {
|
||||
case .heading1: p.paragraphSpacing = 18; p.paragraphSpacingBefore = 26
|
||||
case .heading2: p.paragraphSpacing = 12; p.paragraphSpacingBefore = 20
|
||||
case .quote: p.paragraphSpacing = 10; p.paragraphSpacingBefore = 10
|
||||
case .syntaxOnly, .body: p.paragraphSpacing = 10
|
||||
}
|
||||
return p
|
||||
}
|
||||
/// Paragraph spacing + font for a line kind, applied via NSParagraphStyle.
|
||||
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
||||
let p = NSMutableParagraphStyle()
|
||||
switch kind {
|
||||
case .heading1: p.paragraphSpacing = 18; p.paragraphSpacingBefore = 26
|
||||
case .heading2: p.paragraphSpacing = 12; p.paragraphSpacingBefore = 20
|
||||
case .quote: p.paragraphSpacing = 10; p.paragraphSpacingBefore = 10
|
||||
case .syntaxOnly, .body: p.paragraphSpacing = 10
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed inline syntax.
|
||||
static func attribute(_ text: String) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
||||
let ns = text as NSString
|
||||
ns.enumerateSubstrings(in: NSRange(location: 0, length: ns.length), options: [.byLines]) { line, range, _, _ in
|
||||
guard let line else { return }
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: range)
|
||||
dimSyntax(in: out, range: range)
|
||||
}
|
||||
return out
|
||||
}
|
||||
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed inline syntax.
|
||||
static func attribute(_ text: String) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
||||
let ns = text as NSString
|
||||
ns.enumerateSubstrings(in: NSRange(location: 0, length: ns.length), options: [.byLines]) { line, range, _, _ in
|
||||
guard let line else { return }
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: range)
|
||||
dimSyntax(in: out, range: range)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
||||
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
||||
let line = (out.string as NSString).substring(with: paragraphRange)
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
|
||||
dimSyntax(in: out, range: paragraphRange)
|
||||
}
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
||||
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
||||
let line = (out.string as NSString).substring(with: paragraphRange)
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), 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.
|
||||
static var serif: NSFont { NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed) }
|
||||
static var bodyFont: NSFont { NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
||||
?? NSFont.systemFont(ofSize: 17) }
|
||||
// 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 bodyAttributes: [NSAttributedString.Key: Any] { [
|
||||
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
|
||||
] }
|
||||
static var bodyFont: NSFont {
|
||||
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] {
|
||||
switch kind {
|
||||
case .heading1: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 9, size: 26) ?? .boldSystemFont(ofSize: 26), .paragraphStyle: paragraph(.heading1)]
|
||||
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
|
||||
}
|
||||
}
|
||||
static var bodyAttributes: [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
|
||||
]
|
||||
}
|
||||
|
||||
/// 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: 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static func attributes(for kind: LineKind) -> [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)]
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// 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`.
|
||||
/// 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
|
||||
}
|
||||
// MARK: Quote anchor (Fix-Card feasibility note for the ADR)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
/// Word-tokenized, whitespace/punctuation-tolerant search for `quote` in `text`.
|
||||
/// 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> }
|
||||
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
|
||||
struct SpikeApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
var body: some Scene {
|
||||
Window("Spike B — TextKit2", id: "main") {
|
||||
ContentView()
|
||||
.frame(minWidth: 900, minHeight: 640)
|
||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||
}
|
||||
.windowStyle(.hiddenTitleBar)
|
||||
}
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
var body: some Scene {
|
||||
Window("Spike B — TextKit2", id: "main") {
|
||||
ContentView()
|
||||
.frame(minWidth: 900, minHeight: 640)
|
||||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||||
}
|
||||
.windowStyle(.hiddenTitleBar)
|
||||
}
|
||||
|
||||
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check`
|
||||
init() {
|
||||
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
|
||||
}
|
||||
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --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 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 {
|
||||
print("FAIL: live quote not found"); return
|
||||
}
|
||||
let found = (text as NSString).substring(with: r)
|
||||
assert(found.count > 50 && text.contains(found.trimmingCharacters(in: .whitespacesAndNewlines)))
|
||||
// whitespace-tolerant: join with single spaces, must still match
|
||||
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
||||
assert(ProsePresenter.anchorRange(of: squished, in: text) != nil, "FAIL: whitespace-tolerant match")
|
||||
// stale anchor: deleted text
|
||||
assert(ProsePresenter.anchorRange(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
||||
// reading blocks: heading detected, markup hidden
|
||||
let blocks = SpikeApp.readingBlocks(text)
|
||||
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")
|
||||
// perf smoke: PERF-3k anchor timing
|
||||
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
||||
let t0 = DispatchTime.now()
|
||||
_ = ProsePresenter.anchorRange(of: "The odds are better than they look", in: perf)
|
||||
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")
|
||||
}
|
||||
static func selfCheck() {
|
||||
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.”"
|
||||
guard let r = ProsePresenter.anchorRange(of: quote, in: text) else {
|
||||
print("FAIL: live quote not found"); return
|
||||
}
|
||||
let found = (text as NSString).substring(with: r)
|
||||
assert(found.count > 50 && text.contains(found.trimmingCharacters(in: .whitespacesAndNewlines)))
|
||||
// whitespace-tolerant: join with single spaces, must still match
|
||||
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
||||
assert(ProsePresenter.anchorRange(of: squished, in: text) != nil, "FAIL: whitespace-tolerant match")
|
||||
// stale anchor: deleted text
|
||||
assert(ProsePresenter.anchorRange(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
||||
// reading blocks: heading detected, markup hidden
|
||||
let blocks = SpikeApp.readingBlocks(text)
|
||||
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")
|
||||
// perf smoke: PERF-3k anchor timing
|
||||
let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
|
||||
let t0 = DispatchTime.now()
|
||||
_ = ProsePresenter.anchorRange(of: "The odds are better than they look", in: perf)
|
||||
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")
|
||||
}
|
||||
|
||||
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
|
||||
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
|
||||
md.components(separatedBy: "\n\n").map { para in
|
||||
var level = 0, p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if p.hasPrefix("#") {
|
||||
let hashes = p.prefix { $0 == "#" }.count
|
||||
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
||||
level = hashes
|
||||
}
|
||||
let attr = (try? AttributedString(markdown: p)) ?? AttributedString(p)
|
||||
return (level, attr)
|
||||
}
|
||||
}
|
||||
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
|
||||
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
|
||||
md.components(separatedBy: "\n\n").map { para in
|
||||
var level = 0, p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if p.hasPrefix("#") {
|
||||
let hashes = p.prefix { $0 == "#" }.count
|
||||
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
||||
level = hashes
|
||||
}
|
||||
let attr = (try? AttributedString(markdown: p)) ?? AttributedString(p)
|
||||
return (level, attr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@State private var text: String
|
||||
@State private var reading = false
|
||||
@State private var anchor: NSRange?
|
||||
@State private var staleShown = false
|
||||
@State private var loadMs: Double = 0
|
||||
@State private var doc: NSAttributedString
|
||||
@State private var text: String
|
||||
@State private var reading = false
|
||||
@State private var anchor: NSRange?
|
||||
@State private var staleShown = false
|
||||
@State private var loadMs: Double = 0
|
||||
@State private var doc: NSAttributedString
|
||||
|
||||
// calibration piece default; PERF-3k via arg
|
||||
init() {
|
||||
let args = CommandLine.arguments
|
||||
let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md"
|
||||
let t = (try? String(contentsOfFile: path, 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.)"
|
||||
_text = State(initialValue: t)
|
||||
_doc = State(initialValue: ProsePresenter.attribute(t))
|
||||
}
|
||||
/// calibration piece default; PERF-3k via arg
|
||||
init() {
|
||||
let args = CommandLine.arguments
|
||||
let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md"
|
||||
let t = (try? String(contentsOfFile: path, 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.)"
|
||||
_text = State(initialValue: t)
|
||||
_doc = State(initialValue: ProsePresenter.attribute(t))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
bar
|
||||
Divider()
|
||||
if reading {
|
||||
ScrollView([.vertical]) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
||||
Text(block.text)
|
||||
.font(block.level > 0
|
||||
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
||||
: .system(size: 17))
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 720, alignment: .leading)
|
||||
.padding(.horizontal, 40)
|
||||
.padding(.vertical, 24)
|
||||
}
|
||||
} else {
|
||||
EditorPane(attributed: doc, onEdit: { newText in
|
||||
text = newText
|
||||
}, anchorHighlight: anchor)
|
||||
}
|
||||
}
|
||||
.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.")
|
||||
}
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
bar
|
||||
Divider()
|
||||
if reading {
|
||||
ScrollView([.vertical]) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
||||
Text(block.text)
|
||||
.font(block.level > 0
|
||||
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
||||
: .system(size: 17))
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 720, alignment: .leading)
|
||||
.padding(.horizontal, 40)
|
||||
.padding(.vertical, 24)
|
||||
}
|
||||
} else {
|
||||
EditorPane(attributed: doc, onEdit: { newText in
|
||||
text = newText
|
||||
}, anchorHighlight: anchor)
|
||||
}
|
||||
}
|
||||
.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) {
|
||||
Toggle("Reading", isOn: $reading)
|
||||
Divider().frame(height: 14)
|
||||
Button("Anchor: DM quote") { applyAnchor(#"“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”"#) }
|
||||
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||||
if let a = anchor { Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption) }
|
||||
Spacer()
|
||||
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
private var bar: some View {
|
||||
HStack(spacing: 12) {
|
||||
Toggle("Reading", isOn: $reading)
|
||||
Divider().frame(height: 14)
|
||||
Button("Anchor: DM quote") { applyAnchor(#"“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”"#) }
|
||||
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||||
if let a = anchor {
|
||||
Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption)
|
||||
}
|
||||
Spacer()
|
||||
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
private func applyAnchor(_ quote: String) {
|
||||
let t0 = DispatchTime.now()
|
||||
let r = ProsePresenter.anchorRange(of: quote, in: text)
|
||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||
loadMs = ms
|
||||
if let r {
|
||||
anchor = r
|
||||
} else {
|
||||
anchor = nil
|
||||
staleShown = true
|
||||
}
|
||||
}
|
||||
private func applyAnchor(_ quote: String) {
|
||||
let t0 = DispatchTime.now()
|
||||
let r = ProsePresenter.anchorRange(of: quote, in: text)
|
||||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||||
loadMs = ms
|
||||
if let r {
|
||||
anchor = r
|
||||
} else {
|
||||
anchor = nil
|
||||
staleShown = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
func applicationWillFinishLaunching(_: Notification) {
|
||||
NSApp.setActivationPolicy(.regular)
|
||||
}
|
||||
|
||||
func applicationDidFinishLaunching(_: Notification) {
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user