aboutsummaryrefslogtreecommitdiff
path: root/client/src/View/Payment/Pages.hs
blob: dfd92c05513da93959fa14646c2f26eb76480768 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
module View.Payment.Pages
  ( widget
  , PagesIn(..)
  , PagesOut(..)
  ) where

import qualified Data.Text              as T
import           Reflex.Dom             (Dynamic, Event, MonadWidget)
import qualified Reflex.Dom             as R

import           Common.Model           (Payment (..))

import           Component              (ButtonIn (..), ButtonOut (..))
import qualified Component              as Component

import qualified Icon
import qualified View.Payment.Constants as Constants

data PagesIn t = PagesIn
  { _pagesIn_payments :: Dynamic t [Payment]
  }

data PagesOut t = PagesOut
  { _pagesOut_currentPage :: Dynamic t Int
  }

widget :: forall t m. MonadWidget t m => PagesIn t -> m (PagesOut t)
widget pagesIn = do
  R.divClass "pages" $ do
    rec
      currentPage <- R.holdDyn 1 . R.leftmost $ [ firstPageClic, previousPageClic, pageClic, nextPageClic, lastPageClic ]

      firstPageClic <- pageButton noCurrentPage (R.constDyn 1) Icon.doubleLeftBar

      previousPageClic <- pageButton noCurrentPage (fmap (\x -> max (x - 1) 1) currentPage) Icon.doubleLeft

      pageClic <- pageEvent <$> (R.simpleList (range <$> currentPage <*> maxPage) $ \p ->
        pageButton (Just <$> currentPage) p (R.dynText $ fmap (T.pack . show) p))

      nextPageClic <- pageButton noCurrentPage ((\c m -> min (c + 1) m) <$> currentPage <*> maxPage) Icon.doubleRight

      lastPageClic <- pageButton noCurrentPage maxPage Icon.doubleRightBar

    return $ PagesOut
      { _pagesOut_currentPage = currentPage
      }

    where maxPage =
            R.ffor (_pagesIn_payments pagesIn) (\payments ->
              ceiling $ toRational (length payments) / toRational Constants.paymentsPerPage
            )

          pageEvent = R.switchPromptlyDyn . fmap R.leftmost

          noCurrentPage = R.constDyn Nothing

range :: Int -> Int -> [Int]
range currentPage maxPage = [start..end]
  where sidePages = 2
        start = max 1 (min (currentPage - sidePages) (maxPage - sidePages * 2))
        end = min maxPage (start + sidePages * 2)

pageButton :: forall t m. MonadWidget t m => Dynamic t (Maybe Int) -> Dynamic t Int -> m () -> m (Event t Int)
pageButton currentPage page content = do
  clic <- _buttonOut_clic <$> (Component.button $ ButtonIn
    { _buttonIn_class   = do
        cp <- currentPage
        p <- page
        if cp == Just p then "page current" else "page"
    , _buttonIn_content = content
    , _buttonIn_waiting = R.never
    })
  return . fmap fst $ R.attach (R.current page) clic