{-# language GADTs #-}
{-# language OverloadedStrings #-}
{-# language TypeOperators #-}

{- |
Typed construction and rendering of `Yesod` input forms.

Forms are built from type-safe `FormPiece`s describing individual fields and their layout.
Pieces can be combined horizontally or vertically and rendered as a `CompleteForm` using `formify`.

The result type of a form determines the types and requiredness of its fields.
For custom product types, this structure can be derived generically through `Formify`.

This module provides basic input fields, single- and multiple-choice fields,
list forms, and several specialized field types.
-}

module FlexTask.Form.Core (
  -- * Form Types
  Formify(FormTypes),
  FormPiece,
  SimpleFormPiece,
  ListFormPiece,
  AnyFormPiece,
  CompleteForm,
  -- * Creating Form Pieces
  BaseField(..),
  basic,
  singleChoice,
  singleChoiceEnum,
  multipleChoice,
  multipleChoiceEnum,
  list,
  listRepeatedly,
  listWithoutLabels,
  -- * Fields for List Forms
  -- $TypeFields
  TypeField,
  basicField,
  singleChoiceField,
  singleChoiceEnumField,
  -- * Composition and Layout
  (>|),
  beside,
  (>-),
  above,
  -- * Rendering
  formify,
  formifyComponents,
  formifyComponentsFlat,
  -- * Appearance and Layout Options
  Alignment(..),
  ChoiceShape(..),
  -- * Type-Level Helper Types
  OneField,
  ManyFields,
  (:>),
  type (++),
  CanBeOptional,
  ) where


import Data.List.Extra (
  intercalate,
  nubOrd,
  singleton,
  zipWithLongest,
  )
import Data.Maybe           (catMaybes)
import Data.Text            (Text, pack)
import Yesod (
  AForm,
  Field,
  FieldSettings(..),
  PathPiece,
  SomeMessage,
  Textarea,
  areq,
  aopt,
  boolField,
  convertField,
  doubleField,
  hiddenField,
  intField,
  multiSelectField,
  optionsPairs,
  textareaField,
  textField,
  )

import FlexTask.Form.Formify            (Formify(..))
import FlexTask.Form.Util               (applyToWidget)
import FlexTask.Form.Widgets
  ( checkboxField
  , radioField
  , joinWidgets
  , renderForm
  , selectField
  )
import FlexTask.Form.TypeLevel
import FlexTask.Form.Types (
  FlexForm(..),
  Handler,
  Rendered,
  Widget,
  )
import FlexTask.InputTypes (
  Hidden(..),
  MultipleChoice(..),
  MultipleChoiceSelection,
  SingleChoiceSelection,
  SingleInputList(..),
  singleChoiceAnswer,
  )


{- $setup
>>> :set -XTypeApplications
>>> :set -XDeriveGeneric
>>> :set -XOverloadedStrings
>>> import FlexTask.Form.Util
>>> import FlexTask.InputTypes
>>> import GHC.Generics (Generic)
>>> import Data.Text (Text)
>>> data MyType = One | Two | Three deriving (Bounded, Enum, Eq, Generic, Show)
>>> data MyCoolType = Yes | No deriving (Generic, Eq)
>>> instance Formify MyType
>>> instance Formify MyCoolType
>>> let toCool b = if b then Yes else No
>>> let fromCool c = c == Yes
>>> let existingField = baseField
-}


-- | Represents a specific input field associated with given type @a@.
data TypeField a where
  Basic :: BaseField a => (FieldSettings FlexForm) -> TypeField a
  SingleChoiceField
    :: Eq a
    => ChoiceShape
    -> (FieldSettings FlexForm)
    -> [(SomeMessage FlexForm, a)]
    -> TypeField a
  MultipleChoiceField
    :: Eq a
    => ChoiceShape
    -> (FieldSettings FlexForm)
    -> [(SomeMessage FlexForm, a)]
    -> TypeField (MultipleChoice a)


{- |

The layout data type.
This type is used to select and arrange the input fields in a type-safe manner.
Each `FormPiece` is a form fragment parametrized by the desired final type of the complete form
and the type of the fragment itself.
The overall type is given as a plain type,
while the type of the fragment is a type-level non-empty list of types,
corresponding to the selected input fields.

For example, for a product type

@
data Person = Person {name :: Text, age :: Int, occupation :: Text}
@

we might want to define a form fragment that contains only the first two parts of the record,
but is locked into becoming a @Person@ form:

@
nameAgePiece :: FormPiece Person (OneField Text :> OneField Int)
@

or we could leave the overall type variable, so any type consisting of `Text` and `Int` in that order,
e.g. @(Text,Int)@ could use the fragment:

@
stringIntPiece :: FormPiece t (OneField Text :> OneField Int)
@

You will mostly be able to use the simpler type synonyms `SimpleFormPiece`, `ListFormPiece`,
`AnyFormPiece` or `CompleteForm` to avoid dealing with type-level lists.
-}
data FormPiece finalType fields where
  Single :: TypeField a -> SimpleFormPiece t a
  Combine :: Alignment -> FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
  List :: Alignment -> [TypeField a] -> ListFormPiece t a


{- |
Alias for a `FormPiece` whose fields exactly match the complete form representation of its final type.
Adding another piece will therefore result in a value that is no longer a `CompleteForm`.

@
CompleteForm Person ≡ AnyFormPiece Person Person ≡ FormPiece Person (FormTypes Person)
@
-}
type CompleteForm a = AnyFormPiece a a

{- |
Alias for a `FormPiece` with exactly one type and field
that avoids having to write out the type-level list.

@
SimpleFormPiece t Text ≡ FormPiece t (OneField Text)
@
-}
type SimpleFormPiece t a = FormPiece t (OneField a)


{- |
Alias for a `FormPiece` with exactly one type but multiple fields (a collection)
that avoids having to write out the type-level list.

@
ListFormPiece t Double ≡ FormPiece t (ManyFields Double)
@
-}
type ListFormPiece t a = FormPiece t (ManyFields a)


{- |
Alias for a `FormPiece` with arbitrarily many types
that avoids having to write out the type-level list.

@
AnyFormPiece t Person ≡ FormPiece t (OneField Text :> OneField Int :> OneField Text)
@

@
AnyFormPiece t (Text,Int,Text) ≡ FormPiece t (OneField Text :> OneField Int :> OneField Text)
@

-}
type AnyFormPiece t a = FormPiece t (FormTypes a)


-- | Choice between horizontal and vertical alignment.
data Alignment = Horizontal | Vertical deriving (Alignment -> Alignment -> Bool
(Alignment -> Alignment -> Bool)
-> (Alignment -> Alignment -> Bool) -> Eq Alignment
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Alignment -> Alignment -> Bool
== :: Alignment -> Alignment -> Bool
$c/= :: Alignment -> Alignment -> Bool
/= :: Alignment -> Alignment -> Bool
Eq,Int -> Alignment -> ShowS
[Alignment] -> ShowS
Alignment -> String
(Int -> Alignment -> ShowS)
-> (Alignment -> String)
-> ([Alignment] -> ShowS)
-> Show Alignment
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Alignment -> ShowS
showsPrec :: Int -> Alignment -> ShowS
$cshow :: Alignment -> String
show :: Alignment -> String
$cshowList :: [Alignment] -> ShowS
showList :: [Alignment] -> ShowS
Show)


-- | Choice between radio buttons/checkboxes and selection menus
data ChoiceShape
  = Buttons Alignment
  -- ^ Buttons arranged according to the given alignment
  | Dropdown
  -- ^ Selection menu


{- |
Types that can be represented as a simple Yesod input field.
A `BaseField` instance of type @a@ is needed if @a@ requires a type-specific input method,
i.e. it is not just a wrapping newtype or product type that can be built out of existing input methods.

Common types, like `Int`, `Text` or `Bool`, are already instances of this class,
so you should not need to write your own instances.

An instance can be given manually using the `Field` constructor
or the `convertField` function on an existing `Field` if required anyway.

=== __Example__

>>> instance BaseField MyCoolType where baseField = convertField toCool fromCool existingField
-}
class (Formify a, FormTypes a ~ OneField a) => BaseField a where
  {- |
  The Yesod field used to render values of this type.
  The `Yesod.Form.Types.fieldParse` component of the `Field` is not used.
  It can be assigned `undefined`.
  -}
  baseField :: Field Handler a


instance BaseField Integer where
  baseField :: Field Handler Integer
baseField = Field Handler Integer
forall (m :: * -> *) i.
(Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) =>
Field m i
intField

instance BaseField Int where
  baseField :: Field Handler Int
baseField = Field Handler Int
forall (m :: * -> *) i.
(Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) =>
Field m i
intField

instance BaseField Text where
  baseField :: Field Handler Text
baseField = Field Handler Text
forall (m :: * -> *).
(Monad m, RenderMessage (HandlerSite m) FormMessage) =>
Field m Text
textField


instance BaseField Textarea where
  baseField :: Field Handler Textarea
baseField = Field Handler Textarea
forall (m :: * -> *).
(Monad m, RenderMessage (HandlerSite m) FormMessage) =>
Field m Textarea
textareaField


instance BaseField Bool where
  baseField :: Field Handler Bool
baseField = Field Handler Bool
forall (m :: * -> *).
(Monad m, RenderMessage (HandlerSite m) FormMessage) =>
Field m Bool
boolField


instance BaseField Double where
  baseField :: Field Handler Double
baseField = Field Handler Double
forall (m :: * -> *).
(Monad m, RenderMessage (HandlerSite m) FormMessage) =>
Field m Double
doubleField


instance (Formify a, PathPiece a) => BaseField (Hidden a) where
  baseField :: Field Handler (Hidden a)
baseField = Field Handler (Hidden a)
forall (m :: * -> *) p.
(Monad m, PathPiece p,
 RenderMessage (HandlerSite m) FormMessage) =>
Field m p
hiddenField


-- This indicates I should probably change this class to something more succinct.
-- The first function is never used, since it normally handles the parsing.
instance Show a => BaseField (SingleInputList a) where
  baseField :: Field Handler (SingleInputList a)
baseField = (Text -> SingleInputList a)
-> (SingleInputList a -> Text)
-> Field Handler Text
-> Field Handler (SingleInputList a)
forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> (b -> a) -> Field m a -> Field m b
convertField Text -> SingleInputList a
forall a. HasCallStack => a
undefined (String -> Text
pack (String -> Text)
-> (SingleInputList a -> String) -> SingleInputList a -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " ([String] -> String)
-> (SingleInputList a -> [String]) -> SingleInputList a -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> String) -> [a] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map a -> String
forall a. Show a => a -> String
show ([a] -> [String])
-> (SingleInputList a -> [a]) -> SingleInputList a -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SingleInputList a -> [a]
forall a. SingleInputList a -> [a]
getList) Field Handler Text
forall (m :: * -> *).
(Monad m, RenderMessage (HandlerSite m) FormMessage) =>
Field m Text
textField


combineWidgets
  :: Alignment
  -> Rendered [[a]]
  -> Rendered [[a]]
  -> Rendered [[a]]
combineWidgets :: forall a.
Alignment -> Rendered [[a]] -> Rendered [[a]] -> Rendered [[a]]
combineWidgets Alignment
align Rendered [[a]]
f1 Rendered [[a]]
f2 = do
    res1 <- Rendered [[a]]
ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[a]]))
f1
    res2 <- f2
    pure $ do
      (ids1,names1,xss) <- res1
      (ids2,names2,yss) <- res2
      pure
        ( ids1 ++ ids2
        , nubOrd $ names1 ++ names2
        , appendWidgets xss yss)
  where
    appendWidgets :: [[a]] -> [[a]] -> [[a]]
