Sources/OrgApp/RichTextExport.swift

128 lines · 5715 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 Word's `.docx`, tables included.
 53    public static func docx(html: String, directory: URL?) throws -> Data {
 54        #if os(macOS)
 55        return try docx(attributed(html: html, directory: directory))
 56        #else
 57        let (page, tables) = extractingTables(html)
 58        return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables)
 59        #endif
 60    }
 61
 62    /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the
 63    /// tables as Word XML, header cells bold.
 64    static func extractingTables(_ html: String) -> (html: String, tables: [String]) {
 65        var tables: [String] = []
 66        var out = ""
 67        var rest = Substring(html)
 68        while let match = rest.firstMatch(of: #/(?is)<table\b.*?</table>/#) {
 69            out += rest[..<match.range.lowerBound]
 70            var rows: [[String]] = []
 71            for row in match.0.matches(of: #/(?is)<tr\b[^>]*>(.*?)</tr>/#) {
 72                rows.append(row.1.matches(of: #/(?is)<t([hd])\b[^>]*>(.*?)</t[hd]>/#).map { cell in
 73                    let text = decode(String(cell.2).replacing(#/(?s)<[^>]*>/#, with: "")).trimmingCharacters(in: .whitespacesAndNewlines)
 74                    guard !text.isEmpty else { return "" }
 75                    return "<w:p><w:pPr></w:pPr><w:r><w:rPr>\(cell.1.lowercased() == "h" ? "<w:b/>" : "")</w:rPr><w:t xml:space=\"preserve\">\(DocxWriter.escape(text))</w:t></w:r></w:p>"
 76                })
 77            }
 78            out += "<p>\(DocxWriter.marker(tables.count))</p>"
 79            tables.append(DocxWriter.table(rows, columns: rows.map(\.count).max() ?? 1))
 80            rest = rest[match.range.upperBound...]
 81        }
 82        return (out + rest, tables)
 83    }
 84
 85    /// HTML character references.
 86    static func decode(_ s: String) -> String {
 87        var out = s
 88        for (entity, character) in [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&#39;", "'"), ("&nbsp;", "\u{A0}")] {
 89            out = out.replacingOccurrences(of: entity, with: character)
 90        }
 91        out = out.replacing(#/&#(x?)([0-9a-fA-F]+);/#) { m in
 92            UInt32(m.2, radix: m.1.isEmpty ? 10 : 16).flatMap(Unicode.Scalar.init).map { String(Character($0)) } ?? String(m.0)
 93        }
 94        return out.replacingOccurrences(of: "&amp;", with: "&")
 95    }
 96
 97    /// The HTML export as RTF.
 98    public static func rtf(html: String, directory: URL?) throws -> Data {
 99        try rtf(attributed(html: html, directory: directory))
100    }
101
102    /// The HTML export as plain text.
103    public static func plain(html: String, directory: URL?) throws -> String {
104        plain(try attributed(html: html, directory: directory))
105    }
106
107    /// The text without its styles, ending in one newline.
108    public static func plain(_ text: NSAttributedString) -> String {
109        text.string.replacingOccurrences(of: "\u{2028}", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + "\n"
110    }
111
112    /// The export on the clipboard as HTML, RTF and plain text, for pasting formatted.
113    public static func copy(html: String, directory: URL?) throws {
114        let text = try attributed(html: html, directory: directory)
115        let rtf = try rtf(text)
116        #if os(macOS)
117        let pasteboard = NSPasteboard.general
118        pasteboard.clearContents()
119        pasteboard.setString(html, forType: .html)
120        pasteboard.setData(rtf, forType: .rtf)
121        pasteboard.setString(plain(text), forType: .string)
122        #else
123        UIPasteboard.general.setItems([[
124            "public.html": html, "public.rtf": rtf, "public.utf8-plain-text": plain(text),
125        ]])
126        #endif
127    }
128}