// // PostsPaneView.swift // Museion // // #17 (S1.1): the Posts pane — library column mirroring the Home's // projects/ (and archive/) on disk. #18: lifecycle — New Post draft, ⌘S first-write/save, rename, // trash. #19: the TextKit2 editor core (PostEditorView) replaces the stub; // mentor column (#14). // #108 (variant B, ref/prototypes/wf104-library-ui-prototype.html): sections // per project (serif-15 head + mono count), Pass-State groups inside, and a // 2px accent edge bar on the selected row. // import SwiftUI /// The Posts destination: the workspace's full four-column layout /// library 232 | editor ≥420 | mentor 356 (design contract grid). struct PostsPaneView: View { let home: URL /// #14: the app-scoped mentor model + the gate's winning binary (no re-probe). var mentor: MentorSessionModel var mentorBinaryPath: String? /// #18: app-scoped Posts state (watcher + lifecycle ops). var model: PostsModel /// Width budget after the rail — drives column collapse (export media queries: /// library hides ≤1100, mentor hides ≤920). var availableWidth: CGFloat /// #137 (S4): the mentor pane's missing-key Settings link (default nil /// keeps previews compiling). var onOpenSettings: (() -> Void)? @Environment(AppGateState.self) private var gate /// #33 (S6.1): the Micro.blog publish ask over the open piece. @State private var showingPublish = false private var showsLibrary: Bool { availableWidth >= 1100 - DesignTokens.railWidth } private var showsMentor: Bool { availableWidth >= 920 - DesignTokens.railWidth } var body: some View { Group { if gate.isFocused { // #21: columns recede; the editor surface + centered measure on // the workspace background is all that remains. The mentor // returns by right-edge hover (overlay below) — only while the // width budget grants it (#17's collapse verdict stands here too). ZStack(alignment: .trailing) { editorColumn if showsMentor { FocusOverlayPanel(edge: .trailing, panelWidth: DesignTokens.mentorWidth) { mentorColumn } } } } else { HStack(spacing: 0) { if showsLibrary { PostsLibraryColumn(home: home, model: model) paneBorder } editorColumn if showsMentor { paneBorder mentorColumn } } } } .task(id: home) { // Bind: initial off-main scan + (re)start the FSEvents watcher (#61). model.bind(home: home) } // #33 (S6.1): the publish ask rides the pane (not the library // column) — it targets the open piece. .sheet(isPresented: $showingPublish) { MicropubPublishSheet(posts: model, home: home) } } private var paneBorder: some View { Rectangle() .fill(DesignTokens.border) .frame(width: 1) } // MARK: Editor column (#19: TextKit2 editor core) private var editorColumn: some View { VStack(spacing: 0) { if let draft = model.draft { PostEditorView( session: nil, draftText: draft.text, draftEdited: { model.updateDraft($0) }, draftSave: { model.saveDraft(home: home) }, outline: draft.type == .outline, ) // #109: identity = "draft" + mountID — remounts per staged // draft (the outliner seeds once per mount). .id("draft-\(draft.mountID.uuidString)") } else if let external = model.externalSession { // #92: the guest slot — an external file in the editor column; // one at a time, transient per launch. PostEditorView(session: external, draftText: nil) .id(external.fileURL?.absoluteString ?? "external") } else if let session = model.session, session.postID == model.selectedPostID { // #109: outline routing — the scan's type when the list knows the // piece, plus the just-saved-draft afterglow (the posts list lags // one rescan; without the flag the fresh outline flashes prose). // #111 (S7): the guard's Prose answer overrides to prose (same // lag window); the guard hold never reaches here (no session). PostEditorView( session: session, draftText: nil, outline: session.postID != model.proseOverridePostID && (model.lastDraftWasOutline || model.posts.first(where: { $0.id == session.postID })?.type == .outline), publish: { showingPublish = true }, ) .id(session.postID ?? "post") } else if model.outlineGuardPieceID != nil { // #111 (S7): the guard ask is up — empty editor, nothing // editable until the choice lands. VStack(spacing: 10) { Image(systemName: "list.bullet") .font(.largeTitle) .foregroundStyle(DesignTokens.muted) Text("This outline has lines the outliner can't show.") .font(.callout) .foregroundStyle(DesignTokens.muted) } .frame(maxWidth: .infinity, maxHeight: .infinity) } else { VStack(spacing: 10) { Image(systemName: "square.and.pencil") .font(.largeTitle) .foregroundStyle(DesignTokens.muted) Text("Select a post, or start a new one.") .font(.callout) .foregroundStyle(DesignTokens.muted) } .frame(maxWidth: .infinity, maxHeight: .infinity) } if let error = model.lastError { Text(error) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.accent) .padding(.vertical, 6) } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(DesignTokens.surface) } private var mentorColumn: some View { MentorPaneView( model: mentor, binaryPath: mentorBinaryPath, posts: model, home: home, onOpenSettings: onOpenSettings, ) .frame(width: DesignTokens.mentorWidth) } } /// #21: the library column, shared by the unfocused layout and the focus-mode /// left reveal overlay — one implementation, both surfaces. Owns the rename + /// move sheets and the context menu (they travel with the post rows). /// #108 variant B: sections per project, Pass-State groups inside. struct PostsLibraryColumn: View { let home: URL var model: PostsModel @State private var renamingPost: Post? @State private var movingPost: Post? /// #108: collapsed project sections — per-view state, not persisted (a /// fresh open shows everything; the prototype behaved the same). @State private var collapsed: Set = [] /// #144: the library search — live title+body filter over the /// non-archived pieces. nil = not searching (sections render). @State private var query = "" @State private var matches: [Post]? private var trimmedQuery: String { query.trimmingCharacters(in: .whitespacesAndNewlines) } private var isSearching: Bool { !trimmedQuery.isEmpty } /// Non-archived pieces keyed by project (scan order = title order holds /// inside each group — filter preserves it). private var activeByProject: [String: [Post]] { Dictionary(grouping: model.posts.filter { !$0.isArchived }, by: \.project) } var body: some View { VStack(spacing: 0) { PaneHeader(title: "Posts") { Button { model.newPost() } label: { Image(systemName: "plus") } .buttonStyle(.plain) .foregroundStyle(DesignTokens.muted) .help("New Post") .accessibilityLabel("New Post") } searchField if isSearching { if let matches { if matches.isEmpty { searchEmptyState } else { searchResults(matches) } } else { ProgressView() .frame(maxWidth: .infinity, maxHeight: .infinity) } } else if activeByProject.isEmpty { emptyState } else { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { // #108 audit: Finder order (scan's own sort), not Unicode-scalar // order — the heads render lowercased, "Beta" must not read before "apple". ForEach(activeByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in let pieces = activeByProject[project] ?? [] // #108: the head is the prototype's toggle — click // collapses the project's pieces (chevron rotates). Button { withAnimation { if collapsed.contains(project) { collapsed.remove(project) } else { collapsed.insert(project) } } } label: { HStack(alignment: .firstTextBaseline, spacing: 8) { Image(systemName: "chevron.down") .font(.system(size: 9, weight: .semibold)) .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) .foregroundStyle(DesignTokens.muted) Text(project) .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) .textCase(.lowercase) // #108: display-only — the folder name keeps its case .lineLimit(1) .truncationMode(.tail) Text("· \(pieces.count)") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) Spacer(minLength: 0) } } .buttonStyle(.plain) .foregroundStyle(DesignTokens.foreground) .accessibilityLabel("\(project), \(pieces.count) pieces") .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") .padding(.top, 16) .padding(.horizontal, 14) .padding(.bottom, 6) if !collapsed.contains(project) { passStateGroups(pieces) } } } .padding(.bottom, 12) } } } .frame(width: DesignTokens.libraryWidth) .sheet(item: $renamingPost) { post in RenamePostSheet(post: post) { title in model.rename(post, to: title, home: home) } } .sheet(item: $movingPost) { post in // #108 audit 2: disk-derived list, localized-sorted — same order // the library renders (Unicode-scalar sort split them), and it // includes empty projects (a fresh New Project has no pieces yet — // it must already be a move target). MoveToProjectSheet(post: post, projects: model.moveTargets(home: home)) { project in model.moveToProject(post, project: project, home: home) } } // #144: keystroke-debounced (250 ms), structured body scan — // nonisolated search() runs the disk reads off MainActor while // staying inside this task, so a superseding keystroke or clear // cancels the sweep between pieces (the in-flight file read // always finishes — readBody is synchronous). .task(id: trimmedQuery) { guard !trimmedQuery.isEmpty else { matches = nil return } try? await Task.sleep(for: .milliseconds(250)) guard !Task.isCancelled else { return } let found = await Self.search( candidates: model.posts.filter { !$0.isArchived }, matching: trimmedQuery, home: home, ) guard !Task.isCancelled else { return } matches = found } } /// #144: the title+body scan — title matches first (stable partition, /// both halves keep the scan's Finder order), body via readBody /// (frontmatter never searched); the per-piece cancellation check stops /// a superseded sweep between files. /// /// ponytail: full-body re-read per sweep (folder(of:) re-walked per /// piece — same unbounded-read ceiling as Post.scan, LearningsIndex /// posture); a PostScanCache-style body memo if it ever measures hot. private nonisolated static func search( candidates: [Post], matching trimmed: String, home: URL, ) async -> [Post] { var byTitle: [Post] = [] var byBody: [Post] = [] for post in candidates { if Task.isCancelled { break } if post.title.localizedCaseInsensitiveContains(trimmed) { byTitle.append(post) continue } let body = PostStore.readBody(id: post.id, home: home) ?? "" if body.localizedCaseInsensitiveContains(trimmed) { byBody.append(post) } } return byTitle + byBody } /// One piece row + its context menu — sections and search results /// render the same row (#144: results carry the full menu too). private func postRow(_ post: Post) -> some View { LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { model.select(post.id, home: home) } .contextMenu { Button("Rename…") { renamingPost = post } // #114 (S4): outline pieces only — the ask picks the // body transform, then the piece becomes a prose post. if post.type == .outline { Button("Convert to Post…") { model.stageConversion(post, home: home) } } Button("Move to Project…") { movingPost = post } Button("Move to Archive") { model.archivePost(post, home: home) } Button("Move to Trash", role: .destructive) { model.trash(post, home: home) } } } /// Pass-State groups inside one project (`.vB .group-label`: smaller, /// softer, indented under the section head). private func passStateGroups(_ pieces: [Post]) -> some View { ForEach(Post.PassState.allCases, id: \.self) { state in let grouped = pieces.filter { $0.passState == state } if !grouped.isEmpty { Text(state.rawValue.uppercased()) .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.6) .foregroundStyle(DesignTokens.muted.opacity(0.8)) .padding(.horizontal, 22) .padding(.top, 8) .padding(.bottom, 5) ForEach(grouped) { post in postRow(post) } } } } /// #144: the field row + bottom hairline (the pane-head voice). private var searchField: some View { HStack(spacing: 6) { Image(systemName: "magnifyingglass") .font(.system(size: 11)) .foregroundStyle(DesignTokens.muted) TextField("Search posts", text: $query) .textFieldStyle(.plain) .font(.system(size: 12)) if isSearching { Button { query = "" } label: { Image(systemName: "xmark.circle.fill") } .buttonStyle(.plain) .foregroundStyle(DesignTokens.muted) .accessibilityLabel("Clear search") } } .padding(.horizontal, 12) .padding(.vertical, 7) .overlay(alignment: .bottom) { Rectangle().fill(DesignTokens.border).frame(height: 1) } } /// Flat results, title matches first (stable partition — both halves /// keep the scan's Finder order). Same row the sections render. private func searchResults(_ found: [Post]) -> some View { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { Text("\(found.count) \(found.count == 1 ? "match" : "matches")") .font(.system(size: 10, design: DesignTokens.mono)) .kerning(0.6) .foregroundStyle(DesignTokens.muted.opacity(0.8)) .padding(.horizontal, 14) .padding(.top, 12) .padding(.bottom, 5) ForEach(found) { post in postRow(post) } } .padding(.bottom, 12) } } private var searchEmptyState: some View { VStack(spacing: 8) { Text("No matches") .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) Text("No piece's title or body contains “\(trimmedQuery)”.") .font(.callout) .foregroundStyle(DesignTokens.muted) .multilineTextAlignment(.center) } .padding(38) .frame(maxWidth: .infinity, maxHeight: .infinity) } private var emptyState: some View { VStack(spacing: 8) { Text("No posts yet") .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) Text("Posts in this Home's projects/ folders appear here.") .font(.callout) .foregroundStyle(DesignTokens.muted) .multilineTextAlignment(.center) } .padding(38) .frame(maxWidth: .infinity, maxHeight: .infinity) } } /// #108: Move to Project ask — radio list of the non-archived projects, /// default = the piece's current project. Matches RenamePostSheet's shape. struct MoveToProjectSheet: View { let post: Post let projects: [String] let move: (String) -> Void @Environment(\.dismiss) private var dismiss @State private var target: String init(post: Post, projects: [String], move: @escaping (String) -> Void) { self.post = post self.projects = projects self.move = move _target = State(initialValue: post.project) } var body: some View { VStack(alignment: .leading, spacing: 12) { Text("Move to Project") .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) Text("“\(post.title)” moves into the chosen project. The file stays post.md.") .font(.callout) .foregroundStyle(DesignTokens.muted) Picker("Project", selection: $target) { ForEach(projects, id: \.self) { name in Text(name).tag(name) } } .pickerStyle(.radioGroup) HStack { Spacer() Button("Cancel", role: .cancel) { dismiss() } .keyboardShortcut(.cancelAction) Button("Move") { move(target) dismiss() } .keyboardShortcut(.defaultAction) .disabled(target == post.project) } } .padding(20) .frame(width: 360) } } /// #60: Explicit Rename dialog — asks the new Title (not a slug). struct RenamePostSheet: View { let rename: (String) -> Void @Environment(\.dismiss) private var dismiss @State private var title: String init(post: Post, rename: @escaping (String) -> Void) { self.rename = rename _title = State(initialValue: post.title) } var body: some View { VStack(alignment: .leading, spacing: 12) { Text("Rename Post") .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) Text("The folder moves to match the new Title. The file stays post.md.") .font(.callout) .foregroundStyle(DesignTokens.muted) TextField("Title", text: $title) .textFieldStyle(.roundedBorder) .onSubmit { confirm() } HStack { Spacer() Button("Cancel", role: .cancel) { dismiss() } .keyboardShortcut(.cancelAction) Button("Rename", action: confirm) .keyboardShortcut(.defaultAction) .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } .padding(20) .frame(width: 360) } private func confirm() { let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return } rename(trimmed) dismiss() } } /// One post row per the export: title, Pass State + Origin in mono 11. /// #108 (variant B): 2px accent edge bar on the leading side when selected /// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, /// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the /// Archive pane reuses it. struct LibraryPostRow: View { let post: Post let selected: Bool let select: () -> Void @State private var hover = false var body: some View { // `.vB .post-row { border-left: 2px solid transparent; // border-radius: 0 8px 8px 0 }` — every row: leading corners square // (the 2px strip below), trailing rounded 8. Only the strip's COLOR // changes on selection. let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) return Button(action: select) { HStack(spacing: 0) { // `.vB .post-row { border-left: 2px solid transparent }` — // the leading strip is always 2px wide so hover/selection // never shifts the title. Rectangle() .fill(selected ? DesignTokens.accent : .clear) .frame(width: 2) VStack(alignment: .leading, spacing: 5) { HStack(alignment: .firstTextBaseline, spacing: 0) { Text(post.title) if post.type == .outline { Text(" ✳") .foregroundStyle(DesignTokens.muted) } } .font(.callout.weight(.semibold)) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) HStack { Text(post.passState.rawValue) Text(post.origin.rawValue) } .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .frame(maxWidth: .infinity, alignment: .leading) } .padding(10) } .clipShape(shape) } .buttonStyle(.plain) .foregroundStyle(DesignTokens.foreground) .background { if selected || hover { shape .fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) .overlay( shape.strokeBorder(selected ? DesignTokens.border : .clear), ) } } .padding(.horizontal, 8) .onHover { hover = $0 } // help sits on the row — the ✳ span isn't individually hoverable in // SwiftUI (prototype: `title="outline"` on the star). .help(post.type == .outline ? "\(post.title) — outline" : post.title) .accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)") } }