Skip to content

Commit

Permalink
decode comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrocp committed Jan 25, 2024
1 parent 3608603 commit d1cc807
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
28 changes: 27 additions & 1 deletion lib/beacon/template/heex/heex_decoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,15 @@ defmodule Beacon.Template.HEEx.HEExDecoder do
["<%!--", content, "--%>"]
end

defp transform_node(%{"tag" => "eex_block", "blocks" => blocks, "arg" => arg}) do
defp transform_node(%{"tag" => "eex_block", "arg" => arg, "blocks" => blocks}) do
["<%=", arg, " %>", Enum.map(blocks, &transform_block/1)]
end

# eex_block with a `for` comprehension
defp transform_node(%{"tag" => "eex_block", "arg" => arg, "ast" => ast}) do
["<%= ", arg, " %>", decode_comprehension_ast(ast)]
end

defp transform_node(%{"tag" => tag, "attrs" => %{"self_close" => true} = attrs, "content" => []}) do
attrs = Map.delete(attrs, "self_close")
["<", tag, " ", transform_attrs(attrs), "/>"]
Expand Down Expand Up @@ -129,4 +134,25 @@ defmodule Beacon.Template.HEEx.HEExDecoder do
defp reconstruct_attr({name, {:expr, content, _}, _}) do
[name, "=", ?{, content, ?}]
end

defp decode_comprehension_ast(ast) do
ast
|> Jason.decode!()
|> List.flatten()
|> Enum.reduce([], fn node, acc -> decode_comprehension_ast_node(node, acc) end)
|> Enum.reverse()
end

defp decode_comprehension_ast_node(%{"type" => "text", "content" => [content | _]}, acc) do
[content | acc]
end

defp decode_comprehension_ast_node(%{"type" => "eex", "content" => [expr, %{"opt" => ~c"="}]}, acc) do
[["<%= ", expr, " %>"] | acc]
end

# TODO: improve eex_block closing detection (maybe augment it in JSONEncoder)
defp decode_comprehension_ast_node("end", acc), do: ["<% end %>" | acc]

defp decode_comprehension_ast_node(node, acc) when is_binary(node), do: [node | acc]
end
13 changes: 8 additions & 5 deletions test/beacon/template/heex/heex_decoder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,14 @@ defmodule Beacon.Template.HEEx.HEExDecoderTest do
end

test "comprehensions" do
assert_equal(~S"""
<%= for val <- @beacon_live_data[:vals] do %>
<%= val %>
<% end %>
""")
assert_equal(
~S"""
<%= for val <- @beacon_live_data[:vals] do %>
<%= val %>
<% end %>
""",
%{beacon_live_data: %{vals: [1]}}
)
end

test "function components" do
Expand Down

0 comments on commit d1cc807

Please sign in to comment.