module Text.Digestive.Form
( Form
, SomeForm (..)
, (.:)
, text
, string
, stringRead
, choice
, bool
, file
, check
, checkM
, validate
, validateM
) where
import Data.List (findIndex)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Text.Digestive.Field
import Text.Digestive.Form.Internal
import Text.Digestive.Types
import Text.Digestive.Util
text :: Maybe Text -> Form v m Text
text def = Pure Nothing $ Text $ fromMaybe "" def
string :: Monad m => Maybe String -> Form v m String
string = fmap T.unpack . text . fmap T.pack
stringRead :: (Monad m, Read a, Show a) => v -> Maybe a -> Form v m a
stringRead err = transform readTransform . string . fmap show
where
readTransform = return . maybe (Error err) return . readMaybe
choice :: Eq a => [(a, v)] -> Maybe a -> Form v m a
choice items def = Pure Nothing $ Choice items $ fromMaybe 0 $
maybe Nothing (\d -> findIndex ((== d) . fst) items) def
bool :: Bool
-> Form v m Bool
bool = Pure Nothing . Bool
file :: Form v m (Maybe FilePath)
file = Pure Nothing File
check :: Monad m
=> v
-> (a -> Bool)
-> Form v m a
-> Form v m a
check err = checkM err . (return .)
checkM :: Monad m => v -> (a -> m Bool) -> Form v m a -> Form v m a
checkM err predicate form = validateM f form
where
f x = do
r <- predicate x
return $ if r then return x else Error err
validate :: Monad m => (a -> Result v b) -> Form v m a -> Form v m b
validate = validateM . (return .)
validateM :: Monad m => (a -> m (Result v b)) -> Form v m a -> Form v m b
validateM = transform