Skip to content

Commit

Permalink
helpers: Fix TrimShortHTML
Browse files Browse the repository at this point in the history
Where some tags are siblings of p tag.

Fixes #7081
  • Loading branch information
satotake authored and bep committed Mar 28, 2020
1 parent 4a39564 commit 9c99875
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
11 changes: 8 additions & 3 deletions helpers/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var (
openingPTag = []byte("<p>")
closingPTag = []byte("</p>")
paragraphIndicator = []byte("<p")
closingIndicator = []byte("</")
)

// ContentSpec provides functionality to render markdown content.
Expand Down Expand Up @@ -315,9 +316,13 @@ func (c *ContentSpec) TruncateWordsToWholeSentence(s string) (string, bool) {
// where said tags are the only <p> tags in the input and enclose the content
// of the input (whitespace excluded).
func (c *ContentSpec) TrimShortHTML(input []byte) []byte {
first := bytes.Index(input, paragraphIndicator)
last := bytes.LastIndex(input, paragraphIndicator)
if first == last {
firstOpeningP := bytes.Index(input, paragraphIndicator)
lastOpeningP := bytes.LastIndex(input, paragraphIndicator)

lastClosingP := bytes.LastIndex(input, closingPTag)
lastClosing := bytes.LastIndex(input, closingIndicator)

if firstOpeningP == lastOpeningP && lastClosingP == lastClosing {
input = bytes.TrimSpace(input)
input = bytes.TrimPrefix(input, openingPTag)
input = bytes.TrimSuffix(input, closingPTag)
Expand Down
1 change: 1 addition & 0 deletions helpers/content_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func TestTrimShortHTML(t *testing.T) {
{[]byte("\n \n \t <p> \t Whitespace\nHTML \n\t </p>\n\t"), []byte("Whitespace\nHTML")},
{[]byte("<p>Multiple</p><p>paragraphs</p>"), []byte("<p>Multiple</p><p>paragraphs</p>")},
{[]byte("<p>Nested<p>paragraphs</p></p>"), []byte("<p>Nested<p>paragraphs</p></p>")},
{[]byte("<p>Hello</p>\n<ul>\n<li>list1</li>\n<li>list2</li>\n</ul>"), []byte("<p>Hello</p>\n<ul>\n<li>list1</li>\n<li>list2</li>\n</ul>")},
}

c := newTestContentSpec()
Expand Down

0 comments on commit 9c99875

Please sign in to comment.