defmodule PostlandWeb.ProfileLive do use PostlandWeb, :live_view alias Postland.Accounts.User alias Postland.Repo def render(assigns) do ~H"""
<.form for={@form} phx-submit="avatar" phx-change="avatar"> <.live_file_input :if={@editing} upload={@uploads.avatar} />
<.form for={@form} id="profile-form" phx-change="validate" phx-submit="submit">

<%= @account.name %>

@<%= @account.username %>@<%= @host %> <.input :if={@editing} field={@form[:name]} label="Display Name" />

<%= {:safe, Earmark.as_html!(@account.summary || "")} %>

<.input :if={@editing} field={@form[:summary]} type="textarea" label="Bio" />

<.button :if={!@editing} phx-click="edit">Edit Profile <.button :if={@editing} phx-click="edit" form="profile-form">Save Profile
""" 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() socket = socket |> assign(account: account, host: host, editing: false, form: form) |> allow_upload(:avatar, accept: ~w(.jpg .jpeg .png), progress: &handle_progress/3, auto_upload: true ) {:ok, socket} 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 def handle_event("avatar", _, socket) do # The actual upload is handled by auto-upload and the handle_progress callback {:noreply, socket} end def handle_progress(:avatar, entry, socket) do if entry.done? do uploaded_file = consume_uploaded_entry(socket, entry, fn meta -> Postland.Uploads.handle_upload(entry, meta) end) changeset = User.icon_changeset(socket.assigns.account, uploaded_file) case Repo.update(changeset) do {:ok, account} -> {:noreply, assign(socket, account: account)} {:error, _changeset} -> {:noreply, put_flash(socket, :error, "An error occurred while finishing upload.")} end else {:noreply, socket} end end end