feat(editor): drop an image into the prose (#141)
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
![alt](assets/<slug>.<ext>) 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:
AlexKucera committed 2026-11-02 17:47:35 +01:00
1 parent 695ec27e11
commit de1154dacd
12 files changed
+622 -14

No files matched your search

+174
View File
@@ -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