Buttons, Menus & Inputs
This chapter covers the everyday interactive controls: buttons, menus, choice widgets, sliders, numeric fields, single-line text inputs, and color pickers.
Buttons
button :: Text -> NanoUI Bool
button' :: Text -> NanoUI Response
buttonWith :: (Layout -> Layout) -> Text -> NanoUI Bool
buttonContent :: NanoUI () -> NanoUI Bool
iconButton :: Svg -> Text -> NanoUI Bool
button draws a clickable button and returns True on the single frame it is activated (either by a left click, or by pressing Enter or Space while focused):
saveButton = whenM (button "Save Document") (liftIO saveFile)
Reach for the primed variant (button') whenever you need the Response for hover checks, anchoring a popup, or attaching a tooltip:
refreshButton = do
resp <- button' "Refresh"
tooltip resp "Poll the remote server for updates"
when (respClicked resp) refresh
buttonContent wraps an arbitrary NanoUI () view inside a clickable button. The inner widgets are purely visual; clicking anywhere on the button activates it:
iconSaveButton =
whenM (buttonContent $ rowWith (gap 6 . alignMiddle) $ do
svgIcon 16 saveIcon
label "Save") $
saveDocument
iconButton draws an SVG icon next to a label. Passing an empty string "" produces a square icon-only button.
Wrap adjacent buttons (including iconButton, toggleButton, buttonContent, and select) in buttonGroup or buttonGroupWith to join them with zero gap, outer-only corner rounding, and shared 1-pixel internal borders.
For selectable list items and collapsible sections without a full table or tree:
selectableRow selected body(plusselectableRow',selectableRowWith,selectableRowWith') renders a full-width clickable row that tints on hover and highlights whenselectedisTrue, returningTruewhen clicked.collapsing title openVar body(andcollapsingWith) renders a toggle header with a disclosure arrow and runsbodyinsidescopewhileopenVarisTrue.
Menus
Menu rows are built from menuItem (returns True when clicked), menuItemShortcut (shows a shortcut label and activates on that chord while the menu is open), menuSeparator, and menuItemDisabled.
Build a menu bar by pairing menuButton' triggers with popup' overlays anchored to each button’s rectangle:
fileMenu = do
fileOpen <- useVar False
isOpen <- readVar fileOpen
btn <- menuButton' "File" isOpen
when (respClicked btn) (writeVar fileOpen (not isOpen))
let cfg = (defaultPopupConfig (AnchorRect (respRect btn)))
{popupPlacement = PlacementBelow, popupOffset = 0}
(popupResp, _) <- popup' (constVar isOpen) cfg $
columnWith (tight . gap 0) $ do
whenM (menuItemShortcut "New" (cmdOrCtrl <> key 'n')) newDocument
whenM (menuItem "Open...") openDocument
menuSeparator
whenM (menuItem "Exit") (writeVar fileOpen False >> quit)
when (respClicked popupResp) (writeVar fileOpen False)
Here constVar passes a read-only open flag derived from openMenu, and clicks on the popup update openMenu directly.
Important
Call overlays unconditionally on every frame. A closed
popup'renders nothing, whereas wrapping it inwhen isOpenshifts sibling widget IDs every time a menu opens or closes.
Because menuItemShortcut only listens while its menu is open, bind the same chord outside the menu with shortcut if you want it to work when the menu is closed:
saveBindings :: NanoUI ()
saveBindings = do
whenM (menuItemShortcut "Save" saveChord) saveDocument
whenM (shortcut saveChord) saveDocument
Only the first matching binding in a frame fires, so the open menu item naturally takes priority over the fallback shortcut. For a complete menu bar implementation, see Tutorial 2: Build a Notepad.
Attach a right-click menu to any widget with a Response using contextMenu:
rowMenu = do
(_, rowResp) <- mouseArea (fillW . gap 6) (label "Right-click for actions")
void $ contextMenu rowResp $ do
whenM (menuItem "Inspect") inspectRow
whenM (menuItem "Copy") copyRow
Input widgets
Input widgets display a Var and mutate it in place, keeping transient editing state (caret position, text selection, open dropdowns) under their own widget ID. Write to the Var directly to reset or overwrite a field, and use the primed variant’s Response when you need to react to edits.
| Widget | Signature | Purpose |
|---|---|---|
checkbox | Text -> Var Bool -> NanoUI () | Checkbox with a label |
toggleButton | Tone -> Text -> Var Bool -> NanoUI () | Two-state button filled with its tone color when active |
radio | Foldable f => f Text -> Var Int -> NanoUI () | Radio button group indexed by position |
enumRadio / enumRadioBy | (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI () | Radio group covering every constructor of an enum (enumRadio uses Show) |
select | Foldable f => f Text -> Var Int -> NanoUI () | Dropdown selector indexed by position |
enumSelect / enumSelectBy | (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI () | Dropdown selector over every constructor of an enum (enumSelect uses Show) |
comboBox | Foldable f => Text -> f Text -> Var Text -> NanoUI () | Free-text field with filterable autocomplete suggestions |
slider | Float -> Float -> Var Float -> NanoUI () | Continuous horizontal slider between min and max |
textInput | Var Text -> NanoUI () | Single-line text input |
searchInput | Text -> Var Text -> NanoUI () | Search field with placeholder, clear button, and debounced changes |
numericInput | Var Double -> NanoUI () | Numeric input with increment/decrement steppers |
colorPicker | Var Color -> NanoUI () | Saturation/value square and hue slider |
Every widget in this table provides a primed form (...') returning a Response. Simpler controls (checkbox, toggleButton, select, slider) add ...With for layout modifiers, while richer fields (textInput, searchInput, numericInput) add ...Configured taking a config record (whose *Layout field carries any layout modifier):
byteField = do
byte <- useVar (0 :: Double)
numericInputConfigured defaultNumericInputConfig
{nicMin = 0, nicMax = 255, nicHex = True} byte
Text and search fields
queryField = do
query <- useVar ""
resp <- textInput' query
when (respSubmitted resp) (search =<< readVar query)
when (respChanged resp) (preview =<< readVar query)
On textInput', respChanged is True on every edit and respSubmitted is True when the user presses Enter. When an edit triggers expensive work like filtering a database or calling an API, use searchInput' instead: its respChanged is debounced (300 ms by default) and fires immediately when the clear button is clicked:
packageSearch = do
query <- useVar ""
resp <- searchInput' "Find a package" query
when (respChanged resp) (refreshResults =<< readVar query)
Choices
data Pace = Walk | Jog | Sprint
deriving (Eq, Show, Enum, Bounded)
choices = do
enabled <- useVar True
checkbox "Enable notifications" enabled
isBold <- useVar False
toggleButton Accent "B" isBold
pace <- useEnumVar Jog
enumRadio pace
enumSelect pace
Use select when the options come from runtime data rather than a fixed enum:
sizeSelect = do
choice <- useVar 0
select ["Small", "Medium", "Large"] choice
comboBox accepts both suggested options and arbitrary text. Its respChanged flag fires only when the user commits a choice, not when your code updates the Var externally.
Sliders, numbers, and color
values :: Var Color -> NanoUI ()
values accent = do
volume <- useVar (40 :: Float)
slider 0 100 volume
count <- useVar (0 :: Double)
numericInput count
colorPicker accent -- accent <- newVar (colorHex "#38bdf8") in setup
numericInput accepts digits (plus a leading minus sign when negative numbers are allowed). Pressing Up or Down steps the value, and holding Shift multiplies the step by 10. Set nicDecimals to control both formatting and precision. For colors with transparency, use colorPickerRGBA, which adds an alpha bar.