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 (Frequency (..), Payment (..)) import Component (ButtonIn (..), ButtonOut (..)) import qualified Component as Component import qualified Icon import qualified View.Payment.Constants as Constants data PagesIn = PagesIn { _pagesIn_payments :: [Payment] } data PagesOut t = PagesOut { _pagesOut_currentPage :: Dynamic t Int } widget :: forall t m. MonadWidget t m => PagesIn -> m (PagesOut t) widget pagesIn = do R.divClass "pages" $ do rec currentPage <- R.holdDyn 1 . R.leftmost $ [ firstPageClic, previousPageClic, pageClic, nextPageClic, lastPageClic ] firstPageClic <- pageButton (R.constDyn 0) (R.constDyn 1) Icon.doubleLeftBar previousPageClic <- pageButton (R.constDyn 0) (fmap (\x -> max (x - 1) 1) currentPage) Icon.doubleLeft pageClic <- pageEvent <$> (R.simpleList (fmap (range maxPage) currentPage) $ \p -> pageButton currentPage p (R.dynText $ fmap (T.pack . show) p)) nextPageClic <- pageButton (R.constDyn 0) (fmap (\x -> min (x + 1) maxPage) currentPage) Icon.doubleRight lastPageClic <- pageButton (R.constDyn 0) (R.constDyn maxPage) Icon.doubleRightBar return $ PagesOut { _pagesOut_currentPage = currentPage } where paymentCount = length . filter ((==) Punctual . _payment_frequency) . _pagesIn_payments $ pagesIn maxPage = ceiling $ toRational paymentCount / toRational Constants.paymentsPerPage pageEvent = R.switchPromptlyDyn . fmap R.leftmost range :: Int -> Int -> [Int] range maxPage currentPage = [start..end] where sidePages = 2 start = max 1 (currentPage - sidePages) end = min maxPage (start + sidePages * 2) pageButton :: forall t m. MonadWidget t m => Dynamic t 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 == p then "page current" else "page" , _buttonIn_content = content , _buttonIn_waiting = R.never }) return . fmap fst $ R.attach (R.current page) clic