packages feed

devforms-0.2.0.2: src/Form.hs

module Form (Form (..), FormBuilder, renderForm, getSubmitUrl, getFormUrl) where

import Control.Monad.Writer
import Htmx.Lucid.Core
import Lucid
import Question (Question, renderQuestion)

data Form = Form {title :: Text, formId :: Text, questions :: [Question]} deriving (Show)

-- | A builder monad for adding questions to a form. Use the @question*@ functions to add questions.
type FormBuilder = Writer (Endo Form)

renderForm :: Form -> Html ()
renderForm form@Form{title, questions} = do
    h2_ $ toHtml title
    validationEnhancer_ $
        form_ [hxPost_ $ getSubmitUrl form, script_ "on keydown[key is 'Enter'] from <input/> halt"] $ do
            forM_ (reverse questions) renderQuestion
            input_ [type_ "submit"]

validationEnhancer_ :: Html () -> Html ()
validationEnhancer_ = term "validation-enhancer"

getFormUrl :: (IsString a) => Form -> a
getFormUrl Form{formId} = fromString $ "/" <> toString formId

getSubmitUrl :: (IsString a) => Form -> a
getSubmitUrl Form{formId} = fromString $ "/api/submit/" <> toString formId