Skip to content

Commit

Permalink
Prevent empty attribute values from being appended (#62)
Browse files Browse the repository at this point in the history
When adding an attribute that should be appended to any existing one, first check if either
the existing or new attribute contain an empty value, and if so, don't perform the append.
Otherwise, we'll end up with extra whitespace within attribute values. Also, slight cleanup
of the attribute handling logic within `ElementRenderingBuffer`, to make the conditionals
a bit more clear.
  • Loading branch information
JohnSundell authored May 12, 2021
1 parent 27ba4be commit 0ca2d6b
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Sources/Plot/API/Attribute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ extension Attribute: NodeConvertible {

extension Attribute: AnyAttribute {
func render() -> String {
guard let value = value, !value.isEmpty else {
guard let value = nonEmptyValue else {
return ignoreIfValueIsEmpty ? "" : name
}

Expand Down
6 changes: 6 additions & 0 deletions Sources/Plot/Internal/AnyAttribute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ internal protocol AnyAttribute {

func render() -> String
}

extension AnyAttribute {
var nonEmptyValue: String? {
value?.isEmpty == false ? value : nil
}
}
12 changes: 7 additions & 5 deletions Sources/Plot/Internal/ElementRenderingBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ internal final class ElementRenderingBuffer {

func add(_ attribute: AnyAttribute) {
if let existingIndex = attributeIndexes[attribute.name] {
if !attribute.replaceExisting,
let existingValue = attributes[existingIndex].value,
let newValue = attribute.value {
attributes[existingIndex].value = existingValue + " " + newValue
} else {
if attribute.replaceExisting {
attributes[existingIndex].value = attribute.value
} else if let newValue = attribute.nonEmptyValue {
if let existingValue = attributes[existingIndex].nonEmptyValue {
attributes[existingIndex].value = existingValue + " " + newValue
} else {
attributes[existingIndex].value = newValue
}
}
} else {
attributeIndexes[attribute.name] = attributes.count
Expand Down
11 changes: 11 additions & 0 deletions Tests/PlotTests/HTMLComponentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ final class HTMLComponentTests: XCTestCase {
XCTAssertEqual(html, #"<p class="one two three">Hello</p>"#)
}

func testNotAppendingEmptyClassNames() {
let html = Paragraph("Hello")
.class("")
.class("one")
.class("")
.class("two")
.render()

XCTAssertEqual(html, #"<p class="one two">Hello</p>"#)
}

func testReplacingClass() {
let html = Paragraph("Hello")
.class("one")
Expand Down

0 comments on commit 0ca2d6b

Please sign in to comment.