Files
museion/MuseionTests/ImageIngestTests.swift
T
AlexKucera de1154dacd
CI / ci (push) Canceled after 0s
feat(editor): drop an image into the prose (#141)
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
2026-11-02 17:47:35 +01:00

215 lines
9.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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 ![alt](assets/<slug>.<ext>) 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 == "![alt](assets/my-ink-sketch.png)")
#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("![alt](assets/ink-sketch.png)"), "ref not inserted: \(tv.string)")
let refNSString = tv.string as NSString
let refLoc = refNSString.range(of: "![alt](assets/ink-sketch.png)").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)
}
}