nano-ui-0.2.0.0: lib/NanoUI/Widgets/Custom.hs
-- | Custom widgets and the reference widgets built on them.
--
-- The widgets provided in this module ('knob', 'toggleSwitch', 'circularProgress',
-- 'progressBar', 'spinner', 'sparkline') serve as reference implementations for
-- custom widgets that users may want to implement themselves. This API is meant
-- to accompany the canvas API ('CanvasM', 'customWidget', 'customWidgetWithId'),
-- demonstrating how 2D vector drawing, layout sizing, gesture hooks ('useDrag2DOn',
-- 'useWheelDeltaOn'), keyboard navigation, and responsive state binding ('bindVar')
-- integrate into cohesive, interactive controls.
--
-- 'customWidget' takes a 'CustomWidgetSpec': a layout, optional measurement,
-- a draw function receiving hover and press state, an optional content key, a
-- cursor, and damage slop.
-- 'canvas' is the short form: it draws into a laid-out rectangle with
-- 'CanvasM' (rects, circles, lines, images, text, "NanoUI.Path" paths, clips
-- and transforms). 'canvasConfigured' adds a content key, a cursor and
-- pointer tracking; 'drawContext' reads the hover, press, and theme state
-- inside 'CanvasM'.
-- 'useDrag2DOn' and 'useWheelDeltaOn' are gesture hooks that take the
-- widget's 'Response'; 'knob' and 'toggleSwitch' show them in use. Each
-- reference widget follows the ordinary @x@, @x'@, @xWith@ and @xWith'@
-- convention: a prime adds the 'Response', and @With@ accepts layout and size.
module NanoUI.Widgets.Custom
( -- * Custom widgets
-- ** On a Var
-- | 'bindVar' adapts a pure @a -> NanoUI (Response, a)@ widget to mutate a
-- 'Var' in place.
Binding (..)
, bindVar
, bindVarBy
-- ** Specs
, CustomWidgetSpec (..)
, KeyClaim (..)
, defaultCustomWidgetSpec
, customWidget
, customWidgetWithId
, contentKey
, contentKeyOf
, KeyPart
, keyPart
, CustomDrawContext (..)
, CustomMeasureFn
, CustomDrawBuild
, DrawOp (..)
, DrawingBuild
, shiftDrawOp
, drawing
, drawingVersioned
, drawingCached
, setChanged
, setClicked
, setSubmitted
-- * Canvas
, CanvasM
, canvas
, CanvasConfig (..)
, defaultCanvasConfig
, canvasConfigured
, runCanvasFor
, drawContext
, drawRect
, drawRoundedRect
, drawCircle
, drawStroke
, drawStrokeRoundedRect
, drawStrokeCircle
, drawStrokeAA
, drawQuadGradient
, drawLinearGradientH
, drawLinearGradientV
, drawImage
, drawImageUV
, ImageDraw (..)
, imageDraw
, drawImageWith
, drawText
, drawTextWith
, drawTextClipped
, drawTextClippedWith
, drawCheckbox
, checkboxBoxSize
-- * Paths, clips and transforms
-- | Build a path with "NanoUI.Path", imported qualified, and fill or
-- stroke it here, in a colour or a 'NanoUI.Path.Paint'. 'withTransform'
-- moves, turns and scales what a block draws, and 'withClip' clips it.
, drawPath
, drawPathWith
, drawStrokePath
, drawStrokePathWith
, withTransform
, withClip
-- * Gestures
, useDrag2DOn
, Drag2D (..)
, useWheelDeltaOn
-- * Reference widgets
, knob
, knob'
, knobWith
, knobWith'
, toggleSwitch
, toggleSwitch'
, toggleSwitchWith
, toggleSwitchWith'
, circularProgress
, circularProgress'
, circularProgressWith
, circularProgressWith'
, spinner
, spinner'
, spinnerWith
, spinnerWith'
, progressBar
, progressBar'
, progressBarWith
, progressBarWith'
, sparkline
, sparkline'
, sparklineWith
, sparklineWith'
) where
import Control.Monad (void, when)
import Data.Text qualified as T
import Data.Primitive.SmallArray (emptySmallArray)
import NanoUI.Internal.Canvas
import NanoUI.Internal.Context
import NanoUI.Internal.Draw (DrawOp (..), DrawingBuild, shiftDrawOp)
import NanoUI.Internal.Widgets.Drawing (drawing, drawingCached, drawingVersioned)
import Data.Word (Word64)
import Data.Hashable (Hashable, hash)
import GHC.Float (castFloatToWord32)
import NanoUI.Internal.Font (checkboxBoxSize)
import NanoUI.Internal.Id (WidgetId, mix64)
import NanoUI.Internal.Input
import NanoUI.Internal.Layout.Arena (NodeType (NodeDrawing))
import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, nextId, liftIO, uiTime, withContext)
import NanoUI.Path qualified as P
import NanoUI.Internal.Store
import NanoUI.Internal.Store.Slots (slotDragPoint, slotDragPress)
import NanoUI.Internal.Style
import NanoUI.Internal.Types
import NanoUI.Internal.Var (Binding (..), bindVar, bindVarBy)
import NanoUI.Internal.Var.Types (Var)
import NanoUI.Internal.Widgets.Behavior (dragPressLive, leftPress, navStep, useKeyNav)
import NanoUI.Internal.Widgets.Combinators (finishInput, finishToggle, widgetBaseLayout)
import NanoUI.Internal.Widgets.Node
import NanoUI.Internal.Widgets.Animate (wakeAfter)
import NanoUI.Internal.Sensor.Types (Watch (..))
import NanoUI.Internal.Widgets.Sensor (Visibility (..), defaultSensorConfig, watchSensor)
import NanoUI.Internal.Widgets.Custom (customDrawContext)
-- -----------------------------------------------------------------------------
-- Custom Widget Specification
-- -----------------------------------------------------------------------------
-- | Complete specification for defining a custom widget.
data CustomWidgetSpec a = CustomWidgetSpec
{ widgetLayout :: !LayoutModifier
-- ^ Flex layout modifier applied on top of 'defaultLayout' (with inherited
-- font defaults): for example, @fixedWH 120 24@.
, widgetMeasure :: !(Maybe CustomMeasureFn)
-- ^ Optional intrinsic measurement hook for 'Fit' or dynamic sizing.
, widgetDraw :: !CustomDrawBuild
-- ^ Vector drawing procedure receiving interaction context and layout rect.
, widgetContent :: !Int
-- ^ Content key: a number that changes whenever 'widgetDraw' would draw
-- something different ('contentKey' hashes numbers into one). If the key,
-- size, interaction state and metrics are unchanged, the frame skips
-- rebuilding the ops and repainting. The default 0 means no key: ops are
-- rebuilt and compared every frame. A stale key draws stale pixels, so
-- derive it from everything the drawing reads. The key is trusted even
-- while the widget animates.
, widgetCursor :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))
-- ^ Pointer shape over the widget, given the draw context, the widget's
-- rect and the pointer position, so different parts can show different
-- shapes. It is also queried during a drag that started on the widget,
-- so the drag keeps its shape. 'UiCursorDefault' defers to an enclosing
-- 'NanoUI.withCursorShape', or the arrow.
--
-- > widgetCursor = Just $ \_ (Rect x _ w _) (V2 px _) ->
-- > if px > x + w - 6 then UiCursorEwResize else UiCursorDefault
, widgetFocusable :: !Bool
-- ^ Whether this widget accepts tab/keyboard focus.
, widgetKeys :: !KeyClaim
-- ^ Keys the widget handles itself while focused; shortcuts and
-- 'NanoUI.keyPressed' ignore them. Default 'KeysNavigate'. A terminal or
-- an editor with its own chords uses 'KeysAll'. A widget that claims Tab
-- ('KeysAll', or 'KeysOnly' naming it) keeps focus when it is pressed.
-- Use 'KeysOnly' with "NanoUI.Shortcut" chords for precise ownership,
-- 'KeysNone' to reserve none, or 'KeysReadOnly' for selectable text.
, widgetDamageSlop :: !Float
-- ^ Padding added to dirty rectangles (for shadows, glow, or drag handles).
, widgetTrackPointer :: !Bool
-- ^ Run a frame on every pointer move over the widget, for drawings that
-- depend on the pointer position. Default 'False': a move runs a frame
-- only when it crosses onto another widget.
, widgetInteract :: !(Response -> CustomDrawContext -> Input -> (Response, a))
-- ^ Interaction hook: maps the resolved 'Response', draw context and
-- input to the final response and value.
}
-- | Default configuration for a custom widget with standard hover/press/click behavior.
defaultCustomWidgetSpec :: CustomWidgetSpec ()
defaultCustomWidgetSpec = CustomWidgetSpec
{ widgetLayout = id
, widgetMeasure = Nothing
, widgetDraw = \_ _ -> emptySmallArray
, widgetContent = 0
, widgetCursor = Nothing
, widgetFocusable = False
, widgetKeys = KeysNavigate
, widgetDamageSlop = defaultDamageSlop
, widgetTrackPointer = False
, widgetInteract = \resp _ _ -> (resp, ())
}
fixedSizeSpec :: (Layout -> Layout) -> Float -> Float -> CustomWidgetSpec ()
fixedSizeSpec f w h =
defaultCustomWidgetSpec {widgetLayout = fixedWH w h . f, widgetMeasure = Just $ \_ _ -> (w, h)}
-- | A 'widgetContent' key for a drawing whose output follows these numbers.
-- Pass every value the drawing reads; @0@ means "no key", so a hash that lands
-- there becomes 1.
{-# INLINE contentKey #-}
contentKey :: [Float] -> Int
contentKey vs = contentKeyOf [KeyPart (fromIntegral (castFloatToWord32 v)) | v <- vs]
-- | A 'widgetContent' key over 'Hashable' values, mixed in order. Unlike
-- 'contentKey', an 'Int' or 'Double' is hashed whole, not rounded to 'Float'.
--
-- > widgetContent = contentKeyOf [keyPart version, keyPart scrollY, keyPart query, keyPart selected]
{-# INLINE contentKeyOf #-}
contentKeyOf :: [KeyPart] -> Int
contentKeyOf parts =
let raw = foldl' (\acc (KeyPart v) -> mix64 acc v) 0x9E3779B97F4A7C15 parts
k = fromIntegral raw
in if k == 0 then 1 else k
-- | One value of a 'contentKeyOf' key, made by 'keyPart'.
newtype KeyPart = KeyPart Word64
-- | Wrap any 'Hashable' value (including lists, 'Maybe', tuples, or custom
-- types deriving 'Hashable') for 'contentKeyOf'.
{-# INLINE keyPart #-}
keyPart :: Hashable a => a -> KeyPart
keyPart = KeyPart . fromIntegral . hash
-- | Instantiates a custom widget using an existing 'WidgetId'.
customWidgetWithId :: WidgetId -> CustomWidgetSpec a -> NanoUI (Response, a)
customWidgetWithId wid spec = do
ctx <- askContext
inp <- askInput
lay <- widgetBaseLayout defaultLayout (widgetLayout spec)
when (widgetFocusable spec) $ liftIO (registerFocusable ctx wid)
resp0 <- addWidget wid NodeDrawing T.empty 0 lay
-- Registered on the node just added ('NanoUI.Internal.Context.ctxNodeCustom').
cdc <- liftIO $ do
case widgetMeasure spec of
Just fn -> registerCustomMeasure ctx wid fn
Nothing -> pure ()
registerCustomEntry ctx wid (specEntry spec)
customDrawContext ctx (ctxFontMetrics ctx) wid (respHovered resp0) (respPressed resp0)
pure (widgetInteract spec resp0 cdc inp)
-- | Instantiates a custom widget from a 'CustomWidgetSpec'.
customWidget :: CustomWidgetSpec a -> NanoUI (Response, a)
customWidget spec = nextId >>= (`customWidgetWithId` spec)
-- | Draw into a rectangle sized by the layout modifier. Curves are flattened
-- for the current display ('runCanvasFor'). Ops are rebuilt and compared
-- every frame; use 'canvasConfigured' for a content key or a cursor.
canvas :: LayoutModifier -> (Rect -> CanvasM ()) -> NanoUI Response
canvas f = canvasConfigured defaultCanvasConfig {canvasLayout = f}
-- | Options for 'canvasConfigured'.
data CanvasConfig = CanvasConfig
{ canvasLayout :: !LayoutModifier
-- ^ Layout modifier applied on top of 'defaultLayout' (default 'id').
, canvasContent :: !Int
-- ^ As 'widgetContent'; build it with 'contentKey' or 'contentKeyOf'.
-- Default 0 (no key): the drawing runs every frame.
, canvasTrackPointer :: !Bool
-- ^ As 'widgetTrackPointer' (default 'False').
, canvasCursor :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))
-- ^ As 'widgetCursor' (default 'Nothing').
, canvasFocusable :: !Bool
-- ^ As 'widgetFocusable' (default 'False'): a Tab stop, focused by a
-- press too, with the focus ring Tab draws. Read its keys with
-- 'NanoUI.focusedKeyPressed' or 'NanoUI.useKeyNav' on the response's id.
, canvasKeys :: !KeyClaim
-- ^ As 'widgetKeys' (default 'KeysNavigate').
}
-- | Default layout modifier ('id'), with no content key, cursor or pointer tracking.
defaultCanvasConfig :: CanvasConfig
defaultCanvasConfig =
CanvasConfig
{ canvasLayout = id
, canvasContent = 0
, canvasTrackPointer = False
, canvasCursor = Nothing
, canvasFocusable = False
, canvasKeys = KeysNavigate
}
-- | 'canvas' with a 'CanvasConfig'. The drawing reads hover, press state and
-- theme with 'drawContext':
--
-- > canvasConfigured defaultCanvasConfig {canvasLayout = fixedWH 120 24, canvasContent = contentKey [level]} $ \r -> do
-- > cdc <- drawContext
-- > drawRoundedRect r 4 (if cdcHovered cdc then themeAccent (cdcTheme cdc) else themeMuted (cdcTheme cdc))
canvasConfigured :: CanvasConfig -> (Rect -> CanvasM ()) -> NanoUI Response
canvasConfigured cfg drawAction =
fst <$> customWidget defaultCustomWidgetSpec
{ widgetLayout = canvasLayout cfg
, widgetContent = canvasContent cfg
, widgetTrackPointer = canvasTrackPointer cfg
, widgetCursor = canvasCursor cfg
, widgetFocusable = canvasFocusable cfg
, widgetKeys = canvasKeys cfg
, widgetDraw = \cdc rect -> runCanvasFor cdc (drawAction rect)
}
-- -----------------------------------------------------------------------------
-- Common Gesture & Behavior Helpers
-- -----------------------------------------------------------------------------
-- | Result of a 2D drag gesture.
data Drag2D = Drag2D
{ dragPosition :: !V2
-- ^ Current dragged pointer position clamped within bounds.
, dragActive :: !Bool
-- ^ True while pointer is pressed and dragging is active.
, dragDelta :: !V2
-- ^ Movement delta since previous frame.
}
deriving (Eq, Show)
-- | A left-button drag that starts with a press on the widget and lasts
-- until release, wherever the pointer goes. For colour pickers, joysticks or
-- panned canvases. The position is clamped to the widget's rect. Only the
-- widget's own press ('respPressed') starts a drag, so nothing starts when
-- the press lands on an overlay, a scrolled-off part, or a disabled widget.
-- Call it every frame, after the widget:
--
-- > (resp, ()) <- customWidget spec
-- > drag <- useDrag2DOn resp
-- > when (dragActive drag) (setPan (dragPosition drag))
useDrag2DOn :: HasResponse r => r -> NanoUI Drag2D
useDrag2DOn r = do
(wid, ctx) <- freshWidget
inp <- askInput
-- The press that started the drag is quiet bookkeeping (it causes no
-- damage); the last pointer position goes in a point slot. As in
-- 'useDrag1D', the drag lasts only under that press, so one released while
-- this hook did not run does not come back.
let bounds = respRect r
key = intKey wid
mouse = inputMousePos inp
store <- liftIO (getStore ctx)
let held = findSpec slotDragPress 0 key store
active0 <- liftIO (dragPressLive ctx key store)
let active = heldIn MouseLeft inp && (active0 || (pressedIn MouseLeft inp && respPressed r))
prev = findSpec slotDragPoint mouse key store
delta = if active && active0 then v2Sub mouse prev else V2 0 0
clampedMouse =
V2
(clamp (rectX bounds) (rectX bounds + rectW bounds) (v2X mouse))
(clamp (rectY bounds) (rectY bounds + rectH bounds) (v2Y mouse))
when (active || held /= 0) . liftIO $ do
press <- if active && not active0 then leftPress ctx else pure held
modifyStore ctx $
if active
then insertSpec slotDragPress key press . insertSpec slotDragPoint key mouse
else deleteSpec slotDragPress key . deleteSpec slotDragPoint key
pure Drag2D {dragPosition = clampedMouse, dragActive = active, dragDelta = delta}
-- | This frame's wheel delta while the widget is hovered ('respHovered').
-- Returns @(0, 0)@ when covered by an overlay, clipped out of view, or disabled.
-- The widget does not take the wheel from a scroller around it: one that can
-- still scroll that way moves by the same notches on the same frame.
useWheelDeltaOn :: HasResponse r => r -> NanoUI (Float, Float)
useWheelDeltaOn r = do
V2 x y <- inputScroll <$> askInput
pure (if respHovered r then (x, y) else (0, 0))
-- -----------------------------------------------------------------------------
-- Reference Custom Widgets
-- -----------------------------------------------------------------------------
-- | Rotary knob over @[minV, maxV]@ (36 px diameter) backed by a 'Var'.
-- Supports vertical drag, scroll wheel, and arrow keys. In a scroller that
-- can still scroll, the wheel turns the knob and scrolls too
-- ('useWheelDeltaOn').
{-# INLINE knob #-}
knob :: Float -> Float -> Var Float -> NanoUI ()
knob minV maxV v = void (knobWith' id 36 minV maxV v)
-- | 'knob' returning its response.
{-# INLINE knob' #-}
knob' :: Float -> Float -> Var Float -> NanoUI Response
knob' = knobWith' id 36
-- | 'knob' with a layout modifier and diameter.
{-# INLINE knobWith #-}
knobWith :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI ()
knobWith f diameter lo hi v = void (knobWith' f diameter lo hi v)
-- | 'knob' with a layout modifier and a diameter in pixels, returning its
-- response.
{-# INLINE knobWith' #-}
knobWith' :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI Response
knobWith' f diameter minV maxV v = bindVarBy sameFloat RenderFinal v (knobCore f diameter minV maxV)
knobCore ::
(Layout -> Layout)
-> Float
-> Float
-> Float
-> Float
-> NanoUI (Response, Float)
knobCore f diameter minV maxV value = do
(wid, ctx) <- freshWidget
-- NaN never equals itself, so it would be re-adopted, dirtying every frame.
current <- liftIO $ adoptSlot fieldFloat ctx wid (if isNaN value then minV else value)
let
range = maxV - minV
fracOf x = if range > 0 then clamp01 ((x - minV) / range) else 0
spec x =
(fixedSizeSpec f diameter diameter)
{ widgetCursor = Just (\_ _ _ -> UiCursorNsResize)
, widgetFocusable = True
, widgetContent = contentKey [fracOf x]
, widgetDraw = \cdc (Rect bx by bw bh) -> runCanvasFor cdc $ do
let
cx = bx + bw / 2
cy = by + bh / 2
r = min (bw / 2) (bh / 2) - 2
button = themeButton (cdcTheme cdc)
bgCol
| cdcPressed cdc = styleActiveBg button
| cdcHovered cdc = styleHoverBg button
| otherwise = styleBg button
angle = (135 + fracOf x * 270) * (pi / 180)
tip = V2 (cx + cos angle * (r * 0.75)) (cy + sin angle * (r * 0.75))
drawCircle (V2 cx cy) r bgCol
drawStrokeCircle (V2 cx cy) r 1.5 (styleBorder button)
drawStrokeAA (V2 cx cy) tip 2.5 (themeAccent (cdcTheme cdc))
}
(resp, ()) <- customWidgetWithId wid (spec current)
drag <- useDrag2DOn resp
(_, scrollY) <- useWheelDeltaOn resp
nav <- useKeyNav wid
let
deltaNorm = -v2Y (dragDelta drag) / 120 + scrollY * 2 / 60 + fromIntegral (navStep nav) * 0.05
finalVal
| range > 0 && deltaNorm /= 0 = clamp minV maxV (current + deltaNorm * range)
| otherwise = current
-- Re-register the drawing when the value changes so this frame renders the
-- updated position.
when (finalVal /= current) $ liftIO (registerCustomEntry ctx wid (specEntry (spec finalVal)))
finishInput fieldFloat ctx wid current resp finalVal
-- | Boolean toggle switch backed by a 'Var', toggled by click or Space/Enter.
{-# INLINE toggleSwitch #-}
toggleSwitch :: Var Bool -> NanoUI ()
toggleSwitch v = void (toggleSwitchWith' id v)
-- | 'toggleSwitch' returning its response.
{-# INLINE toggleSwitch' #-}
toggleSwitch' :: Var Bool -> NanoUI Response
toggleSwitch' = toggleSwitchWith' id
-- | 'toggleSwitch' with a layout modifier.
{-# INLINE toggleSwitchWith #-}
toggleSwitchWith :: (Layout -> Layout) -> Var Bool -> NanoUI ()
toggleSwitchWith f v = void (toggleSwitchWith' f v)
-- | 'toggleSwitch' with a layout modifier, returning its response.
{-# INLINE toggleSwitchWith' #-}
toggleSwitchWith' :: (Layout -> Layout) -> Var Bool -> NanoUI Response
toggleSwitchWith' f v = bindVar RenderFinal v (toggleSwitchCore f)
toggleSwitchCore ::
(Layout -> Layout) -> Bool -> NanoUI (Response, Bool)
toggleSwitchCore f on = do
(wid, ctx) <- freshWidget
current <- intBool <$> liftIO (adoptSlot fieldInt ctx wid (boolInt on))
let
pillW = 44.0
pillH = 24.0
spec isOn =
(fixedSizeSpec f pillW pillH)
{ widgetCursor = Just (\_ _ _ -> UiCursorPointer)
, widgetFocusable = True
, widgetKeys = KeysActivate
, widgetContent = contentKey [if isOn then 1 else 0]
, widgetDraw = \cdc rect@(Rect x y w h) -> runCanvasFor cdc $ do
let
theme = cdcTheme cdc
r = h / 2
thumbX = if isOn then x + w - r else x + r
drawRoundedRect rect r (if isOn then themeAccent theme else styleBg (themeButton theme))
drawStrokeRoundedRect rect r 1 (styleBorder (themeButton theme))
drawCircle (V2 thumbX (y + r)) (r - 3) (themeOnAccent theme)
}
(resp, ()) <- customWidgetWithId wid (spec current)
result@(_, value) <- finishToggle ctx wid current resp
when (value /= current) $ liftIO (registerCustomEntry ctx wid (specEntry (spec value)))
pure result
{-# INLINE specEntry #-}
specEntry :: CustomWidgetSpec a -> CustomDrawingEntry
specEntry spec =
CustomDrawingEntry
(widgetContent spec)
(widgetDraw spec)
(widgetCursor spec)
(widgetDamageSlop spec)
(widgetTrackPointer spec)
(widgetKeys spec)
-- | Progress ring for a fraction in @[0, 1]@, 32 px across.
{-# INLINE circularProgress #-}
circularProgress :: Float -> NanoUI ()
circularProgress frac = void (circularProgressWith' id 32 frac)
-- | 'circularProgress' returning its response.
circularProgress' :: Float -> NanoUI Response
circularProgress' = circularProgressWith' id 32
-- | 'circularProgress' with a layout modifier and diameter.
circularProgressWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
circularProgressWith f diameter = void . circularProgressWith' f diameter
-- | 'circularProgress' with a layout modifier and a diameter in pixels,
-- returning its response.
circularProgressWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
circularProgressWith' f diameter frac =
fst <$> customWidget (fixedSizeSpec f diameter diameter)
{ widgetContent = contentKey [clamp01 frac]
, widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do
let centre = V2 (x + w / 2) (y + h / 2)
r = min (w / 2) (h / 2) - 2
theme = cdcTheme cdc
clampedFrac = clamp01 frac
drawStrokeCircle centre r 2.0 (styleBorder (themeButton theme))
when (clampedFrac > 0) $
drawCircle centre (r * clampedFrac) (themeAccent theme)
}
-- | An indeterminate loading indicator, 18 px across: an accent arc turning
-- over a faint ring. While any of it is on screen it wakes the frame loop
-- for each of its 60 steps a second; scrolled or clipped out of view, it
-- wakes nothing.
{-# INLINE spinner #-}
spinner :: NanoUI ()
spinner = void (spinnerWith' id 18)
-- | 'spinner' returning its response.
spinner' :: NanoUI Response
spinner' = spinnerWith' id 18
-- | 'spinner' with a layout modifier and diameter.
spinnerWith :: (Layout -> Layout) -> Float -> NanoUI ()
spinnerWith f = void . spinnerWith' f
-- | 'spinner' with a layout modifier and a diameter in pixels, returning its
-- response. It requests a frame for its next step ('wakeAfter') while any of
-- it is on screen, so it costs 60 frames a second however fast the display
-- refreshes, and none while hidden.
spinnerWith' :: (Layout -> Layout) -> Float -> NanoUI Response
spinnerWith' f diameter = do
t <- uiTime
let !d = max 4 diameter
-- One turn every 0.8 s, in 48 steps: the step is the content key, so
-- frames within a step reuse the ops.
!step = floor (t * 48 / 0.8) `mod` 48 :: Int
resp <-
fst <$> customWidget (fixedSizeSpec f d d)
{ widgetContent = step + 1
, widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do
let theme = cdcTheme cdc
thick = max 1.5 (d / 9)
r = min w h / 2 - thick / 2
cx = x + w / 2
cy = y + h / 2
start = 2 * pi * fromIntegral step / 48
drawStrokeCircle (V2 cx cy) r thick (fadeAlpha (themeAccent theme) 48)
drawStrokePath (P.arc (V2 cx cy) r start (pi / 2)) thick (themeAccent theme)
}
-- The sensor is keyed by the spinner's own id, so it takes no sibling id.
vis <- withContext $ \ctx -> watchSensor ctx (respId resp) (Watch (respId resp) defaultSensorConfig)
when (visVisible vis) $
wakeAfter (max 1.0e-3 (fromIntegral (floor (t * stepsPerSec) + 1 :: Int) / stepsPerSec - t))
pure resp
where
stepsPerSec = 48 / 0.8 :: Double
-- | Horizontal progress bar for a fraction in @[0, 1]@. It fills the
-- available width at a fixed height.
{-# INLINE progressBar #-}
progressBar :: Float -> NanoUI ()
progressBar frac = void (progressBarWith' id progressBarDefaultHeight frac)
-- | 'progressBar' returning its response.
progressBar' :: Float -> NanoUI Response
progressBar' = progressBarWith' id progressBarDefaultHeight
-- | 'progressBar' with a layout modifier and height.
progressBarWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
progressBarWith f height = void . progressBarWith' f height
-- | 'progressBar' with a layout modifier and a height in pixels, returning
-- its response.
progressBarWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
progressBarWith' f height frac =
let !barH = max 0 height
in fst <$> customWidget defaultCustomWidgetSpec
{ widgetLayout = fixedH barH . f . fillW
, widgetMeasure = Just $ \_ _ -> (progressBarDefaultWidth, barH)
, widgetContent = contentKey [clamp01 frac]
, widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do
let theme = cdcTheme cdc
barW = max 0 w
barH' = max 0 h
rad = barH' / 2
fillWpx = barW * clamp01 frac
drawRoundedRect (Rect x y barW barH') rad (styleBg (themeButton theme))
when (fillWpx > 0) $
drawRoundedRect (Rect x y fillWpx barH') (min rad (fillWpx / 2)) (themeAccent theme)
drawStrokeRoundedRect (Rect x y barW barH') rad 1 (styleBorder (themeButton theme))
}
-- | Default height and minimum content width for 'progressBar'.
progressBarDefaultHeight, progressBarDefaultWidth :: Float
progressBarDefaultHeight = 12.0
progressBarDefaultWidth = 120.0
-- | A small line chart of the values, 80 by 24 px, scaled to their range.
{-# INLINE sparkline #-}
sparkline :: [Float] -> NanoUI ()
sparkline values = void (sparklineWith' id 80 24 values)
-- | 'sparkline' returning its response.
sparkline' :: [Float] -> NanoUI Response
sparkline' = sparklineWith' id 80 24
-- | 'sparkline' with a layout modifier, width and height.
sparklineWith :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI ()
sparklineWith f w h = void . sparklineWith' f w h
-- | 'sparkline' with a layout modifier and a preferred size, returning its
-- response.
sparklineWith' :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI Response
sparklineWith' f prefW prefH values =
fst <$> customWidget (fixedSizeSpec f prefW prefH)
{ widgetContent = contentKey values
, widgetDraw = \cdc rect@(Rect x y rw rh) -> runCanvasFor cdc $ do
let accent = themeAccent (cdcTheme cdc)
drawRoundedRect rect 3.0 (styleBg (themePanel (cdcTheme cdc)))
case values of
[] -> pure ()
[_] -> drawCircle (V2 (x + rw / 2) (y + rh / 2)) 2.0 accent
vs -> do
let minV = minimum vs
maxV = maximum vs
range = if maxV > minV then maxV - minV else 1.0
pad = 4.0
plotW = max 1.0 (rw - 2 * pad)
plotH = max 1.0 (rh - 2 * pad)
n = length vs
stepX = plotW / fromIntegral (max 1 (n - 1))
pts = [ V2 (x + pad + fromIntegral i * stepX)
(y + rh - pad - ((v - minV) / range) * plotH)
| (i, v) <- zip [0 :: Int ..] vs
]
drawStrokePath (P.polyline pts) 1.5 accent
drawCircle (last pts) 2.5 accent
}