Skip to content

Commit

Permalink
Fix extra whitespace in some link markup cases
Browse files Browse the repository at this point in the history
Our link icon markup incorrectly leaves behind whitespace in certain
cases. For example, given a link like this:

<a href="https://example.com"> text </a>

the markup will generate:

<a href="https://example.com" class="a-link a-link--icon">
  <span class="a-link__text"> text </span>
  <svg class="cf-icon-svg cf-icon-svg--external-link">...</svg>
</a>

The extra whitespace in the <span> gets underlined incorrectly.

See "View a webinar on the rule" on
https://www.consumerfinance.gov/know-before-you-owe/ for an example
where this happens on the live site.

This fix attempts to strip surrounding whitespace from the link text
to prevent this happening.
  • Loading branch information
chosak committed May 31, 2024
1 parent 526d4e6 commit 0afc93b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
16 changes: 16 additions & 0 deletions cfgov/core/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,19 @@ def test_link_button(self):
expected_tag = BeautifulSoup(expected_html, "html.parser")

self.assertEqual(add_link_markup(tag, path), str(expected_tag))

def test_link_with_whitespace_in_text(self):
url = "https://example.com"
tag = f'<a href="{url}">\nClick <strong>here</strong> now! </a>'
path = "/about-us/blog/"

expected_html = (
f'<a class="a-link a-link--icon" href="{url}">'
'<span class="a-link__text">'
"Click <strong>here</strong> now!</span> "
f"{self.external_link_icon}"
"</a>"
)

expected_tag = BeautifulSoup(expected_html, "html.parser")
self.assertEqual(add_link_markup(tag, path), str(expected_tag))
15 changes: 14 additions & 1 deletion cfgov/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.template.defaultfilters import slugify

from bs4 import BeautifulSoup
from bs4 import BeautifulSoup, NavigableString

from core.templatetags.svg_icon import svg_icon

Expand Down Expand Up @@ -195,6 +195,19 @@ def add_link_markup(tag, request_path):
tag.clear()
tag.append(span)

# Whether we used an existing text span with a-link__text or added a
# new one, we want to make sure that the link text doesn't include any
# wrapping whitespace, otherwise it'll be incorrectly underlined.
#
# This fixes tags like <a> text with surrounding whitespace </a> or
# tags like <a> text with <strong>other</strong> tag </a> but not tags
# like <a> text with <strong>other tag with whitespace </strong></a>.
if span.contents:
if isinstance(span.contents[0], NavigableString):
span.contents[0] = NavigableString(span.contents[0].lstrip())
if isinstance(span.contents[-1], NavigableString):
span.contents[-1] = NavigableString(span.contents[-1].rstrip())

tag.append(" ")
tag.append(icon_soup)

Expand Down

0 comments on commit 0afc93b

Please sign in to comment.