Skip to content

Commit

Permalink
Formatter - Fix texts along with tag blocks w/ whitespaces (#2247)
Browse files Browse the repository at this point in the history
Fix #2237
  • Loading branch information
feliperenan authored Sep 30, 2022
1 parent 52206b7 commit 7569a66
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
24 changes: 23 additions & 1 deletion lib/phoenix_live_view/html_algebra.ex
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,26 @@ defmodule Phoenix.LiveView.HTMLAlgebra do
end

true ->
concat([prev_doc, break(""), next_doc])
# For most cases, we do want to `break("")` here because they are
# block tags (div, p, etc..). But, in case the previous or next token
# is a text without whitespace, such as:
#
# (<div label="application programming interface">API</div>).
#
# We don't want to break("") otherwise it would format it like this:
#
# (
# <div label="application programming interface">API</div>
# ).
#
# Therefore, this check if the previous or next token is not a text
# and, if it is a text, check if that contains whitespace.
if (not text?(prev_node) and not text?(next_node)) or
(text_ends_with_space?(prev_node) or text_starts_with_space?(next_node)) do
concat([prev_doc, break(""), next_doc])
else
concat([prev_doc, next_doc])
end
end

{next_node, next_type, doc}
Expand Down Expand Up @@ -122,6 +141,9 @@ defmodule Phoenix.LiveView.HTMLAlgebra do
defp tag_block?({:tag_block, _, _, _, _}), do: true
defp tag_block?(_node), do: false

defp text?({:text, _text, _meta}), do: true
defp text?(_node), do: false

@codepoints '\s\n\r\t'

defp text_starts_with_space?({:text, text, _meta}) when text != "",
Expand Down
20 changes: 20 additions & 0 deletions test/phoenix_live_view/html_formatter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1959,6 +1959,26 @@ if Version.match?(System.version(), ">= 1.13.0") do
""")
end

test "doesn't break line when tag/component is right after the text" do
assert_formatter_doesnt_change("""
<p>
(<span label="application programming interface">API</span>).
</p>
""")

assert_formatter_doesnt_change("""
<p>
(<div label="application programming interface">API</div>).
</p>
""")

assert_formatter_doesnt_change("""
<p>
(<.abbr label="application programming interface">API</.abbr>).
</p>
""")
end

# TODO: Remove this `if` after Elixir versions before than 1.14 are no
# longer supported.
if function_exported?(EEx, :tokenize, 2) do
Expand Down

0 comments on commit 7569a66

Please sign in to comment.