defmodule Phoenix.WebComponent.Pagination do @moduledoc """ Render pagination. """ use Phoenix.WebComponent, :html @doc """ Generates a pagination. ## Examples <.wc_pagination page_num={5} page_size={15} total={100} update_event="update-page"/> """ @doc type: :component attr(:id, :any, default: false, doc: """ html attribute id """ ) attr(:class, :string, default: "", doc: """ html attribute class """ ) attr(:page_size, :integer, default: 10, doc: """ items shows per page """ ) attr(:page_num, :integer, default: 1, doc: """ page num """ ) attr(:total, :integer, default: 0, doc: """ total items count """ ) attr(:update_event, :string, default: "update_current_page", doc: """ Phoenix live event name for page status update. """ ) def wc_pagination(assigns) do max_page = if assigns.total > 0 do (assigns.total / assigns.page_size) |> ceil else 1 end page_num = assigns.page_num pages = cond do max_page == 1 -> [1] max_page < 7 -> 1..max_page |> Enum.map(& &1) page_num < 3 -> [1, 2, 3] ++ ["..."] ++ [max_page - 2, max_page - 1, max_page] page_num == 3 -> [1, 2, 3, 4] ++ ["..."] ++ [max_page - 2, max_page - 1, max_page] page_num > 3 && page_num < max_page - 2 -> [1] ++ ["...", page_num - 1, page_num, page_num + 1, "..."] ++ [max_page] page_num == max_page - 2 -> [1, 2, 3] ++ ["...", max_page - 3, max_page - 2, max_page - 1, max_page] page_num > max_page - 2 -> [1, 2, 3] ++ ["...", max_page - 2, max_page - 1, max_page] end assigns = assigns |> assign(:max_page, max_page) |> assign(:pages, pages) ~H"""
Total <%= @total %>