module Text.Digestive.Forms.Happstack
( HappstackForm
, happstackEnvironment
, eitherHappstackForm
) where
import Control.Monad (MonadPlus, liftM)
import Control.Applicative (Alternative, optional)
import Data.ByteString.Lazy.UTF8 as LB (toString)
import Data.Either
import Data.Text.Lazy as Text (toStrict)
import Data.Text.Lazy.Encoding as Text (decodeUtf8)
import Happstack.Server ( Input (..), HasRqData (..), lookInputs
, Method (..), ServerMonad (..), rqMethod
)
import Text.Digestive.Forms (FormInput (..))
import Text.Digestive.Types (Form (..), Environment (..), viewForm, eitherForm)
instance FormInput [Input] (String, FilePath) where
getInputStrings inps =
map LB.toString $ rights $ map inputValue inps
getInputTexts inps =
map (Text.toStrict . Text.decodeUtf8) $ rights $ map inputValue inps
getInputFile inps =
case inps of
(inp:_) ->
case inputValue inp of
(Left fp) ->
do fn <- inputFilename inp
return (fn, fp)
_ -> Nothing
_ -> Nothing
type HappstackForm m = Form m [Input]
happstackEnvironment :: (HasRqData m, MonadPlus m, Alternative m)
=> Environment m [Input]
happstackEnvironment = Environment $ fmap toMaybe . lookInputs . show
where
toMaybe :: [a] -> Maybe [a]
toMaybe [] = Nothing
toMaybe l = Just l
eitherHappstackForm :: (HasRqData m, MonadPlus m, Alternative m, ServerMonad m)
=> HappstackForm m e v a
-> String
-> m (Either v a)
eitherHappstackForm form name = askRq >>= \rq ->
case rqMethod rq of GET -> liftM Left $ viewForm form name
_ -> eitherForm form name happstackEnvironment