85 lines
2.2 KiB
Elixir

defmodule SendItWeb.ContactLive.Index do
use SendItWeb, :live_view
alias SendIt.Marketing
alias SendIt.Marketing.Contact
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(page: 1, per_page: 20)
|> paginate_contacts(1)}
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Contact")
|> assign(:contact, %Contact{})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Contacts")
|> assign(:contact, nil)
end
@impl true
def handle_info({SendItWeb.ContactLive.FormComponent, {:saved, contact}}, socket) do
{:noreply, stream_insert(socket, :contacts, contact)}
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
contact = Marketing.get_contact!(id)
{:ok, _} = Marketing.delete_contact(contact)
{:noreply, stream_delete(socket, :contacts, contact)}
end
def handle_event("next-page", _, socket) do
IO.puts("NEXT Pageee")
{:noreply, paginate_contacts(socket, socket.assigns.page + 1)}
end
def handle_event("prev-page", %{"_overran" => true}, socket) do
{:noreply, paginate_contacts(socket, 1)}
end
def handle_event("prev-page", _, socket) do
if socket.assigns.page > 1 do
{:noreply, paginate_contacts(socket, socket.assigns.page - 1)}
else
{:noreply, socket}
end
end
defp paginate_contacts(socket, new_page) when new_page >= 1 do
%{per_page: per_page, page: cur_page} = socket.assigns
contacts = Marketing.list_contacts(offset: (new_page - 1) * per_page, limit: per_page)
{contacts, at, limit} =
if new_page >= cur_page do
{contacts, -1, per_page * 3 * -1}
else
{Enum.reverse(contacts), 0, per_page * 3}
end
case contacts do
[] ->
assign(socket, end_of_timeline?: at == -1)
[_ | _] = contacts ->
socket
|> assign(end_of_timeline?: false)
|> assign(:page, new_page)
|> stream(:contacts, contacts, at: at, limit: limit)
end
end
end