Allow components to be used with inline blocks

Fixes #116
This commit is contained in:
Mitchell Hanberg 2021-04-09 00:27:18 -04:00
parent fe3aed5df7
commit d40ff3e0b1
4 changed files with 43 additions and 27 deletions

View file

@ -13,26 +13,17 @@ defmodule Temple.Parser.Components do
@impl Temple.Parser
def run({:c, _meta, [component_module | args]}) do
{assigns, block} =
case args do
[assigns, [do: block]] ->
{assigns, block}
{do_and_else, args} =
args
|> Temple.Parser.Utils.split_args()
[[do: block]] ->
{[], block}
[assigns] ->
{assigns, nil}
_ ->
{[], nil}
end
{do_and_else, assigns} = Temple.Parser.Utils.consolidate_blocks(do_and_else, args)
children =
if block == nil do
if do_and_else[:do] == nil do
[]
else
Temple.Parser.parse(block)
Temple.Parser.parse(do_and_else[:do])
end
Temple.Ast.new(

View file

@ -21,18 +21,7 @@ defmodule Temple.Parser.NonvoidElementsAliases do
args
|> Temple.Parser.Utils.split_args()
{do_and_else, args} =
case args do
[args] when is_list(args) ->
{do_value, args} = Keyword.pop(args, :do)
do_and_else = Keyword.put_new(do_and_else, :do, do_value)
{do_and_else, args}
_ ->
{do_and_else, args}
end
{do_and_else, args} = Temple.Parser.Utils.consolidate_blocks(do_and_else, args)
children = Temple.Parser.parse(do_and_else[:do])

View file

@ -60,6 +60,18 @@ defmodule Temple.Parser.Utils do
{List.flatten(do_and_else), args}
end
def consolidate_blocks(blocks, args) do
case args do
[args] when is_list(args) ->
{do_value, args} = Keyword.pop(args, :do)
{Keyword.put_new(blocks, :do, do_value), args}
_ ->
{blocks, args}
end
end
def split_on_fn([{:fn, _, _} = func | rest], {args_before, _, args_after}) do
split_on_fn(rest, {args_before, func, args_after})
end

View file

@ -17,6 +17,15 @@ defmodule Temple.Parser.ComponentsTest do
assert Components.applicable?(ast)
end
test "runs when using the `c` ast with an inline block" do
ast =
quote do
c SomeModule, foo: :bar, do: "hello"
end
assert Components.applicable?(ast)
end
test "runs when using the `c` ast without a block" do
ast =
quote do
@ -47,6 +56,21 @@ defmodule Temple.Parser.ComponentsTest do
} = ast
end
test "runs when using the `c` ast with an inline block" do
ast =
quote do
c SomeModule, foo: :bar, do: "hello"
end
ast = Components.run(ast)
assert %Components{
content: SomeModule,
attrs: [foo: :bar],
children: _
} = ast
end
test "adds a node to the buffer that takes args" do
raw_ast =
quote do