Skip to content

Commit

Permalink
feat: add docs and test for trix post processor
Browse files Browse the repository at this point in the history
  • Loading branch information
MelchiorKokernoot committed Oct 17, 2024
1 parent c21e3cf commit 51f3f13
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions core/frameworks/pixel/trix_post_processor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ defmodule Frameworks.Pixel.TrixPostProcessor do
@doc """
Adds `target="_blank"` to any `<a>` tags that do not already have it.
It returns the modified HTML content.
## Regex Breakdown:
- `<a`: Matches the opening part of an <a> tag.
- `(?![^>]*target=)`: Negative lookahead to ensure the <a> tag does not already have a `target` attribute.
- `[^>]*`: Ensures that no characters up to the closing `>` of the tag contain `target=`.
- `([^>]*)`: Captures the remaining attributes inside the <a> tag.
"""
def add_target_blank(html_content) do
Regex.replace(~r/<a(?![^>]*target=)([^>]*)>/, html_content, "<a\\1 target=\"_blank\">")
Expand Down
40 changes: 40 additions & 0 deletions core/test/frameworks/pixel/trix_post_processor_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
defmodule Frameworks.Pixel.TrixPostProcessorTest do
use ExUnit.Case
alias Frameworks.Pixel.TrixPostProcessor

describe "add_target_blank/1" do
test "adds target=_blank to <a> tags without target attribute" do
html_content = "<a href=\"http://example.com\">Example</a>"
expected = "<a href=\"http://example.com\" target=\"_blank\">Example</a>"
assert TrixPostProcessor.add_target_blank(html_content) == expected
end

test "does not modify <a> tags with existing target attribute" do
html_content = "<a href=\"http://example.com\" target=\"_self\">Example</a>"
expected = "<a href=\"http://example.com\" target=\"_self\">Example</a>"
assert TrixPostProcessor.add_target_blank(html_content) == expected
end

test "adds target=_blank to multiple <a> tags without target attribute" do
html_content =
"<a href=\"http://example1.com\">Example1</a> <a href=\"http://example2.com\">Example2</a>"

expected =
"<a href=\"http://example1.com\" target=\"_blank\">Example1</a> <a href=\"http://example2.com\" target=\"_blank\">Example2</a>"

assert TrixPostProcessor.add_target_blank(html_content) == expected
end

test "handles nested <a> tags correctly" do
html_content = "<div><a href=\"http://example.com\">Example</a></div>"
expected = "<div><a href=\"http://example.com\" target=\"_blank\">Example</a></div>"
assert TrixPostProcessor.add_target_blank(html_content) == expected
end

test "returns the same content if no <a> tags are present" do
html_content = "<p>No links here</p>"
expected = "<p>No links here</p>"
assert TrixPostProcessor.add_target_blank(html_content) == expected
end
end
end

0 comments on commit 51f3f13

Please sign in to comment.