Skip to content

Commit

Permalink
Fixes #1418 - Preserve new lines when parsing html strings
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanceriu committed Aug 8, 2023
1 parent 0511bef commit 35685db
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 8 additions & 2 deletions ElementX/Sources/Other/HTMLParsing/AttributedStringBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,21 @@ struct AttributedStringBuilder: AttributedStringBuilderProtocol {
// that could happen with the default HTML renderer of NSAttributedString which is a
// webview.
func fromHTML(_ htmlString: String?) -> AttributedString? {
guard let htmlString,
let data = htmlString.data(using: .utf8) else {
guard let htmlString else {
return nil
}

if let cached = Self.cache.value(forKey: htmlString) {
return cached
}

// Trick DTCoreText into preserving newlines
let adjustedHTMLString = htmlString.replacingOccurrences(of: "\n", with: "<br>")

guard let data = adjustedHTMLString.data(using: .utf8) else {
return nil
}

let defaultFont = UIFont.preferredFont(forTextStyle: .body)

let parsingOptions: [String: Any] = [
Expand Down
11 changes: 11 additions & 0 deletions UnitTests/Sources/AttributedStringBuilderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,17 @@ class AttributedStringBuilderTests: XCTestCase {
XCTAssertEqual(numberOfBlockquotes, 3, "Couldn't find all the blockquotes")
}

func testNewLinesArePreserved() {
let htmlString = "Bob's\nyour\nuncle\nand\nFanny's\nyour\naunt"

guard let attributedString = attributedStringBuilder.fromHTML(htmlString) else {
XCTFail("Could not build the attributed string")
return
}

XCTAssertEqual(String(attributedString.characters), htmlString.replacingOccurrences(of: "\n", with: "\u{2028}"))
}

// MARK: - Private

private func checkLinkIn(attributedString: AttributedString?, expectedLink: String, expectedRuns: Int) {
Expand Down

0 comments on commit 35685db

Please sign in to comment.