feat(microblog): set and create categories
A piece's `category:` frontmatter line now travels to Micro.blog: a first send carries the list beside title and content, and a re-send replaces the post's categories with exactly the piece's list — only when the piece has the line (opt-in by key; `[]` clears; no line leaves the blog's). Naming a category Micro.blog doesn't know creates it there, so there is no separate create step. The publish sheet gains a Categories field: a comma list with the system completion menu over the blog's own categories. The system replaces the whole field text with a completion, so the completion is the merge — a pick adds, a half-typed last word is replaced. The edit lands on the piece at the send (a failed write refuses with nothing on the wire); Publish with a pending edit applies it first and flips the post that send touched. The one-line codec lives in PostFrontmatter (line-bounded; backslashes and quotes escaped; a Set de-duplicates). Import keeps an imported `category:` line — the writer's classification, unlike the micropub bookkeeping keys. Reviewed twice (two-axis during the build, finish-audit after): the stale pending baseline after a failed step, the backslash round-trip, and the publish targeting the caller's possibly-stale URL were found and fixed before this commit. 39 of the 40 new or changed pins were watched fail on their own guard. Rail 791/791; SwiftFormat and SwiftLint clean. Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG [Unreleased], PRD S6.1, the devlog, and the swift wiki (text completion is a whole-text contract). Closes #207
This commit is contained in:
1 parent
6aa31a419a
commit
6db4cf8cf1
18 files changed
+1629
-67
No files matched your search
@@ -0,0 +1,431 @@
|
||||
// PROTOTYPE — #207 "Allow setting and creating Micro.blog categories". THROWAWAY; not part of the app target.
|
||||
// Build: swiftc -O -parse-as-library prototypes/MicropubCategoriesPrototype.swift -o /tmp/micropub_categories_proto
|
||||
// Run: copy the binary into /tmp/MicropubCategoriesProto.app/Contents/MacOS/ (Info.plist: CFBundleExecutable=
|
||||
// micropub_categories_proto, CFBundlePackageType=APPL) and `open` that bundle — a bare binary never gets
|
||||
// real keyboard activation. `<binary> --selftest` runs the field-text ↔ list contract checks and exits.
|
||||
// Under test: which control carries the publish sheet's editable "Categories" field (suggestions = the blog's
|
||||
// existing categories). ONE binary, THREE windows around the SAME mock of MicropubPublishSheet — only the
|
||||
// control differs:
|
||||
// A — comma field + a visible "On your blog:" row of link-styled category buttons
|
||||
// B — comma field + the native completion menu (.textInputSuggestions)
|
||||
// C — AppKit NSTokenField (Mail-style tokens + the delegate completion menu)
|
||||
// Each window's mono state line is exactly what the control would write to the piece's frontmatter (contract
|
||||
// below). Launch env PROTO_SEED=1 pre-fills all three with every dummy category, PROTO_B_TEXT=Te pre-types and
|
||||
// focuses B's field, PROTO_MANY=1 swaps in ~40 categories (screenshot scenarios); default is empty/five.
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
// MARK: - Tokens (inlined from Museion/DesignTokens.swift)
|
||||
|
||||
enum Tok {
|
||||
static let background = Color(red: 0xFA / 255, green: 0xF9 / 255, blue: 0xF3 / 255)
|
||||
static let muted = Color(red: 0x6B / 255, green: 0x69 / 255, blue: 0x64 / 255)
|
||||
static let accent = Color(red: 0xC9 / 255, green: 0x64 / 255, blue: 0x42 / 255)
|
||||
/// The sheet's label/note face and its field face (MicropubPublishSheet).
|
||||
static let monoNote = Font.system(size: 11, design: .monospaced)
|
||||
static let monoField = Font.system(size: 12, design: .monospaced)
|
||||
}
|
||||
|
||||
// MARK: - #207 contract: field text ↔ list ↔ frontmatter
|
||||
|
||||
/// Quote-aware comma split — the field's elements (a comma inside double quotes does not split).
|
||||
func commaSplit(_ text: String) -> [String] {
|
||||
var parts: [String] = []
|
||||
var current = ""
|
||||
var quoted = false
|
||||
for char in text {
|
||||
if char == ",", !quoted {
|
||||
parts.append(current)
|
||||
current = ""
|
||||
} else {
|
||||
if char == "\"" {
|
||||
quoted.toggle()
|
||||
}
|
||||
current.append(char)
|
||||
}
|
||||
}
|
||||
parts.append(current)
|
||||
return parts
|
||||
}
|
||||
|
||||
/// Field text → list: split on commas OUTSIDE double quotes, trim, strip one surrounding quote pair, drop
|
||||
/// empties, de-duplicate (first occurrence wins).
|
||||
func parseCategories(_ text: String) -> [String] {
|
||||
var seen = Set<String>()
|
||||
return commaSplit(text).compactMap { part in
|
||||
var name = part.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if name.count >= 2, name.hasPrefix("\""), name.hasSuffix("\"") {
|
||||
name = String(name.dropFirst().dropLast())
|
||||
}
|
||||
guard !name.isEmpty, seen.insert(name).inserted else { return nil }
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
/// List → frontmatter line: a name carrying `,` `[` `]` or `"` is wrapped in double quotes, inner `"` escaped.
|
||||
func frontmatterLine(_ names: [String]) -> String {
|
||||
let cells = names.map { name in
|
||||
name.contains(where: { ",[]\"".contains($0) }) ? "\"" + name.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : name
|
||||
}
|
||||
return "category: [" + cells.joined(separator: ", ") + "]"
|
||||
}
|
||||
|
||||
func stateLine(_ names: [String]) -> String {
|
||||
names.isEmpty ? "No categories → category: []" : "Travels as → " + frontmatterLine(names)
|
||||
}
|
||||
|
||||
/// A name as written into the comma FIELD (A/B): quoted when it carries a comma, so the parser reads it back.
|
||||
func fieldForm(_ name: String) -> String {
|
||||
name.contains(",") ? "\"\(name)\"" : name
|
||||
}
|
||||
|
||||
/// The word being typed: the last element of the quote-aware split, trimmed and quote-stripped like a
|
||||
/// parsed name ("" when the field is empty or ends with a comma).
|
||||
func partial(_ text: String) -> String {
|
||||
let last = commaSplit(text).last?.trimmingCharacters(in: .whitespaces) ?? ""
|
||||
guard last.count >= 2, last.hasPrefix("\""), last.hasSuffix("\"") else { return last }
|
||||
return String(last.dropFirst().dropLast())
|
||||
}
|
||||
|
||||
func sameName(_ a: String, _ b: String) -> Bool {
|
||||
a.caseInsensitiveCompare(b) == .orderedSame
|
||||
}
|
||||
|
||||
/// The last thing typed is itself a known category → nothing is half-typed.
|
||||
func finished(_ text: String, blog: [String]) -> Bool {
|
||||
blog.contains { sameName($0, partial(text)) }
|
||||
}
|
||||
|
||||
/// B's menu: every category while nothing is typed or the last word is a finished category, else the
|
||||
/// prefix matches (blog order kept); present names are never offered.
|
||||
func suggestions(text: String, blog: [String]) -> [String] {
|
||||
let names = parseCategories(text)
|
||||
let p = partial(text)
|
||||
let candidates = (p.isEmpty || finished(text, blog: blog)) ? blog : blog.filter { $0.lowercased().hasPrefix(p.lowercased()) }
|
||||
return candidates.filter { name in !names.contains { sameName($0, name) } }
|
||||
}
|
||||
|
||||
/// B — what the field becomes when `name` is picked. The system replaces the WHOLE text with the
|
||||
/// completion, so the completion IS the merge: a pick ADDS (never duplicates); a half-typed word goes.
|
||||
/// Pure (field text, picked name, blog) → String; ported into the real sheet and unit-tested there.
|
||||
func completion(text: String, picking name: String, blog: [String]) -> String {
|
||||
var names = parseCategories(text)
|
||||
let p = partial(text)
|
||||
let halfTyped = !p.isEmpty && !finished(text, blog: blog) && name.lowercased().hasPrefix(p.lowercased()) && !sameName(p, name)
|
||||
if halfTyped, let last = names.last, sameName(last, p) {
|
||||
names.removeLast()
|
||||
}
|
||||
if !names.contains(where: { sameName($0, name) }) {
|
||||
names.append(name)
|
||||
}
|
||||
return names.map(fieldForm).joined(separator: ", ")
|
||||
}
|
||||
|
||||
/// `--selftest`: the contract above, run for real (asserts are compiled out under -O).
|
||||
func contractSelfCheck() -> Never {
|
||||
let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||
let swiftBlog = ["Swift", "SwiftUI"]
|
||||
let others = ["Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||
let quotedPick = "Tech, \"Tech, general\""
|
||||
let checks: [(String, Bool)] = [
|
||||
("bare text", parseCategories(" Tech, Notes,, tech ") == ["Tech", "Notes", "tech"]),
|
||||
("quoted comma", parseCategories("\"Tech, general\", Tech") == ["Tech, general", "Tech"]),
|
||||
("dedupe first wins", parseCategories("Notes, \"Notes\"") == ["Notes"]),
|
||||
("empties dropped", parseCategories(" \"\" , ") == []),
|
||||
("line", frontmatterLine(["Tech", "Notes"]) == "category: [Tech, Notes]"),
|
||||
("quoted line", frontmatterLine(["Tech, general", "a\"b"]) == "category: [\"Tech, general\", \"a\\\"b\"]"),
|
||||
("empty state", stateLine([]) == "No categories → category: []"),
|
||||
("state", stateLine(parseCategories("Tech, Notes")) == "Travels as → category: [Tech, Notes]"),
|
||||
("pick on empty field", completion(text: "", picking: "Tech", blog: blog) == "Tech"),
|
||||
("pick adds: Tech + Notes", completion(text: "Tech", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||
("pick adds again: any number of clicks", completion(text: "Tech, Notes", picking: "Essays", blog: blog) == "Tech, Notes, Essays"),
|
||||
("pick replaces the half-typed word", completion(text: "Te", picking: "Tech", blog: blog) == "Tech"),
|
||||
("pick after a comma", completion(text: "Tech, No", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||
("pick keeps both Tech and Tech, general", completion(text: "Tech", picking: "Tech, general", blog: blog) == "Tech, \"Tech, general\""),
|
||||
("pick exact over prefix: Sw + SwiftUI", completion(text: "Sw", picking: "SwiftUI", blog: swiftBlog) == "SwiftUI"),
|
||||
("pick present name: unchanged", completion(text: "Tech, Notes", picking: "Notes", blog: blog) == "Tech, Notes"),
|
||||
("pick present name drops the half-typed word", completion(text: "Notes, No", picking: "Notes", blog: blog) == "Notes"),
|
||||
("pick keeps a new name", completion(text: "MyNewCat", picking: "Notes", blog: blog) == "MyNewCat, Notes"),
|
||||
("suggestions: empty → all", suggestions(text: "", blog: blog) == blog),
|
||||
("suggestions: prefix, case-insensitive", suggestions(text: "te", blog: blog) == ["Tech", "Tech, general"]),
|
||||
("suggestions: finished → every other category", suggestions(text: "Tech", blog: blog) == others),
|
||||
("suggestions: after a comma only the prefix", suggestions(text: "Tech, Te", blog: blog) == ["Tech, general"]),
|
||||
("suggestions: a present name is never offered", !suggestions(text: "Notes", blog: blog).contains("Notes")),
|
||||
("suggestions: after a quoted pick, every other category", suggestions(text: quotedPick, blog: blog) == Array(others.prefix(3))),
|
||||
]
|
||||
for check in checks where !check.1 {
|
||||
print("FAIL: \(check.0)")
|
||||
}
|
||||
let failed = checks.filter { !$0.1 }.count
|
||||
print(failed == 0 ? "contract OK (\(checks.count) checks)" : "contract FAILED (\(failed))")
|
||||
exit(failed == 0 ? 0 : 1)
|
||||
}
|
||||
|
||||
// MARK: - Mock sheet (mirrors MicropubPublishSheet's idle state; only `control` differs)
|
||||
|
||||
enum Variant: String, CaseIterable {
|
||||
case a, b, c
|
||||
|
||||
var id: String {
|
||||
rawValue.uppercased()
|
||||
}
|
||||
|
||||
var title: String {
|
||||
switch self {
|
||||
case .a: "A — comma field + visible row"
|
||||
case .b: "B — comma field + completion menu"
|
||||
case .c: "C — token field"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SheetMock: View {
|
||||
let variant: Variant
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var text = "" // A, B
|
||||
@State private var tokens: [String] = [] // C
|
||||
|
||||
/// The writer's existing blog categories — every variant's suggestion source.
|
||||
static let blogCategories: [String] = isMany ? manyCategories : ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general"]
|
||||
private static let isMany = ProcessInfo.processInfo.environment["PROTO_MANY"] != nil
|
||||
|
||||
/// PROTO_MANY=1: ~40 names at a real blog's scale — shared prefixes (Swift…), two with commas.
|
||||
private static let manyCategories = [
|
||||
"Tech", "Notes", "Essays", "Fieldwork", "Tech, general",
|
||||
"Swift", "SwiftUI", "Swift Testing", "Swift Format", "Swift Concurrency",
|
||||
"Xcode", "AppKit", "Metal", "macOS", "iOS", "Toolchain", "Builds",
|
||||
"Design", "Typography", "Accessibility", "Hugo", "Static Sites", "Web",
|
||||
"Indie Business", "Pricing", "Marketing", "App Store", "Support, email", "Privacy",
|
||||
"Photography", "Film", "Books", "Reading Notes", "Travel", "Field Notes, abroad",
|
||||
"Coffee", "Cooking", "Music", "Synths", "Keyboards",
|
||||
]
|
||||
|
||||
/// Suggestions for a partial word (case-insensitive prefix); empty → all five.
|
||||
static func matches(_ partial: String) -> [String] {
|
||||
blogCategories.filter { $0.lowercased().hasPrefix(partial.lowercased()) }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Publish to Micro.blog?")
|
||||
.font(.headline)
|
||||
Text("The expected value of showing")
|
||||
.font(.callout.weight(.semibold))
|
||||
.lineLimit(2)
|
||||
Text("Museion sends it as a draft first — nothing goes out until you publish.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(Tok.muted)
|
||||
|
||||
control
|
||||
|
||||
Text(stateLine(variant == .c ? tokens : parseCategories(text)))
|
||||
.font(Tok.monoNote)
|
||||
.foregroundStyle(Tok.muted)
|
||||
Text("Sends with the app token in your Keychain — Settings → Micro.blog manages it.")
|
||||
.font(Tok.monoNote)
|
||||
.foregroundStyle(Tok.muted)
|
||||
|
||||
HStack {
|
||||
Button("Publish") {}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(true)
|
||||
Button("Send as Draft") {}
|
||||
.buttonStyle(.bordered)
|
||||
Button("Cancel") {}
|
||||
.buttonStyle(.bordered)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .trailing)
|
||||
}
|
||||
.padding(16)
|
||||
.frame(width: 340, alignment: .leading)
|
||||
.frame(width: 340, height: 360, alignment: .topLeading)
|
||||
.background(Tok.background)
|
||||
.task {
|
||||
if variant == .a {
|
||||
// B last: it ends up the key window, so its field is first responder at launch.
|
||||
openWindow(id: Variant.c.id)
|
||||
openWindow(id: Variant.b.id)
|
||||
}
|
||||
if ProcessInfo.processInfo.environment["PROTO_SEED"] != nil {
|
||||
text = Self.blogCategories.map(fieldForm).joined(separator: ", ")
|
||||
tokens = Self.blogCategories
|
||||
}
|
||||
if variant == .b, let typed = ProcessInfo.processInfo.environment["PROTO_B_TEXT"] {
|
||||
text = typed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var control: some View {
|
||||
switch variant {
|
||||
case .a: CommaField(text: $text, mode: .visibleRow)
|
||||
case .b: CommaField(text: $text, mode: .completionMenu)
|
||||
case .c:
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
FieldLabel()
|
||||
TokenField(tokens: $tokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sheet's label face (mono 11 muted) above the field.
|
||||
struct FieldLabel: View {
|
||||
var body: some View {
|
||||
Text("Categories")
|
||||
.font(Tok.monoNote)
|
||||
.foregroundStyle(Tok.muted)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - A + B: comma-separated TextField (A: visible link row · B: native completion menu)
|
||||
|
||||
struct CommaField: View {
|
||||
enum Mode { case visibleRow, completionMenu }
|
||||
@Binding var text: String
|
||||
let mode: Mode
|
||||
/// Screenshot scenario only (PROTO_B_TEXT=Te): focuses the pre-typed field so the native menu shows.
|
||||
@FocusState private var focused: Bool
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
FieldLabel()
|
||||
switch mode {
|
||||
case .visibleRow:
|
||||
field
|
||||
blogRow
|
||||
case .completionMenu:
|
||||
field
|
||||
// The system filters nothing — it lists every view given here (verified: `Te` typed, all
|
||||
// five provided → five rows). `suggestions` narrows, `completion` is the merged whole text.
|
||||
.textInputSuggestions {
|
||||
ForEach(suggestions(text: text, blog: blog), id: \.self) { name in
|
||||
Text(name).textInputCompletion(completion(text: text, picking: name, blog: blog))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.task {
|
||||
if mode == .completionMenu, ProcessInfo.processInfo.environment["PROTO_B_TEXT"] != nil {
|
||||
focused = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var field: some View {
|
||||
TextField("Tech, Notes", text: $text)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.font(Tok.monoField)
|
||||
.focused($focused)
|
||||
}
|
||||
|
||||
private var blog: [String] {
|
||||
SheetMock.blogCategories
|
||||
}
|
||||
|
||||
/// A: the blog's categories, always visible; a click appends (never duplicates) the name.
|
||||
private var blogRow: some View {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("On your blog:")
|
||||
.font(Tok.monoNote)
|
||||
.foregroundStyle(Tok.muted)
|
||||
HStack(spacing: 10) {
|
||||
ForEach(SheetMock.blogCategories, id: \.self) { name in
|
||||
Button(name) { append(name) }
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(Tok.accent)
|
||||
.pointerStyle(.link)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func append(_ name: String) {
|
||||
var names = parseCategories(text)
|
||||
guard !names.contains(name) else { return }
|
||||
names.append(name)
|
||||
text = names.map(fieldForm).joined(separator: ", ")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - C: NSTokenField (Mail-style tokens + the delegate completion menu)
|
||||
|
||||
struct TokenField: NSViewRepresentable {
|
||||
typealias NSViewType = NSTokenField
|
||||
@Binding var tokens: [String]
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator(self)
|
||||
}
|
||||
|
||||
/// Mock limitation: inside the representable the field stays one line tall, so wrapped tokens
|
||||
/// clip at the bottom (Mail grows its field) — `sizeThatFits`/`maximumNumberOfLines` did not
|
||||
/// change that; not pursued, the owner ruled for B.
|
||||
func makeNSView(context: Context) -> NSTokenField {
|
||||
let field = NSTokenField()
|
||||
field.placeholderString = "Tech, Notes"
|
||||
field.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
|
||||
field.tokenStyle = .rounded
|
||||
field.delegate = context.coordinator
|
||||
return field
|
||||
}
|
||||
|
||||
func updateNSView(_ field: NSTokenField, context _: Context) {
|
||||
guard (field.objectValue as? [String] ?? []) != tokens else { return }
|
||||
field.objectValue = tokens
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, NSTokenFieldDelegate {
|
||||
let parent: TokenField
|
||||
|
||||
init(_ parent: TokenField) {
|
||||
self.parent = parent
|
||||
}
|
||||
|
||||
func controlTextDidChange(_ obj: Notification) {
|
||||
guard let field = obj.object as? NSTokenField else { return }
|
||||
parent.tokens = field.objectValue as? [String] ?? []
|
||||
}
|
||||
|
||||
func tokenField(
|
||||
_: NSTokenField, completionsForSubstring substring: String, indexOfToken _: Int,
|
||||
indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>?,
|
||||
) -> [Any]? {
|
||||
selectedIndex?.pointee = 0
|
||||
return SheetMock.matches(substring)
|
||||
}
|
||||
|
||||
/// The contract's de-duplication at the control: a token already present is not added twice.
|
||||
func tokenField(_: NSTokenField, shouldAdd tokens: [Any], at _: Int) -> [Any] {
|
||||
tokens.compactMap { $0 as? String }.filter { !parent.tokens.contains($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - App: three windows, tiled apart; A opens its siblings
|
||||
|
||||
@main
|
||||
struct CategoriesPrototypeApp: App {
|
||||
init() {
|
||||
if CommandLine.arguments.contains("--selftest") {
|
||||
contractSelfCheck()
|
||||
}
|
||||
// No saved window state: a relaunch would restore B and C, and A's `.task` opens them again.
|
||||
UserDefaults.standard.register(defaults: ["NSQuitAlwaysKeepsWindows": false])
|
||||
}
|
||||
|
||||
var body: some Scene {
|
||||
window(.a, x: 0.18)
|
||||
window(.b, x: 0.5)
|
||||
window(.c, x: 0.82)
|
||||
}
|
||||
|
||||
/// `Window` (not `WindowGroup`): `openWindow` on an already-open window activates it instead of stacking a twin.
|
||||
private func window(_ variant: Variant, x: CGFloat) -> some Scene {
|
||||
Window(variant.title, id: variant.id) { SheetMock(variant: variant) }
|
||||
.defaultPosition(UnitPoint(x: x, y: 0.5))
|
||||
.windowResizability(.contentSize)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user