Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions lib/mob/screen.ex
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,46 @@ defmodule Mob.Screen do
"Add a handle_event/3 clause to handle it."
end

@before_compile Mob.Screen
defoverridable dump_state: 1, load_state: 2, handle_info: 2, terminate: 2, handle_event: 3
end
end

defmacro __before_compile__(env) do
template = Path.rootname(env.file) <> ".mob.heex"

cond do
Module.defines?(env.module, {:render, 1}) ->
quote(do: :ok)

File.exists?(template) ->
source =
template
|> File.read!()
|> String.split("\n")
|> Enum.map_join("\n", &(" " <> &1))

render_ast =
Code.string_to_quoted!("""
def render(assigns) do
import Mob.Sigil

~MOB\"\"\"
#{source}
\"\"\"
end
""")

quote do
@external_resource unquote(template)
unquote(render_ast)
end

true ->
quote(do: :ok)
end
end

# ── GenServer wrapper ─────────────────────────────────────────────────────

use GenServer
Expand Down
37 changes: 37 additions & 0 deletions test/mob/screen_collocation_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
defmodule Mob.ScreenCollocationTest do
use ExUnit.Case, async: true

test "use Mob.Screen compiles a sibling .mob.heex template into render/1" do
dir =
Path.join(System.tmp_dir!(), "mob_screen_collocation_#{System.unique_integer([:positive])}")

File.mkdir_p!(dir)
on_exit(fn -> File.rm_rf!(dir) end)

module = Module.concat([:"CollocatedScreen#{System.unique_integer([:positive])}"])
source = Path.join(dir, "collocated_screen.ex")
template = Path.join(dir, "collocated_screen.mob.heex")

File.write!(template, """
<Column>
<Text text={assigns.title} />
</Column>
""")

File.write!(source, """
defmodule #{inspect(module)} do
use Mob.Screen

def mount(_params, _session, socket), do: {:ok, socket}
end
""")

Code.compile_file(source)

assert %{
type: :column,
props: %{},
children: [%{type: :text, props: %{text: "Hello"}, children: []}]
} = module.render(%{title: "Hello"})
end
end