postland/lib/postland_web/live/profile_live.ex
2024-10-26 10:43:59 -05:00

69 lines
2.4 KiB
Elixir

defmodule PostlandWeb.ProfileLive do
use PostlandWeb, :live_view
alias Postland.Accounts.User
alias Postland.Repo
def render(assigns) do
~H"""
<div class="flex items-start space-x-4">
<img class="h-16 w-16 rounded-full" src={url(~p"/images/avatar.png")} alt="" />
<div class="flex flex-col bg-white rounded-lg shadow container">
<.form for={@form} id="profile-form" phx-change="validate" phx-submit="submit">
<div class="p-4">
<h2 :if={!@editing} class="font-bold"><%= @account.name %></h2>
<.input :if={@editing} field={@form[:name]} label="Display Name" />
<span :if={!@editing} class="text-gray-500">
@<%= @account.username %>@<%= @host %>
</span>
</div>
<hr />
<div class="p-4">
<p :if={!@editing} class="text-gray-500 text-sm">
<%= {:safe, Earmark.as_html!(@account.summary || "")} %>
</p>
<.input :if={@editing} field={@form[:summary]} type="textarea" label="Bio" />
</div>
</.form>
<hr />
<div :if={assigns[:current_user]} class="text-right p-4">
<.button :if={!@editing} phx-click="edit">Edit Profile</.button>
<.button :if={@editing} phx-click="edit" form="profile-form">Save Profile</.button>
</div>
</div>
</div>
"""
end
def mount(_params, _session, socket) do
%{host: host} = URI.parse(Postland.my_actor_id())
account = Postland.Accounts.solo_user()
form = account |> User.profile_changeset(%{}) |> to_form()
{:ok, assign(socket, account: account, host: host, editing: false, form: form)}
end
def handle_event("edit", _, socket) do
{:noreply, assign(socket, :editing, true)}
end
def handle_event("validate", params, socket) do
changeset = User.profile_changeset(socket.assigns.account, params)
form = to_form(changeset)
{:noreply, assign(socket, form: form)}
end
def handle_event("submit", %{"user" => params}, socket) do
changeset = User.profile_changeset(socket.assigns.account, params)
case Repo.update(changeset) do
{:ok, account} ->
form = account |> User.profile_changeset(%{}) |> to_form()
{:noreply, assign(socket, account: account, editing: false, form: form)}
{:error, changeset} ->
form = to_form(changeset)
{:noreply, socket |> put_flash(:error, "An error occurred.") |> assign(form: form)}
end
end
end