// // 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/.) 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 /// The smallest NSDraggingInfo the drag overrides read: only the /// pasteboard matters (the stock text drop also wants a destination view, /// which the hosted text view supplies itself). @MainActor final class DragInfoStub: NSObject, NSDraggingInfo { let draggingPasteboard: NSPasteboard init(_ pb: NSPasteboard) { draggingPasteboard = pb } var draggingDestinationWindow: NSWindow? { nil } var draggingSourceOperationMask: NSDragOperation { [.copy] } var draggingLocation: NSPoint { .zero } var draggedImageLocation: NSPoint { .zero } var draggedImage: NSImage? { nil } var draggingSource: Any? { nil } var draggingSequenceNumber: Int { 0 } func slideDraggedImage(to _: NSPoint) {} override func namesOfPromisedFilesDropped(atDestination _: URL) -> [String]? { nil } var draggingFormation: NSDraggingFormation = .none var animatesToDestination = false var numberOfValidItemsForDrop = 0 func enumerateDraggingItems( options _: NSDraggingItemEnumerationOptions, for _: NSView?, classes _: [AnyClass], searchOptions _: [NSPasteboard.ReadingOptionKey: Any], using _: @escaping (NSDraggingItem, Int, UnsafeMutablePointer) -> Void, ) {} var springLoadingHighlight: NSSpringLoadingHighlight { .none } func resetSpringLoading() {} } @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 — whichever surface took // the drag routes here: the text view's own handlers over the editor, // the window SwiftUI destination elsewhere) @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: - 27.2 drag routing (a drag goes to the deepest destination: // FileDropTextView owns drops that land on the editor — stock NSTextView // handling would paste the file PATH) /// A Finder-shaped drag pasteboard: `public.file-url` plus the legacy /// filenames type NSTextView registers for. private func finderDragPasteboard(_ urls: [URL]) -> NSPasteboard { let filenames = NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType") let pb = NSPasteboard(name: .drag) pb.declareTypes([.fileURL, filenames], owner: nil) pb.setString(urls[0].absoluteString, forType: .fileURL) pb.setPropertyList(urls.map(\.path), forType: filenames) return pb } /// A live text view in a window (the stock text drop inserts only into /// a hosted view). Caller orders the window out. private func hostedView() -> (tv: ProseListTextView, win: NSWindow) { let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false) let tv = ProseListTextView() tv.string = "Body.\n" win.contentView?.addSubview(tv) win.makeFirstResponder(tv) return (tv, win) } /// A temp markdown file standing in for a dragged guest. private func markdownSource() throws -> URL { let md = FileManager.default.temporaryDirectory.appendingPathComponent("imageingest-\(UUID().uuidString).md") try "# Guest\n".write(to: md, atomically: true, encoding: .utf8) return md } @Test func `a file drag landing on the text view routes, never pastes the path`() throws { let (_, folder) = try ingestHome() let (tv, win) = hostedView() defer { win.orderOut(nil) } tv.ingestFolder = folder tv.onFileDrop = { [weak tv] in tv?.ingestDrop($0) ?? false } // the gate's router in miniature let source = try imageSource("sketch.png") let drag = DragInfoStub(finderDragPasteboard([source])) #expect(tv.draggingEntered(drag) == .copy) #expect(tv.draggingUpdated(drag) == .copy) #expect(tv.performDragOperation(drag)) #expect(tv.string.contains("![alt](assets/sketch.png)")) #expect(!tv.string.contains(source.path), "the stock path paste survived") // Unrouted (no handler mounted): a Finder drag claims nothing and // pastes nothing. let (bare, bareWin) = hostedView() defer { bareWin.orderOut(nil) } let bareDrag = DragInfoStub(finderDragPasteboard([source])) #expect(bare.draggingEntered(bareDrag) == []) #expect(!bare.performDragOperation(bareDrag)) #expect(bare.string == "Body.\n") } @Test func `a text-only drag keeps the stock drop and never reaches the router`() { let (tv, win) = hostedView() defer { win.orderOut(nil) } var routed: [URL]? tv.onFileDrop = { routed = $0; return true } let pb = NSPasteboard(name: .drag) pb.declareTypes([.string], owner: nil) pb.setString("dropped text", forType: .string) #expect(FileDropTextView.classify(pb) == .text) #expect(tv.draggingEntered(DragInfoStub(pb)) == .copy) #expect(tv.performDragOperation(DragInfoStub(pb))) #expect(tv.string.contains("dropped text")) #expect(routed == nil) // URL-less AND text-less (raw image data from Photos/Preview): bounces. let png = NSPasteboard(name: .drag) png.declareTypes([.png], owner: nil) #expect(tv.draggingEntered(DragInfoStub(png)) == []) #expect(!tv.performDragOperation(DragInfoStub(png))) #expect(tv.string.contains("dropped text")) } @Test func `the drag probe follows the pasteboard contents, not its memory`() throws { let (tv, win) = hostedView() defer { win.orderOut(nil) } let source = try imageSource("sketch.png") let pb = finderDragPasteboard([source]) #expect(tv.dropKind(of: pb) == .urls([source])) // Same pasteboard object, new contents (changeCount moved): follows. pb.declareTypes([.string], owner: nil) pb.setString("now text", forType: .string) #expect(tv.dropKind(of: pb) == .text) pb.clearContents() #expect(tv.dropKind(of: pb) == .none) } @Test func `the outline rows bounce a file drag instead of pasting the path`() throws { let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: [.titled], backing: .buffered, defer: false) defer { win.orderOut(nil) } let row = RowTextView() row.string = "- item" win.contentView?.addSubview(row) let drag = try DragInfoStub(finderDragPasteboard([imageSource("sketch.png")])) #expect(row.draggingEntered(drag) == []) #expect(!row.performDragOperation(drag)) #expect(row.string == "- item") } @Test func `a web URL refuses loudly with the type notice and plants nothing`() throws { // A browser image drag reaches the router as an https URL — the // extension looks publishable, but nothing is on disk to copy. The // sink would refuse it too; only the isFileURL gate names the type. let (_, folder) = try ingestHome() let tv = ProseListTextView() tv.string = "Body.\n" tv.ingestFolder = folder let web = try #require(URL(string: "https://example.com/cat.jpg")) #expect(!tv.ingestDrop([web])) #expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true, "notice: \(tv.lastIngestNotice ?? "nil")") #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) } @Test func `a file that vanished after the drag refuses as missing, not as a folder`() throws { let (_, folder) = try ingestHome() let tv = ProseListTextView() tv.string = "Body.\n" tv.ingestFolder = folder let gone = try imageSource("ghost.png") try FileManager.default.removeItem(at: gone) #expect(!tv.ingestDrop([gone])) let notice = try #require(tv.lastIngestNotice) #expect(notice.contains("couldn’t be read"), "notice: \(notice)") #expect(!notice.contains("folder"), "notice: \(notice)") #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) } // MARK: - The one router (AppGateState.routeFileDrop) @Test func `the router opens a pure-markdown set as the guest`() throws { let gate = AppGateState() let md = try markdownSource() defer { try? FileManager.default.removeItem(at: md) } #expect(gate.routeFileDrop([md])) #expect(gate.posts.externalSession != nil) } @Test func `the router refuses everything while a Cold Turkey block holds`() throws { let gate = AppGateState() gate.posts.newPost() gate.posts.draft?.text = "seed words here" gate.startWritingLock(goal: .words(2)) defer { gate.writingLock.feed(text: "seed words here plus two more") gate.writingLock.tick() } let md = try markdownSource() defer { try? FileManager.default.removeItem(at: md) } #expect(gate.writingLock.isLocked) #expect(!gate.routeFileDrop([md])) #expect(gate.posts.externalSession == nil) } @Test func `the router hands non-markdown to the open piece's ingest`() throws { let gate = AppGateState() let (_, folder) = try ingestHome() let source = try imageSource("sketch.png") // No editor mounted: bounce. #expect(!gate.routeFileDrop([source])) let tv = ProseListTextView() tv.string = "Body.\n" tv.ingestFolder = folder gate.proseDrop.textView = tv #expect(gate.routeFileDrop([source])) #expect(tv.string.contains("![alt](assets/sketch.png)")) // A mixed md+image set reaches the ingest's loud refusal, never the guest. let md = try markdownSource() defer { try? FileManager.default.removeItem(at: md) } #expect(try !gate.routeFileDrop([imageSource("second.png"), md])) #expect(tv.lastIngestNotice?.hasPrefix("Drop images") == true) #expect(gate.posts.externalSession == nil) } // 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 router 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(_ charIndex: Int) -> CGFloat { guard charIndex >= 2000, charIndex <= 6000 else { return 0 } return CGFloat(800.0 - 0.1 * Double(charIndex - 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) } }