feat(library): projects & archive UI — S2 (#108)
CI / ci (push) Canceled after 0s

Variant B per the #104 prototype verdict: the library column groups
pieces by project (serif lowercase heads, collapse toggle, Pass-State
groups inside, 2px edge-bar selection shared with the new Archive
pane via LibraryPostRow). Move to Project / Archive / Move Back /
whole-project Unarchive are folder moves — post.md bytes untouched,
never clobbering, ids globally unique. File ▸ New Post ⌘N and New
Project… ⌥⌘N (CommandGroup, never CommandMenu per #84).

Every folder move flushes pending edits first and aborts when the
write failed — nothing moves without its text. Project membership and
the archived-refusal derive from freshly resolved disk paths, never
the scan snapshot. Slug and project-name comparisons fold through one
canonical key (NFC + lowercase). Two reviewer fanouts this session;
their findings are all fixed or visibly parked.

144/144 tests green (run twice), swiftformat/swiftlint clean.

Closes #108
This commit is contained in:
AlexKucera committed 2026-10-13 22:18:24 +02:00
1 parent 9da3a07f4a
commit e55747e7fe
15 files changed
+1205 -68

No files matched your search

+163 -11
View File
@@ -7,6 +7,8 @@
// = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
// #107 (ADR-0012): pieces live under projects/<project>/<slug>/ (archive/
// mirrors the shape); the slug namespace is global across both roots.
// #108: project moves and archive/restore are plain folder moves between
// those roots — post.md bytes are never rewritten.
//
import Foundation
@@ -41,7 +43,9 @@ nonisolated enum PostStore {
// project counts; cache id→folder if it ever measures hot.
// Audit: project-level guards mirror scan's skips (hidden dirs,
// symlinks) so write paths and the library agree on what exists —
// a piece in a dot-project must never shadow a visible one.
// a piece in a dot-project must never shadow a visible one. The
// piece-level check resolves symlinks (only a stale-selection race
// reaches one — scan never lists symlinked pieces).
static func folder(of id: String, home: URL) -> URL? {
for root in Post.containerRoots {
let rootURL = home.appendingPathComponent(root, isDirectory: true)
@@ -91,12 +95,6 @@ nonisolated enum PostStore {
return result.isEmpty ? "untitled" : result
}
/// First free slug for a title: base slug, then `-2`, `-3`… (#60).
/// Case-insensitive existence check (#60): the slug namespace is GLOBAL
/// (#107) — every entry (dir or file) under `projects/*/` and `archive/*/`
/// is taken, lowercased — independent of the volume's case sensitivity,
/// and an archived slug is never reused. `excluding` skips an id (the
/// renamer's own, still present).
/// First free slug for a title: base slug, then `-2`, `-3`… (#60), over
/// the GLOBAL namespace (#107) — every entry under `projects/*/` and
/// `archive/*/` (an archived slug must never be reused; restore would
@@ -116,21 +114,34 @@ nonisolated enum PostStore {
atPath: rootURL.appendingPathComponent(project, isDirectory: true).path,
)) ?? []
for entry in entries {
taken.insert(entry.lowercased())
// #108 audit: all slug-space comparisons through `folded` —
// NFC + lowercase. Swift's == and Set hashing already fold
// canonical equivalence, so this is the explicit, tested
// contract rather than a behavior change; the load-bearing
// part is the lowercase (APFS is case-insensitive).
taken.insert(folded(entry))
}
}
}
let base = slug(from: title) // slug() is already lowercase
if !taken.contains(base) || base == ownID?.lowercased() {
let base = slug(from: title) // as-produced — the folder matches the title's bytes
let key = folded(base)
if !taken.contains(key) || key == ownID.flatMap(folded) {
return base
}
var suffix = 2
while taken.contains("\(base)-\(suffix)") {
while taken.contains(folded("\(base)-\(suffix)")) {
suffix += 1
}
return "\(base)-\(suffix)"
}
/// #108 audit: the canonical compare key — case-folded + Unicode-normalization
/// folded (NFC). APFS is normalization-insensitive, so two byte-sequences can
/// be one folder; every name-uniqueness check must compare through this.
private static func folded(_ name: String) -> String {
name.precomposedStringWithCanonicalMapping.lowercased()
}
/// First write (#62): lazily materialize `projects/<project>/<slug>/post.md`
/// with the #59 block stamped (plus `type: post`, #107). Pass State First
/// Draft, origin writer — the only values #18 writes; the folder appears
@@ -347,6 +358,147 @@ nonisolated enum PostStore {
try FileManager.default.trashItem(at: dir, resultingItemURL: &trashed)
}
// MARK: Project moves & archive (#108)
/// #108: move an active piece to another project — projects/<old>/<id> →
/// projects/<project>/<id>/ (folder move, post.md untouched, frontmatter
/// preserved). Destination project folder lazily created. Throws when the
/// piece is archived (restore is the archived move) or unresolvable, or
/// the destination already exists (disk anomaly — never clobber). A move
/// to the piece's own project is a no-op (the picker shows it, the writer
/// might confirm it — not an error). The current project derives from the
/// freshly resolved folder, not the scan snapshot (a Finder-side move
/// between scan and click must not misfile the piece).
static func move(_ post: Post, to project: String, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
// #108 audit 2: the refusal derives from the resolved path, not the
// scan snapshot — a stale isArchived=false must not smuggle an
// archived piece back into projects/ (restore is the archived move).
let projectDir = dir.deletingLastPathComponent()
guard projectDir.deletingLastPathComponent().lastPathComponent != "archive" else {
throw CocoaError(.featureUnsupported)
}
let target = try validatedProject(project)
guard folded(target) != folded(projectDir.lastPathComponent) else { return }
try relocate(dir, id: post.id, toRoot: "projects", project: target, home: home)
}
/// #108: archive one piece — projects/<p>/<id> → archive/<p>/<id>/ (folder
/// move; lazily creates archive/<p>/). The project derives from the
/// freshly resolved folder (not the scan snapshot).
static func archive(_ post: Post, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
try relocate(dir, id: post.id, toRoot: "archive",
project: dir.deletingLastPathComponent().lastPathComponent, home: home)
}
/// #108: put an archived piece back — archive/<p>/<id> → projects/<p>/<id>/.
static func restore(_ post: Post, home: URL) throws {
guard let dir = folder(of: post.id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
try relocate(dir, id: post.id, toRoot: "projects",
project: dir.deletingLastPathComponent().lastPathComponent, home: home)
}
/// #108: unarchive a whole project — archive/<name>/ → projects/<name>/.
/// When projects/<name>/ already exists, merge child-by-child instead of
/// failing (ids are globally unique, so real collisions are disk anomalies
/// that throw honestly). The emptied archive/<name>/ is removed.
static func unarchiveProject(_ name: String, home: URL) throws {
var isDir: ObjCBool = false
let source = home.appendingPathComponent("archive", isDirectory: true)
.appendingPathComponent(name, isDirectory: true)
guard FileManager.default.fileExists(atPath: source.path, isDirectory: &isDir), isDir.boolValue else {
throw CocoaError(.fileReadNoSuchFile)
}
// One code path for both cases: dest created (or already there), every
// child moved, the emptied source removed. moveItem throws on an
// existing destination child — a duplicate id from a Finder copy
// surfaces loudly instead of being clobbered mid-merge.
let dest = home.appendingPathComponent("projects", isDirectory: true)
.appendingPathComponent(name, isDirectory: true)
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
for child in try FileManager.default.contentsOfDirectory(atPath: source.path) {
// #108 audit: Finder metadata (.DS_Store) browsed into both halves
// would collide forever — dot-entries are invisible to the app
// everywhere else (scan, folder(of:)); skip them here too.
guard !child.hasPrefix(".") else { continue }
try FileManager.default.moveItem(
atPath: source.appendingPathComponent(child).path,
toPath: dest.appendingPathComponent(child).path,
)
}
// #108 audit 2: removeItem is permanent — only take the source down
// when the loop emptied it. Dot-entries skipped above (and any hidden
// user folder, .git, .research) stay where they are instead of being
// silently destroyed with the folder.
if (try? FileManager.default.contentsOfDirectory(atPath: source.path))?.isEmpty != false {
try FileManager.default.removeItem(at: source)
}
}
/// #108: materialize an empty projects/<name>/. Throws on a name that is
/// empty after trimming, contains "/", starts with ".", or collides with an
/// existing project under projects/ (case-insensitive, matching the volume).
static func createProject(named name: String, home: URL) throws {
let project = try validatedProject(name)
let projectsRoot = home.appendingPathComponent("projects", isDirectory: true)
// Case-insensitive (#60's rule for slugs, same reason): APFS is
// case-insensitive by default — "Foo" next to "foo" is one folder on
// disk but two projects in the UI. Independent of the volume's actual
// sensitivity, same as availableSlug.
let existing = (try? FileManager.default.contentsOfDirectory(atPath: projectsRoot.path)) ?? []
// #108 audit: fold Unicode normalization before the case-insensitive
// compare — NFC vs NFD "café" reads identical but makes two folders
// on normalization-insensitive APFS (and two indistinguishable
// sections). availableSlug folds through the same `folded` key.
guard !existing.contains(where: { folded($0) == folded(project) }) else {
throw CocoaError(.fileWriteFileExists)
}
try FileManager.default.createDirectory(
at: projectsRoot.appendingPathComponent(project, isDirectory: true),
withIntermediateDirectories: true,
)
}
/// The shared #108 relocation: resolve once, then a plain FileManager move
/// of the whole piece folder into <root>/<project>/<id>/ — lazy parent,
/// never clobbering, post.md bytes untouched.
private static func relocate(
_ dir: URL, id: String, toRoot root: String, project: String, home: URL,
) throws {
let parent = home.appendingPathComponent(root, isDirectory: true)
.appendingPathComponent(project, isDirectory: true)
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)
let dest = parent.appendingPathComponent(id, isDirectory: true)
// ids are globally unique — an existing destination is a disk anomaly
// (duplicate id from a Finder copy) or a self-move; fail loudly.
guard !FileManager.default.fileExists(atPath: dest.path) else {
throw CocoaError(.fileWriteFileExists)
}
try FileManager.default.moveItem(at: dir, to: dest)
}
/// #108: a project name becomes a folder name — trim, then reject empty,
/// path separators (traversal), hidden names (scan skips dot-dirs), and
/// ":"/control characters (Finder displays ":" as "/" — a legal APFS name
/// that round-trips confusingly).
private static func validatedProject(_ name: String) throws -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.hasPrefix("."),
!trimmed.contains(":"),
!trimmed.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
else {
throw CocoaError(.fileWriteInvalidFileName)
}
return trimmed
}
/// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the
/// #17 reader parses.
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String {