From 601c9f2cd81da303594897c67f6a88624c5adfcf Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Fri, 22 Dec 2023 18:43:53 -0500 Subject: [PATCH] Fix converting self-closing br tags --- .../AttributedStringConverter.swift | 19 +++++++++++-------- .../AttributedStringConverterTests.swift | 4 ++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/Sources/HTMLStreamer/AttributedStringConverter.swift b/Sources/HTMLStreamer/AttributedStringConverter.swift index c4a326e..569776c 100644 --- a/Sources/HTMLStreamer/AttributedStringConverter.swift +++ b/Sources/HTMLStreamer/AttributedStringConverter.swift @@ -58,10 +58,7 @@ public struct AttributedStringConverter { case .startTag(let name, let selfClosing, let attributes): let action = Callbacks.elementAction(name: name, attributes: attributes) actionStack.append(action) - // self closing tags are ignored since they have no content - if !selfClosing { - handleStartTag(name, attributes: attributes) - } + handleStartTag(name, selfClosing: selfClosing, attributes: attributes) case .endTag(let name): handleEndTag(name) // if we have a non-default action for the current element, the run finishes here @@ -80,10 +77,17 @@ public struct AttributedStringConverter { return str } - private mutating func handleStartTag(_ name: String, attributes: [HTMLStreamer.Attribute]) { - switch name { - case "br": + private mutating func handleStartTag(_ name: String, selfClosing: Bool, attributes: [HTMLStreamer.Attribute]) { + if name == "br" { currentRun.append("\n") + return + } + // self closing tags are ignored since they have no content + guard !selfClosing else { + return + } + + switch name { case "a": // we need to always insert in attribute, because we need to always have one // to remove from the stack in handleEndTag @@ -195,7 +199,6 @@ public struct AttributedStringConverter { private mutating func finishBlockElement() { if str.length != 0 { previouslyFinishedBlockElement = true -// currentRun.append("\n\n") } } diff --git a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift index 77f0030..307ec85 100644 --- a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift +++ b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift @@ -57,6 +57,10 @@ final class AttributedStringConverterTests: XCTestCase { .font: font, .paragraphStyle: NSParagraphStyle.default, ])) + XCTAssertEqual(convert("a
b"), NSAttributedString(string: "a\nb", attributes: [ + .font: font, + .paragraphStyle: NSParagraphStyle.default, + ])) } func testConvertA() {