packages feed

nano-ui-form-0.2.0.0: lib/NanoUI/Form/Internal/Field.hs

-- | Shared widget-to-form plumbing. Naming and validation stay with ditto;
-- this module only adapts immediate-mode controls to persistent field values.
module NanoUI.Form.Internal.Field
  ( inputWidget
  , Publish (..)
  , decodeBool
  , decodeFloatInput
  , decodeInt
  , fieldErrors
  , enumField
  )
where

import Control.Monad (when)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text qualified as T
import Ditto.Backend (FormError)
import Ditto.Core qualified as Ditto
import Ditto.Generalized.Named qualified as Named
import Ditto.Generalized.Unnamed qualified as Unnamed
import Ditto.Types (FormId, encodeFormId)
import NanoUI
  ( NanoUI
  , Response
  , columnWith
  , fillW
  , gap
  , tight
  , Var
  , liftIO
  , withKey
  , withValue
  )
import NanoUI.Form.Internal.Backend
  ( FormInput (..)
   , FormScope (..)
   , askFormScope
  , fieldDraft
  , storeFieldEdit
  , updateFieldInput
  )
import NanoUI.Form.Types (Form, FormView (..))
import NanoUI.Form.Widgets (defaultErrorView)
import NanoUI.Internal.Monad (askContext)
import Text.Read (readMaybe)

-- | Policy for committing a field's widget value into the form store.
data Publish
  = -- | Commit whenever the widget mutates the 'Var' to a different value.
    OnChange
  | -- | As 'OnChange', and also when the response predicate holds (e.g.,
    -- re-selecting the active option). Built-in inputs use
    -- @OnChangeOr respChanged@ (the checkbox, @OnChangeOr respClicked@).
    OnChangeOr (Response -> Bool)
  | -- | Commit only when the response predicate holds, such as
    -- @OnlyWhen respSubmitted@ for a text field that commits on Enter.
    -- Uncommitted edits are retained as a draft across frames until committed,
    -- overwritten by an external change to the field's value, or cleared by a
    -- form reset.
    OnlyWhen (Response -> Bool)

-- | Adapt a 'Var'-based input widget to a form field. Each frame, the widget
-- runs with a temporary 'Var' initialized to the current field (or draft)
-- value, and mutations are committed according to 'Publish'.
-- 'Just' supplies a stable field name; 'Nothing' uses positional numbering.
-- Naming adds no visible label; include one in the widget action when needed.
-- Decoding and validation errors follow ditto's normal path.
inputWidget ::
  (Eq a, FormError FormInput err) =>
  Maybe Text
  -> (FormInput -> Either err a)
  -> Publish
  -> (a -> FormInput)
  -> (Var a -> NanoUI Response)
  -> a
  -> Form err a
inputWidget name decode publish encode widget initial = do
  owner <- Ditto.liftForm askFormScope
  let draftValue = either (const Nothing) Just . decode
  maybe Unnamed.input Named.input name decode (fieldView owner draftValue publish encode widget) initial

-- | Keep the label and control in the same stable field scope, and publish
-- edits by the field's policy.
fieldView ::
  Eq a =>
  FormScope
  -> (FormInput -> Maybe a)
  -> Publish
  -> (a -> FormInput)
  -> (Var a -> NanoUI Response)
  -> FormId
  -> a
  -> FormView
fieldView (FormScope owner prefix) draftValue publish encode widget formId value = FormView $ withKey fieldKey $ do
  ctx <- askContext
  case publish of
    OnChange -> immediate ctx (const False)
    OnChangeOr changed -> immediate ctx changed
    OnlyWhen commit -> do
      let current = encode value
      pending <- liftIO (fieldDraft owner prefix fieldKey)
      -- A draft begun from another form value is stale: the form changed.
      let shown = case pending of
            Just (base, draft) | base == current, Just held <- draftValue draft -> held
            _ -> value
      (response, newValue) <- withValue shown widget
      let committed = commit response
          draft
            | committed || newValue == value = Nothing
            | otherwise = Just (current, encode newValue)
          published = if committed then Just (encode newValue) else Nothing
      -- An idle field has no draft and publishes nothing, so writes nothing.
      when (draft /= pending || committed) $
        liftIO (storeFieldEdit owner ctx prefix fieldKey draft published)
 where
  fieldKey = encodeFormId formId
  immediate ctx changed = do
    (response, newValue) <- withValue value widget
    when (changed response || newValue /= value) $
      liftIO (updateFieldInput owner ctx prefix fieldKey (encode newValue))

decodeBool :: Bool -> FormInput -> Bool
decodeBool _ (FormInputBool value) = value
decodeBool _ (FormInputText value) = value == "true"
decodeBool initial _ = initial

decodeFloatInput :: Float -> FormInput -> Float
decodeFloatInput _ (FormInputFloat value) = value
decodeFloatInput initial (FormInputText value) = fromMaybe initial (readMaybe (T.unpack value))
decodeFloatInput initial _ = initial

decodeInt :: Int -> FormInput -> Int
decodeInt _ (FormInputInt value) = value
decodeInt initial (FormInputText value) = fromMaybe initial (readMaybe (T.unpack value))
decodeInt initial _ = initial

fieldErrors :: FormView -> [Text] -> FormView
fieldErrors (FormView widget) errs = FormView $
  columnWith (tight . gap 4 . fillW) $ do
    widget
    runFormView (defaultErrorView errs)

-- | Widget indices are zero-based even when an Enum's bounds are not.
enumField ::
  forall a f.
  (Bounded a, Enum a, Show a, Functor f) => ([Text] -> Int -> f Int) -> a -> f a
enumField widget initial =
  fromIndex <$> widget options (fromEnum initial - lower)
 where
  values = [minBound .. maxBound] :: [a]
  options = map (T.pack . show) values
  lower = fromEnum (minBound :: a)
  fromIndex index = toEnum (lower + max 0 (min (length values - 1) index))