nano-ui-form 0.1.0.0 → 0.2.0.0
raw patch · 19 files changed
+1192/−1115 lines, 19 filesdep +transformersdep −effectful-coredep −hashabledep ~containersdep ~dittodep ~nano-uiPVP ok
version bump matches the API change (PVP)
Dependencies added: transformers
Dependencies removed: effectful-core, hashable
Dependency ranges changed: containers, ditto, nano-ui, nano-ui-sdl, text
API changes (from Hackage documentation)
- NanoUI.Form: label :: Text -> Form err ()
- NanoUI.Form: separator :: Form err ()
- NanoUI.Form.Backend: FormInputBool :: Bool -> FormInput
- NanoUI.Form.Backend: FormInputFloat :: Float -> FormInput
- NanoUI.Form.Backend: FormInputInt :: Int -> FormInput
- NanoUI.Form.Backend: FormInputList :: [Text] -> FormInput
- NanoUI.Form.Backend: FormInputText :: Text -> FormInput
- NanoUI.Form.Backend: FormStateStore :: Map Text FormInput -> Bool -> FormStateStore
- NanoUI.Form.Backend: FormUI :: NanoUI a -> FormUI a
- NanoUI.Form.Backend: [fssInputs] :: FormStateStore -> Map Text FormInput
- NanoUI.Form.Backend: [fssSubmitted] :: FormStateStore -> Bool
- NanoUI.Form.Backend: [unFormUI] :: FormUI a -> NanoUI a
- NanoUI.Form.Backend: data FormInput
- NanoUI.Form.Backend: data FormStateStore
- NanoUI.Form.Backend: emptyFormStateStore :: FormStateStore
- NanoUI.Form.Backend: formInputToText :: FormInput -> Text
- NanoUI.Form.Backend: getActiveFormPrefix :: Context -> IO Text
- NanoUI.Form.Backend: getFormStore :: Context -> Text -> IO FormStateStore
- NanoUI.Form.Backend: instance Ditto.Backend.FormError NanoUI.Form.Backend.FormInput Data.Text.Internal.Text
- NanoUI.Form.Backend: instance Ditto.Backend.FormInput NanoUI.Form.Backend.FormInput
- NanoUI.Form.Backend: instance Ditto.Core.Environment NanoUI.Form.Backend.FormUI NanoUI.Form.Backend.FormInput
- NanoUI.Form.Backend: instance GHC.Internal.Base.Applicative NanoUI.Form.Backend.FormUI
- NanoUI.Form.Backend: instance GHC.Internal.Base.Functor NanoUI.Form.Backend.FormUI
- NanoUI.Form.Backend: instance GHC.Internal.Base.Monad NanoUI.Form.Backend.FormUI
- NanoUI.Form.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Backend.FormInput
- NanoUI.Form.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Backend.FormStateStore
- NanoUI.Form.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Backend.StoredForm
- NanoUI.Form.Backend: instance GHC.Internal.Generics.Generic NanoUI.Form.Backend.FormInput
- NanoUI.Form.Backend: instance GHC.Internal.Generics.Generic NanoUI.Form.Backend.FormStateStore
- NanoUI.Form.Backend: instance GHC.Internal.Show.Show NanoUI.Form.Backend.FormInput
- NanoUI.Form.Backend: instance GHC.Internal.Show.Show NanoUI.Form.Backend.FormStateStore
- NanoUI.Form.Backend: isFormSubmitted :: Context -> Text -> IO Bool
- NanoUI.Form.Backend: liftNanoUI :: NanoUI a -> FormUI a
- NanoUI.Form.Backend: markFormSubmitted :: Context -> Text -> Bool -> IO ()
- NanoUI.Form.Backend: newtype FormUI a
- NanoUI.Form.Backend: resetFormState :: Context -> Text -> IO ()
- NanoUI.Form.Backend: setActiveFormPrefix :: Context -> Text -> IO ()
- NanoUI.Form.Backend: setFormStore :: Context -> Text -> FormStateStore -> IO ()
- NanoUI.Form.Backend: updateFieldInput :: Context -> Text -> Text -> FormInput -> IO ()
- NanoUI.Form.Backend: withFormPrefix :: Text -> NanoUI a -> NanoUI a
- NanoUI.Form.Backend: withFormWidgets :: Text -> NanoUI a -> NanoUI a
- NanoUI.Form.Named: childErrors :: ([err] -> FormView) -> Form err ()
- NanoUI.Form.Named: errors :: ([err] -> FormView) -> Form err ()
- NanoUI.Form.Named: inputCheckbox :: FormError FormInput err => Text -> Bool -> Form err Bool
- NanoUI.Form.Named: inputColor :: FormError FormInput err => Text -> Color -> Form err Color
- NanoUI.Form.Named: inputEnumRadio :: (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a
- NanoUI.Form.Named: inputEnumSelect :: (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a
- NanoUI.Form.Named: inputPassword :: FormError FormInput err => Text -> Text -> Form err Text
- NanoUI.Form.Named: inputRadio :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int
- NanoUI.Form.Named: inputSelect :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int
- NanoUI.Form.Named: inputSlider :: FormError FormInput err => Text -> Float -> Float -> Float -> Form err Float
- NanoUI.Form.Named: inputText :: FormError FormInput err => Text -> Text -> Form err Text
- NanoUI.Form.Named: inputTextArea :: FormError FormInput err => Text -> Text -> Form err Text
- NanoUI.Form.Named: inputTextWithPlaceholder :: FormError FormInput err => Text -> Text -> Text -> Form err Text
- NanoUI.Form.Named: label :: Text -> Form err ()
- NanoUI.Form.Named: separator :: Form err ()
- NanoUI.Form.Named: withChildErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
- NanoUI.Form.Named: withErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
- NanoUI.Form.Named: withFieldErrors :: Form Text a -> Form Text a
- NanoUI.Form.Unnamed: childErrors :: ([err] -> FormView) -> Form err ()
- NanoUI.Form.Unnamed: errors :: ([err] -> FormView) -> Form err ()
- NanoUI.Form.Unnamed: inputCheckbox :: FormError FormInput err => Text -> Bool -> Form err Bool
- NanoUI.Form.Unnamed: inputEnumSelect :: (Bounded a, Enum a, Show a, FormError FormInput err) => a -> Form err a
- NanoUI.Form.Unnamed: inputPassword :: FormError FormInput err => Text -> Form err Text
- NanoUI.Form.Unnamed: inputSelect :: (Foldable f, FormError FormInput err) => f Text -> Int -> Form err Int
- NanoUI.Form.Unnamed: inputSlider :: FormError FormInput err => Float -> Float -> Float -> Form err Float
- NanoUI.Form.Unnamed: inputText :: FormError FormInput err => Text -> Form err Text
- NanoUI.Form.Unnamed: inputTextArea :: FormError FormInput err => Text -> Form err Text
- NanoUI.Form.Unnamed: withChildErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
- NanoUI.Form.Unnamed: withErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
- NanoUI.Form.Unnamed: withFieldErrors :: Form Text a -> Form Text a
+ NanoUI.Form: FieldName :: Maybe Text -> Maybe Text -> FieldName
+ NanoUI.Form: OnChange :: Publish
+ NanoUI.Form: OnChangeOr :: (Response -> Bool) -> Publish
+ NanoUI.Form: OnlyWhen :: (Response -> Bool) -> Publish
+ NanoUI.Form: [fieldKey] :: FieldName -> Maybe Text
+ NanoUI.Form: [fieldLabel] :: FieldName -> Maybe Text
+ NanoUI.Form: data FieldName
+ NanoUI.Form: data FormState
+ NanoUI.Form: data Publish
+ NanoUI.Form: formLabel :: Text -> Form err ()
+ NanoUI.Form: formSeparator :: Form err ()
+ NanoUI.Form: inputWidget :: (Eq a, FormError FormInput err) => Maybe Text -> (FormInput -> Either err a) -> Publish -> (a -> FormInput) -> (Var a -> NanoUI Response) -> a -> Form err a
+ NanoUI.Form: markSubmitted :: FormState -> Text -> NanoUI ()
+ NanoUI.Form: named :: Text -> FieldName
+ NanoUI.Form: newFormState :: IO FormState
+ NanoUI.Form: unnamed :: FieldName
+ NanoUI.Form.Input: FieldName :: Maybe Text -> Maybe Text -> FieldName
+ NanoUI.Form.Input: [fieldKey] :: FieldName -> Maybe Text
+ NanoUI.Form.Input: [fieldLabel] :: FieldName -> Maybe Text
+ NanoUI.Form.Input: childErrors :: ([err] -> FormView) -> Form err ()
+ NanoUI.Form.Input: data FieldName
+ NanoUI.Form.Input: errors :: ([err] -> FormView) -> Form err ()
+ NanoUI.Form.Input: formLabel :: Text -> Form err ()
+ NanoUI.Form.Input: formSeparator :: Form err ()
+ NanoUI.Form.Input: inputCheckbox :: FormError FormInput err => FieldName -> Bool -> Form err Bool
+ NanoUI.Form.Input: inputColor :: FormError FormInput err => FieldName -> Color -> Form err Color
+ NanoUI.Form.Input: inputEnumRadio :: (Bounded a, Enum a, Show a, FormError FormInput err) => FieldName -> a -> Form err a
+ NanoUI.Form.Input: inputEnumSelect :: (Bounded a, Enum a, Show a, FormError FormInput err) => FieldName -> a -> Form err a
+ NanoUI.Form.Input: inputPassword :: FormError FormInput err => FieldName -> Text -> Form err Text
+ NanoUI.Form.Input: inputRadio :: (Foldable f, FormError FormInput err) => FieldName -> f Text -> Int -> Form err Int
+ NanoUI.Form.Input: inputSelect :: (Foldable f, FormError FormInput err) => FieldName -> f Text -> Int -> Form err Int
+ NanoUI.Form.Input: inputSlider :: FormError FormInput err => FieldName -> Float -> Float -> Float -> Form err Float
+ NanoUI.Form.Input: inputText :: FormError FormInput err => FieldName -> Text -> Form err Text
+ NanoUI.Form.Input: inputTextArea :: FormError FormInput err => FieldName -> Text -> Form err Text
+ NanoUI.Form.Input: inputTextWithPlaceholder :: FormError FormInput err => Text -> FieldName -> Text -> Form err Text
+ NanoUI.Form.Input: named :: Text -> FieldName
+ NanoUI.Form.Input: unnamed :: FieldName
+ NanoUI.Form.Input: withChildErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
+ NanoUI.Form.Input: withErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a
+ NanoUI.Form.Input: withFieldErrors :: Form Text a -> Form Text a
+ NanoUI.Form.Internal.Backend: FormInputBool :: Bool -> FormInput
+ NanoUI.Form.Internal.Backend: FormInputFloat :: Float -> FormInput
+ NanoUI.Form.Internal.Backend: FormInputInt :: Int -> FormInput
+ NanoUI.Form.Internal.Backend: FormInputList :: [Text] -> FormInput
+ NanoUI.Form.Internal.Backend: FormInputText :: Text -> FormInput
+ NanoUI.Form.Internal.Backend: FormScope :: FormState -> Text -> FormScope
+ NanoUI.Form.Internal.Backend: FormStateStore :: Map Text FormInput -> Bool -> FormStateStore
+ NanoUI.Form.Internal.Backend: FormUI :: ReaderT FormScope NanoUI a -> FormUI a
+ NanoUI.Form.Internal.Backend: [fssInputs] :: FormStateStore -> Map Text FormInput
+ NanoUI.Form.Internal.Backend: [fssSubmitted] :: FormStateStore -> Bool
+ NanoUI.Form.Internal.Backend: [unFormUI] :: FormUI a -> ReaderT FormScope NanoUI a
+ NanoUI.Form.Internal.Backend: askFormScope :: FormUI FormScope
+ NanoUI.Form.Internal.Backend: data FormInput
+ NanoUI.Form.Internal.Backend: data FormScope
+ NanoUI.Form.Internal.Backend: data FormState
+ NanoUI.Form.Internal.Backend: data FormStateStore
+ NanoUI.Form.Internal.Backend: emptyFormStateStore :: FormStateStore
+ NanoUI.Form.Internal.Backend: fieldDraft :: FormState -> Text -> Text -> IO (Maybe (FormInput, FormInput))
+ NanoUI.Form.Internal.Backend: formInputToText :: FormInput -> Text
+ NanoUI.Form.Internal.Backend: getFormStore :: FormState -> Text -> IO FormStateStore
+ NanoUI.Form.Internal.Backend: instance Ditto.Backend.FormError NanoUI.Form.Internal.Backend.FormInput Data.Text.Internal.Text
+ NanoUI.Form.Internal.Backend: instance Ditto.Backend.FormInput NanoUI.Form.Internal.Backend.FormInput
+ NanoUI.Form.Internal.Backend: instance Ditto.Core.Environment NanoUI.Form.Internal.Backend.FormUI NanoUI.Form.Internal.Backend.FormInput
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Base.Applicative NanoUI.Form.Internal.Backend.FormUI
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Base.Functor NanoUI.Form.Internal.Backend.FormUI
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Base.Monad NanoUI.Form.Internal.Backend.FormUI
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Internal.Backend.FormInput
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Internal.Backend.FormStateStore
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Classes.Eq NanoUI.Form.Internal.Backend.StoredForm
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Generics.Generic NanoUI.Form.Internal.Backend.FormInput
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Generics.Generic NanoUI.Form.Internal.Backend.FormStateStore
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Show.Show NanoUI.Form.Internal.Backend.FormInput
+ NanoUI.Form.Internal.Backend: instance GHC.Internal.Show.Show NanoUI.Form.Internal.Backend.FormStateStore
+ NanoUI.Form.Internal.Backend: isFormSubmitted :: FormState -> Text -> IO Bool
+ NanoUI.Form.Internal.Backend: liftNanoUI :: NanoUI a -> FormUI a
+ NanoUI.Form.Internal.Backend: markFormSubmitted :: FormState -> Context -> Text -> Bool -> IO ()
+ NanoUI.Form.Internal.Backend: newFormState :: IO FormState
+ NanoUI.Form.Internal.Backend: newtype FormUI a
+ NanoUI.Form.Internal.Backend: resetFormState :: FormState -> Context -> Text -> IO ()
+ NanoUI.Form.Internal.Backend: runFormUI :: FormState -> Text -> FormUI a -> NanoUI a
+ NanoUI.Form.Internal.Backend: setFormStore :: FormState -> Context -> Text -> FormStateStore -> IO ()
+ NanoUI.Form.Internal.Backend: storeFieldEdit :: FormState -> Context -> Text -> Text -> Maybe (FormInput, FormInput) -> Maybe FormInput -> IO ()
+ NanoUI.Form.Internal.Backend: updateFieldInput :: FormState -> Context -> Text -> Text -> FormInput -> IO ()
+ NanoUI.Form.Internal.Backend: withFormWidgets :: FormState -> Text -> NanoUI a -> NanoUI a
+ NanoUI.Form.Runner: markSubmitted :: FormState -> Text -> NanoUI ()
+ NanoUI.Form.Types: FieldName :: Maybe Text -> Maybe Text -> FieldName
+ NanoUI.Form.Types: [fieldKey] :: FieldName -> Maybe Text
+ NanoUI.Form.Types: [fieldLabel] :: FieldName -> Maybe Text
+ NanoUI.Form.Types: data FieldName
+ NanoUI.Form.Types: instance GHC.Internal.Classes.Eq NanoUI.Form.Types.FieldName
+ NanoUI.Form.Types: instance GHC.Internal.Data.String.IsString NanoUI.Form.Types.FieldName
+ NanoUI.Form.Types: instance GHC.Internal.Show.Show NanoUI.Form.Types.FieldName
+ NanoUI.Form.Types: named :: Text -> FieldName
+ NanoUI.Form.Types: unnamed :: FieldName
- NanoUI.Form: FormUI :: NanoUI a -> FormUI a
+ NanoUI.Form: FormUI :: ReaderT FormScope NanoUI a -> FormUI a
- NanoUI.Form: [unFormUI] :: FormUI a -> NanoUI a
+ NanoUI.Form: [unFormUI] :: FormUI a -> ReaderT FormScope NanoUI a
- NanoUI.Form: inputCheckbox :: FormError FormInput err => Text -> Bool -> Form err Bool
+ NanoUI.Form: inputCheckbox :: FormError FormInput err => FieldName -> Bool -> Form err Bool
- NanoUI.Form: inputColor :: FormError FormInput err => Text -> Color -> Form err Color
+ NanoUI.Form: inputColor :: FormError FormInput err => FieldName -> Color -> Form err Color
- NanoUI.Form: inputEnumRadio :: (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a
+ NanoUI.Form: inputEnumRadio :: (Bounded a, Enum a, Show a, FormError FormInput err) => FieldName -> a -> Form err a
- NanoUI.Form: inputEnumSelect :: (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a
+ NanoUI.Form: inputEnumSelect :: (Bounded a, Enum a, Show a, FormError FormInput err) => FieldName -> a -> Form err a
- NanoUI.Form: inputPassword :: FormError FormInput err => Text -> Text -> Form err Text
+ NanoUI.Form: inputPassword :: FormError FormInput err => FieldName -> Text -> Form err Text
- NanoUI.Form: inputRadio :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int
+ NanoUI.Form: inputRadio :: (Foldable f, FormError FormInput err) => FieldName -> f Text -> Int -> Form err Int
- NanoUI.Form: inputSelect :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int
+ NanoUI.Form: inputSelect :: (Foldable f, FormError FormInput err) => FieldName -> f Text -> Int -> Form err Int
- NanoUI.Form: inputSlider :: FormError FormInput err => Text -> Float -> Float -> Float -> Form err Float
+ NanoUI.Form: inputSlider :: FormError FormInput err => FieldName -> Float -> Float -> Float -> Form err Float
- NanoUI.Form: inputText :: FormError FormInput err => Text -> Text -> Form err Text
+ NanoUI.Form: inputText :: FormError FormInput err => FieldName -> Text -> Form err Text
- NanoUI.Form: inputTextArea :: FormError FormInput err => Text -> Text -> Form err Text
+ NanoUI.Form: inputTextArea :: FormError FormInput err => FieldName -> Text -> Form err Text
- NanoUI.Form: inputTextWithPlaceholder :: FormError FormInput err => Text -> Text -> Text -> Form err Text
+ NanoUI.Form: inputTextWithPlaceholder :: FormError FormInput err => Text -> FieldName -> Text -> Form err Text
- NanoUI.Form: nanoFormEx :: FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)
+ NanoUI.Form: nanoFormEx :: FormState -> FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)
- NanoUI.Form: nanoFormLive :: Text -> Form Text a -> NanoUI (Maybe a)
+ NanoUI.Form: nanoFormLive :: FormState -> Text -> Form Text a -> NanoUI (Maybe a)
- NanoUI.Form: nanoFormSubmit :: Text -> Text -> Form Text a -> NanoUI (Maybe a)
+ NanoUI.Form: nanoFormSubmit :: FormState -> Text -> Text -> Form Text a -> NanoUI (Maybe a)
- NanoUI.Form: resetForm :: Text -> NanoUI ()
+ NanoUI.Form: resetForm :: FormState -> Text -> NanoUI ()
- NanoUI.Form: runNanoForm :: Text -> Form err a -> NanoUI (View err FormView, Result err (Proved a))
+ NanoUI.Form: runNanoForm :: FormState -> Text -> Form err a -> NanoUI (View err FormView, Result err (Proved a))
- NanoUI.Form.Runner: nanoFormEx :: FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)
+ NanoUI.Form.Runner: nanoFormEx :: FormState -> FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)
- NanoUI.Form.Runner: nanoFormLive :: Text -> Form Text a -> NanoUI (Maybe a)
+ NanoUI.Form.Runner: nanoFormLive :: FormState -> Text -> Form Text a -> NanoUI (Maybe a)
- NanoUI.Form.Runner: nanoFormSubmit :: Text -> Text -> Form Text a -> NanoUI (Maybe a)
+ NanoUI.Form.Runner: nanoFormSubmit :: FormState -> Text -> Text -> Form Text a -> NanoUI (Maybe a)
- NanoUI.Form.Runner: resetForm :: Text -> NanoUI ()
+ NanoUI.Form.Runner: resetForm :: FormState -> Text -> NanoUI ()
- NanoUI.Form.Runner: runNanoForm :: Text -> Form err a -> NanoUI (View err FormView, Result err (Proved a))
+ NanoUI.Form.Runner: runNanoForm :: FormState -> Text -> Form err a -> NanoUI (View err FormView, Result err (Proved a))
Files
- CHANGELOG.md +21/−5
- README.md +17/−19
- examples/FormDemo.hs +13/−9
- examples/Main.hs +7/−6
- lib/NanoUI/Form.hs +35/−14
- lib/NanoUI/Form/Backend.hs +0/−223
- lib/NanoUI/Form/Field.hs +0/−75
- lib/NanoUI/Form/Input.hs +185/−0
- lib/NanoUI/Form/Internal/Backend.hs +217/−0
- lib/NanoUI/Form/Internal/Field.hs +154/−0
- lib/NanoUI/Form/Named.hs +0/−181
- lib/NanoUI/Form/Runner.hs +68/−43
- lib/NanoUI/Form/Types.hs +43/−11
- lib/NanoUI/Form/Unnamed.hs +0/−101
- lib/NanoUI/Form/Validation.hs +13/−4
- lib/NanoUI/Form/Widgets.hs +9/−24
- nano-ui-form.cabal +32/−34
- test/Main.hs +378/−120
- test/Scope.hs +0/−246
CHANGELOG.md view
@@ -1,10 +1,26 @@ # Changelog +## 0.2.0.0 -- 2026-12-02++### Breaking changes++- Form runners and `resetForm` now take an explicit `FormState` allocated once with `newFormState`.+- `NanoUI.Form.Input` replaces the separate `Named` and `Unnamed` modules. Built-in inputs take `FieldName` (`OverloadedStrings` for literal names, `named text` for computed names, `unnamed` for positional fields).+- `NanoUI.Form.Backend` moved to `NanoUI.Form.Internal.Backend` (`FormInput`, `FormUI`, and `liftNanoUI` remain in `NanoUI.Form`).+- `inputWidget` adapts custom controls of type `Var a -> NanoUI Response` with an explicit `Publish` policy (`OnChange`, `OnChangeOr`, `OnlyWhen`).+- Dropped the `effectful-core` dependency in favor of `NanoUI`.++### Changed++- The `sdl` Cabal flag (for the example executable) is off by default, so depending on `nano-ui-form` no longer pulls in `nano-ui-sdl` or SDL3.+- `inputColor` formats values as `#rrggbbaa`, and `defaultErrorView` uses `themeDanger`.+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).++### Fixed++- `nanoFormSubmit` includes edits made in the same frame as Enter or submit clicks, submits once per Enter press only when a single-line field or nothing has focus, and respects IME composition and modals.+- `markSubmitted` exposes `FormOnSubmit` errors from custom submit buttons; `inRange` rejects NaN.+ ## 0.1.0.0 First release.--- Applicative forms on ditto whose inputs are nano-ui widgets, with- validation errors shown under each field.-- `nanoFormSubmit`, `nanoFormLive`, `nanoFormEx` and `runNanoForm` run a form- in a view.
README.md view
@@ -1,17 +1,15 @@ # nano-ui-form -Forms for [nano-ui](https://github.com/goolord/nano-ui), built on-[ditto](https://hackage.haskell.org/package/ditto).+Validated applicative forms for [nano-ui](https://github.com/goolord/nano-ui), built on [ditto](https://hackage.haskell.org/package/ditto). Backend-independent. -A form is an applicative value. Each input draws a nano-ui widget and parses-its value; validators attach errors that appear under the field.+Each form combines widget rendering, parsing, and validation in one applicative value, showing field-level error messages beneath invalid inputs. ```haskell {-# LANGUAGE OverloadedStrings #-} import Data.Text (Text) import NanoUI (NanoUI, label)-import NanoUI.Form hiding (label)+import NanoUI.Form data Signup = Signup Text Text @@ -21,25 +19,25 @@ <$> withFieldErrors (inputText "Name" "" `prove` notEmpty "Name is required") <*> withFieldErrors (inputText "Email" "" `prove` validEmail (const "Not an email address")) -view :: NanoUI ()-view = do- submitted <- nanoFormSubmit "signup" "Sign up" signup+-- Allocate owner <- newFormState once during setup.+view :: FormState -> NanoUI ()+view owner = do+ submitted <- nanoFormSubmit owner "signup" "Sign up" signup case submitted of Just (Signup name _) -> label ("Welcome, " <> name) Nothing -> pure () ``` -`nanoFormSubmit` adds a submit button and yields the value on the frame the form-is submitted. `nanoFormLive` yields the value whenever the form is valid,-`nanoFormEx` takes a `FormConfig`, and `runNanoForm` returns the form's view and-result separately.+## Runners and state -## Running+Allocate `newFormState` once per component or session and pass a unique stable key (`"signup"`) to every runner and to `resetForm`. -```sh-cabal run nano-ui-form-example -f sdl-```+- `nanoFormSubmit` renders a submit button and returns `Just a` on the single frame the form submits validly (store or handle the result on that frame).+- `nanoFormLive` returns `Just a` on every frame while all fields are valid.+- `nanoFormEx` takes a `FormConfig`, and `runNanoForm` separates rendering from extracting the result (call `markSubmitted` when using a custom submit button). -The example needs `nano-ui-sdl`, behind this package's `sdl` flag (off by-default, and on in this repository's `cabal.project`). The library itself-does not depend on a backend.+With `OverloadedStrings`, plain string literals set both a field's key and caption; use `named` and `unnamed` in `NanoUI.Form.Input` to separate keys from labels or use positional identity. Wrap any `Var a -> NanoUI Response` widget as a form field with `inputWidget`.++## Documentation++- [The nano-ui Book: Validated Forms](https://goolord.github.io/nano-ui/book/packages/index.html#validated-forms): Companion package overview and examples.
examples/FormDemo.hs view
@@ -32,10 +32,13 @@ , separator , tight , toolbar- , useText+ , readVar+ , useVar+ , writeVar ) import NanoUI.Form ( Form+ , FormState , FormView (..) , inRange , inputCheckbox@@ -106,10 +109,10 @@ <> ", Color: " <> colorToHex (regThemeColor r) <> ", Subscribed: " <> (if regSubscribe r then "Yes" else "No") -formDemoUi :: NanoUI ()-formDemoUi = do- (submittedMsg, setSubmitted) <- useText ""- (view', res) <- runNanoForm "user_reg" registrationForm+formDemoUi :: FormState -> NanoUI ()+formDemoUi owner = do+ submitted <- useVar ""+ (view', res) <- runNanoForm owner "user_reg" registrationForm let mReg = case res of Ditto.Ok (Ditto.Proved _ a) -> Just a Ditto.Error _ -> Nothing@@ -138,11 +141,11 @@ btnReset <- button "Reset Form" when btnSubmit $ do case mReg of- Just reg -> setSubmitted ("Successfully registered: " <> formatRegistration reg)- Nothing -> setSubmitted "Submission failed: Please fix the highlighted validation errors."+ Just reg -> writeVar submitted ("Successfully registered: " <> formatRegistration reg)+ Nothing -> writeVar submitted "Submission failed: Please fix the highlighted validation errors." when btnReset $ do- resetForm "user_reg"- setSubmitted "Form has been reset to defaults."+ resetForm owner "user_reg"+ writeVar submitted "Form has been reset to defaults." columnWith (tight . gap 12 . minW 340 . maxW 380) $ do card $ do@@ -174,6 +177,7 @@ heading "Submission Activity" muted "Record of last form submission:" separator+ submittedMsg <- readVar submitted if T.null submittedMsg then muted "No submission attempted yet." else labelWith (tight . fillW . maxW 350 . fontMono) submittedMsg
examples/Main.hs view
@@ -1,7 +1,8 @@ module Main (main) where import FormDemo (formDemoUi)-import NanoUI (Key (KeyEscape), Size (..), inputKeys, inputKeysElem)+import NanoUI.Form (newFormState)+import NanoUI (Key (KeyEscape), Pressable (..), Size (..), WindowSettings (..), defaultWindowSettings) import NanoUI.Backend.Sdl ( SdlOptions (..) , defaultSdlOptions@@ -9,11 +10,11 @@ ) main :: IO ()-main =+main = do+ owner <- newFormState runSdlApp defaultSdlOptions- { sdlWindowTitle = "nano-ui-form example"- , sdlWindowSize = Size 1100 800- , sdlAppShouldQuit = \inp -> inputKeysElem KeyEscape (inputKeys inp)+ { sdlWindowSettings = defaultWindowSettings {wsTitle = "nano-ui-form example", wsSize = Size 1100 800}+ , sdlAppShouldQuit = pressedOnceIn KeyEscape }- formDemoUi+ (formDemoUi owner)
lib/NanoUI/Form.hs view
@@ -1,4 +1,11 @@--- | Validated forms for nano-ui, built on ditto. A 'Form' is an applicative+-- |+-- Module : NanoUI.Form+-- Description : Validated applicative forms for nano-ui+-- Copyright : (c) 2026 Zachary Churchill+-- License : MIT+-- Maintainer : zacharyachurchill@gmail.com+--+-- Validated forms for nano-ui, built on ditto. A 'Form' is an applicative -- value whose inputs are nano-ui widgets; run one in a view with -- 'nanoFormLive', 'nanoFormSubmit', 'nanoFormEx' or 'runNanoForm'. module NanoUI.Form@@ -7,13 +14,20 @@ , FormView (..) , FormInput (..) , FormUI (..)+ , FormState+ , newFormState , liftNanoUI , FormStatus (..) , FormMode (..) , FormConfig (..) , defaultFormConfig+ , inputWidget+ , Publish (..)+ , FieldName (..)+ , named+ , unnamed - -- * Named Form Inputs+ -- * Form Inputs , inputText , inputTextWithPlaceholder , inputPassword@@ -25,8 +39,8 @@ , inputRadio , inputEnumRadio , inputColor- , label- , separator+ , formLabel+ , formSeparator , errors , childErrors , withErrors@@ -45,6 +59,7 @@ , nanoFormSubmit , nanoFormEx , resetForm+ , markSubmitted -- * Re-exports from Ditto , Ditto.FormRange (..)@@ -55,12 +70,16 @@ , Ditto.view , Ditto.mapView , (Ditto.@$)- ) where+ )+where -import qualified Ditto.Core as Ditto-import qualified Ditto.Types as Ditto-import NanoUI.Form.Named- ( childErrors+import Ditto.Core qualified as Ditto+import Ditto.Types qualified as Ditto+import NanoUI.Form.Internal.Backend (FormInput (..), FormUI (..), FormState, newFormState, liftNanoUI)+import NanoUI.Form.Internal.Field (Publish (..), inputWidget)+import NanoUI.Form.Input+ ( FieldName (..)+ , childErrors , errors , inputCheckbox , inputColor@@ -71,17 +90,19 @@ , inputSelect , inputSlider , inputText- , inputTextWithPlaceholder , inputTextArea- , label- , separator+ , inputTextWithPlaceholder+ , formLabel+ , named+ , formSeparator+ , unnamed , withChildErrors , withErrors , withFieldErrors )-import NanoUI.Form.Backend (FormInput (..), FormUI (..), liftNanoUI) import NanoUI.Form.Runner- ( nanoFormEx+ ( markSubmitted+ , nanoFormEx , nanoFormLive , nanoFormSubmit , resetForm
− lib/NanoUI/Form/Backend.hs
@@ -1,223 +0,0 @@--- | The ditto environment forms run in: field input values, form prefixes and--- submitted state, kept in the widget store.-module NanoUI.Form.Backend- ( FormInput (..)- , formInputToText- , FormUI (..)- , liftNanoUI- , getActiveFormPrefix- , withFormPrefix- , withFormWidgets- , updateFieldInput- , markFormSubmitted- , isFormSubmitted- , resetFormState- -- * Stored form state, for tests- , FormStateStore (..)- , emptyFormStateStore- , getFormStore- , setFormStore- , setActiveFormPrefix- ) where--import Control.Monad (when, (<$!>))-import Data.Dynamic (fromDynamic, toDyn)-import qualified Data.IntMap.Strict as IM-import qualified Data.Map.Strict as Map-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Lazy as TL-import qualified Data.Text.Lazy.Builder as TB-import qualified Data.Text.Lazy.Builder.Int as TB-import qualified Data.Text.Lazy.Builder.RealFloat as TB-import Data.Hashable (hash)-import Data.Maybe (fromMaybe)-import qualified Ditto.Backend as Ditto-import Ditto.Backend- ( FormError (..)- , commonFormErrorText- )-import Ditto.Core (Environment (..))-import Ditto.Types (Value (..), encodeFormId)-import GHC.Generics (Generic)-import Effectful.Exception (bracket)-import NanoUI (NanoUI, uiIO, withKey)-import NanoUI.Monad (askContext)-import NanoUI.Context (Context, getStore, markDirty, setStore)-import NanoUI.Store (WidgetStore (..))---- | A form field's raw input value, before parsing.-data FormInput- = FormInputText !Text- | FormInputBool !Bool- | FormInputInt !Int- | FormInputFloat !Float- | FormInputList ![Text]- deriving stock (Eq, Show, Generic)---- | String representation of a 'FormInput'-formInputToText :: FormInput -> Text-formInputToText (FormInputText t) = t-formInputToText (FormInputBool b) = if b then "true" else "false"-formInputToText (FormInputInt i) = TL.toStrict (TB.toLazyText (TB.decimal i))-formInputToText (FormInputFloat f) = TL.toStrict (TB.toLazyText (TB.realFloat f))-formInputToText (FormInputList ts) = T.intercalate "," ts---- | Internal store for form state across UI frames.-data FormStateStore = FormStateStore- { fssInputs :: !(Map.Map Text FormInput)- , fssSubmitted :: !Bool- } deriving stock (Eq, Show, Generic)---- | Empty form state store.-emptyFormStateStore :: FormStateStore-emptyFormStateStore = FormStateStore Map.empty False---- Keep reset identity alongside the form's values without exposing it in the--- public FormStateStore. A new generation starts fresh form-local widget state,--- including composite controls and text-area buffers.-data StoredForm = StoredForm- { sfGeneration :: !Int- , sfState :: !FormStateStore- }- deriving (Eq)---- | Form execution monad wrapping 'NanoUI'.-newtype FormUI a = FormUI { unFormUI :: NanoUI a }- deriving newtype (Functor, Applicative, Monad)---- | Lift a 'NanoUI' action into 'FormUI'.-liftNanoUI :: NanoUI a -> FormUI a-liftNanoUI = FormUI---- | 'FormInput' instance for 'FormInput' allowing ditto decoding.-instance Ditto.FormInput FormInput where- type FileType FormInput = ()-- getInputText (FormInputText t) = Right t- getInputText (FormInputList (t : _)) = Right t- getInputText other = Right (formInputToText other)-- getInputTexts (FormInputList ts) = ts- getInputTexts other = [formInputToText other]-- getInputString fi = T.unpack <$> Ditto.getInputText fi-- getInputFile _ = Right ()---- | 'FormError' instance translating common form errors into 'Text'.-instance FormError FormInput Text where- commonFormError = commonFormErrorText formInputToText---- | Well-known slot key in 'storeDyn' for the dynamically scoped form prefix.-activePrefixSlot :: Int-activePrefixSlot = -0x464F524D -- -'FORM'---- | Hash a form prefix to a unique 'IntMap' key.-formStoreKey :: Text -> Int-formStoreKey prefix = hash ("nano-ui-form:" :: Text, prefix)---- | Retrieve the active form prefix in the current context.-getActiveFormPrefix :: Context -> IO Text-getActiveFormPrefix ctx = do- ws <- getStore ctx- pure $! fromMaybe "" (IM.lookup activePrefixSlot (storeDyn ws) >>= fromDynamic)---- | Set the active form prefix in the current context.-setActiveFormPrefix :: Context -> Text -> IO ()-setActiveFormPrefix ctx prefix = do- ws <- getStore ctx- setStore ctx ws {storeDyn = IM.insert activePrefixSlot (toDyn prefix) (storeDyn ws)}---- | Evaluate or render a form under its own prefix, restoring the enclosing--- prefix afterwards. Restore only this slot, so field updates survive the scope.-withFormPrefix :: Text -> NanoUI a -> NanoUI a-withFormPrefix prefix action = do- ctx <- askContext- let restorePrefix previous = uiIO $ do- ws <- getStore ctx- setStore ctx ws- { storeDyn = IM.alter (const previous) activePrefixSlot (storeDyn ws)- }- bracket- (uiIO $ IM.lookup activePrefixSlot . storeDyn <$> getStore ctx)- restorePrefix- (\_ -> uiIO (setActiveFormPrefix ctx prefix) >> action)---- | Stable widget identity for a form, renewed when its state is reset.-withFormWidgets :: Text -> NanoUI a -> NanoUI a-withFormWidgets prefix action = do- ctx <- askContext- stored <- uiIO (getStoredForm ctx prefix)- withKey (prefix, sfGeneration stored) action--getStoredForm :: Context -> Text -> IO StoredForm-getStoredForm ctx prefix = do- ws <- getStore ctx- -- Resolve the lookup here rather than returning a thunk over the whole store.- pure $! fromMaybe (StoredForm 0 emptyFormStateStore) (IM.lookup (formStoreKey prefix) (storeDyn ws) >>= fromDynamic)--setStoredForm :: Context -> Text -> StoredForm -> IO ()-setStoredForm ctx prefix !stored = do- ws <- getStore ctx- setStore ctx ws {storeDyn = IM.insert (formStoreKey prefix) (toDyn stored) (storeDyn ws)}---- | Retrieve the 'FormStateStore' for a given form prefix.-getFormStore :: Context -> Text -> IO FormStateStore-getFormStore ctx prefix = sfState <$!> getStoredForm ctx prefix---- | Persist the 'FormStateStore' for a given form prefix.-setFormStore :: Context -> Text -> FormStateStore -> IO ()-setFormStore ctx prefix fss = do- stored <- getStoredForm ctx prefix- setStoredForm ctx prefix stored {sfState = fss}---- Form state lives in a Dynamic slot, which the core cannot compare. Keep--- equality and redraw notification here rather than in each mutation.-modifyFormStore :: Context -> Text -> (FormStateStore -> FormStateStore) -> IO ()-modifyFormStore ctx prefix update =- modifyStoredForm ctx prefix (\stored -> stored {sfState = update (sfState stored)})--modifyStoredForm :: Context -> Text -> (StoredForm -> StoredForm) -> IO ()-modifyStoredForm ctx prefix update = do- previous <- getStoredForm ctx prefix- let next = update previous- when (next /= previous) $ do- setStoredForm ctx prefix next- markDirty ctx---- | Update a specific field's input in the form store.-updateFieldInput :: Context -> Text -> Text -> FormInput -> IO ()-updateFieldInput ctx prefix fieldKey inputVal =- modifyFormStore ctx prefix $ \fss ->- fss {fssInputs = Map.insert fieldKey inputVal (fssInputs fss)}---- | Mark a form as submitted.-markFormSubmitted :: Context -> Text -> Bool -> IO ()-markFormSubmitted ctx prefix isSubmitted =- modifyFormStore ctx prefix (\fss -> fss {fssSubmitted = isSubmitted})---- | Check if a form has been submitted.-isFormSubmitted :: Context -> Text -> IO Bool-isFormSubmitted ctx prefix = do- fss <- getFormStore ctx prefix- pure (fssSubmitted fss)---- | Reset values and renew widget identity so cached control state cannot--- repopulate the form with its old values on the next frame.-resetFormState :: Context -> Text -> IO ()-resetFormState ctx prefix = modifyStoredForm ctx prefix $ \stored ->- if sfState stored == emptyFormStateStore- then stored- else StoredForm (sfGeneration stored + 1) emptyFormStateStore---- | Environment instance for 'FormUI' connecting ditto to nano-ui's context store.-instance Environment FormUI FormInput where- environment fid = FormUI $ do- ctx <- askContext- prefix <- uiIO (getActiveFormPrefix ctx)- fss <- uiIO (getFormStore ctx prefix)- let fieldKey = encodeFormId fid- pure $ case Map.lookup fieldKey (fssInputs fss) of- Just val -> Found val- Nothing -> Default
− lib/NanoUI/Form/Field.hs
@@ -1,75 +0,0 @@--- | 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.Field- ( fieldView- , 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.Types (FormId, encodeFormId)-import NanoUI (NanoUI, Response, columnWith, fillW, gap, tight, uiIO, withKey)-import NanoUI.Form.Backend (FormInput (..), getActiveFormPrefix, updateFieldInput)-import NanoUI.Form.Types (FormView (..))-import NanoUI.Form.Widgets (defaultErrorView)-import NanoUI.Monad (askContext)-import Text.Read (readMaybe)---- | Keep the label and control in the same stable field scope. Some controls--- report activation rather than change, so callers supply the response flag.-fieldView ::- Eq a =>- (Response -> Bool)- -> (a -> FormInput)- -> (a -> NanoUI (Response, a))- -> FormId- -> a- -> FormView-fieldView changed encode widget formId value = FormView $ withKey fieldKey $ do- ctx <- askContext- prefix <- uiIO (getActiveFormPrefix ctx)- (response, newValue) <- widget value- when (changed response || newValue /= value) $- uiIO (updateFieldInput ctx prefix fieldKey (encode newValue))- where- fieldKey = encodeFormId formId--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))
+ lib/NanoUI/Form/Input.hs view
@@ -0,0 +1,185 @@+-- | Form inputs with named or positional identity and an optional caption.+-- "NanoUI.Form" re-exports these. Use a string literal for a labelled, named+-- field, or 'unnamed' for a positional input.+module NanoUI.Form.Input+ ( -- * Field names+ FieldName (..)+ , named+ , unnamed++ -- * Input fields+ , inputText+ , inputTextWithPlaceholder+ , inputPassword+ , inputTextArea+ , inputCheckbox+ , inputSlider+ , inputSelect+ , inputEnumSelect+ , inputRadio+ , inputEnumRadio+ , inputColor++ -- * Static labels and separators+ , formLabel+ , formSeparator++ -- * Errors+ , errors+ , childErrors+ , withErrors+ , withChildErrors+ , withFieldErrors+ )+where++import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Ditto.Backend (FormError)+import Ditto.Core qualified as Ditto+import Ditto.Generalized.Named qualified as Named+import NanoUI+ ( Color+ , TextInputConfig (..)+ , checkbox'+ , colorFromHex+ , colorPicker'+ , colorToHexA+ , defaultTextInputConfig+ , radio'+ , respChanged+ , respClicked+ , select'+ , slider'+ , textArea'+ , textInput'+ , textInputConfigured'+ )+import NanoUI qualified as NUI+import NanoUI.Form.Internal.Backend (FormInput (..), formInputToText)+import NanoUI.Form.Internal.Field+ ( decodeBool+ , decodeFloatInput+ , decodeInt+ , enumField+ , fieldErrors+ , inputWidget+ , Publish (..)+ )+import NanoUI.Form.Types (FieldName (..), Form, FormView (..), named, unnamed)++-- | Single-line text input field.+inputText :: FormError FormInput err => FieldName -> Text -> Form err Text+inputText = textField textInput'++-- | Single-line text input field with custom placeholder text.+inputTextWithPlaceholder ::+ FormError FormInput err => Text -> FieldName -> Text -> Form err Text+inputTextWithPlaceholder placeholder =+ textField+ (textInputConfigured' defaultTextInputConfig {ticPlaceholder = placeholder})++-- | Password text input masking entered characters.+inputPassword :: FormError FormInput err => FieldName -> Text -> Form err Text+inputPassword = textField (textInputConfigured' defaultTextInputConfig {ticPassword = True})++-- | Multi-line text area input.+inputTextArea :: FormError FormInput err => FieldName -> Text -> Form err Text+inputTextArea = textField textArea'++textField ::+ FormError FormInput err =>+ (NUI.Var Text -> NUI.NanoUI NUI.Response) -> FieldName -> Text -> Form err Text+textField widget name = captioned name formInputToText FormInputText widget++-- | Checkbox toggle input.+inputCheckbox :: FormError FormInput err => FieldName -> Bool -> Form err Bool+inputCheckbox name initial =+ inputWidget+ (fieldKey name)+ (Right . decodeBool initial)+ (OnChangeOr respClicked)+ FormInputBool+ (checkbox' (fromMaybe "" (fieldLabel name)))+ initial++-- | Floating-point slider input across the range @[minV, maxV]@.+inputSlider ::+ FormError FormInput err =>+ FieldName -> Float -> Float -> Float -> Form err Float+inputSlider name minV maxV initial =+ captioned name (decodeFloatInput initial) FormInputFloat (slider' minV maxV) initial++-- | Dropdown selection in fold order (returns selected index).+inputSelect ::+ (Foldable f, FormError FormInput err) =>+ FieldName -> f Text -> Int -> Form err Int+inputSelect name options initial =+ captioned name (decodeInt initial) FormInputInt (select' options) initial++-- | Dropdown selection for any bounded enumeration type.+inputEnumSelect ::+ forall a err.+ (Bounded a, Enum a, Show a, FormError FormInput err) =>+ FieldName -> a -> Form err a+inputEnumSelect name = enumField (inputSelect name)++-- | Radio button group (returns selected index).+inputRadio ::+ (Foldable f, FormError FormInput err) =>+ FieldName -> f Text -> Int -> Form err Int+inputRadio name options initial =+ captioned name (decodeInt initial) FormInputInt (radio' options) initial++-- | Radio button group for any bounded enumeration type.+inputEnumRadio ::+ forall a err.+ (Bounded a, Enum a, Show a, FormError FormInput err) =>+ FieldName -> a -> Form err a+inputEnumRadio name = enumField (inputRadio name)++-- | Color picker input. As with 'colorPicker'', an edit makes the colour+-- opaque.+inputColor :: FormError FormInput err => FieldName -> Color -> Form err Color+inputColor name initial = captioned name decode (FormInputText . colorToHexA) colorPicker' initial+ where+ decode = \case+ FormInputText t -> fromMaybe initial (colorFromHex t)+ _ -> initial++-- | A field with its optional caption drawn above the control. Edits to the+-- control count as changes.+captioned ::+ (Eq a, FormError FormInput err) =>+ FieldName -> (FormInput -> a) -> (a -> FormInput) -> (NUI.Var a -> NUI.NanoUI NUI.Response) -> a -> Form err a+captioned name decode encode widget =+ inputWidget (fieldKey name) (Right . decode) (OnChangeOr respChanged) encode $ \value ->+ mapM_ NUI.label (fieldLabel name) >> widget value++-- | Static label inside a form.+formLabel :: Text -> Form err ()+formLabel txt = Ditto.view (FormView (NUI.label txt))++-- | Visual separator line inside a form.+formSeparator :: Form err ()+formSeparator = Ditto.view (FormView NUI.separator)++-- | Render error messages originating directly from this form node.+errors :: ([err] -> FormView) -> Form err ()+errors = Named.errors++-- | Render error messages originating from this form node and any descendant nodes.+childErrors :: ([err] -> FormView) -> Form err ()+childErrors = Named.childErrors++-- | Wrap a form with a custom error handler for its direct errors.+withErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a+withErrors = Named.withErrors++-- | Wrap a form with a custom error handler for errors from it or any child.+withChildErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a+withChildErrors = Named.withChildErrors++-- | Automatically display validation errors directly below the widget.+withFieldErrors :: Form Text a -> Form Text a+withFieldErrors = withChildErrors fieldErrors
+ lib/NanoUI/Form/Internal/Backend.hs view
@@ -0,0 +1,217 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | The ditto environment forms run in: field input values, form prefixes and+-- submitted state, retained by an explicit typed owner.+module NanoUI.Form.Internal.Backend+ ( FormInput (..)+ , formInputToText+ , FormUI (..)+ , FormState+ , newFormState+ , FormScope (..)+ , askFormScope+ , runFormUI+ , liftNanoUI+ , withFormWidgets+ , updateFieldInput+ , fieldDraft+ , storeFieldEdit+ , markFormSubmitted+ , isFormSubmitted+ , resetFormState+ -- * Stored form state, for tests+ , FormStateStore (..)+ , emptyFormStateStore+ , getFormStore+ , setFormStore+ ) where++import Control.Monad (when, (<$!>))+import Control.Monad.Trans.Class (lift)+import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)+import Data.IORef (IORef, newIORef, readIORef, modifyIORef')+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Lazy as TL+import qualified Data.Text.Lazy.Builder as TB+import qualified Data.Text.Lazy.Builder.Int as TB+import qualified Data.Text.Lazy.Builder.RealFloat as TB+import Data.Maybe (fromMaybe)+import qualified Ditto.Backend as Ditto+import Ditto.Backend+ ( FormError (..)+ , commonFormErrorText+ )+import Ditto.Core (Environment (..))+import Ditto.Types (Value (..), encodeFormId)+import GHC.Generics (Generic)+import NanoUI (NanoUI, liftIO, withKey)+import NanoUI.Internal.Context (Context, markDirty)++-- | A form field's raw input value, before parsing.+data FormInput+ = FormInputText !Text+ | FormInputBool !Bool+ | FormInputInt !Int+ | FormInputFloat !Float+ | FormInputList ![Text]+ deriving stock (Eq, Show, Generic)++-- | String representation of a 'FormInput'+formInputToText :: FormInput -> Text+formInputToText (FormInputText t) = t+formInputToText (FormInputBool b) = if b then "true" else "false"+formInputToText (FormInputInt i) = TL.toStrict (TB.toLazyText (TB.decimal i))+formInputToText (FormInputFloat f) = TL.toStrict (TB.toLazyText (TB.realFloat f))+formInputToText (FormInputList ts) = T.intercalate "," ts++-- | Internal store for form state across UI frames.+data FormStateStore = FormStateStore+ { fssInputs :: !(Map.Map Text FormInput)+ , fssSubmitted :: !Bool+ } deriving stock (Eq, Show, Generic)++-- | Empty form state store.+emptyFormStateStore :: FormStateStore+emptyFormStateStore = FormStateStore Map.empty False++-- Keep reset identity alongside the form's values without exposing it in the+-- public FormStateStore. A new generation starts fresh form-local widget state,+-- including composite controls and text-area buffers.+data StoredForm = StoredForm+ { sfGeneration :: !Int+ , sfState :: !FormStateStore+ , sfDrafts :: !(Map.Map Text (FormInput, FormInput))+ -- ^ Uncommitted field edits: the published form value the edit started from,+ -- and the current draft value.+ }+ deriving (Eq)++-- | Allocate once per component/session. Form prefixes distinguish the forms+-- owned by this handle. The map is keyed by the full prefix, without hashing.+newtype FormState = FormState (IORef (Map.Map Text StoredForm))++-- | Allocate a new empty 'FormState' during component or application setup.+newFormState :: IO FormState+newFormState = FormState <$> newIORef Map.empty++-- | Lexical ownership captured by field views during evaluation.+data FormScope = FormScope !FormState !Text++-- | Form evaluation reads its owner through a typed lexical environment.+newtype FormUI a = FormUI { unFormUI :: ReaderT FormScope NanoUI a }+ deriving newtype (Functor, Applicative, Monad)++-- | Read the current form owner and field prefix inside 'FormUI'.+askFormScope :: FormUI FormScope+askFormScope = FormUI ask++-- | Run a 'FormUI' action against a 'FormState' owner and form prefix.+runFormUI :: FormState -> Text -> FormUI a -> NanoUI a+runFormUI owner prefix (FormUI action) = runReaderT action (FormScope owner prefix)++-- | Lift a 'NanoUI' action into 'FormUI'.+liftNanoUI :: NanoUI a -> FormUI a+liftNanoUI = FormUI . lift++-- | Decode scalar values as text and preserve text lists for multi-value fields.+instance Ditto.FormInput FormInput where+ type FileType FormInput = ()++ getInputText (FormInputText t) = Right t+ getInputText (FormInputList (t : _)) = Right t+ getInputText other = Right (formInputToText other)++ getInputTexts (FormInputList ts) = ts+ getInputTexts other = [formInputToText other]++ getInputString fi = T.unpack <$> Ditto.getInputText fi++ getInputFile _ = Right ()++-- | 'FormError' instance translating common form errors into 'Text'.+instance FormError FormInput Text where+ commonFormError = commonFormErrorText formInputToText++-- | Stable widget identity for a form, renewed when its state is reset.+withFormWidgets :: FormState -> Text -> NanoUI a -> NanoUI a+withFormWidgets owner prefix action = do+ stored <- liftIO (getStoredForm owner prefix)+ withKey (prefix, sfGeneration stored) action++getStoredForm :: FormState -> Text -> IO StoredForm+getStoredForm (FormState ref) prefix = do+ forms <- readIORef ref+ pure $! fromMaybe (StoredForm 0 emptyFormStateStore Map.empty) (Map.lookup prefix forms)++setStoredForm :: FormState -> Text -> StoredForm -> IO ()+setStoredForm (FormState ref) prefix !stored = modifyIORef' ref (Map.insert prefix stored)++-- | Retrieve the 'FormStateStore' for a given form prefix.+getFormStore :: FormState -> Text -> IO FormStateStore+getFormStore owner prefix = sfState <$!> getStoredForm owner prefix++-- | Persist the 'FormStateStore' for a given form prefix.+setFormStore :: FormState -> Context -> Text -> FormStateStore -> IO ()+setFormStore owner ctx prefix fss = modifyFormStore owner ctx prefix (const fss)++-- Keep equality and redraw notification at the single mutation boundary.+modifyFormStore :: FormState -> Context -> Text -> (FormStateStore -> FormStateStore) -> IO ()+modifyFormStore owner ctx prefix update =+ modifyStoredForm owner ctx prefix (\stored -> stored {sfState = update (sfState stored)})++modifyStoredForm :: FormState -> Context -> Text -> (StoredForm -> StoredForm) -> IO ()+modifyStoredForm owner ctx prefix update = do+ previous <- getStoredForm owner prefix+ let next = update previous+ when (next /= previous) $ do+ setStoredForm owner prefix next+ markDirty ctx++-- | Update a specific field's input in the form store.+updateFieldInput :: FormState -> Context -> Text -> Text -> FormInput -> IO ()+updateFieldInput owner ctx prefix fieldKey inputVal =+ modifyFormStore owner ctx prefix $ \fss ->+ fss {fssInputs = Map.insert fieldKey inputVal (fssInputs fss)}++-- | A field's unpublished edit: the form value it started from, and the edit.+fieldDraft :: FormState -> Text -> Text -> IO (Maybe (FormInput, FormInput))+fieldDraft owner prefix fieldKey = Map.lookup fieldKey . sfDrafts <$> getStoredForm owner prefix++-- | Keep or drop a field's unpublished edit and, in the same update, publish+-- a value for it.+storeFieldEdit :: FormState -> Context -> Text -> Text -> Maybe (FormInput, FormInput) -> Maybe FormInput -> IO ()+storeFieldEdit owner ctx prefix fieldKey draft published =+ modifyStoredForm owner ctx prefix $ \stored ->+ stored+ { sfDrafts = Map.alter (const draft) fieldKey (sfDrafts stored)+ , sfState = maybe id (\v fss -> fss {fssInputs = Map.insert fieldKey v (fssInputs fss)}) published (sfState stored)+ }++-- | Mark a form as submitted.+markFormSubmitted :: FormState -> Context -> Text -> Bool -> IO ()+markFormSubmitted owner ctx prefix isSubmitted =+ modifyFormStore owner ctx prefix (\fss -> fss {fssSubmitted = isSubmitted})++-- | Check if a form has been submitted.+isFormSubmitted :: FormState -> Text -> IO Bool+isFormSubmitted owner prefix = fssSubmitted <$> getFormStore owner prefix++-- | Reset values and renew widget identity so cached control state cannot+-- repopulate the form with its old values on the next frame.+resetFormState :: FormState -> Context -> Text -> IO ()+resetFormState owner ctx prefix = modifyStoredForm owner ctx prefix $ \stored ->+ if sfState stored == emptyFormStateStore && Map.null (sfDrafts stored)+ then stored+ else StoredForm (sfGeneration stored + 1) emptyFormStateStore Map.empty++-- | Ditto reads from the typed owner supplied by the form runner.+instance Environment FormUI FormInput where+ environment fid = do+ FormScope owner prefix <- askFormScope+ fss <- liftNanoUI (liftIO (getFormStore owner prefix))+ let fieldKey = encodeFormId fid+ pure $ case Map.lookup fieldKey (fssInputs fss) of+ Just val -> Found val+ Nothing -> Default
+ lib/NanoUI/Form/Internal/Field.hs view
@@ -0,0 +1,154 @@+-- | 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))
− lib/NanoUI/Form/Named.hs
@@ -1,181 +0,0 @@--- | Named form inputs: each takes a name that identifies the field and is--- shown as its label. "NanoUI.Form" re-exports these.-module NanoUI.Form.Named- ( inputText- , inputTextWithPlaceholder- , inputPassword- , inputTextArea- , inputCheckbox- , inputSlider- , inputSelect- , inputEnumSelect- , inputRadio- , inputEnumRadio- , inputColor- , label- , separator- , errors- , childErrors- , withErrors- , withChildErrors- , withFieldErrors- )-where--import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Ditto.Backend (FormError)-import Ditto.Core qualified as Ditto-import Ditto.Generalized.Named qualified as Named-import NanoUI- ( Color- , NanoUI- , Response- , TextInputConfig (..)- , checkbox'- , colorFromHex- , colorPicker'- , colorToHex- , defaultTextInputConfig- , radio'- , respChanged- , respClicked- , select'- , slider'- , textArea'- , textInput'- , textInputConfigured'- )-import NanoUI qualified as NUI-import NanoUI.Form.Field- ( decodeBool- , decodeFloatInput- , decodeInt- , enumField- , fieldErrors- , fieldView- )-import NanoUI.Form.Backend (FormInput (..), formInputToText)-import NanoUI.Form.Types (Form, FormView (..))---- | Single-line text input field.-inputText :: FormError FormInput err => Text -> Text -> Form err Text-inputText = textField textInput'---- | Single-line text input field with custom placeholder text.-inputTextWithPlaceholder ::- FormError FormInput err => Text -> Text -> Text -> Form err Text-inputTextWithPlaceholder placeholder = textField (textInputConfigured' defaultTextInputConfig {ticPlaceholder = placeholder})---- | Password text input masking entered characters.-inputPassword :: FormError FormInput err => Text -> Text -> Form err Text-inputPassword = textField (textInputConfigured' defaultTextInputConfig {ticPassword = True})---- | Multi-line text area input.-inputTextArea :: FormError FormInput err => Text -> Text -> Form err Text-inputTextArea = textField textArea'--textField ::- FormError FormInput err =>- (Text -> NanoUI (Response, Text)) -> Text -> Text -> Form err Text-textField widget name =- Named.input- name- (Right . formInputToText)- (fieldView respChanged FormInputText (labelled name widget))--labelled :: Text -> (a -> NanoUI b) -> a -> NanoUI b-labelled name widget value = NUI.label name >> widget value---- | Checkbox toggle input.-inputCheckbox :: FormError FormInput err => Text -> Bool -> Form err Bool-inputCheckbox name initial =- Named.input- name- (Right . decodeBool initial)- (fieldView respClicked FormInputBool (checkbox' name))- initial---- | Floating-point slider input across the range @[minV, maxV]@.-inputSlider ::- FormError FormInput err => Text -> Float -> Float -> Float -> Form err Float-inputSlider name minV maxV initial =- Named.input- name- (Right . decodeFloatInput initial)- (fieldView respChanged FormInputFloat (labelled name (slider' minV maxV)))- initial---- | Dropdown selection in fold order (returns selected index).-inputSelect :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int-inputSelect name options initial =- Named.input- name- (Right . decodeInt initial)- (fieldView respChanged FormInputInt (labelled name (select' options)))- initial---- | Dropdown selection for any bounded enumeration type.-inputEnumSelect ::- forall a err.- (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a-inputEnumSelect name = enumField (inputSelect name)---- | Radio button group (returns selected index).-inputRadio :: (Foldable f, FormError FormInput err) => Text -> f Text -> Int -> Form err Int-inputRadio name options initial =- Named.input- name- (Right . decodeInt initial)- (fieldView respChanged FormInputInt (labelled name (radio' options)))- initial---- | Radio button group for any bounded enumeration type.-inputEnumRadio ::- forall a err.- (Bounded a, Enum a, Show a, FormError FormInput err) => Text -> a -> Form err a-inputEnumRadio name = enumField (inputRadio name)---- | Color picker input.-inputColor :: FormError FormInput err => Text -> Color -> Form err Color-inputColor name initial =- Named.input- name- ( \case- FormInputText t -> Right (fromMaybe initial (colorFromHex t))- _ -> Right initial- )- ( fieldView- respChanged- (FormInputText . colorToHex)- (labelled name colorPicker')- )- initial---- | Static label inside a form.-label :: Text -> Form err ()-label txt = Ditto.view (FormView (NUI.label txt))---- | Visual separator line inside a form.-separator :: Form err ()-separator = Ditto.view (FormView NUI.separator)---- | Render error messages originating directly from this form node.-errors :: ([err] -> FormView) -> Form err ()-errors = Named.errors---- | Render error messages originating from this form node and any descendant nodes.-childErrors :: ([err] -> FormView) -> Form err ()-childErrors = Named.childErrors---- | Wrap a form with a custom error handler for its direct errors.-withErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a-withErrors = Named.withErrors---- | Wrap a form with a custom error handler for errors from it or any child.-withChildErrors :: (FormView -> [err] -> FormView) -> Form err a -> Form err a-withChildErrors = Named.withChildErrors---- | Automatically display validation errors directly below the widget.-withFieldErrors :: Form Text a -> Form Text a-withFieldErrors = withChildErrors fieldErrors
lib/NanoUI/Form/Runner.hs view
@@ -6,9 +6,11 @@ , nanoFormSubmit , nanoFormEx , resetForm+ , markSubmitted ) where import Control.Monad (when)+import Data.Foldable (for_) import Data.Text (Text) import qualified Ditto.Core as Ditto import qualified Ditto.Types as Ditto@@ -17,18 +19,24 @@ , NanoUI , button , column- , inputKeys- , inputKeysElem- , uiIO+ , Pressable (..)+ , liftIO , whenM )-import NanoUI.Monad (askContext, askInput)-import NanoUI.Form.Backend- ( FormUI (..)+import NanoUI.Internal.Context+ ( FocusKind (..)+ , InteractionState (isFocusKind)+ , getsInteraction+ , pointerBlockedByModal+ )+import NanoUI.Internal.Monad (askContext, withContext)+import NanoUI.Monad (askInput)+import NanoUI.Form.Internal.Backend+ ( FormState+ , runFormUI , isFormSubmitted , markFormSubmitted , resetFormState- , withFormPrefix , withFormWidgets ) import NanoUI.Form.Types@@ -42,68 +50,81 @@ -- | Evaluate a formlet and return its view and result. The view retains its -- prefix even when rendered after other forms or inside another form's view.-runNanoForm :: Text -> Form err a -> NanoUI (Ditto.View err FormView, Ditto.Result err (Ditto.Proved a))-runNanoForm prefix form = withNanoForm prefix form $ \view result -> do- let scopedView (FormView action) = FormView (withFormPrefix prefix action)- pure (scopedView <$> view, result)+runNanoForm :: FormState -> Text -> Form err a -> NanoUI (Ditto.View err FormView, Ditto.Result err (Ditto.Proved a))+runNanoForm owner prefix form = withNanoForm owner prefix form $ \view result ->+ pure (view, result) --- Immediate runners evaluate and render in one prefix scope. Only a deferred--- view returned by runNanoForm needs to re-enter that scope when it is rendered.+-- Field views capture their typed owner when the form is evaluated, so even+-- deferred and nested views write to the right form without ambient state. withNanoForm ::- Text+ FormState+ -> Text -> Form err a -> (Ditto.View err FormView -> Ditto.Result err (Ditto.Proved a) -> NanoUI b) -> NanoUI b-withNanoForm prefix form consume = withFormPrefix prefix $ do- (view, result) <- unFormUI (Ditto.runForm prefix form)- let keyedView (FormView action) = FormView (withFormWidgets prefix action)+withNanoForm owner prefix form consume = do+ (view, result) <- runFormUI owner prefix (Ditto.runForm prefix form)+ let keyedView (FormView action) = FormView (withFormWidgets owner prefix action) consume (keyedView <$> view) result -- | Default form runner: renders the form every frame with live validation -- and yields @Just a@ whenever it is valid.-nanoFormLive :: Text -> Form Text a -> NanoUI (Maybe a)-nanoFormLive prefix form = do- status <- nanoFormEx defaultFormConfig prefix form+nanoFormLive :: FormState -> Text -> Form Text a -> NanoUI (Maybe a)+nanoFormLive owner prefix form = do+ status <- nanoFormEx owner defaultFormConfig prefix form pure $ case status of FormValid a -> Just a FormInvalid _ -> Nothing --- | Run a form with an integrated submit button.+-- | Run a form with an integrated submit button. Arguments are stable form+-- prefix, button label, and form. Enter also submits when nothing is focused+-- or a single-line field is, but not while a text area (a newline), an input+-- method, or another control (which Enter activates) has the key, nor behind+-- a modal. Enter is not tied to one form, so avoid treating multiple visible+-- forms as independent Enter targets. -- Validation errors are only displayed after the first submission attempt. -- Returns @Just a@ only on a valid submission.-nanoFormSubmit :: Text -> Text -> Form Text a -> NanoUI (Maybe a)-nanoFormSubmit prefix submitLabel form = do+nanoFormSubmit :: FormState -> Text -> Text -> Form Text a -> NanoUI (Maybe a)+nanoFormSubmit owner prefix submitLabel form = do ctx <- askContext inp <- askInput- submittedBefore <- uiIO (isFormSubmitted ctx prefix)- withNanoForm prefix form $ \view' res -> do+ submittedBefore <- liftIO (isFormSubmitted owner prefix)+ withNanoForm owner prefix form $ \view' res -> do btnClicked <- column $ do renderResult submittedBefore view' res button submitLabel- let enterPressed = inputKeysElem KeyEnter (inputKeys inp)- clickedSubmit = btnClicked || enterPressed+ enterPressed <-+ if pressedOnceIn KeyEnter inp+ then liftIO $ do+ blocked <- pointerBlockedByModal ctx+ kind <- getsInteraction ctx isFocusKind+ pure (not blocked && (kind `elem` [FocusNone, FocusTextLine, FocusTextSelectable]))+ else pure False+ let clickedSubmit = btnClicked || enterPressed when clickedSubmit $- uiIO (markFormSubmitted ctx prefix True)- pure $ case (clickedSubmit, res) of+ liftIO (markFormSubmitted owner ctx prefix True)+ -- The fields published this frame's edits while rendering, after 'res'+ -- was evaluated, so a submission evaluates the form again.+ submitted <- if clickedSubmit then snd <$> runNanoForm owner prefix form else pure res+ pure $ case (clickedSubmit, submitted) of (True, Ditto.Ok (Ditto.Proved _ a)) -> Just a _ -> Nothing --- | Detailed form runner with custom configuration.-nanoFormEx :: FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)-nanoFormEx cfg prefix form = do+-- | Render with configured error visibility and an optional submit button.+-- Returns current validity every frame, not a one-frame submission event;+-- to act on a submission, use the app's own button and 'markSubmitted'.+nanoFormEx :: FormState -> FormConfig -> Text -> Form Text a -> NanoUI (FormStatus a)+nanoFormEx owner cfg prefix form = do ctx <- askContext- submittedBefore <- uiIO (isFormSubmitted ctx prefix)- withNanoForm prefix form $ \view' res -> do+ submittedBefore <- liftIO (isFormSubmitted owner prefix)+ withNanoForm owner prefix form $ \view' res -> do let showErrors = case fcMode cfg of FormLive -> True FormOnSubmit -> submittedBefore column $ do renderResult showErrors view' res- case fcSubmitButton cfg of- Just lbl ->- whenM (button lbl) $- uiIO (markFormSubmitted ctx prefix True)- Nothing -> pure ()+ for_ (fcSubmitButton cfg) $ \lbl ->+ whenM (button lbl) (liftIO (markFormSubmitted owner ctx prefix True)) pure $ case res of Ditto.Ok (Ditto.Proved _ a) -> FormValid a Ditto.Error errs -> FormInvalid errs@@ -118,7 +139,11 @@ -- | Reset input values and the corresponding widget state for a form prefix. -- Re-evaluate the form on the next frame to render its defaults.-resetForm :: Text -> NanoUI ()-resetForm prefix = do- ctx <- askContext- uiIO (resetFormState ctx prefix)+resetForm :: FormState -> Text -> NanoUI ()+resetForm owner prefix = withContext (\ctx -> resetFormState owner ctx prefix)++-- | Count a form as submitted, as its submit button does, so a 'FormOnSubmit'+-- form shows its errors from the next frame. Call it from the app's own+-- submit button. 'resetForm' clears it.+markSubmitted :: FormState -> Text -> NanoUI ()+markSubmitted owner prefix = withContext (\ctx -> markFormSubmitted owner ctx prefix True)
lib/NanoUI/Form/Types.hs view
@@ -2,21 +2,27 @@ module NanoUI.Form.Types ( FormView (..) , Form+ , FieldName (..)+ , named+ , unnamed , FormStatus (..) , FormMode (..) , FormConfig (..) , defaultFormConfig- ) where+ )+where +import Data.String (IsString (..)) import Data.Text (Text)-import qualified Ditto.Core as Ditto+import Data.Text qualified as T+import Ditto.Core qualified as Ditto import Ditto.Types (FormRange) import NanoUI (NanoUI)-import NanoUI.Form.Backend (FormInput, FormUI)+import NanoUI.Form.Internal.Backend (FormInput, FormUI) -- | View representation for forms in nano-ui. -- Forms compose sequentially via '<*>' by sequencing their widget rendering actions.-newtype FormView = FormView { runFormView :: NanoUI () }+newtype FormView = FormView {runFormView :: NanoUI ()} instance Semigroup FormView where FormView a <> FormView b = FormView (a >> b)@@ -27,6 +33,28 @@ -- | Type alias for a form producing @a@ with error type @err@. type Form err a = Ditto.Form FormUI FormInput err FormView a +-- | Identity and caption for a built-in input. A string literal selects a+-- named, labelled field. 'unnamed' selects positional identity without a label.+-- Updating the caption leaves the form's persisted key unchanged.+data FieldName = FieldName+ { fieldKey :: !(Maybe Text)+ -- ^ 'Nothing' uses positional numbering; named keys must be unique in a form.+ , fieldLabel :: !(Maybe Text)+ -- ^ Optional caption, rendered above the control or beside a checkbox.+ }+ deriving (Eq, Show)++instance IsString FieldName where+ fromString = named . T.pack++-- | Use a dynamic text as both stable key and visible caption.+named :: Text -> FieldName+named name = FieldName (Just name) (Just name)++-- | A numbered input without a visible caption.+unnamed :: FieldName+unnamed = FieldName Nothing Nothing+ -- | Outcome of evaluating a form. data FormStatus a = FormValid !a@@ -36,18 +64,22 @@ -- | Validation mode for a form. data FormMode = FormLive- | FormOnSubmit+ | -- | Show errors once the form is submitted: by 'fcSubmitButton', or by+ -- @markSubmitted@ from the app's own button.+ FormOnSubmit deriving stock (Eq, Show) -- | Configuration options for form execution. data FormConfig = FormConfig- { fcMode :: !FormMode+ { fcMode :: !FormMode , fcSubmitButton :: !(Maybe Text)- } deriving stock (Eq, Show)+ }+ deriving stock (Eq, Show) -- | Default form configuration (live validation, no extra submit button). defaultFormConfig :: FormConfig-defaultFormConfig = FormConfig- { fcMode = FormLive- , fcSubmitButton = Nothing- }+defaultFormConfig =+ FormConfig+ { fcMode = FormLive+ , fcSubmitButton = Nothing+ }
− lib/NanoUI/Form/Unnamed.hs
@@ -1,101 +0,0 @@--- | Form inputs without a label, with automatically numbered field names.-module NanoUI.Form.Unnamed- ( inputText- , inputPassword- , inputTextArea- , inputCheckbox- , inputSlider- , inputSelect- , inputEnumSelect- , errors- , childErrors- , withErrors- , withChildErrors- , withFieldErrors- )-where--import Data.Text (Text)-import Ditto.Backend (FormError)-import Ditto.Generalized.Unnamed qualified as Unnamed-import NanoUI- ( NanoUI- , Response- , TextInputConfig (..)- , checkbox'- , defaultTextInputConfig- , respChanged- , respClicked- , select'- , slider'- , textArea'- , textInput'- , textInputConfigured'- )-import NanoUI.Form.Backend (FormInput (..), formInputToText)-import NanoUI.Form.Field- ( decodeBool- , decodeFloatInput- , decodeInt- , enumField- , fieldView- )-import NanoUI.Form.Named- ( childErrors- , errors- , withChildErrors- , withErrors- , withFieldErrors- )-import NanoUI.Form.Types (Form)---- | Auto-enumerated text input.-inputText :: FormError FormInput err => Text -> Form err Text-inputText = textField textInput'---- | Auto-enumerated password input.-inputPassword :: FormError FormInput err => Text -> Form err Text-inputPassword = textField (textInputConfigured' defaultTextInputConfig {ticPassword = True})---- | Auto-enumerated text area input.-inputTextArea :: FormError FormInput err => Text -> Form err Text-inputTextArea = textField textArea'--textField ::- FormError FormInput err =>- (Text -> NanoUI (Response, Text)) -> Text -> Form err Text-textField widget =- Unnamed.input- (Right . formInputToText)- (fieldView respChanged FormInputText widget)---- | Auto-enumerated checkbox toggle.-inputCheckbox :: FormError FormInput err => Text -> Bool -> Form err Bool-inputCheckbox lbl initial =- Unnamed.input- (Right . decodeBool initial)- (fieldView respClicked FormInputBool (checkbox' lbl))- initial---- | Auto-enumerated slider input.-inputSlider ::- FormError FormInput err => Float -> Float -> Float -> Form err Float-inputSlider minV maxV initial =- Unnamed.input- (Right . decodeFloatInput initial)- (fieldView respChanged FormInputFloat (slider' minV maxV))- initial---- | Auto-enumerated select dropdown.-inputSelect :: (Foldable f, FormError FormInput err) => f Text -> Int -> Form err Int-inputSelect options initial =- Unnamed.input- (Right . decodeInt initial)- (fieldView respChanged FormInputInt (select' options))- initial---- | Auto-enumerated select for bounded enums.-inputEnumSelect ::- forall a err.- (Bounded a, Enum a, Show a, FormError FormInput err) => a -> Form err a-inputEnumSelect = enumField inputSelect
lib/NanoUI/Form/Validation.hs view
@@ -1,5 +1,11 @@ -- | Proofs that parse and validate field values: numbers, text length, -- ranges, email addresses, and custom predicates.+--+-- The number proofs from ditto ('decimal', 'signedDecimal', 'realFrac' and+-- 'realFracSigned') read a 'String', and 'notNullProof' takes a list, but+-- text inputs yield 'Text'. Apply them after @fmap T.unpack@:+--+-- > (T.unpack <$> inputText "Age" "") `prove` decimal (const "Not a number") 0 module NanoUI.Form.Validation ( -- * Proof combinators Proof (..)@@ -50,19 +56,22 @@ notEmpty :: Applicative m => err -> Proof m err Text Text notEmpty = satisfies (not . T.null . T.strip) --- | Validate minimum string length.+-- | Require at least the given number of Unicode characters. The error+-- builder receives the actual length; this is not a grapheme-cluster count. minLength :: Applicative m => Int -> (Int -> err) -> Proof m err Text Text minLength minLen mkErr = validate ((>= minLen) . T.length) (mkErr . T.length) --- | Validate maximum string length.+-- | Require at most the given number of Unicode characters. The error+-- builder receives the actual length. maxLength :: Applicative m => Int -> (Int -> err) -> Proof m err Text Text maxLength maxLen mkErr = validate ((<= maxLen) . T.length) (mkErr . T.length) -- | Validate that a value falls within the inclusive range @[minVal, maxVal]@. inRange :: (Applicative m, Ord a) => a -> a -> (a -> err) -> Proof m err a a-inRange minVal maxVal = validate (\x -> not (x < minVal || x > maxVal))+inRange minVal maxVal = validate (\x -> minVal <= x && x <= maxVal) --- | Validate basic email structure (@user@domain.tld@).+-- | Check for one @\@@, a nonempty local part, and a dot inside the domain.+-- This is a small input check, not full email-syntax or deliverability validation. validEmail :: Applicative m => (Text -> err) -> Proof m err Text Text validEmail = validate isEmail where
lib/NanoUI/Form/Widgets.hs view
@@ -8,10 +8,9 @@ , formGroup ) where -import Control.Monad (forM_) import Data.Text (Text) import NanoUI- ( alignMid+ ( alignMiddle , card , columnWith , danger@@ -20,9 +19,8 @@ , heading , label , padXY- , calloutWith- , themeRed- , uiTheme+ , calloutToneWith+ , Tone (Danger) , rowWith ) import NanoUI.Form.Types (FormView (..))@@ -30,34 +28,21 @@ -- | Standard error view rendering a styled error callout directly below invalid fields. defaultErrorView :: Foldable f => f Text -> FormView defaultErrorView errs | null errs = FormView (pure ())-defaultErrorView errs = FormView $ do- errColor <- themeRed <$> uiTheme- calloutWith errColor (padXY 8 4 . gap 2) $ do- forM_ errs $ \err ->- danger ("• " <> err)+defaultErrorView errs = FormView $+ calloutToneWith Danger (padXY 8 4 . gap 2) (mapM_ (danger . ("• " <>)) errs) -- | Wrap a form view in a flex-growing column with standard form gap. formContainer :: FormView -> FormView-formContainer (FormView inner) = FormView $ do- columnWith (gap 10 . fillW) inner+formContainer (FormView inner) = FormView (columnWith (gap 10 . fillW) inner) -- | Horizontal layout putting a field label on the left and form control on the right. formRow :: Text -> FormView -> FormView-formRow lbl (FormView inner) = FormView $ do- rowWith (gap 8 . fillW . alignMid) $ do- label lbl- inner+formRow lbl (FormView inner) = FormView (rowWith (gap 8 . fillW . alignMiddle) (label lbl >> inner)) -- | Vertical field layout placing a label directly above the form control. formField :: Text -> FormView -> FormView-formField lbl (FormView inner) = FormView $ do- columnWith (gap 3 . fillW) $ do- label lbl- inner+formField lbl (FormView inner) = FormView (columnWith (gap 3 . fillW) (label lbl >> inner)) -- | Group related form fields into a titled visual card. formGroup :: Text -> FormView -> FormView-formGroup title (FormView inner) = FormView $ do- card $ do- heading title- columnWith (gap 6 . fillW) inner+formGroup title (FormView inner) = FormView (card (heading title >> columnWith (gap 6 . fillW) inner))
nano-ui-form.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: nano-ui-form-version: 0.1.0.0+version: 0.2.0.0 synopsis: Validated forms for nano-ui, built on ditto description: Applicative forms whose inputs are nano-ui widgets, with validation errors@@ -9,9 +9,9 @@ license-file: LICENSE author: goolord maintainer: zacharyachurchill@gmail.com-category: Graphics homepage: https://github.com/goolord/nano-ui bug-reports: https://github.com/goolord/nano-ui/issues+category: Graphics build-type: Simple tested-with: GHC ==9.10.3 || ==9.14.1 extra-doc-files:@@ -31,45 +31,44 @@ TypeFamilies common warnings- ghc-options:- -Wall- -Wextra- -Wcompat- -Widentities- -Wincomplete-record-updates- -Wincomplete-uni-patterns- -Wmissing-export-lists- -Wmissing-home-modules- -Wpartial-fields- -Wredundant-constraints- -Wunused-packages+ ghc-options:+ -Wall+ -Wextra+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wmissing-export-lists+ -Wmissing-home-modules+ -Wpartial-fields+ -Wredundant-constraints+ -Wunused-packages library import: extensions import: warnings exposed-modules: NanoUI.Form- NanoUI.Form.Backend- NanoUI.Form.Named+ NanoUI.Form.Internal.Backend+ NanoUI.Form.Input NanoUI.Form.Runner NanoUI.Form.Types- NanoUI.Form.Unnamed NanoUI.Form.Validation NanoUI.Form.Widgets other-modules:- NanoUI.Form.Field+ NanoUI.Form.Internal.Field build-depends: base >=4.20 && <4.23,- containers >=0.6.7 && <0.9,- ditto >=0.5 && <0.6,- effectful-core >=2.5 && <2.8,- hashable >=1.4 && <1.6,- nano-ui ^>=0.1,- text >=2.0 && <2.2+ containers >=0.7 && <0.9,+ ditto ^>=0.5.0,+ nano-ui ^>=0.2,+ text ^>=2.1,+ transformers >=0.6 && <0.7 hs-source-dirs: lib flag sdl- description: Build the SDL3 window example+ description: Build the SDL3 window example. Off by default, so that+ depending on the library does not need nano-ui-sdl and SDL3. manual: True default: False @@ -81,13 +80,13 @@ ghc-options: -rtsopts -threaded "-with-rtsopts=-N1 -A64m -T -I0" build-depends: base >=4.20 && <4.23,- ditto >=0.5 && <0.6,- nano-ui ^>=0.1,+ ditto ^>=0.5.0,+ nano-ui ^>=0.2, nano-ui-form,- text >=2.0 && <2.2+ text ^>=2.1 if flag(sdl) build-depends:- nano-ui-sdl ^>=0.1+ nano-ui-sdl ^>=0.2 if os(windows) ghc-options: -optl-mconsole if !flag(sdl)@@ -99,13 +98,12 @@ import: warnings type: exitcode-stdio-1.0 main-is: Main.hs- other-modules: Scope ghc-options: -rtsopts -threaded "-with-rtsopts=-M256m -N1" build-depends: base >=4.20 && <4.23,- containers >=0.6.7 && <0.9,- ditto >=0.5 && <0.6,- nano-ui,+ containers >=0.7 && <0.9,+ ditto ^>=0.5.0,+ nano-ui ^>=0.2, nano-ui-form,- text >=2.0 && <2.2+ text ^>=2.1 hs-source-dirs: test
test/Main.hs view
@@ -1,143 +1,401 @@ module Main (main) where +import Control.Exception (IOException, try)+import Control.Monad (forM_, void)+import Data.Either (isLeft)+import Data.IORef (newIORef, readIORef, writeIORef) import Data.Int (Int8)+import Data.List (sort)+import Data.Map.Strict qualified as Map+import Data.Sequence qualified as Seq import Data.Text (Text)-import qualified Data.Sequence as Seq-import qualified Data.Text as T-import qualified Ditto.Types as Ditto+import Data.Text qualified as T+import Ditto.Core qualified as Ditto+import Ditto.Types qualified as Ditto import NanoUI- ( Input (..)- , Size (..)- , columnWith- , emptyInput- , maxW- , minW- , runNanoUI- , tight- )-import NanoUI.Testing (collectTextSpans, newContext, runFrame)+import NanoUI qualified as NUI+import NanoUI.Widgets.Custom (setSubmitted)+import NanoUI.Backend (runNanoUI) import NanoUI.Form-import NanoUI.Form.Backend (updateFieldInput)-import qualified NanoUI.Form.Unnamed as Unnamed-import System.IO (BufferMode (NoBuffering), hSetBuffering, stdout)-import Scope (check, runScopeTests)+import NanoUI.Form.Internal.Backend+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Testing (Context, clearDirty, collectTextSpans, isDirty, newPixelContext, runFrame)+import NanoUI.Testing.Assert (require, requireEq)+import NanoUI.Testing.Harness (hasText, keyInp, nodesOfType, withInputOff)+import NanoUI.Testing.Sim hiding (result, spans)+import NanoUI.Var (peekVar) -data Person = Person- { personName :: !Text- , personAge :: !Float- , personOk :: !Bool- } deriving (Eq, Show)+type Checked a = Ditto.Result Text (Ditto.Proved a) -failingForm :: Form Text Person-failingForm =- Person- <$> (inputText "name" "" `prove` notEmpty "Name is required")- <*> (inputSlider "age" 0 100 12 `prove` inRange 18 100 (const "Must be at least 18"))- <*> inputCheckbox "accepted" False+-- | A form's value, failing on validation errors.+okValue :: String -> Checked a -> IO a+okValue msg = \case+ Ditto.Ok (Ditto.Proved _ value) -> pure value+ Ditto.Error errs -> fail (msg <> ": " <> show errs) +-- | A form's validation errors, failing when it has a value.+errorsOf :: String -> Ditto.Result Text a -> IO [(Ditto.FormRange, Text)]+errorsOf msg = \case+ Ditto.Error errs -> pure errs+ Ditto.Ok _ -> fail (msg <> ": expected validation errors")++-- | Event-free input for a 400 by 240 window.+input :: Input+input = withInputOff 400 240++-- | A fresh context and form owner.+fresh :: IO (Context, FormState)+fresh = (,) <$> newPixelContext <*> newFormState++-- | Run a form once, without its view.+runForm :: FormState -> Context -> Text -> Form Text a -> IO (Ditto.View Text FormView, Checked a)+runForm owner ctx prefix form = runNanoUI ctx input (runNanoForm owner prefix form)++-- | Run a form once, without its view, and return its value.+formValue :: FormState -> Context -> Text -> Form Text a -> IO a+formValue owner ctx prefix form = okValue (T.unpack prefix) . snd =<< runForm owner ctx prefix form++-- | Draw a form's view with the given errors.+drawView :: Context -> Ditto.View Text FormView -> [(Ditto.FormRange, Text)] -> IO ()+drawView ctx v errs = runNanoUI ctx input (runFormView (Ditto.unView v errs))++decodeText :: FormInput -> Either Text Text+decodeText (FormInputText t) = Right t+decodeText _ = Left "Expected text"++enabledForm :: Form Text Bool+enabledForm = inputCheckbox "enabled" False++-- | Run a script against a view in a 400 by 240 window of the context,+-- stopping at the first failed check.+sim :: Context -> NanoUI a -> Sim a r -> IO r+sim ctx ui script = newIORef 0 >>= \failed -> runSimWith opts ctx failed input ui script+ where+ opts = defaultSimOptions {simFailFast = True}++-- | Focus the frame's first control of a type.+focusFirst :: NodeType -> Sim a ()+focusFirst ty =+ onContext (nodesOfType ty) >>= \case+ (wid, _) : _ -> focusOn wid+ [] -> fail ("expected a " <> show ty)+ main :: IO () main = do- hSetBuffering stdout NoBuffering- putStrLn "=== Running nano-ui-form Test Suite ==="- runScopeTests+ testCustomFields+ testCommitOnly+ testCaptions+ testValues+ testErrorsKeepSiblings+ testFormOwnership+ testPrefixRestoration+ testFormInvalidation+ testSubmit+ testColorEdit+ testMarkSubmitted+ testReset+ putStrLn "nano-ui-form tests passed." - ctx <- newContext- let inp = emptyInput { inputWindowSize = Size 60 20 }+-- | A custom field publishes value changes without a response flag, is+-- named by its key rather than its label, and passes decoder errors on.+testCustomFields :: IO ()+testCustomFields = do+ (ctx, owner) <- fresh+ let+ customForm :: Form Text (Text, Text)+ customForm =+ (,)+ <$> inputWidget+ (Just "internal-key")+ decodeText+ OnChange+ FormInputText+ ( \v -> do+ NUI.label "Visible caption"+ NUI.modifyVar v (\value -> if value == "initial" then "edited" else value)+ pure mempty+ )+ "initial"+ <*> inputWidget Nothing decodeText (OnChangeOr NUI.respChanged) FormInputText NUI.textInput' "automatic"+ current = formValue owner ctx "custom" customForm+ (customView, _) <- runForm owner ctx "custom" customForm+ drawView ctx customView []+ require "custom fields did not publish their changes" . (== ("edited", "automatic")) =<< current+ updateFieldInput owner ctx "custom" "internal-key" (FormInputText "external")+ require "custom field identity depends on its label" . (== ("external", "automatic")) =<< current+ updateFieldInput owner ctx "custom" "internal-key" (FormInputBool True)+ errs <- errorsOf "custom decoder" . snd =<< runForm owner ctx "custom" customForm+ require "custom field decoder errors did not reach ditto" (map snd errs == ["Expected text"]) - let collectionForm :: Form Text (Int, Int, Int)- collectionForm = (,,)+-- | A commit-only field holds uncommitted edits as a draft and publishes+-- them only when committed; an outside change replaces the draft.+testCommitOnly :: IO ()+testCommitOnly = do+ (ctx, owner) <- fresh+ commitNow <- newIORef False+ shown <- newIORef ""+ let+ commitForm :: Form Text Text+ commitForm =+ inputWidget+ (Just "draft")+ decodeText+ (OnlyWhen NUI.respSubmitted)+ FormInputText+ ( \v -> do+ value <- peekVar v+ submitted <- liftIO (writeIORef shown value >> readIORef commitNow)+ NUI.modifyVar v (\x -> if x == "a" then "ab" else x)+ pure (setSubmitted submitted mempty)+ )+ "a"+ runCommit = runForm owner ctx "commit" commitForm+ drawCommit (v, _) = drawView ctx v []+ drawCommit =<< runCommit+ editing <- runCommit+ require "a commit-only field published an uncommitted edit" . (== "a") =<< okValue "editing" (snd editing)+ drawCommit editing+ require "a commit-only field does not show its held edit" . (== "ab") =<< readIORef shown+ writeIORef commitNow True+ drawCommit editing+ require "a commit-only field did not publish on commit" . (== "ab") =<< formValue owner ctx "commit" commitForm+ writeIORef commitNow False+ forM_ ["a", "external"] $ \t -> do+ updateFieldInput owner ctx "commit" "draft" (FormInputText t)+ drawCommit =<< runCommit+ require "an outside change did not replace a held edit" . (== "external") =<< readIORef shown++-- | A named field keeps its value when its caption changes, and built-in+-- inputs draw the current caption.+testCaptions :: IO ()+testCaptions = do+ (ctx, owner) <- fresh+ let+ renderCaption spec = columnWith tight $ do+ (fieldView, result) <- runNanoForm owner "captions" (inputText spec "initial" :: Form Text Text)+ runFormView (Ditto.unView fieldView [])+ pure result+ firstCaption = (named "stable-key") {fieldLabel = Just "First caption"}+ _ <- runFrame ctx input (renderCaption firstCaption)+ updateFieldInput owner ctx "captions" "stable-key" (FormInputText "kept")+ (result, _, _) <- runFrame ctx input (renderCaption firstCaption {fieldLabel = Just "Second caption"})+ require "a caption change lost the named field's value" . (== "kept") =<< okValue "captions" result+ spans <- collectTextSpans ctx+ require "built-in inputs do not draw their caption" $+ hasText "Second caption" spans && not (hasText "First caption" spans)++-- | Initial and decoded values of collection, enum and number fields, and+-- the errors of failing proofs.+testValues :: IO ()+testValues = do+ (ctx, owner) <- fresh+ let+ collectionForm =+ (,,) <$> inputSelect "select" (Seq.fromList ["First", "Second"]) 1 <*> inputRadio "radio" (Seq.fromList ["First", "Second"]) 0- <*> Unnamed.inputSelect (Just "Only") 0- (_, collectionResult) <- runNanoUI ctx inp (runNanoForm "collections" collectionForm)- case collectionResult of- Ditto.Ok (Ditto.Proved _ values) ->- check "Foldable form options preserve initial indices" (values == (1, 0, 0))- Ditto.Error errs -> fail (show errs)-- putStrLn "\n--- Validation Failure & Errors (runNanoUI) ---"- (_, res2) <- runNanoUI ctx inp (runNanoForm "failing" failingForm)- case res2 of- Ditto.Error errs -> do- let errorMsgs = map snd errs- check "Detected two validation errors" (length errs == 2)- check "Caught Name is required" ("Name is required" `elem` errorMsgs)- check "Caught Must be at least 18" ("Must be at least 18" `elem` errorMsgs)- Ditto.Ok _ ->- fail "Expected validation failure, but form succeeded"+ <*> inputSelect unnamed (Just "Only") 0+ require "foldable options lost their initial indices" . (== (1, 0, 0 :: Int))+ =<< formValue owner ctx "collections" collectionForm+ let+ failing =+ (,)+ <$> (inputText "name" "" `prove` notEmpty "Name is required")+ <*> (inputSlider "age" 0 100 12 `prove` inRange 18 100 (const "Must be at least 18"))+ errs <- errorsOf "failing" . snd =<< runForm owner ctx "failing" failing+ require "failing proofs did not both report" $+ sort (map snd errs) == ["Must be at least 18", "Name is required"]+ inRangeNaN <- proofFunction (inRange 0 1 (const ("Out of range" :: Text))) (0 / 0 :: Double)+ require "inRange accepts NaN" (isLeft inRangeNaN)+ -- Enum fields use zero-based widget indices whatever the enum's bounds,+ -- and clamp indices outside them.+ let+ enumForm :: Form Text (Int8, Int8, Int8)+ enumForm =+ (,,) <$> inputEnumSelect "select" (-42) <*> inputEnumRadio "radio" 42 <*> inputEnumSelect unnamed (-12)+ enums = formValue owner ctx "enums" enumForm+ require "enum fields lost their initial values" . (== (-42, 42, -12)) =<< enums+ forM_ [(0, 255), (-10, 300)] $ \(sel, rad) -> do+ updateFieldInput owner ctx "enums" "select" (FormInputInt sel)+ updateFieldInput owner ctx "enums" "radio" (FormInputInt rad)+ require ("enum indices " <> show (sel, rad)) . (== (minBound, maxBound, -12)) =<< enums - let enumForm :: Form Text (Int8, Int8, Int8)- enumForm = (,,)- <$> inputEnumSelect "select" (-42)- <*> inputEnumRadio "radio" 42- <*> Unnamed.inputEnumSelect (-12)- checkEnums expected = do- (_, result) <- runNanoUI ctx inp (runNanoForm "enums" enumForm)- case result of- Ditto.Ok (Ditto.Proved _ values) ->- check "Enum fields use zero-based widget indices independently of enum bounds" (values == expected)- Ditto.Error errs -> fail (show errs)- checkEnums (-42, 42, -12)- updateFieldInput ctx "enums" "select" (FormInputInt 0)- updateFieldInput ctx "enums" "radio" (FormInputInt 255)- checkEnums (minBound, maxBound, -12)- updateFieldInput ctx "enums" "select" (FormInputInt (-10))- updateFieldInput ctx "enums" "radio" (FormInputInt 300)- checkEnums (minBound, maxBound, -12)+-- | An error appearing and clearing on one field leaves its siblings'+-- values alone, and a long error message is drawn whole.+testErrorsKeepSiblings :: IO ()+testErrorsKeepSiblings = do+ (ctx, owner) <- fresh+ let+ multiForm =+ (,,)+ <$> withFieldErrors (inputText "user" "Ada" `prove` minLength 3 (const "Too short"))+ <*> withFieldErrors (inputSlider "age" 10 100 25 `prove` inRange 18 100 (const "Must be 18+"))+ <*> withFieldErrors (inputText "bio" "Bio text" `prove` notEmpty "Bio required")+ valid msg want = do+ (v, r) <- runForm owner ctx "multi" multiForm+ require msg . (== want) =<< okValue msg r+ drawView ctx v []+ valid "initial values" ("Ada", 25 :: Float, "Bio text")+ updateFieldInput owner ctx "multi" "age" (FormInputFloat 15)+ (v2, r2) <- runForm owner ctx "multi" multiForm+ errs <- errorsOf "age 15" r2+ require "age did not fail alone" (length errs == 1)+ drawView ctx v2 errs+ updateFieldInput owner ctx "multi" "bio" (FormInputText "Bio modified")+ updateFieldInput owner ctx "multi" "age" (FormInputFloat 30)+ valid "fixing the age reset a sibling" ("Ada", 30, "Bio modified")+ let+ message = "Invalid email address format (e.g. name@domain.com)"+ emailForm = withFieldErrors (inputText "email" "bad-email" `prove` validEmail (const message))+ (v, r) <- runForm owner ctx "longError" (emailForm :: Form Text Text)+ emailErrs <- errorsOf "email" r+ require "the email error did not report once" (length emailErrs == 1)+ _ <- runFrame ctx (input {inputWindowSize = NUI.Size 60 20}) $+ columnWith (tight . minW 300 . maxW 360) (runFormView (Ditto.unView v emailErrs))+ shown <- T.unwords . map (\(_, t, _, _, _) -> t) <$> collectTextSpans ctx+ require "the long email error lost text" (all (`T.isInfixOf` shown) ["Invalid email", "name@domain.com"]) - putStrLn "\n--- Multi-field stability & no ID shift on error appearance/clear ---"- let multiForm :: Form Text (Text, Float, Text)- multiForm =- (,,)- <$> withFieldErrors (inputText "user" "Ada" `prove` minLength 3 (const "Too short"))- <*> withFieldErrors (inputSlider "age" 10 100 25 `prove` inRange 18 100 (const "Must be 18+"))- <*> withFieldErrors (inputText "bio" "Bio text" `prove` notEmpty "Bio required")+-- | Clicking a checkbox writes only to the form that owns it: same-named+-- fields of forms whose views are drawn later, and a field after a form+-- nested in another.+testFormOwnership :: IO ()+testFormOwnership = do+ let+ deferred owner = columnWith fillW $ do+ (left, _) <- runNanoForm owner "left" enabledForm+ (right, _) <- runNanoForm owner "right" enabledForm+ runFormView (Ditto.unView left [] <> Ditto.unView right [])+ nested owner = void . nanoFormLive owner "outer" $+ Ditto.view (FormView (void (nanoFormLive owner "inner" enabledForm))) *> enabledForm+ forM_ [(deferred, 0, "left", "right"), (nested, 1, "outer", "inner")] $ \(mkUi, clicked, own, other) -> do+ (ctx, owner) <- fresh+ sim ctx (mkUi owner) $ do+ onContext (nodesOfType NodeButton) >>= \case+ controls@[(a, _), (b, _)] -> do+ -- Same-named fields in different forms have their own widget ids.+ check (a /= b)+ void (click (Within (snd (controls !! clicked))))+ found -> fail ("expected two checkboxes, got " <> show (length found))+ void settle+ require ("the click did not reach " <> T.unpack own) =<< formValue owner ctx own enabledForm+ require ("the click wrote to " <> T.unpack other) . not =<< formValue owner ctx other enabledForm - -- Frame 1: Initial valid state- (v1, r1) <- runNanoUI ctx inp (runNanoForm "multi" multiForm)- case r1 of- Ditto.Ok (Ditto.Proved _ (u, a, b)) -> do- check "Initial valid form decoded" (u == "Ada" && a == 25 && b == "Bio text")- runNanoUI ctx inp (runFormView (Ditto.unView v1 []))- _ -> fail "Expected valid initial form"+-- | A form scope that throws restores the enclosing one and keeps the+-- field updates made before the throw.+testPrefixRestoration :: IO ()+testPrefixRestoration = do+ (ctx, owner) <- fresh+ (prefix, result) <- runNanoUI ctx input $ runFormUI owner "outer" $ do+ result <- liftNanoUI . liftIO . try $ runNanoUI ctx input $ runFormUI owner "inner" $ do+ FormScope innerOwner innerPrefix <- askFormScope+ liftNanoUI $ liftIO $ do+ updateFieldInput innerOwner ctx innerPrefix "value" (FormInputText "preserved")+ ioError (userError "form failed")+ FormScope _ prefix <- askFormScope+ pure (prefix, result :: Either IOException ())+ require "expected a form exception" (isLeft result)+ require "exception changed the enclosing form owner" (prefix == "outer")+ store <- getFormStore owner "inner"+ require "prefix restoration discarded field updates" $+ Map.lookup "value" (fssInputs store) == Just (FormInputText "preserved") - -- Frame 2: Update age to 15 (invalid)- updateFieldInput ctx "multi" "age" (FormInputFloat 15)- (v2, r2) <- runNanoUI ctx inp (runNanoForm "multi" multiForm)- case r2 of- Ditto.Error errs -> do- check "Age failed validation" (length errs == 1)- -- Render with error callout- runNanoUI ctx inp (runFormView (Ditto.unView v2 errs))- Ditto.Ok _ -> fail "Expected age validation error"+-- | Each form mutation requests one redraw, and repeating it none.+testFormInvalidation :: IO ()+testFormInvalidation = do+ (ctx, owner) <- fresh+ forM_+ [ updateFieldInput owner ctx "form" "field" (FormInputText "value")+ , markFormSubmitted owner ctx "form" True+ , resetFormState owner ctx "form"+ ]+ $ \update -> forM_ [True, False] $ \dirties -> do+ clearDirty ctx+ update+ require "a form mutation's redraw request is wrong" . (== dirties) =<< isDirty ctx - -- Frame 3: User updates Bio to "Bio modified"- updateFieldInput ctx "multi" "bio" (FormInputText "Bio modified")+-- | Enter submits a form's value once, including text typed in the same+-- frame, for a field that publishes each edit and one that publishes on+-- Enter. Enter in a text area inserts a newline instead.+testSubmit :: IO ()+testSubmit = do+ (ctx, owner) <- fresh+ sim ctx (nanoFormSubmit owner "submit" "Save" (pure (42 :: Int))) $ do+ checkEq Nothing =<< frame+ checkEq (Just 42) =<< pressKey KeyEnter+ -- A submitted form emits nothing on idle frames.+ checkEq Nothing =<< settle+ let onEnter = inputWidget (Just "query") decodeText (OnlyWhen respSubmitted) FormInputText textInput' ""+ forM_+ [ ("submit-typed", inputText "query" "", NodeTextInput, Just "abc")+ , ("submit-on-enter", onEnter, NodeTextInput, Just "abc")+ , ("submit-notes", inputTextArea "notes" "", NodeTextArea, Nothing)+ ]+ $ \(prefix, field, ty, want) -> do+ (fctx, fowner) <- fresh+ got <- sim fctx (nanoFormSubmit fowner prefix "Save" (field `prove` notEmpty "Required")) $ do+ focusFirst ty+ _ <- settle+ frameWith (\i -> keyInp KeyEnter i {inputChars = "abc"})+ requireEq ("the value Enter submitted: " <> show prefix) want got - -- Frame 4: Fix age back to 30 (error clears)- updateFieldInput ctx "multi" "age" (FormInputFloat 30)- (v4, r4) <- runNanoUI ctx inp (runNanoForm "multi" multiForm)- case r4 of- Ditto.Ok (Ditto.Proved _ (u, a, b)) -> do- check "Form valid again without sibling reset" (u == "Ada" && a == 30 && b == "Bio modified")- runNanoUI ctx inp (runFormView (Ditto.unView v4 []))- Ditto.Error errs -> fail $ "Expected valid form after fix, got: " ++ show errs+-- | A colour field's value is the colour its picker shows: a picker without+-- an alpha bar makes an edited translucent colour opaque.+testColorEdit :: IO ()+testColorEdit = do+ (ctx, owner) <- fresh+ let+ overlay = colorRGBA 0 0 0 128+ edited <- sim ctx (nanoFormLive owner "colour" (inputColor "Overlay" overlay)) $ do+ -- The picker's first part is its saturation / value field.+ focusFirst NodeColorPicker+ _ <- settle+ _ <- pressKey KeyUp+ settle+ require "Up did not brighten the colour" (edited /= Just overlay)+ require "the field's colour is not the opaque one its picker shows" (fmap colorA edited == Just 255) - putStrLn "\n--- Long error text wrapping ---"- let emailErrorMsg = "Invalid email address format (e.g. name@domain.com)"- longErrorForm :: Form Text Text- longErrorForm = withFieldErrors (inputText "email" "bad-email" `prove` validEmail (\_ -> emailErrorMsg))- (v7, r7) <- runNanoUI ctx inp (runNanoForm "longError" longErrorForm)- case r7 of- Ditto.Error errs -> do- check "Caught long email error" (length errs == 1)- let ui = columnWith (tight . minW 300 . maxW 360) (runFormView (Ditto.unView v7 errs))- _ <- runFrame ctx inp ui- spans <- collectTextSpans ctx- let emailSpans = [t | (_, t, _, _, _) <- spans, "Invalid email" `T.isInfixOf` t || "name@domain.com" `T.isInfixOf` t]- check "Email error message is rendered without being lost" (not (null emailSpans))- let allText = T.unwords emailSpans- check "Full email error text is preserved" ("Invalid email" `T.isInfixOf` allText && "name@domain.com" `T.isInfixOf` allText)- Ditto.Ok _ -> fail "Expected email validation error"+-- | The app's own button submits a 'FormOnSubmit' form through+-- 'markSubmitted', and the form then shows its errors.+testMarkSubmitted :: IO ()+testMarkSubmitted = do+ (ctx, owner) <- fresh+ let+ form = withFieldErrors (inputText "name" "" `prove` notEmpty "Name is required")+ ui = nanoFormEx owner defaultFormConfig {fcMode = FormOnSubmit} "on-submit" form+ sim ctx ui $ do+ -- The message wraps, so look for its last word.+ expectNot "required"+ liftIO (runNanoUI ctx input (markSubmitted owner "on-submit"))+ _ <- settle+ expect "required" - putStrLn "\n=== All nano-ui-form Tests Passed! ==="+-- | Resetting a form restores its defaults, including a text area's cached+-- buffer, and leaves other forms' values and widget ids alone.+testReset :: IO ()+testReset = do+ (ctx, owner) <- fresh+ let+ ui =+ columnWith fillW $+ (,)+ <$> nanoFormLive owner "reset-left" enabledForm+ <*> nanoFormLive owner "reset-right" enabledForm+ afterward act = liftIO act >> settle+ sim ctx ui $ do+ controls <- onContext (nodesOfType NodeButton)+ mapM_ (click . Within . snd) controls+ -- The checkboxes keep their edits; a reset restores only its own form's+ -- defaults, and keeps the other form's widget ids.+ checkEq (Just True, Just True) =<< settle+ checkEq (Just False, Just True) =<< afterward (runNanoUI ctx input (resetForm owner "reset-left"))+ after <- onContext (nodesOfType NodeButton)+ checkEq (map fst (drop 1 controls)) (map fst (drop 1 after))+ -- Writing form data does not revive a retired widget cache.+ checkEq (Just False, Just True) =<< afterward (setFormStore owner ctx "reset-left" emptyFormStateStore)+ (actx, aowner) <- fresh+ sim actx (nanoFormLive aowner "reset-editor" (inputTextArea "notes" "initial")) $ do+ focusFirst NodeTextArea+ _ <- typeText "edited"+ checkEq (Just "editedinitial") =<< settle+ -- A reset drops the text area's cached buffer.+ checkEq (Just "initial") =<< afterward (runNanoUI actx input (resetForm aowner "reset-editor"))
− test/Scope.hs
@@ -1,246 +0,0 @@-module Scope (check, runScopeTests) where--import Control.Exception (IOException, try)-import Control.Monad (forM, forM_, unless, void)-import Data.IORef (writeIORef)-import Data.Map.Strict qualified as Map-import Data.Text (Text)-import Ditto.Core qualified as Ditto-import Ditto.Types qualified as Ditto-import NanoUI- ( Input (..)- , Key (KeyEnter)- , NanoUI- , Rect (..)- , columnWith- , fillW- , inputKeysFromList- , runNanoUI- , uiIO- )-import NanoUI.Context (ctxFocusId, ctxNodeArena)-import NanoUI.Form-import NanoUI.Form.Backend- ( FormStateStore (..)- , emptyFormStateStore- , getActiveFormPrefix- , getFormStore- , markFormSubmitted- , resetFormState- , setActiveFormPrefix- , setFormStore- , updateFieldInput- , withFormPrefix- )-import NanoUI.Id (WidgetId)-import NanoUI.Layout.Arena- ( NodeType (NodeCheckbox, NodeTextArea)- , arenaCount- , getNodeType- , getRect- , getWidgetId- )-import NanoUI.Testing (Context, clearDirty, isDirty, newPixelContext, runFrame)-import NanoUI.Testing.Harness (clickPair, spanCenter, warmup2, withInputOff)--check :: String -> Bool -> IO ()-check message ok = unless ok (fail message)--runScopeTests :: IO ()-runScopeTests = do- testDeferredViews- testNestedViews- testPrefixRestoration- testFormInvalidation- testSubmitPulse- testResetWidgets- testResetTextArea--checkboxes :: Context -> IO [(WidgetId, Rect)]-checkboxes = controlsOf NodeCheckbox--controlsOf :: NodeType -> Context -> IO [(WidgetId, Rect)]-controlsOf wanted ctx = do- let- arena = ctxNodeArena ctx- count <- arenaCount arena- concat- <$> forM- [0 .. count - 1]- ( \index -> do- nodeType <- getNodeType arena index- if nodeType /= wanted- then pure []- else do- wid <- getWidgetId arena index- (x, y, w, h) <- getRect arena index- pure [(wid, Rect x y w h)]- )--enabledForm :: Form Text Bool-enabledForm = inputCheckbox "enabled" False--readEnabled :: Context -> Text -> IO Bool-readEnabled ctx prefix = do- (_, result) <-- runNanoUI ctx (withInputOff 400 240) (runNanoForm prefix enabledForm)- case result of- Ditto.Ok (Ditto.Proved _ value) -> pure value- Ditto.Error _ -> fail "checkbox form unexpectedly failed validation"--testDeferredViews :: IO ()-testDeferredViews = do- ctx <- newPixelContext- let- input = withInputOff 400 240- ui :: NanoUI ()- ui = columnWith fillW $ do- (left, _) <- runNanoForm "left" enabledForm- (right, _) <- runNanoForm "right" enabledForm- runFormView (Ditto.unView left [] <> Ditto.unView right [])- _ <- warmup2 ctx input ui- controls <- checkboxes ctx- case controls of- [(leftId, leftRect), (rightId, _)] -> do- check- "same-named fields in different forms share a widget ID"- (leftId /= rightId)- let- (press, release) = clickPair input (spanCenter leftRect)- void (runFrame ctx press ui)- void (runFrame ctx release ui)- _ <- warmup2 ctx input ui- check "deferred view wrote to the wrong form" =<< readEnabled ctx "left"- check "editing one form changed another form" . not =<< readEnabled ctx "right"- _ -> fail "expected two deferred checkbox fields"--testNestedViews :: IO ()-testNestedViews = do- ctx <- newPixelContext- setActiveFormPrefix ctx "host"- let- input = withInputOff 400 240- nested = Ditto.view (FormView (void (nanoFormLive "inner" enabledForm)))- outer = nested *> enabledForm- ui = nanoFormLive "outer" outer- _ <- warmup2 ctx input ui- controls <- checkboxes ctx- case controls of- [_, (_, outerRect)] -> do- let- (press, release) = clickPair input (spanCenter outerRect)- void (runFrame ctx press ui)- void (runFrame ctx release ui)- _ <- warmup2 ctx input ui- check "field following a nested form lost its owner" =<< readEnabled ctx "outer"- check "outer field wrote to the nested form" . not =<< readEnabled ctx "inner"- check "form evaluation or rendering leaked its prefix" . (== "host")- =<< getActiveFormPrefix ctx- _ -> fail "expected nested and outer checkbox fields"--testPrefixRestoration :: IO ()-testPrefixRestoration = do- ctx <- newPixelContext- let- input = withInputOff 400 240- result <-- try- ( runNanoUI ctx input $ withFormPrefix "outer" $ withFormPrefix "inner" $ do- uiIO (updateFieldInput ctx "inner" "value" (FormInputText "preserved"))- uiIO (ioError (userError "form failed"))- ) ::- IO (Either IOException ())- check "expected a form exception" (either (const True) (const False) result)- check "exception leaked the active form prefix" . (== "")- =<< getActiveFormPrefix ctx- store <- getFormStore ctx "inner"- check- "prefix restoration discarded field updates"- (Map.lookup "value" (fssInputs store) == Just (FormInputText "preserved"))--testFormInvalidation :: IO ()-testFormInvalidation = do- ctx <- newPixelContext- forM_- [ updateFieldInput ctx "form" "field" (FormInputText "value")- , markFormSubmitted ctx "form" True- , resetFormState ctx "form"- ]- $ \update -> do- clearDirty ctx- update- check "form mutation did not request a redraw" =<< isDirty ctx- clearDirty ctx- update- check "an unchanged form mutation requested another redraw" . not- =<< isDirty ctx--testSubmitPulse :: IO ()-testSubmitPulse = do- ctx <- newPixelContext- let- input = withInputOff 400 240- ui = nanoFormSubmit "submit" "Save" (pure (42 :: Int))- initial <- warmup2 ctx input ui- check "form submitted before activation" (initial == Nothing)- (submitted, _, _, _) <-- runFrame ctx input {inputKeys = inputKeysFromList [KeyEnter]} ui- check "valid submission did not return its value" (submitted == Just 42)- idle <- warmup2 ctx input ui- check "a submitted form kept emitting values on idle frames" (idle == Nothing)--testResetWidgets :: IO ()-testResetWidgets = do- ctx <- newPixelContext- let- input = withInputOff 400 240- ui =- columnWith fillW $- (,)- <$> nanoFormLive "reset-left" enabledForm- <*> nanoFormLive "reset-right" enabledForm- _ <- warmup2 ctx input ui- controls <- checkboxes ctx- case controls of- [(_, leftRect), (rightId, rightRect)] -> do- forM_ [leftRect, rightRect] $ \rect -> do- let- (press, release) = clickPair input (spanCenter rect)- void (runFrame ctx press ui)- void (runFrame ctx release ui)- edited <- warmup2 ctx input ui- check "checkboxes did not retain their edits" (edited == (Just True, Just True))- runNanoUI ctx input (resetForm "reset-left")- reset <- warmup2 ctx input ui- check- "reset did not restore defaults or changed another form"- (reset == (Just False, Just True))- after <- checkboxes ctx- check- "reset changed another form's widget identity"- (map fst (drop 1 after) == [rightId])- setFormStore ctx "reset-left" emptyFormStateStore- persisted <- warmup2 ctx input ui- check- "writing form data revived a retired widget cache"- (persisted == (Just False, Just True))- _ -> fail "expected two reset-test checkboxes"--testResetTextArea :: IO ()-testResetTextArea = do- ctx <- newPixelContext- let- input = withInputOff 400 240- ui = nanoFormLive "reset-editor" (inputTextArea "notes" "initial")- _ <- warmup2 ctx input ui- controls <- controlsOf NodeTextArea ctx- case controls of- [(wid, _)] -> do- writeIORef (ctxFocusId ctx) wid- void (runFrame ctx input {inputChars = "edited"} ui)- edited <- warmup2 ctx input ui- check "text area did not retain its edit" (edited == Just "editedinitial")- runNanoUI ctx input (resetForm "reset-editor")- reset <- warmup2 ctx input ui- check "reset retained the text area's cached buffer" (reset == Just "initial")- _ -> fail "expected one reset-test text area"