Skip to content

Commit

Permalink
Remove custom cid and use LiveView's new @Myself
Browse files Browse the repository at this point in the history
  • Loading branch information
msaraiva committed Apr 9, 2020
1 parent 63ae14e commit 262491f
Show file tree
Hide file tree
Showing 9 changed files with 25 additions and 75 deletions.
4 changes: 2 additions & 2 deletions lib/surface.ex
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ defmodule Surface do
end

def event_value(_key, name, caller_cid) when is_binary(name) do
%{name: name, target: "[surface-cid=#{caller_cid}]"}
%{name: name, target: to_string(caller_cid)}
end

def event_value(_key, %{name: _, target: _} = event, _caller_cid) do
Expand Down Expand Up @@ -253,7 +253,7 @@ defmodule Surface do
end

def on_phx_event(phx_event, event, caller_cid) when is_binary(event) do
[phx_event, "=", quot(event), " phx-target=", "[surface-cid=", caller_cid, "]"]
[phx_event, "=", quot(event), " phx-target=", to_string(caller_cid)]
end

def on_phx_event(_phx_event, nil, _caller_cid) do
Expand Down
18 changes: 2 additions & 16 deletions lib/surface/live_component.ex
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,6 @@ defmodule Surface.LiveComponent do
end

defp quoted_mount(env) do
prefix = Module.split(env.module) |> List.last() |> String.downcase()

defaults =
for %{name: name, opts: opts} <- Module.get_attribute(env.module, :data) do
{name, Keyword.get(opts, :default)}
Expand All @@ -100,30 +98,18 @@ defmodule Surface.LiveComponent do
defoverridable mount: 1

def mount(socket) do
assigns = unquote(__MODULE__).default_assigns(unquote(prefix), unquote(defaults))
super(assign(socket, assigns))
super(assign(socket, unquote(defaults)))
end
end
else
quote do
def mount(socket) do
assigns = unquote(__MODULE__).default_assigns(unquote(prefix), unquote(defaults))
{:ok, assign(socket, assigns)}
{:ok, assign(socket, unquote(defaults))}
end
end
end
end

@doc false
def default_assigns(prefix, defaults) do
[__surface_cid__: "#{prefix}-#{hash_id()}"] ++ defaults
end

defp hash_id() do
:crypto.strong_rand_bytes(4)
|> Base.encode32(padding: false, case: :lower)
end

