diff --git a/lib/decentralised_book_index_web/live/author_live/edit.ex b/lib/decentralised_book_index_web/live/author_live/edit.ex new file mode 100644 index 0000000..96d013e --- /dev/null +++ b/lib/decentralised_book_index_web/live/author_live/edit.ex @@ -0,0 +1,60 @@ +defmodule DecentralisedBookIndexWeb.AuthorLive.Edit do + use DecentralisedBookIndexWeb, :live_view + + alias DecentralisedBookIndex.Metadata + + @impl true + def render(assigns) do + ~H""" + <.live_component + module={DecentralisedBookIndexWeb.AuthorLive.FormComponent} + id={(@author && @author.id) || :new} + title={@page_title} + current_user={@current_user} + action={@live_action} + author={@author} + /> + """ + end + + @impl true + def mount(_params, _session, socket) do + {:ok, + socket + |> stream( + :authors, + Ash.read!(DecentralisedBookIndex.Metadata.Author, actor: socket.assigns[:current_user]) + ) + |> assign_new(:current_user, fn -> nil end)} + end + + @impl true + def handle_params(params, _url, socket) do + socket = + socket + |> assign(:params, params) + |> apply_action(socket.assigns.live_action, params) + + {:noreply, socket} + end + + defp apply_action(socket, :edit, %{"id" => id}) do + socket + |> assign(:page_title, "Edit Author") + |> assign( + :author, + Ash.get!(DecentralisedBookIndex.Metadata.Author, id, actor: socket.assigns.current_user) + ) + end + + defp apply_action(socket, :new, _params) do + socket + |> assign(:page_title, "New Author") + |> assign(:author, nil) + end + + @impl true + def handle_info({DecentralisedBookIndexWeb.AuthorLive.FormComponent, {:saved, author}}, socket) do + {:noreply, stream_insert(socket, :authors, author)} + end +end