Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift

09c5ecd551a0ae8f5078cb88c33958c92428d71f
orgstar/Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift

137 lines · 7154 bytes

  1import AppKit
  2import OrgCore
  3@testable import OrgEditorAppKit
  4import Testing
  5
  6@MainActor
  7struct InlineImagesEditorTests {
  8    static let filler = String(repeating: "word ", count: 40)
  9    static let text = "* Images\n\(filler)[[file:pic.png]] \(filler)\n[[file:pic.png]]\n| a | [[file:pic.png]] | [[./pic.png]] |\n"
 10        + "Described [[file:pic.png][a figure]] here\nMissing [[file:missing.png]] here\n"
 11
 12    /// A folder holding `pic.png`, 100 by 60 points.
 13    static func folder() throws -> URL {
 14        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)")
 15        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 16        let bitmap = try #require(NSBitmapImageRep(
 17            bitmapDataPlanes: nil, pixelsWide: 100, pixelsHigh: 60, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
 18            colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
 19        ))
 20        try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent("pic.png"))
 21        return folder
 22    }
 23
 24    static func harness(_ folder: URL) -> Harness {
 25        let h = Harness(text)
 26        h.editor.baseDirectory = folder
 27        return h
 28    }
 29
 30    static func box(_ h: Harness, at offset: Int) -> InlineImageBox? {
 31        h.textView.textStorage?.attribute(.orgImage, at: offset, effectiveRange: nil) as? InlineImageBox
 32    }
 33
 34    static func fragment(_ h: Harness, at offset: Int) -> NSTextLayoutFragment? {
 35        h.layout()
 36        let manager = h.editor.textLayoutManager
 37        let content = manager.textContentManager!
 38        guard let location = content.location(content.documentRange.location, offsetBy: offset) else { return nil }
 39        return manager.textLayoutFragment(for: location)
 40    }
 41
 42    @Test func anImageInWrappedTextMakesOnlyItsLineTall() throws {
 43        let folder = try Self.folder()
 44        defer { try? FileManager.default.removeItem(at: folder) }
 45        let h = Self.harness(folder)
 46        let ns = Self.text as NSString
 47        let link = ns.range(of: "[[file:pic.png]]")
 48        #expect(Self.box(h, at: link.location) == nil)
 49        h.editor.run("org.toggle-inline-images")
 50
 51        let box = try #require(Self.box(h, at: link.location))
 52        #expect(box.inText && !box.below && box.size == CGSize(width: 100, height: 60))
 53        #expect(Self.box(h, at: link.location + 1) == nil)
 54        let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
 55        let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
 56        #expect(lines.count > 2)
 57        let tall = lines.filter { $0.typographicBounds.height >= 59 }
 58        #expect(tall.count == 1 && NSLocationInRange(link.location - NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0))), tall[0].characterRange))
 59        #expect(lines.filter { $0.typographicBounds.height < 30 }.count == lines.count - 1)
 60        // The image covers the link's place: from its first character, 100 points wide, in the tall line.
 61        let frame = try #require(ImageFragment.frames(of: fragment).first).frame
 62        let bounds = tall[0].typographicBounds
 63        #expect(frame.width == 100 && frame.height == 60)
 64        #expect(frame.minY >= bounds.minY - 1 && frame.maxY <= bounds.maxY + 1)
 65        let start = tall[0].locationForCharacter(at: tall[0].characterRange.location + 0).x
 66        #expect(frame.minX >= bounds.minX + start)
 67        let paragraphStart = NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0)))
 68        let before = tall[0].locationForCharacter(at: link.location - paragraphStart).x
 69        let after = tall[0].locationForCharacter(at: NSMaxRange(link) - paragraphStart).x
 70        #expect(abs(after - before - 100) < 1)
 71    }
 72
 73    @Test func theCaretsLineShowsTheLinkWithTheImageUnderIt() throws {
 74        let folder = try Self.folder()
 75        defer { try? FileManager.default.removeItem(at: folder) }
 76        let h = Self.harness(folder)
 77        let ns = Self.text as NSString
 78        let link = ns.range(of: "[[file:pic.png]]")
 79        h.editor.run("org.toggle-inline-images")
 80        h.caret(at: link.location + 3)
 81        h.editor.revealCaretLine()
 82
 83        let box = try #require(Self.box(h, at: link.location))
 84        #expect(box.inText && box.below)
 85        let storage = try #require(h.textView.textStorage)
 86        #expect(storage.attribute(.kern, at: link.location, effectiveRange: nil) == nil)
 87        let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
 88        let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
 89        #expect(lines.allSatisfy { $0.typographicBounds.height < 30 })
 90        let frame = try #require(ImageFragment.frames(of: fragment).first).frame
 91        #expect(frame.minY >= lines.last!.typographicBounds.maxY)
 92        #expect(fragment.layoutFragmentFrame.height >= frame.maxY)
 93
 94        // Away again, the image is back in the text.
 95        h.caret(at: 0)
 96        h.editor.revealCaretLine()
 97        #expect(Self.box(h, at: link.location)?.below == false)
 98    }
 99
100    @Test func aLinkAloneKeepsItsLineAndATableRowShowsEachImage() throws {
101        let folder = try Self.folder()
102        defer { try? FileManager.default.removeItem(at: folder) }
103        let h = Self.harness(folder)
104        let ns = Self.text as NSString
105        h.editor.run("org.toggle-inline-images")
106
107        let alone = ns.range(of: "\n[[file:pic.png]]\n").location + 1
108        let box = try #require(Self.box(h, at: alone))
109        #expect(!box.inText && !box.below)
110        #expect(Self.box(h, at: alone + 5) === box)
111
112        let row = ns.range(of: "| a |").location
113        let fragment = try #require(Self.fragment(h, at: row) as? ImageFragment)
114        let frames = ImageFragment.frames(of: fragment).map(\.frame)
115        #expect(frames.count == 2 && frames[1].minX >= frames[0].maxX)
116        #expect(fragment.textLineFragments[0].typographicBounds.height >= 59)
117    }
118
119    @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws {
120        let folder = try Self.folder()
121        defer { try? FileManager.default.removeItem(at: folder) }
122        let h = Self.harness(folder)
123        let ns = Self.text as NSString
124        let described = ns.range(of: "[[file:pic.png][a figure]]").location
125        let missing = ns.range(of: "[[file:missing.png]]").location
126        var messages: [String] = []
127        h.editor.onMessage = { messages.append($0) }
128
129        h.editor.run("org.toggle-inline-images")
130        #expect(Self.box(h, at: described) == nil && Self.box(h, at: missing) == nil)
131        h.editor.run("org.toggle-inline-images-linked")
132        #expect(!h.editor.showsImages && Self.box(h, at: ns.range(of: "[[file:pic.png]]").location) == nil)
133        h.editor.run("org.toggle-inline-images-linked")
134        #expect(h.editor.showsImages && Self.box(h, at: described)?.inText == true && Self.box(h, at: missing) == nil)
135        #expect(messages == ["4 images displayed inline", "Inline image display turned off", "5 images displayed inline"])
136    }
137}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form