defmodule ExmrWeb.ExamLive.Index do use ExmrWeb, :live_view alias Exmr.Exams alias Exmr.Exams.Exam @impl true def mount(_params, _session, socket) do socket = socket |> assign(:exams, Exams.list_exams()) |> assign(:sort_by, "date") {:ok, socket} end @impl true def handle_params(params, _url, socket) do {:noreply, apply_action(socket, socket.assigns.live_action, params)} end defp apply_action(socket, :edit, %{"id" => id}) do socket |> assign(:page_title, "Edit Exam") |> assign(:exam, Exams.get_exam!(id)) end defp apply_action(socket, :new, _params) do socket |> assign(:page_title, "New Exam") |> assign(:exam, %Exam{}) end defp apply_action(socket, :index, _params) do socket |> assign(:page_title, "Listing Exams") |> assign(:exam, nil) end @impl true def handle_info({ExmrWeb.ExamLive.FormComponent, {:saved, exam}}, socket) do socket = socket |> assign(:exams, [exam | socket.assigns.exams]) {:noreply, socket} end @impl true def handle_event("remove", %{"id" => id}, socket) do exam = Exams.get_exam!(id) {:ok, _} = Exams.delete_exam(exam) socket = socket |> update(:exams, fn exams -> Enum.reject(exams, fn l -> l.id == exam.id end) end) {:noreply, socket} end def handle_event("sort", %{"by" => sort_by}, socket) do exams = sort_items(socket.assigns.exams, sort_by) {:noreply, assign(socket, exams: exams, sort_by: sort_by)} end defp sort_items(items, "subject") do Enum.sort_by(items, & &1.subject) end defp sort_items(items, "date") do Enum.sort_by(items, & &1.date, &Date.before?/2) end end