-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlive_vue.ex
195 lines (165 loc) · 5.7 KB
/
live_vue.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
defmodule LiveVue do
@moduledoc """
See README.md for installation instructions and usage.
"""
use Phoenix.Component
import Phoenix.HTML
alias Phoenix.LiveView
alias LiveVue.Slots
alias LiveVue.SSR
require Logger
@ssr_default Application.compile_env(:live_vue, :ssr, true)
defmacro __using__(_opts) do
quote do
import LiveVue
end
end
# TODO - commented out because it's impossible to make :rest accept all attrs without a warning
# attr(
# :"v-component",
# :string,
# required: true,
# doc: "Name of the Vue component",
# examples: ["YourComponent", "directory/Example"]
# )
# attr(
# :id,
# :string,
# default: nil,
# doc:
# "Explicit id of a wrapper component. If not provided, a random one will be generated. Useful to keep ID consistent in development.",
# examples: ["vue-1"]
# )
# attr(
# :class,
# :string,
# default: nil,
# doc: "Class to apply to the Vue component",
# examples: ["my-class", "my-class another-class"]
# )
# attr(
# :"v-ssr",
# :boolean,
# default: Application.compile_env(:live_vue, :ssr, true),
# doc: "Whether to render the component on the server",
# examples: [true, false]
# )
# attr(
# :"v-socket",
# :map,
# default: nil,
# doc: "LiveView socket, should be provided when rendering inside LiveView"
# )
# attr :rest, :global
def vue(assigns) do
init = assigns.__changed__ == nil
dead = assigns[:"v-socket"] == nil or not LiveView.connected?(assigns[:"v-socket"])
render_ssr? = init and dead and Map.get(assigns, :"v-ssr", @ssr_default)
# we manually compute __changed__ for the computed props and slots so it's not sent without reason
{props, props_changed?} = extract(assigns, :props)
{slots, slots_changed?} = extract(assigns, :slots)
{handlers, handlers_changed?} = extract(assigns, :handlers)
assigns =
assigns
|> Map.put_new(:class, nil)
|> Map.put(:__component_name, Map.get(assigns, :"v-component"))
|> Map.put(:props, props)
|> Map.put(:handlers, handlers)
|> Map.put(:slots, if(slots_changed?, do: Slots.rendered_slot_map(slots), else: %{}))
assigns =
Map.put(assigns, :ssr_render, if(render_ssr?, do: ssr_render(assigns), else: nil))
computed_changed =
%{
props: props_changed?,
slots: slots_changed?,
handlers: handlers_changed?,
ssr_render: render_ssr?
}
assigns =
update_in(assigns.__changed__, fn
nil -> nil
changed -> for {k, true} <- computed_changed, into: changed, do: {k, true}
end)
# optimizing diffs by using string interpolation
# https://elixirforum.com/t/heex-attribute-value-in-quotes-send-less-data-than-values-in-braces/63274
~H"""
<%= raw(@ssr_render[:preloadLinks]) %>
<div
id={assigns[:id] || id(@__component_name)}
data-name={@__component_name}
data-props={"#{json(@props)}"}
data-ssr={(@ssr_render != nil) |> to_string()}
data-handlers={"#{for({k, v} <- @handlers, into: %{}, do: {k, json(v.ops)}) |> json()}"}
data-slots={"#{@slots |> Slots.base_encode_64() |> json}"}
phx-update="ignore"
phx-hook="VueHook"
phx-no-format
class={@class}
><%= raw(@ssr_render[:html]) %></div>
"""
end
defp extract(assigns, type) do
Enum.reduce(assigns, {%{}, false}, fn {key, value}, {acc, changed} ->
case normalize_key(key, value) do
^type -> {Map.put(acc, key, value), changed || key_changed(assigns, key)}
{^type, k} -> {Map.put(acc, k, value), changed || key_changed(assigns, key)}
_ -> {acc, changed}
end
end)
end
defp normalize_key(key, _val) when key in ~w"id class v-ssr v-component v-socket __changed__ __given__"a, do: :special
defp normalize_key(_key, [%{__slot__: _}]), do: :slots
defp normalize_key(key, val) when is_atom(key), do: key |> to_string() |> normalize_key(val)
defp normalize_key("v-on:" <> key, _val), do: {:handlers, key}
defp normalize_key(_key, _val), do: :props
defp key_changed(%{__changed__: nil}, _key), do: true
defp key_changed(%{__changed__: changed}, key), do: changed[key] != nil
defp ssr_render(assigns) do
try do
name = assigns[:"v-component"]
case SSR.render(name, assigns.props, assigns.slots) do
{:error, message} ->
Logger.error("Vue SSR error: #{message}")
nil
%{preloadLinks: links, html: html} ->
%{preloadLinks: links, html: html}
end
rescue
SSR.NotConfigured ->
nil
end
end
defp json(data), do: Jason.encode!(data, escape: :html_safe)
defp id(name) do
# a small trick to avoid collisions of IDs but keep them consistent across dead and live render
# id(name) is called only once during the whole LiveView lifecycle because it's not using any assigns
number = Process.get(:live_vue_counter, 1)
Process.put(:live_vue_counter, number + 1)
"#{name}-#{number}"
end
@doc false
def get_socket(assigns) do
case get_in(assigns, [:vue_opts, :socket]) || assigns[:socket] do
%LiveView.Socket{} = socket -> socket
_ -> nil
end
end
@doc false
defmacro sigil_V({:<<>>, _meta, [string]}, []) do
path = "./assets/vue/_build/#{__CALLER__.module}.vue"
with :ok <- File.mkdir_p(Path.dirname(path)) do
File.write!(path, string)
end
quote do
~H"""
<LiveVue.vue
class={get_in(assigns, [:vue_opts, :class])}
v-component={"_build/#{__MODULE__}"}
v-socket={get_socket(assigns)}
v-ssr={get_in(assigns, [:vue_opts, :ssr]) != false}
{Map.drop(assigns, [:vue_opts, :socket, :flash, :live_action])}
/>
"""
end
end
end