appendWidgets = case Alignment
align of
      Alignment
Vertical -> [[a]] -> [[a]] -> [[a]]
forall a. [a] -> [a] -> [a]
(++)
      Alignment
Horizontal -> (Maybe [a] -> Maybe [a] -> [a]) -> [[a]] -> [[a]] -> [[a]]
forall a b c. (Maybe a -> Maybe b -> c) -> [a] -> [b] -> [c]
zipWithLongest (\Maybe [a]
xs Maybe [a]
ys -> [[a]] -> [a]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[a]] -> [a]) -> [[a]] -> [a]
forall a b. (a -> b) -> a -> b
$ [Maybe [a]] -> [[a]]
forall a. [Maybe a] -> [a]
catMaybes [Maybe [a]
xs,Maybe [a]
ys])


{- |
Renders a form from a `CompleteForm` description,
optionally prefilling its fields with a default value.

Whether individual fields are required or optional is determined by the `CompleteForm`'s result type.
For example, a field corresponding to `Text` is required,
while one corresponding to `Maybe` `Text` is optional.
The type of the default value, when present,
must match that result type and can be used to infer it.

For example

@
formify (Just "enter name") $ basic "last name"
@

determines the `Text` input is required

@
formify (Just $ Just "enter name") $ basic "last name"
@

would make it optional instead.

This also applies for multiple fields

@
formify (Just ("enter name", True)) $ basic "last name" >- basic "receive newsletter?"
@

means both fields are required

@
formify (Just ("enter name", Nothing)) $ basic "last name" >- basic "receive newsletter?"
@

means the `Text` field is required, while the `Bool` field is optional.

Forms for custom data types will also automatically infer this
based on the types of the constructor fields.

Note that the type of the form can only be inferred if either the default is a `Just` value
or the `CompleteForm` was previously given an explicit type signature.
You will have to use `TypeApplications` on `formify` if that's not the case, e.g.

@
formify @(Text, Maybe Bool) Nothing $ basic "last name" >- basic "receive newsletter?"
@

More examples can be found under sections /Creating Form Pieces/ and /Composition and Layout/
-}
formify
  :: Formify a
  => Maybe a
  -- ^ Optional default value.
  -> CompleteForm a
  -- ^ Structure and type of the form.
  -> Rendered Widget
  -- ^ Rendered form.
