Skip to content

Instantly share code, notes, and snippets.

@ream88
Last active January 30, 2025 13:28
Show Gist options
  • Save ream88/7d11015b4d3648273ae7213f9330e345 to your computer and use it in GitHub Desktop.
Save ream88/7d11015b4d3648273ae7213f9330e345 to your computer and use it in GitHub Desktop.
A Phoenix LiveView toggle
defmodule AppWeb.Toggle do
@moduledoc false
use AppWeb, :live_component
attr :name, :string, required: true
attr :checked, :boolean, required: true
def toggle(assigns) do
assigns = assign_new(assigns, :id, fn %{name: name} -> "toggle_#{name}" end)
~H|<.live_component module={__MODULE__} {assigns} />|
end
@impl true
def mount(socket) do
ok(socket)
end
@impl true
def update(assigns, socket) do
socket
|> assign(assigns)
|> ok()
end
@impl true
def render(assigns) do
~H"""
<button
type="button"
class={["relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-hidden focus:ring-2 focus:ring-offset-2", if(@checked, do: "bg-green-500", else: "bg-neutral-200")]}
role="switch"
aria-checked={if(@checked, do: "true", else: "false")}
phx-click="toggle"
value={@name}
>
<span class="sr-only">Use setting</span>
<span
aria-hidden="true"
class={["size-5 pointer-events-none inline-block transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ease-in-out", if(@checked, do: "translate-x-5", else: "translate-x-0")]}
>
</span>
</button>
"""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment