mgwidmann / scrivener_html

HTML view helpers for Scrivener
MIT License
125 stars 208 forks source link

Add helper to display item count information #67

Closed dsandstrom closed 7 years ago

dsandstrom commented 7 years ago

Similar to what will_paginate has: 00000370

I always found this type of information handy and have included it in my Rails projects. I didn't see this option available for this plugin (sorry, not sure if that is the right term) and added a simple version of the functionality myself.

Would you accept a PR for this?

mgwidmann commented 7 years ago

You provide the %Scrivener.Page{} which has that information easily accessible so I'm not following whats to be gained by offering a helper to do that? Additionally, the copy would need to be swappable and I wouldn't want to introduce a gettext dependency. What would your helper do exactly?

dsandstrom commented 7 years ago

What would your helper do exactly?

The bottom part, "Displaying x 1-20, of 59 in total"

You provide the %Scrivener.Page{} which has that information easily accessible

It provides page_number, page_size, total_entries, total_pages, right? Does it provide the indexes of the entries on the current page?

Here is the code if it's helpful for anyone else. I'm new to elixir so I'm probably doing something fundamentally wrong and I need to cover some edge cases:

 def pagination_info(page, type) do
  total_entries = page.total_entries

  first_index = find_first_index(page)
  if first_index <= total_entries do
    content_tag :p, class: "pagination-info" do
      pagination_info_content(page, type)
    end
  end
end

defp pagination_info_content(page, type) do
  page_size = page.page_size
  total_entries = page.total_entries
  first_index = find_first_index(page)
  last_index = find_last_index(page)

  if page_size >= total_entries do
    "Displaying all #{type}"
  else
    start = "Displaying "
    indexes =
      if page_size > 1 and first_index != last_index do
        "#{first_index} - #{last_index}"
      else
        first_index
      end

    indexes = content_tag :strong, indexes
    total_entries = content_tag(:strong, total_entries)

    [start, type, " ", indexes, " of ", total_entries, " in total"]
  end
end

defp find_first_index(page) do
  (page.page_number - 1) * page.page_size + 1
end

defp find_last_index(page) do
  page_number = page.page_number
  page_size = page.page_size
  total_entries = page.total_entries

  index = if page_size > 1, do: page_number * page_size
  cond do
    index > total_entries -> total_entries
    true -> index
  end
end

Use like so:

<%= pagination_info @page, "Widgets" %>
mgwidmann commented 7 years ago

I think this should be a helper in your application since that text you have in there will need to be configurable and internationalized w/ gettext. If you really feel it something others could use, feel free to create your own package on hex.