formify :: forall a. Formify a => Maybe a -> CompleteForm a -> Rendered Widget
formify Maybe a
mDefault = ([[Widget]] -> Widget)
-> Rendered' (ReaderT Html Identity) [[Widget]] -> Rendered Widget
forall (m :: * -> *) w w'.
Functor m =>
(w -> w') -> Rendered' m w -> Rendered' m w'
applyToWidget [[Widget]] -> Widget
joinWidgets (ReaderT
   Html
   Identity
   (RWST
      (Maybe (Env, FileEnv), FlexForm, [Text])
      Enctype
      Ints
      Handler
      ([Text], [[Text]], [[Widget]]))
 -> ReaderT
      Html
      Identity
      (RWST
         (Maybe (Env, FileEnv), FlexForm, [Text])
         Enctype
         Ints
         Handler
         ([Text], [[Text]], Widget)))
-> (FormPiece a (FormTypes a)
    -> ReaderT
         Html
         Identity
         (RWST
            (Maybe (Env, FileEnv), FlexForm, [Text])
            Enctype
            Ints
            Handler
            ([Text], [[Text]], [[Widget]])))
-> FormPiece a (FormTypes a)
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], Widget))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe a
-> FormPiece a (FormTypes a)
-> Rendered' (ReaderT Html Identity) [[Widget]]
forall a.
Formify a =>
Maybe a
-> CompleteForm a -> Rendered' (ReaderT Html Identity) [[Widget]]
formifyComponents Maybe a
mDefault


{- |
Like `formify`, but yields the individual sub-renders instead of a combined form.
Retains the layout structure given by the `CompleteForm` as a nested list.
Each inner list is a row in the form layout.
This can be used in custom forms to incorporate `formify`-generated forms.
-}
formifyComponents
  :: Formify a
  => Maybe a
  -- ^ Optional default value for form
  -> CompleteForm a
  -- ^ Structure and type of form
  -> Rendered [[Widget]]
  -- ^ structured sub-renders
formifyComponents :: forall a.
Formify a =>
Maybe a
-> CompleteForm a -> Rendered' (ReaderT Html Identity) [[Widget]]
formifyComponents Maybe a
mDefault = TypeList (FormTypes a)
-> FormPiece a (FormTypes a)
-> Rendered' (ReaderT Html Identity) [[Widget]]
forall a t.
TypeList a
-> FormPiece t a -> Rendered' (ReaderT Html Identity) [[Widget]]
renderLayout (Maybe a -> TypeList (FormTypes a)
forall a. Formify a => Maybe a -> TypeList (FormTypes a)
formDefaults Maybe a
mDefault)


{- |
Like `formifyComponents`, but forgets the layout information of `CompleteForm`.
Simply returns all sub-renders in a flat list.
-}
formifyComponentsFlat
  :: Formify a
  => Maybe a
  -- ^ Optional default value for form
  -> CompleteForm a
  -- ^ Structure and type of form
  -> Rendered [Widget]
  -- ^ sub-renders
formifyComponentsFlat :: forall a.
Formify a =>
Maybe a -> CompleteForm a -> Rendered [Widget]
formifyComponentsFlat Maybe a
mDefault = ([[Widget]] -> [Widget])
-> Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered [Widget]
forall (m :: * -> *) w w'.
Functor m =>
(w -> w') -> Rendered' m w -> Rendered' m w'
applyToWidget [[Widget]] -> [Widget]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (ReaderT
   Html
   Identity
   (RWST
      (Maybe (Env, FileEnv), FlexForm, [Text])
      Enctype
      Ints
      Handler
      ([Text], [[Text]], [[Widget]]))
 -> ReaderT
      Html
      Identity
      (RWST
         (Maybe (Env, FileEnv), FlexForm, [Text])
         Enctype
         Ints
         Handler
         ([Text], [[Text]], [Widget])))
-> (FormPiece a (FormTypes a)
    -> ReaderT
         Html
         Identity
         (RWST
            (Maybe (Env, FileEnv), FlexForm, [Text])
            Enctype
            Ints
            Handler
            ([Text], [[Text]], [[Widget]])))
-> FormPiece a (FormTypes a)
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [Widget]))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe a
-> FormPiece a (FormTypes a)
-> Rendered' (ReaderT Html Identity) [[Widget]]
forall a.
Formify a =>
Maybe a
-> CompleteForm a -> Rendered' (ReaderT Html Identity) [[Widget]]
formifyComponents Maybe a
mDefault


renderRequiredness :: OneDefault a -> TypeField a -> Rendered Widget
renderRequiredness :: forall a. OneDefault a -> TypeField a -> Rendered Widget
renderRequiredness (OptionalDefault Maybe a
mDefault) TypeField a
field = (Field Handler a
 -> FieldSettings FlexForm -> AForm Handler (Maybe a))
-> TypeField a -> Rendered Widget
forall a c.
(Field Handler a -> FieldSettings FlexForm -> AForm Handler c)
-> TypeField a -> Rendered Widget
renderField (\Field Handler a
f FieldSettings FlexForm
fs -> Field Handler a
-> FieldSettings (HandlerSite Handler)
-> Maybe (Maybe a)
-> AForm Handler (Maybe a)
forall (m :: * -> *) a.
MonadHandler m =>
Field m a
-> FieldSettings (HandlerSite m)
-> Maybe (Maybe a)
-> AForm m (Maybe a)
aopt Field Handler a
f FieldSettings (HandlerSite Handler)
FieldSettings FlexForm
fs (Maybe (Maybe a) -> AForm Handler (Maybe a))
-> Maybe (Maybe a) -> AForm Handler (Maybe a)
forall a b. (a -> b) -> a -> b
$ Maybe a -> Maybe (Maybe a)
forall a. a -> Maybe a
Just Maybe a
mDefault) TypeField a
field
renderRequiredness (RequiredDefault Maybe a
mDefault) TypeField a
field = (Field Handler a -> FieldSettings FlexForm -> AForm Handler a)
-> TypeField a -> Rendered Widget
forall a c.
(Field Handler a -> FieldSettings FlexForm -> AForm Handler c)
-> TypeField a -> Rendered Widget
renderField (\Field Handler a
f FieldSettings FlexForm
fs -> Field Handler a
-> FieldSettings FlexForm -> Maybe a -> AForm Handler a
forall site (m :: * -> *) a.
(RenderMessage site FormMessage, HandlerSite m ~ site,
 MonadHandler m) =>
Field m a -> FieldSettings site -> Maybe a -> AForm m a
areq Field Handler a
f FieldSettings FlexForm
fs Maybe a
mDefault) TypeField a
field


renderField :: (Field Handler a  -> FieldSettings FlexForm -> AForm Handler c) -> TypeField a -> Rendered Widget
renderField :: forall a c.
(Field Handler a -> FieldSettings FlexForm -> AForm Handler c)
-> TypeField a -> Rendered Widget
renderField Field Handler a -> FieldSettings FlexForm -> AForm Handler c
req TypeField a
info = case TypeField a
info of
  Basic FieldSettings FlexForm
fs -> (FieldSettings FlexForm -> AForm Handler c)
-> FieldSettings FlexForm -> Rendered Widget
forall a.
(FieldSettings FlexForm -> AForm Handler a)
-> FieldSettings FlexForm -> Rendered Widget
renderForm (Field Handler a -> FieldSettings FlexForm -> AForm Handler c
req Field Handler a
forall a. BaseField a => Field Handler a
baseField) FieldSettings FlexForm
fs
  SingleChoiceField ChoiceShape
