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
@@ -37,7 +37,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
|
||||
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
|
||||
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
|
||||
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
|
||||
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107). `ImageIngestTests.swift` (#141, own file, `@Suite` + `@MainActor` — scenario header at file top) pins the ingest write side: a dropped image lands slugged (`My Ink Sketch.png` → `assets/my-ink-sketch.png`), byte-identical, COPY-never-move (the source survives); a same-named second drop collides `-2` and the ref's destination always matches the landed name; `PostStore.illustrationRef` builds the exact `` string and it rides #34's rail (`Micropub.illustrations` parses it with alt + destination — the Send-as-Draft round-trip shape); HEIC/PDF/a Finder folder with an image extension all throw `IngestError` with `assets/` never materialized. The drag layer pins drive `ingestDrop` directly (the SwiftUI drop target's perform entry, no drag session): copies/lands/inserts/alt-selects; HEIC and a nil-folder draft both refuse loudly with nothing planted. **Finish-audit pins (2026-11-02):** a dropped SYMLINK refuses with nothing planted (`isLink` — `copyItem` would land the link itself, empirically verified); a mixed image+markdown set refuses loudly with nothing inserted (the ingest-side gate of the window destination's pure-markdown routing — the SwiftUI closure itself is unpinned, no harness); and the drop-point solve is pinned WITHOUT a window via the extracted pure `dropIndex` (banded synthetic rectY: exact drop-line landing, pointer-above-viewport → first visible char — the flip-verified discriminator against the old zero-trusted fallback, pointer-below → band tail, garbage geometry → 0) — all flip-verified in one batched cycle (each pin failed on its own guard).
|
||||
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused). **#114:** `headingsLadderBody` pin — ladder shape to the `######` floor, bullet remainder re-based, preamble verbatim, mixed-content prose drops.
|
||||
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil).
|
||||
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//
|
||||
// ImageIngestTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #141: illustration ingest — a dropped image lands in the piece's
|
||||
// assets/ under a parser-clean slugged name (collision -2), copied
|
||||
// never moved, and the inserted ref rides #34's rail (parses with
|
||||
// alt + destination). Non-publishable types refuse honestly with
|
||||
// nothing planted.
|
||||
//
|
||||
// ## Scenario: Drop an image, get a publish-able illustration
|
||||
// From #141
|
||||
//
|
||||
// Given a saved post open in the prose editor and a publishable image
|
||||
// file in Finder
|
||||
// When the writer drops it at a point in the prose
|
||||
// Then the file is copied (never moved) into the piece's assets/ under
|
||||
// a slugged name, and  is inserted at the
|
||||
// drop point with alt selected for type-over
|
||||
// And a non-publishable file refuses with nothing copied or inserted
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ImageIngestTests {
|
||||
/// Throwaway Home + a saved post standing in for the open editor
|
||||
/// (PostStoreTests convention).
|
||||
private func ingestHome() throws -> (home: URL, folder: URL) {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("imageingest-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
let post = try PostStore.writeNew(body: "# Ink\n\nBody.", home: home)
|
||||
let folder = try #require(PostStore.folder(of: post.id, home: home))
|
||||
return (home, folder)
|
||||
}
|
||||
|
||||
/// A source image standing in for the Finder drag — minimal bytes;
|
||||
/// the gate is extension-based, matching #34's rail.
|
||||
private func imageSource(_ name: String, bytes: [UInt8] = [0x89, 0x50, 0x4E, 0x47]) throws -> URL {
|
||||
let dir = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
let url = dir.appendingPathComponent(name)
|
||||
try Data(bytes).write(to: url)
|
||||
return url
|
||||
}
|
||||
|
||||
@Test func `dropped image lands slugged, copied never moved, and rides the rail`() throws {
|
||||
let (home, folder) = try ingestHome()
|
||||
let source = try imageSource("My Ink Sketch.png")
|
||||
let bytes = try Data(contentsOf: source)
|
||||
|
||||
let destination = try PostStore.ingestImage(from: source, pieceFolder: folder)
|
||||
|
||||
#expect(destination == "assets/my-ink-sketch.png")
|
||||
#expect(try Data(contentsOf: folder.appendingPathComponent(destination)) == bytes) // landed byte-identical
|
||||
#expect(FileManager.default.fileExists(atPath: source.path)) // copy, never move
|
||||
|
||||
// The inserted ref must ride #34's rail: it parses with the alt
|
||||
// placeholder and the landed destination (slug + collision agree).
|
||||
let ref = PostStore.illustrationRef(destination)
|
||||
#expect(ref == "")
|
||||
#expect(Micropub.illustrations(in: ref) == [Micropub.Illustration(alt: "alt", destination: destination)])
|
||||
}
|
||||
|
||||
@Test func `same-named second drop collides -2 with the ref matching the landed name`() throws {
|
||||
let (_, folder) = try ingestHome()
|
||||
_ = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder)
|
||||
|
||||
let second = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder)
|
||||
|
||||
#expect(second == "assets/sketch-2.png") // -2, not a clobber
|
||||
#expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets/sketch.png").path))
|
||||
#expect(Micropub.illustrations(in: PostStore.illustrationRef(second)).first?.destination == second)
|
||||
}
|
||||
|
||||
@Test func `non-publishable types refuse with nothing planted`() throws {
|
||||
let (_, folder) = try ingestHome()
|
||||
let heic = try imageSource("photo.heic")
|
||||
let pdf = try imageSource("paper.pdf")
|
||||
// A Finder FOLDER with an image extension — the extension gate
|
||||
// alone would copyItem a whole directory into assets/.
|
||||
let folderPng = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true)
|
||||
.appendingPathComponent("trick.png", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folderPng, withIntermediateDirectories: true)
|
||||
|
||||
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: heic, pieceFolder: folder) }
|
||||
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: pdf, pieceFolder: folder) }
|
||||
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: folderPng, pieceFolder: folder) }
|
||||
// Refusal planted nothing — assets/ was never even materialized.
|
||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||
}
|
||||
|
||||
// MARK: - #141 drag-layer entry (ingestDrop — the SwiftUI drop
|
||||
|
||||
// target's perform lands on the text view)
|
||||
|
||||
@Test func `ingestDrop copies lands the ref and selects alt`() throws {
|
||||
let (_, folder) = try ingestHome()
|
||||
let tv = ProseListTextView()
|
||||
tv.string = "Hello paragraph.\n\nSecond paragraph.\n"
|
||||
tv.ingestFolder = folder
|
||||
|
||||
#expect(try tv.ingestDrop([imageSource("ink sketch.png")]))
|
||||
|
||||
let landed = folder.appendingPathComponent("assets").appendingPathComponent("ink-sketch.png")
|
||||
#expect(FileManager.default.fileExists(atPath: landed.path))
|
||||
#expect(tv.string.contains(""), "ref not inserted: \(tv.string)")
|
||||
let refNSString = tv.string as NSString
|
||||
let refLoc = refNSString.range(of: "").location
|
||||
#expect(tv.selectedRange() == NSRange(location: refLoc + 2, length: 3), "alt not selected (sel=\(tv.selectedRange()))")
|
||||
}
|
||||
|
||||
@Test func `ingestDrop refuses loudly and plants nothing`() throws {
|
||||
let (_, folder) = try ingestHome()
|
||||
let tv = ProseListTextView()
|
||||
tv.string = "Body.\n"
|
||||
tv.ingestFolder = folder
|
||||
#expect(try !tv.ingestDrop([imageSource("photo.heic")]))
|
||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||
// A draft (no folder) refuses with the same honesty.
|
||||
let draft = ProseListTextView()
|
||||
draft.ingestFolder = nil
|
||||
#expect(try !draft.ingestDrop([imageSource("x.png")]))
|
||||
}
|
||||
|
||||
// MARK: - #141 finish-audit pins
|
||||
|
||||
@Test func `a dropped symlink refuses with nothing planted`() throws {
|
||||
// copyItem would land the LINK itself (empirically verified,
|
||||
// 2026-11-02) — the #34 rail then refuses the whole send.
|
||||
let (_, folder) = try ingestHome()
|
||||
let target = try imageSource("real image.png")
|
||||
let linkURL = target.deletingLastPathComponent()
|
||||
.appendingPathComponent("linked image.png")
|
||||
try? FileManager.default.removeItem(at: linkURL)
|
||||
try FileManager.default.createSymbolicLink(at: linkURL, withDestinationURL: target)
|
||||
defer { try? FileManager.default.removeItem(at: linkURL) }
|
||||
|
||||
#expect(throws: IngestError.self) {
|
||||
_ = try PostStore.ingestImage(from: linkURL, pieceFolder: folder)
|
||||
}
|
||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||
}
|
||||
|
||||
@Test func `a mixed image and markdown set refuses loudly`() throws {
|
||||
// The window destination forwards only PURE-markdown sets (#91);
|
||||
// a mixed set must reach this refusal, not vanish behind the md.
|
||||
let (_, folder) = try ingestHome()
|
||||
let tv = ProseListTextView()
|
||||
tv.string = "Body.\n"
|
||||
tv.ingestFolder = folder
|
||||
let md = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("mixed-\(UUID().uuidString).md")
|
||||
try Data("# Guest\n".utf8).write(to: md)
|
||||
defer { try? FileManager.default.removeItem(at: md) }
|
||||
|
||||
#expect(try !tv.ingestDrop([imageSource("ink sketch.png"), md]))
|
||||
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
|
||||
#expect(tv.string == "Body.\n", "mixed set must not insert: \(tv.string)")
|
||||
}
|
||||
|
||||
// MARK: - #141 drop-point solve (pure)
|
||||
|
||||
/// Viewport band [200, 800]; characters 2000…6000 laid out with y
|
||||
/// decreasing 800→400; everything off-screen reports 0 (the lie
|
||||
/// non-contiguous layout tells). MidY at i = 800 − 0.1·(i − 2000).
|
||||
private func bandedRectY(_ i: Int) -> CGFloat {
|
||||
guard i >= 2000, i <= 6000 else { return 0 }
|
||||
return CGFloat(800.0 - 0.1 * Double(i - 2000))
|
||||
}
|
||||
|
||||
@Test func `dropIndex lands on the drop line`() {
|
||||
// y crosses 600 between 4000 (== 600, at-or-above) and 4001.
|
||||
let index = ProseListTextView.dropIndex(
|
||||
length: 10000, targetY: 600, bandMinY: 200, bandMaxY: 800,
|
||||
sampleCount: 100, rectY: bandedRectY,
|
||||
)
|
||||
#expect(index == 4001)
|
||||
}
|
||||
|
||||
@Test func `dropIndex above the viewport clamps to the first visible char`() {
|
||||
// Pointer above every in-band sample — the old code trusted a
|
||||
// zero-initialized "above" and landed at the document start.
|
||||
// (sampleCount 100 → samples land on 2000/4000/6000 exactly.)
|
||||
let index = ProseListTextView.dropIndex(
|
||||
length: 10000, targetY: 900, bandMinY: 200, bandMaxY: 800,
|
||||
sampleCount: 100, rectY: bandedRectY,
|
||||
)
|
||||
#expect(index == 2000)
|
||||
}
|
||||
|
||||
@Test func `dropIndex below the viewport clamps into the band tail`() {
|
||||
let index = ProseListTextView.dropIndex(
|
||||
length: 10000, targetY: 100, bandMinY: 200, bandMaxY: 800,
|
||||
sampleCount: 100, rectY: bandedRectY,
|
||||
)
|
||||
#expect(index == 6000)
|
||||
}
|
||||
|
||||
@Test func `dropIndex with no in-band rects falls to the document start`() {
|
||||
// Viewless/garbage geometry (tests, or a hostile layout) — the
|
||||
// honest floor.
|
||||
let index = ProseListTextView.dropIndex(
|
||||
length: 10000, targetY: 500, bandMinY: 200, bandMaxY: 800,
|
||||
) { _ in 0 }
|
||||
#expect(index == 0)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user