Sources/OrgApp/RichTextExport.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgApp/RichTextExport.swift history · blame · raw

83 lines · 3378 bytes

 1import Foundation
 2#if os(macOS)
 3import AppKit
 4#else
 5import UIKit
 6#endif
 7
 8/// Word, RTF and plain text from the HTML export, through the system's HTML import, and the
 9/// same for the clipboard.
10@MainActor
11public enum RichTextExport {
12    public struct Failure: Error, CustomStringConvertible {
13        public let description: String
14    }
15
16    /// The HTML export as styled text: light colors, and fonts other apps have.
17    public static func attributed(html: String, directory: URL?) throws -> NSAttributedString {
18        // The dark rules would turn the text white wherever the system is dark.
19        let light = html.components(separatedBy: "\n").filter { !$0.contains("prefers-color-scheme: dark") }.joined(separator: "\n")
20        let page = light.replacingOccurrences(of: "</head>", with: """
21            <style>
22            body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
23            code, pre { font-family: Menlo, Consolas, "Courier New", monospace; }
24            </style>
25            </head>
26            """)
27        var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
28            .documentType: NSAttributedString.DocumentType.html,
29            .characterEncoding: String.Encoding.utf8.rawValue,
30        ]
31        #if os(macOS)
32        if let directory { options[.baseURL] = directory }
33        #endif
34        do {
35            return try NSAttributedString(data: Data(page.utf8), options: options, documentAttributes: nil)
36        } catch {
37            throw Failure(description: "The text couldn't be converted: \(error.localizedDescription)")
38        }
39    }
40
41    public static func rtf(_ text: NSAttributedString) throws -> Data {
42        try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])
43    }
44
45    #if os(macOS)
46    /// Word's `.docx`, tables included.
47    public static func docx(_ text: NSAttributedString) throws -> Data {
48        DocxWriter.data(from: text)
49    }
50    #endif
51
52    /// The HTML export as RTF.
53    public static func rtf(html: String, directory: URL?) throws -> Data {
54        try rtf(attributed(html: html, directory: directory))
55    }
56
57    /// The HTML export as plain text.
58    public static func plain(html: String, directory: URL?) throws -> String {
59        plain(try attributed(html: html, directory: directory))
60    }
61
62    /// The text without its styles, ending in one newline.
63    public static func plain(_ text: NSAttributedString) -> String {
64        text.string.replacingOccurrences(of: "\u{2028}", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + "\n"
65    }
66
67    /// The export on the clipboard as HTML, RTF and plain text, for pasting formatted.
68    public static func copy(html: String, directory: URL?) throws {
69        let text = try attributed(html: html, directory: directory)
70        let rtf = try rtf(text)
71        #if os(macOS)
72        let pasteboard = NSPasteboard.general
73        pasteboard.clearContents()
74        pasteboard.setString(html, forType: .html)
75        pasteboard.setData(rtf, forType: .rtf)
76        pasteboard.setString(plain(text), forType: .string)
77        #else
78        UIPasteboard.general.setItems([[
79            "public.html": html, "public.rtf": rtf, "public.utf8-plain-text": plain(text),
80        ]])
81        #endif
82    }
83}