k FieldSettings FlexForm
fs [(SomeMessage FlexForm, a)]
xs -> (FieldSettings FlexForm -> AForm Handler c)
-> FieldSettings FlexForm -> Rendered Widget
forall a.
(FieldSettings FlexForm -> AForm Handler a)
-> FieldSettings FlexForm -> Rendered Widget
renderForm (Field Handler a -> FieldSettings FlexForm -> AForm Handler c
req (Field Handler a -> FieldSettings FlexForm -> AForm Handler c)
-> Field Handler a -> FieldSettings FlexForm -> AForm Handler c
forall a b. (a -> b) -> a -> b
$ case ChoiceShape
k of
    ChoiceShape
Dropdown -> Handler (OptionList a) -> Field Handler a
forall a. Eq a => Handler (OptionList a) -> Field Handler a
selectField (Handler (OptionList a) -> Field Handler a)
-> Handler (OptionList a) -> Field Handler a
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> Handler (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs
    Buttons Alignment
Vertical -> Bool -> Handler (OptionList a) -> Field Handler a
forall a. Eq a => Bool -> Handler (OptionList a) -> Field Handler a
radioField Bool
True (Handler (OptionList a) -> Field Handler a)
-> Handler (OptionList a) -> Field Handler a
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> Handler (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs
    Buttons Alignment
Horizontal -> Bool -> Handler (OptionList a) -> Field Handler a
forall a. Eq a => Bool -> Handler (OptionList a) -> Field Handler a
radioField Bool
False (Handler (OptionList a) -> Field Handler a)
-> Handler (OptionList a) -> Field Handler a
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> Handler (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs) FieldSettings FlexForm
fs
  MultipleChoiceField ChoiceShape
k FieldSettings FlexForm
fs [(SomeMessage FlexForm, a)]
xs -> (FieldSettings FlexForm -> AForm Handler c)
-> FieldSettings FlexForm -> Rendered Widget
forall a.
(FieldSettings FlexForm -> AForm Handler a)
-> FieldSettings FlexForm -> Rendered Widget
renderForm (Field Handler a -> FieldSettings FlexForm -> AForm Handler c
req (Field Handler a -> FieldSettings FlexForm -> AForm Handler c)
-> Field Handler a -> FieldSettings FlexForm -> AForm Handler c
forall a b. (a -> b) -> a -> b
$
    ([a] -> a) -> (a -> [a]) -> Field Handler [a] -> Field Handler a
forall (m :: * -> *) a b.
Functor m =>
(a -> b) -> (b -> a) -> Field m a -> Field m b
convertField [a] -> a
[a] -> MultipleChoice a
forall a. [a] -> MultipleChoice a
MultipleChoice a -> [a]
MultipleChoice a -> [a]
forall a. MultipleChoice a -> [a]
getChoices (Field Handler [a] -> Field Handler a)
-> Field Handler [a] -> Field Handler a
forall a b. (a -> b) -> a -> b
$ case ChoiceShape
k of
      ChoiceShape
Dropdown -> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a site.
Eq a =>
HandlerFor site (OptionList a) -> Field (HandlerFor site) [a]
multiSelectField (HandlerFor FlexForm (OptionList a) -> Field Handler [a])
-> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> HandlerFor FlexForm (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs
      Buttons Alignment
Vertical -> Bool -> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a.
Eq a =>
Bool -> Handler (OptionList a) -> Field Handler [a]
checkboxField Bool
True (HandlerFor FlexForm (OptionList a) -> Field Handler [a])
-> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> HandlerFor FlexForm (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs
      Buttons Alignment
Horizontal -> Bool -> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a.
Eq a =>
Bool -> Handler (OptionList a) -> Field Handler [a]
checkboxField Bool
False (HandlerFor FlexForm (OptionList a) -> Field Handler [a])
-> HandlerFor FlexForm (OptionList a) -> Field Handler [a]
forall a b. (a -> b) -> a -> b
$ [(SomeMessage FlexForm, a)] -> HandlerFor FlexForm (OptionList a)
forall (m :: * -> *) msg a.
(MonadHandler m, RenderMessage (HandlerSite m) msg) =>
[(msg, a)] -> m (OptionList a)
optionsPairs [(SomeMessage FlexForm, a)]
xs) FieldSettings FlexForm
fs


renderLayout :: TypeList a -> FormPiece t a -> Rendered [[Widget]]
renderLayout :: forall a t.
TypeList a
-> FormPiece t a -> Rendered' (ReaderT Html Identity) [[Widget]]
renderLayout (TOne OneDefault x
mDefault) (Single TypeField a
x) = (Widget -> [[Widget]])
-> Rendered Widget -> Rendered' (ReaderT Html Identity) [[Widget]]
forall (m :: * -> *) w w'.
Functor m =>
(w -> w') -> Rendered' m w -> Rendered' m w'
applyToWidget ([Widget] -> [[Widget]]
forall a. a -> [a]
singleton ([Widget] -> [[Widget]])
-> (Widget -> [Widget]) -> Widget -> [[Widget]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Widget -> [Widget]
forall a. a -> [a]
singleton) (Rendered Widget -> Rendered' (ReaderT Html Identity) [[Widget]])
-> Rendered Widget -> Rendered' (ReaderT Html Identity) [[Widget]]
forall a b. (a -> b) -> a -> b
$
  OneDefault x -> TypeField x -> Rendered Widget
forall a. OneDefault a -> TypeField a -> Rendered Widget
renderRequiredness OneDefault x
mDefault TypeField x
TypeField a
x
renderLayout TypeList a
mDefault (Combine Alignment
align FormPiece t xs
x FormPiece t ys
y) = TypeList xs
-> FormPiece t xs -> Rendered' (ReaderT Html Identity) [[Widget]]
forall a t.
TypeList a
-> FormPiece t a -> Rendered' (ReaderT Html Identity) [[Widget]]
renderLayout TypeList xs
a FormPiece t xs
x Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
`how` TypeList ys
-> FormPiece t ys -> Rendered' (ReaderT Html Identity) [[Widget]]
forall a t.
TypeList a
-> FormPiece t a -> Rendered' (ReaderT Html Identity) [[Widget]]
renderLayout TypeList ys
b FormPiece t ys
y
  where
    (TypeList xs
a,TypeList ys
b) = TypeShape xs -> TypeList (xs ++ ys) -> (TypeList xs, TypeList ys)
forall xs ys.
TypeShape xs -> TypeList (xs ++ ys) -> (TypeList xs, TypeList ys)
splitTypeList (FormPiece t xs -> TypeShape xs
forall t xs. FormPiece t xs -> TypeShape xs
pieceShape FormPiece t xs
x) TypeList a
TypeList (xs ++ ys)
mDefault
    how :: Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
how = Alignment
-> Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
-> Rendered' (ReaderT Html Identity) [[Widget]]
forall a.
Alignment -> Rendered [[a]] -> Rendered [[a]] -> Rendered [[a]]
combineWidgets Alignment
align
renderLayout (TMany OneDefault x
t Maybe [OneDefault x]
mDefault) (List Alignment
align [TypeField a]
fs) =
    (ReaderT
   Html
   Identity
   (RWST
      (Maybe (Env, FileEnv), FlexForm, [Text])
      Enctype
      Ints
      Handler
      ([Text], [[Text]], [[Widget]]))
 -> ReaderT
      Html
      Identity
      (RWST
         (Maybe (Env, FileEnv), FlexForm, [Text])
         Enctype
         Ints
         Handler
         ([Text], [[Text]], [[Widget]]))
 -> ReaderT
      Html
      Identity
      (RWST
         (Maybe (Env, FileEnv), FlexForm, [Text])
         Enctype
         Ints
         Handler
         ([Text], [[Text]], [[Widget]])))
-> [ReaderT
      Html
      Identity
      (RWST
         (Maybe (Env, FileEnv), FlexForm, [Text])
         Enctype
         Ints
         Handler
         ([Text], [[Text]], [[Widget]]))]
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [[Widget]]))
forall a. (a -> a -> a) -> [a] -> a
forall (t :: * -> *) a. Foldable t => (a -> a -> a) -> t a -> a
foldr1 ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[Widget]]))
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [[Widget]]))
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [[Widget]]))
addParams [TypeList (OneField x)
-> FormPiece (ZonkAny 0) (OneField x)
-> Rendered' (ReaderT Html Identity) [[Widget]]
forall a t.
TypeList a
-> FormPiece t a -> Rendered' (ReaderT Html Identity) [[Widget]]
renderLayout (OneDefault x -> TypeList (OneField x)
forall x. OneDefault x -> TypeList (OneField x)
TOne OneDefault x
d) (TypeField x -> FormPiece (ZonkAny 0) (OneField x)
forall a t. TypeField a -> SimpleFormPiece t a
Single TypeField x
TypeField a
f) | (OneDefault x
d,TypeField a
f) <- [OneDefault x] -> [TypeField a] -> [(OneDefault x, TypeField a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [OneDefault x]
defaults [TypeField a]
fs]
  where
    defaults :: [OneDefault x]
defaults = case Maybe [OneDefault x]
mDefault of
      Maybe [OneDefault x]
Nothing -> OneDefault x -> [OneDefault x]
forall a. a -> [a]
repeat OneDefault x
t
      Just [OneDefault x]
ds
        | [OneDefault x] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [OneDefault x]
ds Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= [TypeField a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [TypeField a]
fs
          -> String -> [OneDefault x]
forall a. HasCallStack => String -> a
error
              String
"Lengths of form default value and FieldInfo list do not match!"
        | Bool
otherwise -> [OneDefault x]
ds


    addParams :: ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[Widget]]))
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [[Widget]]))
-> ReaderT
     Html
     Identity
     (RWST
        (Maybe (Env, FileEnv), FlexForm, [Text])
        Enctype
        Ints
        Handler
        ([Text], [[Text]], [[Widget]]))
