defmodule PutzplanWeb.TaskLive.Show do require Ash.Query use PutzplanWeb, :live_view @pubsub_name Putzplan.PubSub defp get_topic(id) do "completed:" <> id end @impl true def render(assigns) do ~H""" <.header> Task {@task.description} <:actions> <.link patch={~p"/tasks/#{@task}/show/edit"} phx-click={JS.push_focus()}> <.button>Edit task
<.modal :if={@live_action in [:new, :edit]} id="task-modal" show on_cancel={JS.patch(~p"/tasks/#{@task}")} > <.live_component module={PutzplanWeb.TaskLive.FormComponent} id={(@task && @task.id) || :new} title={@page_title} current_user={@current_user} action={@live_action} task={@task} patch={~p"/"} /> <.back navigate={~p"/"}>Back to tasks """ end @impl true def mount(%{"id" => id}, _session, socket) do if connected?(socket), do: Phoenix.PubSub.subscribe(@pubsub_name, get_topic(id)) {:ok, socket} end @impl true def handle_params(%{"id" => id}, _, socket) do task = Ash.get!(Putzplan.Tasks.Task, id, actor: socket.assigns.current_user) {:noreply, socket |> assign(:page_title, page_title(socket.assigns.live_action)) |> assign(:task, task) |> stream( :completed_tasks, Putzplan.Tasks.CompletedTask |> Ash.Query.filter(task_id == ^task.id) |> Ash.read!(actor: socket.assigns[:current_user]) )} end defp page_title(:show), do: "Show Task" defp page_title(:edit), do: "Edit Task" @impl true def handle_event("delete", %{"id" => id}, socket) do completed_task = Ash.get!(Putzplan.Tasks.CompletedTask, id, actor: socket.assigns.current_user) Ash.destroy!(completed_task, actor: socket.assigns.current_user) Phoenix.PubSub.broadcast!(@pubsub_name, get_topic(id), {:delete, completed_task}) Phoenix.PubSub.broadcast!(@pubsub_name, "tasks", {:update, completed_task.tasks.id}) {:noreply, socket} end @impl true def handle_info({:delete, completed_task}, socket) do {:noreply, stream_delete(socket, :completed_tasks, completed_task)} end @impl true def handle_info({:upsert, completed_task}, socket) do {:noreply, stream_insert(socket, :completed_tasks, completed_task)} end end