packages feed

nano-ui-emit (empty) → 0.2.0.0

raw patch · 8 files changed

+558/−0 lines, 8 filesdep +basedep +nano-uidep +nano-ui-emit

Dependencies added: base, nano-ui, nano-ui-emit, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- Extracted typed Elm-style message emission from `nano-ui` into `NanoUI.Emit`.+- `NanoUIE msg a` is a `NanoUI a` view with a typed message sink (`?emit`) in scope, so every core widget, container, overlay, and callback-taking widget runs inside an emitting view without wrappers or `Typeable`.+- Message adapters `emit`, `emitWhen`, `emitChanged`, `emitEdited`, and `mapMessages` for composing child components into a parent message type.+- Typed frame and reducer runners (`runFrameE`, `reduceFrame`, `reduceMessages`, `reduceUpdates`) and headless reducer testing helpers (`runClickReduce`).+- Per-frame messages stay ordered across view rebuilds, retain queued background messages on view exceptions, and discard messages from a failed pass.
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 goolord++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ README.md view
@@ -0,0 +1,33 @@+# nano-ui-emit++Statically typed message emission and Elm-style reducers for [nano-ui](https://github.com/goolord/nano-ui). `NanoUI.Emit` re-exports all of `NanoUI`, so standard containers, widgets, and overlays run inside `NanoUIE msg a` unchanged.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import NanoUI.Emit++data Msg = Save | SetVolume Float++view :: Float -> NanoUIE Msg ()+view volume = column $ do+  label "Settings"+  emitChanged (slider 0 100) volume SetVolume+  emitWhen (button "Save") Save+```++`NanoUIE msg a` is a `NanoUI a` action with a typed message sink in scope (`?emit`). Give top-level emitting views an explicit `NanoUIE Msg a` signature so GHC keeps the sink in scope, and avoid calling `emit` unconditionally at the top level of a view (a frame can run two passes).++- `emit :: msg -> NanoUIE msg ()`: Emits a message directly.+- `mapMessages :: (child -> parent) -> NanoUIE child a -> NanoUIE parent a`: Embeds reusable child views in traversal order.+- `emitWhen`, `emitChanged`, `emitEdited`: Adapt `NanoUI Bool` and `Var`-based widgets to emit messages on activation or user edits.++## Running views++Backend runners (`runSdlAppReduce`, `runRgfwAppReduce`, `runSdlWebAppReduce`) pair a `model -> NanoUIE msg ()` view with a pure update function `msg -> model -> model`.++For headless tests and custom loops, `runFrameE` collects emitted messages from a frame, `runFrameReduce` folds them into the model (flagging another frame when the model changes), and `runClickReduce` drives a press/release click pair.++## Documentation++- [The nano-ui Book: Elm-Style State](https://goolord.github.io/nano-ui/book/state/elm.html): Combining `NanoUIE` with local `Var` state and testing reducers.
+ lib/NanoUI/Emit.hs view
@@ -0,0 +1,191 @@+{-# LANGUAGE ImplicitParams #-}++-- |+-- Module      : NanoUI.Emit+-- Description : Statically typed messages and reducers for nano-ui+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- Reducer-style views with one statically checked message type.+--+-- A 'NanoUIE' view is an ordinary 'NanoUI' action with the view's message+-- sink in scope, so every widget exported by core "NanoUI" (re-exported+-- here) runs in it unchanged, including containers, overlays and widgets+-- taking callbacks or several bodies. 'emit' and the adapters below send+-- messages of the view's type; emitting another type is a compile error.+module NanoUI.Emit+  ( -- * Emitting messages+    NanoUIE+  , emit+  , emitWhen+  , emitChanged+  , emitEdited+  , mapMessages++    -- * Headless frame execution and reduction+  , runNanoUIE+  , runFrameE+  , runFrameReduce+  , runClickReduce+  , reduceMessages+  , reduceUpdates++    -- * Running a session+  , Reducer+  , newReducer+  , reducerModel+  , reduceFrame++    -- * Core widgets+  , module NanoUI+  )+where++import Control.Exception (onException)+import Control.Monad (unless, when)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import NanoUI+import NanoUI.Internal.Context (isDirty, markDirty)+import NanoUI.Backend (Context, DrawData, runFrame)+import NanoUI.Testing.Harness (clickPair)++import NanoUI.Emit.Internal+  ( NanoUIE+  , collectMessages+  , emit+  , mapMessages+  , runNanoUIE+  , withSink+  )++-- | Emit when a widget activates.+--+-- > emitWhen (button "Save") Save+{-# INLINE emitWhen #-}+emitWhen :: NanoUI Bool -> msg -> NanoUIE msg ()+emitWhen widget msg = widget >>= \active -> when active (emit msg)++-- | Run a 'Var'-based input widget on a temporary 'Var' initialized to @old@,+-- and emit only when the value changes. A widget that emits itself, given by+-- name, needs a lambda: @emitChanged (\\v -> myInput v) old SetValue@.+--+-- > emitChanged (slider 0 100) volume SetVolume+{-# INLINE emitChanged #-}+emitChanged :: Eq a => (Var a -> NanoUI r) -> a -> (a -> msg) -> NanoUIE msg ()+emitChanged widget old toMsg = do+  (_, new) <- withValue old widget+  when (new /= old) (emit (toMsg new))++-- | Emit a changed value only when the input's response also reports an+-- edit.+{-# INLINE emitEdited #-}+emitEdited ::+  (Eq a, HasResponse r) => (Var a -> NanoUI r) -> a -> (a -> msg) -> NanoUIE msg ()+emitEdited widget old toMsg = do+  (r, new) <- withValue old widget+  when (respChanged (toResponse r) && new /= old) (emit (toMsg new))++-- | Run a complete frame and collect messages from all its passes in order.+-- The queue belongs to this invocation: an exception cannot leak messages+-- into a later frame, nor can another runner consume them.+runFrameE :: Context -> Input -> NanoUIE msg a -> IO (a, [msg], DrawData, Bool)+runFrameE ctx inp view = do+  ((a, draw, dirty), msgs) <- collectMessages (\sink -> runFrame ctx inp (withSink sink view))+  pure (a, msgs, draw, dirty)++-- | View the model, then reduce all messages at frame end. The drawing is+-- from the pre-reduce model; a changed model requests a follow-up frame.+runFrameReduce ::+  Eq model =>+  (msg -> model -> model)+  -> Context+  -> Input+  -> model+  -> (model -> NanoUIE msg a)+  -> IO (a, model, [msg], DrawData, Bool)+runFrameReduce update ctx inp model view = do+  (a, msgs, draw, dirty) <- runFrameE ctx inp (view model)+  (model', dirty') <- reduceAfterFrame update ctx model msgs dirty+  pure (a, model', msgs, draw, dirty')++-- | Reduce a frame's messages; a changed model asks for another frame.+-- Answers the model and whether the context needs another frame.+reduceAfterFrame :: Eq model => (msg -> model -> model) -> Context -> model -> [msg] -> Bool -> IO (model, Bool)+reduceAfterFrame update ctx model msgs dirty = do+  let model' = reduceMessages update model msgs+  when (model' /= model) (markDirty ctx)+  (model',) . (dirty ||) <$> isDirty ctx++-- | Drive a left press and release through a reducer, returning the final+-- model, release-frame messages, and release-frame dirty flag.+runClickReduce ::+  Eq model =>+  (msg -> model -> model)+  -> Context+  -> Input+  -> model+  -> (model -> NanoUIE msg Response)+  -> V2+  -> IO (model, [msg], Bool)+runClickReduce update ctx inp model view pos = do+  let+    (press, release) = clickPair inp pos+  (_, modelP, _, _, _) <- runFrameReduce update ctx press model view+  (_, modelR, msgs, _, dirty) <- runFrameReduce update ctx release modelP view+  pure (modelR, msgs, dirty)++-- | A reducer session's update function and model, for a backend's runner.+-- It also keeps the messages a view emitted after its frame ended: a further+-- window's view ('NanoUI.nativeWindow') runs in that window's own frames+-- and emits through the sink of the view that declared it.+data Reducer msg model = Reducer+  { rUpdate :: msg -> model -> model+  , rModel :: IORef model+  , rFrame :: IORef (Maybe [msg])+  -- ^ The running frame's messages, newest first; 'Nothing' between frames.+  , rLate :: IORef [msg]+  -- ^ Messages emitted between frames, newest first.+  }++-- | A reducer session starting from @model@, with no messages pending.+newReducer :: (msg -> model -> model) -> model -> IO (Reducer msg model)+newReducer update model = Reducer update <$> newIORef model <*> newIORef Nothing <*> newIORef []++-- | The current model.+reducerModel :: Reducer msg model -> IO model+reducerModel = readIORef . rModel++-- | Run a frame of the view on the model, as 'runFrameReduce' does, and keep+-- the result. Messages emitted after an earlier frame ended are reduced+-- first, so the frame draws them; a message emitted after this frame ends+-- asks the context for another. If the frame throws, the messages it emitted+-- are dropped and the earlier late ones are kept for the next frame.+reduceFrame :: Eq model => Reducer msg model -> Context -> Input -> (model -> NanoUIE msg a) -> IO (a, DrawData, Bool)+reduceFrame r ctx inp view = do+  late <- readIORef (rLate r)+  unless (null late) (writeIORef (rLate r) [])+  model <- reduceMessages (rUpdate r) <$> readIORef (rModel r) <*> pure (reverse late)+  writeIORef (rFrame r) (Just [])+  let restore = do+        writeIORef (rFrame r) Nothing+        modifyIORef' (rLate r) (++ late)+  (a, draw, dirty) <- runFrame ctx inp (withSink sink (view model)) `onException` restore+  msgs <- maybe [] reverse <$> readIORef (rFrame r)+  writeIORef (rFrame r) Nothing+  (model', dirty') <- reduceAfterFrame (rUpdate r) ctx model msgs dirty+  writeIORef (rModel r) model'+  pure (a, draw, dirty')+  where+    sink msg = liftIO $ readIORef (rFrame r) >>= \case+      Just msgs -> writeIORef (rFrame r) (Just (msg : msgs))+      Nothing -> modifyIORef' (rLate r) (msg :) >> markDirty ctx++-- | Strictly fold messages through an update function in traversal order.+reduceMessages ::+  Foldable f => (msg -> model -> model) -> model -> f msg -> model+reduceMessages update = foldl' (flip update)++-- | Apply function-valued messages in traversal order.+reduceUpdates :: Foldable f => model -> f (model -> model) -> model+reduceUpdates = reduceMessages ($)
+ lib/NanoUI/Emit/Internal.hs view
@@ -0,0 +1,57 @@+{-# LANGUAGE ImplicitParams #-}++-- | Core types and emission mechanics for 'NanoUIE'.+module NanoUI.Emit.Internal+  ( NanoUIE+  , mapMessages+  , runNanoUIE+  , withSink+  , collectMessages+  , emit+  )+where++import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.IORef (modifyIORef', newIORef, readIORef)+import NanoUI (NanoUI)++-- | A UI action that can emit only @msg@: an ordinary 'NanoUI' action with+-- the view's message sink in scope as the implicit parameter @?emit@. Every+-- core widget, container and callback runs in it unchanged, and an emission+-- inside any of them goes to the sink of the view around it. The sink is+-- shared by every pass of a frame, so a local-state rebuild cannot discard+-- earlier messages.+type NanoUIE msg a = (?emit :: msg -> NanoUI ()) => NanoUI a++-- | Embed a child's message type in its parent's. Messages go straight to+-- the parent sink in traversal order, including across frame rebuilds.+--+-- > mapMessages SettingsMessage (settingsView settings)+{-# INLINE mapMessages #-}+mapMessages :: (child -> parent) -> NanoUIE child a -> NanoUIE parent a+mapMessages f body = let ?emit = ?emit . f in body++-- | Run an emitting view with @sink@ as its message sink.+{-# INLINE withSink #-}+withSink :: (msg -> NanoUI ()) -> NanoUIE msg a -> NanoUI a+withSink sink body = let ?emit = sink in body++-- | Collect messages from one UI action, in emission order. For complete+-- frames use 'NanoUI.Emit.runFrameE', which also retains messages across+-- rebuilds.+runNanoUIE :: NanoUIE msg a -> NanoUI (a, [msg])+runNanoUIE view = collectMessages (`withSink` view)++-- | Run a body with a sink that queues its messages, and return them in+-- emission order.+collectMessages :: MonadIO m => ((msg -> NanoUI ()) -> m a) -> m (a, [msg])+collectMessages body = do+  messages <- liftIO (newIORef [])+  a <- body (\msg -> liftIO (modifyIORef' messages (msg :)))+  msgs <- liftIO (reverse <$> readIORef messages)+  pure (a, msgs)++-- | Emit a message of this view's message type.+{-# INLINE emit #-}+emit :: msg -> NanoUIE msg ()+emit msg = ?emit msg
+ nano-ui-emit.cabal view
@@ -0,0 +1,60 @@+cabal-version:      3.4+name:               nano-ui-emit+version:            0.2.0.0+synopsis:           Statically typed messages and reducers for nano-ui+description:        Typed emitting views, widget adapters, and headless reducer runners.+license:            MIT+license-file:       LICENSE+author:             goolord+maintainer:         zacharyachurchill@gmail.com+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:    README.md CHANGELOG.md++source-repository head+    type:           git+    location:       https://github.com/goolord/nano-ui.git+    subdir:         packages/nano-ui-emit++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++library+    import:           warnings+    default-language: GHC2024+    exposed-modules:+        NanoUI.Emit+    other-modules:+        NanoUI.Emit.Internal+    hs-source-dirs:   lib+    build-depends:+        base >=4.20 && <4.23,+        nano-ui ^>=0.2++test-suite nano-ui-emit-test+    import:           warnings+    type:             exitcode-stdio-1.0+    default-language: GHC2024+    default-extensions: OverloadedStrings+    main-is:          Main.hs+    other-modules:    DeferredWrongMessage+    hs-source-dirs:   test+    build-depends:+        base >=4.20 && <4.23,+        nano-ui ^>=0.2,+        nano-ui-emit,+        text ^>=2.1
+ test/DeferredWrongMessage.hs view
@@ -0,0 +1,10 @@+{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}++-- | A view that must not typecheck, with its type error deferred to run time,+-- so the suite can check that emitting another message type is an error.+module DeferredWrongMessage (wrongMessage) where++import NanoUI.Emit (NanoUIE, emit)++wrongMessage :: NanoUIE Int ()+wrongMessage = emit True
+ test/Main.hs view
@@ -0,0 +1,176 @@+module Main (main) where++import Control.Exception (TypeError (..), evaluate, throwIO, try)+import Control.Monad (unless, when)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (isInfixOf)+import Data.Text qualified as T+import DeferredWrongMessage (wrongMessage)+import NanoUI qualified as UI+import NanoUI.Emit+import NanoUI.Testing (Context, DrawData, isDirty, newContext, runFrame)+import NanoUI.Testing.Assert (require, requireEq, withInput)+import NanoUI.Testing.Harness (centerOf)+import NanoUI.Testing.Sim hiding (result)++-- | Run a script against an emitting view in a fresh context, stopping at+-- its first failed check; its result is the view's with the frame's messages.+simE :: Input -> NanoUIE msg a -> Sim (a, [msg]) r -> IO r+simE inp view script = do+  ctx <- newContext+  failed <- newIORef 0+  runSimWith defaultSimOptions {simFailFast = True} ctx failed inp (runNanoUIE view) script++-- | The messages of one frame.+messages :: Context -> Input -> NanoUIE msg a -> IO [msg]+messages ctx inp view = (\(_, msgs, _, _) -> msgs) <$> runFrameE ctx inp view++data Msg = Inc | Dec deriving (Eq, Show)++update :: Msg -> Int -> Int+update Inc = (+ 1)+update Dec = subtract 1++main :: IO ()+main = do+  testReduce+  testAdapters+  testClick+  testScopes+  testWrongMessage+  testLateMessages+  putStrLn "Typed emission tests passed."++testReduce :: IO ()+testReduce = do+  ctx <- newContext+  let+    inp = withInput 80 80+    reduce :: NanoUIE Msg () -> IO (Int, [Msg], Bool)+    reduce emits = do+      ((), m, msgs, _, dirty) <- runFrameReduce update ctx inp 0 (\_ -> emits)+      pure (m, msgs, dirty)+  require "reducer messages and dirty" . (== (1, [Inc, Dec, Inc], True))+    =<< reduce (emit Inc >> emit Dec >> emit Inc)+  require "unchanged model stays clean" . (== (0, [Inc, Dec], False)) =<< reduce (emit Inc >> emit Dec)+  -- A message can be a function over a type the view does not know, and+  -- functions apply in emission order, not just as a net sum.+  functions <- messages ctx inp (emit ((+ 2) :: Int -> Int) >> emit (* 3))+  require "function messages in emission order" (reduceUpdates 1 functions == 9)++testAdapters :: IO ()+testAdapters = do+  ctx <- newContext+  calls <- newIORef (0 :: Int)+  let+    control v = liftIO (modifyIORef' calls (+ 1)) >> UI.modifyVar v (+ 1)+    adapters :: NanoUIE Int ()+    adapters = do+      emitWhen (pure False) (1 :: Int)+      emitWhen (pure True) 2+      emitChanged (\_ -> pure ()) 3 id+      emitChanged control 3 id+      emitEdited (\v -> (mempty :: Response) <$ UI.modifyVar v (+ 1)) 5 id+      emitEdited (\_ -> pure mempty {rawRespChanged = True}) 6 id+      emitEdited (\v -> mempty {rawRespChanged = True} <$ UI.modifyVar v (+ 1)) 7 id+  requireEq "adapters distinguish edits and changes" [2, 4, 8] =<< messages ctx (withInput 80 80) adapters+  requireEq "control evaluated once" 1 =<< readIORef calls++-- | Core buttons emit through 'emitWhen' and a primed response, and a click+-- reduces once.+testClick :: IO ()+testClick = do+  let+    inp = withInput 240 160+    view :: Int -> NanoUIE Msg Response+    view m = column $ do+      heading "Counter"+      row $ do+        emitWhen (button "-") Dec+        label (T.pack (show m))+        b <- button' "+"+        when (respClicked b) (emit Inc)+        pure b+  simE inp (view 0) $ do+    (_, idle) <- frame+    checkEq [] idle+    (_, decs) <- click "-"+    checkEq [Dec] decs+  ctx <- newContext+  -- Geometry lags a frame: the first frame's response has no rect yet.+  _ <- runFrameReduce update ctx inp 0 view+  (inc, model, _, _, dirty) <- runFrameReduce update ctx inp 0 view+  require "initial view" (model == 0 && not dirty)+  (model1, msgs1, dirty1) <- runClickReduce update ctx inp 0 view (centerOf inc)+  require "click reduces once" (msgs1 == [Inc] && model1 == 1 && dirty1)+  (_, model2, idle, _, _) <- runFrameReduce update ctx inp model1 view+  require "idle after click" (model2 == 1 && null idle)++-- | 'mapMessages' children keep their results and message order, and their+-- messages survive a rebuild once.+testScopes :: IO ()+testScopes = do+  ctx <- newContext+  let inp = withInput 120 80+  let+    child :: NanoUIE Bool Int+    child = UI.column $ do+      emit True+      UI.row (emit False)+      pure 42+  (mapped, msgs, _, _) <- runFrameE ctx inp $ do+    emit (Left "before" :: Either String Int)+    r <- mapMessages Right (mapMessages (\b -> if b then 1 else 2) child)+    emit (Left "after")+    pure r+  require "mapped children keep results and message order" $+    mapped == 42 && msgs == [Left "before", Right 1, Right 2, Left "after"]+  cell <- newVar False+  rebuilt <- messages ctx inp $ mapMessages Just $ do+    done <- readVar cell+    unless done $ emit True >> writeVar cell True+  require "mapped messages survive a child rebuild once" (rebuilt == [Just True])++-- | The message type is part of the view: emitting a Bool from an Int view+-- does not typecheck, so its deferred type error fires.+testWrongMessage :: IO ()+testWrongMessage = do+  ctx <- newContext+  result <- try (evaluate . sum =<< messages ctx (withInput 80 80) wrongMessage)+  case result of+    Left (TypeError err)+      | "Int" `isInfixOf` err && "Bool" `isInfixOf` err -> pure ()+      | otherwise -> fail ("the type error was not the Int/Bool mismatch: " <> err)+    Right _ -> fail "a view emitted a message of another type"++-- | A message emitted after its frame ended, as a further window's view+-- does through the sink of the view that declared it, asks for a frame,+-- which reduces it before drawing.+testLateMessages :: IO ()+testLateMessages = do+  ctx <- newContext+  other <- newContext+  reducer <- newReducer update 0+  later <- newIORef (pure ())+  seen <- newIORef []+  let inp = withInput 80 80+      view :: Int -> NanoUIE Msg ()+      view m = do+        UI.liftIO (modifyIORef' seen (m :))+        UI.liftIO (writeIORef later (emit Inc))+  _ <- reduceFrame reducer ctx inp view+  _ <- runFrame ctx inp (pure ())+  isDirty ctx >>= require "nothing pending before the late message" . not+  late <- readIORef later+  _ <- runFrame other inp late+  isDirty ctx >>= require "a late message asks for a frame"+  reducerModel reducer >>= requireEq "a late message waits for that frame" 0+  _ <- reduceFrame reducer ctx inp view+  reducerModel reducer >>= requireEq "the next frame reduces it" 1+  readIORef seen >>= requireEq "and draws the reduced model" [1, 0]+  -- A frame that throws keeps the late messages it took and drops its own.+  _ <- runFrame other inp late+  thrown <- try (reduceFrame reducer ctx inp (\_ -> emit Dec >> UI.liftIO (throwIO (userError "view failed"))))+  require "the failing frame throws" (either (const True) (const False) (thrown :: Either IOError ((), DrawData, Bool)))+  _ <- reduceFrame reducer ctx inp view+  reducerModel reducer >>= requireEq "a failed frame loses no late message" 2