addParams ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[Widget]]))
f1 ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[Widget]]))
f2 = do
      res1 <- ReaderT
  Html
  Identity
  (RWST
     (Maybe (Env, FileEnv), FlexForm, [Text])
     Enctype
     Ints
     Handler
     ([Text], [[Text]], [[Widget]]))
f1
      res2 <- f2
      pure $ do
        (ids1,names1,wid1) <- res1
        (ids2,names2,wid2) <- res2
        pure
          ( ids1 ++ ids2
          , [nubOrd $ concat $ names1 ++ names2]
          , case align of
              Alignment
Vertical   -> [[Widget]]
wid1 [[Widget]] -> [[Widget]] -> [[Widget]]
forall a. [a] -> [a] -> [a]
++ [[Widget]]
wid2
              Alignment
Horizontal -> [[[Widget]] -> [Widget]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[Widget]] -> [Widget]) -> [[Widget]] -> [Widget]
forall a b. (a -> b) -> a -> b
$ [[Widget]]
wid1 [[Widget]] -> [[Widget]] -> [[Widget]]
forall a. [a] -> [a] -> [a]
++ [[Widget]]
wid2]
          )


{- $TypeFields

The functions in this section behave identically to their counterparts producing a `FormPiece`,
for example `basicField` behaves like `basic`, but produces a `TypeField` instead.

Their purpose is to restrict the options that can be used with `list` at the type level.
The builder passed to `list` must produce a `TypeField`.
It cannot produce a composed `FormPiece`, such as one obtained using `>|`.

The restriction is necessary,
because the current approach to parsing the user input cannot handle arbitrary combinations,
but only a specific subset of those.
There is also no `TypeField` equivalent for `multipleChoice` and `multipleChoiceEnum` for the same reason.
Lists of `MultipleChoice` forms are therefore not supported at the moment.
-}


{- |
A typed single input field.
-}
basicField :: BaseField a => FieldSettings FlexForm -> TypeField a
basicField :: forall a. BaseField a => FieldSettings FlexForm -> TypeField a
basicField = FieldSettings FlexForm -> TypeField a
forall a. BaseField a => FieldSettings FlexForm -> TypeField a
Basic


{- |
A `TypeField` for custom enum types.
This is either a set of radio buttons or a selection menu,
depending on the given `ChoiceShape`.

The third argument is an assignment of labels for each enum constructor.
-}
singleChoiceEnumField
  :: (Eq a, Bounded a, Enum a)
  => ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> (a -> SomeMessage FlexForm)
  -- ^ Function from enum type values to labels.
  -> TypeField a
singleChoiceEnumField :: forall a.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField a
singleChoiceEnumField ChoiceShape
shape FieldSettings FlexForm
fs = ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField a
forall a.
Eq a =>
ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField a
SingleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs ([(SomeMessage FlexForm, a)] -> TypeField a)
-> ((a -> SomeMessage FlexForm) -> [(SomeMessage FlexForm, a)])
-> (a -> SomeMessage FlexForm)
-> TypeField a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> SomeMessage FlexForm) -> [(SomeMessage FlexForm, a)]
forall b a. (Bounded b, Enum b) => (b -> a) -> [(a, b)]
optionsFromType


{- |
A `TypeField` for the predefined `SingleChoiceSelection` type.
This is either a set of radio buttons or a selection menu,
depending on the given `ChoiceShape`.
-}
singleChoiceField
  :: ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> [SomeMessage FlexForm]
  -- ^ Option labels
  -> TypeField SingleChoiceSelection
singleChoiceField :: ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> TypeField SingleChoiceSelection
singleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs = ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, SingleChoiceSelection)]
-> TypeField SingleChoiceSelection
forall a.
Eq a =>
ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField a
SingleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs ([(SomeMessage FlexForm, SingleChoiceSelection)]
 -> TypeField SingleChoiceSelection)
-> ([SomeMessage FlexForm]
    -> [(SomeMessage FlexForm, SingleChoiceSelection)])
-> [SomeMessage FlexForm]
-> TypeField SingleChoiceSelection
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [SomeMessage FlexForm]
-> [(SomeMessage FlexForm, SingleChoiceSelection)]
forall a. [a] -> [(a, SingleChoiceSelection)]
options


multipleChoiceField
  :: ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> [SomeMessage FlexForm]
  -- ^ Option labels
  -> TypeField MultipleChoiceSelection
