692 lines
22 kB
1
defmodule BlogWeb.CoreComponents do
2
@moduledoc """
3
Provides core UI components.
4
5
At first glance, this module may seem daunting, but its goal is to provide
6
core building blocks for your application, such as modals, tables, and
7
forms. The components consist mostly of markup and are well-documented
8
with doc strings and declarative assigns. You may customize and style
9
them in any way you want, based on your application growth and needs.
10
11
The default components use Tailwind CSS, a utility-first CSS framework.
12
See the [Tailwind CSS documentation](https://tailwindcss.com) to learn
13
how to customize them or feel free to swap in another framework altogether.
14
15
Icons are provided by [heroicons](https://heroicons.com). See `icon/1` for usage.
16
"""
17
use Phoenix.Component
18
use Gettext, backend: BlogWeb.Gettext
19
20
alias Phoenix.LiveView.JS
21
22
@doc """
23
Renders a modal.
24
25
## Examples
26
27
<.modal id="confirm-modal">
28
This is a modal.
29
</.modal>
30
31
JS commands may be passed to the `:on_cancel` to configure
32
the closing/cancel event, for example:
33
34
<.modal id="confirm" on_cancel={JS.navigate(~p"/posts")}>
35
This is another modal.
36
</.modal>
37
38
"""
39
attr :id, :string, required: true
40
attr :show, :boolean, default: false
41
attr :on_cancel, JS, default: %JS{}
42
slot :inner_block, required: true
43
44
attr :meta_attrs, :list, required: true
45
attr :page_title, :string, required: true
46
def head_tags(assigns) do
47
~H"""
48
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
49
<%= for meta <- @meta_attrs do %>
50
<%= if Map.has_key?(meta, :name) do %>
51
<meta name={meta.name} content={meta.content}/>
52
<% else %>
53
<meta property={meta.property} content={meta.content}/>
54
<% end %>
55
<% end %>
56
<title><%= @page_title %></title>
57
"""
58
end
59
60
def modal(assigns) do
61
~H"""
62
<div
63
id={@id}
64
phx-mounted={@show && show_modal(@id)}
65
phx-remove={hide_modal(@id)}
66
data-cancel={JS.exec(@on_cancel, "phx-remove")}
67
class="relative z-50 hidden"
68
>
69
<div id={"#{@id}-bg"} class="bg-zinc-50/90 fixed inset-0 transition-opacity" aria-hidden="true" />
70
<div
71
class="fixed inset-0 overflow-y-auto"
72
aria-labelledby={"#{@id}-title"}
73
aria-describedby={"#{@id}-description"}
74
role="dialog"
75
aria-modal="true"
76
tabindex="0"
77
>
78
<div class="flex min-h-full items-center justify-center">
79
<div class="w-full max-w-3xl p-4 sm:p-6 lg:py-8">
80
<.focus_wrap
81
id={"#{@id}-container"}
82
phx-window-keydown={JS.exec("data-cancel", to: "##{@id}")}
83
phx-key="escape"
84
phx-click-away={JS.exec("data-cancel", to: "##{@id}")}
85
class="shadow-zinc-700/10 ring-zinc-700/10 relative hidden rounded-2xl bg-white p-14 shadow-lg ring-1 transition"
86
>
87
<div class="absolute top-6 right-5">
88
<button
89
phx-click={JS.exec("data-cancel", to: "##{@id}")}
90
type="button"
91
class="-m-3 flex-none p-3 opacity-20 hover:opacity-40"
92
aria-label={gettext("close")}
93
>
94
<.icon name="hero-x-mark-solid" class="h-5 w-5" />
95
</button>
96
</div>
97
<div id={"#{@id}-content"}>
98
{render_slot(@inner_block)}
99
</div>
100
</.focus_wrap>
101
</div>
102
</div>
103
</div>
104
</div>
105
"""
106
end
107
108
@doc """
109
Renders flash notices.
110
111
## Examples
112
113
<.flash kind={:info} flash={@flash} />
114
<.flash kind={:info} phx-mounted={show("#flash")}>Welcome Back!</.flash>
115
"""
116
attr :id, :string, doc: "the optional id of flash container"
117
attr :flash, :map, default: %{}, doc: "the map of flash messages to display"
118
attr :title, :string, default: nil
119
attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup"
120
attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container"
121
122
slot :inner_block, doc: "the optional inner block that renders the flash message"
123
124
def flash(assigns) do
125
assigns = assign_new(assigns, :id, fn -> "flash-#{assigns.kind}" end)
126
127
~H"""
128
<div
129
:if={msg = render_slot(@inner_block) || Phoenix.Flash.get(@flash, @kind)}
130
id={@id}
131
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
132
role="alert"
133
class={[
134
"fixed top-2 right-2 mr-2 w-80 sm:w-96 z-50 rounded-lg p-3 ring-1",
135
@kind == :info && "bg-emerald-50 text-emerald-800 ring-emerald-500 fill-cyan-900",
136
@kind == :error && "bg-rose-50 text-rose-900 shadow-md ring-rose-500 fill-rose-900"
137
]}
138
{@rest}
139
>
140
<p :if={@title} class="flex items-center gap-1.5 text-sm font-semibold leading-6">
141
<.icon :if={@kind == :info} name="hero-information-circle-mini" class="h-4 w-4" />
142
<.icon :if={@kind == :error} name="hero-exclamation-circle-mini" class="h-4 w-4" />
143
{@title}
144
</p>
145
<p class="mt-2 text-sm leading-5">{msg}</p>
146
<button type="button" class="group absolute top-1 right-1 p-2" aria-label={gettext("close")}>
147
<.icon name="hero-x-mark-solid" class="h-5 w-5 opacity-40 group-hover:opacity-70" />
148
</button>
149
</div>
150
"""
151
end
152
153
@doc """
154
Shows the flash group with standard titles and content.
155
156
## Examples
157
158
<.flash_group flash={@flash} />
159
"""
160
attr :flash, :map, required: true, doc: "the map of flash messages"
161
attr :id, :string, default: "flash-group", doc: "the optional id of flash container"
162
163
def flash_group(assigns) do
164
~H"""
165
<div id={@id}>
166
<.flash kind={:info} title={gettext("Success!")} flash={@flash} />
167
<.flash kind={:error} title={gettext("Error!")} flash={@flash} />
168
<.flash
169
id="client-error"
170
kind={:error}
171
title={gettext("We can't find the internet")}
172
phx-disconnected={show(".phx-client-error #client-error")}
173
phx-connected={hide("#client-error")}
174
hidden
175
>
176
{gettext("Attempting to reconnect")}
177
<.icon name="hero-arrow-path" class="ml-1 h-3 w-3 animate-spin" />
178
</.flash>
179
180
<.flash
181
id="server-error"
182
kind={:error}
183
title={gettext("Something went wrong!")}
184
phx-disconnected={show(".phx-server-error #server-error")}
185
phx-connected={hide("#server-error")}
186
hidden
187
>
188
{gettext("Hang in there while we get back on track")}
189
<.icon name="hero-arrow-path" class="ml-1 h-3 w-3 animate-spin" />
190
</.flash>
191
</div>
192
"""
193
end
194
195
@doc """
196
Renders a simple form.
197
198
## Examples
199
200
<.simple_form for={@form} phx-change="validate" phx-submit="save">
201
<.input field={@form[:email]} label="Email"/>
202
<.input field={@form[:username]} label="Username" />
203
<:actions>
204
<.button>Save</.button>
205
</:actions>
206
</.simple_form>
207
"""
208
attr :for, :any, required: true, doc: "the data structure for the form"
209
attr :as, :any, default: nil, doc: "the server side parameter to collect all input under"
210
211
attr :rest, :global,
212
include: ~w(autocomplete name rel action enctype method novalidate target multipart),
213
doc: "the arbitrary HTML attributes to apply to the form tag"
214
215
slot :inner_block, required: true
216
slot :actions, doc: "the slot for form actions, such as a submit button"
217
218
def simple_form(assigns) do
219
~H"""
220
<.form :let={f} for={@for} as={@as} {@rest}>
221
<div class="mt-10 space-y-8 bg-white">
222
{render_slot(@inner_block, f)}
223
<div :for={action <- @actions} class="mt-2 flex items-center justify-between gap-6">
224
{render_slot(action, f)}
225
</div>
226
</div>
227
</.form>
228
"""
229
end
230
231
@doc """
232
Renders a button.
233
234
## Examples
235
236
<.button>Send!</.button>
237
<.button phx-click="go" class="ml-2">Send!</.button>
238
"""
239
attr :type, :string, default: nil
240
attr :class, :string, default: nil
241
attr :rest, :global, include: ~w(disabled form name value)
242
243
slot :inner_block, required: true
244
245
def button(assigns) do
246
~H"""
247
<button
248
type={@type}
249
class={[
250
"phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3",
251
"text-sm font-semibold leading-6 text-white active:text-white/80",
252
@class
253
]}
254
{@rest}
255
>
256
{render_slot(@inner_block)}
257
</button>
258
"""
259
end
260
261
@doc """
262
Renders an input with label and error messages.
263
264
A `Phoenix.HTML.FormField` may be passed as argument,
265
which is used to retrieve the input name, id, and values.
266
Otherwise all attributes may be passed explicitly.
267
268
## Types
269
270
This function accepts all HTML input types, considering that:
271
272
* You may also set `type="select"` to render a `<select>` tag
273
274
* `type="checkbox"` is used exclusively to render boolean values
275
276
* For live file uploads, see `Phoenix.Component.live_file_input/1`
277
278
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
279
for more information. Unsupported types, such as hidden and radio,
280
are best written directly in your templates.
281
282
## Examples
283
284
<.input field={@form[:email]} type="email" />
285
<.input name="my-input" errors={["oh no!"]} />
286
"""
287
attr :id, :any, default: nil
288
attr :name, :any
289
attr :label, :string, default: nil
290
attr :value, :any
291
292
attr :type, :string,
293
default: "text",
294
values: ~w(checkbox color date datetime-local email file month number password
295
range search select tel text textarea time url week)
296
297
attr :field, Phoenix.HTML.FormField,
298
doc: "a form field struct retrieved from the form, for example: @form[:email]"
299
300
attr :errors, :list, default: []
301
attr :checked, :boolean, doc: "the checked flag for checkbox inputs"
302
attr :prompt, :string, default: nil, doc: "the prompt for select inputs"
303
attr :options, :list, doc: "the options to pass to Phoenix.HTML.Form.options_for_select/2"
304
attr :multiple, :boolean, default: false, doc: "the multiple flag for select inputs"
305
306
attr :rest, :global,
307
include: ~w(accept autocomplete capture cols disabled form list max maxlength min minlength
308
multiple pattern placeholder readonly required rows size step)
309
310
def input(%{field: %Phoenix.HTML.FormField{} = field} = assigns) do
311
errors = if Phoenix.Component.used_input?(field), do: field.errors, else: []
312
313
assigns
314
|> assign(field: nil, id: assigns.id || field.id)
315
|> assign(:errors, Enum.map(errors, &translate_error(&1)))
316
|> assign_new(:name, fn -> if assigns.multiple, do: field.name <> "[]", else: field.name end)
317
|> assign_new(:value, fn -> field.value end)
318
|> input()
319
end
320
321
def input(%{type: "checkbox"} = assigns) do
322
assigns =
323
assign_new(assigns, :checked, fn ->
324
Phoenix.HTML.Form.normalize_value("checkbox", assigns[:value])
325
end)
326
327
~H"""
328
<div>
329
<label class="flex items-center gap-4 text-sm leading-6 text-zinc-600">
330
<input type="hidden" name={@name} value="false" disabled={@rest[:disabled]} />
331
<input
332
type="checkbox"
333
id={@id}
334
name={@name}
335
value="true"
336
checked={@checked}
337
class="rounded border-zinc-300 text-zinc-900 focus:ring-0"
338
{@rest}
339
/>
340
{@label}
341
</label>
342
<.error :for={msg <- @errors}>{msg}</.error>
343
</div>
344
"""
345
end
346
347
def input(%{type: "select"} = assigns) do
348
~H"""
349
<div>
350
<.label for={@id}>{@label}</.label>
351
<select
352
id={@id}
353
name={@name}
354
class="mt-2 block w-full rounded-md border border-gray-300 bg-white shadow-sm focus:border-zinc-400 focus:ring-0 sm:text-sm"
355
multiple={@multiple}
356
{@rest}
357
>
358
<option :if={@prompt} value="">{@prompt}</option>
359
{Phoenix.HTML.Form.options_for_select(@options, @value)}
360
</select>
361
<.error :for={msg <- @errors}>{msg}</.error>
362
</div>
363
"""
364
end
365
366
def input(%{type: "textarea"} = assigns) do
367
~H"""
368
<div>
369
<.label for={@id}>{@label}</.label>
370
<textarea
371
id={@id}
372
name={@name}
373
class={[
374
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 min-h-[6rem]",
375
@errors == [] && "border-zinc-300 focus:border-zinc-400",
376
@errors != [] && "border-rose-400 focus:border-rose-400"
377
]}
378
{@rest}
379
>{Phoenix.HTML.Form.normalize_value("textarea", @value)}</textarea>
380
<.error :for={msg <- @errors}>{msg}</.error>
381
</div>
382
"""
383
end
384
385
# All other inputs text, datetime-local, url, password, etc. are handled here...
386
def input(assigns) do
387
~H"""
388
<div>
389
<.label for={@id}>{@label}</.label>
390
<input
391
type={@type}
392
name={@name}
393
id={@id}
394
value={Phoenix.HTML.Form.normalize_value(@type, @value)}
395
class={[
396
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6",
397
@errors == [] && "border-zinc-300 focus:border-zinc-400",
398
@errors != [] && "border-rose-400 focus:border-rose-400"
399
]}
400
{@rest}
401
/>
402
<.error :for={msg <- @errors}>{msg}</.error>
403
</div>
404
"""
405
end
406
407
@doc """
408
Renders a label.
409
"""
410
attr :for, :string, default: nil
411
slot :inner_block, required: true
412
413
def label(assigns) do
414
~H"""
415
<label for={@for} class="block text-sm font-semibold leading-6 text-zinc-800">
416
{render_slot(@inner_block)}
417
</label>
418
"""
419
end
420
421
@doc """
422
Generates a generic error message.
423
"""
424
slot :inner_block, required: true
425
426
def error(assigns) do
427
~H"""
428
<p class="mt-3 flex gap-3 text-sm leading-6 text-rose-600">
429
<.icon name="hero-exclamation-circle-mini" class="mt-0.5 h-5 w-5 flex-none" />
430
{render_slot(@inner_block)}
431
</p>
432
"""
433
end
434
435
@doc """
436
Renders a header with title.
437
"""
438
attr :class, :string, default: nil
439
440
slot :inner_block, required: true
441
slot :subtitle
442
slot :actions
443
444
def header(assigns) do
445
~H"""
446
<header class={[@actions != [] && "flex items-center justify-between gap-6", @class]}>
447
<div>
448
<h1 class="text-lg font-semibold leading-8 text-zinc-800">
449
{render_slot(@inner_block)}
450
</h1>
451
<p :if={@subtitle != []} class="mt-2 text-sm leading-6 text-zinc-600">
452
{render_slot(@subtitle)}
453
</p>
454
</div>
455
<div class="flex-none">{render_slot(@actions)}</div>
456
</header>
457
"""
458
end
459
460
@doc ~S"""
461
Renders a table with generic styling.
462
463
## Examples
464
465
<.table id="users" rows={@users}>
466
<:col :let={user} label="id">{user.id}</:col>
467
<:col :let={user} label="username">{user.username}</:col>
468
</.table>
469
"""
470
attr :id, :string, required: true
471
attr :rows, :list, required: true
472
attr :row_id, :any, default: nil, doc: "the function for generating the row id"
473
attr :row_click, :any, default: nil, doc: "the function for handling phx-click on each row"
474
475
attr :row_item, :any,
476
default: &Function.identity/1,
477
doc: "the function for mapping each row before calling the :col and :action slots"
478
479
slot :col, required: true do
480
attr :label, :string
481
end
482
483
slot :action, doc: "the slot for showing user actions in the last table column"
484
485
def table(assigns) do
486
assigns =
487
with %{rows: %Phoenix.LiveView.LiveStream{}} <- assigns do
488
assign(assigns, row_id: assigns.row_id || fn {id, _item} -> id end)
489
end
490
491
~H"""
492
<div class="overflow-y-auto px-4 sm:overflow-visible sm:px-0">
493
<table class="w-[40rem] mt-11 sm:w-full">
494
<thead class="text-sm text-left leading-6 text-zinc-500">
495
<tr>
496
<th :for={col <- @col} class="p-0 pb-4 pr-6 font-normal">{col[:label]}</th>
497
<th :if={@action != []} class="relative p-0 pb-4">
498
<span class="sr-only">{gettext("Actions")}</span>
499
</th>
500
</tr>
501
</thead>
502
<tbody
503
id={@id}
504
phx-update={match?(%Phoenix.LiveView.LiveStream{}, @rows) && "stream"}
505
class="relative divide-y divide-zinc-100 border-t border-zinc-200 text-sm leading-6 text-zinc-700"
506
>
507
<tr :for={row <- @rows} id={@row_id && @row_id.(row)} class="group hover:bg-zinc-50">
508
<td
509
:for={{col, i} <- Enum.with_index(@col)}
510
phx-click={@row_click && @row_click.(row)}
511
class={["relative p-0", @row_click && "hover:cursor-pointer"]}
512
>
513
<div class="block py-4 pr-6">
514
<span class="absolute -inset-y-px right-0 -left-4 group-hover:bg-zinc-50 sm:rounded-l-xl" />
515
<span class={["relative", i == 0 && "font-semibold text-zinc-900"]}>
516
{render_slot(col, @row_item.(row))}
517
</span>
518
</div>
519
</td>
520
<td :if={@action != []} class="relative w-14 p-0">
521
<div class="relative whitespace-nowrap py-4 text-right text-sm font-medium">
522
<span class="absolute -inset-y-px -right-4 left-0 group-hover:bg-zinc-50 sm:rounded-r-xl" />
523
<span
524
:for={action <- @action}
525
class="relative ml-4 font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
526
>
527
{render_slot(action, @row_item.(row))}
528
</span>
529
</div>
530
</td>
531
</tr>
532
</tbody>
533
</table>
534
</div>
535
"""
536
end
537
538
@doc """
539
Renders a data list.
540
541
## Examples
542
543
<.list>
544
<:item title="Title">{@post.title}</:item>
545
<:item title="Views">{@post.views}</:item>
546
</.list>
547
"""
548
slot :item, required: true do
549
attr :title, :string, required: true
550
end
551
552
def list(assigns) do
553
~H"""
554
<div class="mt-14">
555
<dl class="-my-4 divide-y divide-zinc-100">
556
<div :for={item <- @item} class="flex gap-4 py-4 text-sm leading-6 sm:gap-8">
557
<dt class="w-1/4 flex-none text-zinc-500">{item.title}</dt>
558
<dd class="text-zinc-700">{render_slot(item)}</dd>
559
</div>
560
</dl>
561
</div>
562
"""
563
end
564
565
@doc """
566
Renders a back navigation link.
567
568
## Examples
569
570
<.back navigate={~p"/posts"}>Back to posts</.back>
571
"""
572
attr :navigate, :any, required: true
573
slot :inner_block, required: true
574
575
def back(assigns) do
576
~H"""
577
<div class="mt-16">
578
<.link
579
navigate={@navigate}
580
class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
581
>
582
<.icon name="hero-arrow-left-solid" class="h-3 w-3" />
583
{render_slot(@inner_block)}
584
</.link>
585
</div>
586
"""
587
end
588
589
@doc """
590
Renders a [Heroicon](https://heroicons.com).
591
592
Heroicons come in three styles – outline, solid, and mini.
593
By default, the outline style is used, but solid and mini may
594
be applied by using the `-solid` and `-mini` suffix.
595
596
You can customize the size and colors of the icons by setting
597
width, height, and background color classes.
598
599
Icons are extracted from the `deps/heroicons` directory and bundled within
600
your compiled app.css by the plugin in your `assets/tailwind.config.js`.
601
602
## Examples
603
604
<.icon name="hero-x-mark-solid" />
605
<.icon name="hero-arrow-path" class="ml-1 w-3 h-3 animate-spin" />
606
"""
607
attr :name, :string, required: true
608
attr :class, :string, default: nil
609
610
def icon(%{name: "hero-" <> _} = assigns) do
611
~H"""
612
<span class={[@name, @class]} />
613
"""
614
end
615
616
## JS Commands
617
618
def show(js \\ %JS{}, selector) do
619
JS.show(js,
620
to: selector,
621
time: 300,
622
transition:
623
{"transition-all transform ease-out duration-300",
624
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",
625
"opacity-100 translate-y-0 sm:scale-100"}
626
)
627
end
628
629
def hide(js \\ %JS{}, selector) do
630
JS.hide(js,
631
to: selector,
632
time: 200,
633
transition:
634
{"transition-all transform ease-in duration-200",
635
"opacity-100 translate-y-0 sm:scale-100",
636
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"}
637
)
638
end
639
640
def show_modal(js \\ %JS{}, id) when is_binary(id) do
641
js
642
|> JS.show(to: "##{id}")
643
|> JS.show(
644
to: "##{id}-bg",
645
time: 300,
646
transition: {"transition-all transform ease-out duration-300", "opacity-0", "opacity-100"}
647
)
648
|> show("##{id}-container")
649
|> JS.add_class("overflow-hidden", to: "body")
650
|> JS.focus_first(to: "##{id}-content")
651
end
652
653
def hide_modal(js \\ %JS{}, id) do
654
js
655
|> JS.hide(
656
to: "##{id}-bg",
657
transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"}
658
)
659
|> hide("##{id}-container")
660
|> JS.hide(to: "##{id}", transition: {"block", "block", "hidden"})
661
|> JS.remove_class("overflow-hidden", to: "body")
662
|> JS.pop_focus()
663
end
664
665
@doc """
666
Translates an error message using gettext.
667
"""
668
def translate_error({msg, opts}) do
669
# When using gettext, we typically pass the strings we want
670
# to translate as a static argument:
671
#
672
# # Translate the number of files with plural rules
673
# dngettext("errors", "1 file", "%{count} files", count)
674
#
675
# However the error messages in our forms and APIs are generated
676
# dynamically, so we need to translate them by calling Gettext
677
# with our gettext backend as first argument. Translations are
678
# available in the errors.po file (as we use the "errors" domain).
679
if count = opts[:count] do
680
Gettext.dngettext(BlogWeb.Gettext, "errors", msg, msg, count, opts)
681
else
682
Gettext.dgettext(BlogWeb.Gettext, "errors", msg, opts)
683
end
684
end
685
686
@doc """
687
Translates the errors for a field from a keyword list of errors.
688
"""
689
def translate_errors(errors, field) when is_list(errors) do
690
for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts})
691
end
692
end
693