// // LearningsPaneView.swift // Museion // // #26 (S4.4, ADR-0005): the Learnings pane — the writer's per-writer // portable critique memory as plain files. List-only (Archive pane // precedent): read side; promotion (the fix-card rail) writes the files. // import SwiftUI /// The pane's disk reader. One markdown file per Learning under /// `/learnings//` (literal plurals: "posts", /// "outlines"), named `YYYYMMDD-.md` — hand-editable, /// git-diffable, surviving restarts. Every read is lenient: a /// stranger's hand-edit never crashes the pane. nonisolated enum LearningsIndex { /// One Learning on disk. `pattern` falls back to the filename /// (extension and leading date + hyphen stripped); `problem`/ /// `promoted` omit when the frontmatter key is absent. nonisolated struct Entry: Identifiable { /// The file name (with extension) — unique within its group. let id: String let pattern: String var problem: String? var promoted: String? init(file: String, text: String) { let frontmatter = Post.frontmatter(of: text) id = file pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file) problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 } promoted = frontmatter["promoted"].flatMap { $0.isEmpty ? nil : $0 } } /// "20261021-fold-the-ladder.md" → "fold-the-ladder". static func pattern(fromFilename file: String) -> String { let stem = (file as NSString).deletingPathExtension guard Self.isDated(file) else { return stem } return String(stem.dropFirst(9)) } /// The filename contract: a `YYYYMMDD-` prefix (8 digits + hyphen). static func isDated(_ file: String) -> Bool { let stem = (file as NSString).deletingPathExtension let digits = stem.prefix(8) return digits.count == 8 && digits.allSatisfy(\.isNumber) && stem.dropFirst(8).first == "-" } } /// One content-type section, keyed by the directory name. nonisolated struct Group { let type: String var entries: [Entry] } /// Scans `/learnings/*/` — groups keyed by directory name /// (type-sorted), entries newest-first (the YYYYMMDD prefix sorts /// lexicographically desc; undated files last). Missing learnings/ → /// empty; hidden dirs/files, non-.md, loose files, and unreadable /// files never surface. Same skip posture as `Post.scan`. static func scan(home: URL) -> [Group] { let root = home.appendingPathComponent("learnings", isDirectory: true) guard let typeDirs = try? FileManager.default.contentsOfDirectory( at: root, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], ) else { return [] } var groups: [Group] = [] for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix(".") else { continue } guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { continue } let entries = files .filter { !$0.lastPathComponent.hasPrefix(".") && $0.pathExtension.caseInsensitiveCompare("md") == .orderedSame } .compactMap { file in // ponytail: unbounded read, file symlinks followed — same // ceiling as Post.scan/FixCardStore.learnings (systemic, // local-Home threat only); isSymbolicLink + size cap if a // hostile Home ever matters. (try? String(contentsOf: file, encoding: .utf8)) .map { Entry(file: file.lastPathComponent, text: $0) } } guard !entries.isEmpty else { continue } groups.append(Group( type: dir.lastPathComponent, // Dated files first (newest first — lexicographic desc on // the name), undated hand-edits last. entries: entries.sorted { lhs, rhs in let (lhsDated, rhsDated) = (Entry.isDated(lhs.id), Entry.isDated(rhs.id)) return lhsDated == rhsDated ? lhs.id > rhs.id : lhsDated }, )) } return groups } private static func isPlainDirectory(_ url: URL) -> Bool { let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false) } } /// #26: the Learnings pane — list-only, like the Archive pane. struct LearningsPaneView: View { let home: URL @State private var groups: [LearningsIndex.Group] = [] var body: some View { VStack(spacing: 0) { // No New button — learnings arrive by promotion, not creation. PaneHeader(title: "Learnings") if groups.isEmpty { emptyState } else { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { ForEach(groups, id: \.type) { group in LearningSection(group: group) } } .padding(.bottom, 12) } } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(DesignTokens.background) // Disk I/O stays off MainActor (rescan posture, PostsModel) — the // .task body is MainActor, so the scan hops to a detached task and // the assignment lands back on the main actor. // ponytail: no FSEvents watcher — the pane re-scans on .task(id: home) // each time it appears; a promote landing while the pane stays open // goes stale until the pane is re-entered. Add a watcher if that // ever annoys. .task(id: home) { let scanned = await Task.detached(priority: .userInitiated) { LearningsIndex.scan(home: home) }.value // A home repoint cancels the awaiting task, but a detached // scan is not cancellation-aware — a slow OLD scan must not // overwrite the new Home's groups after it resumes. guard !Task.isCancelled else { return } groups = scanned } } private var emptyState: some View { VStack(spacing: 8) { Text("No learnings yet.") .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) Text("Promoting a fix card writes one plain markdown Learning here.") .font(.callout) .foregroundStyle(DesignTokens.muted) .multilineTextAlignment(.center) } .padding(38) .frame(maxWidth: .infinity, maxHeight: .infinity) } } /// One content-type section: the head + its rows. A child view so the /// lazy stack sees one view per group (its inner ForEach is the view's /// own body, not uneven outer-row content). private struct LearningSection: View { let group: LearningsIndex.Group var body: some View { SectionHeadView(type: group.type, count: group.entries.count) .padding(.top, 16) .padding(.horizontal, 14) .padding(.bottom, 6) ForEach(group.entries) { entry in LearningRow(entry: entry) } } } /// The library's section-head voice: serif-15 semibold name /// (display-lowercased) + mono-11 `· N` count. private struct SectionHeadView: View { let type: String let count: Int var body: some View { HStack(alignment: .firstTextBaseline, spacing: 8) { Text(type) .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) .textCase(.lowercase) // display-only — the dir name keeps its case .lineLimit(1) .truncationMode(.tail) Text("· \(count)") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) Spacer(minLength: 0) } } } /// One Learning row: pattern as the title, problem as the secondary /// line, promoted date + file name in mono-11. private struct LearningRow: View { let entry: LearningsIndex.Entry var body: some View { VStack(alignment: .leading, spacing: 5) { Text(entry.pattern) .font(.callout.weight(.semibold)) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) if let problem = entry.problem { Text(problem) .font(.callout) .foregroundStyle(DesignTokens.muted) .lineLimit(2) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) } Text(metaLine) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) } .padding(10) } private var metaLine: String { entry.promoted.map { "promoted · \($0) · \(entry.id)" } ?? entry.id } }