multipleChoiceField :: ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> TypeField MultipleChoiceSelection
multipleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs = ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, SingleChoiceSelection)]
-> TypeField MultipleChoiceSelection
forall a.
Eq a =>
ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField (MultipleChoice a)
MultipleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs ([(SomeMessage FlexForm, SingleChoiceSelection)]
 -> TypeField MultipleChoiceSelection)
-> ([SomeMessage FlexForm]
    -> [(SomeMessage FlexForm, SingleChoiceSelection)])
-> [SomeMessage FlexForm]
-> TypeField MultipleChoiceSelection
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [SomeMessage FlexForm]
-> [(SomeMessage FlexForm, SingleChoiceSelection)]
forall a. [a] -> [(a, SingleChoiceSelection)]
options


multipleChoiceEnumField
  :: (Eq a, Bounded a, Enum a)
  => ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> (a -> SomeMessage FlexForm)
  -- ^ Function from enum type values to labels.
  -> TypeField (MultipleChoice a)
multipleChoiceEnumField :: forall a.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField (MultipleChoice a)
multipleChoiceEnumField ChoiceShape
shape FieldSettings FlexForm
fs = ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField (MultipleChoice a)
forall a.
Eq a =>
ChoiceShape
-> FieldSettings FlexForm
-> [(SomeMessage FlexForm, a)]
-> TypeField (MultipleChoice a)
MultipleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs ([(SomeMessage FlexForm, a)] -> TypeField (MultipleChoice a))
-> ((a -> SomeMessage FlexForm) -> [(SomeMessage FlexForm, a)])
-> (a -> SomeMessage FlexForm)
-> TypeField (MultipleChoice a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> SomeMessage FlexForm) -> [(SomeMessage FlexForm, a)]
forall b a. (Bounded b, Enum b) => (b -> a) -> [(a, b)]
optionsFromType


single :: TypeField a -> SimpleFormPiece t a
single :: forall a t. TypeField a -> SimpleFormPiece t a
single = TypeField a -> SimpleFormPiece t a
forall a t. TypeField a -> SimpleFormPiece t a
Single


{- |
A typed single input `FormPiece`.

=== __Example__

>>> printWidget "en" $ formify @Int Nothing $ basic "Age"
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Age
    </label>
    <input id="flexident1" name="flex1" type="number" step="1" required="" value="">
...
</div>

![rendered Int form piece](doc-images/basic.png)
-}
basic :: BaseField a => FieldSettings FlexForm -> SimpleFormPiece t a
basic :: forall a t.
BaseField a =>
FieldSettings FlexForm -> SimpleFormPiece t a
basic = TypeField a -> SimpleFormPiece t a
forall a t. TypeField a -> SimpleFormPiece t a
single (TypeField a -> SimpleFormPiece t a)
-> (FieldSettings FlexForm -> TypeField a)
-> FieldSettings FlexForm
-> SimpleFormPiece t a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FieldSettings FlexForm -> TypeField a
forall a. BaseField a => FieldSettings FlexForm -> TypeField a
basicField


{- |
A `FormPiece` for the predefined `SingleChoiceSelection` type.
This is either a set of radio buttons or a selection menu,
depending on the given `ChoiceShape`.

=== __Example__

>>> let labels = ["First Option", "Second Option", "Third Option"]
>>> printWidget "en" $ formify (Just $ singleChoiceAnswer 3) $ singleChoice Dropdown "Choose one" labels
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose one
    </label>
    <select id="flexident1" ...>
      <option value="" selected disabled>
        &lt;None&gt;
      </option>
      <option value="1">
        First Option
      </option>
      <option value="2">
        Second Option
      </option>
      <option value="3" selected>
        Third Option
      </option>
    </select>
...
</div>

![rendered single choice field](doc-images/single_choice.png)
-}
singleChoice
  :: ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> [SomeMessage FlexForm]
  -- ^ option labels
  -> SimpleFormPiece t SingleChoiceSelection
singleChoice :: forall t.
ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> SimpleFormPiece t SingleChoiceSelection
singleChoice ChoiceShape
shape FieldSettings FlexForm
fs = TypeField SingleChoiceSelection
-> SimpleFormPiece t SingleChoiceSelection
forall a t. TypeField a -> SimpleFormPiece t a
single (TypeField SingleChoiceSelection
 -> SimpleFormPiece t SingleChoiceSelection)
-> ([SomeMessage FlexForm] -> TypeField SingleChoiceSelection)
-> [SomeMessage FlexForm]
-> SimpleFormPiece t SingleChoiceSelection
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> TypeField SingleChoiceSelection
singleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs


{- |
A `FormPiece` for custom enum types.
This is either a set of radio buttons or a selection menu,
depending on the given `ChoiceShape`.

The third argument is an assignment of labels for each enum constructor.


=== __Examples__

>>> printWidget "en" $ formify (Just Two) $ singleChoiceEnum (Buttons Horizontal) "Choose one" $ showToUniversalLabel @MyType
...
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose one
    </label>
    <div>
      <span id="flexident1">
        <label>
          <input id="flexident1-1" type="radio" ... value="1" required...>
          One
        </label>
        <label>
          <input id="flexident1-2" type="radio" ... value="2" checked required...>
          Two
        </label>
        <label>
          <input id="flexident1-3" type="radio" ... value="3" required...>
          Three
        </label>
      </span>
    </div>
...
</div>

![rendered single choice enum field](doc-images/single_choice_enum_buttons.png)

>>> printWidget "en" $ formify (Just Two) $ singleChoiceEnum Dropdown "Choose one" $ showToUniversalLabel @MyType
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose one
    </label>
    <select id="flexident1" ...>
      <option value="" selected disabled>
        &lt;None&gt;
      </option>
      <option value="1">
        One
      </option>
      <option value="2" selected>
        Two
      </option>
      <option value="3">
        Three
      </option>
    </select>
...
</div>

![rendered single choice enum field 2](doc-images/single_choice_enum_dropdown.png)
-}
singleChoiceEnum
  :: (Eq a, Bounded a, Enum a)
  => ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> (a -> SomeMessage FlexForm)
  -- ^ Function from enum type values to labels
  -> SimpleFormPiece t a
singleChoiceEnum :: forall a t.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> SimpleFormPiece t a
singleChoiceEnum ChoiceShape
shape FieldSettings FlexForm
fs = TypeField a -> SimpleFormPiece t a
forall a t. TypeField a -> SimpleFormPiece t a
single (TypeField a -> SimpleFormPiece t a)
-> ((a -> SomeMessage FlexForm) -> TypeField a)
-> (a -> SomeMessage FlexForm)
-> SimpleFormPiece t a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField a
forall a.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField a
singleChoiceEnumField ChoiceShape
shape FieldSettings FlexForm
fs


{- |
A `FormPiece` for the predefined `MultipleChoiceSelection` type.
This is either a set of checkboxes or a multi-selection menu,
depending on the given `ChoiceShape`.

=== __Example__

>>> let labels = ["First Option", "Second Option", "Third Option"]
>>> printWidget "en" $ formify (Just $ multipleChoiceAnswer [1,2]) $ multipleChoice Dropdown "Choose some" labels
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose some
    </label>
    <select id="flexident1" ... multiple>
      <option value="1" selected>
        First Option
      </option>
      <option value="2" selected>
        Second Option
      </option>
      <option value="3">
        Third Option
      </option>
    </select>
...
</div>

![rendered multiple choice field](doc-images/multiple_choice_dropdown.png)
-}
multipleChoice
  :: ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> [SomeMessage FlexForm]
  -> SimpleFormPiece t MultipleChoiceSelection
