Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / XIdeaDraft.swift
| 1 | import Foundation |
| 2 | import InkspringSchedule |
| 3 | |
| 4 | /// Keep link placement independent of the writing provider's output. |
| 5 | enum XIdeaDraft { |
| 6 | static let linkWritingInstructions = """ |
| 7 | For each distinct URL in ideaLinks, return a linkCallsToAction array entry with url (the exact supplied URL) and text. |
| 8 | Write one short sentence that tells readers what they will find and what to do, in the author's voice. Use the brief and URL as evidence. Do not make up details about the destination. |
| 9 | For an app homepage, invite people to try or download the app. For an article or guide, invite people to read it and say what they will learn if that is supported by the brief. |
| 10 | Keep the text under 180 characters and exclude URLs and Markdown. Inkspring will attach each exact URL to its reply. |
| 11 | """ |
| 12 | |
| 13 | static func links(in text: String) -> [String] { |
| 14 | matches(in: text).map(\.address) |
| 15 | } |
| 16 | |
| 17 | static func separate(_ opening: String, replies: [String] = [], suppliedLinks: [String], linkCopy: [[String: String]] = [], |
| 18 | long: Bool = false) throws -> (text: String, format: String) { |
| 19 | let found = matches(in: opening) |
| 20 | let clean = removingLinks(from: opening, matches: found) |
| 21 | guard !clean.isEmpty, !clean.contains("\0"), !clean.contains(XThreadText.separator) else { |
| 22 | throw WorkspaceError("The generated X opening needs some text. Try again with a little more detail.") |
| 23 | } |
| 24 | |
| 25 | var writtenReplies: [String] = [] |
| 26 | var bareReplyLinks: [String] = [] |
| 27 | for reply in replies { |
| 28 | let found = matches(in: reply) |
| 29 | let copy = removingLinks(from: reply, matches: found) |
| 30 | let label = copy.lowercased().trimmingCharacters(in: .punctuationCharacters.union(.whitespacesAndNewlines)) |
| 31 | if !found.isEmpty, label.isEmpty || ["link", "links", "source", "sources", "url", "urls"].contains(label) { |
| 32 | bareReplyLinks += found.map(\.address) |
| 33 | } else { |
| 34 | writtenReplies.append(reply) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | var seen = Set(writtenReplies.flatMap { links(in: $0) }) |
| 39 | let missing = (suppliedLinks + found.map(\.address) + bareReplyLinks).filter { seen.insert($0).inserted } |
| 40 | var actions: [String: String] = [:] |
| 41 | for entry in linkCopy { |
| 42 | guard let url = entry["url"], let text = entry["text"], actions[url] == nil else { continue } |
| 43 | let copy = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") |
| 44 | guard copy.contains(where: \.isLetter), !copy.contains("\0"), !copy.contains("<!--"), links(in: copy).isEmpty, |
| 45 | XThreadText.weight(copy + "\n" + url) <= 280 else { continue } |
| 46 | actions[url] = copy |
| 47 | } |
| 48 | var linkReplies: [String] = [] |
| 49 | var previousAction: String? |
| 50 | for address in missing { |
| 51 | let action = actions[address] ?? fallbackAction(for: address) |
| 52 | let section = action + "\n" + address |
| 53 | let addition = previousAction == action ? "\n" + address : "\n\n" + section |
| 54 | if let last = linkReplies.last, XThreadText.weight(last + addition) <= 280 { |
| 55 | linkReplies[linkReplies.count - 1] = last + addition |
| 56 | } else { |
| 57 | linkReplies.append(section) |
| 58 | } |
| 59 | previousAction = action |
| 60 | } |
| 61 | let posts = [clean] + writtenReplies + linkReplies |
| 62 | let format = posts.count == 1 ? "post" : posts.count == 2 ? "followup" : "thread" |
| 63 | let body = posts.joined(separator: XThreadText.separator) |
| 64 | let openingLimit = long ? 25_000 : 280 |
| 65 | let valid = format == "post" ? XThreadText.weight(clean) <= openingLimit |
| 66 | : XThreadText.valid(body, format: format, openingLimit: openingLimit) |
| 67 | guard valid, body.utf16.count <= 40_000 else { |
| 68 | throw WorkspaceError("The generated X post or its replies exceed X’s limits. Try again with a shorter idea or fewer links.") |
| 69 | } |
| 70 | return (body, format) |
| 71 | } |
| 72 | |
| 73 | private static func fallbackAction(for address: String) -> String { |
| 74 | let url = URLComponents(string: address) |
| 75 | if ["inkspring.ai", "www.inkspring.ai"].contains(url?.host?.lowercased() ?? ""), |
| 76 | ["", "/", "/download", "/download/"].contains(url?.path ?? "") { |
| 77 | return "Download Inkspring for Mac and try it for yourself." |
| 78 | } |
| 79 | return "Find more information here:" |
| 80 | } |
| 81 | |
| 82 | private static func removingLinks(from text: String, matches: [(range: NSRange, address: String)]) -> String { |
| 83 | guard !matches.isEmpty else { return text } |
| 84 | let copy = NSMutableString(string: text) |
| 85 | for match in matches.reversed() { copy.deleteCharacters(in: match.range) } |
| 86 | return (copy as String) |
| 87 | .replacingOccurrences(of: #"\[([^\[\]\n]*)\]\(\)"#, with: "$1", options: .regularExpression) |
| 88 | .replacingOccurrences(of: #"\(\)|<>|\[\]|``"#, with: "", options: .regularExpression) |
| 89 | .replacingOccurrences(of: #"[ \t]+([,.;:!?])"#, with: "$1", options: .regularExpression) |
| 90 | .replacingOccurrences(of: #"[ \t]+(?=\n|$)|(?<=\n)[ \t]+"#, with: "", options: .regularExpression) |
| 91 | .replacingOccurrences(of: #"[ \t]{2,}"#, with: " ", options: .regularExpression) |
| 92 | .replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression) |
| 93 | .trimmingCharacters(in: .whitespacesAndNewlines) |
| 94 | } |
| 95 | |
| 96 | private static func matches(in text: String) -> [(range: NSRange, address: String)] { |
| 97 | guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return [] } |
| 98 | return detector.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap { match in |
| 99 | guard let url = match.url, let bounds = Range(match.range, in: text) else { return nil } |
| 100 | var literal = text[bounds] |
| 101 | if url.scheme == "mailto", !literal.lowercased().hasPrefix("mailto:") { return nil } |
| 102 | // The detector includes the closing delimiter of some parenthesized links. |
| 103 | var extraParentheses = literal.reduce(0) { balance, character in |
| 104 | balance + (character == ")" ? 1 : character == "(" ? -1 : 0) |
| 105 | } |
| 106 | while literal.last == ")", extraParentheses > 0 { |
| 107 | literal = literal.dropLast() |
| 108 | extraParentheses -= 1 |
| 109 | } |
| 110 | let explicitScheme = url.scheme.map { literal.lowercased().hasPrefix($0.lowercased() + ":") } ?? false |
| 111 | let address = explicitScheme ? String(literal) : "https://" + String(literal) |
| 112 | return (NSRange(literal.startIndex..<literal.endIndex, in: text), address) |
| 113 | } |
| 114 | } |
| 115 | } |