Jake Prem's Blog

LiveView Event Playground

Added February 18, 2025
Run in Livebook
  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
Mix.install([
  {:phoenix_playground, ">= 0.0.0"}
])

defmodule SimpleComponent do
  use Phoenix.Component

  attr :count, :integer, required: true
  slot :inner_block, required: true

  def counter(assigns) do
    ~H"""
    <p>Count: {@count}</p>
    <button
      phx-click="component-clicked"
      phx-value-count={@count + 1}>
        {render_slot(@inner_block)}
    </button>
    """
  end
end

defmodule SimpleLiveView do
  use Phoenix.LiveView
  import SimpleComponent

  def render(assigns) do
    ~H"""
    <.counter count={@count}>Click me</.counter>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, count: 0)}
  end

  # This works, but our LiveView has no control besides the assign name.
  def handle_event("component-clicked", %{"count" => count}, socket) do
    count = String.to_integer(count)
    {:noreply, assign(socket, count: count)}
  end
end

defmodule SmartComponent do
  use Phoenix.Component

  attr :count, :integer, required: true
  attr :on_click, :any, required: true
  slot :inner_block, required: true

  def counter(assigns) do
    ~H"""
    <p>Count: {@count}</p>
    <button phx-click={@on_click} phx-value-count={@count + 1}>
      {render_slot(@inner_block)}
    </button>
    """
  end
end

defmodule SmartLiveView do
  use Phoenix.LiveView
  alias Phoenix.LiveView.JS

  import SmartComponent

  def render(assigns) do
    ~H"""
    <h2>Custom Event Counter</h2>
    <.counter count={@custom_event_count} on_click="custom-event">
      Increment Custom Event Counter
    </.counter>

    <h2>Query Params Counter</h2>
    <.counter
      count={@query_params_count}
      on_click={JS.patch("/smart?count=#{@query_params_count + 1}")}
    >
      Increment Query Params
    </.counter>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, custom_event_count: 0, query_params_count: 0)}
  end

  def handle_event("custom-event", %{"count" => count}, socket) do
    count = String.to_integer(count)
    {:noreply, assign(socket, custom_event_count: count)}
  end

  def handle_params(params, _uri, socket) do
    count = params["count"] || "0"
    count = String.to_integer(count)
    {:noreply, assign(socket, query_params_count: count)}
  end
end

defmodule CallbackComponent do
  use Phoenix.Component

  attr :count, :integer, required: true
  attr :on_click, :any, required: true
  slot :inner_block, required: true

  def counter(assigns) do
    ~H"""
    <p>Count: {@count}</p>
    <button
      phx-click={@on_click && @on_click.(%{count: @count + 1})}
      phx-value-count={@count + 1}
    >
      {render_slot(@inner_block)}
    </button>
    """
  end
end

defmodule CallbackLiveView do
  use Phoenix.LiveView
  alias Phoenix.LiveView.JS

  import CallbackComponent

  def render(assigns) do
    ~H"""
    <h2>Query Params Counter</h2>
    <.counter
      count={@query_params_count}
      on_click={fn %{count: new_count} -> 
        JS.patch("/callback?count=#{new_count}")
      end}
    >
      Increment Query Params
    </.counter>

    <h2>Custom Event Counter</h2>
    <.counter
      count={@custom_event_count}
      on_click={fn %{count: new_count} -> 
        JS.push("increment-counter", value: %{count: new_count}) 
      end}
    >
      Click me
    </.counter>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, query_params_count: 0, custom_event_count: 0)}
  end

  def handle_params(params, _uri, socket) do
    count = params["count"] || "0"
    count = String.to_integer(count)
    {:noreply, assign(socket, query_params_count: count)}
  end

  def handle_event("increment-counter", %{"count" => count}, socket) do
    {:noreply, assign(socket, custom_event_count: count)}
  end
end

defmodule SmartestComponent do
  use Phoenix.Component
  alias Phoenix.LiveView.JS

  attr :count, :integer, required: true
  attr :on_click, :any, required: true
  slot :inner_block, required: true

  def counter(assigns) do
    ~H"""
    <p>Count: {@count}</p>
    <button
      phx-click={generate_on_click(@on_click, %{count: @count + 1})}
      phx-value-count={@count + 1}
    >
      {render_slot(@inner_block)}
    </button>
    """
  end

  defp generate_on_click(on_click_attr, context) do
    case on_click_attr do
      nil -> nil
      click when is_binary(click) -> click
      %JS{} = click -> click
      click when is_function(click, 1) -> click.(context)
    end
  end
end

defmodule SmartestLiveView do
  use Phoenix.LiveView
  alias Phoenix.LiveView.JS

  import SmartestComponent

  def render(assigns) do
    ~H"""
    <h2>Query Params Counter</h2>
    <.counter
      count={@query_params_count}
      on_click={fn %{count: new_count} ->
        JS.patch("/smartest?count=#{new_count}")
      end}
    >
      Increment Query Params
    </.counter>

    <h2>Custom Event Counter</h2>
    <.counter
      count={@custom_event_count}
      on_click={fn %{count: new_count} ->
        JS.push("increment-event", value: %{count: new_count})
      end}
    >
      Click me
    </.counter>

    <h2>JS Push Counter</h2>
    <.counter count={@js_push_count} on_click={fn %{count: new_count} ->
        JS.push("js-push-increment", value: %{count: new_count})
      end}
    >
      Click me
    </.counter>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, query_params_count: 0, custom_event_count: 0, js_push_count: 0)}
  end

  def handle_event("increment-event", %{"count" => count}, socket) do
    count = String.to_integer(count)
    {:noreply, assign(socket, custom_event_count: count)}
  end

  def handle_event("js-push-increment", %{"count" => count}, socket) do
    count = String.to_integer(count)
    {:noreply, assign(socket, js_push_count: count)}
  end

  def handle_params(params, _uri, socket) do
    count = params["count"] || "0"
    count = String.to_integer(count)
    {:noreply, assign(socket, query_params_count: count)}
  end
