Tests/OrgAppTests/RichTextExportTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgAppTests/RichTextExportTests.swift history · blame · raw

92 lines · 5552 bytes

6 symbols in this file
 1import AppKit
 2import Foundation
 3import OrgCore
 4import Testing
 5@testable import OrgApp
 6
 7@MainActor
 8struct RichTextExportTests {
 9    static let html = HTMLExport.page("""
10        #+TITLE: Report
11        * Results
12        Some *bold* text.
13        | Name | Count |
14        |------+-------|
15        | a    |     1 |
16        - first
17        - second
18        #+begin_src sh
19        echo hi
20        #+end_src
21        """, fallbackTitle: "t")
22
23    @Test func wordAndRTFReadBackWithTheText() throws {
24        let text = try RichTextExport.attributed(html: Self.html, directory: nil)
25        for data in [try RichTextExport.docx(text), try RichTextExport.rtf(text)] {
26            let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
27            #expect(back.contains("Report") && back.contains("bold") && back.contains("Count") && back.contains("second") && back.contains("echo hi"), "\(back)")
28        }
29        // Word gets a real table, which the system's own writer leaves out.
30        let xml = String(decoding: try RichTextExport.docx(text), as: UTF8.self)
31        #expect(xml.contains("<w:tbl>") && xml.components(separatedBy: "<w:tc>").count - 1 == 4)
32        // Bold survives.
33        let bold = (text.string as NSString).range(of: "bold")
34        let font = text.attribute(.font, at: bold.location, effectiveRange: nil) as? NSFont
35        #expect(font?.fontDescriptor.symbolicTraits.contains(.bold) == true)
36    }
37
38    /// As iOS writes Word, whose HTML import keeps no tables: the tables from the HTML.
39    @Test func wordTablesFromTheHTML() throws {
40        let (page, tables) = RichTextExport.extractingTables(Self.html)
41        #expect(tables.count == 1 && !page.contains("<table") && page.contains(DocxWriter.marker(0)))
42        #expect(tables[0].components(separatedBy: "<w:tc>").count - 1 == 4)
43        #expect(tables[0].contains("<w:b/></w:rPr><w:t xml:space=\"preserve\">Name</w:t>"))
44        #expect(tables[0].contains("<w:r><w:rPr></w:rPr><w:t xml:space=\"preserve\">1</w:t>"))
45        let data = DocxWriter.data(from: try RichTextExport.attributed(html: page, directory: nil), tables: tables)
46        let xml = String(decoding: data, as: UTF8.self)
47        #expect(xml.contains("<w:tbl>") && !xml.contains("\u{E000}"))
48        // A page size of its own, or readers choose a narrow one.
49        #expect(xml.contains("<w:pgSz w:w="))
50        let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
51        #expect(back.contains("Report") && back.contains("Count") && back.contains("second"), "\(back)")
52        #expect(RichTextExport.decode("a &amp;lt; &#233;&#x41; &quot;") == "a &lt; éA \"")
53    }
54
55    /// Headings get Word's heading styles, so its navigation pane and contents fields see them,
56    /// and image links come through as pictures.
57    @Test func wordHeadingStylesAndImages() throws {
58        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-docx-\(UUID().uuidString)")
59        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
60        defer { try? FileManager.default.removeItem(at: folder) }
61        let rep = try #require(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 40, pixelsHigh: 20, bitsPerSample: 8, samplesPerPixel: 4,
62                                                hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
63        try #require(rep.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent("red.png"))
64        let html = HTMLExport.page("#+TITLE: Report\n* Results\nText.\n** Detail\n[[file:red.png]]\n", fallbackTitle: "t")
65        let data = try RichTextExport.docx(html: html, directory: folder)
66        let xml = String(decoding: data, as: UTF8.self)
67        #expect(xml.contains("word/styles.xml") && xml.contains("w:styleId=\"Heading1\"") && xml.contains("<w:name w:val=\"heading 1\"/>"))
68        #expect(xml.contains("<w:pStyle w:val=\"Title\"/>"))
69        #expect(xml.contains("<w:pStyle w:val=\"Heading1\"/>") && xml.contains("<w:pStyle w:val=\"Heading2\"/>"))
70        #expect(!xml.contains("\u{E002}") && !xml.contains("\u{E004}"))
71        #expect(xml.contains("word/media/image1.png") && xml.contains("<w:drawing>") && xml.contains("r:embed=\"img1\""))
72        // 40 by 20 pixels at 96 to the inch.
73        #expect(xml.contains("cx=\"381000\" cy=\"190500\""))
74        let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
75        #expect(back.contains("Results") && back.contains("Detail") && back.contains("Text."))
76    }
77
78    @Test func wordPagesAreLetterOrA4() {
79        #expect(PDFExport.usesLetter("US") && !PDFExport.usesLetter("DE") && !PDFExport.usesLetter(nil))
80        #expect(DocxWriter.section(letter: true).contains("<w:pgSz w:w=\"12240\" w:h=\"15840\"/>"))
81        #expect(DocxWriter.section(letter: false).contains("<w:pgSz w:w=\"11906\" w:h=\"16838\"/>"))
82    }
83
84    @Test func plainTextAndDarkSystemsStayReadable() throws {
85        let text = try RichTextExport.attributed(html: Self.html, directory: nil)
86        let plain = RichTextExport.plain(text)
87        #expect(plain.hasPrefix("Report") && plain.contains("Some bold text.") && plain.hasSuffix("echo hi\n"))
88        // The colors are the light ones whatever the appearance.
89        let color = text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
90        #expect((color?.usingColorSpace(.sRGB)?.brightnessComponent ?? 0) < 0.5)
91    }
92}