Skip to content

Commit

Permalink
feat(project): add rel noopener to external links in Markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
ChristiaanScheermeijer committed Jun 23, 2021
1 parent ae0ac47 commit 15a5eaa
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
18 changes: 15 additions & 3 deletions src/components/MarkdownComponent/MarkdownComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,22 @@ describe('<MarkdownComponent>', () => {

expect(container).toMatchSnapshot();
});
test('marks a link', () => {

test('should create a save and valid link element', () => {
const markdownString = 'This is a test markdown string with a [testlink](https://www.example.com)';
const { container } = render(<MarkdownComponent markdownString={markdownString} />);
const { getByText } = render(<MarkdownComponent markdownString={markdownString} />);

expect(getByText('testlink')).toHaveAttribute('href', 'https://www.example.com');
expect(getByText('testlink')).toHaveAttribute('rel', 'noopener');
expect(getByText('testlink')).toHaveAttribute('target', '_blank');
});

test('should create a valid link element for local pages', () => {
const markdownString = 'This is a test markdown string with a [testlink](/page)';
const { getByText } = render(<MarkdownComponent markdownString={markdownString} />);

expect(container).toContainHTML('<a href');
expect(getByText('testlink')).toHaveAttribute('href', '/page');
expect(getByText('testlink')).not.toHaveAttribute('rel', 'noopener');
expect(getByText('testlink')).not.toHaveAttribute('target', '_blank');
});
});
6 changes: 4 additions & 2 deletions src/components/MarkdownComponent/MarkdownComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ const parseMarkdown = (value: string): string =>
.replace(MARKDOWN_STRONG_REGEX, (...[, word]) => `<strong>${word}</strong>`)
.replace(MARKDOWN_ITALIC_REGEX, (...[, word]) => `<em>${word}</em>`)
.replace(MARKDOWN_LINK_REGEX, (...[, word, link]) => {
const target = /^(https?|www\.|\/\/)/.test(link) ? ' target="_blank"' : '';
const externalLink = /^(https?|www\.|\/\/)/.test(link);
const target = externalLink ? ' target="_blank"' : '';
const rel = externalLink ? ' rel="noopener"' : '';

return `<a href="${link}"${target}>${word}</a>`;
return `<a href="${link}"${target}${rel}>${word}</a>`;
})
.replace(LINEBREAK_REGEX, '<br />'); // linebreak formatter should run last

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ exports[`<MarkdownComponent> renders and matches snapshot 1`] = `
This is a test markdown string with a
<a
href="https://www.example.com"
rel="noopener"
target="_blank"
>
testlink
Expand Down

0 comments on commit 15a5eaa

Please sign in to comment.