end

defmodule CalendarComponent do
  use Phoenix.Component

  attr :current_date, :map, required: true
  attr :selected_month, :map, required: true
  attr :events, :list, default: []
  attr :date_changed, :any, required: true
  attr :date_clicked, :any, default: nil

  def calendar(assigns) do
    assigns = assign(assigns, events_map: Enum.group_by(assigns.events, & &1.date))

    ~H"""
    <div style="width: 100%; max-width: 800px; margin: 0 auto;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <button phx-click={@date_changed && @date_changed.(%{selected_month: shift_month(@selected_month, -1)})} style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; cursor: pointer;">
          Previous
        </button>
        <button phx-click={@date_changed && @date_changed.(%{selected_month: shift_month(Date.utc_today(), 0)})} style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; cursor: pointer;">
          Today
        </button>
        <h2 style="margin: 0; font-size: 1.5rem;">
          <%= Calendar.strftime(@selected_month, "%B %Y") %>
        </h2>
        <button phx-click={@date_changed && @date_changed.(%{selected_month: Date.shift(@selected_month, month: 1)})} style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; cursor: pointer;">
          Next
        </button>
      </div>

      <div style="display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; background: #ddd;">
        <%= for day <- ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] do %>
          <div style="background: #f8f8f8; padding: 10px; text-align: center; font-weight: bold;">
            <%= day %>
          </div>
        <% end %>

        <%= for date <- calendar_days(@selected_month) do %>
          <div phx-click={@date_clicked && @date_clicked.(%{date: date})} style={"background: #fff; padding: 10px; min-height: 100px; position: relative;#{if run_handler(@date_clicked, %{date: date}), do: " cursor: pointer;", else: ""}#{if date == @current_date, do: " background: lightyellow;", else: ""}"}>
            <div style={"position: absolute; top: 5px; left: 5px;#{if date.month != @selected_month.month, do: " color: #999", else: ""}"}>
              <%= date.day %>
            </div>

            <div style="margin-top: 25px;">
              <%= for event <- Map.get(@events_map, date, []) do %>
                <div
                  phx-click={run_handler(@date_clicked, %{date: date, event: event})}
                  style={"background: #e3f2fd; padding: 4px 8px; margin-bottom: 4px; border-radius: 4px; font-size: 0.875rem;#{if run_handler(@date_clicked, %{date: date, event: event}), do: " cursor: pointer;", else: ""}"}
                >
                  <%= event.title %>
                </div>
              <% end %>
            </div>
          </div>
        <% end %>
      </div>
    </div>
    """
  end

  defp shift_month(date, amount), do: Date.shift(date, month: amount)

  defp run_handler(handler, context), do: handler && handler.(context)

  defp calendar_days(date) do
    first_day = Date.beginning_of_month(date)
    last_day = Date.end_of_month(date)

    first_calendar_day = Date.add(first_day, -rem(Date.day_of_week(first_day) - 1, 7))
    last_calendar_day = Date.add(last_day, 7 - rem(Date.day_of_week(last_day), 7))

    Date.range(first_calendar_day, last_calendar_day)
  end
