Add support for HTML img tags (their alts) on the new AttributedStringBuilder

This commit is contained in:
Stefan Ceriu
2025-09-16 14:26:53 +03:00
committed by Stefan Ceriu
parent 41a2acc0d7
commit 7dd34400e4
2 changed files with 22 additions and 0 deletions

View File

@@ -229,6 +229,13 @@ struct AttributedStringBuilderV2: AttributedStringBuilderProtocol {
paragraphStyle.firstLineHeadIndent = CGFloat(indentLevel) * 20
content.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: content.length))
case "img":
if let alt = try? childElement.attr("alt"), !alt.isEmpty {
content = NSMutableAttributedString(string: "[img: \(alt)]")
} else {
content = NSMutableAttributedString(string: "[img]")
}
default:
content = attributedString(element: childElement, documentBody: documentBody, preserveFormatting: preserveFormatting, listTag: listTag, listIndex: &childIndex, indentLevel: indentLevel)
}

View File

@@ -723,6 +723,21 @@ class AttributedStringBuilderV1Tests: XCTestCase {
XCTAssertEqual(foundAttachments, 2)
}
func testImageTags() {
let htmlString = "Hey <img src=\"smiley.gif\" alt=\"Smiley face\">! How's work<img src=\"workplace.jpg\">?"
guard let attributedString = attributedStringBuilder.fromHTML(htmlString) else {
XCTFail("Could not build the attributed string")
return
}
if AttributedStringBuilder.useNextGenHTMLParser {
XCTAssertEqual(String(attributedString.characters), "Hey [img: Smiley face]! How's work[img]?")
} else {
XCTAssertEqual(String(attributedString.characters), "Hey ! How's work?") // No bueno
}
}
// MARK: - Phishing prevention
func testPhishingLink() {