feat(editor): drop an image into the prose (#141)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Dragging an image onto a saved post's prose editor copies it (never moves) into the piece's assets/ under a parser-clean slugged name (collision -2 via the shared uniqueFile helper) and inserts  at the drop point with alt selected for type-over — one edit step, one undo. Routing rides the window-level SwiftUI drop destination, field-verified to starve every deeper drag destination (nested SwiftUI targets never fire; AppKit NSDraggingDestination overrides never fire). Pure-markdown sets keep the open-as-guest behavior; mixed md+image sets refuse loudly instead of silently dropping the images behind the opened markdown. The drop point comes from NSEvent.mouseLocation mapped through the one geometry source that answers under SwiftUI hosting — firstRect(forCharacterRange:), bottom-up screen coords. Non-contiguous layout returns zero/stale rects for off-screen characters, so the solve (a pure static function, pinned by windowless tests) samples the document, keeps only viewport-band rects, brackets the drop between two in-band samples, binary-searches the bracket, and slides to the next whitespace gap — a landing never splices inside a word or an existing ref. The typewriter inset re-syncs after the edit so scrolling never freezes. The source gate refuses folders and symlinks alike: copyItem would land the LINK itself, and the #34 publish rail would then refuse the whole send. Type gate = the rail's exact set (PNG/JPEG/GIF/WebP/ SVG) — nothing enters assets/ that can't ship. Drafts, outlines, and guest surfaces refuse loudly. Finish-audit (three fresh-context reviewers) drove the mixed-set routing, the symlink refusal, and the pure-function extraction; every pin flip-verified in one batched cycle. Eleven ingest tests; suite 557. Closes #141
This commit is contained in:
1 parent
695ec27e11
commit
de1154dacd
12 files changed
+622
-14
No files matched your search
+2
-2
@@ -24,7 +24,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `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)`).
|
||||
- `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. **#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
|
||||
- `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`).
|
||||
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
|
||||
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
|
||||
@@ -37,7 +37,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
|
||||
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting. **#141 illustration ingest:** window-level SwiftUI `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'s #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (`allSatisfy` — a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the drop point. The source must be a PLAIN file — a dropped symlink refuses (`IngestError.isLink`: `copyItem` would land the LINK itself and the #34 rail would refuse the whole send; finish-audit 2026-11-02, empirically verified), a Finder folder with an image extension refuses (`isFolder`); collisions ride `FixCardStore.uniqueFile` (`-2`/`-3`, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure's `location` is UNUSABLE under this hosting; the pointer's screen position (`NSEvent.mouseLocation`) maps to an index via `firstRect(forCharacterRange:)` — its y is bottom-up screen coords like the mouse (no flip), non-contiguous layout makes OFF-SCREEN characters return garbage rects (whole-doc searches converge on the layout boundary), so `dropIndex(length:targetY:bandMinY:bandMaxY:rectY:)` — a `nonisolated static` PURE function (pinned by tests without a window) — SAMPLES the document (512 points), keeps only rects inside the viewport band (plain NSView geometry), brackets the drop between two in-band samples, binary-searches the bracket; a pointer above every in-band sample clamps to the first visible char, below all to the last in-band sample, no in-band evidence to 0 (never the old silent index-0-on-garbage), then slides the index to the next whitespace gap (never splices inside a word or an existing ref; dogfood-verified 2026-11-02, landing within one line). `alt` selected (offset +2, length 3) and scrolled to, with `CaretCentering.syncTypewriterInset` re-synced after the edit — without it the typewriter inset is stale and the editor freezes scrolling until the next keypress; one shouldChangeText step = one undo, didChangeText driving the coordinLine truncated
|
||||
- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes), `testConnection(for:)` runs the probe per provider (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are igLine truncated
|
||||
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
|
||||
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
|
||||
|
||||
@@ -13,6 +13,12 @@ import SwiftUI
|
||||
@MainActor
|
||||
@Observable
|
||||
final class AppGateState {
|
||||
/// #141: the live prose text view — the window-level drop destination
|
||||
/// (the ONLY destination that ever fires; nested editor-level SwiftUI
|
||||
/// targets are never consulted, and AppKit views registered for file
|
||||
/// drags are starved by it — field-verified 2026-11-02) routes image
|
||||
/// drops to the editor through this handle.
|
||||
let proseDrop = ProseDropBridge()
|
||||
var gateRaised = true
|
||||
/// True once the gate sheet's onDismiss fired (dismissal completion, #48) —
|
||||
/// the provisioning failure card presents only after this.
|
||||
|
||||
@@ -176,12 +176,25 @@ struct PostEditorView: View {
|
||||
draftText: session == nil ? draftText : nil,
|
||||
)
|
||||
} else if let session {
|
||||
ProseTextView(session: session, spellChecking: gate.spellChecking, focused: gate.isFocused, caretHint: flipBackCaret)
|
||||
ProseTextView(
|
||||
session: session,
|
||||
spellChecking: gate.spellChecking,
|
||||
focused: gate.isFocused,
|
||||
caretHint: flipBackCaret,
|
||||
dropBridge: gate.proseDrop,
|
||||
)
|
||||
} else {
|
||||
ProseTextView(draft: draftMirror, spellChecking: gate.spellChecking, focused: gate.isFocused, onEdit: { newText in
|
||||
draftMirror = newText
|
||||
draftEdited?(newText)
|
||||
}, caretHint: flipBackCaret)
|
||||
ProseTextView(
|
||||
draft: draftMirror,
|
||||
spellChecking: gate.spellChecking,
|
||||
focused: gate.isFocused,
|
||||
onEdit: { newText in
|
||||
draftMirror = newText
|
||||
draftEdited?(newText)
|
||||
},
|
||||
caretHint: flipBackCaret,
|
||||
dropBridge: gate.proseDrop,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,6 +322,13 @@ private struct SaveStateDot: View {
|
||||
|
||||
// MARK: - TextKit2 surface (the lifted spike pane)
|
||||
|
||||
/// #141: the SwiftUI drop target's handle down to the live prose text
|
||||
/// view (weak — dies with the editor surface).
|
||||
@MainActor
|
||||
final class ProseDropBridge {
|
||||
weak var textView: ProseListTextView?
|
||||
}
|
||||
|
||||
/// NSTextView in a scroll view; attributes are presentation-only over a plain
|
||||
/// store. Session mode: edits → session.edit (debounce), cursor → session,
|
||||
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
|
||||
@@ -322,17 +342,28 @@ struct ProseTextView: NSViewRepresentable {
|
||||
/// #21: focus mode — the text ground joins the workspace background.
|
||||
var focused = false
|
||||
var caretHint: (location: Int, token: Int)?
|
||||
/// #141: the piece folder dropped images ingest into — saved posts
|
||||
/// only (drafts have no folder until first save; the external guest
|
||||
/// isn't a piece). Nil = image drags refuse loudly.
|
||||
var ingestFolder: URL?
|
||||
/// #141: the drop bridge — the WINDOW-level SwiftUI drop target
|
||||
/// reaches this text view through it (app-scoped, passed down from
|
||||
/// the gate at both call sites — never optional).
|
||||
var dropBridge: ProseDropBridge
|
||||
|
||||
init(
|
||||
session: EditorSession,
|
||||
spellChecking: Bool = false,
|
||||
focused: Bool = false,
|
||||
caretHint: (location: Int, token: Int)? = nil,
|
||||
dropBridge: ProseDropBridge,
|
||||
) {
|
||||
self.session = session
|
||||
self.spellChecking = spellChecking
|
||||
self.focused = focused
|
||||
self.caretHint = caretHint
|
||||
ingestFolder = session.postID != nil ? session.folderURL : nil
|
||||
self.dropBridge = dropBridge
|
||||
}
|
||||
|
||||
init(
|
||||
@@ -341,12 +372,14 @@ struct ProseTextView: NSViewRepresentable {
|
||||
focused: Bool = false,
|
||||
onEdit: @escaping (String) -> Void,
|
||||
caretHint: (location: Int, token: Int)? = nil,
|
||||
dropBridge: ProseDropBridge,
|
||||
) {
|
||||
self.draft = draft
|
||||
self.spellChecking = spellChecking
|
||||
self.focused = focused
|
||||
self.onEdit = onEdit
|
||||
self.caretHint = caretHint
|
||||
self.dropBridge = dropBridge
|
||||
}
|
||||
|
||||
/// Cursor state snapshot from the live view (#66).
|
||||
@@ -361,6 +394,8 @@ struct ProseTextView: NSViewRepresentable {
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
|
||||
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
|
||||
dropBridge.textView = tv // #141: the SwiftUI drop target's handle
|
||||
tv.isRichText = false // plain source of truth; attributes are presentation
|
||||
tv.allowsUndo = true
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
@@ -407,6 +442,8 @@ struct ProseTextView: NSViewRepresentable {
|
||||
guard let tv = scroll.documentView as? ProseListTextView else { return }
|
||||
// #77: posture toggle while editing — cheap idempotent set.
|
||||
tv.isContinuousSpellCheckingEnabled = spellChecking
|
||||
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
|
||||
dropBridge.textView = tv // #141: idempotent re-point
|
||||
// #21: the ground follows focus in/out without a remount.
|
||||
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
|
||||
tv.backgroundColor = ground
|
||||
|
||||
@@ -788,3 +788,88 @@ nonisolated extension PostStore {
|
||||
.write(to: file, atomically: true, encoding: .utf8)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - #141 Illustration ingest
|
||||
|
||||
/// #141's refusal reasons — the drop surface shows `localizedDescription`
|
||||
/// as its visible feedback (CardError/WriteError voice).
|
||||
struct IngestError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? {
|
||||
message
|
||||
}
|
||||
|
||||
static func notPublishable(_ name: String) -> IngestError {
|
||||
IngestError(message: "“\(name.prefix(40))” isn’t publishable — PNG, JPEG, GIF, WebP, or SVG.")
|
||||
}
|
||||
|
||||
/// A dropped symlink (e.g. an unzipped archive entry) — copyItem would
|
||||
/// land the LINK itself in assets/; the #34 rail then refuses the send.
|
||||
static func isLink(_ name: String) -> IngestError {
|
||||
IngestError(message: "“\(name.prefix(40))” is a link, not an image file.")
|
||||
}
|
||||
|
||||
/// A Finder folder with an image extension — the extension gate
|
||||
/// alone would copyItem a whole directory into assets/.
|
||||
static func isFolder(_ name: String) -> IngestError {
|
||||
IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
|
||||
}
|
||||
|
||||
/// assets/ exists as a symlink or a file — never write through it
|
||||
/// (research/promote posture: the #34 rail would refuse the send).
|
||||
static func hostileAssets() -> IngestError {
|
||||
IngestError(message: "assets/ isn’t a plain folder in this piece.")
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension PostStore {
|
||||
/// The inserted ref for a landed asset: `` with
|
||||
/// `alt` as the selected placeholder for immediate type-over. The
|
||||
/// destination is parser-clean BY CONSTRUCTION (see `ingestImage`),
|
||||
/// so this exact string rides #34's rail — one helper so the drop
|
||||
/// surface and the tests can never drift.
|
||||
static func illustrationRef(_ destination: String) -> String {
|
||||
")"
|
||||
}
|
||||
|
||||
/// #141: copy a dropped image into the piece's `assets/` — copy,
|
||||
/// never move — and return the ref destination that names it. The
|
||||
/// base name goes through the shared `slug` (whitespace→hyphens and
|
||||
/// more: lowercase, diacritic-fold, 80-char cap) because the #34
|
||||
/// parser never matches space-bearing destinations — the ref and
|
||||
/// the file must agree at ingest. Collisions suffix `-2`/`-3`…
|
||||
/// within `assets/`. Type gate = #34's publish-able set, checked
|
||||
/// BEFORE anything lands.
|
||||
static func ingestImage(from source: URL, pieceFolder: URL) throws -> String {
|
||||
let name = source.lastPathComponent
|
||||
guard Micropub.mimeType(forDestination: name) != nil else {
|
||||
throw IngestError.notPublishable(name)
|
||||
}
|
||||
// The source must be a plain file: copyItem would land a symlink
|
||||
// AS a link (finish-audit 2026-11-02), and the #34 rail then
|
||||
// refuses the whole send — nothing enters assets/ that can't ship.
|
||||
let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard source.isFileURL, let values,
|
||||
values.isDirectory != true, values.isSymbolicLink != true
|
||||
else {
|
||||
throw values?.isSymbolicLink == true ? IngestError.isLink(name) : IngestError.isFolder(name)
|
||||
}
|
||||
let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
|
||||
if FileManager.default.fileExists(atPath: assets.path) {
|
||||
// A symlinked or file-shaped assets/ never takes the write.
|
||||
guard let values = try? assets.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
|
||||
values.isDirectory == true, values.isSymbolicLink != true
|
||||
else {
|
||||
throw IngestError.hostileAssets()
|
||||
}
|
||||
} else {
|
||||
try FileManager.default.createDirectory(at: assets, withIntermediateDirectories: true)
|
||||
}
|
||||
let ext = source.pathExtension.lowercased()
|
||||
let base = slug(from: source.deletingPathExtension().lastPathComponent)
|
||||
let landed = FixCardStore.uniqueFile(assets, base: base, ext: ext)
|
||||
let destination = "assets/\(landed)"
|
||||
try FileManager.default.copyItem(at: source, to: assets.appendingPathComponent(landed))
|
||||
return destination
|
||||
}
|
||||
}
|
||||
@@ -222,6 +222,180 @@ final class ProseListTextView: NSTextView {
|
||||
return len > 0 ? buffer.substring(with: NSRange(location: line.location, length: len)) : ""
|
||||
}
|
||||
|
||||
// MARK: Image ingest (#141)
|
||||
|
||||
/// #141: the piece folder dropped images ingest into — non-nil only
|
||||
/// on a saved post's prose surface (drafts and the external guest
|
||||
/// carry nil; image drags then refuse loudly). Set by ProseTextView
|
||||
/// when the session is known.
|
||||
var ingestFolder: URL?
|
||||
|
||||
/// #141's drop-point solve, pure for tests (#115 field finding: under
|
||||
/// SwiftUI hosting the TextKit2 point→character APIs misanswer — invert
|
||||
/// the one geometry source that DOES answer, `firstRect`, whose y is
|
||||
/// bottom-up screen coords like mouseLocation and DECREASES with index).
|
||||
/// Non-contiguous layout makes OFF-SCREEN chars lie (zero/stale rects,
|
||||
/// dogfood 2026-11-02) — so sample the document, keep only rects inside
|
||||
/// the viewport band (plain NSView geometry — trusted), bracket the drop
|
||||
/// between two in-band samples, binary-search the bracket. Pointer above
|
||||
/// every in-band sample → the first visible char; below all → the last
|
||||
/// in-band sample; no in-band evidence at all (viewless/garbage) → 0.
|
||||
nonisolated static func dropIndex(
|
||||
length: Int,
|
||||
targetY: CGFloat,
|
||||
bandMinY: CGFloat,
|
||||
bandMaxY: CGFloat,
|
||||
sampleCount: Int = 512,
|
||||
rectY: (Int) -> CGFloat,
|
||||
) -> Int {
|
||||
guard length > 0 else { return 0 }
|
||||
var lastAbove: Int?
|
||||
var firstInBand = -1
|
||||
for s in 0 ... sampleCount {
|
||||
let i = min(length - 1, s * length / sampleCount)
|
||||
let y = rectY(i)
|
||||
guard y >= bandMinY, y <= bandMaxY else { continue }
|
||||
if firstInBand < 0 {
|
||||
firstInBand = i
|
||||
}
|
||||
if y >= targetY {
|
||||
lastAbove = i // at-or-above the drop on screen
|
||||
} else if let above = lastAbove, above < i {
|
||||
// Bracket [above, i] straddles the drop; both ends are
|
||||
// in-band (laid out, monotone) so the search probes real rects.
|
||||
var lo = above
|
||||
var hi = i
|
||||
while lo < hi {
|
||||
let mid = (lo + hi) / 2
|
||||
if rectY(mid) >= targetY {
|
||||
lo = mid + 1
|
||||
} else {
|
||||
hi = mid
|
||||
}
|
||||
}
|
||||
return min(lo, length)
|
||||
}
|
||||
}
|
||||
return min(lastAbove ?? max(firstInBand, 0), length)
|
||||
}
|
||||
|
||||
private func rectY(_ i: Int, of length: Int) -> CGFloat {
|
||||
guard window != nil, i >= 0, i < length else { return -1 } // viewless (tests): land at index 0
|
||||
return firstRect(forCharacterRange: NSRange(location: i, length: 1), actualRange: nil).midY
|
||||
}
|
||||
|
||||
/// #141's SwiftUI entry — the window `.dropDestination`'s perform
|
||||
/// routes here after markdown forwarding is ruled out upstream.
|
||||
/// The drop point is read from the live pointer (NSEvent.mouseLocation
|
||||
/// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02).
|
||||
/// Gates: saved piece, every file publishable (#34's mimeType set) —
|
||||
/// refuse loudly otherwise; then copy each file into assets/ and
|
||||
/// insert the refs at the drop point, `alt` selected for type-over.
|
||||
/// One shouldChangeText step = one undo; didChangeText drives the
|
||||
/// delegate (reattribute + session.edit + folds).
|
||||
func ingestDrop(_ urls: [URL]) -> Bool {
|
||||
guard let ingestFolder else {
|
||||
showIngestNotice("Illustrations only land in a saved post's prose editor.")
|
||||
return false
|
||||
}
|
||||
// The publish-able set IS #34's mimeType gate — nothing the rail
|
||||
// can't ship ever enters assets/. A mixed md+image set refuses
|
||||
// here too (only pure-markdown sets are forwarded upstream).
|
||||
guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
|
||||
showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.")
|
||||
return false
|
||||
}
|
||||
let length = (string as NSString).length
|
||||
let mouse = NSEvent.mouseLocation
|
||||
let screenVisible = window?.convertToScreen(convert(visibleRect, to: nil)) ?? .zero
|
||||
var index = Self.dropIndex(
|
||||
length: length,
|
||||
targetY: mouse.y,
|
||||
bandMinY: screenVisible.minY,
|
||||
bandMaxY: screenVisible.maxY,
|
||||
) { i in
|
||||
rectY(i, of: length)
|
||||
}
|
||||
// Never splice inside a word or link — slide to the next gap
|
||||
// (a drop ON an existing ref appends after it, dogfood 2026-11-02).
|
||||
let buffer = string as NSString
|
||||
func isGap(_ c: unichar) -> Bool {
|
||||
guard let scalar = Unicode.Scalar(Int(c)) else { return false }
|
||||
return CharacterSet.whitespacesAndNewlines.contains(scalar)
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
do {
|
||||
// ponytail: multi-image ingest is non-atomic — if file N
|
||||
// fails mid-loop, earlier copies orphan in assets/ (harmless:
|
||||
// never referenced, never shipped; the collision suffix
|
||||
// absorbs them on retry). Pre-flight all sources if it bites.
|
||||
let snippet = try urls.map {
|
||||
try PostStore.illustrationRef(PostStore.ingestImage(from: $0, pieceFolder: ingestFolder))
|
||||
}.joined(separator: " ")
|
||||
guard shouldChangeText(in: NSRange(location: index, length: 0), replacementString: snippet) else { return false }
|
||||
textStorage?.replaceCharacters(in: NSRange(location: index, length: 0), with: snippet)
|
||||
didChangeText()
|
||||
// The first ref's `alt` (offset +2, length 3): one keystroke
|
||||
// replaces it with the real description.
|
||||
let alt = NSRange(location: index + 2, length: 3)
|
||||
setSelectedRange(alt)
|
||||
// Leave the scroll stack as a keystroke would (dogfood
|
||||
// 2026-11-02: without this the inset was out of sync and the
|
||||
// editor froze scrolling until the next keypress).
|
||||
CaretCentering.syncTypewriterInset(textView: self)
|
||||
scrollRangeToVisible(alt)
|
||||
return true
|
||||
} catch {
|
||||
showIngestNotice("Couldn't ingest the image — \(error.localizedDescription)")
|
||||
return false // refused honestly: the drop bounces + the strip names why
|
||||
}
|
||||
}
|
||||
|
||||
/// The transient refusal strip — mono-11 rust on a surface pill
|
||||
/// (focusChip voice), pinned to the scroll view's top-center so it
|
||||
/// never scrolls with the document. Auto-hides ~4 s after the last
|
||||
/// refusal.
|
||||
private var ingestNotice: NSTextField?
|
||||
private var ingestNoticeHide: DispatchWorkItem?
|
||||
|
||||
private func showIngestNotice(_ text: String) {
|
||||
let strip: NSTextField
|
||||
if let ingestNotice {
|
||||
strip = ingestNotice
|
||||
} else {
|
||||
strip = NSTextField(labelWithString: "")
|
||||
strip.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||
strip.textColor = NSColor(DesignTokens.accent)
|
||||
strip.alignment = .center
|
||||
strip.lineBreakMode = .byTruncatingMiddle
|
||||
strip.cell?.truncatesLastVisibleLine = true
|
||||
strip.wantsLayer = true
|
||||
strip.layer?.cornerRadius = DesignTokens.radius
|
||||
strip.layer?.masksToBounds = true
|
||||
strip.layer?.backgroundColor = NSColor(DesignTokens.surface).withAlphaComponent(0.96).cgColor
|
||||
ingestNotice = strip
|
||||
}
|
||||
strip.stringValue = text
|
||||
guard let host = enclosingScrollView ?? window?.contentView else { return }
|
||||
if strip.superview !== host {
|
||||
host.addSubview(strip)
|
||||
}
|
||||
strip.sizeToFit()
|
||||
let width = min(strip.frame.width + 28, host.bounds.width - 24)
|
||||
strip.frame = NSRect(x: (host.bounds.width - width) / 2, y: host.bounds.height - 36, width: width, height: 26)
|
||||
ingestNoticeHide?.cancel()
|
||||
let hide = DispatchWorkItem { [weak strip] in strip?.removeFromSuperview() }
|
||||
ingestNoticeHide = hide
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide)
|
||||
}
|
||||
|
||||
// MARK: Chrome (chevron + ⋯ N)
|
||||
|
||||
/// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted
|
||||
|
||||
@@ -51,10 +51,21 @@ struct WorkspaceView: View {
|
||||
// #91: drag a markdown file onto the window — same guest slot as
|
||||
// File ▸ Open… Non-markdown drops are refused.
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first(where: PostStore.isMarkdown) else { return false }
|
||||
gate.posts.openExternal(url)
|
||||
selection = .posts
|
||||
return true
|
||||
// #141: the window destination is the only one that ever
|
||||
// fires (field-verified 2026-11-02 — nested editor-level
|
||||
// SwiftUI targets are never consulted, and AppKit views
|
||||
// registered for file drags are starved by it).
|
||||
// PURE-markdown sets keep #91's open-as-guest; a mixed
|
||||
// md+image set falls through and ingestDrop refuses it
|
||||
// loudly (images must not vanish silently behind the md).
|
||||
// Nil text view: bounce.
|
||||
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
|
||||
gate.posts.openExternal(url)
|
||||
selection = .posts
|
||||
return true
|
||||
}
|
||||
guard let textView = gate.proseDrop.textView else { return false }
|
||||
return textView.ingestDrop(urls)
|
||||
}
|
||||
// #21: left-edge hover slides rail+library back in as an overlay.
|
||||
// Library only while the window width allows it (#17 verdict stands:
|
||||
|
||||
Reference in new issue
Block a user