multipleChoice :: forall t.
ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> SimpleFormPiece t MultipleChoiceSelection
multipleChoice ChoiceShape
shape FieldSettings FlexForm
fs = TypeField MultipleChoiceSelection
-> SimpleFormPiece t MultipleChoiceSelection
forall a t. TypeField a -> SimpleFormPiece t a
single (TypeField MultipleChoiceSelection
 -> SimpleFormPiece t MultipleChoiceSelection)
-> ([SomeMessage FlexForm] -> TypeField MultipleChoiceSelection)
-> [SomeMessage FlexForm]
-> SimpleFormPiece t MultipleChoiceSelection
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChoiceShape
-> FieldSettings FlexForm
-> [SomeMessage FlexForm]
-> TypeField MultipleChoiceSelection
multipleChoiceField ChoiceShape
shape FieldSettings FlexForm
fs


{- |
A `FormPiece` for custom enum types.
This is either a set of checkboxes or a multi-selection menu,
depending on the given `ChoiceShape`.

The third argument is an assignment of labels for each enum constructor.

=== __Examples__

>>> let prefill = Just $ MultipleChoice [Two,Three]
>>> printWidget "en" $ formify prefill $ multipleChoiceEnum (Buttons Horizontal) "Choose" $ showToUniversalLabel @MyType
...
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose
    </label>
...
...
      <label>
        <input type="checkbox" ... value="1">
        One
      </label>
      <label>
        <input type="checkbox" ... value="2" checked>
        Two
      </label>
      <label>
        <input type="checkbox" ... value="3" checked>
        Three
      </label>
...
</div>

![rendered multiple choice enum field](doc-images/multiple_choice_enum_buttons.png)

>>> let prefill = Just $ MultipleChoice [Two,Three]
>>> printWidget "en" $ formify prefill $ multipleChoiceEnum Dropdown "Choose some" $ showToUniversalLabel @MyType
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Choose some
    </label>
    <select id="flexident1" ... multiple>
      <option value="1">
        One
      </option>
      <option value="2" selected>
        Two
      </option>
      <option value="3" selected>
        Three
      </option>
    </select>
...
</div>

![rendered multiple choice enum field](doc-images/multiple_choice_enum_dropdown.png)
-}
multipleChoiceEnum
  :: (Eq a, Bounded a, Enum a)
  => ChoiceShape
  -> FieldSettings FlexForm
  -- ^ `FieldSettings` for the choice field.
  -> (a -> SomeMessage FlexForm)
  -- ^ Function from enum type values to labels
  -> SimpleFormPiece t (MultipleChoice a)
multipleChoiceEnum :: forall a t.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> SimpleFormPiece t (MultipleChoice a)
multipleChoiceEnum ChoiceShape
shape FieldSettings FlexForm
fs = TypeField (MultipleChoice a)
-> SimpleFormPiece t (MultipleChoice a)
forall a t. TypeField a -> SimpleFormPiece t a
single (TypeField (MultipleChoice a)
 -> SimpleFormPiece t (MultipleChoice a))
-> ((a -> SomeMessage FlexForm) -> TypeField (MultipleChoice a))
-> (a -> SomeMessage FlexForm)
-> SimpleFormPiece t (MultipleChoice a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField (MultipleChoice a)
forall a.
(Eq a, Bounded a, Enum a) =>
ChoiceShape
-> FieldSettings FlexForm
-> (a -> SomeMessage FlexForm)
-> TypeField (MultipleChoice a)
multipleChoiceEnumField ChoiceShape
shape FieldSettings FlexForm
fs


{- |
Combines two `FormPiece`s horizontally, i.e. beside each other.

=== __Examples__

Input

@
basic \"field1\" >| basic \"field2\"
@

Renders as:

![horizontal composition](doc-images/horizontal_composition.png)

Horizontal composition does not preserve empty columns when the two pieces have different numbers of rows.
If the right-hand piece is taller than the left-hand piece,
its remaining rows will therefore appear in the leftmost position.

Input

@
list Vertical basicField ["field1_1, field1_2"] >| list Vertical basicField ["field2_1", "field2_2", field2_3]
@

will __not__ result in

![horizontal composition expectation](doc-images/horizontal_caution_wrong.png)

but instead in

![horizontal composition reality](doc-images/horizontal_caution_correct.png)
-}
infixr 5 >|
(>|) :: FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
>| :: forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
(>|) = Alignment
-> FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
forall t a ys.
Alignment
-> FormPiece t a -> FormPiece t ys -> FormPiece t (a ++ ys)
Combine Alignment
Horizontal


{- |
A non-infix alias for `>|`
-}
beside :: FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
beside :: forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
beside = FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
(>|)


{- |
Combines two `FormPiece`s vertically, i.e. below each other.

=== __Examples__

Input

@
basic \"field1\" >- basic \"field2\"
@

Renders as:

![vertical composition](doc-images/vertical_composition.png)
-}
infixr 4 >-
(>-) :: FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
>- :: forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
(>-) = Alignment
-> FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
forall t a ys.
Alignment
-> FormPiece t a -> FormPiece t ys -> FormPiece t (a ++ ys)
Combine Alignment
Vertical


{- |
A non-infix alias for `>-`
-}
above :: FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
above :: forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
above = FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
forall t xs ys.
FormPiece t xs -> FormPiece t ys -> FormPiece t (xs ++ ys)
(>-)


{- |
Creates a FormPiece for a list type.
The length of the list is equal to the amount of seed values provided.

Preconditions:

  * The list of seed values may not be empty
  * When finally rendered through `formify`,
    if a default value list is given,
    then it must have the same length as the list of seed values

Otherwise you will encounter a runtime error.

=== __Example__

>>> let labels = ["Input 1", "Input 2", "Input 3"]
>>> printWidget "en" $ formify @[Double] Nothing $ list Horizontal basicField labels
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      Input 1
    </label>
    <input id="flexident1" ... type="number" step="any" ...>
...
    <label for="flexident2">
      Input 2
    </label>
    <input id="flexident2" ... type="number" step="any" ...>
...
    <label for="flexident3">
      Input 3
    </label>
    <input id="flexident3" ... type="number" step="any" ...>
...
</div>

![rendered list of fields](doc-images/list_basic.png)
-}
list
  :: Alignment
  -- ^ Alignment of the individual fields
  -> (a -> TypeField b)
  -- ^ how to build each field given an arbitrary value
  -> [a]
  -- ^ the list of values to build individual fields out of
  -> ListFormPiece t b
list :: forall a b t.
Alignment -> (a -> TypeField b) -> [a] -> ListFormPiece t b
list Alignment
align a -> TypeField b
builder = Alignment -> [TypeField b] -> ListFormPiece t b
forall a t. Alignment -> [TypeField a] -> ListFormPiece t a
List Alignment
align ([TypeField b] -> ListFormPiece t b)
-> ([a] -> [TypeField b]) -> [a] -> ListFormPiece t b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> TypeField b) -> [a] -> [TypeField b]
forall a b. (a -> b) -> [a] -> [b]
map a -> TypeField b
builder


