feat(library): search by title and body (#144)
CI / ci (push) Canceled after 0s
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:
1 parent
a2f6dc1653
commit
53c314d4e1
6 files changed
+225
-25
No files matched your search
+1
-1
@@ -22,7 +22,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
|
||||
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
|
||||
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media querieLine truncated
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
|
||||
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#144:** the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); state is view-local (`query`/`matches`, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#143 (OPT-F3):** `scan(home:cache:)` takes an optional `PostScanCache` (path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
|
||||
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
|
||||
|
||||
+162
-21
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user