module View.Income.Reducer ( perPage , reducer , In(..) ) where import Data.Text (Text) import qualified Data.Text as T import Reflex.Dom (Dynamic, Event, MonadWidget) import qualified Reflex.Dom as R import Common.Model (IncomePage) import Loadable (Loadable (..)) import qualified Loadable as Loadable import qualified Util.Ajax as AjaxUtil perPage :: Int perPage = 7 data In t a b c = In { _in_newPage :: Event t Int , _in_currentPage :: Dynamic t Int , _in_addIncome :: Event t a , _in_editIncome :: Event t b , _in_deleteIncome :: Event t c } data Action = LoadPage Int | GetResult (Either Text IncomePage) reducer :: forall t m a b c. MonadWidget t m => In t a b c -> m (Dynamic t (Loadable IncomePage)) reducer input = do postBuild <- R.getPostBuild let loadPage = R.leftmost [ 1 <$ postBuild , _in_newPage input , 1 <$ _in_addIncome input , R.tag (R.current $ _in_currentPage input) (_in_editIncome input) , R.tag (R.current $ _in_currentPage input) (_in_deleteIncome input) ] getResult <- AjaxUtil.get $ fmap pageUrl loadPage R.foldDyn (\action _ -> case action of LoadPage _ -> Loading GetResult (Left err) -> Error err GetResult (Right incomes) -> Loaded incomes ) Loading (R.leftmost [ LoadPage <$> loadPage , GetResult <$> getResult ]) where pageUrl p = "api/incomes?page=" <> (T.pack . show $ p) <> "&perPage=" <> (T.pack . show $ perPage)