Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Async Work & Animation

Two rules keep a nano-ui application feeling snappy and quiet: never block inside the view, and never redraw when nothing is changing. Move slow I/O onto worker threads, schedule delayed updates with timers, and let the event loop sleep in between. Always compile executables with -threaded.

Task: one background job per key

Allocate Task and Stream handles once in IO during startup:

data App = App
  { appSearch :: Task Text [Text]
  , appFile :: Task Text Text
  , appProgress :: Stream () Int
  }

newApp :: IO App
newApp = App <$> newTask <*> newTask <*> newStream

Inside the view, call useTaskStatus to run a job and inspect whether it is loading, finished, or failed:

results :: App -> Text -> NanoUI ()
results app queryKey = do
  status <- useTaskStatus (appSearch app) queryKey (fetchSearchResults queryKey)

  case status of
    TaskRunning previous -> showPreviousOrSpinner previous
    TaskDone found       -> renderResults found
    TaskFailed err _     -> danger (T.pack (displayException err))

If you only care about the most recent completed result, useTask is simpler:

fileView :: App -> Text -> NanoUI ()
fileView app path = do
  contents <- useTask (appFile app) path (T.readFile (T.unpack path))
  label (fromMaybe "Loading..." contents)

How task lifecycles work:

  • Key changes restart the job. Whenever the key changes, nano-ui cancels the previous worker with an asynchronous exception and starts a new one.
  • Skipping the hook cancels the job. If a full frame runs without calling useTask (for instance, because the user switched to another tab or hid a conditional panel), the running worker is canceled. Call useTask outside the tab or branch if work should keep going while hidden.
  • Include a counter in the key to support retries. Pressing Retry on the same input only restarts the task if the key changes (for example, (query, attempt)).
  • Clean up resources with bracket. Because cancellation arrives as an asynchronous exception, acquire files, sockets, or database handles inside bracket or withFile.
  • Force results on the worker thread. useTask evaluates the result to weak head normal form on the worker; if you return a lazy list, force its spine (length found \seq` pure found`) before returning so evaluation does not happen on the UI thread.
  • Keep old results visible while loading. TaskRunning previous carries the last completed result so search lists do not flash blank on every new query.

Stream: continuous pushed updates

Use Stream for background producers that emit values over time: download progress, sensor telemetry, log tails, or streamed model responses.

progress :: App -> NanoUI ()
progress app = do
  pct <- useStream (appProgress app) () (0 :: Int) $ \update ->
    forM_ [1 .. 100] $ \i -> do
      threadDelay 50000
      update (const i)
  progressBar (fromIntegral pct / 100)

The producer receives update :: (s -> s) -> IO () and runs until it returns, throws, or gets canceled. Each call to update wakes the frame loop; multiple pushes between frames coalesce automatically into a single redraw.

  • Stop by skipping the call. Guarding useStream with when isRunning cancels the producer as soon as isRunning becomes False.
  • Save state outside if you want pause/resume. Stopping a stream discards its internal accumulator and restarts from the initial value next time.
  • Never touch the UI Context from a producer. Only call update from the producer thread (or threads it spawns).

Integrating your own threads

If you already manage worker threads outside Task and Stream, mutate shared Vars with the thread-safe IO functions and wake the loop with the callback from askWake:

refreshInBackground :: Var [Text] -> NanoUI ()
refreshInBackground queryResult = do
  wake <- askWake -- in the view, once

  void . liftIO . forkIO $ do
    result <- expensiveQuery
    writeVarIO queryResult result
    wake -- schedule one frame

readVarIO, writeVarIO, and modifyVarIO are safe from any thread. Calling wake schedules a frame that repaints only the widgets whose text, value, or style changed. For high-frequency updates, prefer Stream.

Animation

animateTo smoothly transitions a float toward a target value across frames:

sidebar :: Float -> NanoUI ()
sidebar targetWidth = do
  currentWidth <- animateTo (Tween EaseOutQuad 0.25 0) targetWidth
  panelWith (fixedW currentWidth . fillH) (label "Sidebar")

A Transition is either:

  • Tween ease duration delay (durations in seconds), with easing curves including EaseOutQuad, EaseInOutCubic, EaseOutBack, and EaseCubicBezier.
  • Spring params for damped spring physics, with presets presetSmooth, presetBouncy, and presetStiff.
follow :: Float -> Float -> NanoUI V2
follow targetX targetY = animateToA (Spring presetSmooth) (V2 targetX targetY)

Springs preserve velocity when retargeted mid-flight, so toggling a state back and forth never snaps abruptly. To animate any Animatable value channel by channel (Float, Double, V2, or Color), use animateToA. Once a tween or spring settles, it stops requesting frames and the loop goes back to sleep.

Continuous animations

pulse returns a value oscillating smoothly between 0 and 1 with a given period in seconds:

fading :: NanoUI Float
fading = pulse 1.2

Unlike animateTo, clock-based values like pulse do not wake the loop by themselves. Any widget that draws from a continuous animation must call keepAnimating with its own Response on every frame it is on screen:

breathingDot :: NanoUI ()
breathingDot = do
  t <- pulse 1.2
  (resp, ()) <- customWidget defaultCustomWidgetSpec
    { widgetLayout = fixedWH 24 24
    , widgetContent = contentKey [t * 100]
    , widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $
        drawCircle (V2 (x + w / 2) (y + h / 2)) (6 + 3 * t) (themeAccent (cdcTheme cdc))
    }
  keepAnimating resp

As soon as a frame stops calling keepAnimating, the loop goes right back to sleep.

Caution

Never force animation frames by marking the context dirty every frame. That creates an unpaced busy loop and burns CPU even when nothing is moving.

Timers

Call wakeAfter to schedule a single future frame after a delay in seconds:

clock :: NanoUI ()
clock = do
  label =<< currentTimeText
  wakeAfter 1

Pending wakes clear after every frame, so keep calling wakeAfter on each frame while the timer is still active.

Picking the right primitive

What you needPrimitive to use
Fetch or compute one result for a given inputTask with useTask or useTaskStatus
Receive a stream of updates over timeStream with useStream
Push updates from an existing background threadwriteVarIO / modifyVarIO plus askWake
Keep work running when its tab or panel is hiddenPlace useTask / useStream outside the tab or branch
Trigger periodic or delayed refresheswakeAfter
Animate values smoothly or continuouslyanimateTo / animateToA, or pulse with keepAnimating

For runnable programs, see Tutorial 3: Live Data & Background Work along with Tasks.hs, LiveChart.hs, and Animation.hs.