Tutorial 2: Build a Notepad
In this tutorial, you will build a plain-text editor with a menu bar, keyboard shortcuts, asynchronous file dialogs, undo/redo history, a status bar, and a warning prompt when closing with unsaved edits.
The complete program is in packages/nano-ui-demo/examples/Notepad.hs. Run it with:
cabal run nano-ui-sdl-notepad
1. Session-level state
TextDocument is not one of the primitive types useVar supports, and our menu commands need a stable reference to the editor’s widget ID. Both belong in a state record allocated once during setup:
data NotepadState = NotepadState
{ doc :: !(Var TextDocument)
, editorId :: !(Var WidgetId)
, openDlg :: !(Var (Maybe FileDialogId))
, saveDlg :: !(Var (Maybe FileDialogId))
}
-- | A notepad's private document and dialog state. Allocate one per
-- instance before starting the SDL session, and draw it with 'notepadUi'.
newNotepad :: IO NotepadState
newNotepad = do
doc <- newVar emptyDocument
editorId <- newVar (WidgetId 0)
openDlg <- newVar Nothing
saveDlg <- newVar Nothing
pure NotepadState {..}
Simpler view-local values (which menu is open, the current file path, the dirty flag, zoom level, and status messages) can live in useVar calls inside the view. As a rule of thumb, allocate shared or handle-based state (documents, tasks, dialogs) in IO before starting the app, and keep local UI flags in useVar.
2. Close confirmation
Normally, clicking the window’s close button exits immediately. To catch unsaved changes first, disable automatic exit with wsExitOnCloseRequest = False:
main :: IO ()
main = do
state <- newNotepad
runSdlApp
defaultSdlOptions
{ -- A close request goes to the view, which may ask about unsaved changes.
sdlWindowSettings =
defaultWindowSettings
{ wsTitle = "nano-ui Notepad"
, wsSize = Size 1000 720
, wsExitOnCloseRequest = False
}
, sdlAppTheme = Just tomorrowNightMinDarkTheme
}
(notepadUi state)
With that option disabled, winCloseRequested <$> askWindow becomes True on the frame the user tries to close the window. Instead of quitting immediately, the view calls exitApp:
item (winCloseRequested <$> askWindow) exitApp
When the document has no unsaved edits, exitApp closes the window right away; otherwise it opens a confirmation modal. We will wire up the modal in section 7.
3. Building a menu bar from primitives
nano-ui does not have a dedicated menuBar widget. Instead, you compose a row of menuButton' widgets, each paired with a popup' anchored to its button rectangle. Because a popup’s body is plain NanoUI (), menus can contain any combination of items, separators, or custom rows.
openMenu stores the title of whichever menu is currently open (or an empty string when all menus are closed):
menuBar :: Var Text -> [(Text, NanoUI ())] -> NanoUI ()
menuBar openMenu entries = do
current <- readVar openMenu
rowWith (tight . fillW . fixedH 28) $ do
for_ entries $ \(menuLabel, body) -> do
let
isOpen = current == menuLabel
-- Each title covers the bar's height, its text in the middle.
btn <- menuButtonWith' fillH menuLabel isOpen
when (respClicked btn) (writeVar openMenu (if isOpen then "" else menuLabel))
when
(not isOpen && not (T.null current) && respHovered btn)
(writeVar openMenu menuLabel)
let
cfg =
(defaultPopupConfig (AnchorRect (respRect btn)))
{ popupPlacement = PlacementBelow
, popupOffset = 0
}
-- The open flag is derived from the open menu's name, so the popup
-- gets a constant and closing it is written here.
(popupResp, _) <- popup' (constVar isOpen) cfg (columnWith (tight . gap 0) body)
when (respClicked popupResp) (writeVar openMenu "")
popup' expects a Var Bool for its open state, while our source of truth is openMenu. Passing constVar isOpen supplies a read-only Var (writes to it are ignored), and when the popup reports a click or dismissal via its response, we update openMenu directly.
Important
Always call overlays unconditionally. Notice that
popup'runs for every menu on every frame, even when closed; while closed it draws nothing. Puttingpopup'insidewhen isOpenwould shift the widget IDs of following siblings whenever a menu opens or closes.
4. Commands, menus, and shortcuts
Menu rows use menuItem and menuItemShortcut. Each returns True on the frame it is activated, so the command runs right away:
item menuRow action = whenM menuRow (writeVar openMenu "" >> action)
fileMenu = do
commandItem newCmd
commandItem openCmd
commandItem saveCmd
commandItem saveAsCmd
menuSeparator
commandItem exitCmd
(newDocument, openDocument, saveDocument, and exitApp are plain NanoUI () helpers defined in the full source; openDocument launches a non-blocking dialog with askOpenFileDialog.)
menuItemShortcut displays the shortcut hint on the row and listens for that chord only while the menu is open. To make shortcuts work when the menu is closed too, register the same chords with shortcut outside the menu:
for_ [newCmd, openCmd, saveCmd, saveAsCmd, exitCmd] $
\(_, chord, action) -> item (shortcut chord) action
Only the first matching binding in a frame fires, so the menu item and the top-level shortcut will never trigger twice. Because the menu is declared earlier in the view, its item handles the chord whenever it is open.
menuItemDisabled "Undo"draws a dimmed, non-interactive row. The Edit menu switches between a normal item and a disabled one based ontextCanUndoandtextCanRedo.- Opening a file dialog stores the returned
FileDialogIdin aVar. Dialogs run asynchronously, so the UI keeps responding while the OS dialog is open.
5. Opening and saving files
In nano-ui-sdl, file dialogs never block the render loop. useFileDialog polls a Var (Maybe FileDialogId), passes the selected paths to your callback once the dialog closes, and restores focus to the main window:
useFileDialog openDlg $ \chosenPaths ->
for_ (listToMaybe chosenPaths) $ \filePath -> do
loaded <-
liftIO (try (BS.readFile filePath) :: IO (Either SomeException BS.ByteString))
case loaded of
Left _ -> writeVar statusMsg ("Could not open " <> T.pack filePath)
Right raw -> do
-- Lenient decode: malformed bytes become U+FFFD instead of throwing.
writeVar doc (textDocument (TE.decodeUtf8With (\_ _ -> Just '\xFFFD') raw))
-- A new editor, without the old document's caret and undo history.
modifyVar docGen (+ 1)
writeVar docPath (T.pack filePath)
writeVar docDirty False
writeVar statusMsg ("Opened " <> T.pack filePath)
useFileDialog saveDlg $ \chosenPaths ->
for_ (listToMaybe chosenPaths) $ \filePath -> do
saved <- writeDocument filePath =<< readVar doc
if saved
then do
writeVar docPath (T.pack filePath)
writeVar docDirty False
writeVar statusMsg ("Saved " <> T.pack filePath)
else writeVar statusMsg ("Could not save " <> T.pack filePath)
Clicking Open starts a dialog and saves its handle:
openCmd =
( "Open..."
, cmdOrCtrl <> key 'o'
, writeVar openDlg . Just =<< askOpenFileDialog defaultFileDialogOptions
)
Saving is ordinary IO wrapped in liftIO, triggered only by an event:
writeDocument :: FilePath -> TextDocument -> NanoUI Bool
writeDocument filePath doc = do
result <-
liftIO
( try (BS.writeFile filePath (TE.encodeUtf8 (documentText doc))) ::
IO (Either SomeException ())
)
pure (isRight result)
Only call documentText when you actually need a flat Text value (such as when saving). During normal typing, TextDocument updates individual lines without rebuilding the full string on every keystroke.
6. The editor
textAreaDocument edits a Var TextDocument with structural line sharing and built-in undo history. Its primed variant (textAreaDocument') returns the Response we need for dirty tracking and menu commands:
editorResp <-
withKey gen $
textAreaDocumentWith'
(grow . minW 240 . minH 160 . fontSizeScale zoomVal)
doc
-- respChanged reports an edit, not a caret move.
when (respChanged editorResp) (writeVar docDirty True)
writeVar editorId (respId editorResp)
withKey genresets the editor’s internal state whenever a new file is loaded or created by bumpinggen, giving the new document a clean caret, selection, and undo stack. Normal edits leavegenunchanged.respChangedisTrueonly when text is modified, not when the user merely moves the cursor or selects text. That prevents inspecting a file from marking it dirty.- Saving
respIdlets our Edit menu target the editor withrunTextCommand editor Undoand otherTextCommandactions.
fontSizeScale zoomVal adjusts display size without altering the document, so the zoom actions are simple clamped modifyVar updates.
7. Dirty state, window title, and the close prompt
The window title is computed from the current file name and dirty flag on every frame, then passed to setWindowTitle:
path <- readVar docPath
dirty <- readVar docDirty
let
name = (if T.null path then "Untitled" else path) <> (if dirty then " *" else "")
-- ...after the layout, which returns the name as docName:
setWindowTitle (docName <> " - nano-ui Notepad")
setWindowTitle caches the last title and skips the OS call when nothing changed, so calling it unconditionally on every frame is safe and free. Imperative window commands like resizeWindow or maximizeWindow run on every call and must always sit behind an event check.
Here is how exitApp and the confirmation modal connect:
exitApp = do
dirty <- readVar docDirty
if dirty then writeVar aboutOpen False >> writeVar confirmExit True else quit
-- ...inside the view, called unconditionally:
modal confirmExit "Unsaved changes" $ do
label "Discard the changes to this document and exit?"
rowWith fillW $ do
flex
whenM (button "Discard") quit
whenM (button "Cancel") (writeVar confirmExit False)
Opening the exit prompt closes the About modal first so only one modal appears at a time. Like popups, modal is called unconditionally every frame and controlled by its Var Bool.
8. Undo, redo, and editing commands
Typing, right-click menu actions, and programmatic commands all flow through TextCommand, so they share a single undo stack. The Edit menu queries textCanUndo and textCanRedo, then dispatches commands using the editor’s widget ID:
editMenu = do
editor <- readVar editorId
canUndo <- textCanUndo editor
canRedo <- textCanRedo editor
if canUndo
then editItem "Undo" (cmdOrCtrl <> key 'z') Undo
else menuItemDisabled "Undo"
if canRedo
then editItem "Redo" (cmdOrCtrl <> shift <> key 'z') Redo
else menuItemDisabled "Redo"
menuSeparator
editItem "Cut" (cmdOrCtrl <> key 'x') Cut
editItem "Copy" (cmdOrCtrl <> key 'c') Copy
editItem "Paste" (cmdOrCtrl <> key 'v') Paste
menuSeparator
editItem "Select All" (cmdOrCtrl <> key 'a') SelectAll
TextCommand includes InsertText, Delete, Move, Select, Replace, ReplaceAll, Undo, Redo, Cut, Copy, Paste, and SelectAll. Dispatching commands preserves undo history; overwriting the Var TextDocument directly resets it.
Tip
While a text editor has focus, it claims its own editing shortcuts (Ctrl+Z, Ctrl+X, Ctrl+C, and so on), and
shortcutignores claimed keys. Menu rows still work because they dispatch commands directly, while the top-level shortcuts handle cases where focus is outside the editor.
9. The status bar
The status bar is a row of muted labels. Reading documentLineCount does not flatten the document into a single Text; word and character counts are computed from documentText:
statusBar :: Text -> Var TextDocument -> Var Text -> Float -> NanoUI ()
statusBar docName docVar statusMsg zoomVal = do
doc <- readVar docVar
message <- readVar statusMsg
rowWith (tight . gap 12 . fillW . padXY 8 4) $ do
labelWith (tight . fontMuted) message
flex
labelWith (tight . fontMuted) docName
labelWith
(tight . fontMuted)
("Lines: " <> T.pack (show (documentLineCount doc)))
labelWith
(tight . fontMuted)
("Zoom: " <> T.pack (show (round (zoomVal * 100) :: Int)) <> "%")
Reading doc here causes the status bar to repaint whenever the document changes, which is what we want so the counters stay current. If a counter’s width fluctuates as digits are added, pin it with fixedW so adjacent status labels do not shift sideways (see Recurring Bugs).
10. Things to try next
- Persist a list of recently opened files across launches.
- Turn the About dialog into a draggable, resizable
floatingWindow. - Toggle word wrap through the editor’s configuration.
- Replace the OS title bar with a custom one using
windowCaptionandwindowFrame(see Desktop Windows).
Next: Tutorial 3: Live Data & Background Work moves slow I/O onto worker threads and plots streamed values in real time.