Skip to content

Commit

Permalink
Fix HtmlAttributedStringConverter AttributedString to HTML conversion
Browse files Browse the repository at this point in the history
Fix typo
Add test
  • Loading branch information
mvasilak committed Aug 10, 2023
1 parent a899997 commit a08838c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Zotero/Controllers/HtmlAttributedStringConverter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ final class HtmlAttributedStringConverter {
}

/// Finds which attributes are currently opened (don't have closing attribute before them) in given array.
/// - parameter attributesL Attributes array to check.
/// - parameter attributes: Attributes array to check.
/// - returns: Array of opened attributes.
private func openedAttributes(from attributes: [Attribute]) -> [StringAttribute] {
let allCount = StringAttribute.allCases.count
Expand All @@ -68,7 +68,8 @@ final class HtmlAttributedStringConverter {
opened.append(attribute.type)
}

if (opened.count + closed.count) == allCount {
let uniqueAttributes: Set<StringAttribute> = .init(opened).union(closed)
if uniqueAttributes.count == allCount {
break
}
}
Expand Down
21 changes: 21 additions & 0 deletions ZoteroTests/HtmlAttributedStringConverterSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,27 @@ final class HtmlAttributedStringConverterSpec: QuickSpec {
let string = htmlConverter.convert(attributedString: attributedString)
expect(string).to(equal(#"abc <b><i>def</i></b> ghi <span style="font-variant:small-caps;">jk<sup>l</sup></span> mno"#))
}

it("converts multiple tags complex") {
let attributedStringRaw = #"start_bold_italic_subscript bold bold_superscript bold bold_subscript bold bold\nitalic\nend"#
let htmlStringRaw = #"<b><i><sub>start_bold_italic_subscript</sub></i> bold <sup>bold_superscript</sup> bold <sub>bold_subscript</sub> bold <i>bold\nitalic\nend</i></b>"#
let attributesAndRanges: [([StringAttribute], NSRange)] = [
([.bold, .italic, .subscript], NSRange(location: 0, length: 27)),
([.bold], NSRange(location: 27, length: 6)),
([.bold, .superscript], NSRange(location: 33, length: 16)),
([.bold], NSRange(location: 49, length: 6)),
([.bold, .subscript], NSRange(location: 55, length: 14)),
([.bold], NSRange(location: 69, length: 6)),
([.bold, .italic], NSRange(location: 75, length: 17))
]
let attributedString = NSMutableAttributedString(string: attributedStringRaw, attributes: [.font: font])
expect(attributedString.length).to(equal(attributedStringRaw.count))
for (attributes, range) in attributesAndRanges {
attributedString.addAttributes(StringAttribute.nsStringAttributes(from: attributes, baseFont: font), range: range)
}
let string = htmlConverter.convert(attributedString: attributedString)
expect(string).to(equal(htmlStringRaw))
}
}
}
}

0 comments on commit a08838c

Please sign in to comment.