Tutorial 1: Build a Todo List
In this tutorial, you will build a todo list that supports adding items with Enter, editing rows inline, filtering by status (all, active, or completed), reordering items without scrambling per-row state, and clearing finished tasks. The full source lives in packages/nano-ui-demo/examples/TodoList.hs.
Run the finished example with:
cabal run nano-ui-example-todo-list
1. The data model
Every todo item needs a stable ID that stays the same even when the list changes. List indices shift whenever an item is added, deleted, filtered, or moved; an explicit ID does not. Later, we will key every row’s widgets and local Vars by this ID.
data Todo = Todo
{ todoId :: !Int
, todoText :: !Text
, todoDone :: !Bool
}
deriving (Eq, Generic)
-- | The items in order, and the id the next one gets.
data Todos = Todos
{ todoItems :: ![Todo]
, todoNext :: !Int
}
deriving (Eq, Generic)
newtype App = App {appTodos :: Var Todos}
Because useVar only handles a fixed set of primitive types, we create Var Todos once in IO during startup using newVar:
newApp :: IO App
newApp =
App
<$> newVar
( Todos
[ Todo 0 "Read the header" True
, Todo 1 "Water the plants" False
, Todo 2 "Edit me, then delete the first row" False
]
3
)
Creating the Var in main and passing it into the view lets it persist across frames. Calling liftIO (newVar ...) inside the view would allocate a brand-new Var on every single pass.
Both records derive Generic. With OverloadedRecordDot, app.appTodos.todoItems gives you a Var [Todo] focused on that one field, so changing the item list will not trigger repaints in widgets that only read todoNext.
2. The application shell
main :: IO ()
main = do
app <- newApp
runSdlApp
defaultSdlOptions
{ sdlAppShouldQuit = pressedOnceIn KeyEscape
, sdlWindowSettings =
defaultWindowSettings {wsTitle = "Todo list", wsSize = Size 720 560}
}
(todoApp app)
runSdlApp calls todoApp on every frame, and todoApp lays out the entire window from top to bottom each time:
todoApp :: App -> NanoUI ()
todoApp app = do
let
items = app.appTodos.todoItems
draft <- useVar ""
filt <- useEnumVar All
columnWith (padAll 20 . gap 12 . fillW . fillH) $ do
heading "Todos"
newItemRow app.appTodos draft
filterRow items filt
todoList items filt
Notice that the draft input text and the active filter do not need fields in App. Both are local to this view, so useVar and useEnumVar allocate them automatically based on their call position.
3. Adding an item
The input row displays a text field next to an Add button and inserts a new item when the user presses Enter or clicks the button.
newItemRow :: Var Todos -> Var Text -> NanoUI ()
newItemRow todosVar draft = rowWith (tight . gap 8 . alignMiddle . fillW) $ do
inputR <-
textInputConfigured'
defaultTextInputConfig {ticPlaceholder = "What needs doing?"}
draft
clicked <- button "Add"
text <- T.strip <$> readVar draft
when ((clicked || respSubmitted inputR) && not (T.null text)) $ do
modifyVar todosVar (\(Todos xs n) -> Todos (xs <> [Todo n text False]) (n + 1))
writeVar draft ""
requestFocus (respId inputR)
A few important details are at work here:
textInputConfigured'(the primed form) returns aResponsecontaining the widget’s ID, bounds, hover/click flags, andrespSubmitted(which turnsTruewhen the user presses Enter). By contrast,buttonreturns just theBoolwe need.readVar draftruns below the text input that edits it, so the read immediately sees the new text in the same pass. Reading above an editing widget forces a second pass of the view.modifyVarapplies a pure function to the latest stored value, so multiple updates in one frame compose without overwriting each other.- After inserting the item, we clear
draftand callrequestFocusso the user can keep typing the next task right away. Focus requests take effect at the end of the frame.
Note
Always guard state mutations with an event condition. Because the view runs every frame, an unguarded
modifyVarwould insert a new todo on every single frame. Put event-driven work insidewhenM (button ...)or an explicitwhencheck like the one above.
4. Filtering and a derived count
The active filter has three values. useEnumVar works with any Enum/Bounded type and remembers the selection across frames:
data Filter = All | Active | Done
deriving (Eq, Show, Enum, Bounded)
matches :: Filter -> Todo -> Bool
matches All _ = True
matches Active t = not (todoDone t)
matches Done t = todoDone t
filterRow :: Var [Todo] -> Var Filter -> NanoUI ()
filterRow items filt = rowWith (tight . gap 12 . alignMiddle . fillW) $ do
-- A header for every filter, as a segmented control.
enumTabBarByConfigured
defaultTabsConfig {tabsStyle = TabSegmented}
(T.pack . show)
filt
flex
todos <- readVar items
let
left = length (filter (not . todoDone) todos)
labelWith
(tight . alignMiddle . fontMuted)
(T.pack (show left) <> if left == 1 then " item left" else " items left")
disabledWhen (left == length todos) $
whenM (button "Clear completed") (modifyVar items (filter (not . todoDone)))
enumTabBarByConfigured creates a segmented tab bar with one segment per constructor of Filter, using show for the labels. The active item count is derived on the fly from the current list rather than copied into a separate Var that could fall out of sync. Wrapping the clear button in disabledWhen dims it and ignores clicks without removing it from the layout.
5. Rows own their state
Each row tracks two pieces of local UI state: whether it is currently being edited, and the text currently in its edit box. Because the list can be filtered or reordered at any time, that state has to stay attached to the item’s ID rather than its row position on screen.
todoList :: Var [Todo] -> Var Filter -> NanoUI ()
todoList items filt = do
shownFilter <- readVar filt
scrollWith (grow . fillW) $
columnWith (tight . gap 6 . fillW) $
withElemVars todoId items $ \todos at -> do
let
shown = filter (matches shownFilter) todos
-- Pass each row its visible neighbors so Up and Down skip filtered-out rows.
forM_
(zip3 shown (Nothing : map Just shown) (map Just (drop 1 shown) <> [Nothing])) $ \(todo, above, below) ->
withKey (todoId todo) (todoRow items (at todo) above below)
withElemVars todoId itemsreturns the current list alongside anat :: Todo -> Var Todolookup function. Eachat todotracks its element bytodoId, so edits keep hitting the right item after filtering or reordering.withKey (todoId todo)ties the row’s internal widget state (caret position, selection) and itsuseVarslots to the same ID. WithoutwithKey, deleting the first item would shift every later row’s edit mode and half-typed text up onto the wrong item.matchesfilters the visible items. We also pass each row its visible neighbors (aboveandbelow) so the Up and Down buttons move past hidden items instead of swapping with rows the user cannot see.
Here is the core structure of a single row:
todoRow :: Var [Todo] -> Var Todo -> Maybe Todo -> Maybe Todo -> NanoUI ()
todoRow items todo above below = do
-- Local state, kept under this row's key.
editing <- useVar False
focusPending <- useVar False
draft <- useVar ""
t <- readVar todo
isEditing <- readVar editing
let
tid = todoId t
save = do
writeVar todo.todoText =<< readVar draft
writeVar editing False
when isEditing (whenM takeEscape (writeVar editing False))
rowWith (tight . gap 8 . alignMiddle . fillW) $ do
checkboxWith alignMiddle "" todo.todoDone
-- The label and the field swap places, so they share a scope.
scope $
if isEditing
then do
fieldR <- textInput' draft
-- Focus can only move to a widget declared in the pass that asks,
-- and the field first appears in the pass after Edit was clicked,
-- so the request waits in a Var.
whenM
(readVar focusPending)
(requestFocus (respId fieldR) >> writeVar focusPending False)
when (respSubmitted fieldR) save
else
labelWith
(fillW . alignMiddle . (if todoDone t then fontStrike . fontMuted else id))
(todoText t)
whenM (button (if isEditing then "Save" else "Edit")) $
if isEditing
then save
else
writeVar draft (todoText t)
>> writeVar editing True
>> writeVar focusPending True
disabledWhen (null above) $
whenM (button "Up") (forM_ above (modifyVar items . swapIds tid . todoId))
disabledWhen (null below) $
whenM (button "Down") (forM_ below (modifyVar items . swapIds tid . todoId))
whenM
(styled destructive (button "Delete"))
(modifyVar items (filter ((/= tid) . todoId)))
Three patterns keep this row solid:
scopewraps the label/input toggle. Only one branch of theifruns on any given frame. Withoutscope, toggling between a label and a text input would shift the widget IDs of all siblings that follow.scopereserves one consistent slot either way (and the row’suseVarslots stay isolated underwithKey).- Focus is requested on the frame the field appears.
requestFocuscan only target a widget declared during the current pass. When the user clicks Edit, the text input will not exist until the next pass, so we set afocusPendingflag and callrequestFocusonce the input is actually drawn. - Field projections update items in place.
todo.todoDoneis aVar Boolfor that item’s completion flag, which letscheckboxtoggle it directly. Saving writes the draft intotodo.todoTextand leaves edit mode.
6. Reordering by ID
The Up and Down buttons need to swap two items in the full list, even when a filter hides rows between them. Looking up items by ID handles both filtered and unfiltered views:
-- | Swap the places of two items, by id.
swapIds :: Int -> Int -> [Todo] -> [Todo]
swapIds a b xs = map pick xs
where
byId i t = fromMaybe t (find ((== i) . todoId) xs)
pick t
| todoId t == a = byId b t
| todoId t == b = byId a t
| otherwise = t
Because each row is keyed by todoId, any active edit state moves right along with the item.
7. Keyboard behavior
Pressing Enter in the input box adds an item via respSubmitted. While editing an existing row, Escape cancels the edit:
when isEditing (whenM takeEscape (writeVar editing False))
takeEscape consumes the Escape press so later handlers in the view (such as an open popup or another row) will not react to the same keystroke. Window exit policy is configured separately: the example sets sdlAppShouldQuit = pressedOnceIn KeyEscape, so Escape still exits the app unless you change that option or handle quitting inside the view.
For the complete keyboard model (shortcut, shortcutOnce, menu bindings, and how focused widgets claim keys), see Keyboard, Focus & IME.
8. Things to try next
- Replace the Up and Down buttons with drag-and-drop reordering using
useReorder(see Drag & Drop). - Persist the active filter across sessions in a
Settingsrecord created withnewVar. - Display an empty-state message such as
muted "Nothing here yet."whenshownis empty. - Add draft validation using
nano-ui-form(see Ecosystem Packages).
Next: Tutorial 2: Build a Notepad introduces menu bars, native file dialogs, and full document editing.