Tests/OrgAppTests/PDFExportTests.swift

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

114 lines · 7213 bytes

8 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgMathJax
  4import PDFKit
  5import Testing
  6import WebKit
  7@testable import OrgApp
  8
  9@MainActor
 10struct PDFExportTests {
 11    init() { PDFExport.mathJaxURL = OrgMathJax.script }
 12
 13    /// A long document comes out as several pages with its text, without Emacs.
 14    @Test func paginatesTheHTMLExport() async throws {
 15        let sections = (1...40).map { "* Section \($0)\n" + String(repeating: "Some words in a paragraph. ", count: 30) + "\n" }.joined()
 16        let html = HTMLExport.page("#+TITLE: Long\n" + sections + "#+begin_src sh\necho done\n#+end_src\n", fallbackTitle: "t")
 17        let data = try await PDFExport.pdf(html: html, directory: nil)
 18        let document = try #require(PDFDocument(data: data))
 19        #expect(document.pageCount > 3)
 20        let text = document.string ?? ""
 21        #expect(text.contains("Long") && text.contains("Section 40") && text.contains("echo done"))
 22        let page = try #require(document.page(at: 0)).bounds(for: .mediaBox)
 23        #expect(page.width < page.height)
 24        // Page numbers, centred under the text, as annotations so the export's links stay.
 25        let numbers = (0..<document.pageCount).compactMap { document.page(at: $0)?.annotations.first { $0.type == "FreeText" }?.contents }
 26        #expect(numbers == (1...document.pageCount).map(String.init))
 27    }
 28
 29    @Test func marginsFontAndNoNumbers() async throws {
 30        let html = HTMLExport.page("#+TITLE: Short\nOne paragraph.\n", fallbackTitle: "t")
 31        let data = try await PDFExport.pdf(html: html, directory: nil, options: PDFExport.Options(margin: 100, font: "Georgia", pageNumbers: false))
 32        let document = try #require(PDFDocument(data: data))
 33        #expect(document.page(at: 0)?.annotations.contains { $0.type == "FreeText" } == false)
 34        let css = PDFExport.css(PDFExport.Options(margin: 100, font: "Georgia", pageNumbers: false))
 35        #expect(css.contains("font-family: \"Georgia\""))
 36        #expect(!PDFExport.css(PDFExport.Options()).contains("font-family"))
 37    }
 38
 39    /// In the sandbox WebKit can't read the user's folders, so local images go in the page.
 40    @Test func inlinesLocalImages() throws {
 41        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
 42        try FileManager.default.createDirectory(at: folder.appendingPathComponent("img"), withIntermediateDirectories: true)
 43        defer { try? FileManager.default.removeItem(at: folder) }
 44        try Data([1, 2, 3]).write(to: folder.appendingPathComponent("img/a b.png"))
 45        try Data([4]).write(to: folder.appendingPathComponent("c.svg"))
 46        let absolute = folder.appendingPathComponent("c.svg").path
 47        let html = #"<p><img src="img/a b.png" alt="a"> <img alt="c" src="\#(absolute)"> <img src="https://x.org/r.png"> <img src="gone.png"></p>"#
 48        let inlined = PDFExport.inliningImages(html, directory: folder)
 49        #expect(inlined.contains(#"<img src="data:image/png;base64,AQID" alt="a">"#))
 50        #expect(inlined.contains(#"<img alt="c" src="data:image/svg+xml;base64,BA==">"#))
 51        #expect(inlined.contains(#"<img src="https://x.org/r.png">"#))
 52        #expect(inlined.contains(#"<img src="gone.png">"#))
 53        #expect(PDFExport.inliningImages(#"<img src="img/a b.png">"#, directory: nil) == #"<img src="img/a b.png">"#)
 54    }
 55
 56    /// The images to ask for access to before exporting.
 57    @Test func localImageFiles() {
 58        let html = #"<img src="img/a.png"> <img alt="c" src="/abs/c.svg"> <img src="https://x.org/r.png"> <img src="img/a.png">"#
 59        #expect(PDFExport.imageFiles(html, directory: URL(fileURLWithPath: "/notes")) == ["/notes/img/a.png", "/abs/c.svg"])
 60    }
 61
 62    /// Export to HTML and Open on iOS: a temporary page with its images in it.
 63    @Test func previewHasItsImages() throws {
 64        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
 65        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 66        defer { try? FileManager.default.removeItem(at: folder) }
 67        try Data([1, 2, 3]).write(to: folder.appendingPathComponent("a.png"))
 68        let url = try HTMLPreview.write(#"<p><img src="a.png"></p>"#, directory: folder, name: "notes.html")
 69        defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
 70        #expect(url.lastPathComponent == "notes.html")
 71        #expect(try String(contentsOf: url, encoding: .utf8) == #"<p><img src="data:image/png;base64,AQID"></p>"#)
 72    }
 73
 74    /// The page PDF export renders has MathJax in it and no remote script; saved HTML keeps the CDN.
 75    @Test func bundlesMathJax() async throws {
 76        let html = HTMLExport.page("Math: \\(a^2\\)\n", fallbackTitle: "t")
 77        #expect(html.contains(HTMLExport.mathJaxScript))
 78        let page = try PDFExport.bundlingMathJax(html)
 79        #expect(page.firstMatch(of: /(?i)<script[^>]*\bsrc=/) == nil)
 80        #expect(page.contains("window.MathJax = { tex: "))
 81        #expect(page.contains("<script id=\"MathJax-script\">") && page.contains("VERSION=\"3.2.2\""))
 82        // Typeset before printing: the TeX source is gone from the PDF.
 83        let text = try #require(PDFDocument(data: try await PDFExport.pdf(html: html, directory: nil))?.string)
 84        #expect(text.contains("Math:") && !text.contains("a^2"))
 85        let plain = HTMLExport.page("No math.\n", fallbackTitle: "t")
 86        #expect(try PDFExport.bundlingMathJax(plain) == plain)
 87    }
 88
 89    /// The bundled MathJax typesets in WebKit with every network load blocked.
 90    @Test func typesetsMathOffline() async throws {
 91        let rules = #"[{"trigger": {"url-filter": "://"}, "action": {"type": "block"}}]"#
 92        let store = try #require(WKContentRuleListStore.default())
 93        let list = try #require(try await store.compileContentRuleList(forIdentifier: "orgstar-offline-test", encodedContentRuleList: rules))
 94        defer { store.removeContentRuleList(forIdentifier: "orgstar-offline-test") { _ in } }
 95        let configuration = WKWebViewConfiguration()
 96        configuration.userContentController.add(list)
 97        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 800, height: 600), configuration: configuration)
 98        let html = HTMLExport.page("Math: \\(a^2 + \\frac{1}{2}\\)\n\n\\begin{align}\nx &= 1\n\\end{align}\n\nWater: \\(\\ce{H2O}\\)\n", fallbackTitle: "t")
 99        webView.loadHTMLString(try PDFExport.bundlingMathJax(html), baseURL: nil)
100        var counts: [Int]?
101        for _ in 0..<100 {
102            let result = try await webView.callAsyncJavaScript("""
103                if (!(window.MathJax && MathJax.startup && MathJax.startup.promise)) { return 'waiting'; }
104                await MathJax.startup.promise;
105                return [document.querySelectorAll('mjx-container svg').length, document.querySelectorAll('[data-mjx-error]').length];
106                """, contentWorld: .page)
107            counts = result as? [Int]
108            if counts != nil { break }
109            #expect(result as? String == "waiting")
110            try await Task.sleep(for: .milliseconds(100))
111        }
112        #expect(counts == [3, 0])
113    }
114}