-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathDrafty.swift
1868 lines (1654 loc) · 68.6 KB
/
Drafty.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Drafty.swift
//
// Copyright © 2019-2022 Tinode LLC. All rights reserved.
//
import Foundation
import UIKit
public enum DraftyError: Error {
case illegalArgument(String)
case invalidIndex(String)
}
/// Describes a class which converts nodes of a Drafty formatting tree to string representation.
public protocol DraftyFormatter {
typealias FormattedString = AnyObject
func apply(type: String?, data: [String: JSONValue]?, key: Int?, content: [FormattedString], stack: [String]?) -> FormattedString
func wrapText(_ content: String) -> FormattedString
}
/// Span tree transformer interface.
public protocol DraftyTransformer {
init()
// Called on every node of the span tree.
// Returns a new node that the given node should be replaced with.
func transform(node: Drafty.Span) -> Drafty.Span?
}
/// Class representing formatted text with optional attachments.
open class Drafty: Codable, CustomStringConvertible, Equatable {
public static let kMimeType = "text/x-drafty"
public static let kJSONMimeType = "application/json"
private static let kMaxFormElements = 8
private static let kMaxPreviewDataSize = 64
private static let kMaxPreviewAttachments = 3
// Styles which require no body (but may have a body which will be ignored).
private static let kVoidStyles = ["BR", "EX", "HD"]
// Entity data field names which will be processed.
private static let kKnownDataFelds =
["act", "duration", "height", "incoming", "mime", "name", "premime", "preview", "preref", "ref", "size", "state", "title", "url", "val", "width"]
// Regular expressions for parsing inline formats.
private static let kInlineStyles = try! [
"ST": NSRegularExpression(pattern: #"(?<=^|[\W_])\*([^*]+[^\s*])\*(?=$|[\W_])"#), // bold *bo*
"EM": NSRegularExpression(pattern: #"(?<=^|\W)_([^_]+[^\s_])_(?=$|\W)"#), // italic _it_
"DL": NSRegularExpression(pattern: #"(?<=^|[\W_])~([^~]+[^\s~])~(?=$|[\W_])"#), // strikethough ~st~
"CO": NSRegularExpression(pattern: #"(?<=^|\W)`([^`]+)`(?=$|\W)"#) // code/monospace `mono`
]
private static let kEntities = try! [
EntityProc(name: "LN",
pattern: NSRegularExpression(pattern: #"\b(https?://)?(?:www\.)?(?:[a-z0-9][-a-z0-9]*[a-z0-9]\.){1,5}[a-z]{2,6}(?:[/?#:][-a-z0-9@:%_+.~#?&/=]*)?"#, options: [.caseInsensitive]),
pack: {(text: NSString, m: NSTextCheckingResult) -> [String: JSONValue] in
var data: [String: JSONValue] = [:]
data["url"] = JSONValue.string(m.range(at: 1).location == NSNotFound ? "http://" + text.substring(with: m.range) : text.substring(with: m.range))
return data
}),
EntityProc(name: "MN",
pattern: NSRegularExpression(pattern: #"\B@(\w\w+)"#),
pack: {(text: NSString, m: NSTextCheckingResult) -> [String: JSONValue] in
var data: [String: JSONValue] = [:]
data["val"] = JSONValue.string(text.substring(with: m.range(at: 1)))
return data
}),
EntityProc(name: "HT",
pattern: NSRegularExpression(pattern: #"(?<=[\s,.!]|^)#(\w\w+)"#),
pack: {(text: NSString, m: NSTextCheckingResult) -> [String: JSONValue] in
var data: [String: JSONValue] = [:]
data["val"] = JSONValue.string(text.substring(with: m.range(at: 1)))
return data
})
]
private enum CodingKeys: String, CodingKey {
case txt = "txt"
case fmt = "fmt"
case ent = "ent"
}
// Formatting weights. Used to break ties between formatting spans
// covering the same text range.
private static let kFmtWeights = ["QQ": 1000]
private static let kFmtDefaultWeight = 0
public var txt: String
public var fmt: [Style]?
public var ent: [Entity]?
public var hasRefEntity: Bool {
guard let ent = ent, ent.count > 0 else { return false }
return ent.first(where: { $0.data?["ref"] != nil }) != nil
}
private var length: Int { return txt.count }
/// Initializes empty object
public init() {
txt = ""
}
/// Initializer to comply with Decodable protocol:
/// First tries to decode Drafty from plain text, then
/// from from JSON.
required public init(from decoder: Decoder) throws {
// First try optional decoding of 'txt' from a primitive string.
// Most content is sent as primitive strings.
if let container = try? decoder.singleValueContainer(),
let txt = try? container.decode(String.self) {
self.txt = txt
} else {
// Non-optional decoding as a Drafty object.
let container = try decoder.container(keyedBy: CodingKeys.self)
// Txt is missing for attachments.
do {
txt = try container.decode(String.self, forKey: .txt)
} catch DecodingError.keyNotFound {
txt = ""
}
fmt = try? container.decode([Style].self, forKey: .fmt)
ent = try? container.decode([Entity].self, forKey: .ent)
}
}
/// encode makes Drafty compliant with Encodable protocol.
/// First checks if Drafty can be represented as plain text and if so encodes
/// it as a primitive string. Otherwise encodes into a JSON object.
public func encode(to encoder: Encoder) throws {
if isPlain {
// If trafty contains plain text, encode it as a primitive string.
var container = encoder.singleValueContainer()
try container.encode(txt)
} else {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(txt, forKey: CodingKeys.txt)
// fmt cannot be nil.
try container.encode(fmt, forKey: CodingKeys.fmt)
// Encode entities only if they are present.
if ent != nil {
try container.encode(ent, forKey: CodingKeys.ent)
}
}
}
/// Parses provided content string using markdown-like markup.
///
/// - Parameters:
/// - content: a string with optional markdown-style markup
public init(content: String) {
let that = Drafty.parse(content: content)
self.txt = that.txt
self.fmt = that.fmt
self.ent = that.ent
}
/// Initializes Drafty without parsing the text string.
/// - Parameters:
/// - plainText: text body
public init(plainText: String) {
txt = plainText
}
/// Initializes Drafty with text and formatting obeject without parsing the text string.
/// - Parameters:
/// - text: text body
/// - fmt: array of inline styles and references to entities
/// - ent: array of entity attachments
init(text: String, fmt: [Style]?, ent: [Entity]?) {
self.txt = text
self.fmt = fmt
self.ent = ent
}
public static func isVoid(type: String?) -> Bool {
return kVoidStyles.contains(type ?? "-")
}
// Polifill brain-damaged Swift.
private static func subString(line: String, start: Int, end: Int) -> String {
return String(line[line.index(line.startIndex, offsetBy: start)..<line.index(line.startIndex, offsetBy: end)])
}
// Detect starts and ends of formatting spans. Unformatted spans are
// ignored at this stage.
private static func spannify(original: String, re: NSRegularExpression, type: String) -> [Span] {
var spans: [Span] = []
let nsoriginal = original as NSString
let matcher = re.matches(in: original, range: NSRange(location: 0, length: nsoriginal.length))
for match in matcher {
let s = Span()
// Convert NSRange to Range otherwise it will fail on strings with characters not
// representable in UTF16 (i.e. emoji)
var r = Range(match.range, in: original)!
// ^ match.range.lowerBound -> index of the opening markup character
s.start = original.distance(from: original.startIndex, to: r.lowerBound) // 'hello *world*'
s.text = nsoriginal.substring(with: match.range(at: 1))
r = Range(match.range(at: 1), in: original)!
s.end = original.distance(from: original.startIndex, to: r.upperBound)
s.type = type
spans.append(s)
}
return spans
}
// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is
// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->
// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');
//
// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert
// ranges from markup-ed offsets to plain text offsets.
private static func chunkify(line: String, start startAt: Int, end: Int, spans: [Span]) -> [Span] {
guard !spans.isEmpty else { return spans }
var start = startAt
var chunks: [Span] = []
for span in spans {
// Grab the initial unstyled chunk.
if span.start > start {
// Substrings in Swift are crazy.
chunks.append(Span(text: Drafty.subString(line: line, start: start, end: span.start)))
}
// Grab the styled chunk. It may include subchunks.
let chunk = Span()
chunk.type = span.type
if let children = span.children {
chunk.children = chunkify(line: line, start: span.start + 1, end: span.end, spans: children)
} else {
chunk.text = span.text
}
chunks.append(chunk)
start = span.end + 1 // '+1' is to skip the formatting character
}
// Grab the remaining unstyled chunk, after the last span
if start < end {
chunks.append(Span(text: String(line[line.index(line.startIndex, offsetBy: start)..<line.index(line.startIndex, offsetBy: end)])))
}
return chunks
}
// Convert flat array or spans into a tree representation.
// Keep standalone and nested spans, throw away partially overlapping spans.
private static func toSpanTree(spans: [Span]) -> [Span] {
guard !spans.isEmpty else { return spans }
var tree: [Span] = []
var last = spans[0]
tree.append(last)
for i in 1..<spans.count {
let curr = spans[i]
// Keep spans which start after the end of the previous span or those which
// are complete within the previous span.
if curr.start > last.end {
// Span is completely outside of the previous span.
tree.append(curr)
last = curr
} else if curr.end < last.end {
// Span is fully inside of the previous span. Push to subnode.
if last.children == nil {
last.children = []
}
last.children!.append(curr)
}
// Span could also partially overlap, ignore it as invalid.
}
// Recursively rearrange the subnodes.
for span in tree {
if let children = span.children {
span.children = toSpanTree(spans: children)
}
}
return tree
}
// Convert a list of chunks into a block. A block fully describes one line of formatted text.
private static func draftify(chunks: [Span]?, startAt: Int) -> Block? {
guard let chunks = chunks else { return nil }
let block = Block(txt: "")
var ranges: [Style] = []
for chunk in chunks {
if chunk.text == nil {
if let drafty = draftify(chunks: chunk.children, startAt: block.txt.count + startAt) {
chunk.text = drafty.txt
if let fmt = drafty.fmt {
ranges.append(contentsOf: fmt)
}
}
}
if chunk.type != nil {
ranges.append(Style(tp: chunk.type, at: block.txt.count + startAt, len: chunk.text!.count))
}
if chunk.text != nil {
block.txt += chunk.text!
}
}
if ranges.count > 0 {
block.fmt = ranges
}
return block
}
// Extract entities from a line of text.
private static func extractEntities(line: String) -> [ExtractedEnt] {
let nsline = line as NSString
return Drafty.kEntities.flatMap { (proc: EntityProc) -> [ExtractedEnt] in
let matches = proc.re.matches(in: line, range: NSRange(location: 0, length: nsline.length))
return matches.map { (m) -> ExtractedEnt in
let ee = ExtractedEnt()
// m.range is the entire match including markup
let r = Range(m.range, in: line)!
ee.at = line.distance(from: line.startIndex, to: r.lowerBound)
ee.value = nsline.substring(with: m.range)
ee.len = ee.value.count
ee.tp = proc.name
ee.data = proc.pack(nsline, m)
return ee
}
}
}
/// Parse optionally marked-up text into structured representation.
///
/// - Parameters:
/// - content: plain-text content to parse.
/// - Returns: Drafty object.
public static func parse(content: String) -> Drafty {
// Break input into individual lines because format cannot span multiple lines.
// This breaks lines by \n only, we do not expect to see Windows-style \r\n.
let lines = content.components(separatedBy: .newlines)
// This method also accounts for Windows-style line breaks, but it's probably not needed.
// let lines = content.split { $0 == "\n" || $0 == "\r\n" }.map(String.init)
var blks: [Block] = []
var refs: [Entity] = []
var entityMap: [String: JSONValue] = [:]
for line in lines {
var spans = Drafty.kInlineStyles.flatMap { (arg) -> [Span] in
let (name, re) = arg
return spannify(original: line, re: re, type: name)
}
let b: Block?
if !spans.isEmpty {
// Sort styled spans in ascending order by .start
spans.sort { lhs, rhs in
return lhs.start < rhs.start
}
// Rearrange flat list of styled spans into a tree, throw away invalid spans.
spans = toSpanTree(spans: spans)
// Parse the entire string into spans, styled or unstyled.
spans = chunkify(line: line, start: 0, end: line.count, spans: spans)
// Convert line into a block.
b = draftify(chunks: spans, startAt: 0)
} else {
b = Block(txt: line)
}
if let b = b {
// Extract entities from the string already cleared of markup.
let eentities = extractEntities(line: b.txt)
// Normalize entities by splitting them into spans and references.
for eent in eentities {
// Check if the entity has been indexed already
var index = entityMap[eent.value]
if index == nil {
entityMap[eent.value] = JSONValue.int(refs.count)
index = entityMap[eent.value]
refs.append(Entity(tp: eent.tp, data: eent.data))
}
b.addStyle(s: Style(at: eent.at, len: eent.len, key: index!.asInt()))
}
blks.append(b)
}
}
var text: String = ""
var fmt: [Style] = []
// Merge lines and save line breaks as BR inline formatting.
if !blks.isEmpty {
var b = blks[0]
text = b.txt
if let bfmt = b.fmt {
fmt.append(contentsOf: bfmt)
}
for i in 1..<blks.count {
let offset = text.count + 1
fmt.append(Style(tp: "BR", at: offset - 1, len: 1))
b = blks[i]
text.append(" ") // BR points to this space
text.append(b.txt)
if let bfmt = b.fmt {
for s in bfmt {
s.at += offset
fmt.append(s)
}
}
}
}
return Drafty(text: text, fmt: fmt.isEmpty ? nil : fmt, ent: refs.isEmpty ? nil : refs)
}
/// Get inline styles and references to entities
public var styles: [Style]? {
return fmt
}
// Get entities (attachments)
public var entities: [Entity]? {
return ent
}
/// Extract attachment references for use in message header.
///
/// - Returns: string array of attachment references or nil if no attachments with references were found.
public var entReferences: [String]? {
guard let ent = ent else { return nil }
var result: [String] = []
for anEnt in ent {
if let ref = anEnt.data?["ref"] {
if case .string(let str) = ref {
result.append(str)
}
}
if let preref = anEnt.data?["preref"] {
if case .string(let str) = preref {
result.append(str)
}
}
}
return result.isEmpty ? nil : result
}
/// Find entity from the reference given in style object
public func entityFor(for style: Style) -> Entity? {
let index = style.key ?? 0
guard let ent = ent, ent.count > index else { return nil }
return ent[index]
}
/// Convert Drafty to plain text
public var string: String {
return txt
}
/// Make sure Drafty is properly initialized for entity insertion.
private func prepareForEntity(at: Int, len: Int) {
if fmt == nil {
fmt = []
}
if ent == nil {
ent = []
}
fmt!.append(Style(at: at, len: len, key: ent!.count))
}
/// Make sure Drafty is properly initialized for style insertion.
private func prepareForStyle() {
if fmt == nil {
fmt = []
}
}
/// Insert audio message.
///
/// - Parameters:
/// - at: location to insert audio at
/// - mime: Content-type, such as 'image/jpeg'.
/// - bits: Content as an array of bytes
/// - preview: an array of amplitudes to use as preview.
/// - duration:record duration in milliseconds.
/// - fname: name of the file to suggest to the receiver.
/// - refurl: Reference to full/extended image.
/// - size: file size hint (in bytes) as reported by the client.
/// - Returns: 'self' Drafty object.
public func insertAudio(at: Int, mime: String?, bits: Data?, preview: Data, duration: Int, fname: String?, refurl: URL?, size: Int) throws -> Drafty {
guard bits != nil || refurl != nil else {
throw DraftyError.illegalArgument("Either image bits or reference URL must not be null.")
}
guard txt.count > at && at >= 0 else {
throw DraftyError.invalidIndex("Invalid insertion position")
}
prepareForEntity(at: at, len: 1)
var data: [String: JSONValue] = [:]
if let mime = mime, !mime.isEmpty {
data["mime"] = JSONValue.string(mime)
}
if let bits = bits {
data["val"] = JSONValue.bytes(bits)
}
data["preview"] = JSONValue.bytes(preview)
data["duration"] = JSONValue.int(duration)
if let fname = fname, !fname.isEmpty {
data["name"] = JSONValue.string(fname)
}
if let refurl = refurl {
data["ref"] = JSONValue.string(refurl.absoluteString)
}
if size > 0 {
data["size"] = JSONValue.int(size)
}
ent!.append(Entity(tp: "AU", data: data))
return self
}
/// Insert video message.
///
/// - Parameters:
/// - at: location to insert audio at
/// - mime: Content-type, such as 'video/mp4'.
/// - bits: Content as an array of bytes
/// - preview: an array of amplitudes to use as preview.
/// - duration:record duration in milliseconds.
/// - fname: name of the file to suggest to the receiver.
/// - refurl: reference to full/extended video.
/// - size: file size hint (in bytes) as reported by the client.
/// - previewRef: reference to preview image.
/// - Returns: 'self' Drafty object.
public func insertVideo(at: Int,
mime: String, bits: Data?, refurl: URL?,
duration: Int, width: Int, height: Int, fname: String?, size: Int,
preMime: String?, preview: Data?, previewRef: URL?) throws -> Drafty {
guard bits != nil || refurl != nil else {
throw DraftyError.illegalArgument("Either image bits or reference URL must not be null.")
}
guard txt.count > at && at >= 0 else {
throw DraftyError.invalidIndex("Invalid insertion position")
}
prepareForEntity(at: at, len: 1)
var data: [String: JSONValue] = [:]
if !mime.isEmpty {
data["mime"] = .string(mime)
}
if let bits = bits {
data["val"] = .bytes(bits)
}
if let refurl = refurl {
data["ref"] = .string(refurl.absoluteString)
}
data["duration"] = .int(duration)
if let fname = fname, !fname.isEmpty {
data["name"] = .string(fname)
}
data["height"] = .int(height)
data["width"] = .int(width)
if size > 0 {
data["size"] = .int(size)
}
if let preMime = preMime, !preMime.isEmpty {
data["premime"] = .string(preMime)
}
if let preview = preview {
data["preview"] = .bytes(preview)
}
if let previewRef = previewRef {
data["preref"] = .string(previewRef.absoluteString)
}
ent!.append(Entity(tp: "VD", data: data))
return self
}
/// Insert inline image
///
/// - Parameters:
/// - at: location to insert image at
/// - mime: Content-type, such as 'image/jpeg'.
/// - bits: Content as an array of bytes
/// - width: image width in pixels
/// - height: image height in pixels
/// - fname: name of the file to suggest to the receiver.
/// - Returns: 'self' Drafty object.
public func insertImage(at: Int, mime: String?, bits: Data, width: Int, height: Int, fname: String?) -> Drafty {
return try! insertImage(at: at, mime: mime, bits: bits, width: width, height: height, fname: fname, refurl: nil, size: bits.count)
}
/// Insert image either as a reference or inline.
///
/// - Parameters:
/// - at: location to insert image at
/// - mime: Content-type, such as 'image/jpeg'.
/// - bits: Content as an array of bytes
/// - width: image width in pixels
/// - height: image height in pixels
/// - fname: name of the file to suggest to the receiver.
/// - refurl: Reference to full/extended image.
/// - size: file size hint (in bytes) as reported by the client.
/// - Returns: 'self' Drafty object.
public func insertImage(at: Int, mime: String?, bits: Data?, width: Int, height: Int, fname: String?, refurl: URL?, size: Int) throws -> Drafty {
guard bits != nil || refurl != nil else {
throw DraftyError.illegalArgument("Either image bits or reference URL must not be null.")
}
guard txt.count > at && at >= 0 else {
throw DraftyError.invalidIndex("Invalid insertion position")
}
prepareForEntity(at: at, len: 1)
var data: [String: JSONValue] = [:]
if let mime = mime, !mime.isEmpty {
data["mime"] = JSONValue.string(mime)
}
if let bits = bits {
data["val"] = JSONValue.bytes(bits)
}
data["width"] = JSONValue.int(width)
data["height"] = JSONValue.int(height)
if let fname = fname, !fname.isEmpty {
data["name"] = JSONValue.string(fname)
}
if let refurl = refurl {
data["ref"] = JSONValue.string(refurl.absoluteString)
}
if size > 0 {
data["size"] = JSONValue.int(size)
}
ent!.append(Entity(tp: "IM", data: data))
return self
}
/// Attach file to a drafty object inline.
///
/// - Parameters:
/// - mime: Content-type, such as 'text/plain'.
/// - bits: Content as an array of bytes.
/// - fname: Optional file name to suggest to the receiver.
/// - Returns: 'self' Drafty object.
public func attachFile(mime: String?, bits: Data, fname: String?) -> Drafty {
return try! attachFile(mime: mime, bits: bits, fname: fname, refurl: nil, size: bits.count)
}
/// Attach file to a drafty object as reference.
///
/// - Parameters:
/// - mime: Content-type, such as 'text/plain'.
/// - fname: Optional file name to suggest to the receiver.
/// - refurl: reference to content location. If URL is relative, assume current server.
/// - size: size of the attachment (treated by client as an untrusted hint).
/// - Returns: 'self' Drafty object.
public func attachFile(mime: String?, fname: String?, refurl: URL, size: Int) throws -> Drafty {
return try! attachFile(mime: mime, bits: nil, fname: fname, refurl: refurl, size: size)
}
/// Attach file to a drafty object either as a reference or inline.
///
/// - Parameters:
/// - mime: Content-type, such as 'text/plain'.
/// - fname: Optional file name to suggest to the receiver.
/// - bits: Content as an array of bytes.
/// - refurl: reference to content location. If URL is relative, assume current server.
/// - size: size of the attachment (treated by client as an untrusted hint).
/// - Returns: 'self' Drafty object.
public func attachFile(mime: String?, bits: Data?, fname: String?, refurl: URL?, size: Int) throws -> Drafty {
guard bits != nil || refurl != nil else {
throw DraftyError.illegalArgument("Either file bits or reference URL must not be nil.")
}
prepareForEntity(at: -1, len: 1)
var data: [String: JSONValue] = [:]
if let mime = mime, !mime.isEmpty {
data["mime"] = JSONValue.string(mime)
}
if let bits = bits {
data["val"] = JSONValue.bytes(bits)
}
if let fname = fname, !fname.isEmpty {
data["name"] = JSONValue.string(fname)
}
if let refurl = refurl {
data["ref"] = JSONValue.string(refurl.absoluteString)
}
if size > 0 {
data["size"] = JSONValue.int(size)
}
ent!.append(Entity(tp: "EX", data: data))
return self
}
/// Attach object as json. Intended to be used as a form response.
///
/// - Parameters:
/// - json: object to attach.
/// - Returns: 'self' Drafty object.
public func attachJSON(_ json: [String: JSONValue]) -> Drafty {
prepareForEntity(at: -1, len: 1)
var data: [String: JSONValue] = [:]
data["mime"] = JSONValue.string(Drafty.kJSONMimeType)
data["val"] = JSONValue.dict(json)
ent!.append(Entity(tp: "EX", data: data))
return self
}
/// Create a Drafty document consisting of a single mention.
///
/// - Parameters:
/// - name: name of the user to be mentioned
/// - uid: user's unique id
/// - Returns: new Drafty object mentioning the user.
public static func mention(userWithName name: String, uid: String) -> Drafty {
let d = Drafty(plainText: name)
d.fmt = [Style(at: 0, len: name.count, key: 0)]
d.ent = [Entity(tp: "MN", data: ["val": JSONValue.string(uid)])]
return d
}
/// Create a Drafty document consisting of a single video call.
///
/// - Returns: new Drafty object representing a video call.
public static func videoCall() -> Drafty {
let d = Drafty(plainText: " ")
d.fmt = [Style(at: 0, len: 1, key: 0)]
d.ent = [Entity(tp: "VC", data: nil)]
return d
}
/// Wrap contents of the document into the specified style.
///
/// - Parameters:
/// - style: style to wrap document into.
/// - Returns: 'self' Drafty document wrapped in style.
public func wrapInto(style: String) -> Drafty {
prepareForStyle()
fmt!.append(Style(tp: style, at: 0, len: txt.count))
return self
}
/// Create a quote of a given Drafty document.
///
/// - Parameters:
/// - header: Quote header (title, etc.).
/// - uid: UID of the author to mention.
/// - body: Body of the quoted message.
/// - Returns:a Drafty doc with the quote formatting.
public static func quote(quoteHeader header: String, authorUid uid: String, quoteContent body: Drafty) -> Drafty {
return Drafty.mention(userWithName: header, uid: uid)
.appendLineBreak()
.append(body)
.wrapInto(style: "QQ")
}
/// Append line break 'BR' to Darfty document
/// - Returns: 'self' Drafty object.
public func appendLineBreak() -> Drafty {
prepareForStyle()
fmt!.append(Style(tp: "BR", at: txt.count, len: 1))
txt += " "
return self
}
/// Append one Drafty document to another.
/// - Returns: 'self' Drafty object.
public func append(_ that: Drafty) -> Drafty {
let len = txt.count
txt += that.txt
if let thatFmt = that.fmt {
if fmt == nil {
fmt = []
}
if that.ent != nil && ent == nil {
ent = []
}
for src in thatFmt {
let style = Style()
style.at = src.at + len
style.len = src.len
// Special case for the outside of the normal rendering flow styles (e.g. EX).
if src.at == -1 {
style.at = -1
style.len = 0
}
if src.tp != nil {
style.tp = src.tp
} else if let thatEnt = that.ent {
style.key = ent!.count
ent!.append(thatEnt[src.key ?? 0])
}
fmt!.append(style)
}
}
return self
}
/// Insert button into Drafty document.
///
/// - Parameters:
/// - at: is location where the button is inserted.
/// - len: is the length of the text to be used as button title.
/// - name: is an opaque ID of the button. Client should just return it to the server when the button is clicked.
/// - actionType: is the type of the button, one of 'url' or 'pub'.
/// - actionValue: is the value associated with the action: 'url': URL, 'pub': optional data to add to response.
/// - refUrl: parameter required by URL buttons: url to go to on click.
///
/// - Returns: 'self' Drafty object.
internal func insertButton(at: Int, len: Int, name: String?, actionType: String, actionValue: String?, refUrl: URL?) throws -> Drafty {
prepareForEntity(at: at, len: len)
guard actionType == "url" || actionType == "pub" else {
throw DraftyError.illegalArgument("Unknown action type \(actionType)")
}
guard actionType == "url" && refUrl != nil else {
throw DraftyError.illegalArgument("URL required for URL buttons")
}
var data: [String: JSONValue] = [:]
data["act"] = JSONValue.string(actionType)
if let name = name, !name.isEmpty {
data["name"] = JSONValue.string(name)
}
if let actionValue = actionValue, !actionValue.isEmpty {
data["val"] = JSONValue.string(actionValue)
}
if actionType == "url" {
data["ref"] = JSONValue.string(refUrl!.absoluteString)
}
ent!.append(Entity(tp: "BN", data: data))
return self
}
// Comparator is needed for testing.
public static func == (lhs: Drafty, rhs: Drafty) -> Bool {
return lhs.txt == rhs.txt &&
lhs.fmt == rhs.fmt &&
((lhs.ent == nil && rhs.ent == nil) || (lhs.ent == rhs.ent))
}
/// Check if the instance contains no markup and consequently can be represented by
/// plain String without loss of information.
public var isPlain: Bool {
return ent == nil && fmt == nil
}
/// Collection of methods to convert Drafty object into a tree of Span's and traverse the tree top-down and bottom-up.
fileprivate class SpanTreeProcessor {
// Inverse of chunkify. Returns a tree of formatted spans.
class private func spansToTree(tree parent: Span, line: String, start startAt: Int, end: Int, spans: [Span]) -> Span {
var start = startAt
guard !spans.isEmpty else {
return parent.append(Span(text: Drafty.subString(line: line, start: start, end: end)))
}
// Process ranges calling formatter for each range. Have to use index because it needs to step back.
var i = 0
while i < spans.count {
let span = spans[i]
i += 1
if span.start < 0 && span.type == "EX" {
parent.append(Span(type: span.type, data: span.data, key: span.key, attachment: true))
continue
}
// Add un-styled range before the styled span starts.
if start < span.start {
parent.append(Span(text: Drafty.subString(line: line, start: start, end: span.start)))
start = span.start
}
// Get all spans which are within the current span.
var subspans: [Drafty.Span] = []
while i < spans.count {
let inner = spans[i]
i += 1
if inner.start < 0 || inner.start >= span.end {
// Either an attachment at the end, or past the current span. Put back and stop.
i -= 1
break
} else if inner.end <= span.end {
if inner.start < inner.end || inner.isVoid {
// Valid subspan: completely within the current span and
// either non-zero length or zero length is acceptable.
subspans.append(inner)
}
}
// else: overlapping subspan, ignore it.
}
parent.append(self.spansToTree(tree: span, line: line, start: start, end: span.end, spans: subspans))
start = span.end
}
// Add the last unformatted range.
if start < end {
parent.append(Span(text: Drafty.subString(line: line, start: start, end: end)))
}
return parent
}
class public func toTree(contentOf content: Drafty) -> Span? {
let txt = content.txt
var fmt = content.fmt
let ent = content.ent
let entCount = ent?.count ?? 0
// Handle special case when all values in fmt are 0 and fmt therefore was
// skipped.
if fmt == nil || fmt!.isEmpty {
if entCount == 1 {
fmt = [Style(at: 0, len: 0, key: 0)]
} else {
return Span(text: txt)
}
}
var attachments: [Span] = []
var spans: [Span] = []
let maxIndex = txt.count
for aFmt in fmt! {
if aFmt.len < 0 {
// Invalid length
continue
}
let key = aFmt.key ?? 0
if (ent != nil && (key < 0 || key >= entCount)) {
// Invalid key.
continue
}
if aFmt.at < 0 {
// Attachment
aFmt.at = -1
aFmt.len = 1
attachments.append(Span(start: aFmt.at, end: 0, index: key))
continue
} else if aFmt.at + aFmt.len > maxIndex {
// Out of bounds span.
continue
}
if aFmt.tp == nil || aFmt.tp!.isEmpty {
spans.append(Drafty.Span(start: aFmt.at, end: aFmt.at + aFmt.len, index: key))
} else {
spans.append(Drafty.Span(type: aFmt.tp, start: aFmt.at, end: aFmt.at + aFmt.len))
}
}
// Get span's actual type and attached data.
typealias TypeDataPair = (tp: String, data: [String : JSONValue]?)
let getTypeAndData = { (span: Drafty.Span) -> TypeDataPair in
var tp: String?
var data: [String : JSONValue]?
if span.type != nil && !span.type!.isEmpty {
tp = span.type
} else {
let e = ent![span.key]
tp = e.tp
data = e.data
}
// Is type still undefined? Hide the invalid element!
if tp == nil || tp!.isEmpty {
tp = "HD"
}
return (tp: tp!, data: data)