end

defmodule CalendarLive do
  use Phoenix.LiveView
  alias Phoenix.LiveView.JS

  import CalendarComponent

  def render(assigns) do
    ~H"""
    <.calendar
      :if={@live_action == :calendar}
      current_date={@current_date}
      selected_month={@selected_month}
      events={@events}
      date_changed={fn %{selected_month: new_month} -> JS.patch("/calendar?selected_month=#{new_month}") end}
      date_clicked={&build_date_clicked/1}
    />
    <%= if @live_action == :event do %>
      <.link patch={"/calendar?selected_month=#{@selected_month}"}>Back to calendar</.link>
      <h2>Event</h2>
      <dl>
        <dt>ID</dt>
        <dd><%= @event.id %></dd>
        <dt>Title</dt>
        <dd><%= @event.title %></dd>
        <dt>Date</dt>
        <dd><%= Calendar.strftime(@event.date, "%B %d, %Y") %></dd>
      </dl>
    <% end %>
    """
  end

  defp build_date_clicked(%{date: _date, event: event}) do
    if event[:disabled] do
      nil
    else
      JS.patch("/calendar/event/#{event[:id]}")
    end
  end

  defp build_date_clicked(_), do: nil

  def mount(_params, _session, socket) do
    current_date = Date.utc_today()

    socket = socket
    |> assign(:current_date, current_date)
    |> assign(:events, events_for_month(current_date))

    {:ok, socket}
  end

  def handle_params(%{"id" => id}, _uri, socket) do
    event = get_event(id)
    event_date = event.date
    {:noreply, socket |> assign(event: event) |> assign_new(:selected_month, fn -> event_date end)}
  end

  def handle_params(params, _uri, socket) do
    selected_month =
      if month_str = params["selected_month"] do
        Date.from_iso8601!(month_str)
      else
        Date.utc_today()
      end

    events = events_for_month(selected_month)

    {:noreply, assign(socket, selected_month: selected_month, events: events)}
  end

  defp get_event(id) do
    sample_events() |> Enum.find(&(&1.id == String.to_integer(id)))
  end

  defp events_for_month(month) do
    sample_events()
    |> Enum.filter(fn event -> event.date.month == month.month && event.date.year == month.year end)
  end

  defp sample_events do
    reference_date = Date.utc_today()

    [
      %{id: 1, date: reference_date, title: "Pretzel Day"},
      %{id: 2, date: reference_date, title: "Brains Storming"},
      %{id: 3, date: Date.add(reference_date, 2), title: "Neon Night Market"},
      %{id: 4, date: Date.shift(reference_date, month: 1), title: "National Noodle Day"},
      %{id: 5, date: Date.shift(reference_date, month: 2), title: "Client Review"},
      %{id: 6, date: Date.add(reference_date, -5), title: "Time Traveler's Meeting"}
    ]
  end
end

defmodule Layouts do
  use Phoenix.Component

  def playground(assigns) do
    ~H"""
    <header style="display: flex; justify-content: center; gap: 10px; margin-bottom: 20px;">
      <.link patch="/simple">Simple</.link>
      <.link patch="/smart">Smart</.link>
      <.link patch="/callback">Callback</.link>
      <.link patch="/smartest">Smartest</.link>
      <.link patch="/calendar">Calendar</.link>
    </header>
    <main style="display: flex; justify-content: center;">
      <div style="width: 100%; max-width: 800px;">
      {@inner_content}
      </div>
    </main>
    """
  end
end

defmodule RedirectController do
  use Phoenix.Controller

  def index(conn, _params) do
    redirect(conn, to: conn.private[:to])
  end
end

defmodule PlaygroundRouter do
  use Phoenix.Router
  import Phoenix.LiveView.Router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :put_root_layout, html: {PhoenixPlayground.Layout, :root}
    plug :put_layout, html: {Layouts, :playground}
    plug :put_secure_browser_headers
  end

  scope "/" do
    pipe_through :browser

    get "/", RedirectController, :index, private: %{to: "/simple"}

    live_session :playground, layout: {Layouts, :playground} do
      live "/simple", SimpleLiveView
      live "/smart", SmartLiveView
      live "/callback", CallbackLiveView
      live "/smartest", SmartestLiveView
      live "/calendar", CalendarLive, :calendar
      live "/calendar/event/:id", CalendarLive, :event
    end
  end
end

PhoenixPlayground.start(plug: PlaygroundRouter)

# Run this file with:
# iex playground.exs