@doc """
This optional callback is invoked in order to set up a
context that can be retrieved for any descendent component.
Expand Down
4 changes: 2 additions & 2 deletions lib/surface/translator/component_translator_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,15 @@ defmodule Surface.Translator.ComponentTranslatorHelper do
def translate_value(:event, key, value, caller, line) do
case value do
{:attribute_expr, [expr]} ->
{:attribute_expr, ["event_value(\"#{key}\", [#{expr}], assigns[:__surface_cid__])"]}
{:attribute_expr, ["event_value(\"#{key}\", [#{expr}], assigns[:myself])"]}

event ->
if Module.open?(caller.module) do
event_reference = {to_string(event), caller.line + line}
Module.put_attribute(caller.module, :event_references, event_reference)
end

{:attribute_expr, ["event_value(\"#{key}\", \"#{event}\", assigns[:__surface_cid__])"]}
{:attribute_expr, ["event_value(\"#{key}\", \"#{event}\", assigns[:myself])"]}
end
end

Expand Down
10 changes: 3 additions & 7 deletions lib/surface/translator/live_component_translator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ defmodule Surface.Translator.LiveComponentTranslator do

@impl true
def prepare(nodes, caller) do
validate_root_node_and_add_cid(nodes, caller)
validate_root_node(nodes, caller)
end

@impl true
Expand Down Expand Up @@ -47,7 +47,7 @@ defmodule Surface.Translator.LiveComponentTranslator do
{open, Translator.translate(children_contents, caller), close}
end

defp validate_root_node_and_add_cid(children, caller) do
defp validate_root_node(children, caller) do
{nodes, n_tags, _n_binary} =
Enum.reduce(children, {[], 0, 0}, fn child, {nodes, n_tags, n_non_tags} ->
cond do
Expand All @@ -61,11 +61,7 @@ defmodule Surface.Translator.LiveComponentTranslator do
{[child | nodes], n_tags, n_non_tags + 1}

n_tags + n_non_tags == 0 && match?({_, _, _, %{translator: TagTranslator}}, child) ->
{mod_str, attributes, children, %{line: line} = meta} = child
expr = {:attribute_expr, ["@__surface_cid__"]}
new_attr = {"surface-cid", expr, %{line: line, spaces: [" ", "", ""]}}
updated_child = {mod_str, [new_attr | attributes], children, meta}
{[updated_child | nodes], n_tags + 1, n_non_tags}
{[child | nodes], n_tags + 1, n_non_tags}

true ->
{_, _, _, %{line: line}} = child
Expand Down
7 changes: 1 addition & 6 deletions lib/surface/translator/tag_translator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ defmodule Surface.Translator.TagTranslator do
space2,
"[",
value_to_code(value),
"], assigns[:__surface_cid__]) %>",
"], assigns[:myself]) %>",
space3
]
end
Expand Down Expand Up @@ -164,11 +164,6 @@ defmodule Surface.Translator.TagTranslator do
]
end

defp translate_attribute_assignment("surface-cid", value, %{spaces: spaces}) do
[space1, space2, space3] = spaces
[space1, "surface-cid", space2, "=", space3, wrap_safe_value(value)]
end

defp translate_attribute_assignment(key, value, %{spaces: spaces}) do
[space1, space2, space3] = spaces
[space1, key, space2, "=", space3, wrap_unsafe_value(key, value)]
Expand Down
14 changes: 3 additions & 11 deletions test/live_component_events_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ defmodule Surface.EventsTest do
property click, :event, default: "click"

def render(assigns) do
assigns = Map.put(assigns, :__surface_cid__, "button")

~H"""
<button :on-phx-click={{ @click }}>Click me!</button>
"""
Expand All @@ -40,8 +38,6 @@ defmodule Surface.EventsTest do
property buttonClick, :event, default: "click"

def render(assigns) do
assigns = Map.put(assigns, :__surface_cid__, "panel")

~H"""
<div>
<Button id="button_id" click={{ @buttonClick }}/>
Expand Down Expand Up @@ -82,16 +78,12 @@ defmodule Surface.EventsTest do
end
end

test "automatically generate surface-cid for live components" do
assert render_live("<LiveDiv/>") =~ ~r(<div surface-cid="livediv-.{7}">Live div</div>)
end

test "handle event in the parent liveview" do
{:ok, _view, html} = live_isolated(build_conn(), View)

assert_html(
html =~ """
<button surface-cid="button" phx-click="click" data-phx-component="1">Click me!</button>
<button phx-click="click" data-phx-component="1">Click me!</button>
"""
)
end
Expand All @@ -104,7 +96,7 @@ defmodule Surface.EventsTest do
"""

assert render_live(code) =~ """
<button surface-cid="button" phx-click="click" phx-target="[surface-cid=panel]"\
<button phx-click="click" phx-target="0"\
"""
end

Expand All @@ -116,7 +108,7 @@ defmodule Surface.EventsTest do
"""

assert render_live(code) =~ """
<button surface-cid="button" phx-click="click" phx-target="[surface-cid=button]"\
<button phx-click="click" phx-target="0"\
"""
end

Expand Down
22 changes: 4 additions & 18 deletions test/live_component_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ defmodule LiveComponentTest do
</InfoProviderWithoutSlotProps>
"""

assert render_live(code) =~ ~r"""
<div surface-cid=".+"><span>Hi there!</span></div>
assert render_live(code) =~ """
<div><span>Hi there!</span></div>
"""
end

