feat(library): search by title and body (#144)
CI / ci (push) Canceled after 0s

The library offered only project/pass-state browsing — no way to find a
piece by content ("which piece was it that talked about X", FEAT-004).
The library column gains a plain-text search field under the Posts
header: a 250 ms-debounced title+body filter over the non-archived
pieces, flat results with title matches first (both halves keep the
scan's Finder order), a mono match count, and the full row context menu
(Rename/Convert/Move/Archive/Trash) on result rows — extracted into one
postRow helper shared with the sections. Body matches go through
PostStore.readBody, so frontmatter never matches (machinery, not
prose). Clearing returns the project sections; state is view-local, so
both render sites (unfocused layout + focus-mode reveal) get the field.

The scan runs as a nonisolated static async helper awaited from
.task(id: trimmedQuery): off MainActor (a nonisolated async function
doesn't inherit the caller's actor) while staying INSIDE the structured
task, so a superseding keystroke or clear actually cancels the sweep
between pieces — the spec's Task.detached shape never received
cancellation (two-reviewer convergence in the finish-audit caught it,
plus the code comment claiming it did), and trimming the task id stops
whitespace-only edits from re-running identical scans.

Deliberately deferred: re-filter on a watcher rescan while a query sits
unchanged (any keystroke refreshes), and a PostScanCache-style body
memo (full-body re-read per sweep — same unbounded-read ceiling as
Post.scan; upgrade path noted in the helper's ponytail comment).

Known pre-existing (unchanged by this diff, proven by stash control):
repo-wide swiftlint exits 2 with 289 violations / 72 serious at HEAD;
this diff adds zero error-severity violations.

Suite 574/574 (xcresult executed count).

Closes #144
This commit is contained in:
AlexKucera committed 2026-11-03 12:04:09 +01:00
1 parent a2f6dc1653
commit 53c314d4e1
6 files changed
+225 -25

No files matched your search

+162 -21
View File
@@ -181,6 +181,18 @@ struct PostsLibraryColumn: View {
/// #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 = ""
@State private var matches: [Post]?
private var trimmedQuery: String {
query.trimmingCharacters(in: .whitespacesAndNewlines)
}
private var isSearching: Bool {
!trimmedQuery.isEmpty
}
/// Non-archived pieces keyed by project (scan order = title order holds
/// inside each group — filter preserves it).
@@ -201,7 +213,19 @@ struct PostsLibraryColumn: View {
.help("New Post")
.accessibilityLabel("New Post")
}
if activeByProject.isEmpty {
searchField
if isSearching {
if let matches {
if matches.isEmpty {
searchEmptyState
} else {
searchResults(matches)
}
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
} else if activeByProject.isEmpty {
emptyState
} else {
ScrollView {
@@ -268,6 +292,82 @@ struct PostsLibraryColumn: View {
model.moveToProject(post, project: project, home: home)
}
}
// #144: keystroke-debounced (250 ms), structured body scan —
// nonisolated search() runs the disk reads off MainActor while
// staying inside this task, so a superseding keystroke or clear
// cancels the sweep between pieces (the in-flight file read
// always finishes — readBody is synchronous).
.task(id: trimmedQuery) {
guard !trimmedQuery.isEmpty else {
matches = nil
return
}
try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return }
let found = await Self.search(
candidates: model.posts.filter { !$0.isArchived },
matching: trimmedQuery,
home: home,
)
guard !Task.isCancelled else { return }
matches = found
}
}
/// #144: the title+body scan — title matches first (stable partition,
/// both halves keep the scan's Finder order), body via readBody
/// (frontmatter never searched); the per-piece cancellation check stops
/// a superseded sweep between files.
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
/// posture); a PostScanCache-style body memo if it ever measures hot.
private nonisolated static func search(
candidates: [Post],
matching trimmed: String,
home: URL,
) async -> [Post] {
var byTitle: [Post] = []
var byBody: [Post] = []
for post in candidates {
if Task.isCancelled {
break
}
if post.title.localizedCaseInsensitiveContains(trimmed) {
byTitle.append(post)
continue
}
let body = PostStore.readBody(id: post.id, home: home) ?? ""
if body.localizedCaseInsensitiveContains(trimmed) {
byBody.append(post)
}
}
return byTitle + byBody
}
/// One piece row + its context menu — sections and search results
/// render the same row (#144: results carry the full menu too).
private func postRow(_ post: Post) -> some View {
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
// #114 (S4): outline pieces only — the ask picks the
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post, home: home)
}
Button("Move to Trash", role: .destructive) {
model.trash(post, home: home)
}
}
}
/// Pass-State groups inside one project (`.vB .group-label`: smaller,
@@ -284,31 +384,72 @@ struct PostsLibraryColumn: View {
.padding(.top, 8)
.padding(.bottom, 5)
ForEach(grouped) { post in
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
// #114 (S4): outline pieces only — the ask picks the
// body transform, then the piece becomes a prose post.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
Button("Move to Project…") { movingPost = post }
Button("Move to Archive") {
model.archivePost(post, home: home)
}
Button("Move to Trash", role: .destructive) {
model.trash(post, home: home)
}
}
postRow(post)
}
}
}
}
/// #144: the field row + bottom hairline (the pane-head voice).
private var searchField: some View {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
TextField("Search posts", text: $query)
.textFieldStyle(.plain)
.font(.system(size: 12))
if isSearching {
Button {
query = ""
} label: {
Image(systemName: "xmark.circle.fill")
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.accessibilityLabel("Clear search")
}
}
.padding(.horizontal, 12)
.padding(.vertical, 7)
.overlay(alignment: .bottom) {
Rectangle().fill(DesignTokens.border).frame(height: 1)
}
}
/// Flat results, title matches first (stable partition — both halves
/// keep the scan's Finder order). Same row the sections render.
private func searchResults(_ found: [Post]) -> some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
Text("\(found.count) \(found.count == 1 ? "match" : "matches")")
.font(.system(size: 10, design: DesignTokens.mono))
.kerning(0.6)
.foregroundStyle(DesignTokens.muted.opacity(0.8))
.padding(.horizontal, 14)
.padding(.top, 12)
.padding(.bottom, 5)
ForEach(found) { post in
postRow(post)
}
}
.padding(.bottom, 12)
}
}
private var searchEmptyState: some View {
VStack(spacing: 8) {
Text("No matches")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("No piece's title or body contains “\(trimmedQuery)”.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("No posts yet")