Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / NewsletterDocument.swift
| 1 | import CCMark |
| 2 | import Foundation |
| 3 | |
| 4 | @MainActor |
| 5 | enum NewsletterDocument { |
| 6 | private static let registered: Void = { cmark_gfm_core_extensions_ensure_registered() }() |
| 7 | |
| 8 | static func localCopy(of newsletter: WorkspaceRecord) -> WorkspaceRecord { |
| 9 | var draft = WorkspaceRecord.new("newsletter", projectID: newsletter.projectID) |
| 10 | let suffix = " (copy)" |
| 11 | var remaining = 300 - suffix.utf16.count |
| 12 | let title = newsletter.title.prefix { character in |
| 13 | remaining -= String(character).utf16.count |
| 14 | return remaining >= 0 |
| 15 | } |
| 16 | draft["title"] = String(title) + suffix |
| 17 | for key in ["subtitle", "body", "audience", "sendEmail", "coverImage"] { |
| 18 | if let value = newsletter.fields[key] { draft.fields[key] = value } |
| 19 | } |
| 20 | return draft |
| 21 | } |
| 22 | |
| 23 | static func importMarkdown(_ source: String, filename: String) -> (title: String, body: String) { |
| 24 | let normalized = source.replacingOccurrences(of: "\r\n", with: "\n") |
| 25 | let clean = normalized.hasPrefix("\u{feff}") ? String(normalized.dropFirst()) : normalized |
| 26 | let lines = clean.split(separator: "\n", maxSplits: 1, omittingEmptySubsequences: false) |
| 27 | if let first = lines.first, first.hasPrefix("# "), !first.dropFirst(2).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { |
| 28 | let title = first.dropFirst(2).trimmingCharacters(in: .whitespacesAndNewlines) |
| 29 | let body = lines.count == 2 ? lines[1].drop(while: \.isNewline) : "" |
| 30 | return (title, String(body)) |
| 31 | } |
| 32 | return (filename, clean) |
| 33 | } |
| 34 | |
| 35 | static func parse(_ markdown: String) throws -> [String: Any] { |
| 36 | guard markdown.utf16.count <= 200_000, !markdown.contains("\0"), let parser = cmark_parser_new(0) else { |
| 37 | throw WorkspaceError("Use Markdown with up to 200,000 characters.") |
| 38 | } |
| 39 | _ = registered |
| 40 | defer { cmark_parser_free(parser) } |
| 41 | if let extensionPointer = cmark_find_syntax_extension("strikethrough") { |
| 42 | _ = cmark_parser_attach_syntax_extension(parser, extensionPointer) |
| 43 | } |
| 44 | markdown.withCString { cmark_parser_feed(parser, $0, markdown.utf8.count) } |
| 45 | guard let root = cmark_parser_finish(parser) else { throw WorkspaceError("This Markdown could not be parsed.") } |
| 46 | defer { cmark_node_free(root) } |
| 47 | return ["type": "doc", "attrs": ["schemaVersion": "v1"], "content": try children(root).map { try block($0, depth: 1) }] |
| 48 | } |
| 49 | |
| 50 | static func withLeadingCover(_ document: [String: Any], url: String, title: String) -> [String: Any] { |
| 51 | var updated = document |
| 52 | var content = document["content"] as? [[String: Any]] ?? [] |
| 53 | if content.first?["type"] as? String == "captionedImage", |
| 54 | let first = (content.first?["content"] as? [[String: Any]])?.first, |
| 55 | let attrs = first["attrs"] as? [String: Any], attrs["src"] as? String == url { return document } |
| 56 | content.insert(imageBlock(url, alt: "Cover for " + title), at: 0) |
| 57 | updated["content"] = content |
| 58 | return updated |
| 59 | } |
| 60 | |
| 61 | private static func imageBlock(_ source: String, alt: String) -> [String: Any] { |
| 62 | ["type": "captionedImage", "content": [ |
| 63 | ["type": "image2", "attrs": ["src": source, "alt": alt.isEmpty ? NSNull() : alt as Any]] |
| 64 | ]] |
| 65 | } |
| 66 | |
| 67 | private static func children(_ node: OpaquePointer) -> [OpaquePointer] { |
| 68 | var results: [OpaquePointer] = [] |
| 69 | var next = cmark_node_first_child(node) |
| 70 | while let child = next { |
| 71 | results.append(child) |
| 72 | next = cmark_node_next(child) |
| 73 | } |
| 74 | return results |
| 75 | } |
| 76 | |
| 77 | private static func type(_ node: OpaquePointer) -> String { |
| 78 | cmark_node_get_type_string(node).map { String(cString: $0) } ?? "" |
| 79 | } |
| 80 | |
| 81 | private static func literal(_ node: OpaquePointer) -> String { |
| 82 | cmark_node_get_literal(node).map { String(cString: $0) } ?? "" |
| 83 | } |
| 84 | |
| 85 | private static func link(_ node: OpaquePointer) -> String? { |
| 86 | guard let pointer = cmark_node_get_url(node), let url = URL(string: String(cString: pointer)), |
| 87 | ["https", "mailto"].contains(url.scheme ?? ""), url.user == nil, url.password == nil, |
| 88 | url.scheme != "https" || url.host != nil else { return nil } |
| 89 | return url.absoluteString |
| 90 | } |
| 91 | |
| 92 | private static func block(_ node: OpaquePointer, depth: Int) throws -> [String: Any] { |
| 93 | guard depth <= 32 else { throw WorkspaceError("Simplify the newsletter’s nested Markdown.") } |
| 94 | let kind = type(node) |
| 95 | if kind == "code_block" { |
| 96 | let info = cmark_node_get_fence_info(node).map { String(cString: $0) } ?? "" |
| 97 | let language: Any = info.split(whereSeparator: \.isWhitespace).first.map { String($0.prefix(50)) } as Any? ?? NSNull() |
| 98 | let text = literal(node) |
| 99 | var block: [String: Any] = ["type": "code_block", "attrs": ["language": language]] |
| 100 | if !text.isEmpty { block["content"] = [["type": "text", "text": text]] } |
| 101 | return block |
| 102 | } |
| 103 | if kind == "thematic_break" { return ["type": "horizontal_rule"] } |
| 104 | if kind == "html_block" { return ["type": "paragraph", "content": [["type": "text", "text": literal(node).trimmingCharacters(in: .newlines)]]] } |
| 105 | let descendants = children(node) |
| 106 | if kind == "paragraph" || kind == "heading" { |
| 107 | if descendants.count == 1, let image = descendants.first, type(image) == "image", let src = link(image) { |
| 108 | let alt = try inline(children(image), marks: [], depth: depth + 1).compactMap { $0["text"] as? String }.joined() |
| 109 | return imageBlock(src, alt: alt) |
| 110 | } |
| 111 | var block: [String: Any] = ["type": kind, "content": try inline(descendants, marks: [], depth: depth + 1)] |
| 112 | if kind == "heading" { block["attrs"] = ["level": Int(cmark_node_get_heading_level(node))] } |
| 113 | return block |
| 114 | } |
| 115 | let name: String |
| 116 | var attributes: [String: Int]? |
| 117 | switch kind { |
| 118 | case "block_quote": name = "blockquote" |
| 119 | case "item": name = "listItem" |
| 120 | case "list": |
| 121 | if cmark_node_get_list_type(node) == 2 { |
| 122 | name = "orderedList" |
| 123 | let start = Int(cmark_node_get_list_start(node)) |
| 124 | attributes = ["start": start, "order": start] |
| 125 | } else { name = "bulletList" } |
| 126 | default: throw WorkspaceError("A Markdown block could not be converted. Check the newsletter source.") |
| 127 | } |
| 128 | var block: [String: Any] = ["type": name, "content": try descendants.map { try self.block($0, depth: depth + 1) }] |
| 129 | if let attributes { block["attrs"] = attributes } |
| 130 | return block |
| 131 | } |
| 132 | |
| 133 | private static func inline(_ nodes: [OpaquePointer], marks: [[String: Any]], depth: Int) throws -> [[String: Any]] { |
| 134 | guard depth <= 32 else { throw WorkspaceError("Simplify the newsletter’s nested formatting.") } |
| 135 | var result: [[String: Any]] = [] |
| 136 | for node in nodes { |
| 137 | let kind = type(node) |
| 138 | switch kind { |
| 139 | case "text", "html_inline", "code", "softbreak", "image": |
| 140 | let value: String |
| 141 | var formatting = marks |
| 142 | if kind == "softbreak" { value = " " } |
| 143 | else if kind == "image" { |
| 144 | let alt = try inline(children(node), marks: [], depth: depth + 1).compactMap { $0["text"] as? String }.joined() |
| 145 | value = alt.isEmpty ? "Image" : alt |
| 146 | if let url = link(node) { formatting.append(["type": "link", "attrs": ["href": url]]) } |
| 147 | } else { |
| 148 | value = literal(node) |
| 149 | if kind == "code" { formatting.append(["type": "code"]) } |
| 150 | } |
| 151 | if !value.isEmpty { |
| 152 | var text: [String: Any] = ["type": "text", "text": value] |
| 153 | if !formatting.isEmpty { text["marks"] = formatting } |
| 154 | result.append(text) |
| 155 | } |
| 156 | case "linebreak": result.append(["type": "hard_break"]) |
| 157 | case "strong", "emph", "strikethrough", "link": |
| 158 | var next = marks |
| 159 | if kind == "link" { |
| 160 | if let url = link(node) { next.append(["type": "link", "attrs": ["href": url]]) } |
| 161 | } else { |
| 162 | next.append(["type": kind == "emph" ? "em" : kind]) |
| 163 | } |
| 164 | result += try inline(children(node), marks: next, depth: depth + 1) |
| 165 | default: throw WorkspaceError("A Markdown formatting element could not be converted.") |
| 166 | } |
| 167 | } |
| 168 | return result |
| 169 | } |
| 170 | |
| 171 | static func canonical(_ value: Any) throws -> String { |
| 172 | if let object = value as? [String: Any] { |
| 173 | return "{" + (try object.keys.sorted().map { key in try canonical(key) + ":" + canonical(object[key] ?? NSNull()) }).joined(separator: ",") + "}" |
| 174 | } |
| 175 | if let array = value as? [Any] { return "[" + (try array.map(canonical)).joined(separator: ",") + "]" } |
| 176 | return String(decoding: try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed, .withoutEscapingSlashes]), as: UTF8.self) |
| 177 | } |
| 178 | |
| 179 | static func html(_ document: [String: Any], title: String, subtitle: String, includeHeading: Bool = true) -> String { |
| 180 | let introduction = includeHeading ? "<h1>" + escape(title) + "</h1>" + (subtitle.isEmpty ? "" : "<p><em>" + escape(subtitle) + "</em></p>") : "" |
| 181 | return "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>" + escape(title) |
| 182 | + "</title></head><body>" + introduction + render(document) + "</body></html>" |
| 183 | } |
| 184 | |
| 185 | private static func render(_ node: [String: Any]) -> String { |
| 186 | let kind = node["type"] as? String ?? "" |
| 187 | let attrs = node["attrs"] as? [String: Any] ?? [:] |
| 188 | if kind == "text" { |
| 189 | var text = escape(node["text"] as? String ?? "") |
| 190 | for mark in node["marks"] as? [[String: Any]] ?? [] { |
| 191 | let kind = mark["type"] as? String ?? "" |
| 192 | if kind == "link", let address = (mark["attrs"] as? [String: String])?["href"] { |
| 193 | text = "<a href=\"" + escape(address) + "\">" + text + "</a>" |
| 194 | } else if let tag = ["strong": "strong", "em": "em", "code": "code", "strikethrough": "s"][kind] { |
| 195 | text = "<" + tag + ">" + text + "</" + tag + ">" |
| 196 | } |
| 197 | } |
| 198 | return text |
| 199 | } |
| 200 | let body = (node["content"] as? [[String: Any]] ?? []).map(render).joined() |
| 201 | if kind == "hard_break" { return "<br>" } |
| 202 | if kind == "horizontal_rule" { return "<hr>" } |
| 203 | if kind == "code_block" { |
| 204 | return "<figure><figcaption>" + escape(attrs["language"] as? String ?? "Code") + "</figcaption><pre><code>" + body + "</code></pre></figure>" |
| 205 | } |
| 206 | if kind == "image2", let source = attrs["src"] as? String { |
| 207 | return "<p><a href=\"" + escape(source) + "\">Image: " + escape(attrs["alt"] as? String ?? source) + "</a></p>" |
| 208 | } |
| 209 | let level = min(6, max(1, attrs["level"] as? Int ?? 2)) |
| 210 | guard let tag = ["doc": "article", "paragraph": "p", "heading": "h\(level)", "blockquote": "blockquote", |
| 211 | "bulletList": "ul", "orderedList": "ol", "listItem": "li", "captionedImage": "figure"][kind] else { return body } |
| 212 | let attributes = tag == "ol" && (attrs["start"] as? Int ?? 1) != 1 ? " start=\"\(attrs["start"] as? Int ?? 1)\"" : "" |
| 213 | return "<" + tag + attributes + ">" + body + "</" + tag + ">" |
| 214 | } |
| 215 | |
| 216 | private static func escape(_ value: String) -> String { |
| 217 | value.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") |
| 218 | .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) |
| 219 | .replacingOccurrences(of: "'", with: "'") |
| 220 | } |
| 221 | } |