oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2
3/// Base: the person's own message as the chat's Markdown tree, in the web's
4/// little subset (richText and personText in ask_cards.go, rich and
5/// strictEmphasis in ask.js), not CommonMark: runs of "- " or "* " lines
6/// are a bulleted list, runs of "1. " or "1) " lines (1 to 3 digits) a
7/// numbered one from its first number, and every other line is text with
8/// its newlines (the one next to a list goes). In text and list items a
9/// Markdown link or bare URL is a link only to an http(s) address, and
10/// between links **x** is bold and *x* or _x_ italic, only at word
11/// boundaries. Nothing else is Markdown: headings, quotes, rules, escapes,
12/// entities and indented code are text as typed. The samples in
13/// internal/web/testdata/person.json check the three agree.
14enum PersonMarkdown {
15 /// `links: false` draws every address as text (LookupMarkdown).
16 static func parse(_ text: String, links: Bool = true) -> [ChatMarkdownNode] {
17 var builder = Builder(links: links)
18 let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
19 .replacingOccurrences(of: "\0", with: "").components(separatedBy: "\n")
20 var out: [ChatMarkdownNode] = []
21 var i = 0
22 while i < lines.count {
23 guard let first = listLine(lines[i]) else {
24 var j = i + 1
25 while j < lines.count, listLine(lines[j]) == nil { j += 1 }
26 let inline = builder.inline(lines[i..<j].joined(separator: "\n"))
27 if !inline.isEmpty { out.append(builder.node("paragraph", children: inline)) }
28 i = j
29 continue
30 }
31 var items: [ChatMarkdownNode] = []
32 while i < lines.count, let line = listLine(lines[i]), line.ordered == first.ordered {
33 items.append(builder.node("item", children: builder.inline(line.item)))
34 i += 1
35 }
36 var list = builder.node(first.ordered ? "ordered" : "unordered", children: items)
37 if first.ordered, first.n != 1 { list.start = first.n }
38 out.append(list)
39 }
40 return out
41 }
42
43 /// Whether a tree is only words: the message is then drawn exactly as
44 /// written.
45 static func isPlain(_ nodes: [ChatMarkdownNode]) -> Bool {
46 nodes.allSatisfy { $0.kind == "paragraph" && $0.children.allSatisfy { $0.kind == "text" } }
47 }
48
49 private static let number = try! NSRegularExpression(pattern: #"^([0-9]{1,3})[.)] "#)
50
51 /// A line's list (numbered or not, its number) and the item after the
52 /// marker, which is never empty.
53 static func listLine(_ line: String) -> (ordered: Bool, n: Int, item: String)? {
54 let u = Array(line.utf8)
55 if u.count > 2, u[0] == UInt8(ascii: "-") || u[0] == UInt8(ascii: "*"), u[1] == UInt8(ascii: " ") {
56 return (false, 0, String(decoding: u[2...], as: UTF8.self))
57 }
58 if let m = number.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)),
59 let whole = Range(m.range, in: line), let digits = Range(m.range(at: 1), in: line), whole.upperBound < line.endIndex {
60 return (true, Int(line[digits]) ?? 1, String(line[whole.upperBound...]))
61 }
62 return nil
63 }
64
65 private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#)
66 /// A lookup's answer's whitespace, spelled out as Go and ask.js spell
67 /// it (lookupSpace in ask_cards.go).
68 static let lookupSpace = #"\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"#
69 /// link with lookupSpace for its whitespace (plainLinkRE in ask_cards.go).
70 private static let plainLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()"# + lookupSpace + #"]{1,1000})\)|https?://[^"# + lookupSpace + #"<>()\[\]"']+"#)
71
72 private struct Builder {
73 let links: Bool
74 var offset = 0
75 /// Every node its own offset: the rows are told apart by it.
76 mutating func node(_ kind: String, text: String? = nil, target: String? = nil, children: [ChatMarkdownNode] = []) -> ChatMarkdownNode {
77 offset += 1
78 return ChatMarkdownNode(sourceOffset: offset, kind: kind, text: text, target: target, children: children)
79 }
80
81 mutating func inline(_ text: String) -> [ChatMarkdownNode] {
82 var out: [ChatMarkdownNode] = []
83 let ns = text as NSString
84 var last = 0
85 for m in (links ? PersonMarkdown.link : PersonMarkdown.plainLink).matches(in: text, range: NSRange(location: 0, length: ns.length)) {
86 var end = NSMaxRange(m.range), label: String, target: String
87 if m.range(at: 1).location != NSNotFound {
88 label = ns.substring(with: m.range(at: 1)); target = ns.substring(with: m.range(at: 2))
89 } else {
90 var bare = ns.substring(with: m.range)
91 while let c = bare.last, ".,;:!?".contains(c) { bare.removeLast() }
92 target = bare; label = bare; end = m.range.location + (bare as NSString).length
93 }
94 guard links else {
95 // An address is text, whatever it is, untouched by
96 // emphasis: no URL check decides how it is drawn.
97 out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
98 out.append(node("text", text: ns.substring(with: NSRange(location: m.range.location, length: end - m.range.location))))
99 last = end
100 continue
101 }
102 guard ChatMarkdown.allowsLink(target) else { continue }
103 out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
104 out.append(node("link", target: target, children: [node("text", text: label)]))
105 last = end
106 }
107 out += emphasis(ns.substring(from: last))
108 return out
109 }
110
111 /// strictEmphasis in ask_cards.go, over Unicode scalars (a scalar
112 /// beyond ASCII is a word's, as any byte of one is there).
113 mutating func emphasis(_ text: String) -> [ChatMarkdownNode] {
114 let s = Array(text.unicodeScalars)
115 var out: [ChatMarkdownNode] = []
116 func str(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(s[r])) }
117 func word(_ c: Unicode.Scalar) -> Bool { c.value >= 0x80 || c == "_" || ("0"..."9").contains(c) || ("a"..."z").contains(c) || ("A"..."Z").contains(c) }
118 func run(_ at: Int) -> Int { var n = 1; while at + n < s.count, s[at + n] == s[at] { n += 1 }; return n }
119 func emphasized(_ r: Range<Int>) -> Bool {
120 !r.isEmpty && !s[r].contains("\n") && s[r.lowerBound] != " " && s[r.lowerBound] != "\t" && s[r.upperBound - 1] != " " && s[r.upperBound - 1] != "\t"
121 }
122 var last = 0, i = 0
123 while i < s.count {
124 let c = s[i]
125 guard c == "*" || c == "_" else { i += 1; continue }
126 let n = run(i)
127 if i == 0 || !word(s[i - 1]), n == 1 || (n == 2 && c == "*"), let j = s[(i + n)...].firstIndex(of: c) {
128 let end = j + run(j)
129 if end - j == n, emphasized((i + n)..<j), end == s.count || !word(s[end]) {
130 if i > last { out.append(node("text", text: str(last..<i))) }
131 out.append(node(n == 2 ? "strong" : "emphasis", children: [node("text", text: str((i + n)..<j))]))
132 i = end; last = end
133 continue
134 }
135 }
136 i += n
137 }
138 if s.count > last { out.append(node("text", text: str(last..<s.count))) }
139 return out
140 }
141 }
142}
143
144/// Base: a lookup's answer as the chat's Markdown tree: PersonMarkdown's
145/// subset with no links at all (lookupMarkdown in ask_cards.go and
146/// ask.js). A Markdown link shows as its words; a bare URL or an autolink
147/// stays as text. The only links under a reply are its sources.
148enum LookupMarkdown {
149 private static let markdownLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()"# + PersonMarkdown.lookupSpace + #"]{1,1000})\)"#)
150
151 static func parse(_ text: String) -> [ChatMarkdownNode] {
152 let t = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
153 .replacingOccurrences(of: "\0", with: "")
154 let words = markdownLink.stringByReplacingMatches(in: t, range: NSRange(t.startIndex..., in: t), withTemplate: "$1")
155 return PersonMarkdown.parse(words, links: false)
156 }
157}
158