aboutsummaryrefslogtreecommitdiff
path: root/client/src/Util/Validation.hs
blob: f9545a4dcb23975031e70006c3cec2e17fa62a72 (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
module Util.Validation
  ( nelError
  , toMaybe
  , maybeError
  , fireValidation
  , fireMaybe
  ) where

import           Control.Monad      (join)
import           Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NEL
import           Data.Text          (Text)
import           Data.Validation    (Validation (Failure, Success))
import qualified Data.Validation    as Validation
import           Reflex.Dom         (Dynamic, Event, Reflex)
import qualified Reflex.Dom         as R

nelError :: Validation a b -> Validation (NonEmpty a) b
nelError = Validation.validation (Failure . NEL.fromList . (:[])) Success

toMaybe :: Validation a b -> Maybe b
toMaybe (Success s) = Just s
toMaybe (Failure _) = Nothing

maybeError :: Validation a b -> Maybe a
maybeError (Success _) = Nothing
maybeError (Failure e) = Just e

fireValidation
  :: forall t a b c. Reflex t
  => Dynamic t (Validation a b)
  -> Event t c
  -> Event t b
fireValidation value validate =
  R.fmapMaybe
    (Validation.validation (const Nothing) Just)
    (R.tag (R.current value) validate)

fireMaybe
  :: forall t a b. Reflex t
  => Dynamic t (Maybe a)
  -> Event t b
  -> Event t a
fireMaybe value validate =
  R.fmapMaybe
    id
    (R.tag (R.current value) validate)