Fix extra line breaks being inserted before lists

This commit is contained in:
Shadowfacts 2024-01-16 19:26:40 -05:00
parent a32b972201
commit e709543568
2 changed files with 20 additions and 1 deletions

View File

@ -28,6 +28,7 @@ public struct AttributedStringConverter<Callbacks: HTMLConversionCallbacks> {
private var styleStack: [Style] = [] private var styleStack: [Style] = []
private var previouslyFinishedBlockElement = false private var previouslyFinishedBlockElement = false
private var currentElementIsEmpty = true private var currentElementIsEmpty = true
private var previouslyFinishedListItem = false
// The current run of text w/o styles changing // The current run of text w/o styles changing
private var currentRun: String = "" private var currentRun: String = ""
@ -135,7 +136,7 @@ public struct AttributedStringConverter<Callbacks: HTMLConversionCallbacks> {
finishRun() finishRun()
styleStack.append(.unorderedList) styleStack.append(.unorderedList)
case "li": case "li":
if str.length != 0 || !currentRun.isEmpty { if previouslyFinishedListItem {
currentRun.append("\n") currentRun.append("\n")
} }
let marker: String let marker: String
@ -186,12 +187,15 @@ public struct AttributedStringConverter<Callbacks: HTMLConversionCallbacks> {
finishRun() finishRun()
removeLastStyle(.orderedList) removeLastStyle(.orderedList)
finishBlockElement() finishBlockElement()
previouslyFinishedListItem = false
case "ul": case "ul":
finishRun() finishRun()
removeLastStyle(.unorderedList) removeLastStyle(.unorderedList)
finishBlockElement() finishBlockElement()
previouslyFinishedListItem = false
case "li": case "li":
finishRun() finishRun()
previouslyFinishedListItem = true
default: default:
break break
} }

View File

@ -319,4 +319,19 @@ final class AttributedStringConverterTests: XCTestCase {
XCTAssertEqual(convert("<p></p><blockquote><span>inside<br>quote</span></blockquote><span>after</span><p></p>"), result) XCTAssertEqual(convert("<p></p><blockquote><span>inside<br>quote</span></blockquote><span>after</span><p></p>"), result)
} }
func testParagraphFollowedByList() {
let result = NSMutableAttributedString()
result.append(NSAttributedString(string: "a\n\n", attributes: [
.font: font,
.paragraphStyle: NSParagraphStyle.default,
.foregroundColor: color,
]))
result.append(NSAttributedString(string: "\t1.\tb\n\t2.\tc", attributes: [
.font: font,
.paragraphStyle: listParagraphStyle,
.foregroundColor: color,
]))
XCTAssertEqual(convert("<p>a</p><ol><li>b</li><li>c</li></ol>"), result)
}
} }