Expand All @@ -103,25 +103,11 @@ defmodule LiveComponentTest do
</InfoProvider>
"""

assert render_live(code) =~ ~r"""
<div surface-cid=".+"><span>Hi there!</span></div>
assert render_live(code) =~ """
<div><span>Hi there!</span></div>
"""
end

test "generate a different cid for each instance when using :for" do
code = """
<StatefulComponent:for={{ i <- [1,2] }} id={{i}} />
"""

[cid1, cid2] =
Regex.scan(~r/surface-cid="(.+)"/U, render_live(code))
|> Enum.map(fn [_, cid] -> cid end)

assert cid1 =~ ~r/^statefulcomponent-/
assert cid2 =~ ~r/^statefulcomponent-/
assert cid1 != cid2
end

test "render stateless component" do
{:ok, _view, html} = live_isolated(build_conn(), View)
assert html =~ "Initial stateless"
Expand Down
15 changes: 5 additions & 10 deletions test/slot_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ defmodule SlotTest do
use Surface.LiveComponent

def render(assigns) do
assigns = Map.put(assigns, :__surface_cid__, "stateful")

~H"""
<div>Stateful</div>
"""
Expand All @@ -28,8 +26,6 @@ defmodule SlotTest do
slot inner

def render(assigns) do
assigns = Map.put(assigns, :__surface_cid__, "outer")

~H"""
<div>
<div :for={{ data <- @inner }}>
Expand Down Expand Up @@ -149,7 +145,6 @@ defmodule SlotTest do
slot cols, props: [:info, item: ^items]

def render(assigns) do
assigns = Map.put(assigns, :__surface_cid__, "table")
info = "Some info from Grid"

~H"""
Expand Down Expand Up @@ -189,10 +184,10 @@ defmodule SlotTest do

assert_html(
render_live(code) =~ """
<div surface-cid="outer">
<div>
<div>
label 1:<b>content 1</b>
<div surface-cid="stateful" data-phx-component="0">Stateful</div>
<div data-phx-component="0">Stateful</div>
</div>
<div>
label 2:<b>content 2</b>
Expand All @@ -202,7 +197,7 @@ defmodule SlotTest do
Content 2
Content 2.1
Content 3
<div surface-cid="stateful" data-phx-component="1">Stateful</div>
<div data-phx-component="1">Stateful</div>
</div>
</div>
"""
Expand Down Expand Up @@ -338,7 +333,7 @@ defmodule SlotTest do

assert_html(
render_live(code, assigns) =~ """
<table surface-cid="table">
<table>
<tr>
<th>ID</th><th>NAME</th>
</tr><tr>
Expand Down Expand Up @@ -370,7 +365,7 @@ defmodule SlotTest do

assert_html(
render_live(code, assigns) =~ """
<table surface-cid="table">
<table>
<tr>
<th>ID</th><th>NAME</th>
</tr><tr>
Expand Down
6 changes: 3 additions & 3 deletions test/translator_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ defmodule TranslatorTest do
translated = Surface.Translator.run(code, 0, __ENV__)

assert translated =~ """
click: (event_value(\"click\", \"click_event\", assigns[:__surface_cid__]))\
click: (event_value(\"click\", \"click_event\", assigns[:myself]))\
"""
end

Expand All @@ -115,7 +115,7 @@ defmodule TranslatorTest do
label: "label",
disabled: true,
click:
(event_value(\"click\", "event", assigns[:__surface_cid__]))
(event_value(\"click\", "event", assigns[:myself]))
}, Button) %>\
"""
end
Expand All @@ -137,7 +137,7 @@ defmodule TranslatorTest do
label: "label",
disabled: true,
click:
(event_value(\"click\", "event", assigns[:__surface_cid__]))
(event_value(\"click\", "event", assigns[:myself]))
}, Button) %>\
"""
end
Expand Down

0 comments on commit 262491f

Please sign in to comment.