Data.Pagination

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{-# LANGUAGE RecordWildCards #-}
-- | Data pagination.

module Data.Pagination where

import Data.Default
import Data.Maybe
import Safe
import Network.URI
import Network.URI.Params

-- | A pagination object, holds information about the name, total, per
--   page, current page, etc.
data Pagination = Pagination
  { pnTotal       :: Integer
  , pnPerPage     :: Integer
  , pnName        :: String
  , pnCurrentPage :: Integer
  , pnShowDesc    :: Bool
  } deriving (Show)

instance Default Pagination where
  def = Pagination
        { pnTotal       = 0
        , pnPerPage     = 5
        , pnName        = ""
        , pnCurrentPage = 1
        , pnShowDesc    = True
        }

-- | Get the page count of the pagination results.
pnPageCount :: Pagination -> Integer
pnPageCount Pagination{..} = max 1 $
  if total/perpage > fromIntegral (round (total/perpage))
     then round (total/perpage) + 1
     else round (total/perpage)
  where total = fromIntegral pnTotal
        perpage = fromIntegral pnPerPage

-- | Add the current page of the pagination from the current URI.
addCurrentPage :: URI -> Pagination -> Pagination
addCurrentPage uri pagination = pagination { pnCurrentPage = currentPage } where
  currentPage = fromMaybe 1 $ do
    p <- lookup paramName $ uriParams uri
    readMay p
  paramName = pnName pagination ++ "_page"