packages feed

nano-ui-diagrams 0.1.0.0 → 0.2.0.0

raw patch · 16 files changed

+1085/−1076 lines, 16 filesdep −effectful-coredep ~colourdep ~containersdep ~diagrams-libPVP ok

version bump matches the API change (PVP)

Dependencies removed: effectful-core

Dependency ranges changed: colour, containers, diagrams-lib, dlist, hashable, hspec, lens, nano-ui, primitive, text, vector

API changes (from Hackage documentation)

- NanoUI.Diagrams.Tessellation: fillPolygon :: Color -> [(Float, Float)] -> [DrawOp]
- NanoUI.Diagrams.Tessellation: flattenCubic :: (Float, Float) -> (Float, Float) -> (Float, Float) -> (Float, Float) -> [(Float, Float)]
- NanoUI.Diagrams.Tessellation: strokePolyline :: Color -> Float -> Bool -> [(Float, Float)] -> [DrawOp]
- NanoUI.Diagrams.Tessellation: triangulatePolygon :: [(Float, Float)] -> [((Float, Float), (Float, Float), (Float, Float))]
+ NanoUI.Plot.Chrome: chartDiagramWithTicks :: FontMetrics -> Theme -> PlotStyle -> (Domain, Domain) -> ([(Double, Text)], [(Double, Text)]) -> [Vector (Double, Double)] -> Chart -> Diagram B
+ NanoUI.Plot.Chrome: chartTicks :: (Domain, Domain) -> Chart -> ([(Double, Text)], [(Double, Text)])
+ NanoUI.Plot.Scale: domainBoundsBy :: Vector v a => (a -> Double) -> v a -> Domain
+ NanoUI.Plot.Scale: niceTickLabels :: Int -> Domain -> [(Double, Text)]
+ NanoUI.Plot.Scale: settleDomain :: Domain -> Domain
+ NanoUI.Plot.Types: instance NanoUI.Internal.Widgets.Node.HasResponse NanoUI.Plot.Types.PlotResponse
+ NanoUI.Plot.Widget: data PlotCache
+ NanoUI.Plot.Widget: newPlotCache :: IO PlotCache
- NanoUI.Diagrams.Widget: diagram :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> Eff es Response
+ NanoUI.Diagrams.Widget: diagram :: (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> NanoUI Response
- NanoUI.Diagrams.Widget: diagramWithEnvelope :: forall (es :: [Effect]). Ui :> es => Double -> Double -> (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> Eff es Response
+ NanoUI.Diagrams.Widget: diagramWithEnvelope :: Double -> Double -> (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> NanoUI Response
- NanoUI.Diagrams.Widget: diagramWithKeyAndEnvelope :: forall (es :: [Effect]). Ui :> es => Int -> Double -> Double -> (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> Eff es Response
+ NanoUI.Diagrams.Widget: diagramWithKeyAndEnvelope :: Int -> Double -> Double -> (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> NanoUI Response
- NanoUI.Diagrams.Widget: uiPlotStyle :: forall (es :: [Effect]). Ui :> es => Eff es PlotStyle
+ NanoUI.Diagrams.Widget: uiPlotStyle :: NanoUI PlotStyle
- NanoUI.Plot.Widget: areaChart :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse
+ NanoUI.Plot.Widget: areaChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse
- NanoUI.Plot.Widget: barChart :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [(Text, Double)] -> Eff es PlotResponse
+ NanoUI.Plot.Widget: barChart :: PlotCache -> (Layout -> Layout) -> [(Text, Double)] -> NanoUI PlotResponse
- NanoUI.Plot.Widget: lineChart :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse
+ NanoUI.Plot.Widget: lineChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse
- NanoUI.Plot.Widget: plot :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Chart -> Eff es PlotResponse
+ NanoUI.Plot.Widget: plot :: PlotCache -> (Layout -> Layout) -> Chart -> NanoUI PlotResponse
- NanoUI.Plot.Widget: scatterChart :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse
+ NanoUI.Plot.Widget: scatterChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse

Files

CHANGELOG.md view
@@ -1,10 +1,32 @@ # Changelog +## 0.2.0.0 -- 2026-12-02++### Breaking changes++- Plot widgets now take an explicit `PlotCache` allocated once with `newPlotCache`.+- Views and widgets use the concrete `NanoUI` monad instead of `Ui :> es => Eff es`, dropping the `effectful-core` dependency.+- Removed `NanoUI.Diagrams.Tessellation`. Build vector paths with `NanoUI.Path` and draw them through `drawPath` / `drawStrokePath`.++### Added++- `niceTickLabels`, `domainBoundsBy`, and `settleDomain` in `NanoUI.Plot.Scale`.+- `HasResponse` instance for `PlotResponse`, allowing `resp*`, `tooltip`, and `contextMenu` directly on chart responses.++### Changed++- Charts and diagrams render anti-aliased paths (`FillPolygon` and `StrokePolyline`) with full line cap, join, miter limit, dashing, and even-odd/non-zero fill rule support.+- Bar charts label the x axis by category name and anchor bars at y = 0.+- Default decimation preserves up to 2000 scatter/marker points; hover selects the nearest point in screen pixels; tick labels keep exact precision for fine steps and large offsets.+- Unchanged charts skip re-boxing and redundant style comparisons, cutting per-frame allocation by half or more on retained multi-thousand-point plots.+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).++### Fixed++- Non-finite values (NaN, infinities) are ignored in domains, drawing, and hover without triggering continuous redraws.+- Area series now include their baseline in the y domain, fill cleanly across baseline crossings, and align with data coordinates (along with diamond and triangle markers).+- Fixed step series final segments, `withMarker` on line series, `LegendTop` placement, translucent diagram opacity, `fitLayout` on zero-width diagrams, and growing-width plots preserving caller height constraints.+ ## 0.1.0.0  First release.--- `diagram` places a diagrams-lib `Diagram` in a nano-ui layout, drawn-  through a nano-ui backend for diagrams.-- `NanoUI.Plot` builds line, bar, scatter, area and step charts with axes,-  legends, and hover lookup, and decimates long series before drawing them.
README.md view
@@ -1,11 +1,8 @@ # nano-ui-diagrams -Charts and [diagrams](https://diagrams.github.io/) drawings for-[nano-ui](https://github.com/goolord/nano-ui).+Charts and [diagrams](https://diagrams.github.io/) vector graphics for [nano-ui](https://github.com/goolord/nano-ui). Backend-agnostic: pair with any `nano-ui` backend to open a window. -`diagram` places a diagrams-lib `Diagram` in a nano-ui layout. `NanoUI.Plot`-builds line, bar, scatter, area, and step charts with axes, legends, and hover-lookup, and thins out long series before drawing them.+`NanoUI.Plot` draws line, bar, scatter, area, and step charts with automatic axes, legends, hover inspection, and point decimation for large series. `NanoUI.Diagrams` re-exports `NanoUI.Plot` alongside `diagram`, which embeds any `diagrams-lib` `Diagram` inside a `nano-ui` layout.  ```haskell {-# LANGUAGE OverloadedStrings #-}@@ -22,13 +19,17 @@       , line "Outdoor" [(0, 8), (1, 11), (2, 14), (3, 12)]       ] -view :: NanoUI ()-view = column $ do-  resp <- plot (minH 240 . fillW) temperatures+-- Allocate cache <- newPlotCache once during setup.+view :: PlotCache -> NanoUI ()+view cache = column $ do+  resp <- plot cache (minH 240 . fillW) temperatures   case plotHover resp of     Just h -> label (T.pack (show (hoverDataX h, hoverDataY h)))     Nothing -> pure () ``` -The Plots tab of `nano-ui-sdl-demo` in `nano-ui-demo` shows more charts and a-diagram.+Series points use data-space coordinates while the layout modifier passed to `plot` sizes the widget in logical pixels. Define static `Chart` values outside the per-frame view so `PlotCache` skips rebuilds between frames.++## Documentation++- [The nano-ui Book: Charts and Diagrams](https://goolord.github.io/nano-ui/book/packages/index.html#charts-and-diagrams): Chart types, styling, legends, hover readouts, and `diagram` examples.
lib/NanoUI/Diagrams.hs view
@@ -1,8 +1,20 @@--- | The whole nano-ui-diagrams API: the diagrams-lib backend, the diagram--- widgets, and "NanoUI.Plot".+-- |+-- Module      : NanoUI.Diagrams+-- Description : Charts and diagrams-lib rendering for nano-ui+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- Full @nano-ui-diagrams@ API: the @diagrams-lib@ backend, diagram widgets,+-- and "NanoUI.Plot" charting widgets. module NanoUI.Diagrams-  ( module NanoUI.Diagrams.Backend+  ( -- * Diagrams backend+    module NanoUI.Diagrams.Backend++    -- * Diagram widgets   , module NanoUI.Diagrams.Widget++    -- * Charts   , module NanoUI.Plot   ) where 
lib/NanoUI/Diagrams/Backend.hs view
@@ -9,17 +9,18 @@   ) where +import Control.Applicative ((<|>)) import Control.Lens (Lens', (^.), (^?))-import Data.Colour (AlphaColour, alphaChannel, black, over)-import Data.Colour.SRGB (RGB (..), toSRGB)+import Data.Colour (AlphaColour) import Data.DList (DList) import Data.DList qualified as DL import Data.Maybe (fromMaybe) import Data.Text qualified as T import Data.Tree (Tree (Node)) import Data.Typeable (Typeable)+import Data.Primitive.PrimArray (primArrayToList) import Data.Primitive.SmallArray (SmallArray, emptySmallArray, mapSmallArray', smallArrayFromList)-import Diagrams.Attributes (_lineWidthU)+import Diagrams.Attributes (Dashing (..), LineCap (..), LineJoin (..), colorToSRGBA, _dashingU, _fillOpacity, _lineCap, _lineJoin, _lineMiterLimit, _lineWidthU, _opacity, _strokeOpacity) import Diagrams.Core   ( Backend (..)   , N@@ -39,7 +40,6 @@   , Trail   , V2 (..)   , origin-  , p2   , papply   , reflectY   , reflectionY@@ -51,26 +51,25 @@ import Diagrams.Trail (fixTrail, isLoop) import Diagrams.TwoD.Adjust (adjustDia2D) import Diagrams.TwoD.Attributes (_AC, _fillTexture, _lineTexture)+import Diagrams.TwoD.Path (FillRule (..), _fillRule) import Diagrams.TwoD.Size (mkHeight) import Diagrams.TwoD.Text (Text (..), TextAlignment (..)) import NanoUI   ( Color-  , DrawOp (..)+  , Rect (..)   , colorA   , colorRGBA   , defaultTheme-  , shiftDrawOp   , themeMuted   )-import NanoUI.Diagrams.Tessellation-  ( fillPolygon-  , flattenCubic-  , strokePolyline-  )+import NanoUI.Widgets.Custom (DrawOp (..), shiftDrawOp)+import NanoUI.Internal.Path qualified as P +-- | Diagrams backend that emits nano-ui draw operations for paths and text. data NanoUIBackend = NanoUIBackend   deriving (Eq, Show) +-- | Short backend name for @Diagram B@ type signatures. type B = NanoUIBackend  type instance V NanoUIBackend = V2@@ -83,6 +82,7 @@ instance (Typeable n, RealFloat n) => Backend NanoUIBackend V2 n where   newtype Render NanoUIBackend V2 n     = NRenderFull (Bool -> DiaCore.Style V2 n -> DList DrawOp)+    deriving (Semigroup, Monoid)   type Result NanoUIBackend V2 n = SmallArray DrawOp   data Options NanoUIBackend V2 n = NanoUIOptions (SizeSpec V2 n) Bool   renderRTree _ (NanoUIOptions _ textOnly) rt = smallArrayFromList (DL.toList (walkFull textOnly mempty rt))@@ -90,12 +90,6 @@    where     (sz, t, d') = adjustDia2D fullSize c opts (d # reflectY) -instance Semigroup (Render NanoUIBackend V2 n) where-  NRenderFull f <> NRenderFull g = NRenderFull (\textOnly sty -> f textOnly sty <> g textOnly sty)--instance Monoid (Render NanoUIBackend V2 n) where-  mempty = NRenderFull (\_ _ -> DL.empty)- walkFull ::   (Typeable n, RealFloat n) =>   Bool@@ -116,7 +110,7 @@   render _ path = NRenderFull $ \textOnly sty ->     if textOnly       then DL.empty-      else foldMap (DL.fromList . trailOps sty) (pathTrails path)+      else DL.fromList (pathOps sty (pathTrails path))  textOps ::   (Typeable n, RealFloat n) => Text n -> DiaCore.Style V2 n -> DList DrawOp@@ -130,81 +124,106 @@           case align of             BaselineText -> (0, -1)             BoxAlignedText bx by -> (toF bx, toF by)-        col =-          case solidColour (sty ^? (_fillTexture . _AC)) of-            Just c -> c-            Nothing ->-              fromMaybe-                (themeMuted defaultTheme)-                (solidColour (sty ^? (_lineTexture . _AC)))+        col = fromMaybe (themeMuted defaultTheme) (fillColour sty <|> lineColour sty)        in         DL.singleton (DrawText (toF x) (toF y) ax ay (T.pack str) col)  instance (Typeable n, RealFloat n) => Renderable (Text n) NanoUIBackend where   render _ t = NRenderFull (const (textOps t)) -trailOps ::+-- | A path's ops: all loops filled together under the style's fill rule (so+-- an inner loop can be a hole), then every trail stroked with the style's+-- caps, joins and dashes.+pathOps ::   (Typeable n, RealFloat n) =>-  DiaCore.Style V2 n -> Located (Trail V2 n) -> [DrawOp]-trailOps sty lt =-  let-    pts = [(toF x, toF y) | (x, y) <- map unp2 (trailSamples lt)]-    lineW0 = sty ^. _lineWidthU-    lineW =-      case fmap toF lineW0 of-        Nothing -> 1-        Just w-          | w <= 0 -> 0-          | w < 1 -> 1-          | otherwise -> w-    fillC = solidColour (sty ^? (_fillTexture . _AC))-    lineC = solidColour (sty ^? (_lineTexture . _AC))-    closed = isLoop (unLoc lt)-    fills =-      case fillC of-        Just c-          | colorA c > 0 && closed && length pts >= 3 -> fillPolygon c pts-        _ -> []-    strokes =-      case lineC of-        Just c-          | colorA c > 0 && lineW > 0 && length pts >= 2 ->-              strokePolyline c lineW closed pts-        _ -> []-   in-    fills ++ strokes+  DiaCore.Style V2 n -> [Located (Trail V2 n)] -> [DrawOp]+pathOps sty trails = fills ++ strokes+  where+    trailOf lt = let closed = isLoop (unLoc lt) in (closed, trailPath closed (fixTrail lt))+    paths = map trailOf trails+    loops = mconcat [path | (True, path) <- paths]+    lineW = case toF <$> sty ^. _lineWidthU of+      Nothing -> 1+      Just w+        | w <= 0 -> 0+        | otherwise -> max 1 w+    rule = case sty ^. _fillRule of+      Winding -> P.NonZero+      EvenOdd -> P.EvenOdd+    lineStroke =+      (P.stroke lineW)+        { P.strokeCap = case sty ^. _lineCap of+            LineCapButt -> P.ButtCap+            LineCapRound -> P.RoundCap+            LineCapSquare -> P.SquareCap+        , P.strokeJoin = case sty ^. _lineJoin of+            LineJoinMiter -> P.MiterJoin+            LineJoinRound -> P.RoundJoin+            LineJoinBevel -> P.BevelJoin+        , P.strokeMiterLimit = toF (sty ^. _lineMiterLimit)+        , P.strokeDash = maybe [] (\(Dashing ds _) -> map toF ds) (sty ^. _dashingU)+        , P.strokeDashOffset = maybe 0 (\(Dashing _ o) -> toF o) (sty ^. _dashingU)+        }+    fills = case fillColour sty of+      Just c | colorA c > 0 && any fst paths -> map rectOp (P.fillPathOps curveTol mempty rule loops (P.Solid c))+      _ -> []+    strokes = case lineColour sty of+      Just c | colorA c > 0 && lineW > 0 -> P.strokePathOps curveTol mempty lineStroke (mconcat (map snd paths)) (P.Solid c)+      _ -> [] -trailSamples :: RealFloat n => Located (Trail V2 n) -> [P2 n]-trailSamples lt =-  case map sampleSeg (fixTrail lt) of-    [] -> []-    (firstSeg : rest) ->-      let-        pts = firstSeg ++ concatMap (drop 1) rest-       in-        if isLoop (unLoc lt) && not (null pts)-          then pts ++ take 1 pts-          else pts+-- | Maximum distance of a flattened curve from the true one, in logical pixels.+curveTol :: Float+curveTol = 0.5 -sampleSeg :: RealFloat n => FixedSegment V2 n -> [P2 n]-sampleSeg (FLinear p0 p1) = [p0, p1]-sampleSeg (FCubic p0 c1 c2 p1) =-  [ p2 (realToFrac x, realToFrac y)-  | (x, y) <- flattenCubic (f p0) (f c1) (f c2) (f p1)-  ]- where-  f p = let (x, y) = unp2 p in (toF x, toF y)+-- | A trail as a canvas path, closed when it is a loop.+trailPath :: Real n => Bool -> [FixedSegment V2 n] -> P.Path+trailPath _ [] = mempty+trailPath closed segs@(s0 : _) = P.Path (start s0 : map seg segs ++ [P.SegClose | closed])+  where+    start (FLinear p _) = at P.SegMove p+    start (FCubic p _ _ _) = at P.SegMove p+    seg (FLinear _ p) = at P.SegLine p+    seg (FCubic _ c1 c2 p) =+      let (ax, ay) = pointFloats c1+          (bx, by) = pointFloats c2+       in at (P.SegCubic ax ay bx by) p+    at f p = uncurry f (pointFloats p) -solidColour :: Maybe (AlphaColour Double) -> Maybe Color-solidColour mc = do+-- | Turn a flat-filled axis-aligned rectangle (a chart bar) into a rect op,+-- which avoids the seams a polygon's triangles can show.+rectOp :: DrawOp -> DrawOp+rectOp op@(FillPolygon pts _ _ (P.Flat col)) = case primArrayToList pts of+  [x0, y0, x1, y1, x2, y2, x3, y3]+    | level x0 y0 x1 y1 x2 y2 x3 y3 || level y0 x0 y1 x1 y2 x2 y3 x3 ->+        FillRect (Rect (min x0 x2) (min y0 y2) (abs (x2 - x0)) (abs (y2 - y0))) col+  _ -> op+  where+    -- Edges alternate between the two axes.+    level ax ay bx by cx cy dx dy = near ay by && near bx cx && near cy dy && near dx ax+    near a b = abs (a - b) <= 1e-3+rectOp op = op++pointFloats :: Real n => P2 n -> (Float, Float)+pointFloats p = let (x, y) = unp2 p in (toF x, toF y)++-- | A style's solid fill and line colours, if they are visible, with the+-- style's opacity and its fill or stroke opacity applied.+fillColour, lineColour :: (Typeable n, Floating n) => DiaCore.Style V2 n -> Maybe Color+fillColour sty = solidColour (sty ^. _opacity * sty ^. _fillOpacity) (sty ^? (_fillTexture . _AC))+lineColour sty = solidColour (sty ^. _opacity * sty ^. _strokeOpacity) (sty ^? (_lineTexture . _AC))++-- | A straight-alpha colour: diagrams' channels without its alpha+-- premultiplied, which the renderer would apply a second time.+solidColour :: Double -> Maybe (AlphaColour Double) -> Maybe Color+solidColour opacity mc = do   ac <- mc   let-    a = alphaChannel ac+    (r, g, b, a0) = colorToSRGBA ac+    a = a0 * opacity   if a <= 0     then Nothing     else       let-        RGB r g b = toSRGB (ac `over` black)         q x = round (clamp01 x * 255)        in         Just (colorRGBA (q r) (q g) (q b) (q a))@@ -215,10 +234,14 @@ toF :: Real n => n -> Float toF = realToFrac +-- | Render into a logical-pixel viewport of the given width and height,+-- preserving aspect ratio and centring the result. Non-positive sizes return no ops. diagramOps ::   Double -> Double -> QDiagram NanoUIBackend V2 Double Any -> SmallArray DrawOp diagramOps = renderFull False +-- | Text-only form of 'diagramOps', using the same viewport transform.+-- Used to measure labels before building all geometry. diagramTextOps ::   Double -> Double -> QDiagram NanoUIBackend V2 Double Any -> SmallArray DrawOp -- Text uses the same backend and viewport as geometry. In particular, do not
− lib/NanoUI/Diagrams/Tessellation.hs
@@ -1,250 +0,0 @@--- | Polygon triangulation and filling, polyline stroking, and cubic Bezier--- flattening for the diagrams backend.-module NanoUI.Diagrams.Tessellation-  ( triangulatePolygon-  , fillPolygon-  , strokePolyline-  , flattenCubic-  ) where--import Control.Monad (forM_)-import Control.Monad.ST (runST)-import Data.Primitive.PrimArray-  ( PrimArray-  , indexPrimArray-  , newPrimArray-  , readPrimArray-  , runPrimArray-  , sizeofPrimArray-  , writePrimArray-  )-import NanoUI (Color, DrawOp (..), Rect (..))--bezierTolerance :: Float-bezierTolerance = 0.5--triangulatePolygon :: [(Float, Float)] -> [((Float, Float), (Float, Float), (Float, Float))]-triangulatePolygon [] = []-triangulatePolygon [_] = []-triangulatePolygon pts0 =-  let pts = stripClosed pts0-    in earClip (pointsArray pts)--stripClosed :: [(Float, Float)] -> [(Float, Float)]-stripClosed [] = []-stripClosed [p] = [p]-stripClosed (p : rest)-  | p == last rest = p : init rest-  | otherwise = p : rest---- | Points stored as x then y.-pointsArray :: [(Float, Float)] -> PrimArray Float-pointsArray pts = runPrimArray $ do-  out <- newPrimArray (2 * length pts)-  let fill !_ [] = pure out-      fill !i ((x, y) : rest) = do-        writePrimArray out (2 * i) x-        writePrimArray out (2 * i + 1) y-        fill (i + 1) rest-  fill 0 pts--{-# INLINE pointAt #-}-pointAt :: PrimArray Float -> Int -> (Float, Float)-pointAt vs i = (indexPrimArray vs (2 * i), indexPrimArray vs (2 * i + 1))--signedArea :: PrimArray Float -> Float-signedArea vs =-  let n = sizeofPrimArray vs `div` 2-   in foldl' (\acc i -> acc + cross (pointAt vs i) (pointAt vs ((i + 1) `mod` n)) / 2) 0 [0 .. n - 1]--cross :: (Float, Float) -> (Float, Float) -> Float-cross (x0, y0) (x1, y1) = x0 * y1 - x1 * y0--diff :: (Float, Float) -> (Float, Float) -> (Float, Float)-diff (x0, y0) (x1, y1) = (x1 - x0, y1 - y0)--isConvex :: Bool -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool-isConvex ccw a b c =-  let ab = diff a b-      bc = diff b c-   in if ccw then cross ab bc >= 0 else cross ab bc <= 0--pointInTri :: (Float, Float) -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool-pointInTri p a b c =-  let sign (p1, p2, p3) = cross (diff p1 p3) (diff p2 p3)-      d1 = sign (p, a, b)-      d2 = sign (p, b, c)-      d3 = sign (p, c, a)-   in not ((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))--earClip :: PrimArray Float -> [((Float, Float), (Float, Float), (Float, Float))]-earClip vs-  | n < 3 = []-  | n == 3 = [(at 0, at 1, at 2)]-  | otherwise = runST $ do-      let !ccw = signedArea vs >= 0-      -- Coordinates never move. Remove an ear by relinking two neighbours,-      -- instead of copying the remaining coordinates at every step.-      prevs <- newPrimArray n-      nexts <- newPrimArray n-      forM_ [0 .. n - 1] $ \i -> do-        writePrimArray prevs i ((i - 1 + n) `mod` n)-        writePrimArray nexts i ((i + 1) `mod` n)-      let triangle i = do-            p <- readPrimArray prevs i-            q <- readPrimArray nexts i-            pure (p, q, (at p, at i, at q))-          isEarAt first count i p q (a, b, c)-            | not (isConvex ccw a b c) = pure False-            | otherwise = outside first count-            where-              outside !_ 0 = pure True-              outside !j !left-                | j /= p && j /= i && j /= q && pointInTri (at j) a b c = pure False-                | otherwise = do-                    next <- readPrimArray nexts j-                    outside next (left - 1)-          convex !_ 0 = pure True-          convex !i !left = do-            (_, q, (a, b, c)) <- triangle i-            if isConvex ccw a b c then convex q (left - 1) else pure False-          fan origin i left-            | left <= 0 = pure []-            | otherwise = do-                q <- readPrimArray nexts i-                rest <- fan origin q (left - 1)-                pure ((at origin, at i, at q) : rest)-          go !first !count !idx !tries tris-            | count == 3 = do-                second <- readPrimArray nexts first-                third <- readPrimArray nexts second-                pure ((at first, at second, at third) : tris)-            | tries >= count = do-                isConvexRing <- convex first count-                if isConvexRing then do-                  second <- readPrimArray nexts first-                  rest <- fan first second (count - 2)-                  pure (tris ++ rest)-                else pure tris-            | otherwise = do-                (p, q, tri) <- triangle idx-                ear <- isEarAt first count idx p q tri-                if ear then do-                  writePrimArray nexts p q-                  writePrimArray prevs q p-                  let !first' = if idx == first then q else first-                  go first' (count - 1) first' 0 (tri : tris)-                else go first count q (tries + 1) tris-      reverse <$> go 0 n 0 0 []-  where-    n = sizeofPrimArray vs `div` 2-    at = pointAt vs--fillPolygon :: Color -> [(Float, Float)] -> [DrawOp]-fillPolygon col pts =-  case axisAlignedRect pts of-    Just r -> [FillRect r col]-    Nothing ->-      [ FillTriangle x0 y0 x1 y1 x2 y2 col-      | ((x0, y0), (x1, y1), (x2, y2)) <- triangulatePolygon pts-      ]--axisAlignedRect :: [(Float, Float)] -> Maybe Rect-axisAlignedRect pts =-  case stripClosed pts of-    [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]-      | near y0 y1 && near x1 x2 && near y2 y3 && near x3 x0 ->-          Just (Rect (min x0 x3) (min y0 y2) (abs (x1 - x0)) (abs (y2 - y0)))-    [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]-      | near x0 x1 && near y1 y2 && near x2 x3 && near y3 y0 ->-          Just (Rect (min x0 x2) (min y0 y1) (abs (x2 - x0)) (abs (y1 - y0)))-    _ -> Nothing-  where-    near a b = abs (a - b) <= 1e-3---strokePolyline :: Color -> Float -> Bool -> [(Float, Float)] -> [DrawOp]-strokePolyline _ _ _ [] = []-strokePolyline _ _ _ [_] = []-strokePolyline col w closed pts0 =-  let pts = if closed && length pts0 > 2 then stripClosed pts0 else pts0-      hw = w / 2-      !vPts = pointsArray pts-      !n = sizeofPrimArray vPts `div` 2-   in if n < 2-        then []-        else-          let !segCount = if closed then n else n - 1-              -- Each segment's unit normal, x then y.-              !segNormals = runPrimArray $ do-                out <- newPrimArray (2 * segCount)-                forM_ [0 .. segCount - 1] $ \i -> do-                  let !(p0x, p0y) = pointAt vPts i-                      !(p1x, p1y) = pointAt vPts ((i + 1) `mod` n)-                      nx = p0y - p1y-                      ny = p1x - p0x-                      d = sqrt (nx * nx + ny * ny)-                  writePrimArray out (2 * i) (if d <= 1e-9 then 0 else nx / d)-                  writePrimArray out (2 * i + 1) (if d <= 1e-9 then 0 else ny / d)-                pure out-              joinNormal !i-                | not closed && i <= 0 = pointAt segNormals 0-                | not closed && i >= n - 1 = pointAt segNormals (segCount - 1)-                | otherwise =-                    let (ax, ay) = pointAt segNormals ((i - 1 + segCount) `mod` segCount)-                        (bx, by) = pointAt segNormals (i `mod` segCount)-                        sx = ax + bx-                        sy = ay + by-                        d = sqrt (sx * sx + sy * sy)-                     in if d <= 1e-9 then (0, 0) else (sx / d, sy / d)-              -- Adjacent quads share a vertex, so offset each vertex once: the-              -- two sides' points, four numbers a vertex.-              !offsets = runPrimArray $ do-                out <- newPrimArray (4 * n)-                forM_ [0 .. n - 1] $ \i -> do-                  let (!px, !py) = pointAt vPts i-                      (!nx, !ny) = joinNormal i-                  writePrimArray out (4 * i) (px + hw * nx)-                  writePrimArray out (4 * i + 1) (py + hw * ny)-                  writePrimArray out (4 * i + 2) (px - hw * nx)-                  writePrimArray out (4 * i + 3) (py - hw * ny)-                pure out-              offset i k = indexPrimArray offsets (4 * i + k)-              buildQuads !i-                | i >= segCount = []-                | otherwise =-                    let !j = if closed then (i + 1) `mod` n else i + 1-                     in FillTriangle (offset i 0) (offset i 1) (offset j 0) (offset j 1) (offset j 2) (offset j 3) col-                          : FillTriangle (offset i 0) (offset i 1) (offset j 2) (offset j 3) (offset i 2) (offset i 3) col-                          : buildQuads (i + 1)-           in buildQuads 0--flattenCubic ::-  (Float, Float) ->-  (Float, Float) ->-  (Float, Float) ->-  (Float, Float) ->-  [(Float, Float)]-flattenCubic p0 c1 c2 p1 = go p0 c1 c2 p1-  where-    go a b c d =-      let mid (p, q) = ((fst p + fst q) / 2, (snd p + snd q) / 2)-          ab = mid (a, b)-          bc = mid (b, c)-          cd = mid (c, d)-          abbc = mid (ab, bc)-          bccd = mid (bc, cd)-          mid12 = mid (abbc, bccd)-          flat =-            let (dx, dy) = diff d a-                len = sqrt (dx * dx + dy * dy)-                dist =-                  if len <= 1e-9-                    then 0-                    else abs (cross (diff b a) (dx, dy)) / len-             in dist <= bezierTolerance-       in if flat-            then [a, d]-            else-              let rest = go mid12 bccd cd d-               in go a ab abbc mid12 ++ drop 1 rest
lib/NanoUI/Diagrams/Widget.hs view
@@ -24,28 +24,20 @@ import Data.Primitive.SmallArray (SmallArray, emptySmallArray, indexSmallArray, mapSmallArray', sizeofSmallArray, smallArrayFromList) import Diagrams.Core (QDiagram) import Diagrams.Prelude (Any, Diagram, V2 (..), size)-import Effectful (Eff, type (:>)) import NanoUI-  ( Color-  , DrawOp (..)-  , FontMetrics (..)-  , Layout (..)+  ( NanoUI+  , Color   , Rect (..)   , Response   , Sizing (..)   , Style (..)   , Theme (..)-  , Ui   , colorB   , colorG   , colorR-  , colorToWord32   , defaultLayout   , defaultTheme-  , drawTextBox-  , drawingCached   , lerpColor-  , shiftDrawOp   , styleBg   , styleBorder   , themeAccent@@ -57,12 +49,13 @@   , themeSeparator   , themeWindow   , themeYellow-  , uiFontMetrics-  , prepareFontMetricsMany   , uiTheme   )-import NanoUI.Context (lookupDrawFitEnvelope)-import NanoUI.Monad (askContext, currentId, uiIO)+import NanoUI.Backend (FontMetrics (..), Layout (..), colorToWord32, drawTextBox, prepareFontMetricsMany, uiFontMetrics)+import NanoUI.Widgets.Custom (DrawOp (..), drawingCached, shiftDrawOp)+import NanoUI.Internal.Context (lookupDrawFitEnvelope)+import NanoUI.Internal.Monad (askContext)+import NanoUI.Monad (currentId, liftIO) import NanoUI.Diagrams.Backend   ( B   , NanoUIBackend@@ -70,6 +63,7 @@   , diagramTextOps   ) +-- | Colours for diagram content, grid, muted labels, and the enclosing frame. data PlotStyle = PlotStyle   { plotInk :: Colour Double   , plotFill :: Colour Double@@ -80,9 +74,11 @@   }   deriving (Eq, Show) +-- | Convert RGB channels to a diagrams colour, discarding alpha. colourOf :: Color -> Colour Double colourOf c = sRGB24 (colorR c) (colorG c) (colorB c) +-- | Derive plot colours from a nano-ui theme's accents and surfaces. themePlotStyle :: Theme -> PlotStyle themePlotStyle t =   let muted = themeMuted t@@ -96,9 +92,11 @@         , plotFrameBorder = styleBorder panel         } +-- | Plot colours derived from 'defaultTheme'. defaultPlotStyle :: PlotStyle defaultPlotStyle = themePlotStyle defaultTheme +-- | Cache key for theme colours used by chart content and frames. themePlotKey :: Theme -> Int themePlotKey t =   hash (colorToWord32 (themeAccent t))@@ -114,9 +112,12 @@     `hashWithSalt` colorToWord32 (styleBorder (themePanel t))     `hashWithSalt` colorToWord32 (styleBg (themeInput t)) -uiPlotStyle :: Ui :> es => Eff es PlotStyle+-- | Plot colours from the current view's scoped theme.+uiPlotStyle :: NanoUI PlotStyle uiPlotStyle = fmap themePlotStyle uiTheme +-- | Estimate a scale from 1 to 2 that separates overlapping plain-text labels.+-- The cap means this is a sizing heuristic, not a guarantee against overlap. labelFitScale :: FontMetrics -> SmallArray DrawOp -> Double labelFitScale fm ops =   let -- Six numbers a label: its anchor, and its box's origin and size.@@ -171,6 +172,8 @@           !need = loO + loS + 2 - hiO        in if den <= 1e-6 then 1.0 else max 1.0 (need / den) +-- | Background and four border strokes for a logical-pixel rectangle.+-- The second argument is border width in logical pixels. diagramFrame :: PlotStyle -> Float -> Rect -> SmallArray DrawOp diagramFrame ps bw (Rect x y w h) =   smallArrayFromList@@ -181,14 +184,20 @@     , Stroke x (y + h) x y bw (plotFrameBorder ps)     ] --- Grow plots cap here unless the caller set a tighter layoutMaxH.+-- Grow plots cap here unless the caller set a tighter layoutMaxH, a fixed+-- height, or a larger minimum. growPlotCapH :: Float growPlotCapH = 260 +-- | Choose diagram dimensions from its aspect ratio and measured labels.+-- Growing widths retain flexibility and keep a fixed height; any other+-- height is at most 260 unless the layout sets a larger minimum or grows in+-- height. Other widths become fixed. Prepare font metrics for all labels before calling+-- this pure sizing operation. fitLayout :: FontMetrics -> Layout -> Diagram B -> Layout fitLayout fm layout d =   let V2 dw dh = size d-      ar = if dh <= 1e-9 then 1 else dw / dh+      ar = if dh <= 1e-9 || dw <= 1e-9 then 1 else dw / dh       growW =         case layoutWidth layout of           Grow _ -> True@@ -199,6 +208,7 @@             | dw > 1e-9 && dh > 1e-9 ->                 let s = min (realToFrac bw / dw) (realToFrac bh / dh)                  in (dw * s, dh * s)+            | otherwise -> (realToFrac bw, realToFrac bh)           (_, Fixed bh) ->             let h = realToFrac bh :: Double              in (h * ar, h)@@ -214,12 +224,19 @@       clampSize x = realToFrac (max 8 x) :: Float    in if growW         then-          let capH = min growPlotCapH (layoutMaxH layout)-              floorH = if layoutMinH layout > 0 then layoutMinH layout else 180+          let -- The caller's fixed height, which is also the cap, or its+              -- minimum, which may raise the cap; a growing height keeps+              -- growing above the measured minimum.+              (callerH, cap, growH) = case layoutHeight layout of+                Fixed h -> (h, h, False)+                Grow _ -> (layoutMinH layout, growPlotCapH, True)+                _ -> (layoutMinH layout, growPlotCapH, False)+              capH = min (max cap callerH) (layoutMaxH layout)+              floorH = if callerH > 0 then callerH else 180               probeH0 =                 realToFrac-                  ( if layoutMinH layout > 0-                      then layoutMinH layout+                  ( if callerH > 0+                      then callerH                       else 200                   ) ::                   Double@@ -229,10 +246,10 @@               needW = clampSize (probeW * k)               needH = min capH (max floorH (clampSize (probeH * k)))            in layout-                { layoutHeight = Fit+                { layoutHeight = if growH then layoutHeight layout else Fit                 , layoutMinW = max (layoutMinW layout) needW                 , layoutMinH = needH-                , layoutMaxH = max needH capH+                , layoutMaxH = if growH then layoutMaxH layout else max needH capH                 }         else           let k = labelFitScale fm (diagramTextOps baseW baseH d)@@ -250,41 +267,43 @@ -- | 'diagramWithEnvelope' whose cached draw ops are also keyed by @userKey@. -- Change the key when the diagram's content changes. diagramWithKeyAndEnvelope ::-  Ui :> es =>   Int ->   Double ->   Double ->   (Layout -> Layout) ->   QDiagram NanoUIBackend V2 Double Any ->-  Eff es Response+  NanoUI Response diagramWithKeyAndEnvelope userKey dw dh f =   framedDiagram (\t -> hash (userKey, themePlotKey t)) dw dh (f defaultLayout) --- | 'diagram' with an explicit envelope width and height.+-- | 'diagram' with an explicit envelope width and height. The drawing is+-- cached per theme and redrawn when the envelope or the widget's size+-- changes, not when other content does: for a diagram that changes, use+-- 'diagramWithKeyAndEnvelope'. diagramWithEnvelope ::-  Ui :> es =>   Double ->   Double ->   (Layout -> Layout) ->   QDiagram NanoUIBackend V2 Double Any ->-  Eff es Response+  NanoUI Response diagramWithEnvelope dw dh f = framedDiagram themePlotKey dw dh (f defaultLayout)  -- | Draw a diagram inside the plot frame. Its draw ops are cached under the -- content key the caller derives from the current theme. framedDiagram ::-  Ui :> es =>   (Theme -> Int) ->   Double ->   Double ->   Layout ->   QDiagram NanoUIBackend V2 Double Any ->-  Eff es Response+  NanoUI Response framedDiagram contentKey dw dh layout d = do   fm <- uiFontMetrics   theme <- uiTheme   let ps = themePlotStyle theme-  drawingCached dw dh (fmLineHeight fm) (contentKey theme) (const layout) (fitLayoutIO fm layout d) $ \rectBox ->+      texts = foldMap (\case DrawText _ _ _ _ t _ -> [t]; _ -> []) (diagramTextOps 100 100 d)+      fit = (\prepared -> fitLayout prepared layout d) <$> prepareFontMetricsMany fm texts+  drawingCached dw dh (fmLineHeight fm) (contentKey theme) (const layout) fit $ \rectBox ->     let inner = frameInner rectBox         w = realToFrac (rectW inner) :: Double         h = realToFrac (rectH inner)@@ -302,26 +321,19 @@ frameInner (Rect x y w h) =   Rect (x + frameBorder) (y + frameBorder) (max 0 (w - 2 * frameBorder)) (max 0 (h - 2 * frameBorder)) -fitLayoutIO :: FontMetrics -> Layout -> Diagram B -> IO Layout-fitLayoutIO fm layout d = do-  let texts = foldr (\op rest -> case op of-        DrawText _ _ _ _ t _ -> t : rest-        _ -> rest) [] (diagramTextOps 100 100 d)-  prepared <- prepareFontMetricsMany fm texts-  pure (fitLayout prepared layout d)- -- | Draw a diagram inside a framed box sized by the layout modifier. Text in--- the diagram is measured with the current font so labels fit.-diagram :: Ui :> es => (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> Eff es Response+-- the diagram is measured with the current font so labels fit. The drawing+-- and its envelope are cached, and redrawn when the theme, the font's line+-- height, the layout or the widget's size changes, not when the diagram+-- does: for a diagram that changes, such as a gauge's needle, use+-- 'diagramWithKeyAndEnvelope' with a key that changes with it.+diagram :: (Layout -> Layout) -> QDiagram NanoUIBackend V2 Double Any -> NanoUI Response diagram f d = do   ctx <- askContext   wid <- currentId   fm <- uiFontMetrics   theme <- uiTheme-  let content = themePlotKey theme-  mEnv <- uiIO (lookupDrawFitEnvelope ctx wid (fmLineHeight fm) content (f defaultLayout))+  mEnv <- liftIO (lookupDrawFitEnvelope ctx wid (fmLineHeight fm) (themePlotKey theme) (f defaultLayout))   case mEnv of     Just (dw, dh) -> diagramWithEnvelope dw dh f d-    Nothing ->-      let V2 dw dh = size d-       in diagramWithEnvelope dw dh f d+    Nothing -> let V2 dw dh = size d in diagramWithEnvelope dw dh f d
lib/NanoUI/Plot.hs view
@@ -1,17 +1,37 @@--- | Charting and plotting API for nano-ui.+-- |+-- Module      : NanoUI.Plot+-- Description : Interactive charts and plotting widgets for nano-ui+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- Charting and plotting API for nano-ui: line, scatter, bar, area, and step+-- series, automatic tick scaling, LTTB point decimation, hover inspection,+-- and cached chart widgets. module NanoUI.Plot-  ( module NanoUI.Plot.Types+  ( -- * Chart builders+    module NanoUI.Plot.Builder++    -- * Chart widgets+  , module NanoUI.Plot.Widget++    -- * Series constructors   , module NanoUI.Plot.Series++    -- * Core types+  , module NanoUI.Plot.Types++    -- * Domains and scales   , module NanoUI.Plot.Scale++    -- * Decimation   , module NanoUI.Plot.Decimate++    -- * Axes and chrome   , module NanoUI.Plot.Chrome-  , module NanoUI.Plot.Widget-  , module NanoUI.Plot.Builder-  , module NanoUI.Plot.Hit   ) where  import NanoUI.Plot.Builder-import NanoUI.Plot.Hit import NanoUI.Plot.Chrome import NanoUI.Plot.Decimate import NanoUI.Plot.Scale
lib/NanoUI/Plot/Builder.hs view
@@ -20,26 +20,35 @@   , emptyChart   ) +-- | A chart with the supplied series and 'emptyChart' defaults. chart :: [Series] -> Chart chart series = emptyChart {chartSeries = series} +-- | Set the title above the chart. withTitle :: Text -> Chart -> Chart withTitle t c = c {chartTitle = Just t} +-- | Set the horizontal axis title; does not change its data domain. withXAxis :: Text -> Chart -> Chart withXAxis t c = c {chartXTitle = Just t} +-- | Set the vertical axis title; does not change its data domain. withYAxis :: Text -> Chart -> Chart withYAxis t c = c {chartYTitle = Just t} +-- | Choose the legend position or hide it. withLegend :: LegendPos -> Chart -> Chart withLegend p c = c {chartLegend = p} +-- | Choose which grid directions to draw. withGrid :: GridMode -> Chart -> Chart withGrid g c = c {chartGrid = g} +-- | Enable or disable thinning numeric series before drawing and hit testing.+-- Scatter series and lines with markers are thinned only past 2000 points. withDecimate :: Bool -> Chart -> Chart withDecimate b c = c {chartDecimate = b} +-- | Append a series, preserving the existing series and legend order. addSeries :: Series -> Chart -> Chart addSeries s c = c {chartSeries = chartSeries c ++ [s]}
lib/NanoUI/Plot/Chrome.hs view
@@ -2,13 +2,16 @@ -- a diagram. module NanoUI.Plot.Chrome   ( chartDiagram+  , chartDiagramWithTicks   , chartMargins+  , chartTicks   , Margins (..)   , seriesDomains   , seriesPoints   ) where  import Data.Colour (Colour)+import Data.Foldable (toList) import Data.Maybe (fromMaybe) import Data.Text qualified as T import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)@@ -26,36 +29,35 @@   , lc   , lw   , lwO+  , mapLoc   , moveTo   , none   , p2   , phantom   , rect-  , strokeTrail+  , strokeLocTrail   , translate   , (^&)   , ( # )   ) import NanoUI   ( Color-  , FontMetrics (..)   , Rect (..)   , Theme (..)-  , drawTextBox-  , fmLineHeight   , lerpColor   , themeSeries   )+import NanoUI.Backend (FontMetrics (..), drawTextBox, fmLineHeight) import NanoUI.Diagrams.Backend (B) import NanoUI.Diagrams.Widget (PlotStyle (..), colourOf) import NanoUI.Plot.Decimate (lttb) import NanoUI.Plot.Scale-  ( domainExtentBy+  ( domainBoundsBy   , domainToPlot-  , formatTick   , mergeDomains-  , niceTicks+  , niceTickLabels   , padDomain+  , settleDomain   ) import NanoUI.Plot.Types   ( Chart (..)@@ -82,6 +84,7 @@ plotGapRef :: FontMetrics -> Double plotGapRef fm = max 120 (realToFrac (fmLineHeight fm) * 7.5) +-- | Space around the unit data box, in plot coordinates rather than pixels. data Margins = Margins   { marginLeft :: !Double   , marginRight :: !Double@@ -98,21 +101,25 @@   , ccYTitleX :: !Double   , ccXTitleY :: !Double   , ccLegendW :: !Float+  , ccTopLegend :: !Double   } +-- | Space needed for titles, ticks, and legend with the supplied font metrics.+-- Prepare those metrics for the chart's text before measuring. chartMargins :: FontMetrics -> Chart -> Margins chartMargins fm chart = ccMargins (chartChrome fm (snd (seriesDomains chart)) chart)  -- | Chrome for a chart whose y domain the caller has already computed. chartChrome :: FontMetrics -> Domain -> Chart -> ChartChrome-chartChrome fm yDom chart =-  let yLabels = map formatTick (niceTicks 6 yDom)+chartChrome fm yDom = chartChromeWith fm (niceTickLabels 6 yDom)++-- | Chrome for a chart whose y ticks the caller has already computed.+chartChromeWith :: FontMetrics -> [(Double, T.Text)] -> Chart -> ChartChrome+chartChromeWith fm yTicks chart =+  let yLabels = map snd yTicks       maxYW = maximum (0 : map (textWidth fm) yLabels)       lh = fmLineHeight fm-      yTitleW =-        case chartYTitle chart of-          Nothing -> 0-          Just t -> textWidth fm t+      yTitleW = maybe 0 (textWidth fm) (chartYTitle chart)       legendW =         case chartLegend chart of           LegendNone -> 0@@ -134,10 +141,16 @@       xTitleY = -xTickPad - tickH - titleGap       leftTick = tickPad + tickW + px 4       botTick = xTickPad + tickH + px 4+      -- A top legend takes a row of its own, under the title.+      topLegend =+        case chartLegend chart of+          LegendTop -> px lh + px 6+          _ -> 0       topM =-        if chartTitle chart /= Nothing-          then px lh + px 8-          else px 4+        topLegend+          + if chartTitle chart /= Nothing+            then px lh + px 8+            else px 4       rightM =         case chartLegend chart of           LegendRight -> px legendW + 0.22@@ -166,45 +179,74 @@         , ccYTitleX = yTitleX         , ccXTitleY = xTitleY         , ccLegendW = legendW+        , ccTopLegend = topLegend         }  textWidth :: FontMetrics -> T.Text -> Float textWidth fm s = rectW (drawTextBox fm 0 0 0 (-1) s) +-- | Combined x/y extents of the series' finite values, with 5% numeric+-- padding. Categories use zero-based positions with half a slot at each+-- end, and their bars' y extent includes zero. An area's y extent includes+-- its baseline, which its fill reaches. An axis with no values spans 0-1+-- before the padding, and one with a single value half a unit each side of+-- it. seriesDomains :: Chart -> (Domain, Domain)-seriesDomains chart =-  case map seriesExtent (chartSeries chart) of-    [] -> (Domain 0 1, Domain 0 1)-    d : ds -> foldl' mergePair d ds+seriesDomains chart = (xDom, fit yBounds)   where-    mergePair (dx, dy) (xd, yd) = (mergeDomains dx xd, mergeDomains dy yd)+    -- Series merge their bounds before the fallbacks and padding, so an+    -- empty or constant one does not widen the others' span.+    fit = padDomain 0.05 . settleDomain+    (xBounds, yBounds, slots) = foldl' add (Domain (1 / 0) (-1 / 0), Domain (1 / 0) (-1 / 0), 0) (chartSeries chart)+    add (!bx, !by, !n) s = case seriesData s of+      PointsXY pts -> (mergeDomains bx (domainBoundsBy fst pts), mergeDomains by (reach s (domainBoundsBy snd pts)), n)+      CategoryY _ values ->+        let k = sizeofPrimArray values+         in (bx, mergeDomains by (mergeDomains (Domain 0 0) (domainBoundsBy (indexPrimArray values) (U.enumFromN 0 k))), max n k)+    -- An area with values reaches its baseline, when that is finite.+    reach s d@(Domain lo hi) = case seriesKind s of+      AreaSeries b | lo <= hi && not (isNaN b || isInfinite b) -> mergeDomains (Domain b b) d+      _ -> d+    slotDom = Domain (-0.5) (fromIntegral slots - 0.5)+    xDom+      | slots == 0 = fit xBounds+      | Domain lo hi <- xBounds, lo > hi = slotDom+      | otherwise = mergeDomains slotDom (fit xBounds) -seriesExtent :: Series -> (Domain, Domain)-seriesExtent s =-  case seriesData s of-    PointsXY pts ->-      (padDomain 0.05 (domainExtentBy fst pts), padDomain 0.05 (domainExtentBy snd pts))-    CategoryY _ values ->-      let n = sizeofPrimArray values-       in (Domain (-0.5) (fromIntegral n - 0.5), padDomain 0.05 (domainExtentBy (indexPrimArray values) (U.enumFromN 0 n)))+-- | Compute X and Y axis tick labels once for a chart and its 'seriesDomains'.+chartTicks :: (Domain, Domain) -> Chart -> ([(Double, T.Text)], [(Double, T.Text)])+chartTicks (xDom, yDom) chart =+  ( case [labels | Series {seriesData = CategoryY labels _} <- chartSeries chart] of+      labels : _ -> zip [0 ..] (toList labels)+      [] -> niceTickLabels 6 xDom+  , niceTickLabels 6 yDom+  )  -- | Draw a chart from its 'seriesDomains' and each series' 'seriesPoints'. chartDiagram :: FontMetrics -> Theme -> PlotStyle -> (Domain, Domain) -> [U.Vector (Double, Double)] -> Chart -> Diagram B-chartDiagram fm theme ps (xDom, yDom) points chart =-  let chrome = chartChrome fm yDom chart-      margins = ccMargins chrome-      leftM = marginLeft margins-      rightM = marginRight margins-      botM = marginBottom margins-      topM = marginTop margins-      xTicks = niceTicks 6 xDom-      yTicks = niceTicks 6 yDom+chartDiagram fm theme ps domains points chart =+  chartDiagramWithTicks fm theme ps domains (chartTicks domains chart) points chart++-- | Draw a chart using precomputed '(xTicks, yTicks)' from 'chartTicks' so+-- callers that also measure tick labels avoid recomputing them.+chartDiagramWithTicks ::+  FontMetrics ->+  Theme ->+  PlotStyle ->+  (Domain, Domain) ->+  ([(Double, T.Text)], [(Double, T.Text)]) ->+  [U.Vector (Double, Double)] ->+  Chart ->+  Diagram B+chartDiagramWithTicks fm theme ps (xDom, yDom) (xTicks, yTicks) points chart =+  let chrome = chartChromeWith fm yTicks chart+      m = ccMargins chrome       tickPad = ccTickPad chrome       xTickPad = ccXTickPad chrome       toX = domainToPlot xDom       toY = domainToPlot yDom-      horizontalGrid = mconcat [fromVertices [p2 (0, toY y), p2 (1, toY y)] | y <- yTicks]-      verticalGrid = mconcat [fromVertices [p2 (toX x, 0), p2 (toX x, 1)] | x <- xTicks]+      horizontalGrid = mconcat [fromVertices [p2 (0, toY y), p2 (1, toY y)] | (y, _) <- yTicks]+      verticalGrid = mconcat [fromVertices [p2 (toX x, 0), p2 (toX x, 1)] | (x, _) <- xTicks]       grid =         case chartGrid chart of           GridNone -> mempty@@ -214,34 +256,21 @@       axes =         fromVertices [p2 (0, 0), p2 (1, 0)]           <> fromVertices [p2 (0, 0), p2 (0, 1)]-          <> mconcat [fromVertices [p2 (toX x, 0), p2 (toX x, 0.03)] | x <- xTicks]-          <> mconcat [fromVertices [p2 (0, toY y), p2 (0.03, toY y)] | y <- yTicks]+          <> mconcat [fromVertices [p2 (toX x, 0), p2 (toX x, 0.03)] | (x, _) <- xTicks]+          <> mconcat [fromVertices [p2 (0, toY y), p2 (0.03, toY y)] | (y, _) <- yTicks]       xLabs =         mconcat-          [ plotLbl ps 0.5 1 (T.unpack (formatTick x)) # moveTo (p2 (toX x, -xTickPad))-          | x <- xTicks+          [ plotLbl ps 0.5 1 (T.unpack t) # moveTo (p2 (toX x, -xTickPad))+          | (x, t) <- xTicks           ]       yLabs =         mconcat-          [ plotLbl ps 1 0.5 (T.unpack (formatTick y)) # moveTo (p2 (-tickPad, toY y))-          | y <- yTicks+          [ plotLbl ps 1 0.5 (T.unpack t) # moveTo (p2 (-tickPad, toY y))+          | (y, t) <- yTicks           ]-      title =-        case chartTitle chart of-          Nothing -> mempty-          Just t -> plotLbl ps 0.5 0 (T.unpack t) # moveTo (p2 (0.5, 1.03))-      xt =-        case chartXTitle chart of-          Nothing -> mempty-          Just t ->-            plotLbl ps 0.5 1 (T.unpack t)-              # moveTo (p2 (0.5, ccXTitleY chrome))-      yt =-        case chartYTitle chart of-          Nothing -> mempty-          Just t ->-            plotLbl ps 1 0.5 (T.unpack t)-              # moveTo (p2 (ccYTitleX chrome, 0.5))+      title = foldMap (\t -> plotLbl ps 0.5 0 (T.unpack t) # moveTo (p2 (0.5, 1.03 + ccTopLegend chrome))) (chartTitle chart)+      xt = foldMap (\t -> plotLbl ps 0.5 1 (T.unpack t) # moveTo (p2 (0.5, ccXTitleY chrome))) (chartXTitle chart)+      yt = foldMap (\t -> plotLbl ps 1 0.5 (T.unpack t) # moveTo (p2 (ccYTitleX chrome, 0.5))) (chartYTitle chart)       coloredSeries =         [ (fromMaybe fallback (seriesColor s), s)         | (fallback, s) <- zip (cycle (themeSeries theme)) (chartSeries chart)@@ -254,9 +283,9 @@       legend = renderLegend fm ps coloredSeries chart chrome       marginBox :: Diagram B       marginBox =-        rect (1 + leftM + rightM) (1 + botM + topM)+        rect (1 + marginLeft m + marginRight m) (1 + marginBottom m + marginTop m)           # alignBL-          # moveTo (p2 (-leftM, -botM))+          # moveTo (p2 (-marginLeft m, -marginBottom m))       gridDia = grid # lc (plotGrid ps) # lwO (plotStroke 1)       axesDia = axes # lc (plotMuted ps) # lwO (plotStroke 1)       -- Diagrams composes front-to-back: keep the grid behind the data.@@ -269,108 +298,112 @@ renderSeries :: PlotStyle -> Color -> Domain -> Domain -> Series -> U.Vector (Double, Double) -> Diagram B renderSeries ps c xDom yDom s pts =   let ink = colourOf c-      fillCol = lerpColor c (plotFrameBg ps) 0.18-      fill = colourOf fillCol       toP (x, y) = p2 (domainToPlot xDom x, domainToPlot yDom y)    in case seriesKind s of-        LineSeries w _ ->-          fromVertices (U.foldr (\p acc -> toP p : acc) [] pts) # lc ink # lwO (plotStroke w)+        -- Markers are twice the line's width, a default scatter marker's+        -- size on a default line.+        LineSeries w mark ->+          (fromVertices (U.foldr (\p acc -> toP p : acc) [] pts) # lc ink # lwO (plotStroke w))+            <> foldMap (\mk -> U.foldl' (\acc p -> acc <> markShape mk (2 * w) ink (toP p)) mempty pts) mark         ScatterSeries w mk ->           U.foldl' (\acc p -> acc <> markShape mk w ink (toP p)) mempty pts         BarSeries frac ->-          renderBars ink frac pts+          renderBars ink frac xDom yDom pts         AreaSeries baseline ->-          areaPath baseline xDom yDom pts # fc fill # lw none+          mconcat [closedPoly (map toP ring) | ring <- areaRings baseline pts]+            # fc (colourOf (lerpColor c (plotFrameBg ps) 0.18))+            # lw none         StepSeries w ->-          fromVertices (stepPoints pts xDom yDom) # lc ink # lwO (plotStroke w)+          let steps = U.foldr (\((x0, y0), (x1, _)) acc -> toP (x0, y0) : toP (x1, y0) : acc) [toP (U.last pts) | not (U.null pts)] (U.zip pts (U.drop 1 pts))+           in fromVertices steps # lc ink # lwO (plotStroke w) +-- | An area series' fill polygons: for each run of points on one side of+-- the baseline, the points and then the baseline's two ends under them. The+-- baseline is straight, so those two are enough; a point under every+-- sample only doubled the polygon, its triangulation and its outline. A run+-- ends where the data crosses the baseline, at the crossing, so no polygon+-- crosses itself.+areaRings :: Double -> U.Vector (Double, Double) -> [[(Double, Double)]]+areaRings baseline = map closeRun . runs . U.toList+  where+    closeRun run = case run of+      (x0, _) : _ -> run ++ [(fst (last run), baseline), (x0, baseline)]+      [] -> []+    side (_, y) = compare y baseline+    runs (p : ps) = go [p] (side p) p ps+    runs [] = []+    -- The run so far, reversed; its side (EQ while all its points are on+    -- the baseline); and its last point.+    go run _ _ [] = [reverse run]+    go run s prev@(px, py) (q@(qx, qy) : qs)+      | sq == EQ || s == EQ || sq == s = go (q : run) (if s == EQ then sq else s) q qs+      | side prev == EQ = reverse run : go [q, prev] sq q qs+      | otherwise =+          let crossing = (px + (qx - px) * (baseline - py) / (qy - py), baseline)+           in reverse (crossing : run) : go [q, crossing] sq q qs+      where+        sq = side q++-- | Points used for drawing and hit tests, without those that are not+-- finite. Line, area and step data may be decimated, and scatter series and+-- lines with markers past 2000 points; categories become zero-based x+-- positions paired with their values. seriesPoints :: Chart -> Series -> U.Vector (Double, Double) seriesPoints chart s =   case seriesData s of-    PointsXY pts ->-      let k = decimateK (U.length pts)+    PointsXY raw ->+      let pts = finitePoints raw+          -- Markers are not joined, so a dropped one is simply missing:+          -- marked series keep every point up to the cap.+          k = case seriesKind s of+            ScatterSeries {} -> 2000+            LineSeries _ (Just _) -> 2000+            _ -> decimateK (U.length pts)        in if chartDecimate chart && U.length pts > k then lttb k pts else pts     CategoryY _ values ->-       U.generate (sizeofPrimArray values) (\i -> (fromIntegral i, indexPrimArray values i))+       finitePoints (U.generate (sizeofPrimArray values) (\i -> (fromIntegral i, indexPrimArray values i)))+  where+    -- Finite data, the usual case, is not copied.+    finitePoints pts = if U.all ok pts then pts else U.filter ok pts+    ok (x, y) = not (isNaN x || isInfinite x || isNaN y || isInfinite y)  decimateK :: Int -> Int decimateK n = min n (max 64 (min 2000 (n `div` 2))) -renderBars :: Colour Double -> Float -> U.Vector (Double, Double) -> Diagram B-renderBars fill frac pts-  | U.null pts = mempty-  | otherwise =-      let !len  = U.length pts-          !n    = fromIntegral len :: Double-          !w    = realToFrac frac / n-          !invN = 1.0 / n-          !xOff = 0.5 * invN--          -- Single-pass strict fold for maxY (avoids allocating a list or intermediate vector)-          !maxY = U.foldl' (\ !acc (_, y) -> max acc (abs y)) 1e-9 pts-          !invMaxY = 1.0 / maxY--          drawBar (x, y) =-            let !absY = abs y-                !h    = absY * invMaxY-                !posX = x * invN + xOff-                !posY = signum y * h * 0.5-             in rect w h-                  # fc fill-                  # lw none-                  # translate (posX ^& posY)-       in U.foldl' (\acc p -> acc <> drawBar p) mempty pts--areaPath :: Double -> Domain -> Domain -> U.Vector (Double, Double) -> Diagram B-areaPath baseline xDom yDom pts-  | U.null pts = mempty-  | otherwise =-      let !baseY = domainToPlot yDom baseline-          toTop (!x, !y) = p2 (domainToPlot xDom x, domainToPlot yDom y)-          toBase (!x, !_) = p2 (domainToPlot xDom x, baseY)--          -- Forward traversal builds `top` in order-          top = U.foldr (\p acc -> toTop p : acc) [] pts-          -- Left fold naturally yields reverse order without allocating an intermediate reversed vector-          base = U.foldl' (\acc p -> toBase p : acc) [] pts-       in closedPoly (top ++ base)+-- | Bars a fraction of their category slot wide, from zero to each value on+-- the chart's axes.+renderBars :: Colour Double -> Float -> Domain -> Domain -> U.Vector (Double, Double) -> Diagram B+renderBars fill frac xDom yDom = U.foldl' (\acc p -> acc <> drawBar p) mempty+  where+    half = realToFrac frac / 2+    base = domainToPlot yDom 0+    drawBar (x, y) =+      let x0 = domainToPlot xDom (x - half)+          x1 = domainToPlot xDom (x + half)+          top = domainToPlot yDom y+       in rect (x1 - x0) (abs (top - base)) # fc fill # lw none # translate (((x0 + x1) / 2) ^& ((base + top) / 2)) +-- | A closed polygon through the points. The trail keeps its location: a+-- bare trail would be drawn from the origin rather than its first point. closedPoly :: [P2 Double] -> Diagram B-closedPoly pts = fromVertices pts # closeTrail # strokeTrail--stepPoints :: U.Vector (Double, Double) -> Domain -> Domain -> [P2 Double]-stepPoints pts xDom yDom =-  let toP (x, y) = p2 (domainToPlot xDom x, domainToPlot yDom y)-   in U.foldr-        (\((x0, y0), (x1, _)) acc -> toP (x0, y0) : toP (x1, y0) : acc)-        []-        (U.zip pts (U.drop 1 pts))+closedPoly pts = strokeLocTrail (mapLoc closeTrail (fromVertices pts))  markShape :: MarkShape -> Float -> Colour Double -> P2 Double -> Diagram B-markShape MarkCircle w c p =-  circle (plotMarkerRadius w) # fc c # lw none # moveTo p-markShape MarkSquare w c p =-  let s = plotMarkerRadius w * 2-   in rect s s # fc c # lw none # moveTo p-markShape MarkDiamond w c p =-  let r = plotMarkerRadius w * 1.4-   in closedPoly [p2 (0, r), p2 (r, 0), p2 (0, -r), p2 (-r, 0)]-        # fc c-        # lw none-        # moveTo p-markShape MarkTriangle w c p =-  let r = plotMarkerRadius w * 1.6-   in closedPoly [p2 (0, r), p2 (-r, -r * 0.6), p2 (r, -r * 0.6)]-        # fc c-        # lw none-        # moveTo p-markShape MarkCross w c p =-  let r = plotMarkerRadius w * 1.4-      sw = plotStroke w-   in ( (fromVertices [p2 (-r, -r), p2 (r, r)] # lc c # lwO sw)-          <> (fromVertices [p2 (-r, r), p2 (r, -r)] # lc c # lwO sw)-      )-        # moveTo p+markShape shape w c p = moveTo p $ case shape of+  MarkCircle -> filled (circle (plotMarkerRadius w))+  MarkSquare -> let s = plotMarkerRadius w * 2 in filled (rect s s)+  MarkDiamond ->+    let r = plotMarkerRadius w * 1.4+     in filled (closedPoly [p2 (0, r), p2 (r, 0), p2 (0, -r), p2 (-r, 0)])+  MarkTriangle ->+    let r = plotMarkerRadius w * 1.6+     in filled (closedPoly [p2 (0, r), p2 (-r, -r * 0.6), p2 (r, -r * 0.6)])+  MarkCross ->+    let r = plotMarkerRadius w * 1.4+        stroke' a b = fromVertices [a, b] # lc c # lwO (plotStroke w)+     in stroke' (p2 (-r, -r)) (p2 (r, r)) <> stroke' (p2 (-r, r)) (p2 (r, -r))+  where+    filled d = d # fc c # lw none  renderLegend :: FontMetrics -> PlotStyle -> [(Color, Series)] -> Chart -> ChartChrome -> Diagram B renderLegend _ _ _ Chart {chartLegend = LegendNone} _ = mempty@@ -385,7 +418,7 @@       position i = case chartLegend chart of         LegendRight -> (1.04, 0.98 - i * row)         LegendBottom -> (i * col, botLegendY)-        LegendTop -> (i * col, 1.12)+        LegendTop -> (i * col, 1 + px 4 + px (fmLineHeight fm) / 2)         LegendInside -> (0.02, 0.98 - i * row)         LegendNone -> (0, 0)    in mconcat
lib/NanoUI/Plot/Hit.hs view
@@ -7,7 +7,7 @@ import NanoUI (Rect (..), V2, rectContains, v2X, v2Y) import NanoUI.Diagrams.Backend (letterbox) import NanoUI.Diagrams.Widget (frameInner)-import NanoUI.Plot.Scale (plotToDomain)+import NanoUI.Plot.Scale (domainToPlot) import NanoUI.Plot.Types (Domain, PlotHover (..)) import qualified Data.Vector.Unboxed as U @@ -40,22 +40,23 @@   lx = realToFrac (v2X mouse - rectX inner)   ly = realToFrac (v2Y mouse - rectY inner) --- | The data point nearest a position in the unit plot box, given the chart's--- domains and each series' drawn points.+-- | The nearest drawn point to a position in the unit plot box. Distance is+-- measured in that box, which a chart draws square, so the nearest point on+-- screen wins whatever the axes' units; there is no distance cutoff.+-- Ties keep the earlier series/point. Returns 'Nothing' outside the unit box+-- or when every series is empty. nearestPlotHover :: (Domain, Domain) -> [U.Vector (Double, Double)] -> Double -> Double -> Maybe PlotHover nearestPlotHover (xDom, yDom) points gx gy   | gx < 0 || gx > 1 || gy < 0 || gy > 1 = Nothing   | otherwise = snd <$> scanSeries 0 Nothing points  where-  dataX = plotToDomain xDom gx-  dataY = plotToDomain yDom gy   -- The best hover carries its squared distance, so each point computes only   -- its own and a point that loses allocates nothing.   scanSeries !_ !best [] = best   scanSeries !si !best (pts : rest) =     let pick current !ptIdx (!x, !y) =-          let !dx = x - dataX-              !dy = y - dataY+          let !dx = domainToPlot xDom x - gx+              !dy = domainToPlot yDom y - gy               !d = dx * dx + dy * dy            in case current of                 Just (bestD, _) | bestD <= d -> current
lib/NanoUI/Plot/Scale.hs view
@@ -4,9 +4,12 @@   ( domainToPlot   , plotToDomain   , niceTicks+  , niceTickLabels   , formatTick   , domainExtent   , domainExtentBy+  , domainBoundsBy+  , settleDomain   , mergeDomains   , padDomain   ) where@@ -20,7 +23,9 @@ import qualified Data.Text.Lazy.Builder.RealFloat as TB import qualified Data.Vector.Generic as GV --- | Map a domain value into the unit plot box: @lo@ goes to 0, @hi@ to 1.+-- | Map a data value to plot coordinates without clamping. For a domain span+-- of at least 1e-9, the lower bound maps to 0 and the upper bound to 1.+-- Smaller or reversed spans use a denominator of 1e-9. domainToPlot :: Domain -> Double -> Double domainToPlot (Domain lo hi) v = (v - lo) / max 1e-9 (hi - lo) @@ -28,25 +33,40 @@ plotToDomain :: Domain -> Double -> Double plotToDomain (Domain lo hi) v = lo + v * max 1e-9 (hi - lo) --- Works with Data.Vector, Data.Vector.Unboxed, or Data.Vector.Storable+-- | Bounds of a numeric vector. Empty input gives 0-1; constant input gets+-- half a unit of padding on each side. Values that are not finite are skipped. domainExtent :: (GV.Vector v Double) => v Double -> Domain domainExtent = domainExtentBy id {-# INLINE domainExtent #-} --- | Project while reducing, without materialising a mapped numeric vector.+-- | 'domainExtent' after a projection, without allocating a mapped vector. domainExtentBy :: GV.Vector v a => (a -> Double) -> v a -> Domain-domainExtentBy project xs+domainExtentBy project = settleDomain . domainBoundsBy project+{-# INLINE domainExtentBy #-}++-- | The least and greatest finite values after a projection, without the+-- fallbacks of 'domainExtent': no finite values give the empty domain from+-- infinity down to minus infinity, which 'mergeDomains' leaves out. Merge+-- the bounds of several series, then 'settleDomain' the result.+domainBoundsBy :: GV.Vector v a => (a -> Double) -> v a -> Domain+domainBoundsBy project =+  GV.foldl' (\d@(Domain mn mx) value -> let !x = project value in if finite x then Domain (min mn x) (max mx x) else d) (Domain (1 / 0) (-1 / 0))+{-# INLINE domainBoundsBy #-}++-- | Bounds made usable as an axis: empty bounds become 0-1, and a single+-- value gets half a unit on each side.+settleDomain :: Domain -> Domain+settleDomain d@(Domain lo hi)   | lo > hi = Domain 0 1   | lo == hi = Domain (lo - 0.5) (hi + 0.5)-  | otherwise = extent-  where-    extent@(Domain lo hi) =-      GV.foldl' (\(Domain mn mx) value -> let !x = project value in Domain (min mn x) (max mx x)) (Domain (1 / 0) (-1 / 0)) xs-{-# INLINE domainExtentBy #-}+  | otherwise = d +-- | Smallest domain containing both inputs. mergeDomains :: Domain -> Domain -> Domain mergeDomains (Domain a b) (Domain c d) = Domain (min a c) (max b d) +-- | Extend each end by a fraction of the span, using at least 1e-9 for the span.+-- A fraction of 0.05 adds 5% at each end. padDomain :: Double -> Domain -> Domain padDomain frac (Domain lo hi) =   let dSpan = max 1e-9 (hi - lo)@@ -68,6 +88,9 @@         | otherwise = 10    in nf * (10 ** fromIntegral exp10) +-- | Readable ticks using 1, 2, or 5 times a power of ten. The requested count+-- guides spacing; endpoints can add a tick. Invalid domains or non-positive+-- counts return an empty list, and a constant domain returns its one value. niceTicks :: Int -> Domain -> [Double] niceTicks maxTicks (Domain lo hi)   | maxTicks <= 0 || not (finite lo && finite hi) || hi < lo = []@@ -78,31 +101,57 @@   where     dSpan = max 1e-9 (hi - lo)     step = niceStep (dSpan / fromIntegral (max 2 maxTicks))-    start = fromIntegral (ceiling (lo / step - 1e-9) :: Integer) * step-    go !v !count acc+    -- Each tick is its index times the step, so zero is exact and rounding+    -- does not build up along the axis.+    start = ceiling (lo / step - 1e-9) :: Integer+    go !i !count acc       | not (finite v) || v > hi + step * 0.001 = reverse acc       | otherwise =           let !accepted = v >= lo - step * 0.001               acc' = if accepted then v : acc else acc-              !next = v + step+              !next = fromIntegral (i + 1) * step            in if count >= maxTicks || next <= v                 then reverse acc'-                else go next (count + 1) acc'+                else go (i + 1) (count + 1) acc'+      where+        !v = fromIntegral i * step +-- | 'niceTicks' with their labels, which have the digits that tell+-- neighbouring ticks apart and no more.+niceTickLabels :: Int -> Domain -> [(Double, Text)]+niceTickLabels maxTicks d = case niceTicks maxTicks d of+  ts@(a : b : _) -> [(t, formatStep (b - a) t) | t <- ts]+  ts -> [(t, formatTick t) | t <- ts]++-- | Format a finite tick in fixed point with trailing zeros removed, or, for+-- very small or large magnitudes, in scientific notation with three decimals+-- (@1.500e-10@). Non-finite values produce empty text. formatTick :: Double -> Text formatTick v   | not (finite v) = T.empty+  | abs v >= 1e6 || (abs v > 0 && abs v < 1e-6) = render (TB.formatRealFloat TB.Exponent (Just 3) v)   | otherwise =       let snapped = snapNoise v-       in if abs snapped >= 1e6 || (abs snapped > 0 && abs snapped < 1e-6)-            then render (TB.formatRealFloat TB.Exponent (Just 3) snapped)-            else-              let n = round snapped :: Integer-               in if abs (snapped - fromIntegral n) < 1e-6-                    then render (TB.decimal n)-                    else stripZeros (render (TB.formatRealFloat TB.Fixed (Just 6) snapped))+          n = round snapped :: Integer+       in if abs (snapped - fromIntegral n) < 1e-6+            then render (TB.decimal n)+            else stripZeros (render (TB.formatRealFloat TB.Fixed (Just 6) snapped))++-- A tick on an axis whose ticks are @step@ apart, in 'formatTick''s forms+-- with the step's last digit as its last.+formatStep :: Double -> Double -> Text+formatStep step v+  | v /= 0 && (abs v >= 1e6 || abs v < 1e-6) =+      let (mantissa, e) = T.breakOn "e" (render (TB.formatRealFloat TB.Exponent (Just (max 0 (mag v - mag step))) v))+       in stripZeros mantissa <> e+  | decimals == 0 = render (TB.decimal (round v :: Integer))+  | otherwise = stripZeros (render (TB.formatRealFloat TB.Fixed (Just decimals) v))   where-    render = TL.toStrict . TB.toLazyText+    decimals = max 0 (negate (mag step))+    mag x = floor (logBase 10 (abs x) + 1e-9) :: Int++render :: TB.Builder -> Text+render = TL.toStrict . TB.toLazyText  snapNoise :: Double -> Double snapNoise v =
lib/NanoUI/Plot/Series.hs view
@@ -33,24 +33,33 @@   , SeriesKind (..)   ) +-- | Connect numeric points in input order with a 1.5-width line. Points are+-- not sorted; supply them in the desired path order. line :: Foldable f => Text -> f (Double, Double) -> Series line name = lineVec name . U.fromList . toList +-- | Plot numeric points as circle markers of size 3. scatter :: Foldable f => Text -> f (Double, Double) -> Series scatter name = scatterVec name . U.fromList . toList +-- | Category bars in input order, occupying 72% of each category slot. bar :: Foldable f => Text -> f (Text, Double) -> Series bar name = barVec name . V.fromList . toList +-- | Fill the path through numeric points down to a baseline of zero. area :: Foldable f => Text -> f (Double, Double) -> Series area name = areaVec name . U.fromList . toList +-- | Join points in input order with horizontal and vertical steps. step :: Foldable f => Text -> f (Double, Double) -> Series step name = stepVec name . U.fromList . toList +-- | Override the theme palette colour for this series. withColor :: Color -> Series -> Series withColor c s = s {seriesColor = Just c} +-- | Set line/step width, scatter marker size, or bar slot fraction. Has no+-- effect on area series. The parameter is interpreted by the series kind. withStrokeWidth :: Float -> Series -> Series withStrokeWidth w s =   case seriesKind s of@@ -60,6 +69,8 @@     StepSeries _ -> s {seriesKind = StepSeries w}     _ -> s +-- | Mark each point of a line or scatter series with a shape; leave other+-- kinds unchanged. A line's markers are sized at twice its stroke width. withMarker :: MarkShape -> Series -> Series withMarker mk s =   case seriesKind s of@@ -67,30 +78,39 @@     ScatterSeries w _ -> s {seriesKind = ScatterSeries w mk}     _ -> s +-- | Set an area series' baseline in data units; leave other kinds unchanged. withBaseline :: Double -> Series -> Series withBaseline b s =   case seriesKind s of     AreaSeries _ -> s {seriesKind = AreaSeries b}     _ -> s --- | Numeric series retain unboxed coordinates. Unboxed inputs are shared;--- boxed/storable inputs are converted once at the construction boundary.+-- | Vector form of 'line'. Coordinates are copied into an unboxed vector,+-- whatever the input vector's kind. {-# INLINE lineVec #-} lineVec :: G.Vector v (Double, Double) => Text -> v (Double, Double) -> Series-lineVec name pts = Series name Nothing (LineSeries 1.5 Nothing) (PointsXY (G.convert pts))+lineVec = pointSeries (LineSeries 1.5 Nothing) +-- | Vector form of 'scatter'. {-# INLINE scatterVec #-} scatterVec :: G.Vector v (Double, Double) => Text -> v (Double, Double) -> Series-scatterVec name pts = Series name Nothing (ScatterSeries 3 MarkCircle) (PointsXY (G.convert pts))+scatterVec = pointSeries (ScatterSeries 3 MarkCircle) +-- | Vector form of 'area', with a baseline of zero. {-# INLINE areaVec #-} areaVec :: G.Vector v (Double, Double) => Text -> v (Double, Double) -> Series-areaVec name pts = Series name Nothing (AreaSeries 0) (PointsXY (G.convert pts))+areaVec = pointSeries (AreaSeries 0) +-- | Vector form of 'step', preserving point order. {-# INLINE stepVec #-} stepVec :: G.Vector v (Double, Double) => Text -> v (Double, Double) -> Series-stepVec name pts = Series name Nothing (StepSeries 1.5) (PointsXY (G.convert pts))+stepVec = pointSeries (StepSeries 1.5) +{-# INLINE pointSeries #-}+pointSeries :: G.Vector v (Double, Double) => SeriesKind -> Text -> v (Double, Double) -> Series+pointSeries kind name pts = Series name Nothing kind (PointsXY (G.convert pts))++-- | Vector form of 'bar'. Copies labels and values into equally sized arrays. barVec :: Text -> Vector (Text, Double) -> Series barVec name rows =   Series name Nothing (BarSeries 0.72) $
lib/NanoUI/Plot/Types.hs view
@@ -13,32 +13,69 @@   , emptyChart   ) where -import Data.Primitive.PrimArray (PrimArray)+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, sizeofPrimArray) import Data.Primitive.SmallArray (SmallArray) import Data.Text (Text) import Data.Vector.Unboxed qualified as U-import NanoUI (Color, Response)+import NanoUI (Color, HasResponse (..), Response)+import NanoUI.Internal.Store (sameDouble, sameFloat) +-- | Lower and upper axis bounds. Use finite, increasing bounds for plotting. data Domain = Domain !Double !Double   deriving (Eq, Show) +-- | Numeric x/y pairs or category labels with y values. Category arrays must+-- have equal lengths; use the constructors in "NanoUI.Plot.Series" to build them.+-- Points and values that are not finite (NaN, infinities) are not drawn. data SeriesData   = PointsXY !(U.Vector (Double, Double))   | -- | Bar labels and their values, in order.     CategoryY !(SmallArray Text) !(PrimArray Double)-  deriving (Eq, Show)+  deriving (Show) +-- Points compare pair by pair, as the vector's own instance does, without+-- boxing each pair: charts are compared every frame to reuse their drawing.+-- A NaN equals the same NaN, or a chart holding one would be new every+-- frame, rebuilt and repainted forever.+instance Eq SeriesData where+  PointsXY a == PointsXY b = U.length a == U.length b && go 0+    where+      go !i+        | i >= U.length a = True+        | otherwise = case (U.unsafeIndex a i, U.unsafeIndex b i) of+            ((x, y), (x', y')) -> sameDouble x x' && sameDouble y y' && go (i + 1)+  CategoryY labels values == CategoryY labels' values' =+    labels == labels' && n == sizeofPrimArray values' && go 0+    where+      n = sizeofPrimArray values+      go !i = i >= n || (sameDouble (indexPrimArray values i) (indexPrimArray values' i) && go (i + 1))+  _ == _ = False++-- | Shape of a plotted point marker. data MarkShape = MarkCircle | MarkSquare | MarkDiamond | MarkTriangle | MarkCross   deriving (Eq, Show) +-- | Drawing method and its size parameter: line/step stroke width, scatter+-- marker size, bar fraction of a category slot, or area baseline in data units. data SeriesKind   = LineSeries !Float (Maybe MarkShape)   | ScatterSeries !Float !MarkShape   | BarSeries !Float   | AreaSeries !Double   | StepSeries !Float-  deriving (Eq, Show)+  deriving (Show) +-- A NaN parameter equals the same NaN, as in 'SeriesData'.+instance Eq SeriesKind where+  LineSeries w m == LineSeries w' m' = sameFloat w w' && m == m'+  ScatterSeries w m == ScatterSeries w' m' = sameFloat w w' && m == m'+  BarSeries f == BarSeries f' = sameFloat f f'+  AreaSeries b == AreaSeries b' = sameDouble b b'+  StepSeries w == StepSeries w' = sameFloat w w'+  _ == _ = False++-- | Named data and rendering options. An absent colour selects the chart's+-- theme palette by series index. data Series = Series   { seriesName :: !Text   , seriesColor :: !(Maybe Color)@@ -47,12 +84,17 @@   }   deriving (Eq, Show) +-- | Legend position relative to the plot, or no legend. data LegendPos = LegendRight | LegendBottom | LegendTop | LegendInside | LegendNone   deriving (Eq, Show) +-- | Which axis grid lines to draw through the data box. data GridMode = GridBoth | GridHorizontal | GridVertical | GridNone   deriving (Eq, Show) +-- | Series and chart decoration. Decimation reduces line, area and step+-- series before drawing and hit testing; it does not alter the stored data.+-- Scatter series and lines with markers are thinned only past 2000 points. data Chart = Chart   { chartTitle :: !(Maybe Text)   , chartXTitle :: !(Maybe Text)@@ -64,6 +106,9 @@   }   deriving (Eq, Show) +-- | Nearest drawn point in data coordinates. Both indices are zero-based;+-- the point index addresses the drawn points, which leave out those that are+-- not finite and are decimated when decimation is enabled. data PlotHover = PlotHover   { hoverDataX :: !Double   , hoverDataY :: !Double@@ -72,12 +117,19 @@   }   deriving (Eq, Show) +-- | Widget response plus the nearest point while the pointer is inside the+-- data box. Hover is 'Nothing' outside it or when there are no points. data PlotResponse = PlotResponse   { plotResponse :: !Response   , plotHover :: !(Maybe PlotHover)   }   deriving (Eq, Show) +instance HasResponse PlotResponse where+  {-# INLINE toResponse #-}+  toResponse = plotResponse++-- | No series or titles, a right-hand legend, both grid directions, and decimation. emptyChart :: Chart emptyChart =   Chart
lib/NanoUI/Plot/Widget.hs view
@@ -1,40 +1,47 @@ -- | Chart widgets: 'plot' draws a chart and reports the hovered point, and -- 'lineChart', 'barChart', 'scatterChart' and 'areaChart' draw one series. module NanoUI.Plot.Widget-  ( plot+  ( PlotCache+  , newPlotCache+  , plot   , lineChart   , barChart   , scatterChart   , areaChart   ) where -import Data.Dynamic (fromDynamic, toDyn) import Data.IORef (readIORef)-import qualified Data.IntMap.Strict as IM import Data.Maybe (fromMaybe, catMaybes) import Data.Text (Text) import Data.Vector.Unboxed qualified as U import Diagrams.Prelude (Diagram, V2 (..), extentX, extentY, size)-import Effectful (Eff, type (:>)) import NanoUI-  ( FontMetrics+  ( NanoUI   , Layout   , Theme-  , Ui   , WidgetId-  , uiFontMetrics   , uiMousePos   , uiTheme-  , prepareFontMetricsMany   , respRect   )-import NanoUI.Context (Context (..), WidgetStore (..), getStore, intKey, setStore)-import NanoUI.Monad (askContext, nextId, uiIO)+import NanoUI.Backend+  ( FontMetrics+  , IntGenCache+  , intGenCacheInsert+  , intGenCacheLookup+  , intGenCacheStartFrame+  , intGenCacheTouch+  , newIntGenCache+  , prepareFontMetricsMany+  , uiFontMetrics+  )+import NanoUI.Internal.Context (Context (..), frameNumber, intKey, markDirty)+import NanoUI.Internal.Monad (freshWidget)+import NanoUI.Monad (liftIO) import NanoUI.Diagrams.Backend (B)-import NanoUI.Diagrams.Widget (PlotStyle, diagramWithKeyAndEnvelope, uiPlotStyle)+import NanoUI.Diagrams.Widget (diagramWithKeyAndEnvelope, themePlotStyle) import NanoUI.Plot.Builder qualified as Builder-import NanoUI.Plot.Chrome (chartDiagram, seriesDomains, seriesPoints)-import NanoUI.Plot.Scale (formatTick, niceTicks)+import NanoUI.Plot.Chrome (chartDiagramWithTicks, chartTicks, seriesDomains, seriesPoints) import NanoUI.Plot.Hit (hitTestChartCached) import NanoUI.Plot.Series (area, bar, line, scatter) import NanoUI.Plot.Types@@ -44,12 +51,23 @@   , LegendPos (..)   , PlotResponse (..)   )+import NanoUI.Internal.Store (eqByPtr) +-- | Typed chart cache owned by a component in one session. Allocate once+-- during setup; multiple plots in that component are distinguished by widget id.+-- Backed by a bounded two-generation cache, so dynamic plot ids do not retain+-- stale diagrams indefinitely.+newtype PlotCache = PlotCache (IntGenCache CachedChart)++-- | An empty cache. Allocate it once, during setup, and pass it to the+-- component's plots: a cache made each frame rebuilds every chart each frame.+newPlotCache :: IO PlotCache+newPlotCache = PlotCache <$> newIntGenCache 16+ data CachedChart = CachedChart   { ccChart :: !Chart   , ccTheme :: !Theme   , ccFont :: {-# UNPACK #-} !Int-  , ccStyle :: !PlotStyle   , ccVersion :: {-# UNPACK #-} !Int   , ccDiagram :: !(Diagram B)   , ccWidth :: {-# UNPACK #-} !Double@@ -60,59 +78,70 @@   , ccPoints :: ![U.Vector (Double, Double)]   } --- Keep the cache in the owning context's widget store. Versions only need--- to distinguish successive contents of this widget's draw-op cache.-cachedChartDiagram :: Context -> WidgetId -> FontMetrics -> Theme -> PlotStyle -> Chart -> IO CachedChart-cachedChartDiagram ctx wid fm theme ps chart = do+-- Keep the cache in the component's typed owner. Versions only need+-- to distinguish successive contents of this widget's draw-op cache. The+-- plot style is derived from the theme, so the theme check covers it. A+-- chart kept across frames matches by pointer, before its value is compared.+cachedChartDiagram :: PlotCache -> Context -> WidgetId -> FontMetrics -> Theme -> Chart -> IO CachedChart+cachedChartDiagram (PlotCache cache) ctx wid fm theme chart = do   let k = intKey wid+  frame <- frameNumber ctx+  intGenCacheStartFrame cache frame   font <- readIORef (ctxMetricGen ctx)-  store <- getStore ctx-  let previous = IM.lookup k (storeDyn store) >>= fromDynamic+  previous <- intGenCacheLookup cache k   case previous of-    Just cc | ccChart cc == chart && ccTheme cc == theme && ccFont cc == font && ccStyle cc == ps -> pure cc+    Just cc | ccTheme cc == theme && ccFont cc == font && eqByPtr (ccChart cc) chart -> do+      intGenCacheTouch cache k cc+      pure cc     _ -> do-      let domains@(xDom, yDom) = seriesDomains chart+      let ps = themePlotStyle theme+          domains = seriesDomains chart+          ticks@(xTicks, yTicks) = chartTicks domains chart           points = map (seriesPoints chart) (chartSeries chart)           labels = catMaybes [chartTitle chart, chartXTitle chart, chartYTitle chart]             ++ map seriesName (chartSeries chart)-            ++ map formatTick (niceTicks 6 xDom ++ niceTicks 6 yDom)+            ++ map snd xTicks+            ++ map snd yTicks       prepared <- prepareFontMetricsMany fm labels-      let !d = chartDiagram prepared theme ps domains points chart+      let !d = chartDiagramWithTicks prepared theme ps domains ticks points chart           !(V2 dw dh) = size d           extX = fromMaybe (0, dw) (extentX d)           extY = fromMaybe (0, dh) (extentY d)       let !v = maybe 1 ((+ 1) . ccVersion) previous-          !cc = CachedChart chart theme font ps v d dw dh extX extY domains points-      setStore ctx (store {storeDyn = IM.insert k (toDyn cc) (storeDyn store)})+          !cc = CachedChart chart theme font v d dw dh extX extY domains points+      intGenCacheInsert cache k cc+      -- The diagram's content version damages its actual drawing node.+      markDirty ctx       pure cc  -- | Draw a chart sized by the layout modifier. The response reports the -- nearest data point under the pointer.-plot :: Ui :> es => (Layout -> Layout) -> Chart -> Eff es PlotResponse-plot f chart = do-  wid <- nextId-  ctx <- askContext+plot :: PlotCache -> (Layout -> Layout) -> Chart -> NanoUI PlotResponse+plot cache f chart = do+  (wid, ctx) <- freshWidget   fm <- uiFontMetrics   theme <- uiTheme-  ps <- uiPlotStyle-  cc <- uiIO (cachedChartDiagram ctx wid fm theme ps chart)+  cc <- liftIO (cachedChartDiagram cache ctx wid fm theme chart)   resp <- diagramWithKeyAndEnvelope (ccVersion cc) (ccWidth cc) (ccHeight cc) f (ccDiagram cc)   mouse <- uiMousePos   let hover = hitTestChartCached (ccWidth cc) (ccHeight cc) (ccExtX cc) (ccExtY cc) (ccDomains cc) (ccPoints cc) (respRect resp) mouse   pure PlotResponse {plotResponse = resp, plotHover = hover}  -- | One line series with a grid and no legend.-lineChart :: Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse-lineChart f pts = plot f (singleSeries True (line "series" pts))+lineChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse+lineChart cache f pts = plot cache f (singleSeries True (line "series" pts)) -barChart :: Ui :> es => (Layout -> Layout) -> [(Text, Double)] -> Eff es PlotResponse-barChart f pts = plot f (singleSeries False (bar "series" pts))+-- | One category-bar series with a grid, no legend, and no decimation.+barChart :: PlotCache -> (Layout -> Layout) -> [(Text, Double)] -> NanoUI PlotResponse+barChart cache f pts = plot cache f (singleSeries False (bar "series" pts)) -scatterChart :: Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse-scatterChart f pts = plot f (singleSeries False (scatter "series" pts))+-- | One scatter series with a grid, no legend, and no decimation.+scatterChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse+scatterChart cache f pts = plot cache f (singleSeries False (scatter "series" pts)) -areaChart :: Ui :> es => (Layout -> Layout) -> [(Double, Double)] -> Eff es PlotResponse-areaChart f pts = plot f (singleSeries True (area "series" pts))+-- | One area series with a zero baseline, grid, no legend, and decimation.+areaChart :: PlotCache -> (Layout -> Layout) -> [(Double, Double)] -> NanoUI PlotResponse+areaChart cache f pts = plot cache f (singleSeries True (area "series" pts))  -- | A gridded chart of one series without a legend, optionally decimated. singleSeries :: Bool -> Series -> Chart
nano-ui-diagrams.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.4 name:               nano-ui-diagrams-version:            0.1.0.0+version:            0.2.0.0 synopsis:           Charts and diagrams-lib drawings for nano-ui description:     Places diagrams-lib drawings in nano-ui layouts and builds line, bar,@@ -9,9 +9,9 @@ license-file:       LICENSE author:             goolord maintainer:         zacharyachurchill@gmail.com-category:           Graphics homepage:           https://github.com/goolord/nano-ui bug-reports:        https://github.com/goolord/nano-ui/issues+category:           Graphics build-type:         Simple tested-with:        GHC ==9.10.3 || ==9.14.1 extra-doc-files:@@ -31,18 +31,18 @@         TypeFamilies  common warnings-  ghc-options:-    -Wall-    -Wextra-    -Wcompat-    -Widentities-    -Wincomplete-record-updates-    -Wincomplete-uni-patterns-    -Wmissing-export-lists-    -Wmissing-home-modules-    -Wpartial-fields-    -Wredundant-constraints-    -Wunused-packages+    ghc-options:+        -Wall+        -Wextra+        -Wcompat+        -Widentities+        -Wincomplete-record-updates+        -Wincomplete-uni-patterns+        -Wmissing-export-lists+        -Wmissing-home-modules+        -Wpartial-fields+        -Wredundant-constraints+        -Wunused-packages  library     import:           extensions@@ -50,7 +50,6 @@     exposed-modules:         NanoUI.Diagrams         NanoUI.Diagrams.Backend-        NanoUI.Diagrams.Tessellation         NanoUI.Diagrams.Widget         NanoUI.Plot         NanoUI.Plot.Types@@ -63,18 +62,17 @@         NanoUI.Plot.Widget     build-depends:         base >=4.20 && <4.23,-        colour >=2.3.3 && <2.4,-        containers >=0.6.7 && <0.9,+        colour >=2.3.2 && <2.4,+        containers >=0.7 && <0.9,         diagrams-core >=1.5 && <1.6,-        diagrams-lib >=1.4.6 && <1.7,-        dlist >=1.0 && <1.1,-        effectful-core >=2.5 && <2.8,-        hashable >=1.4 && <1.6,-        lens >=5.0 && <5.4,-        nano-ui ^>=0.1,-        primitive >=0.8 && <0.10,-        text >=2.0 && <2.2,-        vector >=0.13 && <0.14+        diagrams-lib >=1.6 && <1.7,+        dlist ^>=1.0,+        hashable ^>=1.5,+        lens >=5.2 && <5.4,+        nano-ui ^>=0.2,+        primitive ^>=0.9,+        text ^>=2.1,+        vector ^>=0.13     hs-source-dirs:   lib  test-suite nano-ui-diagrams-test@@ -84,12 +82,12 @@     main-is:          Main.hs     build-depends:         base >=4.20 && <4.23,-        colour >=2.3.3 && <2.4,-        diagrams-lib >=1.4.6 && <1.7,-        hspec >=2.10 && <2.12,-        nano-ui,+        colour >=2.3.2 && <2.4,+        diagrams-lib >=1.6 && <1.7,+        hspec ^>=2.11,+        nano-ui ^>=0.2,         nano-ui-diagrams,-        primitive >=0.8 && <0.10,-        text >=2.0 && <2.2,-        vector >=0.13 && <0.14+        primitive ^>=0.9,+        text ^>=2.1,+        vector ^>=0.13     hs-source-dirs:   test
test/Main.hs view
@@ -1,350 +1,313 @@ module Main (main) where -import Control.Monad (forM_, unless)-import Data.Colour.Names (coral, steelblue)+import Control.Monad (forM_, replicateM_)+import Data.Colour (withOpacity)+import Data.Colour.Names (coral, red, steelblue) import Data.Foldable (toList) import Data.IORef (readIORef)-import Data.List (tails)-import Data.Maybe (fromMaybe, listToMaybe)+import Data.List (nub, sortOn, tails)+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, primArrayToList, sizeofPrimArray) import Data.Text qualified as T-import Data.Primitive.SmallArray (SmallArray, emptySmallArray) import Data.Vector qualified as V-import Diagrams.Prelude-  ( Diagram-  , circle-  , fc-  , lw-  , lwO-  , none-  , (#)-  )+import Data.Vector.Unboxed qualified as U+import Diagrams.Prelude qualified as D+import Diagrams.Prelude (Diagram, (#)) import NanoUI-import NanoUI.Context (Context (..), DrawingCacheState (..), withFontMetrics)-import NanoUI.Context.Types (DrawOpCacheEntry (..))+import NanoUI.Backend+import NanoUI.Widgets.Custom (DrawOp (..))+import NanoUI.Internal.Context (Context (..), DrawingCacheState (..))+import NanoUI.Internal.Context.Types (DrawOpCacheEntry (..)) import NanoUI.Diagrams-  ( B-  , defaultPlotStyle-  , diagram-  , diagramOps-  , fitLayout-  )-import NanoUI.Diagrams.Backend (diagramTextOps)-import NanoUI.Diagrams.Tessellation-  ( strokePolyline-  , triangulatePolygon-  )-import NanoUI.Plot.Chrome-  ( Margins (..)-  , chartDiagram-  , chartMargins-  , seriesDomains-  , seriesPoints-  )-import NanoUI.Plot.Decimate (lttb, minMaxDecimate)+import NanoUI.Internal.Path (Shade (..))+import NanoUI.Path qualified as P import NanoUI.Plot.Hit (nearestPlotHover)-import NanoUI.Plot.Scale (formatTick, mergeDomains, niceTicks)-import NanoUI.Plot.Series-  ( area-  , bar-  , line-  , scatter-  , withColor-  , withMarker-  )-import NanoUI.Plot.Types-  ( Chart (..)-  , Domain (..)-  , GridMode (..)-  , LegendPos (..)-  , MarkShape (..)-  , PlotHover (..)-  , Series (..)-  ) import NanoUI.Plot.Widget qualified as Plot-import NanoUI.Testing (DrawData (..), drawCmdNull, newPixelContext, runFrame)+import NanoUI.Testing.Assert (require) import Test.Hspec (describe, hspec, it)  main :: IO () main = hspec $ do-  let-    fm = monospaceMetrics 16   describe "rendering" $ do-    it "draws and redraws a filled diagram" $ do-      ctx <- newPixelContext-      testRendering ctx (emptyInput {inputWindowSize = Size 240 120})-    it "renders chart labels apart from geometry" (testTextOnlyRendering fm)+    it "draws a diagram, then from its cache, with labels apart from geometry" testRendering     it "reuses cached chart content within one context" testChartCache-  describe "tessellation" $ do-    it "triangulates indexed polygons with full coverage" testIndexedTriangulation-    it "covers polyline strokes end to end" testStrokeCoversMidpoint+    it "settles on a chart holding NaN" testNaNChartIdle+    it "turns diagram fills and strokes into ops" testDiagramOps   describe "scales and domains" $ do-    it "picks and formats nice ticks" testNiceTicks-    it "shares bounds across series" testMultiSeriesDomains-  describe "decimation" $ do-    it "keeps LTTB extrema and endpoints" testLttb-    it "keeps min/max extrema" testMinMaxDecimate+    it "picks nice ticks and labels them with the digits their step needs" testTicks+    it "shares finite bounds across series and baselines" testDomains+  describe "decimation" $+    it "keeps extrema, endpoints and order, and markers up to 2000" testDecimation   describe "chart chrome" $ do-    it "keeps labels, titles and legends apart" (testLabelFit fm)-    it "colors legend entries like their series" (testLegendColors fm)+    it "keeps labels, titles and legends apart" testLabelFit+    it "colors legend entries like their series" testLegendColors     it "picks the nearest hover point" testPlotHover-    it "fills closed series and markers" (testClosedSeriesFills fm)-    it "caps the height of growing plots" (testGrowPlotHeight fm)+    it "draws series shapes where their data is" testSeriesShapes+    it "fills an area a ring per side of its baseline" testAreaRings+    it "sizes plots and diagrams by the caller's box" testFit +fm :: FontMetrics+fm = monospaceMetrics 16+ -- | A chart of the given series with no legend, grid or decimation. bareChart :: [Series] -> Chart-bareChart ss =-  Chart-    { chartTitle = Nothing-    , chartXTitle = Nothing-    , chartYTitle = Nothing-    , chartSeries = ss-    , chartLegend = LegendNone-    , chartGrid = GridNone-    , chartDecimate = False-    }+bareChart ss = (chart ss) {chartLegend = LegendNone, chartGrid = GridNone, chartDecimate = False} -chartDia :: FontMetrics -> Chart -> Diagram B-chartDia fm c = chartDiagram fm defaultTheme defaultPlotStyle (seriesDomains c) (map (seriesPoints c) (chartSeries c)) c+chartDia :: Chart -> Diagram B+chartDia c = chartDiagram fm defaultTheme defaultPlotStyle (seriesDomains c) (map (seriesPoints c) (chartSeries c)) c +-- | The ops of a chart drawn @w@ by @h@.+chartOps :: Float -> Float -> Chart -> [DrawOp]+chartOps w h = toList . diagramOps (realToFrac w) (realToFrac h) . chartDia++-- | The ops of a 100 by 100 diagram.+diaOps :: Diagram B -> [DrawOp]+diaOps = toList . diagramOps 100 100+ rectsOverlap :: Rect -> Rect -> Bool rectsOverlap (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =   x1 < x2 + w2 && x2 < x1 + w1 && y1 < y2 + h2 && y2 < y1 + h1 -testTextOnlyRendering :: FontMetrics -> IO ()-testTextOnlyRendering fm = do+-- | A flat array of x, y pairs as points.+pointsOf :: PrimArray Float -> [(Float, Float)]+pointsOf p = [(indexPrimArray p (2 * k), indexPrimArray p (2 * k + 1)) | k <- [0 .. sizeofPrimArray p `div` 2 - 1]]++-- | The colour of a polygon fill or a polyline stroke.+inkColor :: DrawOp -> Maybe Color+inkColor (FillPolygon _ _ _ (Flat c)) = Just c+inkColor (StrokePolyline _ _ _ _ _ _ (Flat c)) = Just c+inkColor _ = Nothing++-- | The first theme series colour.+seriesInk :: Color+seriesInk = fromMaybe (themeRed defaultTheme) (listToMaybe (themeSeries defaultTheme))++testRendering :: IO ()+testRendering = do+  ctx <- newPixelContext+  -- The second frame draws from the cache.+  replicateM_ 2 $ do+    (_, dd, _) <-+      runFrame ctx (emptyInput {inputWindowSize = Size 240 120}) $+        diagram (fixedWH 200 80) (D.circle 1 # D.fc coral # D.lw D.none)+    require "diagram produced no draw commands" (drawIndexCount dd > 0 && not (drawCmdNull dd))   let-    d = linePlotDiag fm [(0, 0), (1, 2), (2, 1)]-    isText DrawText {} = True-    isText _ = False+    d = chartDia (bareChart [line "s" [(0, 0), (1, 2), (2, 1)]]) # D.lwO 2 # D.fc steelblue+    isText = \case+      DrawText {} -> True+      _ -> False   forM_ [(400, 240), (120, 400), (0, 100), (100, -1)] $ \(w, h) -> do     let-      full = diagramOps w h d-      labels = diagramTextOps w h d-    unless (toList labels == filter isText (toList full)) $-      fail "text-only rendering differs from the full render's text"-    unless-      (w <= 0 || h <= 0 || (not (null labels) && length labels < length full)) $-      fail "text-only rendering did not separate chart labels from geometry"+      full = toList (diagramOps w h d)+      labels = toList (diagramTextOps w h d)+    require "text-only rendering differs from the full render's text" (labels == filter isText full)+    require "text-only rendering did not separate chart labels from geometry" $+      w <= 0 || h <= 0 || (not (null labels) && length labels < length full)  testChartCache :: IO () testChartCache = do   base <- newPixelContext   other <- newPixelContext+  owner <- Plot.newPlotCache+  otherOwner <- Plot.newPlotCache   let-    inp = emptyInput {inputWindowSize = Size 400 240}-    fm = monospaceMetrics 16-    larger = monospaceMetrics 24     ctx = withFontMetrics base fm-    render c = do+    larger = monospaceMetrics 24+    render cacheOwner c = do       _ <--        runFrame c inp $ Plot.lineChart (fixedWH 360 200) [(0, 0), (1, 1)]-      cache <- readIORef (ctxDrawingCache c)-      pure (map doeContent (toList (dcsDrawOpCache cache)))-  first <- render ctx-  again <- render ctx-  unless (not (null first) && first == again) $-    fail "chart cache did not reuse unchanged content"-  changed <- render (withFontMetrics base larger)-  unless (changed /= first) $-    fail "chart cache ignored changed font metrics"-  independent <- render (withFontMetrics other larger)-  unless (independent == first) $-    fail "chart cache version leaked across contexts"+        runFrame c (emptyInput {inputWindowSize = Size 400 240}) $+          Plot.lineChart cacheOwner (fixedWH 360 200) [(0, 0), (1, 1)]+      map doeContent . toList . dcsDrawOpCache <$> readIORef (ctxDrawingCache c)+  first <- render owner ctx+  again <- render owner ctx+  require "chart cache did not reuse unchanged content" (not (null first) && first == again)+  changed <- render owner (withFontMetrics base larger)+  require "chart cache ignored changed font metrics" (changed /= first)+  independent <- render otherOwner (withFontMetrics other larger)+  require "chart cache version leaked across contexts" (independent == first) -testRendering :: Context -> Input -> IO ()-testRendering ctx inp = do+-- | A chart holding NaN equals a rebuilt copy of itself, so a plot built+-- from it every frame settles instead of asking for frames forever.+testNaNChartIdle :: IO ()+testNaNChartIdle = do+  base <- newPixelContext+  owner <- Plot.newPlotCache   let-    ok d = drawIndexCount d > 0 && not (drawCmdNull d)-  (_, _, filled, _) <--    runFrame ctx inp $-      diagram (fixedWH 200 80) (circle 1 # fc coral # lw none)-  unless (ok filled) $-    fail "diagram produced no draw commands"-  (_, _, filledAgain, _) <--    runFrame ctx inp $-      diagram (fixedWH 200 80) (circle 1 # fc coral # lw none)-  unless (ok filledAgain) $-    fail "cached diagram produced no draw commands"--linePlotDiag :: FontMetrics -> [(Double, Double)] -> Diagram B-linePlotDiag fm pts =-  chartDia fm (bareChart [line "s" pts])-    # lwO 2-    # fc steelblue--triArea :: (Float, Float) -> (Float, Float) -> (Float, Float) -> Float-triArea (x0, y0) (x1, y1) (x2, y2) =-  abs ((x0 - x2) * (y1 - y0) - (x0 - x1) * (y2 - y0)) * 0.5--testIndexedTriangulation :: IO ()-testIndexedTriangulation = do-  forM_ [[], [(0, 0)], [(0, 0), (1, 1)], [(0, 0), (1, 1), (0, 0)]] $ \pts ->-    unless (null (triangulatePolygon pts)) $-      fail "undersized polygon emitted triangles"-  -- Alternating radii exercise repeated ear removal and wraparound indices.-  forM_ [3, 16, 127, 256 :: Int] $ \n -> do-    let-      points =-        [ let-            angle = 2 * pi * fromIntegral i / fromIntegral n-            radius = if even i then 10 else 6-           in-            (radius * cos angle, radius * sin angle)-        | i <- [0 .. n - 1]-        ]-      polygonArea =-        abs-          (sum [x * y' - x' * y | ((x, y), (x', y')) <- zip points (drop 1 (cycle points))])-          / 2-    forM_ [points, reverse points, points ++ take 1 points] $ \pts -> do-      let-        triangles = triangulatePolygon pts-        areaSum = sum [triArea a b c | (a, b, c) <- triangles]-      unless (length triangles == n - 2 && abs (areaSum - polygonArea) < 0.01) $-        fail-          ( "indexed triangulation changed polygon coverage: "-              ++ show (n, length triangles, areaSum, polygonArea)-          )+    nan = 0 / 0+    held = bareChart [line "l" [(0, nan)], bar "b" [("x", nan)]]+    -- A NaN in a series' own parameters, not its data.+    params = bareChart [withBaseline nan (area "a" [(0, 1)]), withStrokeWidth (0 / 0) (line "l" [(0, 1)])]+    ctx = withFontMetrics base fm+    -- The points depend on the frame, so each frame builds a new chart.+    frame k = runFrame ctx (emptyInput {inputWindowSize = Size 400 240}) $ do+      _ <- Plot.lineChart owner (fixedWH 360 100) [(0, 0), (1, nan * fromIntegral (k :: Int)), (2, 1)]+      Plot.plot owner (fixedWH 360 100) (bareChart [withBaseline (nan * fromIntegral k) (area "a" [(0, 0), (1, 1)])])+  require "a chart holding NaN differs from itself" (held == held && params == params)+  again <- mapM frame [1 .. 4]+  require "a plot of a chart holding NaN asks for frames forever" (not (or [more | (_, _, more) <- drop 2 again])) -testStrokeCoversMidpoint :: IO ()-testStrokeCoversMidpoint = do+testDiagramOps :: IO ()+testDiagramOps = do   let-    col = themeRed defaultTheme-    ops = strokePolyline col 2 False [(0, 0), (20, 0), (20, 20)]-    tris =-      [ ((x0, y0), (x1, y1), (x2, y2))-      | FillTriangle x0 y0 x1 y1 x2 y2 _ <- ops-      ]-    covered p = any (inTri p) tris-  unless (covered (10, 0) && covered (1, 0) && covered (20, 10)) $-    fail "stroke polyline left a gap along the segment"--inTri ::-  (Float, Float) -> ((Float, Float), (Float, Float), (Float, Float)) -> Bool-inTri p (a, b, c) =+    fills d = [op | op <- diaOps (d # D.fc coral # D.lw D.none), isFill op]+    isFill = \case+      FillRect {} -> True+      FillPolygon {} -> True+      _ -> False+  require "a level rectangle is not one rect op" $ case fills (D.rect 4 2) of+    [FillRect {}] -> True+    _ -> False+  require "a turned rectangle is not one polygon" $ case fills (D.rect 4 2 # D.rotateBy (1 / 8)) of+    [FillPolygon {}] -> True+    _ -> False+  -- Colours are straight alpha, whether the alpha is the colour's or the opacity's.   let-    s = triArea a b c-    s' = triArea p b c + triArea a p c + triArea a b p-   in-    s > 1e-6 && abs (s' - s) <= 1e-3--testNiceTicks :: IO ()-testNiceTicks = do+    fillsOf d = mapMaybe inkColor (diaOps (d # D.lw D.none))+    halfRed = colorRGBA 255 0 0 128+  require "a translucent fill was darkened" (fillsOf (D.circle 1 # D.fcA (red `withOpacity` 0.5)) == [halfRed])+  require "opacity did not reach the fill" (fillsOf (D.circle 1 # D.fc red # D.opacity 0.5) == [halfRed])+  -- A path's loops fill together. The inner circle is a hole under even-odd,+  -- or under winding when reversed; with the same direction it is filled.   let-    t0 = niceTicks 6 (Domain 0 100)-    t1 = niceTicks 6 (Domain (-5) 5)-  unless-    ( maybe False (<= 0) (listToMaybe t0)-        && maybe False (>= 100) (listToMaybe (reverse t0))-    ) $-    fail "nice ticks failed for [0,100]"-  unless (any (== 0) t1) $-    fail "nice ticks failed for [-5,5]"-  unless (formatTick 6 == "6") $-    fail "formatTick integer"-  unless (formatTick 0.2 == "0.2" && formatTick 0.4 == "0.4") $-    fail "formatTick fractional"-  unless (formatTick (0.2 + 0.2 + 0.2) == "0.6") $-    fail "formatTick binary residue"-  unless (formatTick 0.0008 == "0.0008") $-    fail "formatTick small decimal"-  unless (formatTick 1e308 == "1.000e308" && formatTick (-1e308) == "-1.000e308") $-    fail "formatTick overflowed while snapping a finite value"-  unless-    ( niceTicks 6 (Domain (-1e308) 1e308) == []-        && niceTicks 6 (Domain 1e308 1e308) == [1e308]-        && niceTicks 0 (Domain 0 100) == []-    )-    $ fail "niceTicks failed on overflowing, singleton, or empty-budget domains"+    ringsOf d = [sizeofPrimArray rings - 1 | FillPolygon _ rings _ _ <- diaOps (d # D.fc coral # D.lw D.none)]+    annulus :: D.Path D.V2 Double+    annulus = D.circle 2 <> D.circle 1+  require "even-odd annulus lost its hole" (ringsOf (D.strokeP annulus # D.fillRule D.EvenOdd) == [2])+  require "winding annulus lost its hole" (ringsOf (D.strokeP (D.circle 2 <> D.reversePath (D.circle 1))) == [2])+  require "winding annulus cut a hole" (ringsOf (D.strokeP annulus) == [1])+  let+    strokes d = [(cap, join) | StrokePolyline _ _ _ cap join _ _ <- diaOps (d # D.lc steelblue)]+    zigzag = D.fromVertices [D.p2 (0, 0), D.p2 (1, 0), D.p2 (1, 1)] :: Diagram B+  require "a line's cap and join were not the style's" $+    strokes (zigzag # D.lineCap D.LineCapRound # D.lineJoin D.LineJoinRound) == [(P.RoundCap, P.RoundJoin)]+  require "a line's default cap and join changed" (strokes zigzag == [(P.ButtCap, P.MiterJoin)])+  require "a dashed line was not cut into dashes" (length (strokes (zigzag # D.dashingO [4, 4] 0)) > 4) -testMultiSeriesDomains :: IO ()-testMultiSeriesDomains = do+testTicks :: IO ()+testTicks = do   let-    s1 = line "a" (V.fromList [(0, 0), (1, 1)])-    s2 = line "b" [(0, 10), (1, 20)]-    (Domain xLo xHi, Domain yLo yHi) = seriesDomains (bareChart [s1, s2])-  unless (yLo <= 0 && yHi >= 20 && xLo <= 0 && xHi >= 1) $-    fail "multi-series domains do not share bounds"-  unless (mergeDomains (Domain 0 1) (Domain 0 10) == Domain 0 10) $-    fail "mergeDomains broken"+    t0 = niceTicks 6 (Domain 0 100)+    labels d = map snd (niceTickLabels 6 d)+  require "nice ticks failed for [0,100]" (fmap (<= 0) (listToMaybe t0) == Just True && fmap (>= 100) (listToMaybe (reverse t0)) == Just True)+  require "nice ticks failed for [-5,5]" (0 `elem` niceTicks 6 (Domain (-5) 5))+  require "niceTicks failed on overflowing, singleton, or empty-budget domains" $+    niceTicks 6 (Domain (-1e308) 1e308) == []+      && niceTicks 6 (Domain 1e308 1e308) == [1e308]+      && niceTicks 0 (Domain 0 100) == []+  -- Values snap only after choosing their form, and never overflow.+  forM_+    [ (6, "6"), (0.2, "0.2"), (0.2 + 0.2 + 0.2, "0.6"), (0.0008, "0.0008"), (1.5e-10, "1.500e-10")+    , (1e308, "1.000e308"), (-1e308, "-1.000e308")+    ]+    $ \(v, want) -> require ("formatTick " <> show v) (formatTick v == want)+  require "tick labels carry noise or spare digits" $+    labels (Domain 0 1) == ["0", "0.2", "0.4", "0.6", "0.8", "1"]+      && labels (Domain 1e-8 5e-8) == ["1e-8", "2e-8", "3e-8", "4e-8", "5e-8"]+      && labels (Domain 1700000000 1700086400) == ["1.7e9", "1.70002e9", "1.70004e9", "1.70006e9", "1.70008e9"]+  -- Neighbouring y labels differ however fine the step or large the values'+  -- common offset, as for Unix time over one day.   let-    (Domain fitXLo _, Domain fitYLo _) = seriesDomains (bareChart [scatter "s" [(4, 3), (9, 8)]])-  unless (fitXLo > 2 && fitYLo > 1) $-    fail "seriesDomains seeded with 0..1"+    yLabels pts = [t | DrawText _ _ 1 _ t _ <- chartOps 400 240 (bareChart [line "s" pts])]+    distinct ts = length ts >= 3 && length (nub ts) == length ts+  require "fine ticks lost their digits" (distinct (yLabels [(0, 1), (1, 1.0000004)]))+  require "a large offset hid the ticks' step" (distinct (yLabels [(0, 1700000000), (1, 1700086400)])) -testLttb :: IO ()-testLttb = do+-- | Series share bounds; an area's reaches its baseline. Empty series, flat+-- lines and values that are not finite leave the others' span alone.+testDomains :: IO ()+testDomains = do   let-    pts =-      V.fromList-        [(fromIntegral i, sin (fromIntegral i / 10)) | i <- [0 .. 9999 :: Int]]-    out = lttb 500 pts-  unless (V.length out == 500) $-    fail "LTTB did not downsample to target count"+    nan = 0 / 0+    finite x = not (isNaN x || isInfinite x)+    domains msg ok ss = require msg (ok (seriesDomains (bareChart ss)))+    yDomain msg ok = domains msg (ok . snd)+  domains "multi-series domains do not share bounds" (\(Domain xl xh, Domain yl yh) -> yl <= 0 && yh >= 20 && xl <= 0 && xh >= 1) $+    [line "a" (V.fromList [(0, 0), (1, 1)]), line "b" [(0, 10), (1, 20)]]+  domains "seriesDomains seeded with 0..1" (\(Domain xl _, Domain yl _) -> xl > 2 && yl > 1) [scatter "s" [(4, 3), (9, 8)]]+  yDomain "a constant series widened the shared domain" (\(Domain lo hi) -> lo > 0.09 && hi < 0.16) $+    [line "p" [(0, 0.10), (1, 0.15)], line "target" [(0, 0.12), (1, 0.12)]]+  domains "an empty series pulled the shared domain to zero" (\(Domain xl _, Domain yl _) -> xl > 900 && yl > 900) $+    [line "a" [(1000, 1000), (2000, 2000)], line "b" []]+  yDomain "an area's baseline is outside its y domain" (\(Domain lo hi) -> lo <= 0 && hi >= 60) $+    [area "a" [(0, 50), (1, 55), (2, 60)]]+  yDomain "a baseline above an area is outside its y domain" (\(Domain _ hi) -> hi >= 80) $+    [withBaseline 80 (area "a" [(0, 50), (1, 60)])]+  yDomain "an empty area pulled the shared domain to its baseline" (\(Domain lo _) -> lo > 900) $+    [line "a" [(0, 1000), (1, 2000)], area "b" []]+  yDomain "a NaN baseline reached the y domain" (\(Domain lo hi) -> lo > 40 && hi < 70) $+    [withBaseline nan (area "a" [(0, 50), (1, 60)])]+  yDomain "a NaN dropped the domain's earlier minimum" (\(Domain lo _) -> lo <= -100) $+    [line "s" [(0, -100), (1, nan), (2, 5), (3, 6)]]+  domains "an infinite value made the domain infinite" (\(Domain a b, Domain c d) -> all finite [a, b, c, d] && d >= 3) $+    [line "s" [(0, 1), (1, 1 / 0), (2, 3)]]+  -- Hover and drawing skip a NaN too.   let-    ys = toList (V.map snd out)-  unless (minimum ys < -0.5 && maximum ys > 0.5) $-    fail "LTTB lost waveform extrema"+    holes = bareChart [line "s" [(0, 0), (1, nan), (2, 10)]]+    hovered = nearestPlotHover (seriesDomains holes) (map (seriesPoints holes) (chartSeries holes)) 0.05 0.05+  require "hover picked a point past a NaN" (fmap hoverDataX hovered == Just 0)+  require "a NaN point reached the drawing" $+    all (all finite . primArrayToList) [p | StrokePolyline p _ _ _ _ _ _ <- chartOps 200 120 holes]++testDecimation :: IO ()+testDecimation = do   let-    spike = V.fromList [(x, if x == 1 then 10 else 0) | x <- [0 .. 9]]-  unless (lttb 3 spike == V.fromList [(0, 0), (1, 10), (9, 0)]) $-    fail "LTTB skipped the first bucket's spike"+    wave = V.fromList [(fromIntegral i, sin (fromIntegral i / 10)) | i <- [0 .. 9999 :: Int]]+    ys = toList (V.map snd (lttb 500 wave))+    ordered ps = V.and (V.zipWith (\a b -> fst a < fst b) ps (V.drop 1 ps))+  require "LTTB lost its target count or waveform extrema" (length ys == 500 && minimum ys < -0.5 && maximum ys > 0.5)+  require "LTTB skipped the first bucket's spike" $+    lttb 3 (V.fromList [(x, if x == 1 then 10 else 0) | x <- [0 .. 9]]) == V.fromList [(0, 0), (1, 10), (9, 0)]+  require "min/max decimation changed equal-extrema tie handling" $+    minMaxDecimate 1 (V.fromList [(0, 2), (1, 2), (2, 2)]) == V.singleton (0, 2)+  require "min/max decimation lost extrema or reversed their order" $+    minMaxDecimate 2 (V.fromList [(x, 9 - x) | x <- [0 .. 8]]) == V.fromList [(0, 9), (4, 5), (5, 4), (8, 1)]   forM_ [0 .. 60] $ \n -> forM_ [-1 .. n + 1] $ \k -> do     let       input = V.generate n (\i -> (fromIntegral i, sin (fromIntegral i)))       sampled = lttb k input-    unless (V.length sampled == min n (max 0 k) && orderedPoints sampled) $-      fail "LTTB violated its point budget or input order"-    unless (V.null sampled || V.head sampled == V.head input) $-      fail "LTTB lost the first endpoint"-    unless (V.length sampled < 2 || V.last sampled == V.last input) $-      fail "LTTB lost the last endpoint"--testMinMaxDecimate :: IO ()-testMinMaxDecimate = do-  unless-    (minMaxDecimate 1 (V.fromList [(0, 2), (1, 2), (2, 2)]) == V.singleton (0, 2)) $-    fail "min/max decimation changed equal-extrema tie handling"+      kept = minMaxDecimate k input+      extremes ps = (V.minimum (V.map snd ps), V.maximum (V.map snd ps))+    require "LTTB violated its point budget or input order" (V.length sampled == min n (max 0 k) && ordered sampled)+    require "LTTB lost an endpoint" $+      (V.null sampled || V.head sampled == V.head input) && (V.length sampled < 2 || V.last sampled == V.last input)+    require "min/max decimation violated its budget or input order" (V.length kept <= max 0 (2 * k) && ordered kept)+    require "min/max decimation invented a point" (V.all (`V.elem` input) kept)+    require "min/max decimation lost a global extremum" (V.null kept || extremes input == extremes kept)+  -- Default decimation thins a long line, but keeps every marker of a+  -- scatter or a marked line up to 2000: a dropped marker is simply missing.   let-    descending = V.fromList [(x, 9 - x) | x <- [0 .. 8]]-  unless-    (minMaxDecimate 2 descending == V.fromList [(0, 9), (4, 5), (5, 4), (8, 1)]) $-    fail "min/max decimation lost extrema or reversed their order"-  forM_ [0 .. 60] $ \n -> forM_ [-1 .. n + 1] $ \k -> do-    let-      input = V.generate n (\i -> (fromIntegral i, sin (fromIntegral i)))-      sampled = minMaxDecimate k input-    unless (V.length sampled <= max 0 (2 * k) && orderedPoints sampled) $-      fail "min/max decimation violated its bucket budget or input order"-    unless (V.all (`V.elem` input) sampled) $-      fail "min/max decimation invented a point"-    unless-      ( V.null sampled-          || ( V.minimum (V.map snd input) == V.minimum (V.map snd sampled)-                 && V.maximum (V.map snd input) == V.maximum (V.map snd sampled)-             )-      )-      $ fail "min/max decimation lost a global extremum"+    pts n = [(fromIntegral i, sin (fromIntegral i)) | i <- [0 .. n - 1 :: Int]]+    drawn s = U.length (seriesPoints (chart [s]) s)+  require "decimation did not thin a long line" (drawn (line "l" (pts 100)) < 100)+  require "decimation thinned a scatter series" (drawn (scatter "s" (pts 100)) == 100)+  require "decimation thinned a marked line" (drawn (withMarker MarkCircle (line "l" (pts 100))) == 100)+  require "decimation kept every point of a huge scatter" (drawn (scatter "s" (pts 5000)) == 2000) -orderedPoints :: V.Vector (Double, Double) -> Bool-orderedPoints points = V.and (V.zipWith (\a b -> fst a < fst b) points (V.drop 1 points))+barChartSample :: Chart+barChartSample =+  (bareChart [bar "count" [("Mon", 2), ("Tue", 5), ("Wed", 4), ("Thu", 7), ("Fri", 3)]])+    { chartXTitle = Just "day"+    , chartYTitle = Just "count"+    , chartLegend = LegendRight+    , chartGrid = GridBoth+    } -testLabelFit :: FontMetrics -> IO ()-testLabelFit fm = do+-- | Each label drawn, with its box.+textBoxes :: [DrawOp] -> [(T.Text, Rect)]+textBoxes ops = [(t, drawTextBox fm x y ax ay t) | DrawText x y ax ay t _ <- ops]++testLabelFit :: IO ()+testLabelFit = do   let-    dump = chartDia fm barChartSample-    fitted = fitLayout fm (fixedH 180 defaultLayout) dump-    ops =-      case (layoutWidth fitted, layoutHeight fitted) of-        (Fixed bw, Fixed bh) -> diagramOps (realToFrac bw) (realToFrac bh) dump-        _ -> emptySmallArray-    texts = [(x, y, ax, ay, t) | DrawText x y ax ay t _ <- toList ops]-    xs = [x | (x, _, _, _, _) <- texts]-    boxes = [drawTextBox fm x y ax ay t | (x, y, ax, ay, t) <- texts]-  unless (length xs >= 3 && maximum xs - minimum xs > 20) $-    fail "axis labels did not spread along x"-  unless (not (or [rectsOverlap a b | (a : rest) <- tails boxes, b <- rest])) $-    fail "axis label boxes overlap"+    -- Tall enough for the fit, at most twice the size, to part five+    -- three-letter days in glyphs as wide as they are high.+    fitted = fitLayout fm (fixedH 200 defaultLayout) (chartDia barChartSample)+    boxes = case (layoutWidth fitted, layoutHeight fitted) of+      (Fixed bw, Fixed bh) -> map snd (textBoxes (chartOps bw bh barChartSample))+      _ -> []+    xs = [x | Rect x _ _ _ <- boxes]+  require "axis labels did not spread along x" (length xs >= 3 && maximum xs - minimum xs > 20)+  require "axis label boxes overlap" (not (or [rectsOverlap a b | (a : rest) <- tails boxes, b <- rest]))   let     sleepChart =       (bareChart [scatter "focus" [(4, 3), (9, 8)], line "trend" [(4, 3), (9, 8)]])@@ -352,154 +315,169 @@         , chartYTitle = Just "focus"         , chartXTitle = Just "hours slept"         }-    legendDump = chartDia fm sleepChart-    legendOps = diagramOps 400 240 legendDump-    tightOps = diagramOps 220 150 legendDump-    barTightOps = diagramOps 220 150 dump     botChart = sleepChart {chartLegend = LegendBottom}-    botOps = diagramOps 400 240 (chartDia fm botChart)-    tickText t =-      T.all (\c -> c == '-' || c == '.' || c >= '0' && c <= '9') t && not (T.null t)-    overlapTitleTick chart w h drawOps =-      let-        ts =-          [(drawTextBox fm x y ax ay t, t) | DrawText x y ax ay t _ <- toList drawOps]-        titles =-          [ b-          | (b@(Rect bx by _ _), t) <- ts-          , (chartXTitle chart == Just t && by < h * 0.45)-              || (chartYTitle chart == Just t && bx < w * 0.4)-          ]-        ticks = [b | (b, t) <- ts, tickText t]-       in-        or [rectsOverlap a b | a <- titles, b <- ticks]-    overlapLegendTick chart w h drawOps =-      let-        names = map seriesName (chartSeries chart)-        ts =-          [(drawTextBox fm x y ax ay t, t) | DrawText x y ax ay t _ <- toList drawOps]-        legends =-          [ b-          | (b@(Rect bx by _ _), t) <- ts-          , t `elem` names-          , case chartLegend chart of-              LegendRight -> bx > w * 0.55-              LegendBottom -> by < h * 0.45-              _ -> False-          ]-        ticks = [b | (b, t) <- ts, tickText t]-       in-        or [rectsOverlap a b | a <- legends, b <- ticks]-  unless (not (overlapTitleTick sleepChart 400 240 legendOps)) $-    fail "axis titles overlap ticks"-  unless (not (overlapLegendTick sleepChart 400 240 legendOps)) $-    fail "legend overlaps ticks"-  unless (not (overlapTitleTick sleepChart 220 150 tightOps)) $-    fail "axis titles overlap ticks on a small plot"-  unless (not (overlapTitleTick barChartSample 220 150 barTightOps)) $-    fail "bar axis titles overlap ticks on a small plot"-  unless (not (overlapTitleTick botChart 400 240 botOps)) $-    fail "axis titles overlap ticks with bottom legend"-  unless (not (overlapLegendTick botChart 400 240 botOps)) $-    fail "bottom legend overlaps ticks"+    tickText t = not (T.null t) && T.all (\c -> c == '-' || c == '.' || c >= '0' && c <= '9') t+    -- Whether a label selected by @picks@ overlaps a tick label.+    overlapsTicks c w h picks =+      let ts = textBoxes (chartOps w h c)+       in or [rectsOverlap a b | (t, a) <- ts, picks a t, (t', b) <- ts, tickText t']+    titleOverlaps c w h = overlapsTicks c w h $ \(Rect bx by _ _) t ->+      (chartXTitle c == Just t && by > h * 0.55) || (chartYTitle c == Just t && bx < w * 0.4)+    legendOverlaps c w h = overlapsTicks c w h $ \(Rect bx by _ _) t ->+      t `elem` map seriesName (chartSeries c) && case chartLegend c of+        LegendRight -> bx > w * 0.55+        LegendBottom -> by > h * 0.55+        _ -> False+  forM_ [(sleepChart, 400, 240), (sleepChart, 220, 150), (barChartSample, 220, 150), (botChart, 400, 240)] $+    \(c, w, h) -> require ("axis titles overlap ticks at " <> show (w, h)) (not (titleOverlaps c w h))+  forM_ [sleepChart, botChart] $ \c -> require "legend overlaps ticks" (not (legendOverlaps c 400 240))+  -- A top legend has a row of its own, under the title and inside the+  -- drawing, also where the drawing is as tall as its box.   let-    shortTitles =-      (bareChart [line "sin(x)" [(0, 0), (1, 1)]])-        { chartLegend = LegendRight-        , chartYTitle = Just "y"-        , chartXTitle = Just "x"-        }-    shortM = chartMargins fm shortTitles-  unless (marginLeft shortM < 0.85 && marginBottom shortM < 0.65) $-    fail "short axis titles left a huge gutter"--barChartSample :: Chart-barChartSample =-  (bareChart [bar "count" [("Mon", 2), ("Tue", 5), ("Wed", 4), ("Thu", 7), ("Fri", 3)]])-    { chartXTitle = Just "day"-    , chartYTitle = Just "count"-    , chartLegend = LegendRight-    , chartGrid = GridBoth-    }--testPlotHover :: IO ()-testPlotHover = do-  let hoverAt c = nearestPlotHover (seriesDomains c) (map (seriesPoints c) (chartSeries c)) 0.5 0.5-  forM_ [bareChart [], bareChart [line "empty" []]] $ \chart ->-    unless (hoverAt chart == Nothing) $-      fail "empty chart produced a hover target"+    topChart = (bareChart [line "in" [(0, 20), (1, 22)], line "out" [(0, 8), (1, 14)]]) {chartLegend = LegendTop}+    titled = topChart {chartTitle = Just "Temperature"}+    named ns c h = [b | (t, b) <- textBoxes (chartOps 400 h c), t `elem` ns]+    entries = named ["in", "out"]+  require "top legend overlaps the title" $+    not (or [rectsOverlap a b | a <- named ["Temperature"] titled 240, b <- entries titled 240])+  require "top legend spills above the drawing" $+    all (\(Rect _ y _ _) -> y >= 0) (entries topChart 150 ++ entries titled 150)   let-    tied = bareChart [line "first" [(0, 0), (0, 0)], line "second" [(0, 0)]]-  unless-    ( fmap (\h -> (hoverSeriesIdx h, hoverPointIdx h)) (hoverAt tied)-        == Just (0, 0)-    ) $-    fail "equidistant hover targets did not prefer the first point"-  case hoverAt (bareChart [line "a" [(0, 0), (1, 1), (2, 4)]]) of-    Nothing -> fail "nearestPlotHover missed center point"-    Just h ->-      unless-        ( hoverSeriesIdx h == 0-            && hoverPointIdx h == 1-            && hoverDataX h == 1-            && hoverDataY h == 1-        ) $-        fail "nearestPlotHover picked wrong point"+    shortTitles = (bareChart [line "sin(x)" [(0, 0), (1, 1)]]) {chartYTitle = Just "y", chartXTitle = Just "x"}+    shortM = chartMargins fm shortTitles {chartLegend = LegendRight}+  require "short axis titles left a huge gutter" (marginLeft shortM < 0.85 && marginBottom shortM < 0.65) --- Empty series isolate the legend strokes from data geometry. Every placement--- must retain the labels and use the same color overrides as the series.-testLegendColors :: FontMetrics -> IO ()-testLegendColors fm = do+-- | Empty series isolate the legend strokes from data geometry. Every+-- placement keeps the labels and the series' colour overrides.+testLegendColors :: IO ()+testLegendColors = do   let     custom = colorRGBA 17 211 83 255-    chart = bareChart [withColor custom (line "custom" []), line "default" []]     fallback = themeSeries defaultTheme !! 1+    legendChart = bareChart [withColor custom (line "custom" []), line "default" []]   forM_ [LegendNone, LegendRight, LegendBottom, LegendTop, LegendInside] $ \position -> do     let-      ops = toList (diagramOps 400 280 (chartDia fm chart {chartLegend = position}))-      labels =-        [text | DrawText _ _ _ _ text _ <- ops, text == "custom" || text == "default"]-      colors = [color | FillTriangle _ _ _ _ _ _ color <- ops]+      ops = chartOps 400 280 legendChart {chartLegend = position}+      labels = [t | DrawText _ _ _ _ t _ <- ops, t `elem` ["custom", "default"]]+      colors = mapMaybe inkColor ops     if position == LegendNone-      then-        unless (null labels && custom `notElem` colors) $-          fail "hidden legend rendered entries"+      then require "hidden legend rendered entries" (null labels && custom `notElem` colors)       else do-        unless (length labels == 2 && "custom" `elem` labels && "default" `elem` labels) $-          fail "legend lost or duplicated a series label"-        unless (custom `elem` colors && fallback `elem` colors) $-          fail "legend colors differ from series colors"+        require "legend lost or duplicated a series label" (length labels == 2 && nub labels == labels)+        require "legend colors differ from series colors" (custom `elem` colors && fallback `elem` colors) -fillTriCount :: SmallArray DrawOp -> Int-fillTriCount ops = length [() | FillTriangle {} <- toList ops]+testPlotHover :: IO ()+testPlotHover = do+  let+    hoverAt c = nearestPlotHover (seriesDomains c) (map (seriesPoints c) (chartSeries c))+    centre c = hoverAt c 0.5 0.5+    picked = fmap (\h -> (hoverSeriesIdx h, hoverPointIdx h, hoverDataX h, hoverDataY h)) . centre . bareChart+  forM_ [bareChart [], bareChart [line "empty" []]] $ \c ->+    require "empty chart produced a hover target" (centre c == Nothing)+  require "equidistant hover targets did not prefer the first point" $+    picked [line "first" [(0, 0), (0, 0)], line "second" [(0, 0)]] == Just (0, 0, 0, 0)+  require "nearestPlotHover picked wrong point" (picked [line "a" [(0, 0), (1, 1), (2, 4)]] == Just (0, 1, 1, 1))+  -- Just above the first point, the second is far off on screen but nearer+  -- in data units, where y spans a thousand times x.+  let+    spread = bareChart [scatter "s" [(0.1, 500), (0.9, 505), (0, 0), (1, 1000)]]+    (xDom, yDom) = seriesDomains spread+  require "hover picked a point far away on screen" $+    fmap hoverPointIdx (hoverAt spread (domainToPlot xDom 0.1) (domainToPlot yDom 510)) == Just 0 -testClosedSeriesFills :: FontMetrics -> IO ()-testClosedSeriesFills fm = do+-- | Series shapes sit where their data is: an area starts at the line+-- through the same samples, markers centre on their points, a step ends on+-- its last point, and bars stand on zero under their category names.+testSeriesShapes :: IO ()+testSeriesShapes = do   let-    seriesOps s = diagramOps 200 120 (chartDia fm (bareChart [s]))-    areaOps = seriesOps (area "a" [(0, 1), (1, 2), (2, 0)])-    diamondOps = seriesOps (withMarker MarkDiamond (scatter "d" [(1, 1), (2, 3)]))-    triOps = seriesOps (withMarker MarkTriangle (scatter "t" [(1, 1)]))-    crossOps = seriesOps (withMarker MarkCross (scatter "x" [(8, 8)]))-    ink = fromMaybe (themeRed defaultTheme) (listToMaybe (themeSeries defaultTheme))-    inkXs =-      [ x-      | FillTriangle x0 _ x1 _ x2 _ c <- toList crossOps-      , c == ink-      , x <- [x0, x1, x2]-      ]-  unless (fillTriCount areaOps >= 2) $-    fail "area series produced no fill triangles"-  unless (fillTriCount diamondOps >= 2) $-    fail "diamond marker produced no fill"-  unless (fillTriCount triOps >= 1) $-    fail "triangle marker produced no fill"-  unless (not (null inkXs) && maximum inkXs - minimum inkXs < 40) $-    fail "MarkCross arm left at origin"+    samples = [(x, 1 + sin x) | x <- [0, 0.5 .. 10]]+    ops = chartOps 200 120 (bareChart [area "a" samples, line "l" samples, withMarker MarkDiamond (scatter "d" samples)])+    near (x0, y0) (x1, y1) = abs (x1 - x0) < 1e-3 && abs (y1 - y0) < 1e-3+    centre ps = (sum (map fst ps) / fromIntegral (length ps), sum (map snd ps) / fromIntegral (length ps))+    linePts = [pointsOf p | StrokePolyline p _ _ _ _ _ _ <- ops, sizeofPrimArray p == 2 * length samples]+    areaPts = [pointsOf p | FillPolygon p _ _ _ <- ops, sizeofPrimArray p > 8]+    diamonds = [centre (pointsOf p) | FillPolygon p _ _ _ <- ops, sizeofPrimArray p == 8]+  case (linePts, areaPts) of+    ([l@(start : _)], [area0 : _]) -> do+      require "area does not start at its first sample" (near start area0)+      require "diamond markers are not centred on their points" $+        length diamonds == length l && all (\d -> any (near d) l) diamonds+    _ -> fail ("expected one line and one area, got " <> show (length linePts, length areaPts))+  let+    -- The points of each fill and each stroke in the series colour.+    fills s = [pointsOf p | op@(FillPolygon p _ _ _) <- chartOps 200 120 (bareChart [s]), inkColor op == Just seriesInk]+    strokes s = [pointsOf p | op@(StrokePolyline p _ _ _ _ _ _) <- chartOps 200 120 (bareChart [s]), inkColor op == Just seriesInk]+    cross = withMarker MarkCross (scatter "x" [(8, 8)])+    crossXs = map fst (concat (fills cross ++ strokes cross))+    lineMarkers = filter ((== 4) . length) (fills (withMarker MarkDiamond (line "l" [(0, 0), (1, 1), (2, 0)])))+    triangles = [t | FillPolygon _ _ t _ <- chartOps 200 120 (bareChart [withMarker MarkTriangle (scatter "t" [(1, 1)])])]+  require "triangle marker produced no fill" (sum (map sizeofPrimArray triangles) >= 3)+  require "MarkCross arm left at origin" (not (null crossXs) && maximum crossXs - minimum crossXs < 40)+  require "line markers were not drawn" (length lineMarkers == 3)+  -- A step series ends with the riser to its last point, the highest here.+  require "step series stopped short of its last point" $ case map (map snd) (strokes (step "s" [(0, 0), (1, 1), (2, 5)])) of+    [path] -> length path == 5 && last path == minimum path+    _ -> False+  let+    days = ["Mon", "Tue", "Wed", "Thu", "Fri"]+    barOps = chartOps 400 240 (bareChart [bar "count" (zip days [2, 5, 4, 7, 3])])+    -- A y tick label is right-aligned, level with its tick.+    tickY t = listToMaybe [y | DrawText _ y 1 _ t' _ <- barOps, t' == t]+    bars = map snd (sortOn fst [(rectX r, (rectY r, rectY r + rectH r)) | FillRect r c <- barOps, c == seriesInk])+    close a b = abs (a - b) < 0.5+  require "bar categories are not on the x axis" (all (`elem` [t | DrawText _ _ _ _ t _ <- barOps]) days)+  require "bars disagree with the y axis" $ case (tickY "0", tickY "2", tickY "4", bars) of+    (Just y0, Just y2, Just y4, [(top2, _), _, (top4, _), _, _]) ->+      all (close y0 . snd) bars && close top2 y2 && close top4 y4+    _ -> False -testGrowPlotHeight :: FontMetrics -> IO ()-testGrowPlotHeight fm = do+-- | An area series fills a ring per run of samples on one side of its+-- baseline, split where the data crosses it: the samples and the baseline's+-- two ends, triangulated into as many triangles as the ring has sides less+-- two, covering it exactly.+testAreaRings :: IO ()+testAreaRings = do   let-    fitted = fitLayout fm (fillW defaultLayout) (chartDia fm barChartSample)-  unless (layoutMinH fitted <= 260 && layoutMaxH fitted <= 260) $-    fail "plot grow height ballooned"+    rings samples = [(p, t) | FillPolygon p _ t _ <- chartOps 200 120 (bareChart [area "a" samples])]+    triArea ((x0, y0), (x1, y1), (x2, y2)) = abs ((x0 - x2) * (y1 - y0) - (x0 - x1) * (y2 - y0)) * 0.5+    exact (p, t) =+      let+        at k = pointsOf p !! indexPrimArray t k+        tris = [(at k, at (k + 1), at (k + 2)) | k <- [0, 3 .. sizeofPrimArray t - 3]]+        ps = pointsOf p+        want = abs (sum [x * y' - x' * y | ((x, y), (x', y')) <- zip ps (drop 1 (cycle ps))]) / 2+       in+        length tris == length ps - 2 && abs (sum (map triArea tris) - want) <= 1e-3 * want+    above = [(x, 1 + sin x) | x <- [0, 0.5 .. 10]]+    -- sin crosses its baseline at pi, 2 pi and 3 pi.+    crossing = [(x, sin x) | x <- [0, 0.5 .. 10]]+  case rings above of+    [r@(p, _)] -> do+      require "area ring has more than its samples and the baseline's ends" (sizeofPrimArray p `div` 2 <= length above + 2)+      require "area triangles do not cover their ring" (exact r)+    polys -> fail ("expected one area polygon, got " <> show (length polys))+  require "crossing area is not a ring per side" (length (rings crossing) == 4)+  require "crossing area triangles do not cover their rings" (all exact (rings crossing))++-- | A growing plot's height is capped, but the caller's own height holds. A+-- diagram with no width, such as a vertical rule, takes the caller's box.+testFit :: IO ()+testFit = do+  let+    fittedWith f = fitLayout fm (f defaultLayout) (chartDia barChartSample)+    heights f = let l = fittedWith f in (layoutMinH l, layoutMaxH l)+    (grownMin, grownMax) = heights fillW+  require "plot grow height ballooned" (grownMin <= 260 && grownMax <= 260)+  require "a growing plot capped a taller minimum" (fst (heights (fillW . minH 300)) >= 300)+  require "a growing plot lost its fixed height" (heights (fillW . fixedH 400) == (400, 400))+  -- Too short for the labels, which would otherwise enlarge it.+  require "a growing plot lost a fixed height under the cap" (heights (fillW . fixedH 100) == (100, 100))+  require "a growing plot stopped growing in height" $ case layoutHeight (fittedWith grow) of+    Grow _ -> True+    _ -> False+  let+    rule = D.vrule 50 :: Diagram B+    boxed = fitLayout fm (fixedWH 200 100 defaultLayout) rule+  require "a fixed width made a rule infinitely tall" (layoutMaxH (fitLayout fm (fixedW 200 defaultLayout) rule) < 1e6)+  require "a fixed box lost its width for a rule" (layoutMinW boxed == 200 && layoutMaxW boxed == 200)