{- |
Same as `list`, but without using any field labels.
Per field attributes and CSS classes cannot be set with this function.
Instead, all fields share the given list of attributes.
Use `list` if individual configuration is required.

Preconditions:

  * The amount of fields is positive
  * When finally rendered through `formify`,
    if a default value list is given,
    then its length must match the amount of fields

Otherwise you will encounter a runtime error.

=== __Example__

Renders a series of four input fields of type Text
organized vertically beneath each other.
They are prefilled with the values given above,
assigned the CSS class \"helloInput\" and have no labels attached to them.

>>> let defaults = ["Hallo", "Hello", "Hola", "Ciao" :: Text]
>>> printWidget "en" $ formify (Just defaults) $ listWithoutLabels Vertical 4 basicField [("class","helloInput")]
<div class="flex-form-div form-group">
...
    <input id="flexident1" ... type="text" ... value="Hallo" class="helloInput">
...
</div>
<div class="flex-form-div form-group">
...
    <input id="flexident2" ... type="text" ... value="Hello" class="helloInput">
...
</div>
<div class="flex-form-div form-group">
...
    <input id="flexident3" ... type="text" ... value="Hola" class="helloInput">
...
</div>
<div class="flex-form-div form-group">
...
    <input id="flexident4" ... type="text" ... value="Ciao" class="helloInput">
...
</div>

![rendered list of unlabeled fields](doc-images/list_without_labels_basic.png)
-}
listWithoutLabels
  :: Alignment
  -- ^ Alignment of the individual fields
  -> Int
  -- ^ Amount of fields
  -> (FieldSettings FlexForm -> TypeField a)
  -- ^ The `TypeField` primitive to use
  -> [(Text,Text)]
  -- ^ List of attribute and value pairs (attribute "class" for classes)
  -> ListFormPiece t a
listWithoutLabels :: forall a t.
Alignment
-> Int
-> (FieldSettings FlexForm -> TypeField a)
-> [(Text, Text)]
-> ListFormPiece t a
listWithoutLabels Alignment
align Int
amount FieldSettings FlexForm -> TypeField a
req [(Text, Text)]
attrs =
  Alignment
-> (FieldSettings FlexForm -> TypeField a)
-> [FieldSettings FlexForm]
-> ListFormPiece t a
forall a b t.
Alignment -> (a -> TypeField b) -> [a] -> ListFormPiece t b
list Alignment
align FieldSettings FlexForm -> TypeField a
req ([FieldSettings FlexForm] -> ListFormPiece t a)
-> [FieldSettings FlexForm] -> ListFormPiece t a
forall a b. (a -> b) -> a -> b
$ Int -> FieldSettings FlexForm -> [FieldSettings FlexForm]
forall a. Int -> a -> [a]
replicate Int
amount FieldSettings FlexForm
"" {fsAttrs = attrs}


{- |
Same as `list` but copies a single given `TypeField` multiple times.

Preconditions:

  * The number of copies is positive
  * When finally rendered through `formify`,
    if a default value list is given,
    then its length must match the number of copies

Otherwise you will encounter a runtime error.

=== __Example__

>>> printWidget "en" $ formify @[Int] Nothing $ listRepeatedly Vertical 3 (basicField "input")
<div class="flex-form-div form-group">
...
    <label for="flexident1">
      input
    </label>
    <input id="flexident1" ... type="number" ... value="">
...
</div>
<div class="flex-form-div form-group">
...
    <label for="flexident2">
      input
    </label>
    <input id="flexident2" ... type="number" ... value="">
...
</div>
<div class="flex-form-div form-group">
...
    <label for="flexident3">
      input
    </label>
    <input id="flexident3" ... type="number" ... value="">
...
</div>

![rendered repetition of a field](doc-images/list_repeatedly_basic.png)
-}
listRepeatedly
  :: Alignment
  -- ^ Alignment of the individual fields
  -> Int
  -- ^ How many copies
  -> TypeField a
  -- ^ The field to multiply
  -> ListFormPiece t a
listRepeatedly :: forall a t. Alignment -> Int -> TypeField a -> ListFormPiece t a
listRepeatedly Alignment
alignment Int
amount = Alignment
-> (TypeField a -> TypeField a)
-> [TypeField a]
-> ListFormPiece t a
forall a b t.
Alignment -> (a -> TypeField b) -> [a] -> ListFormPiece t b
list Alignment
alignment TypeField a -> TypeField a
forall a. a -> a
id ([TypeField a] -> ListFormPiece t a)
-> (TypeField a -> [TypeField a])
-> TypeField a
-> ListFormPiece t a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> TypeField a -> [TypeField a]
forall a. Int -> a -> [a]
replicate Int
amount


options :: [a] -> [(a, SingleChoiceSelection)]
options :: forall a. [a] -> [(a, SingleChoiceSelection)]
options [a]
opts = [a] -> [SingleChoiceSelection] -> [(a, SingleChoiceSelection)]
forall a b. [a] -> [b] -> [(a, b)]
zip [a]
opts ([SingleChoiceSelection] -> [(a, SingleChoiceSelection)])
-> [SingleChoiceSelection] -> [(a, SingleChoiceSelection)]
forall a b. (a -> b) -> a -> b
$ (Int -> SingleChoiceSelection) -> [Int] -> [SingleChoiceSelection]
forall a b. (a -> b) -> [a] -> [b]
map Int -> SingleChoiceSelection
singleChoiceAnswer [Int
1..]


optionsFromType :: (Bounded b, Enum b) => (b -> a) -> [(a, b)]
optionsFromType :: forall b a. (Bounded b, Enum b) => (b -> a) -> [(a, b)]
optionsFromType b -> a
f = (b -> (a, b)) -> [b] -> [(a, b)]
forall a b. (a -> b) -> [a] -> [b]
map (\b
x -> (b -> a
f b
x, b
x)) [b
forall a. Bounded a => a
minBound .. b
forall a. Bounded a => a
maxBound]


pieceShape :: FormPiece t xs -> TypeShape xs
pieceShape :: forall t xs. FormPiece t xs -> TypeShape xs
pieceShape Single {} = TypeShape xs
TypeShape (OneField a)
forall a. TypeShape (OneField a)
OneShape
pieceShape List {} = TypeShape xs
TypeShape (ManyFields a)
forall a. TypeShape (ManyFields a)
ManyShape
pieceShape (Combine Alignment
_ FormPiece t xs
x FormPiece t ys
y) = TypeShape xs -> TypeShape ys -> TypeShape (xs ++ ys)
forall xs ys. TypeShape xs -> TypeShape ys -> TypeShape (xs ++ ys)
appendShape (FormPiece t xs -> TypeShape xs
forall t xs. FormPiece t xs -> TypeShape xs
pieceShape FormPiece t xs
x) (TypeShape ys -> TypeShape (xs ++ ys))
-> TypeShape ys -> TypeShape (xs ++ ys)
forall a b. (a -> b) -> a -> b
$ FormPiece t ys -> TypeShape ys
forall t xs. FormPiece t xs -> TypeShape xs
pieceShape FormPiece t ys
y