integrate main: #193 PostsModel split (Watcher/Writes/Imports) into failed-flush departure guard
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
# Conflicts: # Museion/PostsModel.swift # docs/devlog/INDEX.md
This commit is contained in:
commit
ffb9457a63
47 files changed
+3272
-1811
No files matched your search
+11
-3
@@ -23,8 +23,13 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in `docs/devlog/`.
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
|
||||
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
|
||||
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
|
||||
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller).
|
||||
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`.
|
||||
- `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108).
|
||||
- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them.
|
||||
- `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
|
||||
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
|
||||
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it.
|
||||
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
|
||||
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
|
||||
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `` builder.
|
||||
@@ -36,7 +41,10 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
||||
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
|
||||
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
|
||||
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: `illustrations(in:)` parses only `` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
|
||||
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`; watcher+rescan in a file-scope extension). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome`, private(set) — set only by `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). FSEvents stream (file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; rescan off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into `lastError`. Structural ops are flush-first via `flushOrAbort` (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
|
||||
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`) — the #146/#193 splits). **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text. `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only).
|
||||
- `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail.
|
||||
- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive).
|
||||
- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal`/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`).
|
||||
- `OutlineTree.swift` — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); `parsesWithLoss` shares `parseItem` so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); `enter` = split/outdent/new-sibling; `extract`/`insertRun` are the drag primitives; `headingsLadderBody` = the Convert transform. Folds live in the view, keyed by node UUID.
|
||||
- `OutlineEditorView.swift` — `OutlinePresenter` (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, `applyBatch` sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted `OutlineRowTextView` on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). **Esc needs a local NSEvent keyDown monitor** — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand` (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
|
||||
- `OutlineDrag.swift` — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from `CatcherView.rowFrames` reading CURRENT window-space frames (SwiftUI 27 removed the `.window` coordinate space; cached frames go stale on scroll); the pure drop math (`DropTarget`, `draggedIDs`, `isValidDrop`, `applyDrop`, `hitTestDrop`) rides a nonisolated presenter extension — resolved by id AFTER extraction.
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//
|
||||
// ArchivePaneView.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the #108 Archive pane, moved from WorkspaceView.swift
|
||||
// (file-length ceiling), code unchanged (private → internal:
|
||||
// WorkspaceView instantiates it cross-file now).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// #108: the Archive pane — archive/ as a rail destination (prototype
|
||||
/// verdict: a destination, not a library disclosure). List-only: clicking a
|
||||
/// piece selects it and hops to Posts, where the editor column lives.
|
||||
struct ArchivePaneView: View {
|
||||
var model: PostsModel
|
||||
/// Fired after a row select — the pane can't reach WorkspaceView's
|
||||
/// selection itself.
|
||||
let onOpenPiece: () -> Void
|
||||
@State private var renamingPost: Post?
|
||||
/// #108: collapsed project sections — per-view state, not persisted
|
||||
/// (mirrors the library column).
|
||||
@State private var collapsed: Set<String> = []
|
||||
|
||||
private var archivedByProject: [String: [Post]] {
|
||||
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
|
||||
}
|
||||
|
||||
/// #108: the prototype's toggle — click the project name (or chevron).
|
||||
private func toggle(_ project: String) {
|
||||
if collapsed.contains(project) {
|
||||
collapsed.remove(project)
|
||||
} else {
|
||||
collapsed.insert(project)
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
// No New button — things arrive here by being moved, not created.
|
||||
// r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME
|
||||
// fixed 720pt column the rows live in — one framed block.
|
||||
PaneHeader(title: "Archive", hairlineMaxWidth: 720)
|
||||
if archivedByProject.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
// #108 audit: Finder order, matching the library's sort.
|
||||
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
|
||||
let pieces = archivedByProject[project] ?? []
|
||||
// Same section-head shape as the library (#108
|
||||
// variant B), plus the project-level way out.
|
||||
// r7 (mercury#55, argon#41 — FINAL, supersedes the
|
||||
// r6 D24 ladder): the content column is a FIXED
|
||||
// 720pt frame (width, not maxWidth — the r6
|
||||
// content-hugging bound let the pill define the
|
||||
// right edge), left-anchored. TWO axes only, the
|
||||
// library's r7 ladder: the head row leads at x14
|
||||
// (chevron in a 14pt slot) with its label at x28 —
|
||||
// the ONE indent, shared with the entry rows'
|
||||
// inner text via the shared LibraryPostRow (cards
|
||||
// lead at x14); the 'Unarchive Group' pill rides
|
||||
// the header row's trailing edge INSIDE the frame
|
||||
// (14 → 706), and the row hairlines are bounded by
|
||||
// the same frame. Nothing spans past it.
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.onTapGesture {
|
||||
withAnimation { toggle(project) }
|
||||
}
|
||||
.accessibilityLabel("Toggle \(project)")
|
||||
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
|
||||
Text(project)
|
||||
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
.textCase(.uppercase) // #108: display-only — the folder name keeps its case
|
||||
.foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.onTapGesture {
|
||||
withAnimation { toggle(project) }
|
||||
}
|
||||
Text("· \(pieces.count)")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.padding(.leading, 8)
|
||||
Spacer(minLength: 8)
|
||||
// The 'New Post · Fork · Compact' language — a
|
||||
// bordered mono-11 secondary pill at the
|
||||
// trailing edge INSIDE the fixed 720pt frame.
|
||||
// r7 (mercury#55, argon#41): relabeled
|
||||
// 'Unarchive Group' — it moves the whole
|
||||
// project, not one piece.
|
||||
Button("Unarchive Group") {
|
||||
model.unarchiveProject(project)
|
||||
}
|
||||
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
|
||||
.help("Move the whole project back to projects/")
|
||||
.accessibilityLabel("Unarchive \(project)")
|
||||
}
|
||||
.padding(.top, 12)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.bottom, 2)
|
||||
if !collapsed.contains(project) {
|
||||
ForEach(pieces) { post in
|
||||
// r7: the shared LibraryPostRow ladder —
|
||||
// card leads at x14 (PRIMARY), title text
|
||||
// at x28 (the one indent). The hairline is
|
||||
// BOUNDED to the fixed frame: x14 → 706.
|
||||
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
|
||||
model.select(post.id)
|
||||
onOpenPiece()
|
||||
}
|
||||
.overlay(alignment: .bottom) {
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(height: 1)
|
||||
.padding(.horizontal, 14)
|
||||
}
|
||||
.contextMenu {
|
||||
Button("Move Back to \(post.project)") {
|
||||
model.restorePost(post)
|
||||
}
|
||||
Button("Rename…") { renamingPost = post }
|
||||
// #114 (S4): works archived too — the piece
|
||||
// stays where it is, only type + body flip.
|
||||
if post.type == .outline {
|
||||
Button("Convert to Post…") {
|
||||
model.stageConversion(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// r7 (mercury#55, argon#41): the FIXED 720pt reading
|
||||
// column — width, not maxWidth (the r6 content-hugging
|
||||
// bound let the pill define the right edge); rows,
|
||||
// hairlines, and the pill all live inside it.
|
||||
// ponytail: fixed width clips on panes narrower than
|
||||
// 720 — a width-floored variant if a small-window
|
||||
// Archive ever matters.
|
||||
.frame(width: 720, alignment: .leading)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.background)
|
||||
.sheet(item: $renamingPost) { post in
|
||||
RenamePostSheet(post: post) { title in
|
||||
model.rename(post, to: title)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(spacing: 8) {
|
||||
Text("Nothing archived")
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(38)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
@@ -75,8 +75,10 @@ nonisolated enum LearningsIndex {
|
||||
) else { return [] }
|
||||
var groups: [Group] = []
|
||||
for dir in typeDirs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
|
||||
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."), let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
|
||||
else { continue }
|
||||
guard isPlainDirectory(dir), !dir.lastPathComponent.hasPrefix("."),
|
||||
let files = try? FileManager.default.contentsOfDirectory(
|
||||
at: dir, includingPropertiesForKeys: nil,
|
||||
) else { continue }
|
||||
// #27: the pass clock feeds the decay verdict — clocked dirs
|
||||
// carry their count, foreign dirs nil (no verdict; Entry's audit).
|
||||
let currentPass = LearningDecay.isClocked(dir.lastPathComponent)
|
||||
@@ -109,9 +111,14 @@ nonisolated enum LearningsIndex {
|
||||
return groups
|
||||
}
|
||||
|
||||
/// Parens load-bearing for readability — `&&` out-binds `??` (probed;
|
||||
/// a finish-audit misread the bare form as a dead symlink clause).
|
||||
/// lstat semantics: a symlink-to-dir reports isDirectory=false, so
|
||||
/// both halves refuse it; the link clause is the belt for any future
|
||||
/// resolved-URL caller.
|
||||
private static func isPlainDirectory(_ url: URL) -> Bool {
|
||||
let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
return values?.isDirectory ?? false && !(values?.isSymbolicLink ?? false)
|
||||
return (values?.isDirectory ?? false) && !(values?.isSymbolicLink ?? false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// LibraryPostRow.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the shared post row, moved from PostsPaneView.swift
|
||||
// (file-length ceiling) — the Archive pane reuses it, code
|
||||
// unchanged.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// One post row per the export: title + origin-only mono-11 meta (the Pass
|
||||
/// State rides the uppercase group label above; it stays in the a11y label).
|
||||
/// #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
|
||||
// VISIBILITY changes on selection.
|
||||
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
|
||||
return Button(action: select) {
|
||||
HStack(spacing: 0) {
|
||||
// The leading strip is always 2px wide so hover/selection
|
||||
// never shifts the title. r6 (mercury#49/52, argon#13):
|
||||
// the shared SelectedRowStrip capsule — accent, radius-1
|
||||
// ends, vertically inset 6pt (was 3) so it sits INSIDE
|
||||
// the card, never pasted on its square leading edge.
|
||||
SelectedRowStrip()
|
||||
.opacity(selected ? 1 : 0)
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Text(post.title)
|
||||
if post.type == .outline {
|
||||
Text(" ✳")
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
}
|
||||
// ui-polish r8: serif-13 per the row contract — `.callout`
|
||||
// was the system sans design (the r6/r7 councils pixel-
|
||||
// verified sans glyphs on the Archive rows).
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
// Origin only — the Pass State already rides the uppercase
|
||||
// group label above (it stays in the accessibility label).
|
||||
// r7: the status micro-label sits INSIDE the row's content
|
||||
// padding — same x as the title, never flush with the edge.
|
||||
Text(post.origin.rawValue)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 10)
|
||||
}
|
||||
.clipShape(shape)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.background {
|
||||
if selected || hover {
|
||||
// r8 (mercury#11): the selected row DROPS its gray outline —
|
||||
// fill + accent capsule read as ONE shape; stacking fill +
|
||||
// outline + capsule competed. Hover keeps its borderless
|
||||
// 0.06 wash exactly as before.
|
||||
shape
|
||||
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
|
||||
}
|
||||
}
|
||||
// r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
|
||||
// leads at the PRIMARY inset (x14, the 'Posts' header text's
|
||||
// edge); its INNER content (title + status micro-label, strip
|
||||
// 2 + padding 12) lands at x28 — the ONE indent step, shared
|
||||
// with the head text and the group labels. No other x-axis
|
||||
// exists in the column. Vertical padding stays the content
|
||||
// VStack's constant 10 whether or not the row shows its strip.
|
||||
.padding(.horizontal, 14)
|
||||
.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)")
|
||||
}
|
||||
}
|
||||
@@ -149,13 +149,17 @@ nonisolated enum SessionRoster {
|
||||
let dir = directory ?? defaultDirectory
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
let rosterURL = URL(fileURLWithPath: dir).appendingPathComponent("sessions.json")
|
||||
try JSONEncoder().encode(entries).write(
|
||||
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"),
|
||||
to: rosterURL,
|
||||
options: .atomic,
|
||||
)
|
||||
// Finish-audit: names+ids only, but piece titles are the writer's
|
||||
// business — the default umask would hand them to every local user.
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path)
|
||||
// ponytail: post-hoc chmod leaves a sub-second world-readable window
|
||||
// between write and chmod — createFile(0600)+rename if a hostile
|
||||
// local account ever matters.
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: rosterURL.path)
|
||||
} catch {
|
||||
// ponytail: the roster is a convenience index; a write failure must not crash the gate.
|
||||
}
|
||||
|
||||
@@ -55,10 +55,7 @@ nonisolated enum OutlinePresenter {
|
||||
_ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
|
||||
) -> [Row] {
|
||||
var rows: [Row] = []
|
||||
if let zoomRootID,
|
||||
let rootPath = path(of: zoomRootID, in: nodes),
|
||||
let root = node(at: rootPath, in: nodes)
|
||||
{
|
||||
if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) {
|
||||
walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows)
|
||||
} else {
|
||||
walk(nodes, parent: [], depth: 0, folded: folded, into: &rows)
|
||||
@@ -776,27 +773,14 @@ extension OutlineEditorView {
|
||||
}
|
||||
case let .hop(direction):
|
||||
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||
rows.indices.contains(current + direction)
|
||||
{
|
||||
focusedID = rows[current + direction].id
|
||||
selectionAnchor = nil
|
||||
pendingCaret = nil // caret at end of the target row
|
||||
}
|
||||
hopFocus(direction, clearsAnchor: true)
|
||||
case let .extend(direction):
|
||||
// ⇧↑/⇧↓: extend the block selection one visible row. First
|
||||
// press anchors at the focused row; a bare ↑/↓ or click clears.
|
||||
if let focusedID {
|
||||
extendSelection(to: focusedID) // arm the anchor at the current focus
|
||||
}
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||
rows.indices.contains(current + direction)
|
||||
{
|
||||
focusedID = rows[current + direction].id
|
||||
pendingCaret = nil
|
||||
}
|
||||
hopFocus(direction, clearsAnchor: false)
|
||||
case .deselect:
|
||||
_ = handleEscape() // selection first, then zoom — same order as the monitor
|
||||
case .indent, .outdent, .moveUp, .moveDown, .enter:
|
||||
@@ -804,20 +788,27 @@ extension OutlineEditorView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move focus `direction` visible rows from its current position (nil at
|
||||
/// the list edges — folded subtrees are skipped). `clearsAnchor`
|
||||
/// distinguishes hop (clears the block-selection anchor) from extend.
|
||||
private func hopFocus(_ direction: Int, clearsAnchor: Bool) {
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
guard let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||
rows.indices.contains(current + direction)
|
||||
else { return }
|
||||
focusedID = rows[current + direction].id
|
||||
if clearsAnchor {
|
||||
selectionAnchor = nil
|
||||
}
|
||||
pendingCaret = nil // caret at end of the target row
|
||||
}
|
||||
|
||||
/// Tree-mutating ops (indent/outdent/move/enter). Serialize + route
|
||||
/// focus only when something actually changed (boundary no-ops are
|
||||
/// nil and leave the document alone).
|
||||
private func applyTree(_ op: OutlineRowTextView.StructureOp) {
|
||||
guard let focusedID else { return }
|
||||
// Block selection + batchable op → run-wide apply. Moves treat
|
||||
// the run as a unit (boundary leader no-ops the whole batch).
|
||||
if let anchor = selectionAnchor,
|
||||
let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1,
|
||||
let batchOp = map(op)
|
||||
{
|
||||
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
|
||||
pushToDocument()
|
||||
}
|
||||
if applyBatchIfPossible(op, focus: focusedID) {
|
||||
return
|
||||
}
|
||||
guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return }
|
||||
@@ -833,27 +824,52 @@ extension OutlineEditorView {
|
||||
case .moveDown:
|
||||
didChange = OutlineTree.move(&nodes, path: path, up: false) != nil
|
||||
case let .enter(caretGraphemes):
|
||||
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
|
||||
case .noOp:
|
||||
break
|
||||
case let .outdented(newPath):
|
||||
didChange = newPath != nil // nil = boundary no-op
|
||||
case let .newNode(newPath, caret):
|
||||
didChange = true
|
||||
if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id {
|
||||
newFocus = (id, caret)
|
||||
}
|
||||
}
|
||||
let enter = applyEnter(caretGraphemes: caretGraphemes, path: path)
|
||||
didChange = enter.didChange
|
||||
newFocus = enter.focus
|
||||
case .fold, .unfold, .hop, .extend, .deselect:
|
||||
return // unreachable — apply(_:) routes those to view state
|
||||
}
|
||||
if didChange {
|
||||
if let newFocus {
|
||||
self.focusedID = newFocus.id
|
||||
pendingCaret = newFocus.caret
|
||||
}
|
||||
commitIfChanged(didChange, newFocus)
|
||||
}
|
||||
|
||||
/// Serialize + route focus only when something actually changed.
|
||||
private func commitIfChanged(_ didChange: Bool, _ newFocus: (id: UUID, caret: Int)?) {
|
||||
guard didChange else { return }
|
||||
if let newFocus {
|
||||
focusedID = newFocus.id
|
||||
pendingCaret = newFocus.caret
|
||||
}
|
||||
pushToDocument()
|
||||
}
|
||||
|
||||
/// Block-selection fast path: a batchable op over a multi-row run
|
||||
/// (moves treat the run as a unit — a boundary leader no-ops the whole
|
||||
/// batch). Returns true when the batch ran (caller stops here).
|
||||
private func applyBatchIfPossible(_ op: OutlineRowTextView.StructureOp, focus: UUID) -> Bool {
|
||||
guard let anchor = selectionAnchor,
|
||||
let range = selectedRangeIDs(anchor: anchor, focus: focus), range.count > 1,
|
||||
let batchOp = map(op)
|
||||
else { return false }
|
||||
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
|
||||
pushToDocument()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Split (⏎) at `path`: serialize through OutlineTree.enter; focus
|
||||
/// follows the NEW node when one was created (nil path = boundary
|
||||
/// no-op).
|
||||
private func applyEnter(caretGraphemes: Int, path: [Int]) -> (didChange: Bool, focus: (id: UUID, caret: Int)?) {
|
||||
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
|
||||
case .noOp:
|
||||
return (false, nil)
|
||||
case let .outdented(newPath):
|
||||
return (newPath != nil, nil) // nil = boundary no-op
|
||||
case let .newNode(newPath, caret):
|
||||
let id = OutlinePresenter.node(at: newPath, in: nodes)?.id
|
||||
return (true, id.map { ($0, caret) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected row ids in visible order (anchor↔focus, inclusive).
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
//
|
||||
// PostsLibraryColumn.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the Posts library column, moved from PostsPaneView.swift
|
||||
// (file-length ceiling) — PostsLibraryColumn with its rename/move
|
||||
// sheets, the file-scope librarySearch mount (#144), and
|
||||
// LaunchFocusReset (r8), code unchanged.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// #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<String> = []
|
||||
/// #144: the library search — live title+body filter over the
|
||||
/// non-archived pieces. nil = not searching (sections render).
|
||||
@State private var query = ""
|
||||
/// #144 (mounted half): the landed sweep — results plus the key that
|
||||
/// computed them. nil = not searching or recomputing (the sections /
|
||||
/// spinner states); a snapshot that isn't `isFresh` for the current
|
||||
/// key never renders.
|
||||
@State private var snapshot: LibrarySearch.Snapshot?
|
||||
/// r5 (argon#44, mercury#52, sol#37): focus state for the field's
|
||||
/// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7
|
||||
/// onAppear-unfocus could never work — the launch focus is AppKit
|
||||
/// assigning the window's INITIAL first responder to its first text
|
||||
/// input (this field), at window-become-key, AFTER onAppear. FocusState
|
||||
/// merely mirrors that back as true. LaunchFocusReset (below) resigns
|
||||
/// it at the first become-key; from then on only the user drives this.
|
||||
@FocusState private var searchFocused: Bool
|
||||
|
||||
private var trimmedQuery: String {
|
||||
query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// #144 (mounted half): the sweep's identity — trimmed query, the
|
||||
/// Home, and the library content revision (`PostsModel.contentRevision`,
|
||||
/// bumped by the rescan rail on any list change or re-read body). The
|
||||
/// `.task(id:)` below re-keys on ANY difference, so library writes and
|
||||
/// Home repoints restart the sweep instead of leaving stale rows; the
|
||||
/// landed snapshot renders only while `isFresh` for the current key.
|
||||
private var searchKey: LibrarySearch.SearchKey {
|
||||
LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision)
|
||||
}
|
||||
|
||||
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 {
|
||||
// #144 (mounted half): a landed sweep renders only while
|
||||
// fresh for the CURRENT key — a library write that bumped
|
||||
// the revision (archive, trash, rename, body edit) or a
|
||||
// moved query drops to the recompute state, never stale rows.
|
||||
if let snapshot, snapshot.isFresh(for: searchKey) {
|
||||
if snapshot.results.isEmpty {
|
||||
searchEmptyState
|
||||
} else {
|
||||
searchResults(snapshot.results)
|
||||
}
|
||||
} 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: {
|
||||
// r7 (mercury#18, argon#12 — TWO-AXIS ladder,
|
||||
// the r6 four-step collapse undone): the
|
||||
// head ROW leads at the column's PRIMARY
|
||||
// inset (x14) — chevron glyph in a 14pt slot
|
||||
// — and every nested CONTENT shares the one
|
||||
// indent step (x28): head text, group
|
||||
// labels, and the rows' inner text. No third
|
||||
// or fourth x-axis exists in the column.
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
.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)
|
||||
// r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7
|
||||
// onAppear-unfocus — see LaunchFocusReset below for the mechanism.
|
||||
.background(LaunchFocusReset())
|
||||
.sheet(item: $renamingPost) { post in
|
||||
RenamePostSheet(post: post) { title in
|
||||
model.rename(post, to: title)
|
||||
}
|
||||
}
|
||||
.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()) { project in
|
||||
model.moveToProject(post, project: project)
|
||||
}
|
||||
}
|
||||
// #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). Keyed to the full
|
||||
// search key: a library write (revision bump) or a Home repoint
|
||||
// restarts the sweep too. The snapshot lands under the key
|
||||
// captured at start; a mid-sweep key change cancels here, and
|
||||
// even a raced assignment can't render — body gates on isFresh.
|
||||
.task(id: searchKey) {
|
||||
let key = searchKey
|
||||
guard !key.query.isEmpty else {
|
||||
snapshot = nil
|
||||
return
|
||||
}
|
||||
try? await Task.sleep(for: .milliseconds(250))
|
||||
guard !Task.isCancelled else { return }
|
||||
let found = await librarySearch(
|
||||
candidates: model.posts.filter { !$0.isArchived },
|
||||
matching: key.query,
|
||||
home: home,
|
||||
)
|
||||
guard !Task.isCancelled else { return }
|
||||
snapshot = LibrarySearch.Snapshot(key: key, results: found)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
.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)
|
||||
}
|
||||
}
|
||||
Button("Move to Project…") { movingPost = post }
|
||||
Button("Move to Archive") {
|
||||
model.archivePost(post)
|
||||
}
|
||||
Button("Move to Trash", role: .destructive) {
|
||||
model.trash(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
|
||||
/// softer, indented under the section head). r2: the label binds to
|
||||
/// its FIRST row (bottom 1 + stack 4) — it floated closer to the
|
||||
/// preceding row than to its own children.
|
||||
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 {
|
||||
// mercury#53 (r5): display-only normalization — the stored
|
||||
// rawValues keep their hyphen ("Pass-1 Done"); the rendered
|
||||
// label uses the space form so it matches the Pass 1 / Pass 2
|
||||
// vocabulary everywhere else.
|
||||
Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " "))
|
||||
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
// r6 (sol#6/21 — contrast final): group labels are
|
||||
// informational meta — FULL muted ink, no wash.
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
// r6 ladder: full muted ink. r7 two-axis: x28 — the ONE
|
||||
// indent step, shared with the head text and the row
|
||||
// cards' inner content.
|
||||
.padding(.leading, 28)
|
||||
.padding(.top, 10)
|
||||
.padding(.bottom, 1)
|
||||
ForEach(grouped) { post in
|
||||
postRow(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
|
||||
/// border on the column's chrome, taller than a text row; the placeholder
|
||||
/// r5 (argon#44, mercury#52, sol#37): the insertion caret tints
|
||||
/// terracotta (.tint on the field), and the small magnifier glyph sits at
|
||||
/// the field's leading edge (icon→text spacing rides the HStack's 6pt);
|
||||
/// the placeholder is the native prompt wearing the palette's muted ink
|
||||
/// (the composer's pattern).
|
||||
/// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6,
|
||||
/// present but never the strongest saturation on screen.
|
||||
private var searchField: some View {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "magnifyingglass")
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
|
||||
.textFieldStyle(.plain)
|
||||
.font(.system(size: 12))
|
||||
.focused($searchFocused)
|
||||
.tint(DesignTokens.accent)
|
||||
if isSearching {
|
||||
Button {
|
||||
query = ""
|
||||
} label: {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.accessibilityLabel("Clear search")
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 8)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(DesignTokens.surface)
|
||||
.overlay(
|
||||
// r8 (argon#6, mercury#12): quiet focus — accent at 0.6,
|
||||
// one step down from full strength.
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.strokeBorder(
|
||||
searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border,
|
||||
lineWidth: 1,
|
||||
),
|
||||
),
|
||||
)
|
||||
// r7 (mercury#18, argon#12 — two-axis ladder): the box spans the
|
||||
// FULL padded column width at the PRIMARY inset — leading 14
|
||||
// (aligned with the 'Posts' header text) to trailing 14 — the
|
||||
// same edges the row cards lead at.
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// 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: 11, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
// r6: full muted ink; r7 two-axis: x28 — the indent
|
||||
// step, heading the flat result list exactly where
|
||||
// group labels head their sections.
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.padding(.leading, 28)
|
||||
.padding(.top, 12)
|
||||
.padding(.bottom, 1)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// #144: the title+body scan — a thin mount for the pure
|
||||
/// `LibrarySearch` seam (title matches first, stable partition, both
|
||||
/// halves keep the scan's Finder order; body via readBody — frontmatter
|
||||
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
|
||||
/// The reader's per-piece cancellation check stops a superseded sweep's
|
||||
/// body reads between files; the in-memory title walk itself completes
|
||||
/// cheaply and the caller's guard discards its result. File scope since
|
||||
/// r6 (PostsLibraryColumn hit its type-body ceiling).
|
||||
///
|
||||
/// 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 func librarySearch(
|
||||
candidates: [Post],
|
||||
matching trimmed: String,
|
||||
home: URL,
|
||||
) async -> [Post] {
|
||||
LibrarySearch.results(for: trimmed, in: candidates) { post in
|
||||
guard !Task.isCancelled else { return nil }
|
||||
return PostStore.readBody(id: post.id, home: home)
|
||||
}
|
||||
}
|
||||
|
||||
/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at
|
||||
/// the source): the search field is the window's first — and at launch,
|
||||
/// only — text input, and AppKit assigns the window's initial first
|
||||
/// responder to it when the window becomes key. That happens AFTER
|
||||
/// onAppear, so the r6/r7 `searchFocused = false` writes were always
|
||||
/// overridden (FocusState mirrors the assignment back as true: terracotta
|
||||
/// ring + caret, the strongest element on screen). This invisible rider
|
||||
/// rides the library column and, at the window's FIRST become-key,
|
||||
/// resigns focus back to the window itself (`makeFirstResponder(nil)` —
|
||||
/// the neutral state; nothing gains focus instead). ONCE per process: a
|
||||
/// pane-switch remount must never steal a focus the user set on return.
|
||||
/// The second, next-runloop resign covers an assignment that lands after
|
||||
/// the notification (the PostEditorView layout-race precedent).
|
||||
private struct LaunchFocusReset: NSViewRepresentable {
|
||||
/// Process-wide once-flag — launch is a once-per-process event.
|
||||
private static var hasRun = false
|
||||
|
||||
final class RiderView: NSView {
|
||||
private var keyObserver: NSObjectProtocol?
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
if let keyObserver {
|
||||
NotificationCenter.default.removeObserver(keyObserver)
|
||||
}
|
||||
keyObserver = nil
|
||||
guard let window else { return }
|
||||
keyObserver = NotificationCenter.default.addObserver(
|
||||
forName: NSWindow.didBecomeKeyNotification,
|
||||
object: window,
|
||||
queue: .main,
|
||||
) { _ in
|
||||
MainActor.assumeIsolated {
|
||||
// The observer is scoped to `window` (object:), so the
|
||||
// notification carries nothing we don't already hold —
|
||||
// reading `note` here would cross a Sendable boundary.
|
||||
guard !LaunchFocusReset.hasRun else { return }
|
||||
LaunchFocusReset.hasRun = true
|
||||
window.makeFirstResponder(nil)
|
||||
DispatchQueue.main.async { window.makeFirstResponder(nil) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeNSView(context _: Context) -> RiderView {
|
||||
RiderView()
|
||||
}
|
||||
|
||||
func updateNSView(_: RiderView, context _: Context) {}
|
||||
}
|
||||
|
||||
/// #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()
|
||||
}
|
||||
}
|
||||
+26
-511
@@ -2,24 +2,19 @@
|
||||
// PostsModel.swift
|
||||
// Museion
|
||||
//
|
||||
// #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece
|
||||
// roots (projects/ + archive/, #107) with a ~0.5 s debounced rescan (#61),
|
||||
// selection, and the New Post draft lifecycle (#62). Own ops route through
|
||||
// the same rescan: one path.
|
||||
// #108: project targeting + the move/archive/restore ops behind the
|
||||
// variant-B library and the Archive pane.
|
||||
// #146: the domain extensions (#111/#114/#24/#122/#23/#25/#26) live in
|
||||
// PostsModelOutline/PostsModelPasses/PostsModelCards.swift; startWatching
|
||||
// + rescan sit in the file-scope watcher extension below (type-body
|
||||
// ceiling).
|
||||
// #18 (S1.1): the Posts pane's write side — selection and the New Post
|
||||
// draft lifecycle (#62). Own ops route through the same rescan: one path.
|
||||
// #179: every library-reflecting store write rides `performWrite` — the
|
||||
// one write rail pairing each write with exactly one rescan and owning
|
||||
// the error strip (card closes and the pass substrate stay off it: they
|
||||
// never regroup the library); the model owns the Home (watchedHome), no
|
||||
// method takes one.
|
||||
// the error strip; the model owns the Home (watchedHome), no method
|
||||
// takes one.
|
||||
// #146/#193: the domain extensions live in their own files — guard+
|
||||
// Convert PostsModelOutline, passes+Blind Read PostsModelPasses, fix
|
||||
// cards PostsModelCards, write rail+structural ops PostsModelWrites,
|
||||
// external guest+imports PostsModelImports, watcher+rescan
|
||||
// PostsModelWatcher.
|
||||
//
|
||||
|
||||
import CoreServices
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
@@ -38,55 +33,6 @@ struct PostDraft {
|
||||
let mountID = UUID()
|
||||
}
|
||||
|
||||
/// Recursive FSEvents stream on one or more directories (#61): file-level
|
||||
/// events, so nested `projects/<name>/<id>/post.md` edits from Finder fire
|
||||
/// too — a plain dir-FD dispatch source only sees direct children and misses
|
||||
/// them.
|
||||
final nonisolated class PostsWatcher: @unchecked Sendable {
|
||||
/// Fired on the main actor when anything under a watched path changes.
|
||||
var onEvent: (@MainActor @Sendable () -> Void)?
|
||||
|
||||
private var stream: FSEventStreamRef?
|
||||
|
||||
func start(urls: [URL]) {
|
||||
stop()
|
||||
var context = FSEventStreamContext(
|
||||
version: 0,
|
||||
info: Unmanaged.passUnretained(self).toOpaque(),
|
||||
retain: nil,
|
||||
release: nil,
|
||||
copyDescription: nil,
|
||||
)
|
||||
// C function pointer — no captures; `self` rides the info pointer.
|
||||
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
|
||||
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
|
||||
Task { @MainActor in watcher.onEvent?() }
|
||||
}
|
||||
guard let stream = FSEventStreamCreate(
|
||||
kCFAllocatorDefault,
|
||||
callback,
|
||||
&context,
|
||||
urls.map(\.path) as CFArray,
|
||||
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
|
||||
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
|
||||
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
|
||||
) else { return }
|
||||
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
||||
FSEventStreamStart(stream)
|
||||
self.stream = stream
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard let stream else { return }
|
||||
FSEventStreamStop(stream)
|
||||
FSEventStreamInvalidate(stream)
|
||||
FSEventStreamRelease(stream)
|
||||
self.stream = nil
|
||||
}
|
||||
|
||||
deinit { stop() }
|
||||
}
|
||||
|
||||
/// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern).
|
||||
/// The watcher runs while the workspace is open (app-scoped, #61).
|
||||
@MainActor
|
||||
@@ -94,7 +40,8 @@ final nonisolated class PostsWatcher: @unchecked Sendable {
|
||||
final class PostsModel {
|
||||
/// The scanned, title-sorted list — mirrors `projects/` + `archive/` at
|
||||
/// all times (#107).
|
||||
private(set) var posts: [Post] = []
|
||||
/// #193: setter internal — PostsModelWatcher's rescan writes it.
|
||||
var posts: [Post] = []
|
||||
|
||||
/// #144 (mounted half): the library content revision — the search
|
||||
/// snapshot's invalidation signal. The rescan rail bumps it whenever
|
||||
@@ -103,7 +50,8 @@ final class PostsModel {
|
||||
/// keeps the list still — yet the search must re-sweep). The `posts`
|
||||
/// assignment skip stays untouched: panes never regroup on bumps,
|
||||
/// only the mounted search re-keys.
|
||||
private(set) var contentRevision = 0
|
||||
/// #193: setter internal — PostsModelWatcher's rescan bumps it.
|
||||
var contentRevision = 0
|
||||
|
||||
/// The selected Post's id; nil = nothing selected (empty editor).
|
||||
/// #146: setter internal — the split-out domain extensions set it.
|
||||
@@ -121,11 +69,13 @@ final class PostsModel {
|
||||
/// #92: the external buffer's guest slot — one at a time, transient per
|
||||
/// launch. Takes the editor column; opening a Post or draft dismisses it
|
||||
/// (flush first).
|
||||
private(set) var externalSession: EditorSession?
|
||||
/// #193: setter internal — PostsModelImports owns the guest slot.
|
||||
var externalSession: EditorSession?
|
||||
|
||||
/// #94: a multi-file import waiting on its ONE Origin ask; the sheet
|
||||
/// answers, then the batch runs.
|
||||
private(set) var pendingImportURLs: [URL]?
|
||||
/// #193: setter internal — PostsModelImports stages the batch.
|
||||
var pendingImportURLs: [URL]?
|
||||
|
||||
/// #108: the explicit target for the NEXT new piece — set by New Project
|
||||
/// once the folder exists; outranks selection. Cleared when the draft
|
||||
@@ -136,7 +86,8 @@ final class PostsModel {
|
||||
/// #108: File ▸ New Project… stages its ask here — commands can't
|
||||
/// present sheets, so the model holds the flag and WorkspaceView
|
||||
/// presents (the pendingImportURLs pattern, #94).
|
||||
private(set) var askNewProject = false
|
||||
/// #193: setter internal — PostsModelWrites stages the ask.
|
||||
var askNewProject = false
|
||||
|
||||
/// #109: the just-saved outline draft's afterglow — the posts list
|
||||
/// lags one rescan (the FSEvents window), so the freshly-opened
|
||||
@@ -189,63 +140,21 @@ final class PostsModel {
|
||||
/// driven by WorkspaceView's root `.task(id: museionHome)` (first frame
|
||||
/// + every repoint, whichever pane is showing); no public method takes
|
||||
/// a Home parameter, callers pass none.
|
||||
/// `private(set)` — the setter stays PostsModel.swift-file-private.
|
||||
private(set) var watchedHome: URL?
|
||||
private var watcher = PostsWatcher()
|
||||
/// #193: setter internal — PostsModelWatcher's startWatching (the one
|
||||
/// writer) is a split-out extension now.
|
||||
var watchedHome: URL?
|
||||
var watcher = PostsWatcher()
|
||||
/// #143 (OPT-F3): scan parse memo — a rescan re-parses only changed
|
||||
/// post.md files, not the library (see PostScanCache).
|
||||
private let scanCache = PostScanCache()
|
||||
let scanCache = PostScanCache()
|
||||
/// #93: per-file watcher on the open external file — the #67 conflict
|
||||
/// check reused verbatim for foreign files.
|
||||
private var externalWatcher = PostsWatcher()
|
||||
|
||||
/// Bind a Home: ensure both container roots exist (FSEvents on a missing
|
||||
/// path is unreliable; archive/ is a watcher root now, #107), initial
|
||||
/// scan + start (or restart) the watcher. Called from WorkspaceView's
|
||||
/// root `.task(id: museionHome)` — first frame and every Home repoint,
|
||||
/// pane-independent.
|
||||
func bind(home: URL) {
|
||||
startWatching(home: home)
|
||||
Task { await rescan() }
|
||||
}
|
||||
|
||||
// MARK: Own ops (route through the same rescan, #61)
|
||||
|
||||
// ponytail: the PostStore calls here run on MainActor — small single-file
|
||||
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
|
||||
// them in Task.detached like rescan.
|
||||
|
||||
/// #179: the write rail — ONE seam pairs every library store write with
|
||||
/// exactly one rescan and owns the error strip. A verb passes its
|
||||
/// PostStore write (plus any post-write state surgery); a throw lands
|
||||
/// its reason in the strip with nothing rescanned, a clean run rescans
|
||||
/// once. The strip clears BEFORE the write, so a batch write that sets
|
||||
/// its own per-file failure messages mid-closure (importFiles) keeps
|
||||
/// them. The editor's debounced flush stays OUTSIDE the rail — its
|
||||
/// error semantics are the session's own (EditorSession.onError).
|
||||
/// Returns nil when the write landed; the failure reason otherwise
|
||||
/// (createProject hands that to its sheet).
|
||||
@discardableResult
|
||||
func performWrite(_ write: (URL) throws -> Void) -> String? {
|
||||
guard let home = watchedHome else {
|
||||
lastError = "No library is open yet — nothing was changed."
|
||||
return lastError
|
||||
}
|
||||
lastError = nil
|
||||
do {
|
||||
try write(home)
|
||||
Task { await rescan() }
|
||||
return nil
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
return lastError
|
||||
}
|
||||
}
|
||||
var externalWatcher = PostsWatcher()
|
||||
|
||||
/// #107: the project a NEW piece lands in — #108: an explicit pending
|
||||
/// target first, else the selected non-archived post's project, else the
|
||||
/// default. One home; newPost/importFiles must not drift.
|
||||
private var targetProject: String {
|
||||
var targetProject: String {
|
||||
pendingProject
|
||||
?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project
|
||||
?? Post.defaultProject
|
||||
@@ -290,27 +199,6 @@ final class PostsModel {
|
||||
openPieceCards = [] // #23: no open piece, no cards
|
||||
}
|
||||
|
||||
/// #92: dismiss the external guest slot, flushing pending edits (the
|
||||
/// guest is always leaving for somewhere — same posture as post
|
||||
/// selection change). brief-25: the dismissal is GUARDED — a guest
|
||||
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
|
||||
/// buffer and watcher live: teardown would drop the only retained
|
||||
/// copy of the unsaved edits. Callers abort their navigation on
|
||||
/// false, before clearing anything.
|
||||
/// #146: internal — the split-out domain extensions dismiss too.
|
||||
@discardableResult
|
||||
func dismissExternal() -> Bool {
|
||||
guard let guest = externalSession else {
|
||||
externalWatcher.stop()
|
||||
return true
|
||||
}
|
||||
guard sessionMayDepart(guest) else { return false }
|
||||
guest.teardown(flushFirst: false) // the gate already flushed
|
||||
externalSession = nil
|
||||
externalWatcher.stop()
|
||||
return true
|
||||
}
|
||||
|
||||
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
|
||||
/// here. The saved post opens straight into an editing session — the
|
||||
/// writer keeps typing where they were. #179: the write rides the rail.
|
||||
@@ -427,298 +315,6 @@ final class PostsModel {
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
|
||||
/// first (rename reads the file from disk — unflushed edits must land
|
||||
/// before the move), then reopens a session at the new id. #179: the
|
||||
/// write rides the rail.
|
||||
func rename(_ post: Post, to title: String) {
|
||||
// #108 audit 2: rename reads the file from disk — a failed write
|
||||
// aborts (moving the folder would strand unflushed edits), and the
|
||||
// session stays up, dirty and honest.
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
let moved = try PostStore.rename(post, to: title, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = moved.id
|
||||
if session?.postID == post.id {
|
||||
session = EditorSession(postID: moved.id, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
|
||||
/// was the post; the session is torn down (cancel only — the folder is
|
||||
/// leaving, a flush would resurrect nothing but churn the watcher).
|
||||
/// #179: the write rides the rail.
|
||||
func trash(_ post: Post) {
|
||||
performWrite { home in
|
||||
try PostStore.trash(post, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = nil
|
||||
if let open = session, open.postID == post.id {
|
||||
open.teardown(flushFirst: false)
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Projects (#108)
|
||||
|
||||
/// #108: New Project's confirmed sheet — the folder exists, the next
|
||||
/// draft targets it, and opens now.
|
||||
func newProjectPending(named name: String) {
|
||||
pendingProject = name
|
||||
newPost()
|
||||
}
|
||||
|
||||
/// #108: raw create — the sheet composes on it. #179: rides the write
|
||||
/// rail (one rescan pairs the new folder); the failure reason is BOTH
|
||||
/// returned for the sheet's inline display AND owned by the strip —
|
||||
/// the rail posture replaces the old sheet-only rule.
|
||||
func createProject(named name: String) -> String? {
|
||||
performWrite { try PostStore.createProject(named: name, home: $0) }
|
||||
}
|
||||
|
||||
/// #108: File ▸ New Project… — stage the ask (WorkspaceView presents).
|
||||
func stageNewProject() {
|
||||
askNewProject = true
|
||||
}
|
||||
|
||||
/// #108: the ask's Cancel.
|
||||
func cancelNewProject() {
|
||||
askNewProject = false
|
||||
}
|
||||
|
||||
/// #108 audit 2: the Move-to-Project list — every project on disk under
|
||||
/// projects/ plus the default (bind creates the roots, not posts/ — an
|
||||
/// empty Home must still offer it), localized-sorted to match the
|
||||
/// library's section order.
|
||||
func moveTargets() -> [String] {
|
||||
guard let home = watchedHome else { return [Post.defaultProject] }
|
||||
let root = home.appendingPathComponent("projects", isDirectory: true)
|
||||
let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
|
||||
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
|
||||
names.insert(Post.defaultProject)
|
||||
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
|
||||
}
|
||||
|
||||
/// #108 audit: flush the open piece, aborting when the write failed — a
|
||||
/// folder move must never carry away text that didn't land (the move
|
||||
/// itself succeeds exactly when a file write fails). Returns false with
|
||||
/// lastError set; the session stays up, dirty and honest.
|
||||
/// #33: internal — the Micropub draft flow (Micropub.swift) flushes
|
||||
/// through the same rail.
|
||||
func flushOrAbort(_ postID: String) -> Bool {
|
||||
guard let session, session.postID == postID else { return true }
|
||||
return sessionMayDepart(session)
|
||||
}
|
||||
|
||||
/// brief-25 (failed-flush-discarded-on-document-switch): the departure
|
||||
/// gate for ONE outgoing session — flushOrAbort's two gates lifted to
|
||||
/// document departure. An unanswered #67 conflict means disk holds
|
||||
/// foreign text with the session's version unwritten (#114 audit); a
|
||||
/// failed flush means the edits never landed. Either way the document
|
||||
/// may not leave: the caller aborts its navigation BEFORE clearing
|
||||
/// document-specific state, so the dirty session stays retained and
|
||||
/// honest while lastError says why (the structural rail's #108
|
||||
/// posture — now the navigation sites' too).
|
||||
/// #146: internal — PostsModelOutline's openUnguarded gates too.
|
||||
func sessionMayDepart(_ outgoing: EditorSession) -> Bool {
|
||||
if outgoing.conflictAlert {
|
||||
lastError = "This piece changed on disk underneath you — answer the reload question first."
|
||||
return false
|
||||
}
|
||||
if !outgoing.flush() {
|
||||
// Append, don't replace — the flush already routed the write's
|
||||
// localizedDescription into lastError; only say what was skipped.
|
||||
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// brief-25: the shared departure run for a full document switch —
|
||||
/// the external guest and the post session both leave (newPost,
|
||||
/// newOutline, openExternal). Each flushes through the departure gate
|
||||
/// first; a failure retains BOTH exactly as they are and the
|
||||
/// navigation aborts with nothing cleared.
|
||||
@discardableResult
|
||||
func departOpenDocuments() -> Bool {
|
||||
guard dismissExternal() else { return false }
|
||||
if let open = session {
|
||||
guard sessionMayDepart(open) else { return false }
|
||||
open.teardown(flushFirst: false) // the gate already flushed
|
||||
session = nil
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// #108: Move to Project — flush first (move reads disk), then the
|
||||
/// folder moves under projects/. Id stays the same; the session is
|
||||
/// reopened anyway so folderURL re-resolves to the new parent.
|
||||
/// #179: the write rides the rail.
|
||||
func moveToProject(_ post: Post, project: String) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.move(post, to: project, home: home)
|
||||
if session?.postID == post.id {
|
||||
session = EditorSession(postID: post.id, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: Move to Archive. Archiving the open piece clears it — the
|
||||
/// editor is empty until the next selection (archived pieces open from
|
||||
/// the Archive pane, where they're listed). #179: the write rides the
|
||||
/// rail.
|
||||
func archivePost(_ post: Post) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.archive(post, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = nil
|
||||
}
|
||||
if let open = session, open.postID == post.id {
|
||||
open.teardown(flushFirst: false) // already flushed above
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: Move Back — the restored piece lands in its project and opens;
|
||||
/// the writer stays in the piece they just revived. A session already
|
||||
/// open on the piece survives `select` — reopen it so folderURL points
|
||||
/// at projects/, not the archive path it was born with.
|
||||
/// #179: the write rides the rail.
|
||||
func restorePost(_ post: Post) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.restore(post, home: home)
|
||||
if let open = session, open.postID == post.id {
|
||||
session = EditorSession(postID: post.id, home: home)
|
||||
wireSession()
|
||||
} else {
|
||||
select(post.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: whole-project unarchive from the Archive pane's section header.
|
||||
/// Flush-first like every folder move (a dirty open piece inside the
|
||||
/// project would otherwise race the move), and its session is reopened so
|
||||
/// folderURL re-resolves off archive/ (same reason as restorePost).
|
||||
/// #179: the write rides the rail.
|
||||
func unarchiveProject(_ name: String) {
|
||||
// #108 audit 2: disk-derived membership — the posts snapshot is stale
|
||||
// the moment a Finder move lands. Captured BEFORE the move: after it
|
||||
// the piece resolves under projects/ and its archive membership is
|
||||
// invisible. dir − 1 = project dir (…/archive/<name>), − 2 = root.
|
||||
guard let boundHome = watchedHome else { return }
|
||||
func openPieceInArchivedProject() -> String? {
|
||||
guard let id = session?.postID,
|
||||
let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(),
|
||||
projectDir.lastPathComponent == name,
|
||||
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
|
||||
else { return nil }
|
||||
return id
|
||||
}
|
||||
let openID = openPieceInArchivedProject()
|
||||
if let openID {
|
||||
// #108 audit 2: the only #108 folder move that skipped the gate.
|
||||
guard flushOrAbort(openID) else { return }
|
||||
}
|
||||
performWrite { home in
|
||||
try PostStore.unarchiveProject(name, home: home)
|
||||
if let openID {
|
||||
session = EditorSession(postID: openID, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: External buffer (#91–#93) + Import (#94/#95)
|
||||
|
||||
/// #91/#92: open an external markdown file in the guest slot — one at a
|
||||
/// time; opening anything else (file, Post, draft) flushed and replaced
|
||||
/// it first. A Post session/draft stands down while the guest is up
|
||||
/// (the editor column is the guest's; the selection stays for return).
|
||||
/// Local files only (a dragged web link is not a document) and symlinks
|
||||
/// resolve to their real target so the in-place write never severs the
|
||||
/// link (rename over a symlink replaces it).
|
||||
func openExternal(_ url: URL) {
|
||||
guard url.isFileURL else { return }
|
||||
let target = url.resolvingSymlinksInPath()
|
||||
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
|
||||
draft = nil
|
||||
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
|
||||
lastDraftWasOutline = false // #109: same death, same clearing
|
||||
proseOverridePostID = nil // #111: same death, same clearing
|
||||
outlineGuardPieceID = nil // #111: the guest displaces any held ask
|
||||
openPieceCards = [] // #23: the guest is not a piece
|
||||
externalSession = EditorSession(target: .externalFile(target))
|
||||
if externalSession?.loadFailed == true {
|
||||
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
|
||||
externalSession = nil
|
||||
return
|
||||
}
|
||||
wireSession()
|
||||
startExternalWatch(url: target)
|
||||
}
|
||||
|
||||
/// #93: watch the open external file — its rescan is the #67 disk-change
|
||||
/// check, reused verbatim for foreign files. PostsWatcher fires on the
|
||||
/// main actor already; no re-hop needed.
|
||||
private func startExternalWatch(url: URL) {
|
||||
externalWatcher.onEvent = { [weak self] in
|
||||
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
|
||||
session.diskDidChange(diskText: disk)
|
||||
}
|
||||
externalWatcher.start(urls: [url.deletingLastPathComponent()])
|
||||
}
|
||||
|
||||
/// #94: stage a multi-file import — the ONE Origin ask presents; the
|
||||
/// sheet's answer runs the batch.
|
||||
func stageImport(_ urls: [URL]) {
|
||||
guard !urls.isEmpty else { return }
|
||||
pendingImportURLs = urls
|
||||
}
|
||||
|
||||
/// #94: dismiss the ask without an answer — the batch drops.
|
||||
func cancelImport() {
|
||||
pendingImportURLs = nil
|
||||
}
|
||||
|
||||
/// #94/#95: run the batch after the Origin answer — copy each file in as
|
||||
/// a Post; a per-file failure continues the batch into lastError (stated
|
||||
/// default, reversible; never an alert, never an abort). The last
|
||||
/// imported post opens; a failure anywhere keeps its message up even
|
||||
/// when other files landed. #107: the batch lands in the selected
|
||||
/// post's project (newPost's target rule). #179: the batch rides the
|
||||
/// rail — the strip was cleared up front, so the per-file failure
|
||||
/// messages the loop sets survive the rail's success tail.
|
||||
func importFiles(origin: Post.Origin) {
|
||||
guard let urls = pendingImportURLs else { return }
|
||||
pendingImportURLs = nil
|
||||
let project = targetProject
|
||||
var last: Post?
|
||||
performWrite { home in
|
||||
for url in urls {
|
||||
do {
|
||||
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
|
||||
} catch {
|
||||
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
}
|
||||
if let last {
|
||||
select(last.id)
|
||||
}
|
||||
}
|
||||
|
||||
/// #146: internal — the split-out domain extensions wire sessions too.
|
||||
func wireSession() {
|
||||
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
|
||||
@@ -726,84 +322,3 @@ final class PostsModel {
|
||||
externalSession?.onError = route
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Watcher (#61) — #146: file-scope extension (type_body_length)
|
||||
|
||||
extension PostsModel {
|
||||
private func startWatching(home: URL) {
|
||||
guard watchedHome != home else { return }
|
||||
watchedHome = home
|
||||
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
|
||||
for root in roots {
|
||||
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
|
||||
watcher.start(urls: roots)
|
||||
}
|
||||
|
||||
/// Off-main scan; keeps selection valid across the fresh refresh.
|
||||
/// FSEvents already coalesces bursts within its 0.5 s latency window —
|
||||
/// no second debounce on top.
|
||||
/// #146: internal — the split-out domain extensions trigger rescans.
|
||||
func rescan() async {
|
||||
guard let home = watchedHome else { return }
|
||||
// Scan + the #67 disk read both run off-main (a synced large post.md
|
||||
// must never stall the UI on a watcher burst).
|
||||
let openPostID = session?.postID
|
||||
// #114 audit: identity, not id — a same-id reopen (convert/restore/
|
||||
// move) must not receive the OLD session's stale disk text as a
|
||||
// spurious #67 conflict.
|
||||
let openSession = session
|
||||
let scanMemo = scanCache // detached capture, not a property read
|
||||
// The search's content signal: a re-read post.md (a cache miss)
|
||||
// changed library content even when its Post compares equal. Read
|
||||
// the counter before the scan so the delta after it says "this
|
||||
// scan saw disk change" (#144's mounted half).
|
||||
let missesBefore = scanMemo.misses
|
||||
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
|
||||
let posts = Post.scan(home: home, cache: scanMemo)
|
||||
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
|
||||
return (posts, disk)
|
||||
}.value
|
||||
guard !Task.isCancelled else { return }
|
||||
// #143: @Observable invalidates on assignment regardless of equality —
|
||||
// skip the no-op so panes don't regroup on our own autosave echoes.
|
||||
let listChanged = scanned != posts
|
||||
if listChanged {
|
||||
posts = scanned
|
||||
}
|
||||
// #144's mounted half: any list change OR any re-read file bumps the
|
||||
// content revision — the search snapshot's invalidation signal.
|
||||
// Archive/trash/rename arrive as list changes; a body-only edit as
|
||||
// a cache miss (metadata-equal — the skip above keeps the panes
|
||||
// still, the bump alone re-keys the mounted search).
|
||||
if listChanged || scanMemo.misses > missesBefore {
|
||||
contentRevision += 1
|
||||
}
|
||||
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
|
||||
// current selection — bind's initial rescan (detached scan over the
|
||||
// empty tree) can land its continuation after a select its scan never
|
||||
// saw, "vanishing" a piece that exists. Disk is the truth for
|
||||
// vanished; a stale snapshot must not kill a live session (teardown
|
||||
// cancels the debounce — unflushed edits would die with it).
|
||||
// #137 audit (finish): a scan that outlived a Home repoint speaks
|
||||
// for the OLD tree — never let it kill a session selected under
|
||||
// the NEW home (the id is missing from the old snapshot by
|
||||
// construction); the next rescan under the new home owns it.
|
||||
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil {
|
||||
selectedPostID = nil // the post vanished (deleted in Finder or here)
|
||||
if let open = session, open.postID == id {
|
||||
open.teardown(flushFirst: false) // post is gone; cancel the debounce
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
// #67: watcher echo check on the open post — equality against the
|
||||
// session's lastFlushedText suppresses our own writes exactly.
|
||||
if openSession === session, let openDiskText {
|
||||
openSession?.diskDidChange(diskText: openDiskText)
|
||||
}
|
||||
// #23: the open piece's stored fix cards ride the same rescan —
|
||||
// the watcher fires on <piece>/cards/ writes too.
|
||||
refreshCards()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//
|
||||
// PostsModelImports.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the external guest (#91–#93) and the import batch (#94/#95),
|
||||
// moved from PostsModel.swift (file-length ceiling) — openExternal,
|
||||
// dismissExternal, the guest watch, and stageImport/cancelImport/
|
||||
// importFiles, code unchanged.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension PostsModel {
|
||||
/// #92: dismiss the external guest slot, flushing pending edits (the
|
||||
/// guest is always leaving for somewhere — same posture as post
|
||||
/// selection change). brief-25: the dismissal is GUARDED — a guest
|
||||
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
|
||||
/// buffer and watcher live: teardown would drop the only retained
|
||||
/// copy of the unsaved edits. Callers abort their navigation on
|
||||
/// false, before clearing anything.
|
||||
/// #146: internal — the split-out domain extensions dismiss too.
|
||||
@discardableResult
|
||||
func dismissExternal() -> Bool {
|
||||
guard let guest = externalSession else {
|
||||
externalWatcher.stop()
|
||||
return true
|
||||
}
|
||||
guard sessionMayDepart(guest) else { return false }
|
||||
guest.teardown(flushFirst: false) // the gate already flushed
|
||||
externalSession = nil
|
||||
externalWatcher.stop()
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: External buffer (#91–#93) + Import (#94/#95)
|
||||
|
||||
/// #91/#92: open an external markdown file in the guest slot — one at a
|
||||
/// time; opening anything else (file, Post, draft) flushed and replaced
|
||||
/// it first. A Post session/draft stands down while the guest is up
|
||||
/// (the editor column is the guest's; the selection stays for return).
|
||||
/// Local files only (a dragged web link is not a document) and symlinks
|
||||
/// resolve to their real target so the in-place write never severs the
|
||||
/// link (rename over a symlink replaces it).
|
||||
func openExternal(_ url: URL) {
|
||||
guard url.isFileURL else { return }
|
||||
let target = url.resolvingSymlinksInPath()
|
||||
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
|
||||
draft = nil
|
||||
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
|
||||
lastDraftWasOutline = false // #109: same death, same clearing
|
||||
proseOverridePostID = nil // #111: same death, same clearing
|
||||
outlineGuardPieceID = nil // #111: the guest displaces any held ask
|
||||
openPieceCards = [] // #23: the guest is not a piece
|
||||
externalSession = EditorSession(target: .externalFile(target))
|
||||
if externalSession?.loadFailed == true {
|
||||
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
|
||||
externalSession = nil
|
||||
return
|
||||
}
|
||||
wireSession()
|
||||
startExternalWatch(url: target)
|
||||
}
|
||||
|
||||
/// #93: watch the open external file — its rescan is the #67 disk-change
|
||||
/// check, reused verbatim for foreign files. PostsWatcher fires on the
|
||||
/// main actor already; no re-hop needed.
|
||||
private func startExternalWatch(url: URL) {
|
||||
externalWatcher.onEvent = { [weak self] in
|
||||
guard let self, let session = externalSession, let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
|
||||
session.diskDidChange(diskText: disk)
|
||||
}
|
||||
externalWatcher.start(urls: [url.deletingLastPathComponent()])
|
||||
}
|
||||
|
||||
/// #94: stage a multi-file import — the ONE Origin ask presents; the
|
||||
/// sheet's answer runs the batch.
|
||||
func stageImport(_ urls: [URL]) {
|
||||
guard !urls.isEmpty else { return }
|
||||
pendingImportURLs = urls
|
||||
}
|
||||
|
||||
/// #94: dismiss the ask without an answer — the batch drops.
|
||||
func cancelImport() {
|
||||
pendingImportURLs = nil
|
||||
}
|
||||
|
||||
/// #94/#95: run the batch after the Origin answer — copy each file in as
|
||||
/// a Post; a per-file failure continues the batch into lastError (stated
|
||||
/// default, reversible; never an alert, never an abort). The last
|
||||
/// imported post opens; a failure anywhere keeps its message up even
|
||||
/// when other files landed. #107: the batch lands in the selected
|
||||
/// post's project (newPost's target rule). #179: the batch rides the
|
||||
/// rail — the strip was cleared up front, so the per-file failure
|
||||
/// messages the loop sets survive the rail's success tail.
|
||||
func importFiles(origin: Post.Origin) {
|
||||
guard let urls = pendingImportURLs else { return }
|
||||
pendingImportURLs = nil
|
||||
let project = targetProject
|
||||
var last: Post?
|
||||
performWrite { home in
|
||||
for url in urls {
|
||||
do {
|
||||
last = try PostStore.importFile(at: url, origin: origin, project: project, home: home)
|
||||
} catch {
|
||||
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
}
|
||||
if let last {
|
||||
select(last.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//
|
||||
// PostsModelWatcher.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the watching domain of PostsModel, moved from PostsModel.swift
|
||||
// (file-length ceiling) — the PostsWatcher FSEvents stream (#61), Home
|
||||
// binding, startWatching, and the rescan rail, code unchanged.
|
||||
//
|
||||
|
||||
import CoreServices
|
||||
import Foundation
|
||||
|
||||
/// Recursive FSEvents stream on one or more directories (#61): file-level
|
||||
/// events, so nested `projects/<name>/<id>/post.md` edits from Finder fire
|
||||
/// too — a plain dir-FD dispatch source only sees direct children and misses
|
||||
/// them.
|
||||
final nonisolated class PostsWatcher: @unchecked Sendable {
|
||||
/// Fired on the main actor when anything under a watched path changes.
|
||||
var onEvent: (@MainActor @Sendable () -> Void)?
|
||||
|
||||
private var stream: FSEventStreamRef?
|
||||
|
||||
func start(urls: [URL]) {
|
||||
stop()
|
||||
var context = FSEventStreamContext(
|
||||
version: 0,
|
||||
info: Unmanaged.passUnretained(self).toOpaque(),
|
||||
retain: nil,
|
||||
release: nil,
|
||||
copyDescription: nil,
|
||||
)
|
||||
// C function pointer — no captures; `self` rides the info pointer.
|
||||
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
|
||||
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
|
||||
Task { @MainActor in watcher.onEvent?() }
|
||||
}
|
||||
guard let stream = FSEventStreamCreate(
|
||||
kCFAllocatorDefault,
|
||||
callback,
|
||||
&context,
|
||||
urls.map(\.path) as CFArray,
|
||||
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
|
||||
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
|
||||
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
|
||||
) else { return }
|
||||
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
||||
FSEventStreamStart(stream)
|
||||
self.stream = stream
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard let stream else { return }
|
||||
FSEventStreamStop(stream)
|
||||
FSEventStreamInvalidate(stream)
|
||||
FSEventStreamRelease(stream)
|
||||
self.stream = nil
|
||||
}
|
||||
|
||||
deinit { stop() }
|
||||
}
|
||||
|
||||
// MARK: Watcher (#61)
|
||||
|
||||
extension PostsModel {
|
||||
/// Bind a Home: ensure both container roots exist (FSEvents on a missing
|
||||
/// path is unreliable; archive/ is a watcher root now, #107), initial
|
||||
/// scan + start (or restart) the watcher. Called from WorkspaceView's
|
||||
/// root `.task(id: museionHome)` — first frame and every Home repoint,
|
||||
/// pane-independent.
|
||||
func bind(home: URL) {
|
||||
startWatching(home: home)
|
||||
Task { await rescan() }
|
||||
}
|
||||
|
||||
private func startWatching(home: URL) {
|
||||
guard watchedHome != home else { return }
|
||||
watchedHome = home
|
||||
let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) }
|
||||
for root in roots {
|
||||
try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
|
||||
watcher.start(urls: roots)
|
||||
}
|
||||
|
||||
/// Off-main scan; keeps selection valid across the fresh refresh.
|
||||
/// FSEvents already coalesces bursts within its 0.5 s latency window —
|
||||
/// no second debounce on top.
|
||||
/// #146: internal — the split-out domain extensions trigger rescans.
|
||||
func rescan() async {
|
||||
guard let home = watchedHome else { return }
|
||||
// Scan + the #67 disk read both run off-main (a synced large post.md
|
||||
// must never stall the UI on a watcher burst).
|
||||
let openPostID = session?.postID
|
||||
// #114 audit: identity, not id — a same-id reopen (convert/restore/
|
||||
// move) must not receive the OLD session's stale disk text as a
|
||||
// spurious #67 conflict.
|
||||
let openSession = session
|
||||
let scanMemo = scanCache // detached capture, not a property read
|
||||
// The search's content signal: a re-read post.md (a cache miss)
|
||||
// changed library content even when its Post compares equal. Read
|
||||
// the counter before the scan so the delta after it says "this
|
||||
// scan saw disk change" (#144's mounted half).
|
||||
let missesBefore = scanMemo.misses
|
||||
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
|
||||
let posts = Post.scan(home: home, cache: scanMemo)
|
||||
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
|
||||
return (posts, disk)
|
||||
}.value
|
||||
guard !Task.isCancelled else { return }
|
||||
// #143: @Observable invalidates on assignment regardless of equality —
|
||||
// skip the no-op so panes don't regroup on our own autosave echoes.
|
||||
let listChanged = scanned != posts
|
||||
if listChanged {
|
||||
posts = scanned
|
||||
}
|
||||
// #144's mounted half: any list change OR any re-read file bumps the
|
||||
// content revision — the search snapshot's invalidation signal.
|
||||
// Archive/trash/rename arrive as list changes; a body-only edit as
|
||||
// a cache miss (metadata-equal — the skip above keeps the panes
|
||||
// still, the bump alone re-keys the mounted search).
|
||||
if listChanged || scanMemo.misses > missesBefore {
|
||||
contentRevision += 1
|
||||
}
|
||||
// Stale-scan guard (#137 suite find): the snapshot can PREDATE the
|
||||
// current selection — bind's initial rescan (detached scan over the
|
||||
// empty tree) can land its continuation after a select its scan never
|
||||
// saw, "vanishing" a piece that exists. Disk is the truth for
|
||||
// vanished; a stale snapshot must not kill a live session (teardown
|
||||
// cancels the debounce — unflushed edits would die with it).
|
||||
// #137 audit (finish): a scan that outlived a Home repoint speaks
|
||||
// for the OLD tree — never let it kill a session selected under
|
||||
// the NEW home (the id is missing from the old snapshot by
|
||||
// construction); the next rescan under the new home owns it.
|
||||
if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil {
|
||||
selectedPostID = nil // the post vanished (deleted in Finder or here)
|
||||
if let open = session, open.postID == id {
|
||||
open.teardown(flushFirst: false) // post is gone; cancel the debounce
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
// #67: watcher echo check on the open post — equality against the
|
||||
// session's lastFlushedText suppresses our own writes exactly.
|
||||
if openSession === session, let openDiskText {
|
||||
openSession?.diskDidChange(diskText: openDiskText)
|
||||
}
|
||||
// #23: the open piece's stored fix cards ride the same rescan —
|
||||
// the watcher fires on <piece>/cards/ writes too.
|
||||
refreshCards()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//
|
||||
// PostsModelWrites.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the #179 write rail and the structural library ops, moved from
|
||||
// PostsModel.swift (file-length ceiling) — performWrite, flushOrAbort,
|
||||
// rename/trash, the #108 project ops, and move/archive/restore, code
|
||||
// unchanged.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension PostsModel {
|
||||
// MARK: Own ops (route through the same rescan, #61)
|
||||
|
||||
// ponytail: the PostStore calls here run on MainActor — small single-file
|
||||
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
|
||||
// them in Task.detached like rescan.
|
||||
|
||||
/// #179: the write rail — ONE seam pairs every library store write with
|
||||
/// exactly one rescan and owns the error strip. A verb passes its
|
||||
/// PostStore write (plus any post-write state surgery); a throw lands
|
||||
/// its reason in the strip with nothing rescanned, a clean run rescans
|
||||
/// once. The strip clears BEFORE the write, so a batch write that sets
|
||||
/// its own per-file failure messages mid-closure (importFiles) keeps
|
||||
/// them. The editor's debounced flush stays OUTSIDE the rail — its
|
||||
/// error semantics are the session's own (EditorSession.onError).
|
||||
/// Returns nil when the write landed; the failure reason otherwise
|
||||
/// (createProject hands that to its sheet).
|
||||
@discardableResult
|
||||
func performWrite(_ write: (URL) throws -> Void) -> String? {
|
||||
guard let home = watchedHome else {
|
||||
lastError = "No library is open yet — nothing was changed."
|
||||
return lastError
|
||||
}
|
||||
lastError = nil
|
||||
do {
|
||||
try write(home)
|
||||
Task { await rescan() }
|
||||
return nil
|
||||
} catch {
|
||||
lastError = error.localizedDescription
|
||||
return lastError
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
|
||||
/// first (rename reads the file from disk — unflushed edits must land
|
||||
/// before the move), then reopens a session at the new id. #179: the
|
||||
/// write rides the rail.
|
||||
func rename(_ post: Post, to title: String) {
|
||||
// #108 audit 2: rename reads the file from disk — a failed write
|
||||
// aborts (moving the folder would strand unflushed edits), and the
|
||||
// session stays up, dirty and honest.
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
let moved = try PostStore.rename(post, to: title, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = moved.id
|
||||
if session?.postID == post.id {
|
||||
session = EditorSession(postID: moved.id, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
|
||||
/// was the post; the session is torn down (cancel only — the folder is
|
||||
/// leaving, a flush would resurrect nothing but churn the watcher).
|
||||
/// #179: the write rides the rail.
|
||||
func trash(_ post: Post) {
|
||||
performWrite { home in
|
||||
try PostStore.trash(post, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = nil
|
||||
if let open = session, open.postID == post.id {
|
||||
open.teardown(flushFirst: false)
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Projects (#108)
|
||||
|
||||
/// #108: New Project's confirmed sheet — the folder exists, the next
|
||||
/// draft targets it, and opens now.
|
||||
func newProjectPending(named name: String) {
|
||||
pendingProject = name
|
||||
newPost()
|
||||
}
|
||||
|
||||
/// #108: raw create — the sheet composes on it. #179: rides the write
|
||||
/// rail (one rescan pairs the new folder); the failure reason is BOTH
|
||||
/// returned for the sheet's inline display AND owned by the strip —
|
||||
/// the rail posture replaces the old sheet-only rule.
|
||||
func createProject(named name: String) -> String? {
|
||||
performWrite { try PostStore.createProject(named: name, home: $0) }
|
||||
}
|
||||
|
||||
/// #108: File ▸ New Project… — stage the ask (WorkspaceView presents).
|
||||
func stageNewProject() {
|
||||
askNewProject = true
|
||||
}
|
||||
|
||||
/// #108: the ask's Cancel.
|
||||
func cancelNewProject() {
|
||||
askNewProject = false
|
||||
}
|
||||
|
||||
/// #108 audit 2: the Move-to-Project list — every project on disk under
|
||||
/// projects/ plus the default (bind creates the roots, not posts/ — an
|
||||
/// empty Home must still offer it), localized-sorted to match the
|
||||
/// library's section order.
|
||||
func moveTargets() -> [String] {
|
||||
guard let home = watchedHome else { return [Post.defaultProject] }
|
||||
let root = home.appendingPathComponent("projects", isDirectory: true)
|
||||
let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []
|
||||
var names = Set(onDisk.filter { !$0.hasPrefix(".") })
|
||||
names.insert(Post.defaultProject)
|
||||
return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
|
||||
}
|
||||
|
||||
/// #108 audit: flush the open piece, aborting when the write failed — a
|
||||
/// folder move must never carry away text that didn't land (the move
|
||||
/// itself succeeds exactly when a file write fails). Returns false with
|
||||
/// lastError set; the session stays up, dirty and honest.
|
||||
/// #33: internal — the Micropub draft flow (Micropub.swift) flushes
|
||||
/// through the same rail.
|
||||
func flushOrAbort(_ postID: String) -> Bool {
|
||||
guard let session, session.postID == postID else { return true }
|
||||
return sessionMayDepart(session)
|
||||
}
|
||||
|
||||
/// brief-25 (failed-flush-discarded-on-document-switch): the departure
|
||||
/// gate for ONE outgoing session — flushOrAbort's two gates lifted to
|
||||
/// document departure. An unanswered #67 conflict means disk holds
|
||||
/// foreign text with the session's version unwritten (#114 audit); a
|
||||
/// failed flush means the edits never landed. Either way the document
|
||||
/// may not leave: the caller aborts its navigation BEFORE clearing
|
||||
/// document-specific state, so the dirty session stays retained and
|
||||
/// honest while lastError says why (the structural rail's #108
|
||||
/// posture — now the navigation sites' too).
|
||||
/// #146: internal — PostsModelOutline's openUnguarded gates too.
|
||||
func sessionMayDepart(_ outgoing: EditorSession) -> Bool {
|
||||
if outgoing.conflictAlert {
|
||||
lastError = "This piece changed on disk underneath you — answer the reload question first."
|
||||
return false
|
||||
}
|
||||
if !outgoing.flush() {
|
||||
// Append, don't replace — the flush already routed the write's
|
||||
// localizedDescription into lastError; only say what was skipped.
|
||||
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// brief-25: the shared departure run for a full document switch —
|
||||
/// the external guest and the post session both leave (newPost,
|
||||
/// newOutline, openExternal). Each flushes through the departure gate
|
||||
/// first; a failure retains BOTH exactly as they are and the
|
||||
/// navigation aborts with nothing cleared.
|
||||
@discardableResult
|
||||
func departOpenDocuments() -> Bool {
|
||||
guard dismissExternal() else { return false }
|
||||
if let open = session {
|
||||
guard sessionMayDepart(open) else { return false }
|
||||
open.teardown(flushFirst: false) // the gate already flushed
|
||||
session = nil
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// #108: Move to Project — flush first (move reads disk), then the
|
||||
/// folder moves under projects/. Id stays the same; the session is
|
||||
/// reopened anyway so folderURL re-resolves to the new parent.
|
||||
/// #179: the write rides the rail.
|
||||
func moveToProject(_ post: Post, project: String) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.move(post, to: project, home: home)
|
||||
if session?.postID == post.id {
|
||||
session = EditorSession(postID: post.id, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: Move to Archive. Archiving the open piece clears it — the
|
||||
/// editor is empty until the next selection (archived pieces open from
|
||||
/// the Archive pane, where they're listed). #179: the write rides the
|
||||
/// rail.
|
||||
func archivePost(_ post: Post) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.archive(post, home: home)
|
||||
if selectedPostID == post.id {
|
||||
selectedPostID = nil
|
||||
}
|
||||
if let open = session, open.postID == post.id {
|
||||
open.teardown(flushFirst: false) // already flushed above
|
||||
session = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: Move Back — the restored piece lands in its project and opens;
|
||||
/// the writer stays in the piece they just revived. A session already
|
||||
/// open on the piece survives `select` — reopen it so folderURL points
|
||||
/// at projects/, not the archive path it was born with.
|
||||
/// #179: the write rides the rail.
|
||||
func restorePost(_ post: Post) {
|
||||
guard flushOrAbort(post.id) else { return }
|
||||
performWrite { home in
|
||||
try PostStore.restore(post, home: home)
|
||||
if let open = session, open.postID == post.id {
|
||||
session = EditorSession(postID: post.id, home: home)
|
||||
wireSession()
|
||||
} else {
|
||||
select(post.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: whole-project unarchive from the Archive pane's section header.
|
||||
/// Flush-first like every folder move (a dirty open piece inside the
|
||||
/// project would otherwise race the move), and its session is reopened so
|
||||
/// folderURL re-resolves off archive/ (same reason as restorePost).
|
||||
/// #179: the write rides the rail.
|
||||
func unarchiveProject(_ name: String) {
|
||||
// #108 audit 2: disk-derived membership — the posts snapshot is stale
|
||||
// the moment a Finder move lands. Captured BEFORE the move: after it
|
||||
// the piece resolves under projects/ and its archive membership is
|
||||
// invisible. dir − 1 = project dir (…/archive/<name>), − 2 = root.
|
||||
guard let boundHome = watchedHome else { return }
|
||||
func openPieceInArchivedProject() -> String? {
|
||||
guard let id = session?.postID,
|
||||
let projectDir = PostStore.folder(of: id, home: boundHome)?.deletingLastPathComponent(),
|
||||
projectDir.lastPathComponent == name,
|
||||
projectDir.deletingLastPathComponent().lastPathComponent == "archive"
|
||||
else { return nil }
|
||||
return id
|
||||
}
|
||||
let openID = openPieceInArchivedProject()
|
||||
if let openID {
|
||||
// #108 audit 2: the only #108 folder move that skipped the gate.
|
||||
guard flushOrAbort(openID) else { return }
|
||||
}
|
||||
performWrite { home in
|
||||
try PostStore.unarchiveProject(name, home: home)
|
||||
if let openID {
|
||||
session = EditorSession(postID: openID, home: home)
|
||||
wireSession()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-596
@@ -7,11 +7,13 @@
|
||||
// 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.
|
||||
// per project (serif-15 head + mono count), Pass-State groups inside, and
|
||||
// a 2px accent edge bar on the selected row.
|
||||
// #193: the split-out files — the library column + its sheets + the
|
||||
// launch focus rider PostsLibraryColumn.swift, the shared
|
||||
// LibraryPostRow.swift.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// The Posts destination: the workspace's full four-column layout
|
||||
@@ -181,596 +183,3 @@ struct PostsPaneView: View {
|
||||
.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<String> = []
|
||||
/// #144: the library search — live title+body filter over the
|
||||
/// non-archived pieces. nil = not searching (sections render).
|
||||
@State private var query = ""
|
||||
/// #144 (mounted half): the landed sweep — results plus the key that
|
||||
/// computed them. nil = not searching or recomputing (the sections /
|
||||
/// spinner states); a snapshot that isn't `isFresh` for the current
|
||||
/// key never renders.
|
||||
@State private var snapshot: LibrarySearch.Snapshot?
|
||||
/// r5 (argon#44, mercury#52, sol#37): focus state for the field's
|
||||
/// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7
|
||||
/// onAppear-unfocus could never work — the launch focus is AppKit
|
||||
/// assigning the window's INITIAL first responder to its first text
|
||||
/// input (this field), at window-become-key, AFTER onAppear. FocusState
|
||||
/// merely mirrors that back as true. LaunchFocusReset (below) resigns
|
||||
/// it at the first become-key; from then on only the user drives this.
|
||||
@FocusState private var searchFocused: Bool
|
||||
|
||||
private var trimmedQuery: String {
|
||||
query.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// #144 (mounted half): the sweep's identity — trimmed query, the
|
||||
/// Home, and the library content revision (`PostsModel.contentRevision`,
|
||||
/// bumped by the rescan rail on any list change or re-read body). The
|
||||
/// `.task(id:)` below re-keys on ANY difference, so library writes and
|
||||
/// Home repoints restart the sweep instead of leaving stale rows; the
|
||||
/// landed snapshot renders only while `isFresh` for the current key.
|
||||
private var searchKey: LibrarySearch.SearchKey {
|
||||
LibrarySearch.SearchKey(query: trimmedQuery, homePath: home.path, revision: model.contentRevision)
|
||||
}
|
||||
|
||||
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 {
|
||||
// #144 (mounted half): a landed sweep renders only while
|
||||
// fresh for the CURRENT key — a library write that bumped
|
||||
// the revision (archive, trash, rename, body edit) or a
|
||||
// moved query drops to the recompute state, never stale rows.
|
||||
if let snapshot, snapshot.isFresh(for: searchKey) {
|
||||
if snapshot.results.isEmpty {
|
||||
searchEmptyState
|
||||
} else {
|
||||
searchResults(snapshot.results)
|
||||
}
|
||||
} 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: {
|
||||
// r7 (mercury#18, argon#12 — TWO-AXIS ladder,
|
||||
// the r6 four-step collapse undone): the
|
||||
// head ROW leads at the column's PRIMARY
|
||||
// inset (x14) — chevron glyph in a 14pt slot
|
||||
// — and every nested CONTENT shares the one
|
||||
// indent step (x28): head text, group
|
||||
// labels, and the rows' inner text. No third
|
||||
// or fourth x-axis exists in the column.
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
.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)
|
||||
// r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7
|
||||
// onAppear-unfocus — see LaunchFocusReset below for the mechanism.
|
||||
.background(LaunchFocusReset())
|
||||
.sheet(item: $renamingPost) { post in
|
||||
RenamePostSheet(post: post) { title in
|
||||
model.rename(post, to: title)
|
||||
}
|
||||
}
|
||||
.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()) { project in
|
||||
model.moveToProject(post, project: project)
|
||||
}
|
||||
}
|
||||
// #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). Keyed to the full
|
||||
// search key: a library write (revision bump) or a Home repoint
|
||||
// restarts the sweep too. The snapshot lands under the key
|
||||
// captured at start; a mid-sweep key change cancels here, and
|
||||
// even a raced assignment can't render — body gates on isFresh.
|
||||
.task(id: searchKey) {
|
||||
let key = searchKey
|
||||
guard !key.query.isEmpty else {
|
||||
snapshot = nil
|
||||
return
|
||||
}
|
||||
try? await Task.sleep(for: .milliseconds(250))
|
||||
guard !Task.isCancelled else { return }
|
||||
let found = await librarySearch(
|
||||
candidates: model.posts.filter { !$0.isArchived },
|
||||
matching: key.query,
|
||||
home: home,
|
||||
)
|
||||
guard !Task.isCancelled else { return }
|
||||
snapshot = LibrarySearch.Snapshot(key: key, results: found)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
.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)
|
||||
}
|
||||
}
|
||||
Button("Move to Project…") { movingPost = post }
|
||||
Button("Move to Archive") {
|
||||
model.archivePost(post)
|
||||
}
|
||||
Button("Move to Trash", role: .destructive) {
|
||||
model.trash(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
|
||||
/// softer, indented under the section head). r2: the label binds to
|
||||
/// its FIRST row (bottom 1 + stack 4) — it floated closer to the
|
||||
/// preceding row than to its own children.
|
||||
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 {
|
||||
// mercury#53 (r5): display-only normalization — the stored
|
||||
// rawValues keep their hyphen ("Pass-1 Done"); the rendered
|
||||
// label uses the space form so it matches the Pass 1 / Pass 2
|
||||
// vocabulary everywhere else.
|
||||
Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " "))
|
||||
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
// r6 (sol#6/21 — contrast final): group labels are
|
||||
// informational meta — FULL muted ink, no wash.
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
// r6 ladder: full muted ink. r7 two-axis: x28 — the ONE
|
||||
// indent step, shared with the head text and the row
|
||||
// cards' inner content.
|
||||
.padding(.leading, 28)
|
||||
.padding(.top, 10)
|
||||
.padding(.bottom, 1)
|
||||
ForEach(grouped) { post in
|
||||
postRow(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
|
||||
/// border on the column's chrome, taller than a text row; the placeholder
|
||||
/// r5 (argon#44, mercury#52, sol#37): the insertion caret tints
|
||||
/// terracotta (.tint on the field), and the small magnifier glyph sits at
|
||||
/// the field's leading edge (icon→text spacing rides the HStack's 6pt);
|
||||
/// the placeholder is the native prompt wearing the palette's muted ink
|
||||
/// (the composer's pattern).
|
||||
/// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6,
|
||||
/// present but never the strongest saturation on screen.
|
||||
private var searchField: some View {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "magnifyingglass")
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
|
||||
.textFieldStyle(.plain)
|
||||
.font(.system(size: 12))
|
||||
.focused($searchFocused)
|
||||
.tint(DesignTokens.accent)
|
||||
if isSearching {
|
||||
Button {
|
||||
query = ""
|
||||
} label: {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.accessibilityLabel("Clear search")
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 8)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(DesignTokens.surface)
|
||||
.overlay(
|
||||
// r8 (argon#6, mercury#12): quiet focus — accent at 0.6,
|
||||
// one step down from full strength.
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.strokeBorder(
|
||||
searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border,
|
||||
lineWidth: 1,
|
||||
),
|
||||
),
|
||||
)
|
||||
// r7 (mercury#18, argon#12 — two-axis ladder): the box spans the
|
||||
// FULL padded column width at the PRIMARY inset — leading 14
|
||||
// (aligned with the 'Posts' header text) to trailing 14 — the
|
||||
// same edges the row cards lead at.
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
|
||||
/// 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: 11, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
// r6: full muted ink; r7 two-axis: x28 — the indent
|
||||
// step, heading the flat result list exactly where
|
||||
// group labels head their sections.
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.padding(.leading, 28)
|
||||
.padding(.top, 12)
|
||||
.padding(.bottom, 1)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// #144: the title+body scan — a thin mount for the pure
|
||||
/// `LibrarySearch` seam (title matches first, stable partition, both
|
||||
/// halves keep the scan's Finder order; body via readBody — frontmatter
|
||||
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
|
||||
/// The reader's per-piece cancellation check stops a superseded sweep's
|
||||
/// body reads between files; the in-memory title walk itself completes
|
||||
/// cheaply and the caller's guard discards its result. File scope since
|
||||
/// r6 (PostsLibraryColumn hit its type-body ceiling).
|
||||
///
|
||||
/// 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 func librarySearch(
|
||||
candidates: [Post],
|
||||
matching trimmed: String,
|
||||
home: URL,
|
||||
) async -> [Post] {
|
||||
LibrarySearch.results(for: trimmed, in: candidates) { post in
|
||||
guard !Task.isCancelled else { return nil }
|
||||
return PostStore.readBody(id: post.id, home: home)
|
||||
}
|
||||
}
|
||||
|
||||
/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at
|
||||
/// the source): the search field is the window's first — and at launch,
|
||||
/// only — text input, and AppKit assigns the window's initial first
|
||||
/// responder to it when the window becomes key. That happens AFTER
|
||||
/// onAppear, so the r6/r7 `searchFocused = false` writes were always
|
||||
/// overridden (FocusState mirrors the assignment back as true: terracotta
|
||||
/// ring + caret, the strongest element on screen). This invisible rider
|
||||
/// rides the library column and, at the window's FIRST become-key,
|
||||
/// resigns focus back to the window itself (`makeFirstResponder(nil)` —
|
||||
/// the neutral state; nothing gains focus instead). ONCE per process: a
|
||||
/// pane-switch remount must never steal a focus the user set on return.
|
||||
/// The second, next-runloop resign covers an assignment that lands after
|
||||
/// the notification (the PostEditorView layout-race precedent).
|
||||
private struct LaunchFocusReset: NSViewRepresentable {
|
||||
/// Process-wide once-flag — launch is a once-per-process event.
|
||||
private static var hasRun = false
|
||||
|
||||
final class RiderView: NSView {
|
||||
private var keyObserver: NSObjectProtocol?
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
if let keyObserver {
|
||||
NotificationCenter.default.removeObserver(keyObserver)
|
||||
}
|
||||
keyObserver = nil
|
||||
guard let window else { return }
|
||||
keyObserver = NotificationCenter.default.addObserver(
|
||||
forName: NSWindow.didBecomeKeyNotification,
|
||||
object: window,
|
||||
queue: .main,
|
||||
) { _ in
|
||||
MainActor.assumeIsolated {
|
||||
// The observer is scoped to `window` (object:), so the
|
||||
// notification carries nothing we don't already hold —
|
||||
// reading `note` here would cross a Sendable boundary.
|
||||
guard !LaunchFocusReset.hasRun else { return }
|
||||
LaunchFocusReset.hasRun = true
|
||||
window.makeFirstResponder(nil)
|
||||
DispatchQueue.main.async { window.makeFirstResponder(nil) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeNSView(context _: Context) -> RiderView {
|
||||
RiderView()
|
||||
}
|
||||
|
||||
func updateNSView(_: RiderView, context _: Context) {}
|
||||
}
|
||||
|
||||
/// #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 + origin-only mono-11 meta (the Pass
|
||||
/// State rides the uppercase group label above; it stays in the a11y label).
|
||||
/// #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
|
||||
// VISIBILITY changes on selection.
|
||||
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
|
||||
return Button(action: select) {
|
||||
HStack(spacing: 0) {
|
||||
// The leading strip is always 2px wide so hover/selection
|
||||
// never shifts the title. r6 (mercury#49/52, argon#13):
|
||||
// the shared SelectedRowStrip capsule — accent, radius-1
|
||||
// ends, vertically inset 6pt (was 3) so it sits INSIDE
|
||||
// the card, never pasted on its square leading edge.
|
||||
SelectedRowStrip()
|
||||
.opacity(selected ? 1 : 0)
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Text(post.title)
|
||||
if post.type == .outline {
|
||||
Text(" ✳")
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
}
|
||||
// ui-polish r8: serif-13 per the row contract — `.callout`
|
||||
// was the system sans design (the r6/r7 councils pixel-
|
||||
// verified sans glyphs on the Archive rows).
|
||||
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
// Origin only — the Pass State already rides the uppercase
|
||||
// group label above (it stays in the accessibility label).
|
||||
// r7: the status micro-label sits INSIDE the row's content
|
||||
// padding — same x as the title, never flush with the edge.
|
||||
Text(post.origin.rawValue)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 10)
|
||||
}
|
||||
.clipShape(shape)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.background {
|
||||
if selected || hover {
|
||||
// r8 (mercury#11): the selected row DROPS its gray outline —
|
||||
// fill + accent capsule read as ONE shape; stacking fill +
|
||||
// outline + capsule competed. Hover keeps its borderless
|
||||
// 0.06 wash exactly as before.
|
||||
shape
|
||||
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
|
||||
}
|
||||
}
|
||||
// r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
|
||||
// leads at the PRIMARY inset (x14, the 'Posts' header text's
|
||||
// edge); its INNER content (title + status micro-label, strip
|
||||
// 2 + padding 12) lands at x28 — the ONE indent step, shared
|
||||
// with the head text and the group labels. No other x-axis
|
||||
// exists in the column. Vertical padding stays the content
|
||||
// VStack's constant 10 whether or not the row shows its strip.
|
||||
.padding(.horizontal, 14)
|
||||
.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)")
|
||||
}
|
||||
}
|
||||
@@ -84,9 +84,7 @@ nonisolated enum ProfileBackup {
|
||||
|
||||
// Age check against the newest existing snapshot (#15: skips record no
|
||||
// state; the normal age check governs retry).
|
||||
if let newest = sortedSnapshots(in: backupsRoot).first,
|
||||
now.timeIntervalSince(newest.timestamp) < snapshotInterval
|
||||
{
|
||||
if let newest = sortedSnapshots(in: backupsRoot).first, now.timeIntervalSince(newest.timestamp) < snapshotInterval {
|
||||
return .skippedFresh
|
||||
}
|
||||
|
||||
|
||||
@@ -139,16 +139,16 @@ nonisolated enum ProfileProvisioner {
|
||||
return logFailure(.failed(profile: profile, phase: phase, excerpt: excerpt))
|
||||
}
|
||||
|
||||
let env = SurfaceEnv(
|
||||
hermesBinary: hermesBinary,
|
||||
profileRoot: profileRoot,
|
||||
masterRoot: masterRoot,
|
||||
manifest: manifest,
|
||||
serverBinaryPath: serverBinaryPath,
|
||||
timeout: timeout,
|
||||
)
|
||||
for surface in ProfileSurface.allCases {
|
||||
switch provisionSurface(
|
||||
surface,
|
||||
hermesBinary: hermesBinary,
|
||||
profileRoot: profileRoot,
|
||||
masterRoot: masterRoot,
|
||||
manifest: manifest,
|
||||
serverBinaryPath: serverBinaryPath,
|
||||
timeout: timeout,
|
||||
) {
|
||||
switch provisionSurface(surface, env: env) {
|
||||
case let .seeded(deltaCopied, deltaPresent):
|
||||
copied += deltaCopied
|
||||
present += deltaPresent
|
||||
@@ -165,20 +165,27 @@ nonisolated enum ProfileProvisioner {
|
||||
return .seeded(copied: copied, present: present)
|
||||
}
|
||||
|
||||
/// Per-`perform` context threaded into every surface pass — everything
|
||||
/// except the surface itself (the loop variable), so the per-surface
|
||||
/// seam stays under the parameter-count ceiling.
|
||||
private struct SurfaceEnv {
|
||||
let hermesBinary: String?
|
||||
let profileRoot: String
|
||||
let masterRoot: String
|
||||
let manifest: [String]
|
||||
let serverBinaryPath: String?
|
||||
let timeout: TimeInterval
|
||||
}
|
||||
|
||||
/// Phases 1–4 for ONE surface profile (#134): create (or adopt), write
|
||||
/// defaults on fresh profiles via the CLI rail, link skills per
|
||||
/// allocation, register museion-tools (#23).
|
||||
private static func provisionSurface(
|
||||
_ surface: ProfileSurface,
|
||||
hermesBinary: String?,
|
||||
profileRoot: String,
|
||||
masterRoot: String,
|
||||
manifest: [String],
|
||||
serverBinaryPath: String?,
|
||||
timeout: TimeInterval,
|
||||
env: SurfaceEnv,
|
||||
) -> Outcome {
|
||||
let fileManager = FileManager.default
|
||||
let profileDir = ProfileLayout.profileDir(surface.profileName, root: profileRoot)
|
||||
let profileDir = ProfileLayout.profileDir(surface.profileName, root: env.profileRoot)
|
||||
|
||||
// Phase 1 — profile create. Dir-check first; spawn only when
|
||||
// missing (#45). `museion` is adopted, never re-created (ADR-0014).
|
||||
@@ -186,12 +193,12 @@ nonisolated enum ProfileProvisioner {
|
||||
// carry only Museion's curated set — coding and writing never mix, G3).
|
||||
var createdFresh = false
|
||||
if !fileManager.fileExists(atPath: profileDir) {
|
||||
guard let binary = hermesBinary else {
|
||||
guard let binary = env.hermesBinary else {
|
||||
return .failed(profile: surface.profileName, phase: .create, excerpt: "hermes binary not found")
|
||||
}
|
||||
let run = EngineProbe.execute(
|
||||
[binary, "profile", "create", surface.profileName, "--no-alias", "--no-skills"],
|
||||
timeout: timeout,
|
||||
timeout: env.timeout,
|
||||
)
|
||||
// #43: exit 1 + "already exists" on stdout = success (a
|
||||
// concurrent create — not ours, so not fresh); all errors print on stdout.
|
||||
@@ -208,10 +215,10 @@ nonisolated enum ProfileProvisioner {
|
||||
// profile (interrupted before its marker landed) is healed, and
|
||||
// the adopted museion is never touched — its model is the user's.
|
||||
if createdFresh || (surface != .chat && !markerExists(at: profileDir)) {
|
||||
guard let binary = hermesBinary else {
|
||||
guard let binary = env.hermesBinary else {
|
||||
return .failed(profile: surface.profileName, phase: .configure, excerpt: "hermes binary not found")
|
||||
}
|
||||
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: timeout) {
|
||||
if let failure = configureDefaults(profile: surface.profileName, hermesBinary: binary, timeout: env.timeout) {
|
||||
return failure
|
||||
}
|
||||
// A marker we couldn't record = configure incomplete — surface it
|
||||
@@ -224,7 +231,7 @@ nonisolated enum ProfileProvisioner {
|
||||
|
||||
// Phase 3 — per-profile skills: symlinks per allocation + the
|
||||
// copy-era → symlink migration (#133).
|
||||
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: masterRoot, manifest: manifest)
|
||||
let linked = linkSkills(surface: surface, profileDir: profileDir, masterRoot: env.masterRoot, manifest: env.manifest)
|
||||
if case .failed = linked {
|
||||
return linked
|
||||
}
|
||||
@@ -232,7 +239,7 @@ nonisolated enum ProfileProvisioner {
|
||||
// Phase 4 — museion-tools registration per profile (ADR-0008
|
||||
// amendment). nil on either binary is the test-injection seam;
|
||||
// production always has both after a gate pass.
|
||||
guard let hermesBinary, let serverBinaryPath else {
|
||||
guard let hermesBinary = env.hermesBinary, let serverBinaryPath = env.serverBinaryPath else {
|
||||
Logger(subsystem: subsystem, category: "provisioning")
|
||||
.info("museion-tools registration skipped: engine or server binary missing")
|
||||
return linked
|
||||
@@ -241,7 +248,7 @@ nonisolated enum ProfileProvisioner {
|
||||
profile: surface.profileName,
|
||||
hermesBinary: hermesBinary,
|
||||
serverBinaryPath: serverBinaryPath,
|
||||
timeout: timeout,
|
||||
timeout: env.timeout,
|
||||
) {
|
||||
return failure
|
||||
}
|
||||
@@ -511,6 +518,12 @@ nonisolated extension ProfileProvisioner {
|
||||
!name.isEmpty && name.allSatisfy { ($0.isLowercase && $0.isLetter) || $0.isNumber || $0 == "-" }
|
||||
}
|
||||
|
||||
/// True when `path` is a symlink (lstat-true, before any open) — the
|
||||
/// payload never ships one, so a linked entry refuses the tree match.
|
||||
private static func isSymlinked(_ path: String) -> Bool {
|
||||
(try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil
|
||||
}
|
||||
|
||||
/// Recursive byte-comparison of two dir trees — same entry names, every
|
||||
/// file byte-identical. `.DS_Store` is filtered from BOTH listings before
|
||||
/// the name-equality check (Finder noise, not a user edit — a
|
||||
@@ -532,9 +545,7 @@ nonisolated extension ProfileProvisioner {
|
||||
let rhsPath = (rhs as NSString).appendingPathComponent(name)
|
||||
// Neither side may carry a symlink at this entry (lstat-true,
|
||||
// before any open) — the payload never ships one.
|
||||
if (try? fileManager.destinationOfSymbolicLink(atPath: lhsPath)) != nil
|
||||
|| (try? fileManager.destinationOfSymbolicLink(atPath: rhsPath)) != nil
|
||||
{
|
||||
if isSymlinked(lhsPath) || isSymlinked(rhsPath) {
|
||||
return false
|
||||
}
|
||||
var lhsIsDirectory: ObjCBool = false, rhsIsDirectory: ObjCBool = false
|
||||
|
||||
@@ -377,10 +377,7 @@ final class ProseListTextView: NSTextView {
|
||||
guard let scalar = Unicode.Scalar(Int(char)) else { return false }
|
||||
return CharacterSet.whitespacesAndNewlines.contains(scalar)
|
||||
}
|
||||
if index > 0, index < length,
|
||||
!isGap(buffer.character(at: index - 1)),
|
||||
!isGap(buffer.character(at: index))
|
||||
{
|
||||
if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) {
|
||||
while index < length, !isGap(buffer.character(at: index)) {
|
||||
index += 1
|
||||
}
|
||||
|
||||
+177
-102
@@ -38,6 +38,39 @@ nonisolated enum ProsePresenter {
|
||||
classify(line, inFence: false)
|
||||
}
|
||||
|
||||
/// A fence delimiter line (``` or ~~~ prefix) — delimiter lines are
|
||||
/// fences even inside a fence (they close it).
|
||||
static func isFenceDelimiter(_ trimmed: Substring) -> Bool {
|
||||
trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~")
|
||||
}
|
||||
|
||||
/// Pure rule/mark syntax (horizontal rules, dinkus) — no content.
|
||||
static func isRuleSyntax(_ trimmed: Substring) -> Bool {
|
||||
trimmed.allSatisfy { $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }
|
||||
}
|
||||
|
||||
/// CommonMark ATX heading level (1–6) of a trimmed line — a heading
|
||||
/// needs 1–6 hashes followed by a space or end-of-line; 7+ hashes or a
|
||||
/// glued-on word is body text.
|
||||
static func headingLevel(of trimmed: Substring) -> Int? {
|
||||
let hashes = trimmed.prefix(while: { $0 == "#" }).count
|
||||
guard hashes > 0, hashes <= 6 else { return nil } // CommonMark caps at 6; 7+ is body
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
guard after.hasPrefix(" ") || after.isEmpty else { return nil }
|
||||
return hashes
|
||||
}
|
||||
|
||||
/// Heading ladder for a valid ATX level — 1–3 are named steps, 4–6
|
||||
/// share the h4+ rung (CommonMark).
|
||||
private static func headingKind(_ hashes: Int) -> LineKind {
|
||||
switch hashes {
|
||||
case 1: .heading1
|
||||
case 2: .heading2
|
||||
case 3: .heading3
|
||||
default: .heading4Plus
|
||||
}
|
||||
}
|
||||
|
||||
/// Delimiter lines are fences even inside a fence (they close it) — so the
|
||||
/// delim test runs before the inFence shortcut and `applyStyles` toggles
|
||||
/// on `kind == .fence` instead of re-deriving the prefix.
|
||||
@@ -46,28 +79,19 @@ nonisolated enum ProsePresenter {
|
||||
if trimmed.isEmpty {
|
||||
return .blank
|
||||
}
|
||||
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
|
||||
if isFenceDelimiter(trimmed) {
|
||||
return .fence
|
||||
}
|
||||
if inFence {
|
||||
return .fenceInterior
|
||||
}
|
||||
let hashes = trimmed.prefix(while: { $0 == "#" }).count
|
||||
if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
if after.hasPrefix(" ") || after.isEmpty {
|
||||
switch hashes {
|
||||
case 1: return .heading1
|
||||
case 2: return .heading2
|
||||
case 3: return .heading3
|
||||
default: return .heading4Plus
|
||||
}
|
||||
}
|
||||
if let hashes = headingLevel(of: trimmed) {
|
||||
return headingKind(hashes)
|
||||
}
|
||||
if trimmed.hasPrefix(">") {
|
||||
return .quote
|
||||
}
|
||||
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||
if isRuleSyntax(trimmed) {
|
||||
return .syntaxOnly
|
||||
}
|
||||
if line.firstMatch(of: listMarkerPattern) != nil {
|
||||
@@ -102,7 +126,7 @@ nonisolated enum ProsePresenter {
|
||||
var count = 0
|
||||
for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
|
||||
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
|
||||
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
|
||||
if isFenceDelimiter(trimmed) {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
@@ -171,58 +195,76 @@ nonisolated enum ProsePresenter {
|
||||
/// Count unclosed fences before `end` (``` or ~~~ delim lines toggle).
|
||||
private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool {
|
||||
var inFence = false
|
||||
for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) {
|
||||
if classify(line.text, inFence: inFence) == .fence {
|
||||
inFence.toggle()
|
||||
}
|
||||
let prefix = NSRange(location: 0, length: min(end, nsText.length))
|
||||
for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence {
|
||||
inFence.toggle()
|
||||
}
|
||||
return inFence
|
||||
}
|
||||
|
||||
/// The #… ATX marker of a heading line, dimmed to the code face.
|
||||
private static func dimHeadingMarker(_ out: NSMutableAttributedString, line: Line) {
|
||||
let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count
|
||||
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
|
||||
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
|
||||
if marker.length > 0 {
|
||||
out.addAttributes(ProseTypography.codeAttributes, range: marker)
|
||||
}
|
||||
}
|
||||
|
||||
/// Kinds whose text content carries inline trait styling (bold/italic/
|
||||
/// code/link spans).
|
||||
static func carriesInlineTraits(_ kind: LineKind) -> Bool {
|
||||
kind == .body || kind == .quote || kind == .listMarker
|
||||
}
|
||||
|
||||
/// Non-empty UTF-16 marker range of `pattern` at the line start, or nil.
|
||||
private static func markerRange(_ pattern: Regex<Substring>, in line: Line) -> NSRange? {
|
||||
guard let marker = markerRangeUTF16(pattern, in: line.text), marker.length > 0 else { return nil }
|
||||
return marker
|
||||
}
|
||||
|
||||
/// List marker dim + hanging indent: wrapped list lines align with the
|
||||
/// item's text, not the paragraph margin — the marker prefix (leading
|
||||
/// whitespace + "- "/"1. ") sets headIndent, mirroring reading.css's
|
||||
/// hanging lists (padding-left + outside markers; #ui-r1, sol#13; #ui-r2
|
||||
/// argon#53 flush fix). Nested items hang at their own prefix width.
|
||||
/// The prefix is measured in the EXACT attributes it renders in
|
||||
/// (listMarkerAttributes — the line's face and size), so the
|
||||
/// continuation lands flush; a different measuring face drifts
|
||||
/// per-glyph (~4pt left in r1). ponytail: a tab in the prefix measures
|
||||
/// at the default tab stop; the corpus uses spaces — widen if tabbed
|
||||
/// lists drift.
|
||||
private static func applyListMarker(_ out: NSMutableAttributedString, line: Line) {
|
||||
guard let marker = markerRange(listMarkerPattern, in: line) else { return }
|
||||
out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content))
|
||||
let prefix = String(line.text.prefix(NSMaxRange(marker)))
|
||||
let indent = NSAttributedString(
|
||||
string: prefix,
|
||||
attributes: ProseTypography.listMarkerAttributes,
|
||||
).size().width
|
||||
let hanging = NSMutableParagraphStyle()
|
||||
hanging.setParagraphStyle(paragraph(.body))
|
||||
hanging.headIndent = indent
|
||||
// #ui-r7 sol#29: inter-item rhythm (reading.css list margins)
|
||||
// — before-space only, the CSS block has no bottom margin.
|
||||
hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore
|
||||
out.addAttribute(.paragraphStyle, value: hanging, range: line.full)
|
||||
}
|
||||
|
||||
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) {
|
||||
guard line.full.length > 0 else { return }
|
||||
out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full)
|
||||
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
|
||||
switch kind {
|
||||
case .heading1, .heading2, .heading3, .heading4Plus:
|
||||
let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count
|
||||
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
|
||||
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
|
||||
if marker.length > 0 {
|
||||
out.addAttributes(dim, range: marker)
|
||||
}
|
||||
dimHeadingMarker(out, line: line)
|
||||
case .quote:
|
||||
if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 {
|
||||
if let marker = markerRange(quoteMarkerPattern, in: line) {
|
||||
out.addAttributes(dim, range: shifted(marker, into: line.content))
|
||||
}
|
||||
case .listMarker:
|
||||
if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 {
|
||||
out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content))
|
||||
// Hanging indent (#ui-r1, sol#13; #ui-r2 argon#53 flush
|
||||
// fix): wrapped list lines align with the item's text, not
|
||||
// the paragraph margin — the marker prefix (leading
|
||||
// whitespace + "- "/"1. ") sets headIndent, mirroring
|
||||
// reading.css's hanging lists (padding-left + outside
|
||||
// markers). Nested items hang at their own prefix width.
|
||||
// The prefix is measured in the EXACT attributes it
|
||||
// renders in (listMarkerAttributes — the line's face and
|
||||
// size), so the continuation lands flush; a different
|
||||
// measuring face drifts per-glyph (~4pt left in r1).
|
||||
// ponytail: a tab in the prefix measures at the default tab
|
||||
// stop; the corpus uses spaces — widen if tabbed lists drift.
|
||||
let prefix = String(line.text.prefix(NSMaxRange(marker)))
|
||||
let indent = NSAttributedString(
|
||||
string: prefix,
|
||||
attributes: ProseTypography.listMarkerAttributes,
|
||||
).size().width
|
||||
let hanging = NSMutableParagraphStyle()
|
||||
hanging.setParagraphStyle(paragraph(.body))
|
||||
hanging.headIndent = indent
|
||||
// #ui-r7 sol#29: inter-item rhythm (reading.css list margins)
|
||||
// — before-space only, the CSS block has no bottom margin.
|
||||
hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore
|
||||
out.addAttribute(.paragraphStyle, value: hanging, range: line.full)
|
||||
}
|
||||
applyListMarker(out, line: line)
|
||||
case .syntaxOnly:
|
||||
if line.content.length > 0 {
|
||||
out.addAttributes(dim, range: line.content)
|
||||
@@ -232,7 +274,7 @@ nonisolated enum ProsePresenter {
|
||||
case .fenceInterior, .blank, .body:
|
||||
break
|
||||
}
|
||||
if kind == .body || kind == .quote || kind == .listMarker {
|
||||
if carriesInlineTraits(kind) {
|
||||
styleInline(out, content: line.content, text: line.text)
|
||||
}
|
||||
}
|
||||
@@ -256,98 +298,119 @@ nonisolated enum ProsePresenter {
|
||||
private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/
|
||||
|
||||
/// Trait-style inline constructs. Marks dim; content gets real traits.
|
||||
/// Priority: code > link > bold > italic; later matches skip claimed spans.
|
||||
/// Priority: code > link > bold > italic; later matches skip claimed
|
||||
/// spans (`claim` is the shared overlap gate, so each family's loop
|
||||
/// stays honest about the ones before it).
|
||||
private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
|
||||
guard content.length > 0 else { return }
|
||||
var claimed: [Range<Int>] = []
|
||||
styleCodeAndLinks(out, content: content, text: text, claimed: &claimed)
|
||||
styleEmphasis(out, content: content, text: text, claimed: &claimed)
|
||||
dimStraySyntax(out, content: content, text: text, claimed: &claimed)
|
||||
}
|
||||
|
||||
func claim(_ span: Range<Int>) -> Bool {
|
||||
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
|
||||
claimed.append(span)
|
||||
return true
|
||||
}
|
||||
/// Claim `span` unless an earlier (higher-priority) match overlaps it.
|
||||
private static func claim(_ claimed: inout [Range<Int>], _ span: Range<Int>) -> Bool {
|
||||
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
|
||||
claimed.append(span)
|
||||
return true
|
||||
}
|
||||
|
||||
func dim(_ utf16: Range<Int>) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(ProseTypography.codeAttributes, range: range)
|
||||
}
|
||||
/// Dim a utf16 span in the code face (marks, brackets, stray syntax).
|
||||
private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(ProseTypography.codeAttributes, range: range)
|
||||
}
|
||||
|
||||
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(attrs, range: range)
|
||||
}
|
||||
/// Apply `attrs` to a utf16 span.
|
||||
private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(attrs, range: range)
|
||||
}
|
||||
|
||||
let boldFont = ProseTypography.boldBodyFont
|
||||
let italicFont = ProseTypography.italicBodyFont
|
||||
/// Inline code + links (priority 1–2). Code: marks + content in the code
|
||||
/// face, content at ink. Links: label ink + underline (CSS: ink text,
|
||||
/// muted rule); the brackets, ]( and the URL dim (reading hides them;
|
||||
/// dim is the editor's closest parity move).
|
||||
private static func styleCodeAndLinks(
|
||||
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
|
||||
) {
|
||||
let codeFont = ProseTypography.codeFont
|
||||
let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor]
|
||||
let linkAttrs: [NSAttributedString.Key: Any] = [
|
||||
.underlineStyle: NSUnderlineStyle.single.rawValue,
|
||||
.underlineColor: ProseTypography.mutedColor,
|
||||
]
|
||||
|
||||
// inline code — marks + content in the code face, content at ink
|
||||
for match in text.matches(of: codePattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
|
||||
guard claim(&claimed, span) else { continue }
|
||||
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
|
||||
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
|
||||
}
|
||||
// links — label ink + underline (CSS: ink text, muted rule); the
|
||||
// brackets, ]( and the URL dim (reading hides them; dim is the
|
||||
// editor's closest parity move).
|
||||
for match in text.matches(of: linkPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
guard claim(&claimed, span) else { continue }
|
||||
let whole = match.output // whole match (no capture groups)
|
||||
guard let sep = whole.firstRange(of: "](") else { continue }
|
||||
// sep indices are valid in text (Substring shares indices)
|
||||
let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!)
|
||||
let label = span.lowerBound + 1 ..< sepOffset
|
||||
dim(span.lowerBound ..< span.lowerBound + 1) // [
|
||||
attr(label, linkAttrs)
|
||||
dim(sepOffset ..< span.upperBound) // ](url)
|
||||
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [
|
||||
attr(out, content: content, label, linkAttrs)
|
||||
dim(out, content: content, sepOffset ..< span.upperBound) // ](url)
|
||||
}
|
||||
// bold
|
||||
}
|
||||
|
||||
/// Bold + italic (priority 3–4). CommonMark: intraword `_` never
|
||||
/// emphasizes (file_name_here); intraword `*` does. No lookbehind in
|
||||
/// swift-regex, so boundary chars are checked by hand.
|
||||
private static func styleEmphasis(
|
||||
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
|
||||
) {
|
||||
let boldFont = ProseTypography.boldBodyFont
|
||||
let italicFont = ProseTypography.italicBodyFont
|
||||
for match in text.matches(of: boldPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 2)
|
||||
dim(span.upperBound - 2 ..< span.upperBound)
|
||||
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
|
||||
guard claim(&claimed, span) else { continue }
|
||||
dim(out, content: content, span.lowerBound ..< span.lowerBound + 2)
|
||||
dim(out, content: content, span.upperBound - 2 ..< span.upperBound)
|
||||
attr(out, content: content, span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
|
||||
}
|
||||
// italic — two forms. CommonMark: intraword `_` never emphasizes
|
||||
// (file_name_here); intraword `*` does. No lookbehind in swift-regex,
|
||||
// so boundary chars are checked by hand.
|
||||
for match in text.matches(of: emStarPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
guard claim(&claimed, span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
if isMarkAdjacent(lo, hi) {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
|
||||
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
for match in text.matches(of: emUnderPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
guard claim(&claimed, span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
if isMarkAdjacent(lo, hi) {
|
||||
continue
|
||||
}
|
||||
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true {
|
||||
if isIntraword(lo, hi) {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
dim(out, content: content, span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(out, content: content, span.upperBound - 1 ..< span.upperBound)
|
||||
attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
// fallback: dim stray syntax chars outside claimed spans
|
||||
}
|
||||
|
||||
/// Fallback: dim stray syntax chars outside claimed spans.
|
||||
private static func dimStraySyntax(
|
||||
_ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range<Int>],
|
||||
) {
|
||||
let syntax = inlineSyntax
|
||||
for (offset, codeUnit) in text.utf16.enumerated() {
|
||||
guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue }
|
||||
@@ -355,10 +418,22 @@ nonisolated enum ProsePresenter {
|
||||
if claimed.contains(where: { $0.overlaps(unit) }) {
|
||||
continue
|
||||
}
|
||||
dim(unit)
|
||||
dim(out, content: content, unit)
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the char at either boundary of an emphasis span is itself
|
||||
/// a mark (`**foo**`'s inner `*` is bold, not emphasis).
|
||||
private static func isMarkAdjacent(_ lo: Character?, _ hi: Character?) -> Bool {
|
||||
lo == "*" || hi == "*" || lo == "_" || hi == "_"
|
||||
}
|
||||
|
||||
/// True when an `_…_` span sits inside a word (file_name_here never
|
||||
/// emphasizes).
|
||||
private static func isIntraword(_ lo: Character?, _ hi: Character?) -> Bool {
|
||||
lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true
|
||||
}
|
||||
|
||||
// MARK: Base attributes
|
||||
|
||||
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
|
||||
|
||||
@@ -31,10 +31,12 @@ nonisolated enum ProseTypography {
|
||||
|
||||
/// Headings = Concourse OT (the designer's own pairing with Valkyrie);
|
||||
/// Semibold carries heading weight better than Book on screen.
|
||||
nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold)
|
||||
nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size)
|
||||
?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold)
|
||||
|
||||
/// h2 = the headings face at CSS's 0.85× ladder step (#77).
|
||||
nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold)
|
||||
nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size)
|
||||
?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold)
|
||||
|
||||
/// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B
|
||||
/// cut has no 600 member — the bold trait (700, real or synthesized) is
|
||||
|
||||
@@ -104,7 +104,7 @@ nonisolated enum ReadingPresenter {
|
||||
// swiftlint:disable:next force_try
|
||||
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
|
||||
let mutable = NSMutableString(string: html)
|
||||
regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
||||
regex.replaceMatches(in: mutable, range: NSRange(location: 0, length: mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
||||
return mutable as String
|
||||
}
|
||||
|
||||
@@ -207,7 +207,8 @@ nonisolated enum ReadingPresenter {
|
||||
/// apex failure / missing binary → editing-treated source text (#69's
|
||||
/// fallback rule: fallback = the source, not a second renderer).
|
||||
static func fallbackPage(_ text: String) -> String {
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head>" +
|
||||
"<body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
|
||||
}
|
||||
|
||||
static func escapeHTML(_ text: String) -> String {
|
||||
|
||||
@@ -172,6 +172,13 @@ struct ReadingSurface: NSViewRepresentable {
|
||||
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
|
||||
}
|
||||
|
||||
/// True for our own loadHTMLString main-frame load (file URL or
|
||||
/// about:blank) — the only navigation reading allows in-app.
|
||||
private func isOwnMainFrameLoad(_ nav: WKNavigationAction) -> Bool {
|
||||
guard nav.targetFrame?.isMainFrame == true, let url = nav.request.url else { return false }
|
||||
return url.scheme == "file" || url.absoluteString == "about:blank"
|
||||
}
|
||||
|
||||
/// Allow our own loadHTMLString main-frame load (about:blank); a
|
||||
/// blanket .cancel would kill the page before it paints. Everything
|
||||
/// else is cancelled — reading never navigates in-app (#74 lesson).
|
||||
@@ -180,9 +187,7 @@ struct ReadingSurface: NSViewRepresentable {
|
||||
decidePolicyFor nav: WKNavigationAction,
|
||||
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void,
|
||||
) {
|
||||
if nav.targetFrame?.isMainFrame == true,
|
||||
let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank"
|
||||
{
|
||||
if isOwnMainFrameLoad(nav) {
|
||||
decisionHandler(.allow)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//
|
||||
// WorkspaceChrome.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the shared workspace chrome, moved from WorkspaceView.swift
|
||||
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
|
||||
// PaneHeader; every pane reuses them, code unchanged.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
|
||||
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
|
||||
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
|
||||
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
|
||||
/// reservation keeps layout constant.
|
||||
struct SelectedRowStrip: View {
|
||||
var body: some View {
|
||||
RoundedRectangle(cornerRadius: 1)
|
||||
.fill(DesignTokens.accent)
|
||||
.frame(width: 2)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
}
|
||||
|
||||
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
|
||||
/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
|
||||
/// Choose…). 36pt tall by default — a real hit target, not a text-size
|
||||
/// pill; pass a smaller `minHeight` where the row is compact.
|
||||
struct BorderedSecondaryButtonStyle: ButtonStyle {
|
||||
var minHeight: CGFloat = 36
|
||||
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.padding(.horizontal, 12)
|
||||
.frame(minHeight: minHeight)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(DesignTokens.surface)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.strokeBorder(DesignTokens.border),
|
||||
),
|
||||
)
|
||||
.opacity(configuration.isPressed ? 0.7 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
|
||||
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
|
||||
struct PaneHeader<Trailing: View>: View {
|
||||
let title: String
|
||||
/// Leading inset of the title row. Export default 14; the Learnings pane
|
||||
/// passes 26 so its title shares one leading edge with headings + rows.
|
||||
var titleInset: CGFloat = 14
|
||||
/// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom
|
||||
/// hairline is bounded to the same column the pane's content sits in
|
||||
/// (Archive/Learnings' 720pt reading column) — title, hairline, and
|
||||
/// content read as one framed block instead of a full-width rule over
|
||||
/// a bounded column. nil = full width (every other pane's default).
|
||||
var hairlineMaxWidth: CGFloat?
|
||||
@ViewBuilder var trailing: () -> Trailing
|
||||
|
||||
init(
|
||||
title: String,
|
||||
titleInset: CGFloat = 14,
|
||||
hairlineMaxWidth: CGFloat? = nil,
|
||||
@ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() },
|
||||
) {
|
||||
self.title = title
|
||||
self.titleInset = titleInset
|
||||
self.hairlineMaxWidth = hairlineMaxWidth
|
||||
self.trailing = trailing
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Spacer()
|
||||
trailing()
|
||||
}
|
||||
.padding(.horizontal, titleInset)
|
||||
.frame(minHeight: 52)
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(height: 1)
|
||||
// r8: the bound shares the content column's leading edge
|
||||
// (x0) and width — leading-aligned, never centered.
|
||||
.frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-426
@@ -7,6 +7,9 @@
|
||||
// rail 56 | library 232 | editor min 420 | mentor 356.
|
||||
// #108: the Archive rail destination (box icon, above Settings) + the
|
||||
// New Project ask both live here.
|
||||
// #193: the split-out files — ArchivePaneView.swift, the house ask
|
||||
// sheets WorkspaceViewSheets.swift, the shared chrome
|
||||
// WorkspaceChrome.swift; RailButton stays (the rail is its only caller).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
@@ -355,346 +358,6 @@ struct WorkspaceView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: the Archive pane — archive/ as a rail destination (prototype
|
||||
/// verdict: a destination, not a library disclosure). List-only: clicking a
|
||||
/// piece selects it and hops to Posts, where the editor column lives.
|
||||
private struct ArchivePaneView: View {
|
||||
var model: PostsModel
|
||||
/// Fired after a row select — the pane can't reach WorkspaceView's
|
||||
/// selection itself.
|
||||
let onOpenPiece: () -> Void
|
||||
@State private var renamingPost: Post?
|
||||
/// #108: collapsed project sections — per-view state, not persisted
|
||||
/// (mirrors the library column).
|
||||
@State private var collapsed: Set<String> = []
|
||||
|
||||
private var archivedByProject: [String: [Post]] {
|
||||
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
|
||||
}
|
||||
|
||||
/// #108: the prototype's toggle — click the project name (or chevron).
|
||||
private func toggle(_ project: String) {
|
||||
if collapsed.contains(project) {
|
||||
collapsed.remove(project)
|
||||
} else {
|
||||
collapsed.insert(project)
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
// No New button — things arrive here by being moved, not created.
|
||||
// r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME
|
||||
// fixed 720pt column the rows live in — one framed block.
|
||||
PaneHeader(title: "Archive", hairlineMaxWidth: 720)
|
||||
if archivedByProject.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
// #108 audit: Finder order, matching the library's sort.
|
||||
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
|
||||
let pieces = archivedByProject[project] ?? []
|
||||
// Same section-head shape as the library (#108
|
||||
// variant B), plus the project-level way out.
|
||||
// r7 (mercury#55, argon#41 — FINAL, supersedes the
|
||||
// r6 D24 ladder): the content column is a FIXED
|
||||
// 720pt frame (width, not maxWidth — the r6
|
||||
// content-hugging bound let the pill define the
|
||||
// right edge), left-anchored. TWO axes only, the
|
||||
// library's r7 ladder: the head row leads at x14
|
||||
// (chevron in a 14pt slot) with its label at x28 —
|
||||
// the ONE indent, shared with the entry rows'
|
||||
// inner text via the shared LibraryPostRow (cards
|
||||
// lead at x14); the 'Unarchive Group' pill rides
|
||||
// the header row's trailing edge INSIDE the frame
|
||||
// (14 → 706), and the row hairlines are bounded by
|
||||
// the same frame. Nothing spans past it.
|
||||
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
.frame(width: 14, alignment: .leading)
|
||||
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.onTapGesture {
|
||||
withAnimation { toggle(project) }
|
||||
}
|
||||
.accessibilityLabel("Toggle \(project)")
|
||||
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
|
||||
Text(project)
|
||||
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
|
||||
.kerning(0.6)
|
||||
.textCase(.uppercase) // #108: display-only — the folder name keeps its case
|
||||
.foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.onTapGesture {
|
||||
withAnimation { toggle(project) }
|
||||
}
|
||||
Text("· \(pieces.count)")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.padding(.leading, 8)
|
||||
Spacer(minLength: 8)
|
||||
// The 'New Post · Fork · Compact' language — a
|
||||
// bordered mono-11 secondary pill at the
|
||||
// trailing edge INSIDE the fixed 720pt frame.
|
||||
// r7 (mercury#55, argon#41): relabeled
|
||||
// 'Unarchive Group' — it moves the whole
|
||||
// project, not one piece.
|
||||
Button("Unarchive Group") {
|
||||
model.unarchiveProject(project)
|
||||
}
|
||||
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
|
||||
.help("Move the whole project back to projects/")
|
||||
.accessibilityLabel("Unarchive \(project)")
|
||||
}
|
||||
.padding(.top, 12)
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.bottom, 2)
|
||||
if !collapsed.contains(project) {
|
||||
ForEach(pieces) { post in
|
||||
// r7: the shared LibraryPostRow ladder —
|
||||
// card leads at x14 (PRIMARY), title text
|
||||
// at x28 (the one indent). The hairline is
|
||||
// BOUNDED to the fixed frame: x14 → 706.
|
||||
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
|
||||
model.select(post.id)
|
||||
onOpenPiece()
|
||||
}
|
||||
.overlay(alignment: .bottom) {
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(height: 1)
|
||||
.padding(.horizontal, 14)
|
||||
}
|
||||
.contextMenu {
|
||||
Button("Move Back to \(post.project)") {
|
||||
model.restorePost(post)
|
||||
}
|
||||
Button("Rename…") { renamingPost = post }
|
||||
// #114 (S4): works archived too — the piece
|
||||
// stays where it is, only type + body flip.
|
||||
if post.type == .outline {
|
||||
Button("Convert to Post…") {
|
||||
model.stageConversion(post)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// r7 (mercury#55, argon#41): the FIXED 720pt reading
|
||||
// column — width, not maxWidth (the r6 content-hugging
|
||||
// bound let the pill define the right edge); rows,
|
||||
// hairlines, and the pill all live inside it.
|
||||
// ponytail: fixed width clips on panes narrower than
|
||||
// 720 — a width-floored variant if a small-window
|
||||
// Archive ever matters.
|
||||
.frame(width: 720, alignment: .leading)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.background)
|
||||
.sheet(item: $renamingPost) { post in
|
||||
RenamePostSheet(post: post) { title in
|
||||
model.rename(post, to: title)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(spacing: 8) {
|
||||
Text("Nothing archived")
|
||||
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding(38)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
|
||||
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
|
||||
private struct OriginAskSheet: View {
|
||||
let count: Int
|
||||
let answer: (Post.Origin) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var origin: Post.Origin = .writer
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Who wrote this?")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text(count == 1
|
||||
? "Importing 1 file as a Post — the original is untouched."
|
||||
: "Importing \(count) files as Posts — the originals are untouched.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Picker("Origin", selection: $origin) {
|
||||
Text("I wrote it (writer)").tag(Post.Origin.writer)
|
||||
Text("AI-assisted (ai)").tag(Post.Origin.ai)
|
||||
}
|
||||
.pickerStyle(.radioGroup)
|
||||
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel) { dismiss() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Import") {
|
||||
answer(origin)
|
||||
dismiss()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 380)
|
||||
}
|
||||
}
|
||||
|
||||
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
|
||||
/// lines the outliner can't show — opening it as an outline would drop
|
||||
/// them on the next save. Prose = nothing drops; Outline = the explicit
|
||||
/// choice the ruling requires.
|
||||
private struct OutlineGuardSheet: View {
|
||||
let openInProse: () -> Void
|
||||
let openAsOutline: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Open as outline or prose?")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
// Dismissal itself is the cancel (binding set(false) →
|
||||
// cancelOutlineGuard) — Esc and ⌘. land here too.
|
||||
Button("Cancel", role: .cancel) {}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Open as Outline") {
|
||||
openAsOutline()
|
||||
}
|
||||
Button("Open in Prose") {
|
||||
openInProse()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 420)
|
||||
}
|
||||
}
|
||||
|
||||
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
|
||||
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
|
||||
/// to headings. On mixed content the ladder would drop prose lines —
|
||||
/// the sheet says so.
|
||||
private struct ConvertSheet: View {
|
||||
let lossy: Bool
|
||||
/// false = verbatim bullets, true = headings ladder — one decision,
|
||||
/// one model call.
|
||||
let convert: (Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Convert to Post")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
if lossy {
|
||||
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
// Dismissal itself is the cancel (binding set(false) →
|
||||
// cancelConversion) — Esc and ⌘. land here too.
|
||||
Button("Cancel", role: .cancel) {}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Headings") {
|
||||
convert(true)
|
||||
}
|
||||
Button("Verbatim Bullets") {
|
||||
convert(false)
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 440)
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
|
||||
/// future materialize path). Create runs through the model's raw op; the
|
||||
/// thrown reason is shown inline and the sheet stays up.
|
||||
private struct NewProjectSheet: View {
|
||||
/// Create + open a draft in it; nil = success, a string = the failure
|
||||
/// reason to show inline (keeps the sheet up).
|
||||
let create: (String) -> String?
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var name = ""
|
||||
@State private var failure: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("New Project")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Pieces land here when it's selected.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
TextField("Name", text: $name)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit { confirm() }
|
||||
if let failure {
|
||||
Text(failure)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.accent)
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel) { dismiss() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Create", action: confirm)
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 360)
|
||||
}
|
||||
|
||||
private func confirm() {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
if let reason = create(trimmed) {
|
||||
failure = reason
|
||||
} else {
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rail button: 44×44 muted icon, hover wash, the current pane raised as
|
||||
/// a tile. NO visible edge bar — ui-polish r2 re-ruling: the export's
|
||||
/// `::before` selection bar paints behind the app border in the export's
|
||||
@@ -761,89 +424,3 @@ private struct RailButton: View {
|
||||
.accessibilityLabel(label)
|
||||
}
|
||||
}
|
||||
|
||||
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
|
||||
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
|
||||
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
|
||||
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
|
||||
/// reservation keeps layout constant.
|
||||
struct SelectedRowStrip: View {
|
||||
var body: some View {
|
||||
RoundedRectangle(cornerRadius: 1)
|
||||
.fill(DesignTokens.accent)
|
||||
.frame(width: 2)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
}
|
||||
|
||||
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
|
||||
/// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
|
||||
/// Choose…). 36pt tall by default — a real hit target, not a text-size
|
||||
/// pill; pass a smaller `minHeight` where the row is compact.
|
||||
struct BorderedSecondaryButtonStyle: ButtonStyle {
|
||||
var minHeight: CGFloat = 36
|
||||
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.foreground)
|
||||
.padding(.horizontal, 12)
|
||||
.frame(minHeight: minHeight)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(DesignTokens.surface)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.strokeBorder(DesignTokens.border),
|
||||
),
|
||||
)
|
||||
.opacity(configuration.isPressed ? 0.7 : 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
|
||||
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
|
||||
struct PaneHeader<Trailing: View>: View {
|
||||
let title: String
|
||||
/// Leading inset of the title row. Export default 14; the Learnings pane
|
||||
/// passes 26 so its title shares one leading edge with headings + rows.
|
||||
var titleInset: CGFloat = 14
|
||||
/// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom
|
||||
/// hairline is bounded to the same column the pane's content sits in
|
||||
/// (Archive/Learnings' 720pt reading column) — title, hairline, and
|
||||
/// content read as one framed block instead of a full-width rule over
|
||||
/// a bounded column. nil = full width (every other pane's default).
|
||||
var hairlineMaxWidth: CGFloat?
|
||||
@ViewBuilder var trailing: () -> Trailing
|
||||
|
||||
init(
|
||||
title: String,
|
||||
titleInset: CGFloat = 14,
|
||||
hairlineMaxWidth: CGFloat? = nil,
|
||||
@ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() },
|
||||
) {
|
||||
self.title = title
|
||||
self.titleInset = titleInset
|
||||
self.hairlineMaxWidth = hairlineMaxWidth
|
||||
self.trailing = trailing
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text(title)
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Spacer()
|
||||
trailing()
|
||||
}
|
||||
.padding(.horizontal, titleInset)
|
||||
.frame(minHeight: 52)
|
||||
Rectangle()
|
||||
.fill(DesignTokens.border)
|
||||
.frame(height: 1)
|
||||
// r8: the bound shares the content column's leading edge
|
||||
// (x0) and width — leading-aligned, never centered.
|
||||
.frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//
|
||||
// WorkspaceViewSheets.swift
|
||||
// Museion
|
||||
//
|
||||
// #193: the house ask sheets, moved from WorkspaceView.swift
|
||||
// (file-length ceiling) — OriginAskSheet (#94), OutlineGuardSheet
|
||||
// (#111), ConvertSheet (#114), NewProjectSheet (#108) — code
|
||||
// unchanged (private → internal: WorkspaceView presents them
|
||||
// cross-file now).
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
|
||||
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
|
||||
struct OriginAskSheet: View {
|
||||
let count: Int
|
||||
let answer: (Post.Origin) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var origin: Post.Origin = .writer
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Who wrote this?")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text(count == 1
|
||||
? "Importing 1 file as a Post — the original is untouched."
|
||||
: "Importing \(count) files as Posts — the originals are untouched.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Picker("Origin", selection: $origin) {
|
||||
Text("I wrote it (writer)").tag(Post.Origin.writer)
|
||||
Text("AI-assisted (ai)").tag(Post.Origin.ai)
|
||||
}
|
||||
.pickerStyle(.radioGroup)
|
||||
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel) { dismiss() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Import") {
|
||||
answer(origin)
|
||||
dismiss()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 380)
|
||||
}
|
||||
}
|
||||
|
||||
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
|
||||
/// lines the outliner can't show — opening it as an outline would drop
|
||||
/// them on the next save. Prose = nothing drops; Outline = the explicit
|
||||
/// choice the ruling requires.
|
||||
struct OutlineGuardSheet: View {
|
||||
let openInProse: () -> Void
|
||||
let openAsOutline: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Open as outline or prose?")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text(
|
||||
"This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline " +
|
||||
"drops them on the next save. Prose mode shows everything.",
|
||||
)
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
// Dismissal itself is the cancel (binding set(false) →
|
||||
// cancelOutlineGuard) — Esc and ⌘. land here too.
|
||||
Button("Cancel", role: .cancel) {}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Open as Outline") {
|
||||
openAsOutline()
|
||||
}
|
||||
Button("Open in Prose") {
|
||||
openInProse()
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 420)
|
||||
}
|
||||
}
|
||||
|
||||
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
|
||||
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
|
||||
/// to headings. On mixed content the ladder would drop prose lines —
|
||||
/// the sheet says so.
|
||||
struct ConvertSheet: View {
|
||||
let lossy: Bool
|
||||
/// false = verbatim bullets, true = headings ladder — one decision,
|
||||
/// one model call.
|
||||
let convert: (Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Convert to Post")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
if lossy {
|
||||
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
HStack {
|
||||
Spacer()
|
||||
// Dismissal itself is the cancel (binding set(false) →
|
||||
// cancelConversion) — Esc and ⌘. land here too.
|
||||
Button("Cancel", role: .cancel) {}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Headings") {
|
||||
convert(true)
|
||||
}
|
||||
Button("Verbatim Bullets") {
|
||||
convert(false)
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 440)
|
||||
}
|
||||
}
|
||||
|
||||
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
|
||||
/// future materialize path). Create runs through the model's raw op; the
|
||||
/// thrown reason is shown inline and the sheet stays up.
|
||||
struct NewProjectSheet: View {
|
||||
/// Create + open a draft in it; nil = success, a string = the failure
|
||||
/// reason to show inline (keeps the sheet up).
|
||||
let create: (String) -> String?
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var name = ""
|
||||
@State private var failure: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("New Project")
|
||||
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
|
||||
Text("Pieces land here when it's selected.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
TextField("Name", text: $name)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit { confirm() }
|
||||
if let failure {
|
||||
Text(failure)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.accent)
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel", role: .cancel) { dismiss() }
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Create", action: confirm)
|
||||
.keyboardShortcut(.defaultAction)
|
||||
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.frame(width: 360)
|
||||
}
|
||||
|
||||
private func confirm() {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
if let reason = create(trimmed) {
|
||||
failure = reason
|
||||
} else {
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -299,12 +299,19 @@ enum WritingLockKiosk {
|
||||
return false
|
||||
}
|
||||
|
||||
private static func shouldRefuse(_ event: NSEvent) -> Bool {
|
||||
WritingLockState.active?.isLocked == true
|
||||
&& refusesKey(
|
||||
keyCode: event.keyCode,
|
||||
characters: event.charactersIgnoringModifiers,
|
||||
modifiers: event.modifierFlags,
|
||||
)
|
||||
}
|
||||
|
||||
private static func installRefusalMonitor() {
|
||||
guard refusalMonitor == nil else { return }
|
||||
refusalMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
|
||||
if WritingLockState.active?.isLocked == true,
|
||||
Self.refusesKey(keyCode: event.keyCode, characters: event.charactersIgnoringModifiers, modifiers: event.modifierFlags)
|
||||
{
|
||||
if Self.shouldRefuse(event) {
|
||||
return nil // swallowed — the lock holds
|
||||
}
|
||||
return event
|
||||
|
||||
Reference in new issue
Block a user