-
Notifications
You must be signed in to change notification settings - Fork 952
/
Copy pathphoenix_component.ex
2241 lines (1713 loc) · 66.7 KB
/
phoenix_component.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.Component do
@moduledoc ~S'''
Define reusable function components with HEEx templates.
A function component is any function that receives an assigns map as an argument and returns
a rendered struct built with [the `~H` sigil](`sigil_H/2`):
defmodule MyComponent do
use Phoenix.Component
def greet(assigns) do
~H"""
<p>Hello, <%= @name %>!</p>
"""
end
end
When invoked within a `~H` sigil or HEEx template file:
```heex
<MyComponent.greet name="Jane" />
```
The following HTML is rendered:
```html
<p>Hello, Jane!</p>
```
If the function component is defined locally, or its module is imported, then the caller can
invoke the function directly without specifying the module:
```heex
<.greet name="Jane" />
```
For dynamic values, you can interpolate Elixir expressions into a function component:
```heex
<.greet name={@user.name} />
```
Function components can also accept blocks of HEEx content (more on this later):
```heex
<.card>
<p>This is the body of my card!</p>
</.card>
```
Like `Phoenix.LiveView` and `Phoenix.LiveComponent`, function components are implemented using
a map of assigns, and follow [the same rules and best practices](../guides/server/assigns-eex.md).
However, we typically do not implement function components by manipulating the assigns map
directly, as `Phoenix.Component` provides two higher-level abstractions for us:
attributes and slots.
## Attributes
`Phoenix.Component` provides the `attr/3` macro to declare what attributes a function component
expects to receive when invoked:
attr :name, :string, required: true
def greet(assigns) do
~H"""
<p>Hello, <%= @name %>!</p>
"""
end
By calling `attr/3`, it is now clear that `greet/1` requires a string attribute called `name`
present in its assigns map to properly render. Failing to do so will result in a compilation
warning:
```heex
<MyComponent.greet />
<!-- warning: missing required attribute "name" for component MyAppWeb.MyComponent.greet/1
lib/app_web/my_component.ex:15 -->
```
Attributes can provide default values that are automatically merged into the assigns map:
attr :name, :string, default: "Bob"
Now you can invoke the function component without providing a value for `name`:
```heex
<.greet />
```
Rendering the following HTML:
```html
<p>Hello, Bob!</p>
```
Multiple attributes can be declared for the same function component:
attr :name, :string, required: true
attr :age, :integer, required: true
def celebrate(assigns) do
~H"""
<p>
Happy birthday <%= @name %>!
You are <%= @age %> years old.
<p>
"""
end
Allowing the caller to pass multiple values:
```heex
<.celebrate name={"Genevieve"} age={34} />
```
Rendering the following HTML:
```html
<p>
Happy birthday Genevieve!
You are 34 years old.
</p>
```
With the `attr/3` macro you have the core ingredients to create reusable function components.
But what if you need your function components to support dynamic attributes, such as common HTML
attributes to mix into a component's container?
### Global Attributes
Global attributes are a set of attributes that a function component can accept when it
declares an attribute of type `:global`. By default, the set of attributes accepted are those
[common to all HTML elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes).
Once a global attribute is declared, any number of attributes in the set can be passed by
the caller without having to modify the function componet itself.
Below is an example of a function component that accepts a dynamic number of global attributes:
attr :message, :string, required: true
attr :rest, :global
def notification(assigns) do
~H"""
<span {@rest}><%= @message %></span>
"""
end
The caller can pass multiple global attributes (such as `phx-*` bindings or the `class` attribute):
```heex
<.notification message="You've got mail!" class="bg-green-200" phx-click="close" />
```
Rendering the following HTML:
```html
<span class="bg-green-200" phx-click="close">You've got mail!</span>
```
Note that the function component did not have to explicitly declare a `class` or `phx-click`
attribute in order to render.
Global attribute can define defaults which are merged with attributes provided by the caller.
For example, you may declare a default `class` if the caller does not provide one:
attr :rest, :global, default: %{class: "bg-blue-200"}
Now you can call the function component without a `class` attribute:
```heex
<.notification message="You've got mail!" phx-click="close" />
```
Rendering the following HTML:
```html
<span class="bg-blue-200" phx-click="close">You've got mail!</span>
```
### Custom Global Attribute Prefixes
You can extend the set of global attributes by providing a list of attribute prefixes to
`use Phoenix.Component`. Like the default attributes common to all HTML elements,
any number of attributes with that start with a global prefix will be accepted by function
components defined in this module. By default, the following prefixes are supported:
`phx-`, `aria-`, and `data-`. For example, to support the `x-` prefix used by
[Alpine.js](https://alpinejs.dev/), you can pass the `:global_prefixes` option to
`use Phoenix.Component`:
use Phoenix.Component, global_prefixes: ~w(x-)
Now all function components defined in this module will accept any number of attributes prefixed
with `x-`, in addition to the default global prefixes.
You can learn more about attributes by reading the documentation for `attr/3`.
## Slots
In addition to attributes, function components can accept blocks of HEEx content, referred to as
as slots. Slots enable further customization of the rendered HTML, as the caller can pass the
function component HEEx content they want the component to render. `Phoenix.Component` provides
the `slot/3` macro used to declare slots for function components:
slot :inner_block, required: true
def button(assigns) do
~H"""
<button>
<%= render_slot(@inner_block) %>
</button>
"""
end
The expression `render_slot(@inner_block)` renders the HEEx content. You can invoke this function
component like so:
```heex
<.button>
This renders <strong>inside</strong> the button!
</.button>
```
Which renderes the following HTML:
```html
<button>
This renders <strong>inside</strong> the button!
</button>
```
Like the `attr/3` macro, using the `slot/3` macro will provide compile-time validations.
For example, invoking `button/1` without a slot of HEEx content will result in a compilation
warning being emitted:
```heex
<.button />
<!-- warning: missing required slot "inner_block" for component MyAppWeb.MyComponent.button/1
lib/app_web/my_component.ex:15 -->
```
### The Default Slot
The example above uses the default slot, accesible as an assign named `@inner_block`, to render
HEEx content via the `render_slot/2` function.
If the values rendered in the slot need to be dynamic, you can pass a second value back to the
HEEx content by calling `render_slot/2`:
slot :inner_block, required: true
attr :entries, :list, default: []
def unordered_list(assigns) do
~H"""
<ul>
<%= for entry <- @entries do %>
<li><%= render_slot(@inner_block, entry) %></li>
<% end %>
</ul>
"""
end
When invoking the function component, you can use the special attribute `:let` to take the value
that the function component passes back and bind it to a variable:
```heex
<.unordered_list :let={fruit} entries={~w(apples bananas cherries)}>
I like <%= fruit %>!
</.unordered_list>
```
Rendering the following HTML:
```html
<ul>
<li>I like apples!</li>
<li>I like bananas!</li>
<li>I like cherries!</li>
</ul>
```
Now the separation of concerns is maintained: the caller can specify multiple values in a list
attribute without having to specify the HEEx content that surrounds and separates them.
### Named Slots
In addition to the default slot, function components can accept multiple, named slots of HEEx
content. For example, imagine you want to create a modal that has a header, body, and footer:
slot :header
slot :inner_block, required: true
slot :footer, required: true
def modal(assigns) do
~H"""
<div class="modal">
<div class="modal-header">
<%= render_slot(@header) || "Modal" %>
</div>
<div class="modal-body">
<%= render_slot(@inner_block) %>
</div>
<div class="modal-footer">
<%= render_slot(@footer) %>
</div>
</div>
"""
end
You can invoke this function component using the named slot HEEx syntax:
```heex
<.modal>
This is the body, everything not in a named slot is rendered in the default slot.
<:footer>
This is the bottom of the modal.
</:footer>
</.modal>
```
Rendering the following HTML:
```html
<div class="modal">
<div class="modal-header">
Modal.
</div>
<div class="modal-body">
This is the body, everything not in a named slot is rendered in the default slot.
</div>
<div class="modal-footer">
This is the bottom of the modal.
</div>
</div>
```
As shown in the example above, `render_slot/1` returns `nil` when an optional slot
is declared and none is given. This can be used to attach default behaviour.
### Slot Attributes
Unlike the default slot, it is possible to pass a named slot multiple pieces of HEEx content.
Named slots can also accept attributes, defined by passing a block to the `slot/3` macro.
If multiple pieces of content are passed, `render_slot/2` will merge and render all the values.
Below is a table component illustrating multiple named slots with attributes:
slot :column do
attr :label, :string, required: true
end
attr :rows, :list, default: []
def table(assigns) do
~H"""
<table>
<tr>
<%= for col <- @column do %>
<th><%= col.label %></th>
<% end %>
</tr>
<%= for row <- @rows do %>
<tr>
<%= for col <- @column do %>
<td><%= render_slot(col, row) %></td>
<% end %>
</tr>
<% end %>
</table>
"""
end
You can invoke this function component like so:
```heex
<.table rows={[%{name: "Jane", age: "34"}, %{name: "Bob", age: "51"}]}>
<:column :let={user} label="Name">
<%= user.name %>
</:column>
<:column :let={user} label="Age">
<%= user.age %>
</:column>
</.table>
```
Rendering the following HTML:
```html
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jane</td>
<td>34</td>
</tr>
<tr>
<td>Bob</td>
<td>51</td>
</tr>
</table>
```
You can learn more about slots and the `slot/3` macro [in its documentation](`slot/3`).
'''
## Functions
alias Phoenix.LiveView.{Static, Socket}
@reserved_assigns Phoenix.Component.Declarative.__reserved__()
@doc ~S'''
The `~H` sigil for writing HEEx templates inside source files.
> Note: The HEEx HTML formatter requires Elixir >= 1.13.4. See the
> `Phoenix.LiveView.HTMLFormatter` for more information on template formatting.
`HEEx` is a HTML-aware and component-friendly extension of Elixir Embedded
language (`EEx`) that provides:
* Built-in handling of HTML attributes.
* An HTML-like notation for injecting function components.
* Compile-time validation of the structure of the template.
* The ability to minimize the amount of data sent over the wire.
## Example
~H"""
<div title="My div" class={@class}>
<p>Hello <%= @name %></p>
<MyApp.Weather.city name="Kraków"/>
</div>
"""
## Syntax
`HEEx` is built on top of Embedded Elixir (`EEx`). In this section, we are going to
cover the basic constructs in `HEEx` templates as well as its syntax extensions.
### Interpolation
Both `HEEx` and `EEx` templates use `<%= ... %>` for interpolating code inside the body
of HTML tags:
```heex
<p>Hello, <%= @name %></p>
```
Similarly, conditionals and other block Elixir constructs are supported:
```heex
<%= if @show_greeting? do %>
<p>Hello, <%= @name %></p>
<% end %>
```
Note we don't include the equal sign `=` in the closing `<% end %>` tag
(because the closing tag does not output anything).
There is one important difference between `HEEx` and Elixir's builtin `EEx`.
`HEEx` uses a specific annotation for interpolating HTML tags and attributes.
Let's check it out.
### HEEx extension: Defining attributes
Since `HEEx` must parse and validate the HTML structure, code interpolation using
`<%= ... %>` and `<% ... %>` are restricted to the body (inner content) of the
HTML/component nodes and it cannot be applied within tags.
For instance, the following syntax is invalid:
```heex
<div class="<%= @class %>">
...
</div>
```
Instead do:
```heex
<div class={@class}>
...
</div>
```
You can put any Elixir expression between `{ ... }`. For example, if you want
to set classes, where some are static and others are dynamic, you can using
string interpolation:
```heex
<div class={"btn btn-#{@type}"}>
...
</div>
```
The following attribute values have special meaning:
* `true` - if a value is `true`, the attribute is rendered with no value at all.
For example, `<input required={true}>` is the same as `<input required>`;
* `false` or `nil` - if a value is `false` or `nil`, the attribute is not rendered;
* `list` (only for the `class` attribute) - each element of the list is processed
as a different class. `nil` and `false` elements are discarded.
For multiple dynamic attributes, you can use the same notation but without
assigning the expression to any specific attribute.
```heex
<div {@dynamic_attrs}>
...
</div>
```
The expression inside `{...}` must be either a keyword list or a map containing
the key-value pairs representing the dynamic attributes.
You can pair this notation `assigns_to_attributes/2` to strip out any internal
LiveView attributes and user-defined assigns from being expanded into the HTML tag:
```heex
<div {assigns_to_attributes(assigns, [:visible])}>
...
</div>
```
The above would add all caller attributes into the HTML, but strip out LiveView
assigns like slots, as well as user-defined assigns like `:visible` that are not
meant to be added to the HTML itself. This approach is useful to allow a component
to accept arbitrary HTML attributes like class, ARIA attributes, etc.
### HEEx extension: Defining function components
Function components are stateless components implemented as pure functions
with the help of the `Phoenix.Component` module. They can be either local
(same module) or remote (external module).
`HEEx` allows invoking these function components directly in the template
using an HTML-like notation. For example, a remote function:
```heex
<MyApp.Weather.city name="Kraków"/>
```
A local function can be invoked with a leading dot:
```heex
<.city name="Kraków"/>
```
where the component could be defined as follows:
defmodule MyApp.Weather do
use Phoenix.Component
def city(assigns) do
~H"""
The chosen city is: <%= @name %>.
"""
end
def country(assigns) do
~H"""
The chosen country is: <%= @name %>.
"""
end
end
It is typically best to group related functions into a single module, as
opposed to having many modules with a single `render/1` function. Function
components support other important features, such as slots. You can learn
more about components in `Phoenix.Component`.
### HEEx extension: special attributes
Apart from normal HTML attributes, HEEx also support some special attributes
such as `:let` and `:for`.
#### :let
This is used by components and slots that want to yield a value back to the
caller. For an example, see how `form/1` works:
```heex
<.form :let={f} for={@changeset} phx-change="validate" phx-submit="save">
<%= label(f, :username) %>
<%= text_input(f, :username) %>
...
</.form>
```
Notice how the variable `f`, defined by `.form`, is used by `label` and
`text_input`. The `Phoenix.Component` module has detailed documentation on
how to use and implement such functionality.
#### :for
It is a syntax sugar for `<%= for .. do %>` that can be used only in regular HTML
tags, therefore `:for` will not work on components.
```heex
<table id="my-table">
<tr :for={user <- @users}>
<td><%= user.name %>
</tr>
<table>
```
The snippet above will generate a `tr` per user as you would expect.
'''
defmacro sigil_H({:<<>>, meta, [expr]}, []) do
unless Macro.Env.has_var?(__CALLER__, {:assigns, nil}) do
raise "~H requires a variable named \"assigns\" to exist and be set to a map"
end
options = [
engine: Phoenix.LiveView.HTMLEngine,
file: __CALLER__.file,
line: __CALLER__.line + 1,
caller: __CALLER__,
indentation: meta[:indentation] || 0
]
EEx.compile_string(expr, options)
end
@doc ~S'''
Filters the assigns as a list of keywords for use in dynamic tag attributes.
Useful for transforming caller assigns into dynamic attributes while
stripping reserved keys from the result.
## Examples
Imagine the following `my_link` component which allows a caller
to pass a `new_window` assign, along with any other attributes they
would like to add to the element, such as class, data attributes, etc:
```heex
<.my_link href="/" id={@id} new_window={true} class="my-class">Home</.my_link>
```
We could support the dynamic attributes with the following component:
def my_link(assigns) do
target = if assigns[:new_window], do: "_blank", else: false
extra = assigns_to_attributes(assigns, [:new_window])
assigns =
assigns
|> assign(:target, target)
|> assign(:extra, extra)
~H"""
<a href={@href} target={@target} {@extra}>
<%= render_slot(@inner_block) %>
</a>
"""
end
The above would result in the following rendered HTML:
```heex
<a href="/" target="_blank" id="1" class="my-class">Home</a>
```
The second argument (optional) to `assigns_to_attributes` is a list of keys to
exclude. It typically includes reserved keys by the component itself, which either
do not belong in the markup, or are already handled explicitly by the component.
'''
def assigns_to_attributes(assigns, exclude \\ []) do
excluded_keys = @reserved_assigns ++ exclude
for {key, val} <- assigns, key not in excluded_keys, into: [], do: {key, val}
end
@doc """
Renders a LiveView within a template.
This is useful in two situations:
* When rendering a child LiveView inside a LiveView.
* When rendering a LiveView inside a regular (non-live) controller/view.
## Options
* `:session` - a map of binary keys with extra session data to be serialized and sent
to the client. All session data currently in the connection is automatically available
in LiveViews. You can use this option to provide extra data. Remember all session data is
serialized and sent to the client, so you should always keep the data in the session
to a minimum. For example, instead of storing a User struct, you should store the "user_id"
and load the User when the LiveView mounts.
* `:container` - an optional tuple for the HTML tag and DOM attributes to be used for the
LiveView container. For example: `{:li, style: "color: blue;"}`. By default it uses the module
definition container. See the "Containers" section below for more information.
* `:id` - both the DOM ID and the ID to uniquely identify a LiveView. An `:id` is
automatically generated when rendering root LiveViews but it is a required option when
rendering a child LiveView.
* `:sticky` - an optional flag to maintain the LiveView across live redirects, even if it is
nested within another LiveView. If you are rendering the sticky view within your live layout,
make sure that the sticky view itself does not use the same layout. You can do so by returning
`{:ok, socket, layout: false}` from mount.
## Examples
When rendering from a controller/view, you can call:
```heex
<%= live_render(@conn, MyApp.ThermostatLive) %>
```
Or:
```heex
<%= live_render(@conn, MyApp.ThermostatLive, session: %{"home_id" => @home.id}) %>
```
Within another LiveView, you must pass the `:id` option:
```heex
<%= live_render(@socket, MyApp.ThermostatLive, id: "thermostat") %>
```
## Containers
When a `LiveView` is rendered, its contents are wrapped in a container. By default,
the container is a `div` tag with a handful of `LiveView` specific attributes.
The container can be customized in different ways:
* You can change the default `container` on `use Phoenix.LiveView`:
use Phoenix.LiveView, container: {:tr, id: "foo-bar"}
* You can override the container tag and pass extra attributes when calling `live_render`
(as well as on your `live` call in your router):
live_render socket, MyLiveView, container: {:tr, class: "highlight"}
"""
def live_render(conn_or_socket, view, opts \\ [])
def live_render(%Plug.Conn{} = conn, view, opts) do
case Static.render(conn, view, opts) do
{:ok, content, _assigns} ->
content
{:stop, _} ->
raise RuntimeError, "cannot redirect from a child LiveView"
end
end
def live_render(%Socket{} = parent, view, opts) do
Static.nested_render(parent, view, opts)
end
@doc ~S'''
Renders a slot entry with the given optional `argument`.
```heex
<%= render_slot(@inner_block, @form) %>
```
If the slot has no entries, nil is returned.
If multiple slot entries are defined for the same slot,`render_slot/2` will automatically render
all entries, merging their contents. In case you want to use the entries' attributes, you need
to iterate over the list to access each slot individually.
For example, imagine a table component:
```heex
<.table rows={@users}>
<:col :let={user} label="Name">
<%= user.name %>
</:col>
<:col :let={user} label="Address">
<%= user.address %>
</:col>
</.table>
```
At the top level, we pass the rows as an assign and we define a `:col` slot for each column we
want in the table. Each column also has a `label`, which we are going to use in the table header.
Inside the component, you can render the table with headers, rows, and columns:
def table(assigns) do
~H"""
<table>
<tr>
<%= for col <- @col do %>
<th><%= col.label %></th>
<% end %>
</tr>
<%= for row <- @rows do %>
<tr>
<%= for col <- @col do %>
<td><%= render_slot(col, row) %></td>
<% end %>
</tr>
<% end %>
</table>
"""
end
'''
defmacro render_slot(slot, argument \\ nil) do
quote do
unquote(__MODULE__).__render_slot__(
var!(changed, Phoenix.LiveView.Engine),
unquote(slot),
unquote(argument)
)
end
end
@doc false
def __render_slot__(_, [], _), do: nil
def __render_slot__(changed, [entry], argument) do
call_inner_block!(entry, changed, argument)
end
def __render_slot__(changed, entries, argument) when is_list(entries) do
assigns = %{}
~H"""
<%= for entry <- entries do %><%= call_inner_block!(entry, changed, argument) %><% end %>
"""
end
def __render_slot__(changed, entry, argument) when is_map(entry) do
entry.inner_block.(changed, argument)
end
defp call_inner_block!(entry, changed, argument) do
if !entry.inner_block do
message = "attempted to render slot <:#{entry.__slot__}> but the slot has no inner content"
raise RuntimeError, message
end
entry.inner_block.(changed, argument)
end
@doc """
Returns the flash message from the LiveView flash assign.
## Examples
```heex
<p class="alert alert-info"><%= live_flash(@flash, :info) %></p>
<p class="alert alert-danger"><%= live_flash(@flash, :error) %></p>
```
"""
def live_flash(%_struct{} = other, _key) do
raise ArgumentError, "live_flash/2 expects a @flash assign, got: #{inspect(other)}"
end
def live_flash(%{} = flash, key), do: Map.get(flash, to_string(key))
@doc """
Returns the entry errors for an upload.
The following error may be returned:
* `:too_many_files` - The number of selected files exceeds the `:max_entries` constraint
## Examples
def error_to_string(:too_many_files), do: "You have selected too many files"
```heex
<%= for err <- upload_errors(@uploads.avatar) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
```
"""
def upload_errors(%Phoenix.LiveView.UploadConfig{} = conf) do
for {ref, error} <- conf.errors, ref == conf.ref, do: error
end
@doc """
Returns the entry errors for an upload.
The following errors may be returned:
* `:too_large` - The entry exceeds the `:max_file_size` constraint
* `:not_accepted` - The entry does not match the `:accept` MIME types
## Examples
def error_to_string(:too_large), do: "Too large"
def error_to_string(:not_accepted), do: "You have selected an unacceptable file type"
```heex
<%= for entry <- @uploads.avatar.entries do %>
<%= for err <- upload_errors(@uploads.avatar, entry) do %>
<div class="alert alert-danger">
<%= error_to_string(err) %>
</div>
<% end %>
<% end %>
```
"""
def upload_errors(
%Phoenix.LiveView.UploadConfig{} = conf,
%Phoenix.LiveView.UploadEntry{} = entry
) do
for {ref, error} <- conf.errors, ref == entry.ref, do: error
end
@doc ~S'''
Assigns the given `key` with value from `fun` into `socket_or_assigns` if one does not yet exist.
The first argument is either a LiveView `socket` or an `assigns` map from function components.
This function is useful for lazily assigning values and referencing parent assigns.
We will cover both use cases next.
## Lazy assigns
Imagine you have a function component that accepts a color:
```heex
<.my_component color="red" />
```
The color is also optional, so you can skip it:
```heex
<.my_component />
```
In such cases, the implementation can use `assign_new` to lazily
assign a color if none is given. Let's make it so it picks a random one
when none is given:
def my_component(assigns) do
assigns = assign_new(assigns, :color, fn -> Enum.random(~w(red green blue)) end)
~H"""
<div class={"bg-#{@color}"}>
Example
</div>
"""
end
## Referencing parent assigns
When a user first accesses an application using LiveView, the LiveView is first rendered in its
disconnected state, as part of a regular HTML response. In some cases, there may be data that is
shared by your Plug pipelines and your LiveView, such as the `:current_user` assign.
By using `assign_new` in the mount callback of your LiveView, you can instruct LiveView to
re-use any assigns set in your Plug pipelines as part of `Plug.Conn`, avoiding sending additional
queries to the database. Imagine you have a Plug that does:
# A plug
def authenticate(conn, _opts) do
if user_id = get_session(conn, :user_id) do
assign(conn, :current_user, Accounts.get_user!(user_id))
else
send_resp(conn, :forbidden)
end
end
You can re-use the `:current_user` assign in your LiveView during the initial render:
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
end
In such case `conn.assigns.current_user` will be used if present. If there is no such
`:current_user` assign or the LiveView was mounted as part of the live navigation, where no Plug
pipelines are invoked, then the anonymous function is invoked to execute the query instead.
LiveView is also able to share assigns via `assign_new` within nested LiveView. If the parent
LiveView defines a `:current_user` assign and the child LiveView also uses `assign_new/3` to
fetch the `:current_user` in its `mount/3` callback, as above, the assign will be fetched from
the parent LiveView, once again avoiding additional database queries.
Note that `fun` also provides access to the previously assigned values:
assigns =
assigns
|> assign_new(:foo, fn -> "foo" end)
|> assign_new(:bar, fn %{foo: foo} -> foo <> "bar" end)
'''
def assign_new(socket_or_assigns, key, fun)