-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathImageElementConverter.swift
76 lines (60 loc) · 2.83 KB
/
ImageElementConverter.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
import UIKit
/// Provides a representation for `<img>` element.
///
class ImageElementConverter: AttachmentElementConverter {
// MARK: - AttachmentElementConverter
typealias AttachmentType = ImageAttachment
func convert(
_ element: ElementNode,
inheriting attributes: [NSAttributedString.Key: Any],
contentSerializer serialize: ContentSerializer) -> (attachment: ImageAttachment, string: NSAttributedString) {
let attachment = self.attachment(for: element)
let intrinsicRepresentation = NSAttributedString(attachment: attachment, attributes: attributes, aztec: ())
let serialization = serialize(element, intrinsicRepresentation, attributes, false)
return (attachment, serialization)
}
// MARK: - Attachment Creation
private func attachment(for element: ElementNode) -> ImageAttachment {
var extraAttributes = [Attribute]()
for attribute in element.attributes {
if let value = attribute.value.toString() {
extraAttributes[attribute.name] = .string(value)
}
}
let url: URL?
let srcAttribute = element.attributes.first(where: { $0.name == "src" })
if let urlString = srcAttribute?.value.toString() {
extraAttributes.remove(named: "src")
url = URL(string: urlString)
} else {
url = nil
}
let attachment = ImageAttachment(identifier: UUID().uuidString, url: url)
let classAttribute = element.attributes.first(where: { $0.name == "class" })
if let elementClass = classAttribute?.value.toString() {
let classAttributes = elementClass.components(separatedBy: " ")
var attributesToRemove = [String]()
for classAttribute in classAttributes {
if let alignment = ImageAttachment.Alignment.fromHTML(string: classAttribute) {
attachment.alignment = alignment
attributesToRemove.append(classAttribute)
}
if let size = ImageAttachment.Size.fromHTML(string: classAttribute) {
attachment.size = size
attributesToRemove.append(classAttribute)
}
}
let otherAttributes = classAttributes.filter({ (value) -> Bool in
return !attributesToRemove.contains(value)
})
let remainingClassAttributes = otherAttributes.joined(separator: " ")
if remainingClassAttributes.isEmpty {
extraAttributes.remove(named: "class")
} else {
extraAttributes["class"] = .string(remainingClassAttributes)
}
}
attachment.extraAttributes = extraAttributes
return attachment
}
}