/
utils.ex
396 lines (322 loc) · 11.6 KB
/
utils.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
defmodule Phoenix.LiveView.Utils do
# Shared helpers used mostly by Channel and Diff,
# but also Static, and LiveViewTest.
@moduledoc false
alias Phoenix.LiveView.Rendered
alias Phoenix.LiveView.Socket
# All available mount options
@mount_opts [:temporary_assigns, :layout]
@max_flash_age :timer.seconds(60)
@doc """
Assigns a value if it changed change.
"""
def assign(%Socket{} = socket, key, value) do
case socket do
%{assigns: %{^key => ^value}} -> socket
%{} -> force_assign(socket, key, value)
end
end
@doc """
Forces an assign.
"""
def force_assign(%Socket{assigns: assigns, changed: changed} = socket, key, val) do
current_val = Map.get(assigns, key)
# If the current value is a map, we store it in changed so
# we can perform nested change tracking. Also note the use
# of put_new is important. We want to keep the original value
# from assigns and not any intermediate ones that may appear.
new_changed = Map.put_new(changed, key, if(is_map(current_val), do: current_val, else: true))
new_assigns = Map.put(assigns, key, val)
%{socket | assigns: new_assigns, changed: new_changed}
end
@doc """
Clears the changes from the socket assigns.
"""
def clear_changed(%Socket{private: private, assigns: assigns} = socket) do
temporary = Map.get(private, :temporary_assigns, %{})
%Socket{socket | changed: %{}, assigns: Map.merge(assigns, temporary)}
end
@doc """
Checks if the socket changed.
"""
def changed?(%Socket{changed: changed}), do: changed != %{}
@doc """
Checks if the given assign changed.
"""
def changed?(%Socket{changed: %{} = changed}, assign), do: Map.has_key?(changed, assign)
def changed?(%Socket{}, _), do: false
@doc """
Configures the socket for use.
"""
def configure_socket(%Socket{id: nil} = socket, private, action, flash, host_uri) do
%{
socket
| id: random_id(),
private: private,
assigns: configure_assigns(socket.assigns, socket.view, action, flash),
host_uri: prune_uri(host_uri)
}
end
def configure_socket(%Socket{} = socket, private, action, flash, host_uri) do
assigns = configure_assigns(socket.assigns, socket.view, action, flash)
%{socket | host_uri: prune_uri(host_uri), private: private, assigns: assigns}
end
defp configure_assigns(assigns, view, action, flash) do
Map.merge(assigns, %{live_module: view, live_action: action, flash: flash})
end
defp prune_uri(:not_mounted_at_router), do: :not_mounted_at_router
defp prune_uri(url) do
%URI{host: host, port: port, scheme: scheme} = url
if host == nil do
raise "client did not send full URL, missing host in #{url}"
end
%URI{host: host, port: port, scheme: scheme}
end
@doc """
Returns a random ID with valid DOM tokens
"""
def random_id do
"phx-"
|> Kernel.<>(random_encoded_bytes())
|> String.replace(["/", "+"], "-")
end
@doc """
Prunes any data no longer needed after mount.
"""
def post_mount_prune(%Socket{} = socket) do
socket
|> clear_changed()
|> drop_private([:connect_info, :connect_params, :assign_new])
end
@doc """
Renders the view with socket into a rendered struct.
"""
def to_rendered(socket, view) do
inner_content =
render_assigns(socket)
|> view.render()
|> check_rendered!(view)
case layout(socket, view) do
{layout_mod, layout_template} ->
socket = assign(socket, :inner_content, inner_content)
layout_template
|> layout_mod.render(render_assigns(socket))
|> check_rendered!(layout_mod)
false ->
inner_content
end
end
defp check_rendered!(%Rendered{} = rendered, _view), do: rendered
defp check_rendered!(other, view) do
raise RuntimeError, """
expected #{inspect(view)} to return a %Phoenix.LiveView.Rendered{} struct
Ensure your render function uses ~L, or your eex template uses the .leex extension.
Got:
#{inspect(other)}
"""
end
@doc """
Returns the socket's flash messages.
"""
def get_flash(%Socket{assigns: assigns}), do: assigns.flash
def get_flash(%{} = flash, key), do: flash[key]
@doc """
Puts a new flash with the socket's flash messages.
"""
def replace_flash(%Socket{} = socket, %{} = new_flash) do
assign(socket, :flash, new_flash)
end
@doc """
Clears the flash.
"""
def clear_flash(%Socket{} = socket), do: assign(socket, :flash, %{})
@doc """
Clears the key from the flash.
"""
def clear_flash(%Socket{} = socket, key) do
key = flash_key(key)
new_flash = Map.delete(socket.assigns.flash, key)
assign(socket, :flash, new_flash)
end
@doc """
Puts a flash message in the socket.
"""
def put_flash(%Socket{assigns: assigns} = socket, kind, msg) do
kind = flash_key(kind)
new_flash = Map.put(assigns.flash, kind, msg)
assign(socket, :flash, new_flash)
end
defp flash_key(binary) when is_binary(binary), do: binary
defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom)
@doc """
Returns the configured signing salt for the endpoint.
"""
def salt!(endpoint) when is_atom(endpoint) do
endpoint.config(:live_view)[:signing_salt] ||
raise ArgumentError, """
no signing salt found for #{inspect(endpoint)}.
Add the following LiveView configuration to your config/config.exs:
config :my_app, MyAppWeb.Endpoint,
...,
live_view: [signing_salt: "#{random_encoded_bytes()}"]
"""
end
@doc """
Returns the internal or external matched LiveView route info for the given uri
"""
def live_link_info!(%Socket{router: nil}, view, _uri) do
raise ArgumentError,
"cannot invoke handle_params/3 on #{inspect(view)} " <>
"because it is not mounted nor accessed through the router live/3 macro"
end
def live_link_info!(%Socket{router: router, endpoint: endpoint} = socket, view, uri) do
%URI{host: host, path: path, query: query} = parsed_uri = URI.parse(uri)
host = host || socket.host_uri.host
query_params = if query, do: Plug.Conn.Query.decode(query), else: %{}
decoded_path = URI.decode(path || "")
split_path = for segment <- String.split(decoded_path, "/"), segment != "", do: segment
route_path = strip_segments(endpoint.script_name(), split_path) || split_path
case Phoenix.Router.route_info(router, "GET", route_path, host) do
%{plug: Phoenix.LiveView.Plug, phoenix_live_view: {^view, action}, path_params: path_params} ->
{:internal, Map.merge(query_params, path_params), action, parsed_uri}
%{} ->
{:external, parsed_uri}
:error ->
raise ArgumentError,
"cannot invoke handle_params nor live_redirect/live_patch to #{inspect(uri)} " <>
"because it isn't defined in #{inspect(router)}"
end
end
defp strip_segments([head | tail1], [head | tail2]), do: strip_segments(tail1, tail2)
defp strip_segments([], tail2), do: tail2
defp strip_segments(_, _), do: nil
@doc """
Raises error message for bad live patch on mount.
"""
def raise_bad_mount_and_live_patch!() do
raise RuntimeError, """
attempted to live patch while mounting.
a LiveView cannot be mounted while issuing a live patch to the client. \
Use push_redirect/2 or redirect/2 instead if you wish to mount and redirect.
"""
end
@doc """
Calls the optional `mount/N` callback, otherwise returns the socket as is.
"""
def maybe_call_mount!(socket, view, args) do
arity = length(args)
if function_exported?(view, :mount, arity) do
case apply(view, :mount, args) do
{:ok, %Socket{} = socket, opts} when is_list(opts) ->
validate_mount_redirect!(socket.redirected)
Enum.reduce(opts, socket, fn {key, val}, acc -> mount_opt(acc, key, val, arity) end)
{:ok, %Socket{} = socket} ->
validate_mount_redirect!(socket.redirected)
socket
other ->
raise ArgumentError, """
invalid result returned from #{inspect(view)}.mount/#{length(args)}.
Expected {:ok, socket} | {:ok, socket, opts}, got: #{inspect(other)}
"""
end
else
socket
end
end
defp validate_mount_redirect!({:live, {_, _}, _}), do: raise_bad_mount_and_live_patch!()
defp validate_mount_redirect!(_), do: :ok
@doc """
Calls the optional `update/2` callback, otherwise update the socket directly.
"""
def maybe_call_update!(socket, component, assigns) do
if function_exported?(component, :update, 2) do
socket =
case component.update(assigns, socket) do
{:ok, %Socket{} = socket} ->
socket
other ->
raise ArgumentError, """
invalid result returned from #{inspect(component)}.update/2.
Expected {:ok, socket}, got: #{inspect(other)}
"""
end
if socket.redirected do
raise "cannot redirect socket on update/2"
end
socket
else
Enum.reduce(assigns, socket, fn {k, v}, acc -> assign(acc, k, v) end)
end
end
@doc """
Signs the socket's flash into a token if it has been set.
"""
def sign_flash(endpoint_mod, %{} = flash) do
Phoenix.Token.sign(endpoint_mod, flash_salt(endpoint_mod), flash)
end
@doc """
Verifies the socket's flash token.
"""
def verify_flash(endpoint_mod, flash_token) do
salt = flash_salt(endpoint_mod)
case Phoenix.Token.verify(endpoint_mod, salt, flash_token, max_age: @max_flash_age) do
{:ok, flash} -> flash
{:error, _reason} -> %{}
end
end
defp random_encoded_bytes do
binary = <<
System.system_time(:nanosecond)::64,
:erlang.phash2({node(), self()})::16,
:erlang.unique_integer()::16
>>
Base.url_encode64(binary)
end
defp mount_opt(%Socket{} = socket, key, val, _arity) when key in @mount_opts do
do_mount_opt(socket, key, val)
end
defp mount_opt(%Socket{view: view}, key, val, arity) do
raise ArgumentError, """
invalid option returned from #{inspect(view)}.mount/#{arity}.
Expected keys to be one of #{inspect(@mount_opts)}
got: #{inspect(key)}: #{inspect(val)}
"""
end
defp do_mount_opt(socket, :layout, {mod, template}) when is_atom(mod) and is_binary(template) do
%Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, {mod, template})}
end
defp do_mount_opt(socket, :layout, false) do
%Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, false)}
end
defp do_mount_opt(_socket, :layout, bad_layout) do
raise ArgumentError,
"the :layout mount option expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <>
"got: #{inspect(bad_layout)}"
end
defp do_mount_opt(socket, :temporary_assigns, temp_assigns) do
unless Keyword.keyword?(temp_assigns) do
raise "the :temporary_assigns mount option must be keyword list"
end
temp_assigns = Map.new(temp_assigns)
%Socket{
socket
| assigns: Map.merge(temp_assigns, socket.assigns),
private: Map.put(socket.private, :temporary_assigns, temp_assigns)
}
end
defp drop_private(%Socket{private: private} = socket, keys) do
%Socket{socket | private: Map.drop(private, keys)}
end
defp render_assigns(socket) do
Map.put(socket.assigns, :socket, %Socket{socket | assigns: %Socket.AssignsNotInSocket{}})
end
defp layout(socket, view) do
case socket.private do
%{phoenix_live_layout: layout} -> layout
%{} -> view.__live__()[:layout] || false
end
end
defp flash_salt(endpoint_mod) when is_atom(endpoint_mod) do
"flash:" <> salt!(endpoint_mod)
end
end