/
phoenix_live_view.ex
1688 lines (1279 loc) · 64.6 KB
/
phoenix_live_view.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Phoenix.LiveView do
@moduledoc ~S'''
LiveView provides rich, real-time user experiences with
server-rendered HTML.
LiveView programming model is declarative: instead of
saying "once event X happens, change Y on the page",
events in LiveView are regular messages which may cause
changes to its state. Once the state changes, LiveView will
re-render the relevant parts of its HTML template and push it
to the browser, which updates itself in the most efficient
manner. This means developers write LiveView templates as
any other server-rendered HTML and LiveView does the hard
work of tracking changes and sending the relevant diffs to
the browser.
At the end of the day, a LiveView is nothing more than a
process that receives events as messages and updates its
state. The state itself is nothing more than functional
and immutable Elixir data structures. The events are either
internal application messages (usually emitted by `Phoenix.PubSub`)
or sent by the client/browser.
LiveView provides many features that make it excellent
to build rich, real-time user experiences:
* By building on top of Elixir processes and
`Phoenix.Channels`, LiveView scales well vertically
(from small to large instances) and horizontally
(by adding more instances);
* LiveView is first rendered statically as part of
regular HTTP requests, which provides quick times
for "First Meaningful Paint", in addition to helping
search and indexing engines;
* LiveView performs diff tracking. If the LiveView
state changes, it will only re-render those changes.
This reduces latency and the amount of data sent over
the wire;
* LiveView tracks static and dynamic content. Any
server-rendered HTML is made of static parts (i.e.
that never change) and dynamic ones. On the first
render, LiveView sends the static content and in
future updates only the modified dynamic content
is resent;
* (Coming soon) LiveView uses the Erlang Term Format
to send messages to the client. This binary-based
format is quite efficient on the server and uses
less data over the wire;
* (Coming soon) LiveView includes a latency simulator,
which allows you to simulate how your application
would behave with greater latency and guides you to provide
meaningful feedback to users while they wait for events
to be processed;
Furthermore, by keeping a persistent connection between client
and server, LiveView applications can react faster to user events
as there is less work to be done and less data to be sent compared
to stateless requests that have to authenticate, decode, load,
and encode data on every request. The flipside is that LiveView
uses more memory on the server compared to stateless requests.
## Use cases
There are many use cases where LiveView is an excellent
fit right now:
* Handling of user interaction and inputs, buttons, and
forms - such as input validation, dynamic forms,
autocomplete, etc;
* Events and updates pushed by server - such as
notifications, dashboards, etc;
* Page and data navigation - such as navigating between
pages, pagination, etc can be built with LiveView
but currently you will lose the back/forward button,
and the ability to link to pages as you navigate.
Support for `pushState` is on the roadmap;
There are other cases that have limited support but
will become first-class as we further develop LiveView:
* Transitions and loading states - the LiveView
programming model provides a good foundation for
transitions and loading states since any UI change
done after a user action is undone once the server
sends the update for said action. For example, it is
relatively straight-forward to click a button that
changes itself in a way that is automatically undone
when the update arrives. This is especially important
as user feedback when latency is involved. A complete
feature set for modelling those states is coming in
future versions;
* Optimistic UIs - once we add transitions and loading
states, many of the building blocks necessary for
building optimistic UIs will be part of LiveView, but
since optimistic UIs are about doing work on the client
while the server is unavailable, complete support for
Optimistic UIs cannot be achieved without also writing
JavaScript for the cases the server is not available.
See "JS Interop and client-controlled DOM" on how to
integrate JS hooks;
There are also use cases which are a bad fit for LiveView:
* Animations - animations, menus, and general events
that do not need the server in the first place are a
bad fit for LiveView, as they can be achieved purely
with CSS and/or CSS transitions;
## Life-cycle
A LiveView begins as a regular HTTP request and HTML response,
and then upgrades to a stateful view on client connect,
guaranteeing a regular HTML page even if JavaScript is disabled.
Any time a stateful view changes or updates its socket assigns, it is
automatically re-rendered and the updates are pushed to the client.
You begin by rendering a LiveView from your router, controller, or
view. When a view is first rendered, the `mount/3` callback is invoked
with the current params, the current session and the LiveView socket.
As in a regular request, `params` contains public data that can be
modified by the user. The `session` always contains private data set
by the application itself. The `mount/3` callback wires up socket
assigns necessary for rendering the view. After mounting, `render/1`
is invoked and the HTML is sent as a regular HTML response to the
client.
After rendering the static page, LiveView connects from the client
where stateful views are spawned to push rendered updates to the
browser, and receive client events via phx bindings. Just like
the first rendering, `mount/3` is invoked with params, session,
and socket state, where mount assigns values for rendering. However
in the connected client case, a LiveView process is spawned on
the server, pushes the result of `render/1` to the client and
continues on for the duration of the connection. If at any point
during the stateful life-cycle a crash is encountered, or the client
connection drops, the client gracefully reconnects to the server,
calling `mount/3` once again.
## Example
First, a LiveView requires two callbacks: `mount/3` and `render/1`:
defmodule AppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
~L"""
Current temperature: <%= @temperature %>
"""
end
def mount(_params, %{"current_user_id" => user_id}, socket) do
temperature = Thermostat.get_user_reading(user_id)
{:ok, assign(socket, :temperature, temperature)}
end
end
The `render/1` callback receives the `socket.assigns` and is responsible
for returning rendered content. You can use `Phoenix.LiveView.sigil_L/2`
to inline LiveView templates. If you want to use `Phoenix.HTML` helpers,
remember to `use Phoenix.HTML` at the top of your `LiveView`.
A separate `.leex` HTML template can also be rendered within
your `render/1` callback by delegating to an existing `Phoenix.View`
module in your application. For example:
defmodule AppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
Phoenix.View.render(AppWeb.PageView, "page.html", assigns)
end
end
With a LiveView defined, you first define the `socket` path in your endpoint,
and point it to `Phoenix.LiveView.Socket`:
defmodule AppWeb.Endpoint do
use Phoenix.Endpoint
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]
...
end
Where `@session_options` are the options given to `plug Plug.Session` extracted
to a module attribute.
And configure its signing salt in the endpoint:
config :my_app, AppWeb.Endpoint,
...,
live_view: [signing_salt: ...]
You can generate a secure, random signing salt with the `mix phx.gen.secret 32` task.
Next, decide where you want to use your LiveView.
You can serve the LiveView directly from your router (recommended):
defmodule AppWeb.Router do
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", AppWeb do
live "/thermostat", ThermostatLive
end
end
You can also `live_render` from any template:
<h1>Temperature Control</h1>
<%= live_render(@conn, AppWeb.ThermostatLive) %>
Or you can `live_render` your view from any controller:
defmodule AppWeb.ThermostatController do
...
import Phoenix.LiveView.Controller
def show(conn, %{"id" => id}) do
live_render(conn, AppWeb.ThermostatLive)
end
end
When a LiveView is rendered, all of the data currently stored in the
connection session (see `Plug.Conn.get_session/1`) will be given to
the LiveView.
It is also possible to pass additional session information to the LiveView
through a session parameter:
# In the router
live "/thermostat", ThermostatLive, session: %{"extra_token" => "foo"}
# In a view
<%= live_render(@conn, AppWeb.ThermostatLive, session: %{"extra_token" => "foo"}) %>
Notice the `:session` uses string keys as a reminder that session data
is serialized and sent to the client. So you should always keep the data
in the session to a minimum. I.e. instead of storing a User struct, you
should store the "user_id" and load the User when the LiveView mounts.
Once the LiveView is rendered, a regular HTML response is sent. Next, your
client code connects to the server:
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", {params: {_csrf_token: csrfToken}});
liveSocket.connect()
*Note*: Comprehensive JavaScript client usage is covered in a later section.
After the client connects, `mount/3` will be invoked inside a spawned
LiveView process. At this point, you can use `connected?/1` to
conditionally perform stateful work, such as subscribing to pubsub topics,
sending messages, etc. For example, you can periodically update a LiveView
with a timer:
defmodule DemoWeb.ThermostatLive do
use Phoenix.LiveView
...
def mount(_params, %{"current_user_id" => user_id}, socket) do
if connected?(socket), do: :timer.send_interval(30000, self(), :update)
case Thermostat.get_user_reading(user_id) do
{:ok, temperature} ->
{:ok, assign(socket, temperature: temperature, user_id: user_id)}
{:error, reason} ->
{:error, reason}
end
end
def handle_info(:update, socket) do
{:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id)
{:noreply, assign(socket, :temperature, temperature)}
end
end
We used `connected?(socket)` on mount to send our view a message every 30s if
the socket is in a connected state. We receive `:update` in a
`handle_info` just like a GenServer, and update our socket assigns. Whenever
a socket's assigns change, `render/1` is automatically invoked, and the
updates are sent to the client.
## Assigns and LiveEEx Templates
All of the data in a LiveView is stored in the socket as assigns.
The `assign/2` and `assign/3` functions help store those values.
Those values can be accessed in the LiveView as `socket.assigns.name`
but they are most commonly accessed inside LiveView templates as
`@name`.
`Phoenix.LiveView`'s built-in templates are identified by the `.leex`
extension (Live EEx) or `~L` sigil. They are similar to regular `.eex`
templates except they are designed to minimize the amount of data sent
over the wire by splitting static and dynamic parts and tracking changes.
When you first render a `.leex` template, it will send all of the
static and dynamic parts of the template to the client. After that,
any change you do on the server will now send only the dynamic parts,
and only if those parts have changed.
The tracking of changes is done via assigns. Imagine this template:
<div id="user_<%= @user.id %>">
<%= @user.name %>
</div>
If the `@user` assign changes, then LiveView will re-render only
the `@user.id` and `@user.name` and send them to the browser.
The change tracking also works when rendering other templates, as
long as they are also `.leex` templates and as long as all assigns
are passed to the child/inner template:
<%= render "child_template.html", assigns %>
The assign tracking feature also implies that you MUST avoid performing
direct operations in the template. For example, if you perform a database
query in your template:
<%= for user <- Repo.all(User) do %>
<%= user.name %>
<% end %>
Then Phoenix will never re-render the section above, even if the number of
users in the database changes. Instead, you need to store the users as
assigns in your LiveView before it renders the template:
assign(socket, :users, Repo.all(User))
Generally speaking, **data loading should never happen inside the template**,
regardless if you are using LiveView or not. The difference is that LiveView
enforces this best practice.
### Change tracking pitfalls
Although change tracking can considerably reduce the amount of data sent
over the wire, there are some pitfalls users should be aware of.
First of all, change tracking can only track assigns. So for example,
if you do something such as:
<%= @post.the_whole_content %>
If any other field besides `the_whole_content` in `@post` changes for any
reason, `the_whole_content` will be sent downstream. Although this is not
generally a problem, if you have large fields that you don't want to resend
or if you have one field in particular that changes all the time while others
do not, you may want to track them as their own assign.
Another limitation of changing tracking is that it does not work across regular
function calls. For example, imagine the following template that renders a `div`:
<%= content_tag :div, id: "user_#{@id}" do %>
<%= @name %>
<%= @description %>
<% end %>
LiveView knows nothing about `content_tag`, which means the whole `div` will be
sent whenever any of the assigns change. This can be easily fixed by writing the
HTML directly:
<div id="user_<%= @id %>">
<%= @name %>
<%= @description %>
</div>
Note though this concern does not apply to Elixir's constructs, such as `if`,
`case`, `for`, and friends. LiveView always knows how to optimize across those.
## Bindings
Phoenix supports DOM element bindings for client-server interaction. For
example, to react to a click on a button, you would render the element:
<button phx-click="inc_temperature">+</button>
Then on the server, all LiveView bindings are handled with the `handle_event`
callback, for example:
def handle_event("inc_temperature", _value, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
| Binding | Attributes |
|------------------------|------------|
| [Params](#module-click-events) | `phx-value-*` |
| [Click Events](#module-click-events) | `phx-click`, `phx-capture-click` | `phx-target` |
| [Focus/Blur Events](#module-focus-and-blur-events) | `phx-blur`, `phx-focus`, `phx-target` |
| [Form Events](#module-form-events) | `phx-change`, `phx-submit`, `phx-target`, `data-phx-error-for`, `phx-disable-with` |
| [Key Events](#module-key-events) | `phx-keydown`, `phx-keyup`, `phx-target` |
| [Rate Limiting](#module-rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` |
| [DOM Patching](#module-dom-patching-and-temporary-assigns) | `phx-update` |
| [JS Interop](#module-js-interop-and-client--controlled-dom) | `phx-hook` |
### Click Events
The `phx-click` binding is used to send click events to the server.
When any client event, such as a `phx-click` click is pushed, the value
sent to the server will be chosen with the following priority:
* Any number of optional `phx-value-` prefixed attributes, such as:
<div phx-click="inc" phx-value-myvar1="val1" phx-value-myvar2="val2">
will send the following map of params to the server:
def handle_event("inc", %{"myvar1" => "val1", "myvar2" => "val2"}, socket) do
If the `phx-value-` prefix is used, the server payload will also contain a `"value"`
if the element's value attribute exists.
* When receiving a map on the server, the payload will also contain metadata of the
client event, containing all literal keys of the event object, such as a click event's
`clientX`, a keydown event's `keyCode`, etc.
The `phx-capture-click` event is just like `phx-click`, but instead of the click event
bubbling up to the closest `phx-click` element, event capturing is used, where the
events propagate inwards from the clicked element. This is useful when wanting to bind a click
events without receiving bubbled events from child UI elements.
### Focus and Blur Events
Focus and blur events may be bound to DOM elements that emit
such events, using the `phx-blur`, and `phx-focus` bindings, for example:
<input name="email" phx-focus="myfocus" phx-blur="myblur"/>
To detect when the page itself has received focus or blur,
`phx-window-focus` and `phx-window-blur` may be specified. These window
level events may also be necessary if the element in consideration
(most often a `div` with no tabindex) cannot receive focus. Like other
bindings, `phx-value-*` can be provided on the bound element, and those
values will be sent as part of the payload. For example:
<div class="container"
phx-window-focus="page-active"
phx-window-blur="page-inactive"
phx-value-page="123">
...
</div>
The following window-level bindings are supported:
* `phx-window-focus`
* `phx-window-blur`
* `phx-window-keydown`
* `phx-window-keyup`
### Form Events
To handle form changes and submissions, use the `phx-change` and `phx-submit`
events. In general, it is preferred to handle input changes at the form level,
where all form fields are passed to the LiveView's callback given any
single input change. For example, to handle real-time form validation and
saving, your template would use both `phx_change` and `phx_submit` bindings:
<%= f = form_for @changeset, "#", [phx_change: :validate, phx_submit: :save] %>
<%= label f, :username %>
<%= text_input f, :username %>
<%= error_tag f, :username %>
<%= label f, :email %>
<%= text_input f, :email %>
<%= error_tag f, :email %>
<%= submit "Save" %>
</form>
Next, your LiveView picks up the events in `handle_event` callbacks:
def render(assigns) ...
def mount(_params, _session, socket) do
{:ok, assign(socket, %{changeset: Accounts.change_user(%User{})})}
end
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> Accounts.change_user(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.create_user(user_params) do
{:ok, user} ->
{:stop,
socket
|> put_flash(:info, "user created")
|> redirect(to: Routes.user_path(AppWeb.Endpoint, AppWeb.User.ShowView, user))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
The validate callback simply updates the changeset based on all form input
values, then assigns the new changeset to the socket. If the changeset
changes, such as generating new errors, `render/1` is invoked and
the form is re-rendered.
Likewise for `phx-submit` bindings, the same callback is invoked and
persistence is attempted. On success, a `:stop` tuple is returned and the
socket is annotated for redirect with `Phoenix.LiveView.redirect/2` to
the new user page, otherwise the socket assigns are updated with the errored
changeset to be re-rendered for the client.
*Note*: For proper form error tag updates, the error tag must specify which
input it belongs to. This is accomplished with the `data-phx-error-for` attribute.
Failing to add the `data-phx-error-for` attribute will result in displaying error
messages for form fields that the user has not changed yet (e.g. required
fields further down on the page.)
For example, your `AppWeb.ErrorHelpers` may use this function:
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error),
class: "help-block",
data: [phx_error_for: input_id(form, field)]
)
end)
end
### Number inputs
Number inputs are a special case in LiveView forms. On programmatic updates,
some browsers will clear invalid inputs. So LiveView will not send change events
from the client when an input is invalid, instead allowing the browser's native
validation UI to drive user interaction. Once the input becomes valid, change and
submit events will be sent normally.
### Password inputs
Password inputs are also special cased in `Phoenix.HTML`. For security reasons,
password field values are not reused when rendering a password input tag. This
requires explicitly setting the `:value` in your markup, for example:
<%= password_input f, :password, value: input_value(f, :password) %>
<%= password_input f, :password_confirmation, value: input_value(f, :password_confirmation) %>
<%= error_tag f, :password %>
<%= error_tag f, :password_confirmation %>
### Key Events
The `onkeydown`, and `onkeyup` events are supported via
the `phx-keydown`, and `phx-keyup` bindings. When
pushed, the value sent to the server will contain all the client event
object's metadata. For example, pressing the Escape key looks like this:
%{
"altKey" => false, "code" => "Escape", "ctrlKey" => false, "key" => "Escape",
"location" => 0, "metaKey" => false, "repeat" => false, "shiftKey" => false
}
To determine which key has been pressed you should use `key` value. The
available options can be found on
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)
or via the [Key Event Viewer](https://w3c.github.io/uievents/tools/key-event-viewer.html).
By default, the bound element will be the event listener, but a
window-level binding may be provided via `phx-window-keydown`,
for example:
def render(assigns) do
~L"""
<div id="thermostat" phx-window-keyup="update_temp">
Current temperature: <%= @temperature %>
</div>
"""
end
def handle_event("update_temp", %{"code" => "ArrowUp"}, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", %{"code" => "ArrowDown"}, socket) do
{:ok, new_temp} = Thermostat.dec_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", _key, socket) do
{:noreply, socket}
end
### LiveView Specific Events
The `lv:` event prefix supports LiveView specific features that are handled
by LiveView without calling the user's `handle_event/3` callbacks. Today,
the follow events are supported:
- `lv:clear-flash` – clears the flash when send to the server. If a
`phx-value-key` is provided, the specific key will be removed from the flash.
For example:
<p class="alert" phx-click="lv:clear-flash" phx-value-key="info">
<%= live_flash(@flash, :info) %>
</p>
## Compartmentalizing markup and events with `render`, `live_render`, and `live_component`
We can render another template directly from a LiveView template by simply
calling `render`:
render "child_template", assigns
render SomeOtherView, "child_template", assigns
If the other template has the `.leex` extension, LiveView change tracking
will also work across templates.
When rendering a child template, any of the events bound in the child
template will be sent to the parent LiveView. In other words, similar to
regular Phoenix templates, a regular `render` call does not start another
LiveView. This means `render` is useful to sharing markup between views.
One option to address this problem is to render a child LiveView inside a
parent LiveView by calling `live_render/3` instead of `render/3` from the
LiveView template. This child LiveView runs in a completely separate process
than the parent, with its own `mount` and `handle_event` callbacks. If a
child LiveView crashes, it won't affect the parent. If the parent crashes,
all children are terminated.
When rendering a child LiveView, the `:id` option is required to uniquely
identify the child. A child LiveView will only ever be rendered and mounted
a single time, provided its ID remains unchanged. Updates to a child session
will be merged on the client, but not passed back up until either a crash and
re-mount or a connection drop and recovery. To force a child to re-mount with
new session data, a new ID must be provided.
Given that a LiveView runs on its own process, it is an excellent tool for creating
completely isolated UI elements, but it is a slightly expensive abstraction if
all you want is to compartmentalize markup and events. For example, if you are
showing a table with all users in the system, and you want to compartmentalize
this logic, using a separate `LiveView`, each with its own process, would likely
be too expensive. For these cases, LiveView provides `Phoenix.LiveComponent`,
which are rendered using `live_component/3`:
<%= live_component(@socket, UserComponent, id: user.id, user: user) %>
Components have their own `mount` and `handle_event` callbacks, as well as their
own state with change tracking support. Components are also lightweight as they
"run" in the same process as the parent `LiveView`. However, this means an error
in a component would cause the whole view to fail to render. See
`Phoenix.LiveComponent` for a complete rundown on components.
To sum it up:
* `render` - compartmentalizes markup
* `live_component` - compartmentalizes state, markup, and events
* `live_render` - compartmentalizes state, markup, events, and error isolation
## Rate limiting events with Debounce and Throttle
All events can be rate-limited on the client by using the
`phx-debounce` and `phx-throttle` bindings, with the following behavior:
* `phx-debounce` - Accepts either a string integer timeout value, or `"blur"`.
When an int is provided, delays emitting the event by provided milliseconds.
When `"blur"` is provided, delays emitting an input's change event until the
field is blurred by the user.
* `phx-throttle` - Accepts an integer timeout value to throttle the event in milliseconds.
Unlike debounce, throttle will immediately emit the event, then rate limit the
event at one event per provided timeout.
For example, to avoid validating an email until the field is blurred, while validating
the username at most every 2 seconds after a user changes the field:
<form phx-change="validate" phx-submit="save">
<input type="text" name="user[email]" phx-debounce="blur"/>
<input type="text" name="user[username]" phx-debounce="2000"/>
</form>
And to rate limit a button click to once every second:
<button phx-click="search" phx-throttle="1000">Search</button>
Likewise, you may throttle held-down keydown:
<div phx-window-keydown="keydown" phx-throttle="500">
...
</div>
Unless held-down keys are required, a better approach is generally to use
`phx-keyup` bindings which only trigger on key up, thereby being self-limiting.
However, `phx-keydown` is useful for games and other usecases where a constant
press on a key is desired. In such cases, throttle should always be used.
### Debounce and Throttle special behavior
The following specialized behavior is performed for forms and keydown bindings:
* When a `phx-submit`, or a `phx-change` for a different
input is triggered, any current debounce or throttle timers are reset for
existing inputs.
* A `phx-keydown` binding is only throttled for key repeats. Unique keypresses
back-to-back will dispatch the pressed key events.
## DOM patching and temporary assigns
A container can be marked with `phx-update`, allowing the DOM patch
operations to avoid updating or removing portions of the LiveView, or to append
or prepend the updates rather than replacing the existing contents. This
is useful for client-side interop with existing libraries that do their
own DOM operations. The following `phx-update` values are supported:
* `replace` - the default operation. Replaces the element with the contents
* `ignore` - ignores updates to the DOM regardless of new content changes
* `append` - append the new DOM contents instead of replacing
* `prepend` - prepend the new DOM contents instead of replacing
When using `phx-update`, a unique DOM ID must always be set in the
container. If using "append" or "prepend", a DOM ID must also be set
for each child. When appending or prepending elements containing an
ID already present in the container, LiveView will replace the existing
element with the new content instead appending or prepending a new
element.
The "ignore" behaviour is frequently used when you need to integrate
with another JS library. The "append" and "prepend" feature is often
used with "Temporary assigns" to work with large amounts of data. Let's
learn more.
### Temporary assigns
By default, all LiveView assigns are stateful, which enables change
tracking and stateful interactions. In some cases, it's useful to mark
assigns as temporary, meaning they will be reset to a default value after
each update. This allows otherwise large but infrequently updated values
to be discarded after the client has been patched.
Imagine you want to implement a chat application with LiveView. You
could render each message like this:
<%= for message <- @messages do %>
<p><span><%= message.username %>:</span> <%= message.text %></p>
<% end %>
Every time there is a new message, you would append it to the `@messages`
assign and re-render all messages.
As you may suspect, keeping the whole chat conversation in memory
and resending it on every update would be too expensive, even with
LiveView smart change tracking. By using temporary assigns and phx-update,
we don't need to keep any messages in memory, and send messages to be
appended to the UI only when there are new ones.
To do so, the first step is to mark which assigns are temporary and
what values they should be reset to on mount:
def mount(_params, _session, socket) do
socket = assign(socket, :messages, load_last_20_messages())
{:ok, socket, temporary_assigns: [messages: []]}
end
On mount we also load the initial number of messages we want to
send. After the initial render, the initial batch of messages will
be reset back to an empty list.
Now, whenever there are one or more new messages, we will assign
only the new messages to `@messages`:
socket = assign(socket, :messages, new_messages)
In the template, we want to wrap all of the messages in a container
and tag this content with phx-update. Remember, we must add an ID
to the container as well as to each child:
<div id="chat-messages" phx-update="append">
<%= for message <- @messages do %>
<p id="<%= message.id %>">
<span><%= message.username %>:</span> <%= message.text %>
</p>
<% end %>
</div>
When the client receives new messages, it now knows to append to the
old content rather than replace it.
## Live navigation
LiveView provides functionality to allow page navitation using the
[browser's pushState API](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
With live navigation, the page is updated without a full page reload.
You can trigger live navigation in two ways:
* From the client - this is done by replacing `Phoenix.HTML.link/2`
by `Phoenix.LiveView.Helpers.live_patch/2` or
`Phoenix.LiveView.Helpers.live_redirect/2`
* From the server - this is done by replacing `redirect/2` calls
by `push_patch/2` or `push_redirect/2`.
For example, in a template you may write:
<%= live_patch "next", to: Routes.live_path(@socket, MyLive, @page + 1) %>
or in a LiveView:
{:noreply, push_redirect(socket, to: Routes.live_path(socket, MyLive, page + 1))}
The "patch" operations must be used when you want to navigate to the
current LiveView, simply updating the URL and the current parameters,
without mounting a new LiveView. When patch is used, the `c:handle_params/3`
callback is invoked. See the next section for more information.
The "redirect" operations must be used when you want to dismount the
current LiveView and mount a new one. In those cases, the existing root
LiveView is shutdown, and an Ajax request is made to request the necessary
information about the new LiveView without performing a full static render
(which reduces latency and improves performance). Once information is
retrieved, the new LiveView is mounted. While redirecting, a `phx-disconnected`
class is added to the root LiveView, which can be used to indicate to the
user a new page is being loaded.
`live_patch/2`, `live_redirect/2`, `push_redirect/2`, and `push_patch/2`
only work for LiveViews defined at the router with the `live/3` macro.
### `handle_params/3`
The `c:handle_params/3` callback is invoked after `c:mount/3`. It receives the
request parameters as first argument, the url as second, and the socket as third.
For example, imagine you have a `UserTable` LiveView to show all users in
the system and you define it in the router as:
live "/users", UserTable
Now to add live sorting, you could do:
<%= live_patch "Sort by name", to: Routes.live_path(@socket, UserTable, %{sort_by: "name"}) %>
When clicked, since we are navigating to the current LiveView, `c:handle_params/3`
will be invoked. Remember you should never trust the received params, so you must
use the callback to validate the user input and change the state accordingly:
def handle_params(params, _uri, socket) do
socket =
case params["sort_by"] do
sort_by when sort_by in ~w(name company) -> assign(socket, sort_by: sort)
_ -> socket
end
{:noreply, load_users(socket)}
end
As with other `handle_*` callback, changes to the state inside `c:handle_params/3`
will trigger a server render.
Note the parameters given to `c:handle_params/3` are the same as the ones given
to `c:mount/3`. So how do you decide which callback to use to load data?
Generally speaking, data should always be loaded on `c:mount/3`, since `c:mount/3`
is invoked once per LiveView life-cycle. Only the params you expect to be changed
via `live_patch/2` or `push_patch/2` must be loaded on `c:handle_params/3`.
Furthermore, it is very important to not access the same parameters on both
`c:mount/3` and `c:handle_params/3`. For example, do NOT do this:
def mount(%{"organization_id" => org_id}, session, socket) do
# do something with org_id
end
def handle_params(%{"organization_id" => org_id, "sort_by" => sort_by}, url, socket) do
# do something with org_id and sort_by
end
If you do that, because `c:mount/3` is called once and `c:handle_params/3` multiple
times, your state can get out of sync. So once a parameter is read on mount, it
should not be read elsewhere. Instead, do this:
def mount(%{"organization_id" => org_id}, session, socket) do
# do something with org_id
end
def handle_params(%{"sort_by" => sort_by}, url, socket) do
# do something with sort_by
end
### Replace page address
LiveView also allows the current browser URL to be replaced. This is useful when you
want certain events to change the URL but without polluting the browser's history.
This can be done by passing the `replace: true` option to any of the navigation helpers.
## Live Layouts
Your LiveView will be rendered within the layout specified in your Plug pipeline,
such as the default app layout. Assigns defined during `mount` of the root LiveView
are accessible in the layout, but the app layout is never updated after the initial
render. For a live layout, you must specify an additional layout to use with your
LiveView. For example, your regular `app.html` template may display a `@new_message_count`
notification, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= @page_title %></title>
</head>
<body>
<div>
<nav>
...
Messages (<%= @new_message_count %>)
</nav>
<%= render @view_module, @view_template, assigns %>
</div>
</body>
</html>
To allow the `@new_message_count` to be be updated by your LiveView, you can
move the dynamic content inside a sub-layout, such as `app_web/templates/layout/live.html.leex`.
First, you would update your `app.html` layout to keep only the barebones HTML
structure:
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
<script>...</script>
</head>
<body>
<%= render @view_module, @view_template, assigns %>
</body>
</html>
Next, define a new `live.html.leex` layout with the dynamic content,
followed by a render of the inner `@live_view_module`:
<nav>
...
Messages (<%= @new_message_count %>)
</nav>
<%= @live_view_module.render(assigns) %>
Finally, update your LiveView to pass the `:layout` option to `use Phoenix.LiveView`:
use Phoenix.LiveView, layout: {AppWeb.LayoutView, "live.html"}
Or alternatively, you can provide the `:layout` dynamically as an option in mount:
def mount(_params, _session, socket) do
socket = assign(socket, new_message_count: 0)
{:ok, socket, layout: {AppWeb.LayoutView, "live.html"}}
end
def handle_info({:new_messages, count}, socket) do
{:noreply, assign(socket, new_message_count: count)}
end
end
*Note*: The layout will be wrapped by the LiveView's `:container` tag.
### Updating the HTML document title
Because the main layout from the Plug pipeline is rendered outside of LiveView,
the contents cannot be dynamically changed. The one exception is the `<title>`
of the HTML document. Phoenix LiveView special cases the `@page_title` assign
to allow dynamically updating the title of the page, which is useful when
using live navigation, or annotating the browser tab with a notification.
For example, to update the user's notification count in the browser's title bar,
first set the `page_title` assign on mount:
def mount(_params, _session, socket) do
socket = assign(socket, page_title: "Latest Posts")
{:ok, socket}
end
Then access `@page_title` in the app layout:
<title><%= @page_title %></title>
Now, although the app layout is not updated by LiveView, by simply assigning
to `page_title`, LiveView knows you want the title to be updated:
def handle_info({:new_messages, count}, socket) do
{:noreply, assign(socket, page_title: "Latest Posts (#{count} new)")}
end