import Ex import Util import FileExList import CheckAnswer import Text.XHtml import Network.NewCGI hiding (Html) import Control.Monad import Data.Maybe file = "test.tl" type Result = ([ExId],[ExId]) emptyResult :: Result emptyResult = ([],[]) updateResult :: Bool -> Ex -> Result -> Result updateResult ok ex (p,f) = if ok then (exID ex:p,f) else (p,exID ex:f) -- -- * UI building -- ask :: Result -> Ex -> [Html] ask res ex = [quest] ++ gui where quest = p << [toHtml "Translate: ", emphasize << question ex] gui = [form ! [name "transform", method "post"] << [hidden "exercise" (show (exID ex)), hidden "result" (show res), textfield "answer", submit "submit" "Submit"], inlineJavascript "document.transform.answer.focus();" ] feedback :: Ex -> String -> [Html] feedback ex ans = [p << ("You translated \"" ++ question ex ++ "\" to \"" ++ ans ++ "\".")] ++ res where res | checkAnswer ex ans = [p << "Correct!"] | otherwise = [p << "Incorrect! Correct:", ulist << map (li <<) (answers ex)] score :: Result -> Html score (pass,fail) = p << ("Score: " ++ show (length pass) ++ " / " ++ show (length pass + length fail)) -- -- * Process form input -- getAnswer :: Exercises -> CGI (Maybe (Ex,String)) getAnswer exs = do mi <- readInput "exercise" let me = mi >>= getExercise exs ma <- getInput "answer" return $ liftM2 (,) me ma getResult :: CGI Result getResult = liftM (fromMaybe emptyResult) $ readInput "result" cgiMain :: CGI CGIResult cgiMain = do exs <- liftIO $ readExFile file ma <- getAnswer exs res <- getResult let feed = maybe [] (uncurry feedback) ma ex <- liftIO $ randomExercise exs let tit = thetitle << "GF Translation Exercises" hdr = [tit] scr = [score res] bdy = feed ++ ask res ex ++ scr page = thehtml << [header << hdr, body << bdy] outputHtml page outputHtml :: Html -> CGI CGIResult outputHtml h = do setHeader "Content-type" "text/html; charset=UTF-8" output (renderHtml h) main :: IO () main = runCGI cgiMain -- -- * Html utilities -- inlineJavascript :: String -> Html inlineJavascript s = tag "script" ! [thetype "text/javascript"] << primHtml s