packages feed

nano-ui-svg (empty) → 0.2.0.0

raw patch · 23 files changed

+6305/−0 lines, 23 filesdep +basedep +bytestringdep +containers

Dependencies added: base, bytestring, containers, diagrams-lib, directory, lucid2, microaeson, nano-ui, nano-ui-diagrams, nano-ui-sdl, nano-ui-svg, nano-ui-ttf, primitive, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,9 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- `NanoUI.Draw.Svg` (`SvgConfig`, `defaultSvgConfig`, `renderDrawOpsSvg`, `drawOpsToSvg`) exports `SmallArray DrawOp` draw lists to standalone SVG.+- `NanoUI.Draw.FrameSvg` (`FrameSvgConfig`, `defaultFrameSvgConfig`, `enableSvgExport`, `frameToSvg`) exports complete painted `nano-ui` frames to SVG, including clip-cut geometry, vector drawings, fitted `<text>` elements, image URI resolution, and native `<g opacity>` output for opacity shaders.+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 goolord++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ README.md view
@@ -0,0 +1,46 @@+# nano-ui-svg++SVG exporter for [nano-ui](https://github.com/goolord/nano-ui). Export raw `DrawOp` lists (from canvases, custom widgets, and `nano-ui-diagrams` charts) or full rendered frames of any UI view.++## Exporting draw ops++```haskell+import Data.Text (Text)+import NanoUI+import NanoUI.Draw.Svg (drawOpsToSvg)+import NanoUI.Path qualified as P+import NanoUI.Widgets.Custom (runCanvasFor)++badgeSvg :: CustomDrawContext -> Text+badgeSvg cdc = drawOpsToSvg bounds $ runCanvasFor cdc $ do+  drawRoundedRect bounds 8 (colorRGBA 37 99 235 255)+  drawStrokePath (P.circle (V2 20 20) 8) 2 colorWhite+  drawText (V2 68 20) AlignCenter AlignMiddle "Ready" colorWhite+  where+    bounds = Rect 0 0 120 40+```++For finer control, `renderDrawOpsSvg` takes an `SvgConfig`:++- `svgStandalone = False` emits an inline `<g>` fragment instead of a full `<svg>` document.+- `svgPrecision` caps coordinate decimal places.+- `svgImageUri` maps `ImageId` values to `href` URLs or data URIs (unmapped images are omitted).+- `svgIdPrefix` namespaces clip-path and gradient IDs so multiple SVGs can share one HTML page safely.++## Exporting entire UI frames++```haskell+import NanoUI.Draw.FrameSvg (defaultFrameSvgConfig, enableSvgExport, frameToSvg)++enableSvgExport ctx -- call once before running frames+(_, drawData, _) <- runFrame ctx inp view+svg <- frameToSvg defaultFrameSvgConfig ctx inp drawData+```++Normally, widgets paint straight into vertex buffers. Calling `enableSvgExport` tells the paint pass to also record vector shapes and text spans (`frameToSvg` fails if recording was not enabled).++Exported text aligns to the metrics measured during the frame. Headless contexts (`newPixelContext`) measure text on a 16 px monospace grid; wrap your frames in `withSdl` for TrueType metrics matching desktop builds.++## Documentation++- [The nano-ui Book: SVG export](https://goolord.github.io/nano-ui/book/packages/index.html#svg-export)
+ app/CanvasExamples.hs view
@@ -0,0 +1,318 @@+-- | Canvas examples for the book's Custom Drawing chapter. Each anchored+-- block is included in @book/src/widgets/custom-drawing.md@, and the glossary+-- generator renders the same definitions to @book/src/images/canvas/@, so the+-- code on the page is the code that drew the picture beside it.+--+-- Everything outside the anchors is annotation: the captioned cells, and the+-- thin guides (path points, the bounds a stroke is measured against, a+-- transform's starting shape) drawn over the examples.+module CanvasExamples (canvasExamples) where++import Control.Monad (void)+import Data.Foldable (for_)+import Data.Text (Text)+import NanoUI+import NanoUI.Internal.Path (Path (..), Segment (..))+-- ANCHOR: import_path+import NanoUI.Path qualified as P+-- ANCHOR_END: import_path++-- ANCHOR: palette+ink, blue, teal, amber, rose :: Color+ink = colorRGB 226 232 240+blue = colorRGB 59 130 246+teal = colorRGB 20 184 166+amber = colorRGB 245 158 11+rose = colorRGB 244 63 94++centre :: Rect -> V2+centre (Rect x y w h) = V2 (x + w / 2) (y + h / 2)+-- ANCHOR_END: palette++-- ANCHOR: badge+badge :: NanoUI ()+badge = void $ canvas (fixedWH 120 40) $ \r@(Rect x y _ h) -> do+  drawRoundedRect r 8 blue+  drawStrokePath (P.circle (V2 (x + 20) (y + h / 2)) 8) 2 colorWhite+  drawText (V2 (x + 68) (y + h / 2)) AlignCenter AlignMiddle "Ready" colorWhite+-- ANCHOR_END: badge++-- ANCHOR: primitives+primitives :: [(Text, Rect -> CanvasM ())]+primitives =+  [ ("drawRect", \r -> drawRect r blue)+  , ("drawRoundedRect", \r -> drawRoundedRect r 14 teal)+  , ("drawCircle", \r -> drawCircle (centre r) 28 amber)+  , ("drawStrokeCircle", \r -> drawStrokeCircle (centre r) 28 4 rose)+  , ("drawStrokeAA", \(Rect x y w h) -> drawStrokeAA (V2 x (y + h)) (V2 (x + w) y) 4 ink)+  , ("drawLinearGradientH", \r -> drawLinearGradientH r blue teal)+  , ("drawLinearGradientV", \r -> drawLinearGradientV r amber rose)+  , ("drawQuadGradient", \r -> drawQuadGradient r blue teal amber rose)+  ]+-- ANCHOR_END: primitives++-- ANCHOR: segments+segments :: [(Text, Rect -> P.Path)]+segments =+  [ ("lineTo", \(Rect x y w h) ->+      P.moveTo (V2 x (y + h)) <> P.lineTo (V2 (x + w / 2) y) <> P.lineTo (V2 (x + w) (y + h)))+  , ("quadTo", \(Rect x y w h) ->+      P.moveTo (V2 x (y + h)) <> P.quadTo (V2 (x + w / 2) (y - 12)) (V2 (x + w) (y + h)))+  , ("cubicTo", \(Rect x y w h) ->+      P.moveTo (V2 x (y + h)) <> P.cubicTo (V2 x y) (V2 (x + w) (y + h)) (V2 (x + w) y))+  , ("arc", \r -> P.arc (centre r) 28 0 (3 * pi / 2))+  , ("moveTo, arc, close", \r -> P.moveTo (centre r) <> P.arc (centre r) 28 0 (3 * pi / 2) <> P.close)+  ]+-- ANCHOR_END: segments++-- ANCHOR: shapes+shapes :: [(Text, Rect -> CanvasM ())]+shapes =+  [ ("rect", \r -> shape (P.rect r))+  , ("roundedRect", \r -> shape (P.roundedRect r 12))+  , ("roundedRectCorners", \r -> shape (P.roundedRectCorners r 24 4 24 4))+  , ("circle", \r -> shape (P.circle (centre r) 28))+  , ("ellipse", \r -> shape (P.ellipse (centre r) (V2 48 22)))+  , ("polygon", \(Rect x y w h) -> shape (P.polygon [V2 (x + w / 2) y, V2 (x + w) (y + h), V2 x (y + h)]))+  , ("polyline", \(Rect x y w h) ->+      drawStrokePath (P.polyline [V2 x (y + h), V2 (x + w / 3) y, V2 (x + 2 * w / 3) (y + h), V2 (x + w) y]) 2 blue)+  ]+  where+    shape p = drawPath p (withAlpha blue 0.35) >> drawStrokePath p 2 blue+-- ANCHOR_END: shapes++-- ANCHOR: fill_rules+fillRules :: [(Text, Rect -> CanvasM ())]+fillRules =+  [ ("NonZero", \r -> drawPathWith P.NonZero (rings r) (P.Solid teal))+  , ("NonZero, middle reversed", \r -> drawPathWith P.NonZero (reversedMiddle r) (P.Solid teal))+  , ("EvenOdd", \r -> drawPathWith P.EvenOdd (rings r) (P.Solid teal))+  ]+  where+    rings r = P.circle (centre r) 30 <> P.circle (centre r) 20 <> P.circle (centre r) 9+    -- A negative sweep runs the middle circle anticlockwise.+    reversedMiddle r@(Rect x y w h) =+      P.circle (centre r) 30+        <> P.moveTo (V2 (x + w / 2 + 20) (y + h / 2))+        <> P.arc (centre r) 20 0 (-2 * pi)+        <> P.close+        <> P.circle (centre r) 9+-- ANCHOR_END: fill_rules++-- ANCHOR: paints+paints :: [(Text, Rect -> CanvasM ())]+paints =+  [ ("Solid", \r -> drawPathWith P.NonZero (P.roundedRect r 10) (P.Solid blue))+  , ("Linear, two stops", \r@(Rect x y w _) ->+      drawPathWith P.NonZero (P.roundedRect r 10) (P.Linear (V2 x y) (V2 (x + w) y) [(0, blue), (1, teal)]))+  , ("Linear, short span", \r@(Rect x y w _) ->+      drawPathWith P.NonZero (P.roundedRect r 10) (P.Linear (V2 (x + w / 3) y) (V2 (x + 2 * w / 3) y) [(0, blue), (1, teal)]))+  , ("Linear, three stops", \r@(Rect x y w h) ->+      drawPathWith P.NonZero (P.circle (centre r) 30) (P.Linear (V2 x y) (V2 (x + w) (y + h)) [(0, amber), (0.5, rose), (1, blue)]))+  ]+-- ANCHOR_END: paints++-- ANCHOR: caps+capLine :: Rect -> P.Path+capLine (Rect x y w h) = P.moveTo (V2 (x + 16) (y + h / 2)) <> P.lineTo (V2 (x + w - 16) (y + h / 2))++caps :: [(Text, Rect -> CanvasM ())]+caps =+  [ (name, \r -> drawStrokePathWith (P.stroke 18) {P.strokeCap = cap} (capLine r) (P.Solid blue))+  | (name, cap) <- [("ButtCap", P.ButtCap), ("RoundCap", P.RoundCap), ("SquareCap", P.SquareCap)]+  ]+-- ANCHOR_END: caps++-- ANCHOR: joins+zigzag :: Rect -> P.Path+zigzag (Rect x y w h) = P.polyline [V2 (x + w / 4) (y + h - 4), V2 (x + w / 2) (y + 10), V2 (x + 3 * w / 4) (y + h - 4)]++joins :: [(Text, Rect -> CanvasM ())]+joins =+  [ ("MiterJoin", withJoin (P.stroke 14) {P.strokeJoin = P.MiterJoin})+  , ("RoundJoin", withJoin (P.stroke 14) {P.strokeJoin = P.RoundJoin})+  , ("BevelJoin", withJoin (P.stroke 14) {P.strokeJoin = P.BevelJoin})+  , ("strokeMiterLimit 1.5", withJoin (P.stroke 14) {P.strokeJoin = P.MiterJoin, P.strokeMiterLimit = 1.5})+  ]+  where+    withJoin st r = drawStrokePathWith st (zigzag r) (P.Solid teal)+-- ANCHOR_END: joins++-- ANCHOR: dashes+dashes :: [(Text, Rect -> CanvasM ())]+dashes =+  [ ("[12, 6]", dashed (P.stroke 4) {P.strokeDash = [12, 6]})+  , ("[12, 6], offset 9", dashed (P.stroke 4) {P.strokeDash = [12, 6], P.strokeDashOffset = 9})+  , ("[18, 5, 3, 5]", dashed (P.stroke 4) {P.strokeDash = [18, 5, 3, 5]})+  , ("[0, 10], RoundCap", dashed (P.stroke 6) {P.strokeDash = [0, 10], P.strokeCap = P.RoundCap})+  ]+  where+    dashed st r = drawStrokePathWith st (P.roundedRect r 12) (P.Solid amber)+-- ANCHOR_END: dashes++-- ANCHOR: transforms+arrowPath :: Rect -> P.Path+arrowPath r =+  let V2 cx cy = centre r+   in P.polygon [V2 (cx - 24) (cy - 6), V2 cx (cy - 6), V2 cx (cy - 16), V2 (cx + 24) cy, V2 cx (cy + 16), V2 cx (cy + 6), V2 (cx - 24) (cy + 6)]++arrow :: Rect -> CanvasM ()+arrow r = drawPath (arrowPath r) teal >> drawStrokePath (arrowPath r) 2 ink++-- | Scale about a point: move it to the origin, scale, move it back.+scaleAround :: V2 -> Float -> Float -> P.Transform+scaleAround (V2 cx cy) sx sy = P.translate cx cy <> P.scale sx sy <> P.translate (-cx) (-cy)++transforms :: [(Text, Rect -> CanvasM ())]+transforms =+  [ ("translate 20 10", \r -> withTransform (P.translate 20 10) (arrow r))+  , ("rotateAround c (pi / 4)", \r -> withTransform (P.rotateAround (centre r) (pi / 4)) (arrow r))+  , ("scaleAround c 1.5 1.5", \r -> withTransform (scaleAround (centre r) 1.5 1.5) (arrow r))+  , ("scaleAround c (-1) 1", \r -> withTransform (scaleAround (centre r) (-1) 1) (arrow r))+  ]+-- ANCHOR_END: transforms++-- ANCHOR: clip+clipped :: Rect -> CanvasM ()+clipped r@(Rect x y _ h) = do+  drawCircle (centre r) 34 rose+  drawText (V2 (x - 6) (y + h / 2)) AlignStart AlignMiddle "text past the edge" ink++clipRect :: Rect -> Rect+clipRect (Rect x y w h) = Rect (x + 10) (y + 8) (w - 20) (h - 16)++clips :: [(Text, Rect -> CanvasM ())]+clips =+  [ ("no clip", clipped)+  , ("withClip box", \r -> withClip (clipRect r) (clipped r))+  ]+-- ANCHOR_END: clip++-- ANCHOR: text+textAnchors :: [(Text, Rect -> CanvasM ())]+textAnchors =+  [ (name, \r -> drawText (centre r) ax AlignMiddle "Anchor" ink)+  | (name, ax) <- [("AlignStart", AlignStart), ("AlignCenter", AlignCenter), ("AlignEnd", AlignEnd)]+  ]+    <> [ (name, \r -> drawText (centre r) AlignCenter ay "Anchor" ink)+       | (name, ay) <- [("AlignTop", AlignTop), ("AlignMiddle", AlignMiddle), ("AlignBaseline", AlignBaseline), ("AlignBottom", AlignBottom)]+       ]+    <> [ ("drawTextWith", \r ->+          drawTextWith defaultTextFont {textFontSize = 24, textFontWeight = WeightBold} (centre r) AlignCenter AlignMiddle "42" amber)+       ]+-- ANCHOR_END: text++-- ANCHOR: borders+borders :: [(Text, Rect -> CanvasM ())]+borders =+  [ ("drawStrokeRoundedRect", \r -> drawStrokeRoundedRect r 12 8 (withAlpha blue 0.8))+  , ("drawStrokePath", \r -> drawStrokePath (P.roundedRect r 12) 8 (withAlpha blue 0.8))+  ]+-- ANCHOR_END: borders++-- ---------------------------------------------------------------------------+-- Annotation+-- ---------------------------------------------------------------------------++guideInk :: Color+guideInk = colorRGBA 148 163 184 200++guideStroke :: P.Path -> CanvasM ()+guideStroke p = drawStrokePath p 1 guideInk++dashedGuide :: P.Path -> CanvasM ()+dashedGuide p = drawStrokePathWith (P.stroke 1) {P.strokeDash = [3, 3]} p (P.Solid guideInk)++dot :: V2 -> CanvasM ()+dot p = drawCircle p 2.5 ink++hollowDot :: V2 -> CanvasM ()+hollowDot p = drawStrokeCircle p 3.5 1.5 guideInk++-- | The path's points: filled dots on the curve, hollow dots and thin arms+-- for control points, and the centre of an arc.+pathPoints :: P.Path -> CanvasM ()+pathPoints (Path segs) = go (V2 0 0) segs+  where+    go _ [] = pure ()+    go cur (s : rest) = case s of+      SegMove x y -> dot (V2 x y) >> go (V2 x y) rest+      SegLine x y -> dot (V2 x y) >> go (V2 x y) rest+      SegQuad qx qy x y -> do+        guideStroke (P.polyline [cur, V2 qx qy, V2 x y])+        hollowDot (V2 qx qy)+        dot (V2 x y)+        go (V2 x y) rest+      SegCubic ax ay bx by x y -> do+        guideStroke (P.polyline [cur, V2 ax ay])+        guideStroke (P.polyline [V2 bx by, V2 x y])+        hollowDot (V2 ax ay)+        hollowDot (V2 bx by)+        dot (V2 x y)+        go (V2 x y) rest+      SegArc cx cy rx _ _ a0 sweep -> do+        let start = V2 (cx + rx * cos a0) (cy + rx * sin a0)+            end = V2 (cx + rx * cos (a0 + sweep)) (cy + rx * sin (a0 + sweep))+        dashedGuide (P.polyline [start, V2 cx cy, end])+        hollowDot (V2 cx cy)+        dot start+        dot end+        go end rest+      _ -> go cur rest++-- | One canvas holding a grid of captioned cells. Each cell's drawing area+-- is passed to its example.+cells :: Int -> Float -> Float -> [(Text, Rect -> CanvasM ())] -> NanoUI ()+cells cols cw ch examples =+  columnWith (padAll 12) $+    void $ canvas (fixedWH (fromIntegral cols * cw) (fromIntegral rows * ch)) $ \(Rect x0 y0 _ _) ->+      for_ (zip [0 :: Int ..] examples) $ \(i, (caption, draw)) -> do+        let (rowIx, colIx) = i `divMod` cols+            cx = x0 + fromIntegral colIx * cw+            cy = y0 + fromIntegral rowIx * ch+            area = Rect (cx + 26) (cy + 18) (cw - 52) (ch - 56)+        drawRoundedRect (Rect (cx + 4) (cy + 4) (cw - 8) (ch - 8)) 8 (colorRGBA 255 255 255 10)+        draw area+        drawTextWith+          defaultTextFont {textFontSize = 12, textFontVariant = FontMono}+          (V2 (cx + cw / 2) (cy + ch - 18))+          AlignCenter+          AlignMiddle+          caption+          guideInk+  where+    rows = (length examples + cols - 1) `div` cols++-- | Add an annotation over every example in a list.+annotate :: (Rect -> CanvasM ()) -> [(Text, Rect -> CanvasM ())] -> [(Text, Rect -> CanvasM ())]+annotate guide = map (\(caption, draw) -> (caption, \r -> draw r >> guide r))++crosshair :: V2 -> CanvasM ()+crosshair (V2 x y) = do+  guideStroke (P.moveTo (V2 (x - 40) y) <> P.lineTo (V2 (x + 40) y))+  guideStroke (P.moveTo (V2 x (y - 16)) <> P.lineTo (V2 x (y + 16)))+  drawCircle (V2 x y) 2.5 rose++-- | A grid example as (file name, canvas width, view): 'cells' and its+-- padding.+cellGrid :: Text -> Int -> Float -> Float -> [(Text, Rect -> CanvasM ())] -> (Text, Float, NanoUI ())+cellGrid name cols cw ch examples = (name, fromIntegral cols * cw + 24, cells cols cw ch examples)++-- | Every example as (file name, canvas width, view). The width covers the+-- padded canvas; the generator crops the height to what was drawn.+canvasExamples :: [(Text, Float, NanoUI ())]+canvasExamples =+  [ ("badge", 144, columnWith (padAll 12) badge)+  , cellGrid "primitives" 4 160 120 primitives+  , cellGrid "segments" 5 150 130 [(c, \r -> drawStrokePath (mk r) 3 blue >> pathPoints (mk r)) | (c, mk) <- segments]+  , cellGrid "shapes" 4 160 120 shapes+  , cellGrid "fill-rules" 3 200 130 fillRules+  , cellGrid "paints" 4 160 120 paints+  , cellGrid "caps" 3 180 100 (annotate (\r -> guideStroke (capLine r) >> pathPoints (capLine r)) caps)+  , cellGrid "joins" 4 170 120 (annotate (\r -> guideStroke (zigzag r) >> pathPoints (zigzag r)) joins)+  , cellGrid "dashes" 4 160 120 dashes+  , cellGrid "transforms" 4 170 130 (annotate (dashedGuide . arrowPath) transforms)+  , cellGrid "clip" 2 200 130 (annotate (\r -> dashedGuide (P.rect (clipRect r))) clips)+  , cellGrid "text" 4 150 100 (annotate (\r -> crosshair (centre r)) textAnchors)+  , cellGrid "borders" 2 200 130 (annotate (guideStroke . P.rect) borders)+  ]
+ app/ChartExamples.hs view
@@ -0,0 +1,216 @@+-- | Chart and diagram examples for the book. Each anchored block is+-- included in a book page (@packages/index.md@, @tutorials/live-data.md@,+-- @widgets/custom-drawing.md@), and the glossary generator renders the same+-- definitions to @book/src/images/charts/@, so the code on the page is the+-- code that drew the picture beside it.+--+-- Everything outside the anchors is annotation: the captioned cells each+-- example is drawn into, and the pointer marking where a hover was taken.+module ChartExamples (chartExamples) where++import Control.Monad (void)+import Data.Bits (shiftR)+import Data.Foldable (for_)+import Data.List (unfoldr)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word64)+import Diagrams.Prelude (Diagram, arrowBetween', fc, fontSizeL, frame, headLength, lc, local, lw, lwO, none, p2, roundedRect, text, translate, with, (#), (&), (.~))+import Diagrams.Prelude qualified as D+import NanoUI+import NanoUI.Diagrams+import NanoUI.Path qualified as P++-- ANCHOR: cpu_chart+cpuChart :: PlotCache -> [(Double, Double)] -> NanoUI ()+cpuChart cache samples =+  void $ plot cache (fillW . fixedH 220) $+    withGrid GridBoth+      . withXAxis "time (s)"+      . withYAxis "CPU %"+      . withLegend LegendNone+      $ chart [line "cpu" samples]+-- ANCHOR_END: cpu_chart++-- | A minute of CPU load: two slow swells and some faster wobble.+cpuSamples :: [(Double, Double)]+cpuSamples = [(t, 38 + 16 * sin (t / 7) + 7 * sin (t * 0.9 + 1) + 4 * sin (t * 2.3)) | t <- [0 .. 60]]++-- ANCHOR: data+wave :: [(Double, Double)]+wave = [(x, 3 + sin x + 0.5 * sin (2.3 * x)) | x <- [0, 0.3 .. 2 * pi]]++counts :: [(Double, Double)]+counts = zip [0 ..] [2, 4, 3, 6, 5, 7, 4, 5]++quarters :: [(Text, Double)]+quarters = [("Q1", 3), ("Q2", 5), ("Q3", 4), ("Q4", 7)]+-- ANCHOR_END: data++-- ANCHOR: series+seriesKinds :: [(Text, Series)]+seriesKinds =+  [ ("line", line "line" wave)+  , ("scatter", scatter "scatter" wave)+  , ("area", area "area" wave)+  , ("step", step "step" counts)+  , ("bar", bar "bar" quarters)+  ]+-- ANCHOR_END: series++-- ANCHOR: styles+seriesStyles :: [(Text, Series)]+seriesStyles =+  [ ("withColor", withColor (colorRGB 20 184 166) (line "s" wave))+  , ("withStrokeWidth 4", withStrokeWidth 4 (line "s" wave))+  , ("withMarker MarkCircle", withMarker MarkCircle (line "s" counts))+  , ("withBaseline 3", withBaseline 3 (area "s" wave))+  ]+-- ANCHOR_END: styles++-- ANCHOR: markers+markers :: [(Text, Series)]+markers =+  [ (name, withStrokeWidth 6 (withMarker shape (scatter name counts)))+  | (name, shape) <-+      [ ("MarkCircle", MarkCircle)+      , ("MarkSquare", MarkSquare)+      , ("MarkDiamond", MarkDiamond)+      , ("MarkTriangle", MarkTriangle)+      , ("MarkCross", MarkCross)+      ]+  ]+-- ANCHOR_END: markers++-- ANCHOR: grids+grids :: [(Text, Chart)]+grids =+  [ (name, withGrid mode . withLegend LegendNone $ chart [line "s" wave])+  | (name, mode) <-+      [("GridBoth", GridBoth), ("GridHorizontal", GridHorizontal), ("GridVertical", GridVertical), ("GridNone", GridNone)]+  ]+-- ANCHOR_END: grids++-- ANCHOR: legends+latency :: Chart+latency =+  withTitle "Latency" $+    chart [line "p50" [(x, 20 + 4 * sin x) | x <- [0, 0.5 .. 6]], line "p99" [(x, 42 + 9 * sin (x + 1)) | x <- [0, 0.5 .. 6]]]++legends :: [(Text, Chart)]+legends =+  [ (name, withLegend pos latency)+  | (name, pos) <-+      [ ("LegendRight", LegendRight)+      , ("LegendTop", LegendTop)+      , ("LegendNone", LegendNone)+      , ("LegendBottom", LegendBottom)+      , ("LegendInside", LegendInside)+      ]+  ]+-- ANCHOR_END: legends++-- ANCHOR: hover+requests :: [(Double, Double)]+requests = zip [0 ..] [120, 180, 150, 260, 210, 300, 240, 280]++hoverReadout :: PlotCache -> NanoUI ()+hoverReadout cache = columnWith (gap 8) $ do+  resp <- plot cache (fixedWH 240 200) (withLegend LegendNone (chart [line "requests" requests]))+  case plotHover resp of+    Nothing -> muted "Hover a point"+    Just h -> kv "value" (T.pack (show (round (hoverDataY h) :: Int)))+-- ANCHOR_END: hover++-- ANCHOR: diagram+-- | Three labelled boxes joined by arrows, coloured from the theme.+stages :: Theme -> Diagram B+stages t = (mconcat (zipWith stage [0 ..] ["view", "layout", "paint"]) <> arrows) # frame 0.25+  where+    ink = colourOf (styleFg (themePanel t))+    stage i name =+      (text name # fontSizeL 0.3 # fc ink <> roundedRect 1.6 0.8 0.15 # fc (colourOf (themeAccent t)) # lw none)+        # translate (D.r2 (2.4 * i, 0))+    arrows =+      mconcat+        [ arrowBetween' (with & headLength .~ local 0.2) (p2 (2.4 * i + 0.9, 0)) (p2 (2.4 * i + 1.5, 0)) # lc ink # lwO 1.5+        | i <- [0, 1]+        ]++pipelineDiagram :: NanoUI ()+pipelineDiagram = void $ diagram (fixedWH 360 72) . stages =<< uiTheme+-- ANCHOR_END: diagram++-- ANCHOR: sparkline+sparklines :: [Float] -> NanoUI ()+sparklines samples = rowWith (gap 16 . alignMiddle) $ do+  sparkline samples+  sparklineWith (fixedWH 120 32) 120 32 samples+-- ANCHOR_END: sparkline++sparkSamples :: [Float]+sparkSamples = [4 + 2 * sin (x / 2) + sin (x * 1.7) | x <- [0 .. 30]]++-- | The live chart tutorial's chart after 200 samples: the same random walk+-- and chart as @walkChart@ and @advance@ in @nano-ui-demo/examples/LiveChart.hs@.+liveChart :: PlotCache -> NanoUI ()+liveChart cache =+  void $+    plot cache (fillW . minH 300) $+      withGrid GridBoth . withLegend LegendNone . withXAxis "sample" . withYAxis "value" $+        chart [line "walk" (zip [0 ..] (take 200 walk))]+  where+    walk = unfoldr stepWalk (42, 0)+    stepWalk (seed, level) =+      let seed' = seed * 6364136223846793005 + 1442695040888963407 :: Word64+          level' = level + fromIntegral (seed' `shiftR` 11) / 2 ^ (53 :: Int) - 0.5 :: Double+       in Just (level', (seed', level'))++-- ---------------------------------------------------------------------------+-- Annotation+-- ---------------------------------------------------------------------------++-- | Charts of one height, each captioned with its name, wrapped onto lines.+-- A chart with a fixed height takes the width its drawing's proportions+-- give it.+cells :: Float -> PlotCache -> [(Text, Chart)] -> NanoUI ()+cells h cache examples =+  rowWith (wrap . gap 16 . lineGap 16 . padAll 12 . fillW) $+    for_ examples $ \(caption, c) -> columnWith (tight . gap 6) $ do+      void (plot cache (fixedH h) c)+      labelWith (alignCenter . fontMono . fontSize 12 . fontMuted) caption++-- | Cells of one series each, without a legend.+seriesCells :: Float -> PlotCache -> [(Text, Series)] -> NanoUI ()+seriesCells h cache examples =+  cells h cache [(caption, withLegend LegendNone (chart [s])) | (caption, s) <- examples]++-- | Where the hover example's pointer rests, in window coordinates.+hoverPoint :: V2+hoverPoint = V2 222 70++-- | A pointer arrow with its tip on 'hoverPoint', drawn over the view.+pointerOver :: NanoUI () -> NanoUI ()+pointerOver ui = layers $ do+  ui+  let V2 px py = hoverPoint+  void $ canvas (pinAt px py . fixedWH 14 20 . pointer PointerPass) $ \(Rect x y _ _) -> do+    let tip = P.polygon [V2 x y, V2 x (y + 16), V2 (x + 4) (y + 12), V2 (x + 7) (y + 19), V2 (x + 9) (y + 18), V2 (x + 6) (y + 11), V2 (x + 11) (y + 11)]+    drawPath tip colorWhite+    drawStrokePath tip 1 colorBlack++-- | Every example as (file name, widest view width, pointer, view). The+-- generator narrows a view to what it draws and crops its height.+chartExamples :: [(Text, Float, Maybe V2, PlotCache -> NanoUI ())]+chartExamples =+  [ ("cpu-chart", 320, Nothing, \cache -> columnWith (padAll 12 . fillW) (cpuChart cache cpuSamples))+  , ("series", 760, Nothing, \cache -> seriesCells 180 cache seriesKinds)+  , ("styles", 760, Nothing, \cache -> seriesCells 120 cache seriesStyles)+  , ("markers", 760, Nothing, \cache -> seriesCells 110 cache markers)+  , ("grids", 760, Nothing, \cache -> cells 120 cache grids)+  , ("legends", 760, Nothing, \cache -> cells 170 cache legends)+  , ("hover", 760, Just hoverPoint, \cache -> pointerOver (columnWith (padAll 12) (hoverReadout cache)))+  , ("diagram", 760, Nothing, \_ -> columnWith (padAll 12) pipelineDiagram)+  , ("sparkline", 760, Nothing, \_ -> columnWith (padAll 12) (sparklines sparkSamples))+  , ("live-chart", 480, Nothing, \cache -> columnWith (padAll 12 . fillW) (liveChart cache))+  ]
+ app/Glossary.hs view
@@ -0,0 +1,85 @@+-- | Generate a self-contained HTML visual glossary of nano-ui styling+-- modifiers, widget surface mappings, and unexpected interactions, with every+-- specimen rendered headlessly by @nano-ui-svg@ ('frameToSvg').+--+-- The page's stylesheet and script live in @assets/glossary.css@ and+-- @assets/glossary.js@ and are spliced into the generated document, so the+-- output stays one portable file while the visual and interactive layers are+-- edited as plain CSS and JavaScript rather than Haskell string literals.+-- 'generateBookVisuals' also writes the layout-chapter and widget-gallery+-- SVGs used by the documentation book.+--+-- Run:+--+-- > cabal run -j1 nano-ui-svg-glossary -- [docs/styling-glossary.html]+module Main (main) where++import Data.IORef (writeIORef)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import Glossary.BookVisuals (generateBookVisuals)+import Glossary.Html (buildHtmlDocument, buildSvgBanksValue, buildTrapsValue, buildWidgetMetaValue)+import Glossary.Render (encodeJsonText, loadAssets, sdlFontCtxRef)+import Glossary.Specimens+  ( generateInteractions+  , generateProbeMatrix+  , generateRainbowBanner+  , generateStateStrip+  , generateTypoDemos+  )+import NanoUI+import NanoUI.Backend.Sdl (NanoUIFont (..), SdlOptions (..), defaultSdlOptions, withSdl)+import NanoUI.Testing (newPixelContext)+import System.Directory (createDirectoryIfMissing)+import System.Environment (getArgs)+import System.IO (IOMode (WriteMode), hSetEncoding, utf8, withFile)++main :: IO ()+main = do+  args <- getArgs+  let outPath = case args of+        (p : _) -> p+        [] -> "docs/styling-glossary.html"+      sdlOpts =+        defaultSdlOptions+          { sdlWindowSettings =+              defaultWindowSettings+                { wsTitle = "nano-ui-svg-glossary"+                , wsMode = Hidden+                , wsSize = Size 800 600+                , wsResizable = False+                }+          , sdlAppVsync = False+          , sdlAppFont = DefaultFont+          , sdlAppMonoFont = DefaultFont+          , sdlAppFontSize = 14+          , sdlAppUiScale = 1+          }+  assets <- loadAssets+  ctxSeed <- newPixelContext+  withSdl sdlOpts ctxSeed $ \sdlCtx _env -> do+    writeIORef sdlFontCtxRef (Just sdlCtx)+    banner <- generateRainbowBanner+    stateStrip <- generateStateStrip+    probeRows <- generateProbeMatrix+    typoDemos <- generateTypoDemos+    interactions <- generateInteractions+    generateBookVisuals+    let html = buildHtmlDocument assets banner stateStrip probeRows typoDemos interactions+    withFile outPath WriteMode $ \h -> do+      hSetEncoding h utf8+      TIO.hPutStr h html+    putStrLn ("wrote " <> outPath <> " (" <> show (T.length html) <> " chars)")+    createDirectoryIfMissing True "book/theme"+    let banksJs =+          "window.NANO_UI_BANKS = "+            <> encodeJsonText (buildSvgBanksValue (snd banner) (snd stateStrip) probeRows typoDemos)+            <> ";\nwindow.NANO_UI_WIDGET_META = "+            <> encodeJsonText (buildWidgetMetaValue probeRows)+            <> ";\nwindow.NANO_UI_TRAPS = "+            <> encodeJsonText (buildTrapsValue interactions)+            <> ";\n"+    withFile "book/theme/nano-ui-banks.js" WriteMode $ \h -> do+      hSetEncoding h utf8+      TIO.hPutStr h banksJs+    putStrLn "wrote book/theme/nano-ui-banks.js"
+ app/Glossary/BookVisuals.hs view
@@ -0,0 +1,189 @@+-- | SVGs for the documentation book: the layout chapter's examples, the+-- chart and canvas examples, and the widget gallery.+module Glossary.BookVisuals+  ( generateBookVisuals+  ) where++import CanvasExamples (canvasExamples)+import ChartExamples (chartExamples)+import Control.Monad (forM_, void)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import Glossary.Render (cropSvg, exportFrame, frameInkBounds, newSvgContext, renderSvg)+import LayoutExamples (layoutExamples)+import NanoUI+import NanoUI.Plot (PlotCache, newPlotCache)+import NanoUI.Testing (runFrame)+import NanoUI.Testing.Harness (withInputOff)+import System.Directory (createDirectoryIfMissing)++-- ---------------------------------------------------------------------------+-- Book visuals+-- ---------------------------------------------------------------------------++-- ---------------------------------------------------------------------------+-- Layout chapter examples+-- ---------------------------------------------------------------------------++-- | One layout example: a padded frame whose root column fills the canvas.+layoutDemo :: NanoUI () -> NanoUI ()+layoutDemo = columnWith (fillW . fillH . padAll 14 . gap 10)++-- | Render one layout example, cropped to its painted height. @hoverPos@+-- parks the pointer on a control for the hover and pointer-mode examples.+layoutSvg :: Text -> Float -> Float -> Maybe V2 -> NanoUI () -> IO Text+layoutSvg tag w h hoverPos ui = do+  (svg, bounds) <- settledFrame 1 tag w h hoverPos ui+  pure (cropSvg w h bounds svg)++-- | The uncropped SVG of a view after @n@ warm-up frames, and the bounds of+-- what it painted. A chart sizes itself from the envelope of the drawing it+-- made the frame before, so it takes more than one frame to settle.+settledFrame :: Int -> Text -> Float -> Float -> Maybe V2 -> NanoUI () -> IO (Text, Maybe Rect)+settledFrame n tag w h hoverPos ui = do+  ctx <- newSvgContext+  let base = withInputOff w h+      capture = case hoverPos of+        Nothing -> base+        Just pos -> base {inputMousePos = pos}+      warm = replicate n base <> maybe [] (const [capture]) hoverPos+  mapM_ (\inp -> runFrame ctx inp ui) warm+  (svg, dd) <- exportFrame tag ctx capture ui+  bounds <- frameInkBounds ctx capture dd+  pure (svg, bounds)++-- | A chart example narrowed to what it draws. A chart's width comes from+-- its drawing's proportions, so the view is rendered once at the widest+-- width @w@ to find its right edge, then again at that edge plus the 12 px+-- padding. Each render gets a fresh 'PlotCache', as an application+-- allocates one during setup.+chartSvg :: Text -> Float -> Maybe V2 -> (PlotCache -> NanoUI ()) -> IO Text+chartSvg tag w pointerPos ui = do+  (_, ink) <- render w+  let fittedW = maybe w (\(Rect bx _ bw _) -> min w (fromIntegral (ceiling (bx + bw) :: Int) + 12)) ink+  (svg, ink') <- render fittedW+  pure (cropSvg fittedW h ink' svg)+  where+    h = 1200+    render width = do+      cache <- newPlotCache+      settledFrame 3 tag width h pointerPos (ui cache)+++-- | Controls in the book's widget gallery.+galleryControlsSpecimen :: NanoUI ()+galleryControlsSpecimen = do+  enabled <- useVar True+  boldVar <- useVar False+  query <- useVar ""+  priority <- useVar (1 :: Int)+  volume <- useVar (62 :: Float)+  columnWith (fillW . padAll 18 . gap 14) $ do+    heading "Controls"+    rowWith (tight . gap 10 . fillW . wrap . alignMiddle) $ do+      void (button "Primary")+      void (button "Secondary")+      toggleButtonWith (fixedW 90) Accent "Bold" boldVar+      checkbox "Enabled" enabled+    rowWith (tight . gap 14 . fillW . wrap . alignMiddle) $ do+      textInputConfigured+        defaultTextInputConfig {ticPlaceholder = "Project name", ticLayout = fixedW 210}+        query+      selectWith (fixedW 150) ["Low", "Medium", "High"] priority+      sliderWith (fixedW 190) 0 100 volume+    rowWith (tight . gap 12 . fillW) $ do+      panelWith (fillW . padAll 12 . gap 10) $ do+        muted "CUSTOM CONTROLS"+        rowWith (tight . gap 16 . alignMiddle) $ do+          toggleSwitch enabled+          knob 0 100 volume+          circularProgress 0.62+      panelWith (fillW . padAll 12 . gap 10) $ do+        muted "TELEMETRY"+        progressBar 0.62+        sparkline [18, 22, 19, 27, 24, 31, 28, 35, 33, 41, 38, 46]+        muted "12 samples, last 46"++-- | Tabs, a table, and a tree in one frame.+galleryDataSpecimen :: NanoUI ()+galleryDataSpecimen = do+  page <- useVar (0 :: Int)+  selected <- useVar (0 :: Int)+  columnWith (fillW . fillH . padAll 18 . gap 12) $ do+    heading "Collections"+    tabs+      page+      [ tab 0 "Overview" (label "Deployment health across three regions.")+      , tab 1 "Queries" (label "Slow query log for the last hour.")+      , tab 2 "Settings" (label "Retention and sampling policy.")+      ]+    rowWith (tight . gap 12 . fillW . fillH) $ do+      panelWith (fillW . fillH . padAll 12 . gap 8) $ do+        _ <-+          simpleTable+            ["Service", "Status", "Latency"]+            [ ["api", "running", "12 ms"]+            , ["worker", "running", "48 ms"]+            , ["scheduler", "idle", "2 ms"]+            ]+        pure ()+      panelWith (fixedW 230 . fillH . padAll 12 . gap 8) $ do+        muted "TREE"+        tree+          "book-tree"+          [ TreeItem "src" [TreeItem "Main.hs" [], TreeItem "Widgets" []]+          , TreeItem "README.md" []+          ]+          selected++-- | Every tab header style, one per row.+tabStylesSpecimen :: NanoUI ()+tabStylesSpecimen =+  columnWith (fillW . padAll 18 . gap 12) $ do+    heading "Tab styles"+    tabStyleRow "Underline" 0 TabUnderline+    tabStyleRow "Pill" 1 TabPill+    tabStyleRow "Segmented" 2 TabSegmented+    tabStyleRow "Contained" 1 TabContained+  where+    tabStyleRow :: Text -> Int -> TabStyle -> NanoUI ()+    tabStyleRow caption initial style = do+      active <- useVar initial+      labelWith fontMuted caption+      tabsConfigured defaultTabsConfig {tabsStyle = style} active+        [ tab 0 "Overview" (muted "Overview")+        , tab 1 "Activity" (muted "Activity")+        , tab 2 "Settings" (muted "Settings")+        ]++-- | Write the layout, canvas, chart and gallery specimens to the book's images directory.+generateBookVisuals :: IO ()+generateBookVisuals = do+  createDirectoryIfMissing True "book/src/images"+  createDirectoryIfMissing True "book/src/images/layout"+  forM_ layoutExamples $ \(name, w, h, hoverPos, ui) -> do+    svg <- layoutSvg ("book-layout-" <> name) w h hoverPos (layoutDemo ui)+    let path = "book/src/images/layout/" <> T.unpack name <> ".svg"+    TIO.writeFile path svg+    putStrLn ("wrote " <> path)+  createDirectoryIfMissing True "book/src/images/canvas"+  forM_ canvasExamples $ \(name, w, ui) -> do+    svg <- layoutSvg ("book-canvas-" <> name) w 600 Nothing ui+    let path = "book/src/images/canvas/" <> T.unpack name <> ".svg"+    TIO.writeFile path svg+    putStrLn ("wrote " <> path)+  createDirectoryIfMissing True "book/src/images/charts"+  forM_ chartExamples $ \(name, w, pointerPos, ui) -> do+    svg <- chartSvg ("book-chart-" <> name) w pointerPos ui+    let path = "book/src/images/charts/" <> T.unpack name <> ".svg"+    TIO.writeFile path svg+    putStrLn ("wrote " <> path)+  writeSvg "gallery-controls" 880 260 galleryControlsSpecimen+  writeSvg "gallery-data" 880 420 galleryDataSpecimen+  writeSvg "tab-styles" 880 500 tabStylesSpecimen+  where+    writeSvg name w h ui = do+      svg <- renderSvg ("book-" <> name) w h ui+      TIO.writeFile ("book/src/images/" <> T.unpack name <> ".svg") svg+      putStrLn ("wrote book/src/images/" <> T.unpack name <> ".svg")
+ app/Glossary/Html.hs view
@@ -0,0 +1,708 @@+-- | Lucid HTML for the glossary page and the JSON values the book's+-- @nano-ui-banks.js@ carries.+module Glossary.Html+  ( buildHtmlDocument+  , buildSvgBanksValue+  , buildTrapsValue+  , buildWidgetMetaValue+  ) where++import Data.Aeson.Micro (ToJSON (..), Value, object, (.=))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Glossary.Render (Assets (..), encodeJsonText)+import Glossary.Specimens+  ( InteractionCard (..)+  , ProbeRow (..)+  , ToggleNote (..)+  , TypoDemo (..)+  , TypoSectionData (..)+  , impactBadgeText+  , impactCode+  )+import Lucid+import Lucid.Base (makeAttributes)++-- ---------------------------------------------------------------------------+-- HTML Generation+-- ---------------------------------------------------------------------------++-- | 'show' as text, for ids and attribute values.+-- | Escaped text as HTML content.+txt :: Text -> Html ()+txt = toHtml++showT :: Show a => a -> Text+showT = T.pack . show++-- | Pointer enter/leave handlers, which Lucid does not name.+onmouseenter_ :: Text -> Attributes+onmouseenter_ = makeAttributes "onmouseenter"++onmouseleave_ :: Text -> Attributes+onmouseleave_ = makeAttributes "onmouseleave"++-- | Snippet markup for prose and table cells: escaped text, @<code>@, surface+-- badges, line breaks, and links. Interaction notes spell out identifiers with+-- @`backticks`@; 'prose' turns those into code elements rather than requiring+-- hand-written markup in every string.+data Snippet+  = Txt !Text+  | Code !Text+  | Badge !Text !Text+  | Brk+  | Link !Text ![Snippet]++inline :: [Snippet] -> Html ()+inline = mapM_ go+  where+    go = \case+      Txt t -> toHtml t+      Code t -> code_ (toHtml t)+      Badge cls t -> span_ [class_ ("badge " <> cls)] (toHtml t)+      Brk -> br_ []+      Link href xs -> a_ [href_ href] (inline xs)++-- | Render @`backticked`@ runs as @<code>@ and everything else as escaped text.+prose :: Text -> Html ()+prose t = sequence_ [if odd i then code_ (toHtml piece) else toHtml piece | (i, piece) <- zip [0 :: Int ..] (T.splitOn "`" t)]++-- | A section heading row: inline-markup title and summary.+sectionHead :: [Snippet] -> [Snippet] -> Html ()+sectionHead title summary = div_ [class_ "section-head"] $ do+  h2_ (inline title)+  span_ (inline summary)++-- | Section I shell: the state/focus workbench. The frames themselves are+-- pre-rendered; the script swaps them into @#state-svg-well@.+stateStripSection :: Text -> Html ()+stateStripSection baseSvg = do+  div_ [class_ "workbench-card", id_ "state-workbench"] $ do+    div_ [class_ "wb-grid"] $ do+      div_ [class_ "wb-viewport-col"] $ do+        div_ [class_ "wb-viewport-head"] $ do+          span_ [class_ "wb-active-label", id_ "state-active-label"] "State: Resting · defaultTheme"+          button_ [type_ "button", class_ "mini-btn", onclick_ "resetStateWorkbench()"] "Reset"+        div_ [class_ "svg-well wb-svg-stage", id_ "state-svg-well"] (toHtmlRaw baseSvg)+        div_ [class_ "wb-code-bar"] (code_ [id_ "state-code-preview"] "-- Resting state under defaultTheme")+      div_ [class_ "wb-controls-col"] $ do+        div_ [class_ "control-group-label"] "1. Choose a state:"+        div_ [class_ "state-pill-grid", id_ "state-mode-pills"] $+          sequence_ [statePill i title detail | (i, (title, detail)) <- zip [0 :: Int ..] statePills]+        div_ [class_ "control-group-label", style_ "margin-top:12px"] "2. Toggle modifiers:"+        div_ [class_ "toggle-chip-grid", id_ "state-style-toggles"] $+          mapM_ stateStyleChip stateChips+        div_ [class_ "wb-inspector", id_ "state-inspector"] mempty+  where+    statePills =+      [ ("Resting", "styleBg + styleBorder")+      , ("Hovered", "styleHoverBg")+      , ("Pressed", "styleActiveBg")+      , ("Focused", "outer themeFocusRing")+      , ("Focused input", "accent border, active fill")+      , ("Open select", "button box, popup menu")+      ]+    statePill :: Int -> Text -> Text -> Html ()+    statePill i title detail =+      button_+        [ type_ "button"+        , class_ (if i == 0 then "state-pill active" else "state-pill")+        , data_ "state" (showT i)+        , onclick_ ("setStateMode(" <> showT i <> ")")+        ]+        $ do+          strong_ (toHtml title)+          span_ (toHtml detail)+    stateChips =+      [ (0 :: Int, "buttonStyle", "btn", "impact-primary", "themeButton")+      , (1, "inputStyle", "inp", "impact-primary", "themeInput")+      , (2, "popupStyle", "pop", "impact-partial", "Open menu")+      , (3, "accentColor", "acc", "impact-partial", "Focus")+      , (4, "disabledWhen", "dis", "impact-surprise", "Blocked")+      ]+    stateStyleChip :: (Int, Text, Text, Text, Text) -> Html ()+    stateStyleChip (bit, name, probe, toneCls, tag) =+      styleChip+        [ data_ "sbit" (showT bit)+        , data_ "probe" probe+        , onclick_ ("toggleStateStyle(" <> showT bit <> ")")+        ]+        name+        (Just (toneCls, tag))+++-- | A style toggle chip: checkbox square, label, and an optional impact tag.+-- @attrs@ carry the per-workbench data attributes and click handler.+styleChip :: [Attributes] -> Text -> Maybe (Text, Text) -> Html ()+styleChip attrs name mTag =+  button_ ([type_ "button", class_ "style-chip"] <> attrs) $ do+    span_ [class_ "chip-check"] mempty+    span_ [class_ "chip-name"] (toHtml name)+    case mTag of+      Just (toneCls, tag) -> span_ [class_ ("chip-tag " <> toneCls)] (toHtml tag)+      Nothing -> mempty++-- | A small action button.+miniBtn :: [Attributes] -> Text -> Html ()+miniBtn attrs btnLabel = button_ ([type_ "button", class_ "mini-btn"] <> attrs) (toHtml btnLabel)++-- | One per-widget workbench card: metadata, live expression, stage, and the+-- seven style toggles.+probeRowCard :: ProbeRow -> Html ()+probeRowCard pr = do+  article_+    [ class_ "probe-row filter-item"+    , id_ ("widget-" <> wid)+    , data_ "wid" wid+    , data_ "cat" (prCategory pr)+    ]+    $ do+      div_ [class_ "probe-card-grid"] $ do+        div_ [class_ "probe-meta"] $ do+          div_ [class_ "probe-title-line"] $ do+            h3_ [class_ "probe-title"] (toHtml (prTitle pr))+            span_ [class_ "surface-pill"] (toHtml (prPrimarySurface pr))+          code_ [class_ "probe-sig"] (toHtml (prSignature pr))+          p_ [class_ "probe-desc"] (prose (prSummary pr))+          div_ [class_ "wb-code-bar"] $ do+            div_ [class_ "code-bar-head"] (span_ "Live Haskell Expression")+            pre_ (code_ [id_ ("code-" <> wid)] (toHtml (prCodeExpr pr)))+        div_ [class_ "probe-stage-col"] $ do+          div_ [class_ "wb-viewport-head"] $ do+            span_ [class_ "wb-active-label", id_ ("status-" <> wid)] "defaultTheme (0 modifiers)"+            div_ [class_ "wb-head-actions"] $ do+              miniBtn+                [ id_ ("cmp-btn-" <> wid)+                , onclick_ ("toggleWidgetCompare('" <> wid <> "')")+                , title_ "Show defaultTheme baseline next to active SVG"+                ]+                "⇄ Compare"+              miniBtn [onclick_ ("setWidgetMask('" <> wid <> "', 0)")] "Reset"+          div_ [class_ "wb-dual-stage", id_ ("dual-" <> wid)] $ do+            div_ [class_ "svg-well wb-baseline-well hidden-compare", id_ ("base-well-" <> wid)] $ do+              div_ [class_ "well-corner-tag"] "Baseline (defaultTheme)"+              div_ [class_ "well-svg-inner", id_ ("base-svg-" <> wid)] mempty+            div_ [class_ "svg-well wb-active-well", id_ ("svg-" <> wid)] (toHtmlRaw (prBaselineSvg pr))+        div_ [class_ "probe-controls-col"] $ do+          div_ [class_ "control-group-label"] "Toggle modifiers:"+          div_ [class_ "toggle-chip-grid"] $ mapM_ (toggleChip wid) (prToggles pr)+          div_ [class_ "wb-inspector", id_ ("notes-" <> wid)] mempty+  where+    wid = prId pr+    toggleChip :: Text -> ToggleNote -> Html ()+    toggleChip w tn =+      styleChip+        [ data_ "wid" w+        , data_ "bit" (showT (tnBit tn))+        , data_ "probe" (tnKey tn)+        , data_ "impact" (impactCode (tnImpact tn))+        , onmouseenter_ ("previewWidgetNote('" <> w <> "'," <> showT (tnBit tn) <> ")")+        , onmouseleave_ ("clearWidgetPreview('" <> w <> "')")+        , onclick_ ("toggleWidgetBit('" <> w <> "'," <> showT (tnBit tn) <> ")")+        ]+        (tnShort tn)+        (Just ("impact-" <> impactCode (tnImpact tn), impactBadgeText (tnImpact tn)))++-- | Section IV: the 64-combination typography workbench plus reference cards.+typoSection :: TypoSectionData -> Html ()+typoSection tsd = do+  div_+    [ class_ "workbench-card filter-item"+    , data_ "cat" "typography"+    , id_ "typo-workbench"+    , style_ "margin-bottom:16px"+    ]+    $ do+      div_ [class_ "wb-grid"] $ do+        div_ [class_ "wb-viewport-col"] $ do+          div_ [class_ "wb-viewport-head"] $ do+            span_ [class_ "wb-active-label", id_ "typo-active-label"] "No modifiers"+            miniBtn [onclick_ "setTypoMask(0)"] "Reset"+          div_ [class_ "svg-well wb-svg-stage", id_ "typo-svg-well"] (toHtmlRaw (tsdBaseSvg tsd))+          div_ [class_ "wb-code-bar"] (code_ [id_ "typo-code-preview"] "let m = id -- toggle modifiers on the right")+        div_ [class_ "wb-controls-col"] $ do+          div_ [class_ "control-group-label"] "Toggle modifiers:"+          p_ [style_ "margin:0 0 10px 0;font-size:13px;color:var(--ink-secondary)"] $+            inline+              [ Code "labelWith", Txt ", ", Code "textInput", Txt ", ", Code "buttonContent"+              , Txt " take every modifier, and so does ", Code "buttonWith", Txt "."+              ]+          div_ [class_ "toggle-chip-grid", id_ "typo-toggles"] $ mapM_ typoChip typoChips+          div_ [style_ "margin-top:10px;display:flex;gap:6px;flex-wrap:wrap"] $ do+            miniBtn [onclick_ "setTypoMask(63)"] "Enable all"+            miniBtn [onclick_ "setTypoMask(21)"] "Bold, underline, danger"+            miniBtn [onclick_ "setTypoMask(32)"] "fontSize 16"+  mapM_ typoCard (tsdDemos tsd)+  where+    typoChips =+      [ (0 :: Int, "fontBold", "impact-primary", "All rows")+      , (1, "fontItalic", "impact-primary", "All rows")+      , (2, "fontUnderline", "impact-primary", "All rows")+      , (3, "fontStrike", "impact-primary", "All rows")+      , (4, "fontTone Danger", "impact-primary", "All rows")+      , (5, "fontSize 16", "impact-primary", "All rows")+      ]+    typoChip :: (Int, Text, Text, Text) -> Html ()+    typoChip (bit, name, toneCls, tag) =+      styleChip+        [ data_ "tbit" (showT bit)+        , onclick_ ("toggleTypoBit(" <> showT bit <> ")")+        ]+        name+        (Just (toneCls, tag))+    typoCard :: TypoDemo -> Html ()+    typoCard d =+      div_ [class_ "typo-card filter-item", data_ "cat" "typography"] $ do+        div_ [class_ "typo-info"] $ do+          h3_ (toHtml (tdTitle d))+          code_ [class_ "typo-code"] (toHtml (tdCode d))+          p_ (toHtml (tdNote d))+        div_ [class_ "svg-well typo-svg"] (toHtmlRaw (tdSvg d))++-- | Section V: the eight unexpected-interaction cards.+interactionsSection :: [InteractionCard] -> Html ()+interactionsSection = mapM_ trapCard+  where+    trapCard :: InteractionCard -> Html ()+    trapCard c = do+      let tid = icNumber c+      article_+        [ class_ "trap-card filter-item"+        , id_ ("trap-" <> tid)+        , data_ "cat" ("trap " <> icCategory c)+        ]+        $ do+          div_ [class_ "trap-header"] $ do+            div_ [style_ "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px"] $ do+              span_ [class_ "trap-num"] ("INTERACTION #" <> toHtml tid)+              div_ [class_ "trap-mode-bar", data_ "trap" tid] $ do+                button_ [type_ "button", class_ "mini-btn active", onclick_ ("setTrapView('" <> tid <> "','bad',this)")] "⚠ Show Trap"+                button_ [type_ "button", class_ "mini-btn", onclick_ ("setTrapView('" <> tid <> "','good',this)")] "✓ Show Fix"+                button_ [type_ "button", class_ "mini-btn", onclick_ ("setTrapView('" <> tid <> "','split',this)")] "⇄ Side-by-Side"+            h3_ [class_ "trap-title"] (toHtml (icTitle c))+            code_ [class_ "trap-where"] (toHtml (icWhere c))+          div_ [class_ "trap-body"] $ do+            div_ [class_ "trap-prose"] $ do+              div_ [class_ "trap-block"] $ do+                strong_ "Why it happens:"+                txt " "+                prose (icWhy c)+              div_ [class_ "trap-block trap-fix"] $ do+                strong_ "How to handle it:"+                txt " "+                prose (icFix c)+              div_ [class_ "trap-code-grid"] $ do+                div_ [class_ "code-pane code-bad"] $ do+                  div_ [class_ "code-tag"] "Unexpected / Trap"+                  pre_ (code_ (toHtml (icCodeBad c)))+                div_ [class_ "code-pane code-good"] $ do+                  div_ [class_ "code-tag"] "Recommended Pattern"+                  pre_ (code_ (toHtml (icCodeGood c)))+            div_ [class_ "trap-visuals single-view", id_ ("trap-vis-" <> tid)] $ do+              div_ [class_ "trap-svg-box trap-svg-bad", id_ ("trap-bad-" <> tid)] $ do+                div_ [class_ "trap-svg-label"] (toHtml (icLabelA c))+                div_ [class_ "svg-well"] (toHtmlRaw (icSvgA c))+              div_ [class_ "trap-svg-box trap-svg-good hidden-compare", id_ ("trap-good-" <> tid)] $ do+                div_ [class_ "trap-svg-label"] (toHtml (icLabelB c))+                div_ [class_ "svg-well"] (toHtmlRaw (icSvgB c))++buildWidgetMetaValue :: [ProbeRow] -> Value+buildWidgetMetaValue rows =+  object+    [ prId pr+        .= object+          [ "expr" .= prCodeExpr pr+          , "isOverlay" .= prIsOverlay pr+          , "notes" .= prToggles pr+          ]+    | pr <- rows+    ]++buildSvgBanksValue :: Value -> Value -> [ProbeRow] -> TypoSectionData -> Value+buildSvgBanksValue heroBank stateBank rows tsd =+  object $+    [ "hero" .= heroBank+    , "state" .= stateBank+    , "typo" .= tsdBankValue tsd+    ]+      ++ [prId pr .= prBankValue pr | pr <- rows]++buildTrapsValue :: [InteractionCard] -> Value+buildTrapsValue = toJSON++-- | The @aria-label@ attribute, which Lucid does not name.+ariaLabel_ :: Text -> Attributes+ariaLabel_ = makeAttributes "aria-label"++-- | A sidebar navigation list.+navList :: [(Text, Text)] -> Html ()+navList items =+  ul_ [class_ "nav-list"] $+    mapM_ (\(href, navLabel) -> li_ (a_ [href_ href] (toHtml navLabel))) items++-- | A surface-probe legend row.+legendRow :: Text -> Text -> Text -> Html ()+legendRow bg border rowLabel =+  div_ [class_ "legend-row"] $ do+    span_ [class_ "swatch", style_ ("background:" <> bg <> ";border:2px solid " <> border)] mempty+    span_ (toHtml rowLabel)++-- | The fixed sidebar: brand, probe color key, and section/trap links.+sidebarNav :: Html ()+sidebarNav = do+  div_ [class_ "brand-kicker"] "nano-ui-svg Styling Lab"+  h1_ [class_ "brand-title"] "Styling & Surface Glossary"+  p_ [class_ "brand-sub"] $ do+    txt "Toggle any combination of modifiers below. Every preview is a real headless "+    code_ "NanoUI ()"+    txt " frame exported with "+    code_ "frameToSvg"+    txt "."+  div_ [class_ "legend-box"] $ do+    div_ [class_ "nav-group-label", style_ "margin-top:0"] "Surface Probe Color Key"+    legendRow "#0369a1" "#38bdf8" "themeButton (buttonStyle)"+    legendRow "#047857" "#34d399" "themeInput (inputStyle)"+    legendRow "#581c87" "#c084fc" "themePanel (panelStyle)"+    legendRow "#b45309" "#fbbf24" "themePopup (popupStyle)"+    legendRow "#e11d48" "#fb7185" "themeAccent (accentColor)"+  div_ [class_ "nav-group-label"] "Sections"+  navList+    [ ("#sec-states", "I. Interaction States")+    , ("#sec-routing", "II. Surface Routing")+    , ("#sec-matrix", "III. Widget Styles")+    , ("#sec-typo", "IV. Typography")+    , ("#sec-traps", "V. Unexpected Interactions")+    ]+  div_ [class_ "nav-group-label"] "Unexpected Interactions"+  navList trapLinks+  where+    trapLinks =+      [ ("#trap-01", "#01 checkbox 3-Surface + Modal Shift")+      , ("#trap-02", "#02 select vs comboBox Surface")+      , ("#trap-03", "#03 scrollWith grow Loses Well")+      , ("#trap-04", "#04 callout Leaks panelStyle")+      , ("#trap-05", "#05 toggleButton ON Overwrites Style")+      , ("#trap-06", "#06 borderWidth Zero Inset & Sides")+      , ("#trap-07", "#07 (.) Order vs Nested styled")+      , ("#trap-08", "#08 tabs Read themePanel, Not Button")+      ]++-- | The top banner: intro copy and the live composite specimen.+heroSection :: Text -> Html ()+heroSection heroBaseSvg =+  header_ [class_ "hero-banner", id_ "hero-workbench"] $ do+    div_ [class_ "hero-top"] $+      div_ $ do+        h1_ [class_ "hero-title"] $ do+          code_ "nano-ui"+          txt " Styling & Surfaces"+        p_ [class_ "hero-lead"] $ do+          txt "Widgets have no per-widget CSS. A "+          code_ "Theme"+          txt " holds five surface "+          code_ "Style"+          txt " records ("+          code_ "themeButton"+          txt ", "+          code_ "themeInput"+          txt ", "+          code_ "themePanel"+          txt ", "+          code_ "themePopup"+          txt ", "+          code_ "themeFloatingWindow"+          txt "). Toggle styles to see which surface each widget reads."+    div_ [class_ "wb-grid"] $ do+      div_ [class_ "wb-viewport-col"] $ do+        div_ [class_ "wb-viewport-head"] $ do+          span_ [class_ "wb-active-label", id_ "hero-status"] "Composite · defaultTheme (0 modifiers)"+          div_ [class_ "wb-head-actions"] $ do+            miniBtn [onclick_ "setHeroMask(30)"] "All surfaces"+            miniBtn [onclick_ "setHeroMask(0)"] "Reset"+        div_ [class_ "svg-well", id_ "hero-svg-well"] (toHtmlRaw heroBaseSvg)+        div_ [class_ "wb-code-bar"] (code_ [id_ "hero-code-preview"] "compositeDashboardView -- toggle modifiers on the right")+      div_ [class_ "wb-controls-col"] $ do+        div_ [class_ "control-group-label"] "Toggle modifiers:"+        div_ [class_ "toggle-chip-grid", id_ "hero-toggles"] $ mapM_ heroChip heroChips+  where+    heroChips =+      [ (0 :: Int, "light", "Light Theme", "impact-primary", "Base")+      , (1, "btn", "buttonStyle", "impact-primary", "Button")+      , (2, "inp", "inputStyle", "impact-primary", "Input")+      , (3, "pnl", "panelStyle", "impact-primary", "Panel")+      , (4, "acc", "accentColor", "impact-primary", "Accent")+      , (5, "rnd", "rounded 999", "impact-partial", "Partial")+      , (6, "dis", "disabledWhen", "impact-primary", "Dims")+      ]+    heroChip :: (Int, Text, Text, Text, Text) -> Html ()+    heroChip (bit, probe, name, toneCls, tag) =+      styleChip+        [ data_ "hbit" (showT bit)+        , data_ "probe" probe+        , onclick_ ("toggleHeroBit(" <> showT bit <> ")")+        ]+        name+        (Just (toneCls, tag))++-- | The section filter toolbar.+filterBar :: Html ()+filterBar = do+  div_ [class_ "filter-bar", role_ "toolbar", ariaLabel_ "Filter glossary"] $ do+    strong_ [style_ "font-family:var(--font-mono);font-size:12px;margin-right:4px;"] "Filter Sections:"+    filterBtn True "all" "All Specimens"+    filterBtn False "surface-button" "themeButton (buttonStyle)"+    filterBtn False "surface-input" "themeInput (inputStyle)"+    filterBtn False "surface-panel" "themePanel (panelStyle)"+    filterBtn False "typography" "Typography"+    filterBtn False "trap" "8 Unexpected Interactions"+  where+    filterBtn :: Bool -> Text -> Text -> Html ()+    filterBtn active cat btnLabel =+      button_+        [ class_ (if active then "filter-btn active" else "filter-btn")+        , onclick_ ("filterGlossary('" <> cat <> "', this)")+        ]+        (toHtml btnLabel)++-- | Section II: the widget-to-surface routing matrix.+routingTable :: Html ()+routingTable =+  div_ [class_ "routing-table-wrap"] $+    table_ [class_ "routing-table"] $ do+      thead_ (tr_ (mapM_ (\h -> th_ (toHtml h)) routingHeader))+      tbody_ (mapM_ (\cells -> tr_ (mapM_ (td_ . inline) cells)) routingRows)++routingHeader :: [Text]+routingHeader =+  [ "Widget"+  , "Arena NodeType"+  , "Resting Fill / Well"+  , "Border / Outline"+  , "Text / Glyph Color"+  , "Active / Check / Focus Behavior"+  , "Gotchas / Traps"+  ]++-- | One row per widget family; each cell is inline markup.+routingRows :: [[[Snippet]]]+routingRows =+  [ [ [Code "button", Txt ", ", Code "iconButton"]+    , [Code "NodeButton"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleBg"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleBorder"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleFg"]+    , [Txt "Hover: ", Code "styleHoverBg", Txt "; Press: ", Code "styleActiveBg", Txt "; Focus: outer 2px ", Code "themeFocusRing"]+    , [Txt "None"]+    ]+  , [ [Code "toggleButton"]+    , [Code "NodeButton", Txt " (toggle)"]+    , [Txt "OFF: ", Badge "b-btn" "themeButton", Brk, Txt "ON: ", Badge "b-acc" "toneColor"]+    , [Txt "OFF: ", Badge "b-btn" "themeButton", Brk, Txt "ON: ", Badge "b-acc" "toneColor"]+    , [Txt "OFF: ", Badge "b-btn" "themeButton", Brk, Txt "ON: ", Code "readableOn"]+    , [Txt "When ON, overwrites ", Code "styleBg", Txt ", ", Code "styleHoverBg", Txt ", ", Code "styleBorder", Txt ", ", Code "styleFg"]+    , [Link "#trap-05" [Txt "ON state ignores ", Code "buttonStyle", Txt " colors (#05)"]]+    ]+  , [ [Code "checkbox", Txt ", ", Code "radio"]+    , [Code "NodeButton", Txt " (choice)"]+    , [Txt "Unchecked well: ", Badge "b-inp" "themeInput", Txt " ", Code "styleBg"]+    , [Txt "Unchecked ring/box: ", Badge "b-btn" "themeButton", Txt " ", Code "styleBorder"]+    , [Txt "Label: ", Badge "b-btn" "themeButton", Txt " ", Code "styleFg"]+    , [Txt "Checked box/dot: ", Badge "b-acc" "themeAccent", Txt " + ", Code "themeOnAccent"]+    , [Link "#trap-01" [Txt "3-surface split + switches to ", Code "themePopup", Txt " in ", Code "modal", Txt " (#01)"]]+    ]+  , [ [Code "select"]+    , [Code "NodeSelect"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleBg"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleBorder"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleFg", Txt " (text & chevron)"]+    , [Txt "Focused border: ", Badge "b-acc" "themeAccent", Txt "; Open menu: ", Badge "b-pop" "themePopup"]+    , [Link "#trap-02" [Txt "Uses ", Code "themeButton", Txt ", not ", Code "themeInput", Txt " (#02)"]]+    ]+  , [ [Code "comboBox"]+    , [Code "NodeTextInput"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleBg"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleBorder"]+    , [Txt "Text: ", Badge "b-inp" "themeInput", Txt " ", Code "styleFg", Txt "; Chevron: 45% lerp to bg"]+    , [Txt "Focused border: ", Badge "b-acc" "themeAccent", Txt ", bg: ", Code "styleActiveBg", Txt "; Menu: ", Badge "b-pop" "themePopup"]+    , [Link "#trap-02" [Txt "Paired with ", Code "select", Txt " but on ", Code "themeInput", Txt " (#02)"]]+    ]+  , [ [Code "textInput", Txt ", ", Code "searchInput", Txt ", ", Code "numericInput", Txt ", ", Code "textArea"]+    , [Code "NodeTextInput", Txt " / ", Code "NodeTextArea"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleBg"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleBorder"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleFg", Txt " (placeholder 40% lerp to bg)"]+    , [Txt "Focused: swaps border to ", Badge "b-acc" "themeAccent", Txt " & bg to ", Code "styleActiveBg(themeInput)", Txt " (no outer ring)"]+    , [Txt "None"]+    ]+  , [ [Code "slider"]+    , [Code "NodeSlider"]+    , [Txt "35% lerp from ", Badge "b-inp" "themeInput", Txt " ", Code "styleBg", Txt " to ", Code "styleBorder"]+    , [Badge "b-inp" "themeInput", Txt " ", Code "styleBorder", Txt " (1px fixed)"]+    , [Txt "Thumb fill: ", Code "themeOnAccent"]+    , [Txt "Filled bar: ", Badge "b-acc" "themeAccent", Txt "; Focus: outer ", Code "themeFocusRing"]+    , [Txt "Ignores ", Code "borderWidth", Txt " and ", Code "cornerRadius", Txt " (hardcoded 1px / 3px)"]+    ]+  , [ [Code "panel", Txt ", ", Code "card", Txt ", ", Code "callout"]+    , [Code "NodePanel"]+    , [Badge "b-pnl" "themePanel", Txt " ", Code "styleBg"]+    , [Badge "b-pnl" "themePanel", Txt " ", Code "styleBorder"]+    , [Txt "Inherited by child ", Code "label", Txt "s via ", Badge "b-pnl" "themePanel", Txt " ", Code "styleFg"]+    , [Txt "Clips children to ", Code "borderContentClip"]+    , [Link "#trap-04" [Code "callout", Txt " leaks tinted ", Code "panelStyle", Txt " to child panels (#04)"]]+    ]+  , [ [Code "label", Txt ", ", Code "heading", Txt ", ", Code "kv"]+    , [Code "NodeText"]+    , [Txt "Transparent (except in ", Code "frameToSvg", Txt " or striped tables)"]+    , [Txt "None"]+    , [Badge "b-pnl" "themePanel", Txt " ", Code "styleFg", Txt " (or ", Code "fontColor", Txt " / ", Code "fontTone", Txt ")"]+    , [Code "heading", Txt " is ", Code "fontHeading", Txt ": medium weight in ", Badge "b-pnl" "themePanel", Txt " ", Code "styleFg"]+    , [Txt "None"]+    ]+  , [ [Code "scrollWith"]+    , [Code "NodeScroll"]+    , [Txt "Bounded: ", Badge "b-inp" "themeInput", Txt " ", Code "styleBg", Brk, Code "grow", Txt ": ", Code "pageBackground"]+    , [Txt "Bounded: ", Badge "b-inp" "themeInput", Txt " ", Code "styleBorder", Brk, Code "grow", Txt ": None"]+    , [Txt "Scrollbar blends ", Badge "b-inp" "themeInput", Txt " + ", Code "themeSeparator"]+    , [Txt "Always forces ", Code "styleCornerRadius = 0", Txt " on the scroll well"]+    , [Link "#trap-03" [Code "scrollWith grow", Txt " drops well & border (#03)"]]+    ]+  , [ [Code "tabs", Txt ", ", Code "tabBar"]+    , [Code "NodeButton", Txt " (tab)"]+    , [Badge "b-pnl" "themePanel", Txt " / ", Badge "b-acc" "themeAccent"]+    , [Badge "b-pnl" "themePanel", Txt " (", Code "TabSegmented", Txt " uses ", Badge "b-btn" "themeButton", Txt ")"]+    , [Badge "b-pnl" "themePanel", Txt " ", Code "styleFg", Txt " (inactive dimmed to alpha 175)"]+    , [Txt "Selected indicator: ", Badge "b-acc" "themeAccent"]+    , [Link "#trap-08" [Txt "Ignores ", Code "buttonStyle", Txt " on 3 of 4 tab styles (#08)"]]+    ]+  , [ [Code "table", Txt ", ", Code "simpleTable"]+    , [Code "NodePanel", Txt " + ", Code "NodeButton", Txt " + ", Code "NodeText"]+    , [Txt "Headers: 55% ", Badge "b-pnl" "themePanel", Txt " + ", Badge "b-btn" "themeButton", Txt "; Rows: striped"]+    , [Txt "Outer: ", Badge "b-pnl" "themePanel", Txt "; Dividers: ", Code "themeSeparator"]+    , [ Txt "Cells: ", Badge "b-pnl" "themePanel", Txt " ", Code "styleFg"+      , Txt "; Sorted hdr: ", Badge "b-btn" "themeButton", Txt " ", Code "styleFg"+      , Txt "; Unsorted: ", Code "themeMuted"+      ]+    , [Txt "Selected row blends 25% toward ", Badge "b-acc" "themeAccent"]+    , [Txt "Unsorted headers ignore ", Code "buttonStyle (foreground ...)"]+    ]+  , [ [Code "tree"]+    , [Code "NodeButton", Txt " (row)"]+    , [Txt "Even: 25% ", Code "themeWindow", Txt "; Odd: 35% ", Badge "b-btn" "themeButton", Txt " over ", Badge "b-pnl" "themePanel"]+    , [Txt "None (forced 0)"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleFg", Txt " (label & chevron)"]+    , [Txt "Selected row blends 25% toward ", Badge "b-acc" "themeAccent"]+    , [Txt "Row stripes blend 3 surfaces"]+    ]+  , [ [Code "modal", Txt ", ", Code "popup", Txt ", ", Code "menuItem"]+    , [Code "NodeFloatingPanel", Txt " / ", Code "NodeButton"]+    , [Badge "b-pop" "themePopup", Txt " ", Code "styleBg", Txt " (scrim: ", Code "themeOverlayDim", Txt ")"]+    , [Badge "b-pop" "themePopup", Txt " ", Code "styleBorder"]+    , [Badge "b-pop" "themePopup", Txt " ", Code "styleFg"]+    , [Txt "Menu hover falls back to ", Badge "b-btn" "themeButton", Txt " ", Code "styleHoverBg", Txt " when popup ", Code "hoverBg == bg"]+    , [Txt "Inner ", Code "panel", Txt "s inside a modal still read ", Code "themePanel"]+    ]+  , [ [Code "toggleSwitch", Txt ", ", Code "progressBar", Txt ", ", Code "knob", Txt ", ", Code "sparkline"]+    , [Code "NodeDrawing"]+    , [Txt "Controls: ", Badge "b-btn" "themeButton", Txt " ", Code "styleBg", Brk, Code "sparkline", Txt ": ", Badge "b-pnl" "themePanel", Txt " ", Code "styleBg"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleBorder", Txt " (1 to 1.5px fixed)"]+    , [Badge "b-btn" "themeButton", Txt " ", Code "styleFg"]+    , [Txt "Active fill/arc/line: ", Badge "b-acc" "themeAccent", Txt " + ", Code "themeOnAccent"]+    , [Txt "Custom canvas paths ignore ", Code "cornerRadius", Txt " & ", Code "borderWidth"]+    ]+  ]++-- | Section III master controls: apply one mask to every widget card at once.+masterBar :: Html ()+masterBar = do+  div_ [class_ "master-bar"] $ do+    div_ [class_ "master-bar-top"] $ do+      span_ [class_ "master-bar-title"] "Apply a style to every widget:"+      div_ [class_ "wb-head-actions"] $ do+        miniBtn [onclick_ "setAllWidgetsMask(30)"] "All surfaces"+        miniBtn [onclick_ "setAllWidgetsMask(6)"] "Button and input"+        miniBtn [onclick_ "setAllWidgetsMask(32)"] "Rounded 999"+        miniBtn [id_ "global-cmp-btn", onclick_ "toggleGlobalCompare()"] "⇄ Compare all"+        miniBtn [onclick_ "setAllWidgetsMask(0)"] "Reset all"+    div_ [class_ "toggle-chip-grid", id_ "master-toggles"] $ mapM_ globalChip globalChips+  where+    globalChips =+      [ (0 :: Int, "light", "defaultLightTheme")+      , (1, "btn", "buttonStyle")+      , (2, "inp", "inputStyle")+      , (3, "pnl", "panelStyle")+      , (4, "acc", "accentColor")+      , (5, "rnd", "rounded 999")+      , (6, "dis", "disabledWhen True")+      ]+    globalChip :: (Int, Text, Text) -> Html ()+    globalChip (bit, probe, name) =+      styleChip+        [ data_ "gbit" (showT bit)+        , data_ "probe" probe+        , onclick_ ("toggleGlobalBit(" <> showT bit <> ")")+        ]+        name+        Nothing++-- | The whole page. Lucid escapes text and attributes; the stylesheet, script,+-- JSON payloads, and rendered SVG documents go in raw because they are not+-- prose to escape.+glossaryPage ::+  Assets ->+  (Text, Value) ->+  (Text, Value) ->+  [ProbeRow] ->+  TypoSectionData ->+  [InteractionCard] ->+  Html ()+glossaryPage assets (heroBaseSvg, heroBankVal) (stateBaseSvg, stateBankVal) probeRows typoData interactions = do+  doctype_+  html_ [lang_ "en"] $ do+    head_ $ do+      meta_ [charset_ "utf-8"]+      meta_ [name_ "viewport", content_ "width=device-width, initial-scale=1"]+      title_ "nano-ui Styling & Surface Glossary"+      style_ (assetsFontCss assets <> "\n" <> assetsCss assets)+    body_ $ do+      div_ [class_ "layout-shell"] $ do+        aside_ [class_ "sidebar"] sidebarNav+        main_ [class_ "main-content"] $ do+          heroSection heroBaseSvg+          filterBar+          section_ [id_ "sec-states"] $ do+            sectionHead [Txt "I. Interaction States"] [Txt "Prerendered"]+            stateStripSection stateBaseSvg+          section_ [id_ "sec-routing"] $ do+            sectionHead [Txt "II. Surface Routing"] [Txt "Which theme slot paints what"]+            routingTable+          section_ [id_ "sec-matrix"] $ do+            sectionHead [Txt "III. Widget Styles"] [Txt "Prerendered"]+            masterBar+            mapM_ probeRowCard probeRows+          section_ [id_ "sec-typo"] $ do+            sectionHead [Txt "IV. Typography"] [Txt "Modifiers and specimens"]+            div_ [class_ "typo-grid"] (typoSection typoData)+          section_ [id_ "sec-traps"] $ do+            sectionHead [Txt "V. Unexpected Interactions"] [Txt "Click to compare"]+            interactionsSection interactions+      script_ banksJs+      script_ (assetsJs assets)+  where+    banksJs =+      "const SVG_BANKS = "+        <> encodeJsonText (buildSvgBanksValue heroBankVal stateBankVal probeRows typoData)+        <> ";\nconst WIDGET_META = "+        <> encodeJsonText (buildWidgetMetaValue probeRows)+        <> ";"++buildHtmlDocument ::+  Assets ->+  (Text, Value) ->+  (Text, Value) ->+  [ProbeRow] ->+  TypoSectionData ->+  [InteractionCard] ->+  Text+buildHtmlDocument assets hero state rows typo interactions =+  TL.toStrict (renderText (glossaryPage assets hero state rows typo interactions))
+ app/Glossary/Render.hs view
@@ -0,0 +1,413 @@+-- | Headless rendering for the glossary: SVG contexts and font metrics, the+-- page assets, frame export and cropping, the probe themes that colour+-- each surface, and the compact encoding of SVG banks.+module Glossary.Render+  ( Assets (..)+  , canvasSlack+  , cropSvg+  , encodeJsonText+  , exportFrame+  , frameInkBounds+  , framePad+  , loadAssets+  , newSvgContext+  , packSvgBank+  , probeAccent+  , probeButton+  , probeInput+  , probePanel+  , probePopup+  , renderStyleBank+  , renderSvg+  , renderSvgClick+  , renderSvgHover+  , renderSvgPress+  , sdlFontCtxRef+  ) where++import Control.Monad (forM)+import Data.Aeson.Micro (ToJSON (..), Value, encode, object, (.=))+import Data.Bits (shiftL, shiftR, testBit, (.&.))+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as BSL+import Data.IORef (IORef, newIORef, readIORef)+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding (decodeUtf8)+import Data.Word (Word8)+import Foreign.ForeignPtr (withForeignPtr)+import Foreign.Storable (peekByteOff)+import System.Directory (doesFileExist)+import NanoUI+import NanoUI.Backend (DrawData (..), FontMetrics (..), collectRasterSpans, damageFullNow, monospaceMetrics, vertexSize)+import NanoUI.Draw.FrameSvg (FrameSvgConfig (..), defaultFrameSvgConfig, enableSvgExport, frameToSvg)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Testing (newPixelContext, runFrame, withFontMetrics, withMonoFontMetrics)+import NanoUI.Testing.Harness (clickPair, pressAt, withInputOff)+import NanoUI.Ttf.Internal.Inter (fontInterBytes)+import Paths_nano_ui_svg (getDataFileName)+import System.IO.Unsafe (unsafePerformIO)++-- ---------------------------------------------------------------------------+-- Headless Frame-to-SVG Renderers+-- ---------------------------------------------------------------------------++-- | Holds the live SDL context initialized with the embedded @inter.ttf@+-- ('DefaultFont') during 'main' so each specimen's fresh 'Context' inherits+-- real TrueType/HarfBuzz glyph shaping and line metrics.+{-# NOINLINE sdlFontCtxRef #-}+sdlFontCtxRef :: IORef (Maybe Context)+sdlFontCtxRef = unsafePerformIO (newIORef Nothing)++-- | Fallback proportional metrics if run outside 'withSdl'.+svgProportionalMetrics :: FontMetrics+svgProportionalMetrics = svgMonoMetrics {fmAdvance = charAdvance}+  where+    charAdvance :: Char -> Float+    charAdvance c+      | c == ' ' = 4+      | c `elem` ("ilI1.,:;!|'()[]" :: String) = 4+      | c `elem` ("fjrt-/\"" :: String) = 5+      | c `elem` ("mwMW@%#+=>" :: String) = 10+      | c >= 'A' && c <= 'Z' = 8.5+      | otherwise = 7.5++svgMonoMetrics :: FontMetrics+svgMonoMetrics =+  (monospaceMetrics 8)+    { fmLineHeight = 17+    , fmAscent = 13.5+    , fmSnapScale = 0+    , fmAdvance = \c -> if c == ' ' then 4 else 8+    }++newSvgContext :: IO Context+newSvgContext = do+  ctx0 <- newPixelContext+  mSdl <- readIORef sdlFontCtxRef+  let ctx = case mSdl of+        Just sdlCtx ->+          ctx0+            { ctxFontMetrics = ctxFontMetrics sdlCtx+            , ctxMonoFontMetrics = ctxMonoFontMetrics sdlCtx+            , ctxFontSize = ctxFontSize sdlCtx+            , ctxMeasureText = ctxMeasureText sdlCtx+            , ctxResolveFont = ctxResolveFont sdlCtx+            , ctxResolveMeasure = ctxResolveMeasure sdlCtx+            , ctxMetricSource = ctxMetricSource sdlCtx+            }+        Nothing ->+          withMonoFontMetrics (withFontMetrics ctx0 svgProportionalMetrics) svgMonoMetrics+  ctx <$ enableSvgExport ctx++-- | Pure Base64 encoder for embedding @packages/nano-ui-sdl/data/inter.ttf@+-- as a @data:font/ttf;base64,...@ @\@font-face@ in the HTML glossary.+encodeBase64 :: ByteString -> Text+encodeBase64 bs = T.pack (go 0)+  where+    len = BS.length bs+    alphabet :: ByteString+    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"+    b64Char :: Int -> Char+    b64Char idx = toEnum (fromIntegral (BS.index alphabet (idx .&. 0x3F)))+    byteAt :: Int -> Int+    byteAt i = fromIntegral (BS.index bs i :: Word8)+    go :: Int -> String+    go i+      | i >= len = []+      | i + 2 < len =+          let n = (byteAt i `shiftL` 16) + (byteAt (i + 1) `shiftL` 8) + byteAt (i + 2)+           in b64Char (n `shiftR` 18)+                : b64Char (n `shiftR` 12)+                : b64Char (n `shiftR` 6)+                : b64Char n+                : go (i + 3)+      | i + 1 < len =+          let n = (byteAt i `shiftL` 16) + (byteAt (i + 1) `shiftL` 8)+           in [b64Char (n `shiftR` 18), b64Char (n `shiftR` 12), b64Char (n `shiftR` 6), '=']+      | otherwise =+          let n = byteAt i `shiftL` 16+           in [b64Char (n `shiftR` 18), b64Char (n `shiftR` 12), '=', '=']++loadInterFontCss :: IO Text+loadInterFontCss =+  pure $+    "@font-face { font-family: 'Inter'; font-style: normal; font-weight: 100 900; font-display: block; src: url('data:font/ttf;base64,"+      <> encodeBase64 fontInterBytes+      <> "') format('truetype'); }"++-- | Static assets that live beside the source instead of inside it: the+-- stylesheet and script are edited as plain CSS and JavaScript and spliced+-- into the generated document so the result stays self-contained.+data Assets = Assets+  { assetsFontCss :: !Text+  -- ^ @\@font-face@ rule for the embedded Inter face, or empty.+  , assetsCss :: !Text+  -- ^ @assets/glossary.css@.+  , assetsJs :: !Text+  -- ^ @assets/glossary.js@.+  }++-- | Load the embedded font rule and the page's stylesheet and script from the+-- package's data files. The document also embeds every specimen, so the data+-- payload (font + SVG banks) is written inline at generation time.+--+-- Resolution tries the installed data directory first (via @Paths_@) and then+-- a few source-relative paths, so the tool also runs straight from a checkout+-- with @cabal run@ or the built executable.+loadAssets :: IO Assets+loadAssets = do+  fontCss <- loadInterFontCss+  css <- readAsset "glossary.css"+  js <- readAsset "glossary.js"+  pure Assets {assetsFontCss = fontCss, assetsCss = css, assetsJs = js}+  where+    readAsset name = do+      dataPath <- getDataFileName ("assets/" <> T.unpack name)+      let candidates =+            [ dataPath+            , "packages/nano-ui-svg/assets/" <> T.unpack name+            , "../nano-ui-svg/assets/" <> T.unpack name+            , "assets/" <> T.unpack name+            ]+      found <- findFirst candidates+      case found of+        Just path -> T.stripEnd . decodeUtf8 <$> BS.readFile path+        Nothing ->+          ioError . userError $+            "glossary asset not found: " <> T.unpack name <> " (looked in " <> show candidates <> ")"+    findFirst [] = pure Nothing+    findFirst (p : ps) = do+      ok <- doesFileExist p+      if ok then pure (Just p) else findFirst ps++-- | Extra canvas height given to specimens. Widgets can lay out past the+-- nominal height (a tab strip's last row, an overlay's shadow), and the crop+-- recovers it; width is left exact so fill-width demos keep their measure.+canvasSlack :: Float+canvasSlack = 72++-- | Union of a frame's solid geometry (vertex positions) and text line boxes.+-- The full-window backdrop that 'frameToSvg' paints is in neither, so this is+-- the ink a reader sees.+frameInkBounds :: Context -> Input -> DrawData -> IO (Maybe Rect)+frameInkBounds ctx inp dd = do+  verts <- vertexPoints dd+  (pageSpans, overlaySpans) <- collectRasterSpans ctx inp+  let boxes = [Rect x y 0 0 | (x, y) <- verts] <> [r | (r, _, _, _, _) <- pageSpans <> overlaySpans]+  pure $ case boxes of+    (b : rest) -> Just (foldl' rectUnion b rest)+    [] -> Nothing++-- | Every vertex position in the frame's solid-geometry buffer.+vertexPoints :: DrawData -> IO [(Float, Float)]+vertexPoints dd =+  withForeignPtr (drawVertices dd) $ \vp ->+    forM [0 .. drawVertexCount dd - 1] $ \i -> do+      x <- peekByteOff vp (i * vertexSize) :: IO Float+      y <- peekByteOff vp (i * vertexSize + 4) :: IO Float+      pure (x, y)++-- | Crop a rendered SVG to its painted bounds (plus padding), rewriting the+-- root @<svg>@ tag's @width@, @height@, and @viewBox@. Height tightens to the+-- content but never past the canvas (whose backdrop is the frame's only+-- background); width stays at @canvasW@ unless content overhangs it. Scale+-- stays 1:1.+cropSvg :: Float -> Float -> Maybe Rect -> Text -> Text+cropSvg _ _ Nothing svg = svg+cropSvg canvasW canvasH (Just (Rect bx by bw bh)) svg+  | not ("<svg" `T.isPrefixOf` open) || T.null rest = svg+  | otherwise = header <> rest+  where+    (open, rest) = T.breakOn ">" svg+    pad = 8+    minY = max 0 (floor (by - pad) :: Int)+    maxY = min (ceiling canvasH) (ceiling (by + bh + pad))+    h = max 1 (maxY - minY)+    w =+      if bx + bw > canvasW + 0.5+        then ceiling (bx + bw + pad)+        else round canvasW+    header =+      "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\""+        <> tshow w+        <> "\" height=\""+        <> tshow h+        <> "\" viewBox=\"0 "+        <> tshow minY+        <> " "+        <> tshow w+        <> " "+        <> tshow h+        <> "\""+    tshow = T.pack . show++-- | Warm a view over zero or more frames, then run one final frame with+-- 'damageFullNow' and export it as an inline @<svg>@ element whose ids+-- carry @tag@, so the documents on one page never collide.+--+-- Every frame in 'warmInputs' is run once without damage to settle layout+-- and state; the 'captureInput' frame is the one returned.+captureSvg :: Text -> [Input] -> Input -> NanoUI () -> IO Text+captureSvg tag warmInputs captureInput ui = do+  ctx <- newSvgContext+  mapM_ (\inp -> runFrame ctx inp ui) warmInputs+  fst <$> exportFrame tag ctx captureInput ui++-- | Run one frame of @ui@ with 'damageFullNow' and export it with its ids+-- prefixed by @tag@, returning the SVG and the frame's draw data.+exportFrame :: Text -> Context -> Input -> NanoUI () -> IO (Text, DrawData)+exportFrame tag ctx inp ui = do+  (_, dd, _) <- runFrame ctx inp (ui >> damageFullNow)+  svg <- frameToSvg defaultFrameSvgConfig {fsIdPrefix = tag <> "-"} ctx inp dd+  pure (svg, dd)++-- | Render a two-frame warmed-up view with rounded geometry and external text+-- spans, returning a namespaced inline @<svg>@ element.+renderSvg :: Text -> Float -> Float -> NanoUI () -> IO Text+renderSvg tag w h ui = captureSvg tag [inp] inp ui+  where+    inp = withInputOff w h++-- | Render a view with the cursor hovering at @pos@ on the second frame.+renderSvgHover :: Text -> Float -> Float -> V2 -> NanoUI () -> IO Text+renderSvgHover tag w h pos ui = captureSvg tag [base] (base {inputMousePos = pos}) ui+  where+    base = withInputOff w h++-- | Render a view with the left mouse button held down at @pos@.+renderSvgPress :: Text -> Float -> Float -> V2 -> NanoUI () -> IO Text+renderSvgPress tag w h pos ui = captureSvg tag [base] (pressAt base pos) ui+  where+    base = withInputOff w h++-- | Warm up a view, click at @pos@ (press + release frames), and capture the+-- resulting frame (e.g. focused field or open dropdown overlay).+renderSvgClick :: Text -> Float -> Float -> V2 -> NanoUI () -> IO Text+renderSvgClick tag w h pos ui =+  captureSvg tag [base, press, release] base ui+  where+    base = withInputOff w h+    (press, release) = clickPair base pos++-- ---------------------------------------------------------------------------+-- Diagnostic Surface Probe Modifiers+-- ---------------------------------------------------------------------------++-- Distinct high-contrast surface probes used across the matrix so the reader+-- can visually trace which Style record inside Theme paints each pixel.++probeSurface :: ((Style -> Style) -> Theme -> Theme) -> (Color -> Style -> Style) -> Color -> Color -> Color -> Theme -> Theme+probeSurface target fill bg fg bd =+  target (fill bg . foreground fg . borderColor bd . borderWidth 2)++probeButton :: Theme -> Theme+probeButton = probeSurface buttonStyle fillColor (colorRGBA 3 105 161 255) (colorRGBA 224 242 254 255) (colorRGBA 56 189 248 255)++probeInput :: Theme -> Theme+probeInput = probeSurface inputStyle fillColor (colorRGBA 4 120 87 255) (colorRGBA 209 250 229 255) (colorRGBA 52 211 153 255)++probePanel :: Theme -> Theme+probePanel = probeSurface panelStyle background (colorRGBA 88 28 135 255) (colorRGBA 243 232 255 255) (colorRGBA 192 132 252 255)++probePopup :: Theme -> Theme+probePopup = probeSurface popupStyle fillColor (colorRGBA 180 83 9 255) (colorRGBA 254 243 199 255) (colorRGBA 251 191 36 255)++probeWindow :: Theme -> Theme+probeWindow = probeSurface windowStyle background (colorRGBA 30 27 75 255) (colorRGBA 224 231 255 255) (colorRGBA 129 140 248 255)++probeAccent :: Theme -> Theme+probeAccent =+  accentColor (colorRGBA 225 29 72 255)++-- | Frame wrapper that keeps label raster spans transparent unless panelStyle+-- itself is being tested or a panel is drawn.+framePad :: NanoUI () -> NanoUI ()+framePad body =+  columnWith (fillW . fillH . padAll 8 . gap 6) body++-- ---------------------------------------------------------------------------+-- Compact Lossless SVG Combination Bank Encoder (via microaeson)+-- ---------------------------------------------------------------------------++encodeJsonText :: ToJSON a => a -> Text+encodeJsonText = decodeUtf8 . BSL.toStrict . encode++-- | Split each SVG document by @"><"@ (every XML tag boundary) and deduplicate+-- shared tags across all combinations of a widget into @{"l":[...],"c":[[...],...]}@.+-- In JS, @bank.c[mask].map(i => bank.l[i]).join('><')@ losslessly reconstructs+-- the exact 'frameToSvg' output for any bitmask combination.+packSvgBank :: [Text] -> Value+packSvgBank svgs =+  let step (nextIdx, tagMap, revTags, revCombos) svg =+        let tags = T.splitOn "><" svg+            (nextIdx', tagMap', revTags', idxs) =+              foldl'+                ( \(i, mp, rts, acc) tag ->+                    case Map.lookup tag mp of+                      Just existingIdx -> (i, mp, rts, existingIdx : acc)+                      Nothing -> (i + 1, Map.insert tag i mp, tag : rts, i : acc)+                )+                (nextIdx, tagMap, revTags, [])+                tags+         in (nextIdx', tagMap', revTags', reverse idxs : revCombos)+      (_, _, revUniqueTags, revComboLists) = foldl' step (0 :: Int, Map.empty, [], []) svgs+      uniqueTags = reverse revUniqueTags+      comboLists = reverse revComboLists+   in object+        [ "l" .= uniqueTags+        , "c" .= comboLists+        ]++-- | Apply a 7-bit style combination mask (0..127) to a widget subtree:+--+-- * Bit 0 (1):  'themed' 'defaultLightTheme'+-- * Bit 1 (2):  'styled' 'probeButton' (@buttonStyle@)+-- * Bit 2 (4):  'styled' 'probeInput' (@inputStyle@)+-- * Bit 3 (8):  'styled' 'probePanel' (@panelStyle@, plus @popupStyle@/@windowStyle@ on overlays)+-- * Bit 4 (16): 'styled' 'probeAccent' (@accentColor@)+-- * Bit 5 (32): 'styled' (@everyStyle rounded@) (@cornerRadius 999@)+-- * Bit 6 (64): 'disabledWhen' 'True'+applyStyleMask :: Bool -> Int -> NanoUI () -> NanoUI ()+applyStyleMask isOverlay mask view0 =+  let applyBase =+        if testBit mask 0+          then (setTheme defaultLightTheme >>) . themed defaultLightTheme+          else (setTheme defaultTheme >>)+      hasThemeMod = (mask .&. 0x3E) /= 0+      pnlMod = if isOverlay then probePanel . probePopup . probeWindow else probePanel+      themeMod =+        (if testBit mask 5 then rounded 999 else id)+          . (if testBit mask 4 then probeAccent else id)+          . (if testBit mask 3 then pnlMod else id)+          . (if testBit mask 2 then probeInput else id)+          . (if testBit mask 1 then probeButton else id)+      applyStyled = if hasThemeMod then styled themeMod else id+      applyDis = if testBit mask 6 then disabledWhen True else id+   in applyBase (applyStyled (applyDis view0))++-- | Render all 128 combinations (0..127) of the 7 interactive style toggles+-- for a widget, returning @(baselineSvg, packedBankJson)@. Every frame is+-- cropped to the bank's shared painted bounds, so toggling a style never+-- resizes the specimen.+renderStyleBank :: Text -> Float -> Float -> Bool -> NanoUI () -> IO (Text, Value)+renderStyleBank bankId w h isOverlay view = do+  ctx <- newSvgContext+  let inp = withInputOff w h+      nsTag = "wb-" <> bankId+  _ <- runFrame ctx inp view+  caps <- forM [0 .. 127] $ \mask -> do+    (svg, dd) <- exportFrame nsTag ctx inp (applyStyleMask isOverlay mask view)+    bounds <- frameInkBounds ctx inp dd+    pure (svg, bounds)+  let boxes = [b | (_, Just b) <- caps]+      cropBox = case boxes of+        (b0 : bs) -> Just (foldl' rectUnion b0 bs)+        [] -> Nothing+      svgs = [cropSvg w h cropBox svg | (svg, _) <- caps]+      baseSvg = case svgs of+        (s0 : _) -> s0+        [] -> ""+  pure (baseSvg, packSvgBank svgs)
+ app/Glossary/Specimens.hs view
@@ -0,0 +1,1016 @@+-- | The glossary's specimen data: per-widget style cards, typography demos,+-- unexpected interactions, the state strip and the hero banner, each+-- rendered to SVG through "Glossary.Render".+module Glossary.Specimens+  ( InteractionCard (..)+  , ProbeRow (..)+  , ToggleNote (..)+  , TypoDemo (..)+  , TypoSectionData (..)+  , generateInteractions+  , generateProbeMatrix+  , generateRainbowBanner+  , generateStateStrip+  , generateTypoDemos+  , impactBadgeText+  , impactCode+  ) where++import Control.Monad (forM, void)+import Data.Aeson.Micro (ToJSON (..), Value, object, (.=))+import Data.Bits (testBit, (.&.))+import Data.Text (Text)+import Glossary.Render+  ( canvasSlack+  , exportFrame+  , framePad+  , newSvgContext+  , packSvgBank+  , probeAccent+  , probeButton+  , probeInput+  , probePanel+  , probePopup+  , renderStyleBank+  , renderSvg+  , renderSvgClick+  , renderSvgHover+  , renderSvgPress+  )+import NanoUI+import NanoUI.Testing (runFrame)+import NanoUI.Testing.Harness (withInputOff)++-- ---------------------------------------------------------------------------+-- Section II: Interactive Per-Widget Style Workbench Cards (15 Families)+-- ---------------------------------------------------------------------------++data ImpactKind+  = ImpactPrimary+  | ImpactPartial+  | ImpactSurprise+  | ImpactNoOp++impactCode :: ImpactKind -> Text+impactCode = \case+  ImpactPrimary -> "primary"+  ImpactPartial -> "partial"+  ImpactSurprise -> "surprise"+  ImpactNoOp -> "noop"++impactBadgeText :: ImpactKind -> Text+impactBadgeText = \case+  ImpactPrimary -> "Primary"+  ImpactPartial -> "Partial"+  ImpactSurprise -> "Edge case"+  ImpactNoOp -> "No-op"++data ToggleNote = ToggleNote+  { tnBit :: !Int+  , tnKey :: !Text+  , tnLabel :: !Text+  , tnShort :: !Text+  , tnImpact :: !ImpactKind+  , tnDetail :: !Text+  }++mkToggleNotes :: [(ImpactKind, Text)] -> [ToggleNote]+mkToggleNotes specs =+  [ ToggleNote bit key lbl short imp det+  | ((bit, key, lbl, short), (imp, det)) <- zip meta specs+  ]+  where+    meta :: [(Int, Text, Text, Text)]+    meta =+      [ (0, "light", "defaultLightTheme", "Light Theme")+      , (1, "btn", "buttonStyle", "buttonStyle")+      , (2, "inp", "inputStyle", "inputStyle")+      , (3, "pnl", "panelStyle", "panelStyle")+      , (4, "acc", "accentColor", "accentColor")+      , (5, "rnd", "rounded 999", "rounded 999")+      , (6, "dis", "disabledWhen True", "disabledWhen")+      ]++data ProbeRow = ProbeRow+  { prId :: !Text+  , prIsOverlay :: !Bool+  , prCategory :: !Text+  , prTitle :: !Text+  , prSignature :: !Text+  , prPrimarySurface :: !Text+  , prSummary :: !Text+  , prCodeExpr :: !Text+  , prToggles :: ![ToggleNote]+  , prBaselineSvg :: !Text+  , prBankValue :: !Value+  }++buildProbeRow ::+  Text ->+  Text ->+  Text ->+  Text ->+  Text ->+  Text ->+  Text ->+  Bool ->+  Float ->+  Float ->+  [(ImpactKind, Text)] ->+  NanoUI () ->+  IO ProbeRow+buildProbeRow rid cat title sig surf summary codeExpr isOverlay w h notes view = do+  (baseSvg, bankVal) <- renderStyleBank rid w (h + canvasSlack) isOverlay (framePad view)+  pure+    ProbeRow+      { prId = rid+      , prIsOverlay = isOverlay+      , prCategory = cat+      , prTitle = title+      , prSignature = sig+      , prPrimarySurface = surf+      , prSummary = summary+      , prCodeExpr = codeExpr+      , prToggles = mkToggleNotes notes+      , prBaselineSvg = baseSvg+      , prBankValue = bankVal+      }++generateProbeMatrix :: IO [ProbeRow]+generateProbeMatrix =+  sequence+    [ buildProbeRow+        "button"+        "surface-button"+        "button (normal, subtle)"+        "button :: Text -> NanoUI Bool"+        "themeButton"+        "Reads `styleBg`, `styleHoverBg`, `styleActiveBg`, `styleFg`, `styleBorder`, `styleBorderWidth`, and `styleCornerRadius` from `themeButton`. Focus adds a 2px `themeFocusRing` outline."+        "rowWith (gap 8) $ button \"Save\" >> styled subtle (button \"Subtle\")"+        False+        236+        54+        [ (ImpactPrimary, "Switches the base theme to `defaultLightTheme` before scoped modifiers run.")+        , (ImpactPrimary, "Colors `Save` (`styleBg`, `styleBorder`, `styleFg`). `Subtle` keeps only its text color because its inner `styled subtle` clears the background and border.")+        , (ImpactNoOp, "No effect: buttons do not read `themeInput`.")+        , (ImpactNoOp, "No effect: buttons do not read `themePanel`.")+        , (ImpactNoOp, "No effect: plain `button` ignores `themeAccent`. Use `styled primary` or `toggleButton` instead.")+        , (ImpactPrimary, "Sets `styleCornerRadius` to 999, turning the button into a pill (`rx` = half the height).")+        , (ImpactPrimary, "Dims the fill, border, and label, and blocks clicks and focus.")+        ]+        ( rowWith (gap 8 . alignMiddle) $ do+            void (button "Save")+            void (styled subtle (button "Subtle"))+        )+    , buildProbeRow+        "toggle-button"+        "surface-button"+        "toggleButton off and on"+        "toggleButton :: Tone -> Text -> Var Bool -> NanoUI ()"+        "themeButton + Tone"+        "While off, reads `themeButton` so `buttonStyle` applies. While on, replaces the fill, hover fill, and border with `toneColor`, and picks contrasting text with `readableOn`, overriding `buttonStyle` colors."+        "toggleButton Accent \"Off\" vOff >> toggleButton Accent \"On\" vOn"+        False+        236+        54+        [ (ImpactPrimary, "Switches the base theme. `readableOn` recomputes the active text color against the tone fill.")+        , (ImpactPartial, "Styles the off state only. While on, `toneColor` replaces the fill, hover fill, and border, and `readableOn` sets the text color.")+        , (ImpactNoOp, "No effect: `toggleButton` does not read `themeInput`.")+        , (ImpactNoOp, "No effect: `toggleButton` does not read `themePanel`.")+        , (ImpactPrimary, "Colors the active state when the tone is `Accent`; `readableOn` picks dark or light text.")+        , (ImpactPrimary, "Rounds both states into pills. The active state keeps `styleCornerRadius` from `themeButton`.")+        , (ImpactPrimary, "Dims both states and blocks toggling.")+        ]+        ( rowWith (gap 8 . alignMiddle) $ do+            vOff <- useVar False+            vOn <- useVar True+            toggleButton Accent "Off (False)" vOff+            toggleButton Accent "On (True)" vOn+        )+    , buildProbeRow+        "checkbox"+        "surface-button surface-input"+        "checkbox"+        "checkbox :: Text -> Var Bool -> NanoUI ()"+        "themeButton + themeInput + themeAccent"+        "The label and unchecked border come from `themeButton` (`styleFg`, `styleBorder`), the unchecked interior comes from `themeInput` (`styleBg`), and the checked fill uses `themeAccent` and `themeOnAccent`."+        "checkbox \"Unchecked\" vOff >> checkbox \"Checked\" vOn"+        False+        236+        68+        [ (ImpactPrimary, "Switches the base theme to light unchecked boxes and dark labels.")+        , (ImpactPartial, "Colors the label and unchecked border. The button background is cleared so no button frame draws behind the checkbox.")+        , (ImpactPartial, "Colors only the 14x14 unchecked interior.")+        , (ImpactNoOp, "No effect: `checkbox` does not read `themePanel`.")+        , (ImpactPrimary, "Colors the checked box fill and border; the checkmark uses `themeOnAccent`.")+        , (ImpactSurprise, "Ignored: checkbox corners use a fixed small radius proportional to box size.")+        , (ImpactPrimary, "Dims the boxes, checkmark, and label.")+        ]+        ( columnWith (gap 4 . tight) $ do+            vOff <- useVar False+            vOn <- useVar True+            checkbox "Unchecked" vOff+            checkbox "Checked" vOn+        )+    , buildProbeRow+        "radio"+        "surface-button surface-input"+        "radio"+        "radio :: Foldable f => f Text -> Var Int -> NanoUI ()"+        "themeButton + themeInput + themeAccent"+        "Follows the same three-surface split as `checkbox`: the unselected ring interior uses `themeInput`, the ring border and label use `themeButton`, and the selected ring and dot use `themeAccent`."+        "radio [\"Option A\", \"Option B\"] vSelected"+        False+        236+        68+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactPartial, "Colors the labels and unselected ring borders; the button background is cleared.")+        , (ImpactPartial, "Colors only the unselected ring interior.")+        , (ImpactNoOp, "No effect: `radio` does not read `themePanel`.")+        , (ImpactPrimary, "Colors the selected ring and inner dot.")+        , (ImpactSurprise, "No effect: radio indicators are always circular.")+        , (ImpactPrimary, "Dims the rings, dot, and labels.")+        ]+        ( columnWith (gap 4 . tight) $ do+            vSel <- useVar (1 :: Int)+            radio ["Option A (Unselected)" :: Text, "Option B (Selected)"] vSel+        )+    , buildProbeRow+        "text-input"+        "surface-input"+        "textInput"+        "textInput :: Var Text -> NanoUI ()"+        "themeInput"+        "`themeInput` paints the well, text and border. The placeholder blends 40% toward the well fill. On focus the border becomes `themeAccent` and the fill becomes `styleActiveBg`, with no outer ring."+        "textInputConfigured (defaultTextInputConfig {ticPlaceholder = \"Filter...\"}) vEmpty >> textInput vText"+        False+        236+        84+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect: `textInput` reads `themeInput`.")+        , (ImpactPrimary, "Colors the well fill, border, value text and placeholder.")+        , (ImpactNoOp, "No effect: `textInput` never reads `themePanel`.")+        , (ImpactPartial, "Used for the focused border and caret.")+        , (ImpactPrimary, "Turns the well into a pill.")+        , (ImpactPrimary, "Dims the well, border and text, and blocks focus and typing.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            vEmpty <- useVar ("" :: Text)+            vText <- useVar ("nano-ui" :: Text)+            textInputConfigured (defaultTextInputConfig {ticPlaceholder = "Filter..."}) vEmpty+            textInput vText+        )+    , buildProbeRow+        "search-numeric"+        "surface-input"+        "searchInput and numericInput"+        "searchInput :: Text -> Var Text -> NanoUI ()"+        "themeInput"+        "Both use `themeInput`. `searchInput` tints its magnifier and clear glyphs 45% toward the well fill. `numericInput` tints its divider 40% from the border and its stepper arrows 40% from the text color."+        "searchInput \"Search\" vQuery >> numericInput vNum"+        False+        236+        84+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect. The stepper buttons in `numericInput` are painted from `themeInput`, not `themeButton`.")+        , (ImpactPrimary, "Colors both fields. `searchInput` tints its icons 45% toward the well fill; `numericInput` tints its divider and arrows 40% toward the well fill.")+        , (ImpactNoOp, "No effect: neither input reads `themePanel`.")+        , (ImpactPartial, "Used for the focused border and caret.")+        , (ImpactPrimary, "Turns both wells into pills.")+        , (ImpactPrimary, "Dims the wells, icons, arrows and text.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            vQ <- useVar ("plot" :: Text)+            vN <- useVar (42.5 :: Double)+            searchInput "Search" vQ+            numericInput vN+        )+    , buildProbeRow+        "select-vs-combo"+        "surface-button surface-input"+        "select and comboBox"+        "select :: f Text -> Var Int -> NanoUI ()"+        "select: themeButton | comboBox: themeInput"+        "`select` paints its closed trigger from `themeButton`, while `comboBox` is built on `textInput` and paints from `themeInput`. Both draw their open dropdown menus from `themePopup`."+        "selectWith fillW [\"Select (btn)\", ...] vIdx >> comboBox \"Pick...\" [...] vCombo"+        False+        236+        84+        [ (ImpactPrimary, "Switches the base theme on both controls.")+        , (ImpactPartial, "Styles `select` only. `comboBox` reads `themeInput` and ignores `buttonStyle`.")+        , (ImpactPartial, "Styles `comboBox` only. `select` reads `themeButton` and ignores `inputStyle`.")+        , (ImpactNoOp, "No effect while closed; open menus read `themePopup`.")+        , (ImpactPartial, "Highlights the selected row in an open menu and the focused `comboBox` border.")+        , (ImpactPrimary, "Rounds `select` through `themeButton` and `comboBox` through `themeInput`.")+        , (ImpactPrimary, "Dims both controls and prevents opening their menus.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            vIdx <- useVar (0 :: Int)+            vCombo <- useVar ("GHC 9.14" :: Text)+            selectWith fillW ["Select (themeButton)" :: Text, "Option 2"] vIdx+            comboBox "Pick..." ["GHC 9.14" :: Text, "GHC 9.12"] vCombo+        )+    , buildProbeRow+        "textarea"+        "surface-input"+        "textArea"+        "textArea :: Var Text -> NanoUI ()"+        "themeInput"+        "Multi-line editor on `themeInput`. Focus swaps the border to `themeAccent` and the fill to `styleActiveBg`; selections use `themeSelection`."+        "textAreaWith (fillW . fixedH 64) vDoc"+        False+        236+        84+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect: `textArea` reads `themeInput`.")+        , (ImpactPrimary, "Colors the well, border and document text.")+        , (ImpactNoOp, "No effect: `textArea` never reads `themePanel`.")+        , (ImpactPartial, "Used for the active border and caret.")+        , (ImpactPrimary, "Rounds the editor corners.")+        , (ImpactPrimary, "Dims the well and text, and blocks editing.")+        ]+        ( do+            vDoc <- useVar ("line 1: module Main\nline 2: import NanoUI" :: Text)+            textAreaWith (fillW . fixedH 64) vDoc+        )+    , buildProbeRow+        "slider"+        "surface-input"+        "slider"+        "slider :: Float -> Float -> Var Float -> NanoUI ()"+        "themeInput + themeAccent"+        "The track outline and thumb border use `styleBorder` from `themeInput`. The unfilled track blends 35% from `styleBg` toward the border, the active fill uses `themeAccent`, and the thumb interior uses `themeOnAccent`. Border width is fixed at 1px and track radius at 3px."+        "sliderWith fillW 0 100 vVal"+        False+        236+        54+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect: `slider` reads `themeInput` and `themeAccent`.")+        , (ImpactPartial, "Colors the track outline and thumb border, and blends the unfilled track 35% from `styleBg` toward the border.")+        , (ImpactNoOp, "No effect: `slider` never reads `themePanel`.")+        , (ImpactPrimary, "Colors the filled track; the thumb interior uses `themeOnAccent`.")+        , (ImpactSurprise, "Ignored: slider tracks always use a 3px corner radius and 1px border.")+        , (ImpactPrimary, "Dims the track, fill, and thumb.")+        ]+        ( do+            vVal <- useVar (64 :: Float)+            sliderWith fillW 0 100 vVal+        )+    , buildProbeRow+        "custom-controls"+        "surface-button surface-panel"+        "toggleSwitch, progressBar, sparkline"+        "toggleSwitch :: Var Bool -> NanoUI ()"+        "themeButton / themePanel + themeAccent"+        "Canvas widgets from `NanoUI.Widgets.Custom`. `toggleSwitch`, `progressBar`, `circularProgress` and `knob` read `themeButton` plus `themeAccent`; `sparkline` fills its well with `themePanel`'s `styleBg`."+        "toggleSwitch vSw >> progressBar 0.68 >> sparkline [2, 7, 4, 9, 5, 11, 8, 12]"+        False+        236+        94+        [ (ImpactPrimary, "Switches the base theme for all three canvas widgets.")+        , (ImpactPartial, "Colors the track border and unfilled track of `toggleSwitch` and `progressBar`; `sparkline` ignores it.")+        , (ImpactNoOp, "No effect: these widgets never read `themeInput`.")+        , (ImpactPartial, "Colors only the `sparkline` well; `toggleSwitch` and `progressBar` ignore it.")+        , (ImpactPrimary, "Colors the switch pill, progress fill, and sparkline line and dot.")+        , (ImpactSurprise, "Ignored. The switch and progress bar use `r = h/2`; the sparkline uses `r = 3`.")+        , (ImpactPrimary, "Dims `cdcTheme` in `CustomDrawContext` for all three.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            vSw <- useVar True+            toggleSwitch vSw+            progressBar 0.68+            sparkline [2, 7, 4, 9, 5, 11, 8, 12]+        )+    , buildProbeRow+        "panel-card-callout"+        "surface-panel"+        "panel, card, callout"+        "panel :: NanoUI a -> NanoUI a"+        "themePanel"+        "`panel` and `card` read `styleBg`, `styleBorder`, `styleBorderWidth`, `styleBorderSides` and `styleCornerRadius` from `themePanel`. `callout` applies a tinted `panelStyle` to its whole subtree."+        "panel (label \"panel surface\") >> callout amber (label \"Warning callout\")"+        False+        236+        94+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect: containers read `themePanel`.")+        , (ImpactNoOp, "No effect: containers never read `themeInput`.")+        , (ImpactPrimary, "Colors the panel fill, border and child labels. `callout` applies its own tinted `panelStyle` on top.")+        , (ImpactNoOp, "No effect when `callout` uses an explicit color; `calloutTone Accent` binds `themeAccent`.")+        , (ImpactPrimary, "Rounds the panel and callout corners.")+        , (ImpactPrimary, "Dims the surfaces, borders and labels.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            panelWith (fillW . padAll 6) (label "panel surface")+            calloutWith (colorRGBA 235 179 56 255) (fillW . padAll 6) (label "Warning callout")+        )+    , buildProbeRow+        "scroll-bounded"+        "surface-input"+        "scrollWith (bounded)"+        "scrollWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a"+        "themeInput (cornerRadius = 0)"+        "When either axis has a `Fixed` or `Fit` size, `scrollWith` draws a bordered `themeInput` well with square corners (`cornerRadius = 0`). The scrollbar blends `themeInput` with `themeSeparator`."+        "scrollWith (fillW . fixedH 64 . padAll 6) $ label \"Row 1\" >> ..."+        False+        236+        82+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect: scroll wells do not read `themeButton`.")+        , (ImpactPrimary, "Surprise: bounded scroll wells read `themeInput`, not `themePanel`, and blend the scrollbar from it.")+        , (ImpactNoOp, "Surprise no-op: the scroll well ignores `panelStyle`; only child labels read `styleFg` from `themePanel`.")+        , (ImpactNoOp, "No effect: the scrollbar blends `themeInput` and `themeSeparator`.")+        , (ImpactSurprise, "Ignored: bounded scroll wells always draw with square corners (`cornerRadius = 0`).")+        , (ImpactPrimary, "Dims the well, scrollbar, and child labels.")+        ]+        ( scrollWith (fillW . fixedH 64 . padAll 6 . gap 4) $ do+            label "Row 1 in scroll well"+            label "Row 2 in scroll well"+            label "Row 3 in scroll well"+            label "Row 4 in scroll well"+        )+    , buildProbeRow+        "tabs-styles"+        "surface-panel surface-button"+        "tabBar styles"+        "tabBarConfigured :: TabsConfig -> Var a -> f (Tab a b) -> NanoUI ()"+        "themePanel + themeAccent (+ themeButton)"+        "Tab headers behave like buttons, yet read `themePanel` and `themeAccent`. Only `TabSegmented` reads `styleBorder` from `themeButton` for its active segment border."+        "tabBarConfigured (defaultTabsConfig {tabsStyle = ...}) vTab [tab 0 \"Code\" (), tab 1 \"AST\" ()]"+        False+        236+        106+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactSurprise, "Ignored by `TabUnderline` and `TabPill`. Tab headers read `themePanel`; only `TabSegmented` reads `styleBorder` from `themeButton`.")+        , (ImpactNoOp, "No effect: `tabBar` does not read `themeInput`.")+        , (ImpactPrimary, "Colors inactive and active tab labels, the underline rule, and the `TabSegmented` track.")+        , (ImpactPrimary, "Colors the active indicator in `TabUnderline` and the active fill in `TabPill`.")+        , (ImpactPartial, "Rounds the `TabSegmented` track and active segment. `TabUnderline` is unaffected, and `TabPill` is always a full pill.")+        , (ImpactPrimary, "Dims the tab strip and blocks switching.")+        ]+        ( columnWith (gap 4 . fillW . tight) $ do+            vTab <- useVar (0 :: Int)+            let ts = [tab (0 :: Int) "Code" (), tab 1 "AST" ()]+            tabBarConfigured (defaultTabsConfig {tabsStyle = TabUnderline}) vTab ts+            tabBarConfigured (defaultTabsConfig {tabsStyle = TabPill}) vTab ts+            tabBarConfigured (defaultTabsConfig {tabsStyle = TabSegmented}) vTab ts+        )+    , buildProbeRow+        "table-tree"+        "surface-panel surface-button"+        "simpleTable and tree"+        "simpleTable :: [Text] -> f [Text] -> NanoUI TableResponse"+        "themePanel + themeButton + themeAccent"+        "Table headers blend 55% from `themePanel` toward `themeButton`; the sorted header uses `themeButton`'s `styleFg` and unsorted headers use `themeMuted`. Tree rows alternate `themeWindow` and `themeButton` stripes and use `themeButton`'s `styleFg`."+        "simpleTable [\"Mod\", \"Surface\"] [...] >> tree \"demo-tree\" [...] vTree"+        False+        236+        138+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactPartial, "Blends 55% into the table header fill, and colors the sorted header text, tree labels and odd tree row tint.")+        , (ImpactNoOp, "No effect: neither `simpleTable` nor `tree` reads `themeInput`.")+        , (ImpactPrimary, "Colors the table cells, grid borders, header fill and tree row fill.")+        , (ImpactPrimary, "Tints the selected tree row 25% toward `themeAccent` and draws the 2px left bar.")+        , (ImpactNoOp, "No effect: cells and rows are drawn as sharp edge-to-edge rects.")+        , (ImpactPrimary, "Dims the headers, cells, grid lines and rows.")+        ]+        ( columnWith (gap 6 . fillW . tight) $ do+            void $+              simpleTable+                ["Mod", "Surface"]+                [ ["btn", "Button"]+                , ["inp", "Input"]+                ]+            vTree <- useVar (1 :: Int)+            tree+              "demo-tree"+              [ TreeItem "Theme" [TreeItem "themeButton" []]+              ]+              vTree+        )+    , buildProbeRow+        "overlays"+        "surface-popup surface-window"+        "popup, menuItem, window"+        "window :: Var Bool -> Text -> NanoUI () -> NanoUI ()"+        "themePopup / themeFloatingWindow"+        "`modal`, `popup`, `contextMenu` and open select/combo menus use `overlayMenuStyle` (from `themePopup`, with a `themeButton` hover fallback when the popup hover fill equals its fill). `window` reads `themeFloatingWindow` and `themeSeparator`."+        "window vWin \"Inspector\" (label \"Floating window\")"+        True+        236+        106+        [ (ImpactPrimary, "Switches the base theme.")+        , (ImpactNoOp, "No effect until hover. `menuItem` falls back to `styleHoverBg` from `themeButton` only when the popup hover fill equals its fill.")+        , (ImpactNoOp, "No effect: overlays never read `themeInput`.")+        , (ImpactPrimary, "Colors the floating window chrome via `windowStyle` and popup menus via `popupStyle`.")+        , (ImpactNoOp, "No effect on standard window chrome.")+        , (ImpactPrimary, "Rounds the floating window corners.")+        , (ImpactPrimary, "Dims the window chrome, title bar and body.")+        ]+        ( do+            vWin <- useVar True+            floatingWindow vWin "Inspector" $+              label "Floating window"+        )+    ]++-- ---------------------------------------------------------------------------+-- Section III: Interactive Typography Workbench & Specimens+-- ---------------------------------------------------------------------------++data TypoDemo = TypoDemo+  { tdTitle :: !Text+  , tdCode :: !Text+  , tdNote :: !Text+  , tdSvg :: !Text+  }++data TypoSectionData = TypoSectionData+  { tsdBaseSvg :: !Text+  , tsdBankValue :: !Value+  , tsdDemos :: ![TypoDemo]+  }++applyTypoMask :: Int -> Layout -> Layout+applyTypoMask mask =+  (if testBit mask 5 then fontSize 16 else id)+    . (if testBit mask 4 then fontTone Danger else id)+    . (if testBit mask 3 then fontStrike else id)+    . (if testBit mask 2 then fontUnderline else id)+    . (if testBit mask 1 then fontItalic else id)+    . (if testBit mask 0 then fontBold else id)++generateTypoDemos :: IO TypoSectionData+generateTypoDemos = do+  -- 64-combination Interactive Typography & *With Workbench (bits 0..5)+  ctx <- newSvgContext+  let w = 480+      h = 152+      inp = withInputOff w h+      viewFor mask =+        let m = applyTypoMask mask+         in panelWith (fillW . fillH . padAll 10 . gap 8) $ do+              rowWith (gap 8 . alignMiddle . fillW) $ do+                labelWith (fixedW 142 . fontMono) "labelWith"+                labelWith m "Hamburgefonstiv 0123"+              rowWith (gap 8 . alignMiddle . fillW) $ do+                labelWith (fixedW 142 . fontMono) "textInput"+                vTxt <- useVar ("Hamburgefonstiv 0123" :: Text)+                textInputConfigured (defaultTextInputConfig {ticLayout = m . fillW}) vTxt+              rowWith (gap 8 . alignMiddle . fillW) $ do+                labelWith (fixedW 142 . fontMono) "buttonWith"+                void (buttonWith (m . fillW) "Hamburgefonstiv 0123")+              rowWith (gap 8 . alignMiddle . fillW) $ do+                labelWith (fixedW 142 . fontMono) "buttonContent"+                void $+                  buttonContentWith fillW $+                    labelWith m "Hamburgefonstiv 0123"+  _ <- runFrame ctx inp (viewFor 0)+  typoSvgs <- forM [0 .. 63] $ \mask -> do+    fst <$> exportFrame "wb-typo" ctx inp (viewFor mask)+  let typoBaseSvg = case typoSvgs of+        (s0 : _) -> s0+        [] -> ""+      typoBankVal = packSvgBank typoSvgs++  svgLabels <-+    renderSvg "typo-labels" 480 124 $+      panelWith (fillW . fillH . padAll 10 . gap 6) $ do+        rowWith (gap 12 . alignMiddle) $ do+          label "label (14px)"+          heading "heading (WeightMedium)"+          labelWith (fontTone Accent) "fontTone Accent"+        rowWith (gap 12 . alignMiddle) $ do+          muted "muted"+          mono "mono"+          danger "danger"+          bold "bold"+          italic "italic"+          underline "underline"+        rowWith (gap 12 . alignMiddle) $ do+          labelWith fontStrike "fontStrike"+          labelWith (fontColor (colorRGBA 56 189 248 255) . fontBold) "fontColor + fontBold"+          kv "Key" "Value"++  svgToneMatrix <-+    renderSvg "typo-tone-matrix" 480 116 $+      panelWith (fillW . fillH . padAll 10 . gap 8) $ do+        rowWith (gap 6 . alignMiddle) $ do+          void (styled primary (button "primary"))+          void (styled destructive (button "destructive"))+          void (styled success (button "success"))+          void (styled warning (button "warning"))+          void (styled subtle (button "subtle"))+        rowWith (gap 6 . alignMiddle) $ do+          void (styled (tinted themeAccent) (button "tinted Accent"))+          void (styled (tinted themeDanger) (button "tinted Danger"))+          void (styled (tinted themeSuccess) (button "tinted Success"))+          void (styled (tinted themeWarning) (button "tinted Warning"))++  pure+    TypoSectionData+      { tsdBaseSvg = typoBaseSvg+      , tsdBankValue = typoBankVal+      , tsdDemos =+          [ TypoDemo+              "Text helpers and font modifiers"+              "label, heading, labelWith (fontTone Accent), muted, mono, danger, bold, italic, underline, fontStrike, fontColor"+              "Font modifiers (variant, tone, weight, slant, decoration, and color) compose with layout modifiers on text nodes, buttons, and selects without cascading from parent containers."+              svgLabels+          , TypoDemo+              "Tones and tinted surfaces"+              "styled primary / destructive / success / warning / subtle / tinted themeAccent"+              "tone fills the button with the semantic color and picks readableOn for the text. tinted blends 18% of the color into the background, draws a 55% border and keeps the color for the text."+              svgToneMatrix+          ]+      }++-- ---------------------------------------------------------------------------+-- Section IV: 8 Unexpected Interactions & Edge Cases+-- ---------------------------------------------------------------------------++data InteractionCard = InteractionCard+  { icNumber :: !Text+  , icCategory :: !Text+  , icTitle :: !Text+  , icWhere :: !Text+  , icWhy :: !Text+  , icFix :: !Text+  , icCodeBad :: !Text+  , icCodeGood :: !Text+  , icLabelA :: !Text+  , icSvgA :: !Text+  , icLabelB :: !Text+  , icSvgB :: !Text+  }++generateInteractions :: IO [InteractionCard]+generateInteractions = do+  -- 1. checkbox & radio 3-surface split + modal popup shift+  i3Bad <-+    renderSvg "i3-bad" 260 120 $+      styled+        ( buttonStyle+            ( background (colorRGBA 220 38 38 255)+                . borderColor (colorRGBA 56 189 248 255)+                . foreground (colorRGBA 56 189 248 255)+            )+            . inputStyle (background (colorRGBA 4 120 87 255))+        )+        $ panelWith (fillW . fillH . padAll 8 . gap 6) $ do+          v0 <- useVar False+          v1 <- useVar True+          checkbox "Unchecked (input bg + btn border)" v0+          checkbox "Checked (accent bg)" v1+          rSel <- useVar (0 :: Int)+          radio ["Radio ring (input bg + btn border)" :: Text] rSel+  i3Good <-+    renderSvg "i3-good" 260 120 $+      styled+        ( buttonStyle (foreground (colorRGBA 56 189 248 255) . borderColor (colorRGBA 56 189 248 255))+            . popupStyle (foreground (colorRGBA 251 191 36 255) . borderColor (colorRGBA 251 191 36 255))+        )+        $ do+          vOpen <- useVar True+          modal vOpen "Inside modal (reads themePopup)" $ do+            vC <- useVar False+            checkbox "Switched to popupStyle" vC++  -- 2. select (themeButton) vs comboBox (themeInput)+  i4Bad <-+    renderSvg "i4-bad" 260 92 $+      styled probeInput $+        panelWith (fillW . fillH . padAll 8 . gap 6) $ do+          vCombo <- useVar ("comboBox (styled)" :: Text)+          vSel <- useVar (0 :: Int)+          comboBox "Pick..." ["comboBox (styled)" :: Text] vCombo+          selectWith fillW ["select (ignores inputStyle)" :: Text] vSel+  i4Good <-+    renderSvg "i4-good" 260 92 $+      styled (probeInput . buttonStyle (fillColor (colorRGBA 4 120 87 255) . foreground (colorRGBA 209 250 229 255) . borderColor (colorRGBA 52 211 153 255) . borderWidth 2)) $+        panelWith (fillW . fillH . padAll 8 . gap 6) $ do+          vCombo <- useVar ("comboBox (inputStyle)" :: Text)+          vSel <- useVar (0 :: Int)+          comboBox "Pick..." ["comboBox (inputStyle)" :: Text] vCombo+          selectWith fillW ["select (buttonStyle matched)" :: Text] vSel++  -- 3. scrollWith bounded (themeInput well, cornerRadius=0) vs grow (page background, no border)+  i5Bad <-+    renderSvg "i5-bad" 260 96 $+      styled (probeInput . rounded 12) $+        columnWith (fillW . fillH . padAll 8) $+          scrollWith (fillW . fixedH 80 . padAll 6 . gap 4) $ do+            label "fixedH 80: uses themeInput well"+            label "cornerRadius forced to 0"+            label "Line 3 (scrollable)"+            label "Line 4 (scrollable)"+  i5Good <-+    renderSvg "i5-good" 260 96 $+      styled (probeInput . rounded 12) $+        columnWith (fillW . fillH . padAll 8) $+          scrollWith (grow . padAll 6 . gap 4) $ do+            label "scrollWith grow (fillW . fillH):"+            label "Drops the themeInput well and border"+            label "Paints the page background instead"++  -- 4. callout leaks panelStyle into child panels+  let warnCol = colorRGBA 235 179 56 255+  i6Bad <-+    renderSvg "i6-bad" 260 104 $+      framePad $+        callout warnCol $ do+          label "Outer Warning callout"+          card (label "Nested card inherits the yellow tint")+  i6Good <-+    renderSvg "i6-good" 260 104 $+      framePad $ do+        basePanel <- themePanel <$> uiTheme+        callout warnCol $ do+          label "Outer Warning callout"+          styled (\t -> t {themePanel = basePanel}) $+            card (label "Nested card with restored themePanel")++  -- 5. toggleButton active state overwrites buttonStyle with Tone+  i7Bad <-+    renderSvg "i7-bad" 260 80 $+      styled probeButton $+        panelWith (fillW . fillH . padAll 10 . gap 8) $+          rowWith (gap 8 . alignMiddle) $ do+            vOff <- useVar False+            vOn <- useVar True+            toggleButton Warning "OFF (uses buttonStyle)" vOff+            toggleButton Warning "ON (Warning wins)" vOn+  i7Good <-+    renderSvg "i7-good" 260 80 $+      styled (probeButton . probeAccent) $+        panelWith (fillW . fillH . padAll 10 . gap 8) $+          rowWith (gap 8 . alignMiddle) $ do+            vOff <- useVar False+            vOn <- useVar True+            toggleButton Accent "OFF (buttonStyle)" vOff+            toggleButton Accent "ON (accentColor)" vOn++  -- 6. borderWidth & borderSides do not add layout padding+  i9Bad <-+    renderSvg "i9-bad" 260 80 $+      framePad $+        styled (panelStyle (borderColor (colorRGBA 244 63 94 255) . borderWidth 8)) $+          panelWith (fillW . tight) $+            label "tight + borderWidth 8 overlaps text"+  i9Good <-+    renderSvg "i9-good" 260 80 $+      framePad $+        styled (panelStyle (borderLeft 6 (colorRGBA 244 63 94 255))) $+          panelWith (fillW . padLRTB 12 8 8 8) $+            label "borderLeft 6 + padLeft 12 clears stroke"++  -- 7. Composition order (.) vs nested styled scopes+  i10Bad <-+    renderSvg "i10-bad" 260 84 $+      panelWith (fillW . fillH . padAll 8 . gap 6) $ do+        rowWith (gap 6) $ do+          void (styled (primary . destructive) (button "primary . destructive"))+        rowWith (gap 6) $ do+          void (buttonWith (fixedW 110 . fixedW 220) "fixedW 110 wins")+  i10Good <-+    renderSvg "i10-good" 260 84 $+      panelWith (fillW . fillH . padAll 8 . gap 6) $ do+        rowWith (gap 6) $ do+          void (styled primary (styled destructive (button "nested: inner destructive wins")))++  -- 8. Tabs (tabHeaderVisualStyle) read themePanel, not themeButton+  i11Bad <-+    renderSvg "i11-bad" 260 96 $+      styled probeButton $+        panelWith (fillW . fillH . padAll 8 . gap 6) $ do+          vT <- useVar (0 :: Int)+          let ts = [tab (0 :: Int) "Tab A" (), tab 1 "Tab B" ()]+          tabBarConfigured (defaultTabsConfig {tabsStyle = TabUnderline}) vT ts+          tabBarConfigured (defaultTabsConfig {tabsStyle = TabContained}) vT ts+  i11Good <-+    renderSvg "i11-good" 260 96 $+      styled (probePanel . probeAccent) $+        panelWith (fillW . fillH . padAll 8 . gap 6) $ do+          vT <- useVar (0 :: Int)+          let ts = [tab (0 :: Int) "Tab A" (), tab 1 "Tab B" ()]+          tabBarConfigured (defaultTabsConfig {tabsStyle = TabUnderline}) vT ts+          tabBarConfigured (defaultTabsConfig {tabsStyle = TabContained}) vT ts++  pure+    [ InteractionCard+        "01"+        "surface-button surface-input surface-popup"+        "checkbox and radio span three surfaces"+        "NanoUI.Internal.Frame.Chrome (widgetVisualStyle), NanoUI.Internal.Frame.Paint.Widgets (paintCheckboxNode)"+        "Checkboxes and radios strip the button background and read three different theme slots: the unchecked interior comes from `themeInput` (`styleBg`), the outline and label come from `themeButton` (`styleBorder` and `styleFg`), and the checked fill and mark come from `themeAccent` and `themeOnAccent`. Inside a `modal`, the outline and label switch from `themeButton` to `themePopup`."+        "Style `inputStyle` for the unchecked interior, `buttonStyle` for the border and label (plus `popupStyle` inside modals), and `accentColor` for the checked state."+        "-- buttonStyle background is stripped for checkboxes\nstyled (buttonStyle (background red)) (checkbox \"Opt\" v)"+        "styled (inputStyle (background wellBg)\n      . buttonStyle (borderColor ringCol . foreground txtCol)\n      . accentColor checkCol) (checkbox \"Opt\" v)"+        "inputStyle interior, buttonStyle border and text, accentColor check"+        i3Bad+        "inside a modal, border and label switch to popupStyle"+        i3Good+    , InteractionCard+        "02"+        "surface-button surface-input"+        "select and comboBox use different surfaces"+        "NanoUI.Internal.Frame.Chrome (widgetVisualStyle)"+        "Even though they look alike when closed, `select` paints from `themeButton` while `comboBox` is built on `textInput` and paints from `themeInput`. Applying `inputStyle` to a form styles `textInput`, `numericInput`, and `comboBox`, leaving `select` unstyled."+        "Apply your field style to both `inputStyle` and `buttonStyle`, or wrap `select` in `styled (buttonStyle ...)`."+        "-- select stays on themeButton under inputStyle\nstyled (inputStyle myFieldStyle) $ do\n  comboBox \"Choose...\" opts vCombo\n  select opts vIdx"+        "styled (inputStyle myFieldStyle . buttonStyle myFieldStyle) $ do\n  comboBox \"Choose...\" opts vCombo\n  select opts vIdx"+        "inputStyle only: comboBox changes, select stays default"+        i4Bad+        "inputStyle and buttonStyle matched"+        i4Good+    , InteractionCard+        "03"+        "surface-input surface-panel"+        "scrollWith changes surface depending on its size"+        "NanoUI.Internal.Frame.Paint (paintScrollSurface)"+        "When either axis has a fixed or fit size, `scrollWith` draws a square-cornered, bordered `themeInput` well. When both axes fill (`scrollWith grow`), it acts as a full-page scroller, dropping the border and filling with `pageBackground` (`themeWindow` by default)."+        "Give embedded scroll boxes a bounded height (`fixedH`, `maxH`), or wrap a `grow` scroller inside a styled `panelWith`."+        "-- both axes fill: no well, no border\nscrollWith (grow . padAll 6) body"+        "-- bounded height keeps the themeInput well\nscrollWith (fillW . fixedH 80 . padAll 6) body"+        "grow: no well or border, fills with page background"+        i5Good+        "fixedH 80: bordered themeInput well with square corners"+        i5Bad+    , InteractionCard+        "04"+        "surface-panel"+        "callout tints nested panels"+        "NanoUI.Internal.Widgets.Layout (calloutWith)"+        "`calloutWith` wraps its children in `styled (panelStyle ...)`, so any `panel` or `card` inside the callout inherits its tinted background and border. `modal` and `popup` read `themePopup`, so overlays keep the normal `themePanel`."+        "Save `basePanel <- themePanel <$> uiTheme` before the callout and restore it around inner panels with `styled (\\t -> t {themePanel = basePanel})`."+        "calloutTone Warning $ do\n  label \"Warning\"\n  card (label \"Inner card turns yellow\")"+        "basePanel <- themePanel <$> uiTheme\ncalloutTone Warning $ do\n  label \"Warning\"\n  styled (\\t -> t {themePanel = basePanel}) (card (label \"Clean card\"))"+        "nested card inherits the callout tint"+        i6Bad+        "themePanel restored inside the callout"+        i6Good+    , InteractionCard+        "05"+        "surface-button"+        "toggleButton ignores buttonStyle when active"+        "NanoUI.Internal.Frame.Chrome (widgetVisualStyle)"+        "While off, `toggleButton` reads `themeButton`, so `buttonStyle` applies normally. While on, it replaces `styleBg`, `styleHoverBg`, and `styleBorder` with its tone color (`toneColor`) and computes contrasting text via `readableOn`, overriding `buttonStyle`."+        "Change the tone color (`accentColor` for `Accent`, or the matching tone) to customize the active state."+        "-- buttonStyle only styles the off state\nstyled (buttonStyle (fillColor blue)) (toggleButton Warning \"On\" vTrue)"+        "-- pair buttonStyle (off) with accentColor (on)\nstyled (buttonStyle (fillColor blue) . accentColor rose)\n  (toggleButton Accent \"On\" vTrue)"+        "active state ignores buttonStyle"+        i7Bad+        "buttonStyle for off, accentColor for on"+        i7Good+    , InteractionCard+        "06"+        "surface-panel"+        "borderWidth does not reserve layout padding"+        "NanoUI.Internal.Frame.Chrome (strokeStyledSides), NanoUI.Internal.Layout.Solve"+        "Theme scopes never alter layout geometry. `borderWidth 8` draws an 8px inset stroke without adding padding, so inside a `tight` container it paints right over child text. When `borderSides` draws fewer than all four sides, corners are drawn flat and ignore `cornerRadius`."+        "Add matching padding (`padAll`, `padLeft`, or `padLRTB`) whenever you draw thick borders."+        "styled (panelStyle (borderWidth 8)) $\n  panelWith tight (label \"Overlapped\")"+        "styled (panelStyle (borderLeft 6 rose)) $\n  panelWith (padLRTB 12 8 8 8) (label \"Padded\")"+        "borderWidth 8 on tight overlaps text"+        i9Bad+        "borderLeft 6 with padLRTB 12 8 8 8 clears text"+        i9Good+    , InteractionCard+        "07"+        "surface-button"+        "modifier order in (.) vs. nested styled"+        "NanoUI.Internal.Style, function composition"+        "Modifiers are plain Haskell functions. In `(f . g) x`, `g` runs first and `f` runs second, so the leftmost modifier wins: `primary . destructive` resolves to `primary`, and `fixedW 110 . fixedW 220` resolves to 110. Nested scopes run outside in, so `styled outer (styled inner view)` lets the inner scope win."+        "Put the winning override on the left in a `(.)` chain, and innermost when nesting `styled` calls."+        "styled (primary . destructive) (button \"Which wins?\") -- primary\nbuttonWith (fixedW 110 . fixedW 220) \"Width?\"        -- 110px"+        "styled primary $ styled destructive $ button \"Inner destructive wins\""+        "(.) chain: leftmost modifier wins"+        i10Bad+        "nested styled: innermost scope wins"+        i10Good+    , InteractionCard+        "08"+        "surface-panel surface-button"+        "tabs read themePanel, not themeButton"+        "NanoUI.Internal.Frame.Chrome (tabHeaderVisualStyle)"+        "Even though tab headers behave like buttons, they take their colors from `themePanel` and `themeAccent`. `buttonStyle` has no effect on `TabUnderline`, `TabPill`, or `TabContained`; only `TabSegmented` reads `styleBorder` from `themeButton` for its active border."+        "Style tabs through `panelStyle` and `accentColor`."+        "-- buttonStyle does not affect TabUnderline or TabContained\nstyled (buttonStyle myStyle) (tabBar active tabsList)"+        "-- panelStyle and accentColor style the tab strip\nstyled (panelStyle myPanel . accentColor myAccent) (tabBar active tabsList)"+        "buttonStyle leaves TabUnderline and TabContained unchanged"+        i11Bad+        "panelStyle and accentColor style the headers"+        i11Good+    ]++-- ---------------------------------------------------------------------------+-- Interactive States & Styles Playground (6 States x 32 Style Masks = 192 Frames)+-- ---------------------------------------------------------------------------++applyStateStyleMask :: Int -> NanoUI () -> NanoUI ()+applyStateStyleMask smask view0 =+  let hasThemeMod = (smask .&. 0x0F) /= 0+      themeMod =+        (if testBit smask 3 then probeAccent else id)+          . (if testBit smask 2 then probePopup else id)+          . (if testBit smask 1 then probeInput else id)+          . (if testBit smask 0 then probeButton else id)+      applyStyled = if hasThemeMod then styled themeMod else id+      applyDis = if testBit smask 4 then disabledWhen True else id+   in applyStyled (applyDis view0)++generateStateStrip :: IO (Text, Value)+generateStateStrip = do+  let w = 440+      h = 122+      buildView :: Bool -> NanoUI ()+      buildView focusBtn =+        panelWith (fillW . fillH . padAll 10 . gap 8) $ do+          rowWith (gap 10 . alignMiddle . fillW) $ do+            rBtn <- buttonWith' (fixedW 195) "Action Button"+            if focusBtn then requestFocus (respId rBtn) else pure ()+            vInp <- useVar ("Editable Input" :: Text)+            textInputConfigured (defaultTextInputConfig {ticLayout = fillW}) vInp+          rowWith (gap 10 . alignMiddle . fillW) $ do+            vSel <- useVar (0 :: Int)+            selectWith (fixedW 195) ["Select (themeButton)" :: Text, "Popup Row 2", "Popup Row 3"] vSel+            label "Click a state or style pill"++      renderOneState :: Int -> Int -> IO Text+      renderOneState stIdx smask = do+        let ui = applyStateStyleMask smask (buildView (stIdx == 3))+            tag = "wb-state"+        case stIdx of+          0 -> renderSvg tag w h ui+          1 -> renderSvgHover tag w h (V2 95 22) ui+          2 -> renderSvgPress tag w h (V2 95 22) ui+          3 -> renderSvg tag w h ui+          4 -> renderSvgClick tag w h (V2 310 22) ui+          _ -> renderSvgClick tag w h (V2 95 54) ui++  svgs <-+    sequence+      [ renderOneState stIdx smask+      | stIdx <- [0 .. 5]+      , smask <- [0 .. 31]+      ]+  let baseSvg = case svgs of+        (s0 : _) -> s0+        [] -> ""+  pure (baseSvg, packSvgBank svgs)++-- ---------------------------------------------------------------------------+-- Hero Interactive All-Surface Workbench (128 Combinations)+-- ---------------------------------------------------------------------------++generateRainbowBanner :: IO (Text, Value)+generateRainbowBanner = do+  let compositeView :: NanoUI ()+      compositeView =+        panelWith (fillW . fillH . padAll 10 . gap 8) $ do+          rowWith (gap 8 . alignMiddle . fillW) $ do+            heading "Surface Anatomy"+            void (button "Button")+            vOn <- useVar True+            toggleButton Accent "Active" vOn+            vChk <- useVar False+            checkbox "Check" vChk+            vChk2 <- useVar True+            checkbox "On" vChk2+          rowWith (gap 8 . alignMiddle . fillW) $ do+            vTxt <- useVar ("textInput (themeInput)" :: Text)+            textInputConfigured (defaultTextInputConfig {ticLayout = fixedW 170}) vTxt+            vSel <- useVar (0 :: Int)+            selectWith (fixedW 130) ["select (btn)" :: Text, "Item 2"] vSel+            vSl <- useVar (60 :: Float)+            sliderWith fillW 0 100 vSl+  renderStyleBank "hero" 520 96 False compositeView++instance ToJSON ToggleNote where+  toJSON tn =+    object+      [ "bit" .= tnBit tn+      , "key" .= tnKey tn+      , "label" .= tnLabel tn+      , "short" .= tnShort tn+      , "impact" .= impactCode (tnImpact tn)+      , "badge" .= impactBadgeText (tnImpact tn)+      , "detail" .= tnDetail tn+      ]++instance ToJSON InteractionCard where+  toJSON c =+    object+      [ "id" .= icNumber c+      , "category" .= icCategory c+      , "title" .= icTitle c+      , "where" .= icWhere c+      , "why" .= icWhy c+      , "fix" .= icFix c+      , "codeBad" .= icCodeBad c+      , "codeGood" .= icCodeGood c+      , "labelA" .= icLabelA c+      , "svgA" .= icSvgA c+      , "labelB" .= icLabelB c+      , "svgB" .= icSvgB c+      ]
+ app/LayoutExamples.hs view
@@ -0,0 +1,408 @@+-- | Layout examples for the book's Layout chapter. Each anchored block is+-- included in @book/src/layout/index.md@, and the glossary generator renders+-- the same definitions to @book/src/images/layout/@, framed by its own+-- padding, so the code on the page is the code that drew the picture.+module LayoutExamples (layoutExamples) where++import Control.Monad (void, when)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI++-- Every example is a whole view; the signatures are kept here, off the page.+rowExample, columnExample, gridExample, panelExample, cardExample,+  calloutExample, layersExample, centerExample, responsiveExample,+  mouseAreaExample, separatorExample, spacerExample, fillWExample,+  fillHExample, growExample, fixedWExample, fixedHExample, fixedWHExample,+  minWExample, maxWExample, minHExample, maxHExample, percentExample,+  aspectExample, padAllExample, padXYExample, padLeftExample,+  padRightExample, padTopExample, padBottomExample, padLRTBExample,+  gapExample, tightExample, alignStartExample, alignEndExample,+  alignCenterExample, alignTopExample, alignMidExample, alignBottomExample,+  alignBaselineExample, wrapExample, lineGapExample, lineAlignExample,+  pinAtExample, pointerBlockExample, pointerPassExample :: NanoUI ()++-- ANCHOR: row+rowExample =+  rowWith (gap 8) $+    mapM_ (void . button) ["One", "Two", "Three"]+-- ANCHOR_END: row++-- ANCHOR: column+columnExample =+  columnWith (gap 8) $+    mapM_ (void . buttonWith fillW) ["One", "Two", "Three"]+-- ANCHOR_END: column++-- ANCHOR: grid+gridExample =+  gridWith 3 (gap 8 . fillW) $+    mapM_+      (\i -> void (buttonWith fillW ("Cell " <> T.pack (show (i :: Int)))))+      [1 .. 6]+-- ANCHOR_END: grid++-- ANCHOR: panel+panelExample =+  panelWith (fixedW 300 . padAll 12 . gap 6) $ do+    heading "Deployments"+    muted "3 services running"+-- ANCHOR_END: panel++-- ANCHOR: card+cardExample =+  card $ do+    heading "Build #482"+    muted "Passed in 1m 42s"+-- ANCHOR_END: card++-- ANCHOR: callout+calloutExample = do+  warnCol <- themeWarning <$> uiTheme+  callout warnCol $ do+    heading "Certificate expiring"+    muted "TLS certificate expires in 3 days."+-- ANCHOR_END: callout++-- ANCHOR: layers+layersExample =+  layers $ do+    let badgeRed = colorRGB 204 64 64+    void (buttonWith (fixedWH 170 40) "Inbox")+    styled (panelStyle (background badgeRed . borderColor badgeRed)) $+      panelWith (alignEnd . alignTop . padXY 6 1) $+        labelWith (fontColor colorWhite) "3"+-- ANCHOR_END: layers++-- ANCHOR: center+centerExample =+  panelWith (fillW . fillH) $+    center (label "Centered on both axes")+-- ANCHOR_END: center++-- ANCHOR: responsive+responsiveExample =+  responsiveRowCol 640 (tight . gap 8 . fillW) $ do+    panelWith (fillW . padAll 12) (label "Sidebar")+    panelWith (fillW . padAll 12) (label "Content")+-- ANCHOR_END: responsive++-- ANCHOR: mousearea+mouseAreaExample = do+  (_, area) <-+    panelWith fillW $+      mouseArea (fillW . padAll 10 . gap 4) $ do+        label "build.log"+        muted "Click anywhere in this card"+  when (respClicked area) (muted "opening build.log")+-- ANCHOR_END: mousearea++-- ANCHOR: separator+separatorExample =+  columnWith (fillW . gap 8) $ do+    label "Above the rule"+    separator+    label "Below the rule"+-- ANCHOR_END: separator++-- ANCHOR: spacer+spacerExample =+  rowWith (fillW . alignMiddle) $ do+    label "Left"+    spacer (Grow 1) Fit+    label "Right"+-- ANCHOR_END: spacer++-- ANCHOR: fillw+fillWExample =+  rowWith (fillW . gap 8) $ do+    void (buttonWith (fixedW 110) "fixedW 110")+    void (buttonWith fillW "fillW")+-- ANCHOR_END: fillw++-- ANCHOR: fillh+fillHExample =+  rowWith (fillW . gap 8 . fixedH 96) $ do+    panelWith (fixedW 120 . fillH) (label "fillH")+    panelWith (fixedW 120) (label "natural")+-- ANCHOR_END: fillh++-- ANCHOR: grow+growExample =+  rowWith (grow . gap 8) $ do+    panelWith (fixedW 120) (label "fixedW 120")+    panelWith grow (label "grow")+-- ANCHOR_END: grow++-- ANCHOR: fixedw+fixedWExample =+  rowWith (gap 8) $ do+    void (buttonWith (fixedW 60) "60")+    void (buttonWith (fixedW 110) "110")+    void (buttonWith (fixedW 170) "170")+-- ANCHOR_END: fixedw++-- ANCHOR: fixedh+fixedHExample =+  rowWith (gap 8 . fillW) $ do+    void (buttonWith (fixedH 30) "fixedH 30")+    void (buttonWith (fixedH 56) "fixedH 56")+    void (buttonWith (fixedH 82) "fixedH 82")+-- ANCHOR_END: fixedh++-- ANCHOR: fixedwh+fixedWHExample =+  rowWith (gap 8) $ do+    void (buttonWith (fixedWH 120 36) "120 x 36")+    void (buttonWith (fixedWH 200 72) "200 x 72")+-- ANCHOR_END: fixedwh++-- ANCHOR: minw+minWExample =+  rowWith (fillW . gap 8) $ do+    void (buttonWith (minW 200) "minW 200")+    void (button "natural")+-- ANCHOR_END: minw++-- ANCHOR: maxw+maxWExample =+  rowWith (fillW . gap 8) $ do+    void (buttonWith (fillW . maxW 160) "maxW 160")+    void (buttonWith fillW "fillW")+-- ANCHOR_END: maxw++-- ANCHOR: minh+minHExample =+  rowWith (fillW . gap 8) $ do+    panelWith (minH 80 . fillW) (label "minH 80")+    panelWith fillW (label "natural")+-- ANCHOR_END: minh++-- ANCHOR: maxh+maxHExample =+  rowWith (fillW . gap 8 . fixedH 100) $ do+    panelWith (maxH 50 . fillW) (label "maxH 50")+    panelWith (fillW . fillH) (label "fillH")+-- ANCHOR_END: maxh++-- ANCHOR: percent+percentExample =+  rowWith (fillW . gap 8) $ do+    panelWith (percent 30) (label "percent 30")+    panelWith (percent 60) (label "percent 60")+-- ANCHOR_END: percent++-- ANCHOR: aspect+aspectExample =+  panelWith (fillW . aspect (16 / 9)) $+    center (label "16 : 9")+-- ANCHOR_END: aspect++-- ANCHOR: padall+padAllExample =+  panelWith (fixedWH 260 120 . padAll 20) $+    panelWith (fillW . fillH) (label "padAll 20")+-- ANCHOR_END: padall++-- ANCHOR: padxy+padXYExample =+  panelWith (fixedWH 280 100 . padXY 32 10) $+    panelWith (fillW . fillH) (label "padXY 32 10")+-- ANCHOR_END: padxy++-- ANCHOR: padleft+padLeftExample =+  panelWith (fixedWH 260 100 . padLeft 48) $+    panelWith (fillW . fillH) (label "padLeft 48")+-- ANCHOR_END: padleft++-- ANCHOR: padright+padRightExample =+  panelWith (fixedWH 260 100 . padRight 48) $+    panelWith (fillW . fillH) (label "padRight 48")+-- ANCHOR_END: padright++-- ANCHOR: padtop+padTopExample =+  panelWith (fixedWH 260 120 . padTop 40) $+    panelWith (fillW . fillH) (label "padTop 40")+-- ANCHOR_END: padtop++-- ANCHOR: padbottom+padBottomExample =+  panelWith (fixedWH 260 120 . padBottom 40) $+    panelWith (fillW . fillH) (label "padBottom 40")+-- ANCHOR_END: padbottom++-- ANCHOR: padlrtb+padLRTBExample =+  panelWith (fixedWH 280 120 . padLRTB 40 8 30 12) $+    panelWith (fillW . fillH) (label "padLRTB 40 8 30 12")+-- ANCHOR_END: padlrtb++-- ANCHOR: gap+gapExample =+  columnWith (fillW . gap 12) $ do+    rowWith (gap 4) $ mapM_ (void . button) ["gap 4", "B", "C"]+    rowWith (gap 24) $ mapM_ (void . button) ["gap 24", "B", "C"]+-- ANCHOR_END: gap++-- ANCHOR: tight+tightExample =+  rowWith (gap 16 . fillW) $ do+    panelWith (padAll 14 . gap 6 . fillW) $ do+      muted "padAll 14"+      label "default padding"+    panelWith (tight . padAll 14 . gap 6 . fillW) $ do+      muted "tight"+      label "no padding"+-- ANCHOR_END: tight++-- ANCHOR: alignstart+alignStartExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    void (buttonWith (alignStart . fixedW 140) "alignStart")+-- ANCHOR_END: alignstart++-- ANCHOR: alignend+alignEndExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    void (buttonWith (alignEnd . fixedW 140) "alignEnd")+-- ANCHOR_END: alignend++-- ANCHOR: aligncenter+alignCenterExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    void (buttonWith (alignCenter . fixedW 140) "alignCenter")+-- ANCHOR_END: aligncenter++-- ANCHOR: aligntop+alignTopExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    rowWith (fillW . fillH . gap 8) $+      void (buttonWith (alignTop . fixedW 140) "alignTop")+-- ANCHOR_END: aligntop++-- ANCHOR: alignmid+alignMidExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    rowWith (fillW . fillH . gap 8) $+      void (buttonWith (alignMiddle . fixedW 140) "alignMiddle")+-- ANCHOR_END: alignmid++-- ANCHOR: alignbottom+alignBottomExample =+  panelWith (fixedWH 300 110 . padAll 10) $+    rowWith (fillW . fillH . gap 8) $+      void (buttonWith (alignBottom . fixedW 140) "alignBottom")+-- ANCHOR_END: alignbottom++-- ANCHOR: alignbaseline+alignBaselineExample =+  rowWith (gap 12 . fixedW 340) $ do+    labelWith (fontSize 24 . alignBaseline) "Title"+    labelWith alignBaseline "baseline text"+-- ANCHOR_END: alignbaseline++-- ANCHOR: wrap+wrapExample =+  rowWith (wrap . gap 6 . fixedW 280) $+    mapM_ (void . button) ["haskell", "immediate", "mode", "layout", "sdl", "widgets"]+-- ANCHOR_END: wrap++-- ANCHOR: linegap+lineGapExample =+  columnWith (fillW . gap 16) $ do+    let labels = ["haskell", "immediate", "mode", "layout", "sdl", "widgets"]+    muted "lineGap 2"+    rowWith (wrap . lineGap 2 . gap 6 . fixedW 280) $ mapM_ (void . button) labels+    muted "lineGap 18"+    rowWith (wrap . lineGap 18 . gap 6 . fixedW 280) $ mapM_ (void . button) labels+-- ANCHOR_END: linegap++-- ANCHOR: linealign+lineAlignExample =+  rowWith (wrap . lineAlign LinesCenter . gap 6 . fixedW 210) $+    mapM_ (void . button) ["alpha", "beta", "gamma", "delta", "epsilon"]+-- ANCHOR_END: linealign++-- ANCHOR: pinat+pinAtExample =+  panelWith (fixedWH 280 110 . padAll 12) $ do+    heading "Inbox"+    muted "The badge is pinned, not stacked."+    let badgeCol = colorRGB 204 64 64+    styled (panelStyle (background badgeCol . borderColor badgeCol)) $+      panelWith (pinAt 6 (-6) . alignEnd . alignTop . padXY 6 1) $+        labelWith (fontColor colorWhite) "12"+-- ANCHOR_END: pinat++-- ANCHOR: pointerblock+pointerBlockExample =+  layers $ do+    void (buttonWith (fixedWH 200 44) "Open logs")+    styled (panelStyle (background (colorRGBA 0 0 0 150) . borderWidth 0)) $+      panelWith (pinAt 0 0 . grow . pointer PointerBlock . padAll 6) $+        muted "scrim"+-- ANCHOR_END: pointerblock++-- ANCHOR: pointerpass+pointerPassExample =+  layers $ do+    void (buttonWith (fixedWH 200 44) "Open logs")+    labelWith (pinAt 8 (-6) . pointer PointerPass) "decorative label"+-- ANCHOR_END: pointerpass++-- | Every layout example, in the order the book presents them, with the+-- canvas size to render it at. The hover points park the pointer on the+-- control a pointer-mode example overlays.+layoutExamples :: [(Text, Float, Float, Maybe V2, NanoUI ())]+layoutExamples =+  [ ("row", 420, 74, Nothing, rowExample)+  , ("column", 420, 140, Nothing, columnExample)+  , ("grid", 420, 120, Nothing, gridExample)+  , ("panel", 420, 110, Nothing, panelExample)+  , ("card", 420, 120, Nothing, cardExample)+  , ("callout", 420, 130, Nothing, calloutExample)+  , ("layers", 420, 90, Nothing, layersExample)+  , ("center", 420, 150, Nothing, centerExample)+  , ("responsive-narrow", 420, 140, Nothing, responsiveExample)+  , ("responsive-wide", 760, 110, Nothing, responsiveExample)+  , ("mousearea", 420, 100, Nothing, mouseAreaExample)+  , ("separator", 420, 110, Nothing, separatorExample)+  , ("spacer", 420, 74, Nothing, spacerExample)+  , ("fillw", 420, 74, Nothing, fillWExample)+  , ("fillh", 420, 140, Nothing, fillHExample)+  , ("grow", 420, 150, Nothing, growExample)+  , ("fixedw", 420, 74, Nothing, fixedWExample)+  , ("fixedh", 420, 130, Nothing, fixedHExample)+  , ("fixedwh", 420, 120, Nothing, fixedWHExample)+  , ("minw", 420, 74, Nothing, minWExample)+  , ("maxw", 420, 74, Nothing, maxWExample)+  , ("minh", 420, 130, Nothing, minHExample)+  , ("maxh", 420, 130, Nothing, maxHExample)+  , ("percent", 420, 100, Nothing, percentExample)+  , ("aspect", 460, 280, Nothing, aspectExample)+  , ("padall", 420, 150, Nothing, padAllExample)+  , ("padxy", 420, 130, Nothing, padXYExample)+  , ("padleft", 420, 130, Nothing, padLeftExample)+  , ("padright", 420, 130, Nothing, padRightExample)+  , ("padtop", 420, 150, Nothing, padTopExample)+  , ("padbottom", 420, 150, Nothing, padBottomExample)+  , ("padlrtb", 420, 150, Nothing, padLRTBExample)+  , ("gap", 420, 110, Nothing, gapExample)+  , ("tight", 420, 140, Nothing, tightExample)+  , ("alignstart", 420, 150, Nothing, alignStartExample)+  , ("aligncenter", 420, 150, Nothing, alignCenterExample)+  , ("alignend", 420, 150, Nothing, alignEndExample)+  , ("aligntop", 420, 150, Nothing, alignTopExample)+  , ("alignmid", 420, 150, Nothing, alignMidExample)+  , ("alignbottom", 420, 150, Nothing, alignBottomExample)+  , ("alignbaseline", 420, 90, Nothing, alignBaselineExample)+  , ("wrap", 420, 170, Nothing, wrapExample)+  , ("linegap", 420, 230, Nothing, lineGapExample)+  , ("linealign", 420, 170, Nothing, lineAlignExample)+  , ("pinat", 420, 160, Nothing, pinAtExample)+  , ("pointer-block", 420, 100, Just (V2 114 36), pointerBlockExample)+  , ("pointer-pass", 420, 100, Just (V2 40 20), pointerPassExample)+  ]
+ assets/glossary.css view
@@ -0,0 +1,760 @@+:root {+  --draft-bg: #e4e9f1;+  --draft-surface: #f4f6fa;+  --draft-card: #ffffff;+  --draft-border: #c5cedd;+  --draft-border-strong: #94a3b8;+  --well-bg: #0b0c10;+  --well-border: #262936;+  --ink-primary: #0f172a;+  --ink-secondary: #334155;+  --ink-muted: #64748b;+  --probe-btn: #0369a1;+  --probe-btn-border: #38bdf8;+  --probe-inp: #047857;+  --probe-inp-border: #34d399;+  --probe-pnl: #581c87;+  --probe-pnl-border: #c084fc;+  --probe-pop: #b45309;+  --probe-pop-border: #fbbf24;+  --probe-acc: #e11d48;+  --font-display: 'Space Grotesk', 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;+  --font-sans: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;+  --font-mono: 'Cascadia Mono', 'JetBrains Mono', 'Consolas', monospace;+}+* { box-sizing: border-box; }+body {+  margin: 0;+  background-color: var(--draft-bg);+  background-image: radial-gradient(#bac4d6 1px, transparent 1px);+  background-size: 20px 20px;+  color: var(--ink-primary);+  font-family: var(--font-sans);+  font-size: 14px;+  line-height: 1.55;+}+.layout-shell {+  display: grid;+  grid-template-columns: 260px minmax(0, 1fr);+  min-height: 100vh;+}+@media (max-width: 1100px) {+  .layout-shell { grid-template-columns: 1fr; }+  .sidebar { position: static !important; height: auto !important; border-right: none !important; border-bottom: 1px solid var(--draft-border); }+}+.sidebar {+  position: sticky;+  top: 0;+  height: 100vh;+  overflow-y: auto;+  background: #111520;+  color: #e2e8f0;+  padding: 22px 18px;+  border-right: 1px solid #1e293b;+}+.brand-kicker {+  font-family: var(--font-mono);+  font-size: 11px;+  letter-spacing: 0.08em;+  text-transform: uppercase;+  color: #38bdf8;+  margin-bottom: 4px;+}+.brand-title {+  font-family: var(--font-display);+  font-size: 19px;+  font-weight: 700;+  margin: 0 0 6px 0;+  letter-spacing: -0.02em;+  color: #ffffff;+}+.brand-sub {+  font-size: 12px;+  color: #94a3b8;+  margin: 0 0 18px 0;+}+.nav-group-label {+  font-family: var(--font-mono);+  font-size: 10px;+  text-transform: uppercase;+  letter-spacing: 0.09em;+  color: #64748b;+  margin: 16px 0 6px 0;+}+.nav-list {+  list-style: none;+  padding: 0;+  margin: 0;+}+.nav-list li { margin-bottom: 2px; }+.nav-list a {+  display: block;+  padding: 5px 8px;+  border-radius: 5px;+  color: #cbd5e1;+  text-decoration: none;+  font-size: 12.5px;+  transition: background 0.12s, color 0.12s;+}+.nav-list a:hover {+  background: #1e293b;+  color: #ffffff;+}+.legend-box {+  margin-top: 18px;+  padding: 12px;+  background: #171c2b;+  border: 1px solid #263046;+  border-radius: 8px;+}+.legend-row {+  display: flex;+  align-items: center;+  gap: 8px;+  font-family: var(--font-mono);+  font-size: 11px;+  margin-bottom: 6px;+  color: #e2e8f0;+}+.legend-row:last-child { margin-bottom: 0; }+.swatch {+  width: 14px;+  height: 14px;+  border-radius: 3px;+  flex-shrink: 0;+}+.main-content {+  padding: 28px 36px 64px 36px;+  max-width: 1480px;+}+.hero-banner, .workbench-card {+  background: var(--draft-card);+  border: 1px solid var(--draft-border);+  border-radius: 12px;+  padding: 22px 24px;+  margin-bottom: 24px;+  box-shadow: 0 2px 6px rgba(15, 23, 42, 0.04);+}+.hero-top {+  display: flex;+  flex-wrap: wrap;+  justify-content: space-between;+  align-items: flex-start;+  gap: 16px;+  margin-bottom: 16px;+}+.hero-title {+  font-family: var(--font-display);+  font-size: 27px;+  font-weight: 700;+  letter-spacing: -0.025em;+  margin: 0 0 6px 0;+}+.hero-lead {+  color: var(--ink-secondary);+  max-width: 860px;+  margin: 0;+  font-size: 14.5px;+}+.svg-well {+  background: var(--well-bg);+  border: 1px solid var(--well-border);+  border-radius: 7px;+  padding: 6px;+  display: flex;+  align-items: center;+  justify-content: center;+  overflow-x: auto;+  position: relative;+  transition: background 0.15s ease, border-color 0.15s ease;+}+.svg-well.light-theme {+  background: #e4e4e7;+  border-color: #cbd5e1;+}+.svg-well svg {+  display: block;+  flex-shrink: 0;+  /* These are static exports, not live widgets: no text selection, no hit+     testing, no drag-and-drop ghost. */+  user-select: none;+  -webkit-user-select: none;+  pointer-events: none;+  -webkit-user-drag: none;+}+.svg-well svg text,+.svg-well svg rect,+.svg-well svg line,+.svg-well svg polygon {+  pointer-events: none;+  user-select: none;+}+.wb-grid {+  display: grid;+  grid-template-columns: auto minmax(320px, 1fr);+  gap: 22px;+  align-items: start;+}+@media (max-width: 1080px) {+  .wb-grid { grid-template-columns: 1fr; }+}+.wb-viewport-col {+  display: flex;+  flex-direction: column;+  gap: 8px;+}+.wb-viewport-head {+  display: grid;+  /* A definite label track: the header's width no longer depends on the+     status text, so toggling a mask cannot reflow the card's columns. */+  grid-template-columns: minmax(0, 328px) max-content;+  justify-content: space-between;+  align-items: center;+  gap: 8px;+}+.probe-stage-col .wb-viewport-head {+  grid-template-columns: minmax(0, 184px) max-content;+}+.wb-active-label {+  font-family: var(--font-mono);+  font-size: 11.5px;+  font-weight: 600;+  color: var(--ink-secondary);+  min-width: 0;+  overflow: hidden;+  text-overflow: ellipsis;+  white-space: nowrap;+}+.wb-head-actions {+  display: flex;+  flex-shrink: 0;+  gap: 6px;+  align-items: center;+}+.mini-btn {+  font-family: var(--font-mono);+  font-size: 11px;+  font-weight: 600;+  padding: 4px 9px;+  border-radius: 5px;+  border: 1px solid var(--draft-border-strong);+  background: var(--draft-surface);+  color: var(--ink-primary);+  cursor: pointer;+  transition: all 0.12s;+}+.mini-btn:hover { border-color: #0284c7; color: #0284c7; background: #f0f9ff; }+.mini-btn.active { background: #0f172a; color: #ffffff; border-color: #0f172a; }+.control-group-label {+  font-family: var(--font-mono);+  font-size: 11px;+  font-weight: 700;+  text-transform: uppercase;+  letter-spacing: 0.05em;+  color: var(--ink-muted);+  margin-bottom: 8px;+}+.toggle-chip-grid {+  display: grid;+  grid-template-columns: repeat(auto-fill, minmax(172px, 1fr));+  gap: 7px;+}+.style-chip {+  display: flex;+  align-items: center;+  gap: 7px;+  padding: 6px 9px;+  border-radius: 7px;+  border: 1px solid #cbd5e1;+  background: #f8fafc;+  color: var(--ink-primary);+  font-family: var(--font-mono);+  font-size: 11.5px;+  font-weight: 600;+  cursor: pointer;+  text-align: left;+  transition: all 0.12s;+}+.style-chip:hover {+  border-color: #64748b;+  background: #ffffff;+  transform: translateY(-1px);+}+.chip-check {+  width: 14px;+  height: 14px;+  border-radius: 3px;+  border: 1.5px solid #94a3b8;+  background: #ffffff;+  display: inline-flex;+  align-items: center;+  justify-content: center;+  flex-shrink: 0;+  font-size: 10px;+  line-height: 1;+  color: transparent;+}+.style-chip.active {+  background: #0f172a;+  color: #ffffff;+  border-color: #0f172a;+  box-shadow: 0 2px 5px rgba(15, 23, 42, 0.16);+}+.style-chip.active[data-probe="btn"] { background: #0369a1; border-color: #38bdf8; }+.style-chip.active[data-probe="inp"] { background: #047857; border-color: #34d399; }+.style-chip.active[data-probe="pnl"] { background: #581c87; border-color: #c084fc; }+.style-chip.active[data-probe="pop"] { background: #b45309; border-color: #fbbf24; }+.style-chip.active[data-probe="acc"] { background: #be123c; border-color: #fb7185; }+.style-chip.active .chip-check {+  background: #ffffff;+  border-color: #ffffff;+  color: #0f172a;+}+.style-chip.active .chip-check::after { content: '✓'; font-weight: 900; }+.chip-name { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.chip-tag {+  font-size: 9.5px;+  padding: 1px 5px;+  border-radius: 4px;+  font-weight: 700;+  white-space: nowrap;+}+.impact-primary { background: #dcfce7; color: #166534; }+.impact-partial { background: #fef3c7; color: #92400e; }+.impact-surprise { background: #ffe4e6; color: #9f1239; }+.impact-noop { background: #e2e8f0; color: #64748b; }+.style-chip.active .chip-tag {+  background: rgba(255, 255, 255, 0.2);+  color: #ffffff;+}+.state-pill-grid {+  display: grid;+  grid-template-columns: repeat(auto-fill, minmax(165px, 1fr));+  gap: 7px;+}+.state-pill {+  display: flex;+  flex-direction: column;+  align-items: flex-start;+  padding: 7px 10px;+  border-radius: 7px;+  border: 1px solid #cbd5e1;+  background: #f8fafc;+  cursor: pointer;+  text-align: left;+  transition: all 0.12s;+}+.state-pill strong { font-size: 12px; color: var(--ink-primary); }+.state-pill span { font-family: var(--font-mono); font-size: 10.5px; color: var(--ink-muted); }+.state-pill.active {+  background: #0f172a;+  border-color: #38bdf8;+}+.state-pill.active strong { color: #ffffff; }+.state-pill.active span { color: #93c5fd; }+.wb-code-bar {+  background: #0f172a;+  color: #e2e8f0;+  border: 1px solid #1e293b;+  border-radius: 6px;+  padding: 7px 10px;+  font-family: var(--font-mono);+  font-size: 11.5px;+  overflow-x: auto;+  white-space: pre;+  /* The preview text changes with the mask; contribute no intrinsic width so+     it can never widen the column, then fill the column it lands in. */+  width: 0;+  min-width: 100%;+}+/* A fixed pane on the widget cards, whose expression gains `themed`/`styled`+   lines as modifiers toggle. */+.probe-meta .wb-code-bar {+  height: 100px;+  overflow-y: auto;+}+.wb-code-bar pre { margin: 0; font-family: var(--font-mono); font-size: 11.5px; line-height: 1.4; white-space: pre; }+.code-bar-head {+  font-size: 10px;+  text-transform: uppercase;+  letter-spacing: 0.06em;+  color: #64748b;+  margin-bottom: 3px;+}+.wb-inspector {+  margin-top: 10px;+  background: var(--draft-surface);+  border: 1px solid #dbe2ee;+  border-radius: 7px;+  padding: 9px 11px;+  font-size: 12.5px;+  color: var(--ink-secondary);+  /* A fixed pane keeps the card from resizing as notes appear/disappear. */+  height: 132px;+  overflow-y: auto;+}+.ins-item {+  padding: 4px 0;+  border-bottom: 1px dashed #cbd5e1;+}+.ins-item:last-child { border-bottom: none; padding-bottom: 0; }+.ins-item:first-child { padding-top: 0; }+.ins-empty { color: var(--ink-muted); font-style: italic; font-size: 12px; }+.master-bar {+  position: sticky;+  top: 0;+  z-index: 25;+  background: rgba(255, 255, 255, 0.95);+  backdrop-filter: blur(10px);+  border: 1px solid var(--draft-border-strong);+  border-radius: 10px;+  padding: 12px 16px;+  margin-bottom: 18px;+  box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);+}+.master-bar-top {+  display: flex;+  justify-content: space-between;+  align-items: center;+  flex-wrap: wrap;+  gap: 10px;+  margin-bottom: 8px;+}+.master-bar-title {+  font-family: var(--font-mono);+  font-size: 12px;+  font-weight: 700;+  color: var(--ink-primary);+}+.probe-row {+  background: var(--draft-card);+  border: 1px solid var(--draft-border);+  border-radius: 10px;+  padding: 16px 18px;+  margin-bottom: 16px;+  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.03);+}+.probe-card-grid {+  display: grid;+  grid-template-columns: minmax(250px, 0.95fr) auto minmax(320px, 1.25fr);+  gap: 18px;+  align-items: start;+}+@media (max-width: 1220px) {+  .probe-card-grid { grid-template-columns: 1fr; }+}+.probe-meta { display: flex; flex-direction: column; gap: 6px; }+.probe-title-line {+  display: flex;+  align-items: center;+  gap: 10px;+  flex-wrap: wrap;+}+.probe-title {+  font-family: var(--font-display);+  font-size: 17px;+  margin: 0;+}+.surface-pill {+  font-family: var(--font-mono);+  font-size: 11px;+  background: #0f172a;+  color: #38bdf8;+  padding: 2px 8px;+  border-radius: 4px;+}+.probe-sig {+  display: inline-block;+  font-family: var(--font-mono);+  font-size: 12px;+  color: var(--ink-muted);+}+.probe-desc {+  margin: 0;+  color: var(--ink-secondary);+  font-size: 13px;+}+.probe-stage-col {+  display: flex;+  flex-direction: column;+  gap: 8px;+  min-width: 256px;+}+.wb-dual-stage {+  display: flex;+  gap: 10px;+  align-items: stretch;+}+.hidden-compare { display: none !important; }+.well-corner-tag {+  position: absolute;+  top: 4px;+  left: 6px;+  font-family: var(--font-mono);+  font-size: 9.5px;+  color: #94a3b8;+  background: rgba(15, 23, 42, 0.78);+  padding: 1px 5px;+  border-radius: 3px;+}+.wb-baseline-well { padding-top: 22px; border-style: dashed; }+.filter-bar {+  display: flex;+  flex-wrap: wrap;+  gap: 8px;+  align-items: center;+  margin-bottom: 20px;+}+.filter-btn {+  font-family: var(--font-mono);+  font-size: 12px;+  padding: 6px 12px;+  border-radius: 6px;+  border: 1px solid var(--draft-border-strong);+  background: var(--draft-card);+  color: var(--ink-primary);+  cursor: pointer;+  font-weight: 500;+  transition: all 0.12s;+}+.filter-btn:hover { border-color: #0284c7; color: #0284c7; }+.filter-btn.active {+  background: #0f172a;+  color: #ffffff;+  border-color: #0f172a;+}+.section-head {+  margin: 36px 0 14px 0;+  border-bottom: 2px solid var(--ink-primary);+  padding-bottom: 8px;+  display: flex;+  justify-content: space-between;+  align-items: baseline;+  flex-wrap: wrap;+  gap: 8px;+}+.section-head h2 {+  font-family: var(--font-display);+  font-size: 22px;+  margin: 0;+  letter-spacing: -0.02em;+}+.section-head span {+  font-family: var(--font-mono);+  font-size: 12px;+  color: var(--ink-muted);+}+.routing-table-wrap {+  background: var(--draft-card);+  border: 1px solid var(--draft-border);+  border-radius: 10px;+  overflow-x: auto;+  margin-bottom: 28px;+}+table.routing-table {+  width: 100%;+  border-collapse: collapse;+  font-size: 13px;+}+.routing-table th, .routing-table td {+  padding: 9px 12px;+  text-align: left;+  border-bottom: 1px solid #e2e8f0;+  vertical-align: top;+}+.routing-table th {+  background: #f1f5f9;+  font-family: var(--font-mono);+  font-size: 11.5px;+  text-transform: uppercase;+  letter-spacing: 0.04em;+  color: var(--ink-secondary);+}+.routing-table tr:last-child td { border-bottom: none; }+.routing-table code {+  font-family: var(--font-mono);+  font-size: 12px;+  background: #f1f5f9;+  padding: 1px 5px;+  border-radius: 4px;+}+.badge {+  display: inline-block;+  font-family: var(--font-mono);+  font-size: 11px;+  font-weight: 600;+  padding: 1px 6px;+  border-radius: 4px;+  margin-right: 4px;+}+.b-btn { background: #e0f2fe; color: #0369a1; border: 1px solid #7dd3fc; }+.b-inp { background: #d1fae5; color: #047857; border: 1px solid #6ee7b7; }+.b-pnl { background: #f3e8ff; color: #6b21a8; border: 1px solid #d8b4fe; }+.b-pop { background: #fef3c7; color: #92400e; border: 1px solid #fcd34d; }+.b-acc { background: #ffe4e6; color: #be123c; border: 1px solid #fda4af; }+.typo-grid {+  display: grid;+  grid-template-columns: 1fr;+  gap: 14px;+  margin-bottom: 28px;+}+.typo-card {+  background: var(--draft-card);+  border: 1px solid var(--draft-border);+  border-radius: 10px;+  padding: 16px 20px;+  display: grid;+  grid-template-columns: minmax(280px, 1fr) auto;+  gap: 18px;+  align-items: center;+}+@media (max-width: 960px) {+  .typo-card { grid-template-columns: 1fr; }+}+.typo-info h3 { margin: 0 0 4px 0; font-family: var(--font-display); font-size: 16.5px; }+.typo-code { display: inline-block; font-family: var(--font-mono); font-size: 12px; background: #f1f5f9; padding: 2px 6px; border-radius: 4px; margin-bottom: 6px; }+.typo-info p { margin: 0; color: var(--ink-secondary); font-size: 13.5px; }+.trap-card {+  background: var(--draft-card);+  border: 1px solid var(--draft-border);+  border-left: 5px solid #d97706;+  border-radius: 10px;+  padding: 18px 22px;+  margin-bottom: 18px;+  box-shadow: 0 2px 5px rgba(15, 23, 42, 0.04);+}+.trap-header { margin-bottom: 12px; }+.trap-num {+  font-family: var(--font-mono);+  font-size: 11px;+  font-weight: 700;+  color: #b45309;+  background: #fef3c7;+  padding: 2px 7px;+  border-radius: 4px;+  letter-spacing: 0.05em;+}+.trap-title {+  font-family: var(--font-display);+  font-size: 18px;+  margin: 6px 0 4px 0;+}+.trap-where {+  font-family: var(--font-mono);+  font-size: 11.5px;+  color: var(--ink-muted);+}+.trap-body {+  display: grid;+  grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr);+  gap: 20px;+  align-items: start;+}+@media (max-width: 1024px) {+  .trap-body { grid-template-columns: 1fr; }+}+.trap-block {+  margin-bottom: 10px;+  color: var(--ink-secondary);+  font-size: 13.5px;+}+.trap-fix {+  background: #ecfdf5;+  border: 1px solid #a7f3d0;+  color: #065f46;+  padding: 8px 12px;+  border-radius: 6px;+}+.trap-code-grid {+  display: grid;+  grid-template-columns: 1fr 1fr;+  gap: 10px;+  margin-top: 10px;+}+@media (max-width: 680px) {+  .trap-code-grid { grid-template-columns: 1fr; }+}+.code-pane {+  border-radius: 6px;+  overflow: hidden;+  border: 1px solid #cbd5e1;+  background: #0f172a;+  color: #f8fafc;+}+.code-pane pre {+  margin: 0;+  padding: 9px 11px;+  font-family: var(--font-mono);+  font-size: 11.5px;+  line-height: 1.45;+  overflow-x: auto;+}+.code-tag {+  font-family: var(--font-mono);+  font-size: 10.5px;+  font-weight: 700;+  text-transform: uppercase;+  padding: 4px 10px;+  letter-spacing: 0.05em;+}+.code-bad .code-tag { background: #7f1d1d; color: #fecaca; }+.code-good .code-tag { background: #065f46; color: #a7f3d0; }+.trap-visuals {+  display: grid;+  grid-template-columns: 1fr 1fr;+  gap: 10px;+}+.trap-visuals.single-view {+  grid-template-columns: 1fr;+}+@media (max-width: 580px) {+  .trap-visuals { grid-template-columns: 1fr; }+}+.trap-svg-box {+  background: var(--draft-surface);+  border: 1px solid var(--draft-border);+  border-radius: 8px;+  padding: 8px;+}+.trap-svg-bad { border-top: 3px solid #ef4444; }+.trap-svg-good { border-top: 3px solid #10b981; }+.trap-svg-label {+  font-family: var(--font-mono);+  font-size: 11px;+  font-weight: 600;+  margin-bottom: 6px;+  color: var(--ink-secondary);+}+.trap-mode-bar { display: flex; gap: 4px; }+.hidden-by-filter { display: none !important; }++/* Focus visibility, text rendering, and motion preferences */+:root { --focus-ring: #0284c7; }+html { scroll-behavior: smooth; scroll-padding-top: 14px; }+body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility; }+::selection { background: #bae6fd; color: #0f172a; }+:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }+.mini-btn:focus-visible, .filter-btn:focus-visible, .style-chip:focus-visible, .state-pill:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }+.main-content, .sidebar { scrollbar-width: thin; scrollbar-color: #94a3b8 transparent; }+.mini-btn:active, .filter-btn:active { transform: translateY(1px); }+.style-chip:active, .state-pill:active { transform: translateY(0) scale(0.98); }+@media (prefers-reduced-motion: reduce) {+  html { scroll-behavior: auto; }+  *, *::before, *::after { transition-duration: 0.01ms !important; animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; }+  .style-chip:hover { transform: none; }+}++/* Inline code inside prose (backticked runs). */+.probe-desc code, .trap-block code {+  font-family: var(--font-mono);+  font-size: 0.92em;+  background: #eef2f7;+  color: #0f172a;+  padding: 0 4px;+  border-radius: 4px;+  white-space: nowrap;+}+.trap-fix code {+  background: rgba(6, 95, 70, 0.10);+  color: #064e3b;+}
+ assets/glossary.js view
@@ -0,0 +1,270 @@+const widgetMasks = {};+const widgetCompare = {};+let globalMask = 0;+let globalCompare = false;+let heroMask = 0;+let stateMode = 0;+let stateStyleMask = 0;+let typoMask = 0;++function unpackSvg(bankId, mask) {+  const b = SVG_BANKS[bankId];+  if (!b || !b.c[mask]) return '';+  return b.c[mask].map(i => b.l[i]).join('><');+}++function buildHaskellCode(expr, mask, isOverlay) {+  const mods = [];+  if (mask & 32) mods.push('rounded 999');+  if (mask & 16) mods.push('accentColor rose');+  if (mask & 8) mods.push(isOverlay ? 'panelStyle probePnl . popupStyle probePop . windowStyle probeWin' : 'panelStyle probePnl');+  if (mask & 4) mods.push('inputStyle probeInp');+  if (mask & 2) mods.push('buttonStyle probeBtn');+  const lines = [];+  let indent = '';+  if (mask & 1) { lines.push('themed defaultLightTheme $'); indent += '  '; }+  if (mods.length > 0) { lines.push(indent + 'styled (' + mods.join(' . ') + ') $'); indent += '  '; }+  if (mask & 64) { lines.push(indent + 'disabledWhen True $'); indent += '  '; }+  lines.push(indent + expr);+  return lines.join('\n');+}++function describeMaskShort(mask) {+  if (mask === 0) return 'defaultTheme (0 modifiers)';+  const names = [];+  if (mask & 1) names.push('Light');+  if (mask & 2) names.push('buttonStyle');+  if (mask & 4) names.push('inputStyle');+  if (mask & 8) names.push('panelStyle');+  if (mask & 16) names.push('accentColor');+  if (mask & 32) names.push('rounded');+  if (mask & 64) names.push('disabledWhen');+  return 'Active (' + names.length + '): ' + names.join(' + ');+}++/* Status labels have a fixed width so toggling a mask cannot reflow the card;+   the full text stays available as a tooltip. */+function setLabel(el, text) {+  el.textContent = text;+  el.title = text;+}++function renderWidgetNotes(wid, previewBit) {+  const meta = WIDGET_META[wid];+  const mask = widgetMasks[wid] || 0;+  const box = document.getElementById('notes-' + wid);+  if (!meta || !box) return;+  const activeNotes = meta.notes.filter(n => (mask & (1 << n.bit)) !== 0 || n.bit === previewBit);+  if (activeNotes.length === 0) {+    box.innerHTML = '<div class="ins-empty">Select a style above to see what it changes.</div>';+    return;+  }+  box.innerHTML = activeNotes.map(n => {+    const isOn = (mask & (1 << n.bit)) !== 0;+    const prefix = isOn ? '' : '<em>(Preview)</em> ';+    const detail = n.detail.replace(/`([^`]+)`/g, '<code>$1</code>');+    return '<div class="ins-item">' + prefix + '<strong><code>' + n.label + '</code></strong> <span class="chip-tag impact-' + n.impact + '">' + n.badge + '</span>: ' + detail + '</div>';+  }).join('');+}++function previewWidgetNote(wid, bit) { renderWidgetNotes(wid, bit); }+function clearWidgetPreview(wid) { renderWidgetNotes(wid, -1); }++function setWidgetMask(wid, mask) {+  widgetMasks[wid] = mask;+  const svgEl = document.getElementById('svg-' + wid);+  if (svgEl) {+    svgEl.innerHTML = unpackSvg(wid, mask);+    svgEl.classList.toggle('light-theme', (mask & 1) !== 0);+  }+  const statusEl = document.getElementById('status-' + wid);+  if (statusEl) setLabel(statusEl, describeMaskShort(mask));+  const meta = WIDGET_META[wid];+  const codeEl = document.getElementById('code-' + wid);+  if (meta && codeEl) codeEl.textContent = buildHaskellCode(meta.expr, mask, meta.isOverlay);+  document.querySelectorAll('.style-chip[data-wid="' + wid + '"]').forEach(btn => {+    const b = parseInt(btn.getAttribute('data-bit'), 10);+    btn.classList.toggle('active', (mask & (1 << b)) !== 0);+  });+  renderWidgetNotes(wid, -1);+}++function toggleWidgetBit(wid, bit) {+  const cur = widgetMasks[wid] || 0;+  setWidgetMask(wid, cur ^ (1 << bit));+}++function toggleWidgetCompare(wid, forceVal) {+  const next = typeof forceVal === 'boolean' ? forceVal : !widgetCompare[wid];+  widgetCompare[wid] = next;+  const baseWell = document.getElementById('base-well-' + wid);+  const baseSvg = document.getElementById('base-svg-' + wid);+  const btn = document.getElementById('cmp-btn-' + wid);+  if (baseWell && baseSvg) {+    if (next && !baseSvg.innerHTML) {+      baseSvg.innerHTML = unpackSvg(wid, 0).replaceAll('wb-' + wid + '-', 'wb-' + wid + '-base-');+    }+    baseWell.classList.toggle('hidden-compare', !next);+  }+  if (btn) btn.classList.toggle('active', next);+}++function toggleGlobalCompare() {+  globalCompare = !globalCompare;+  const gbtn = document.getElementById('global-cmp-btn');+  if (gbtn) gbtn.classList.toggle('active', globalCompare);+  Object.keys(WIDGET_META).forEach(wid => toggleWidgetCompare(wid, globalCompare));+}++function syncMasterButtons() {+  document.querySelectorAll('#master-toggles .style-chip').forEach(btn => {+    const b = parseInt(btn.getAttribute('data-gbit'), 10);+    btn.classList.toggle('active', (globalMask & (1 << b)) !== 0);+  });+}++function setAllWidgetsMask(mask) {+  globalMask = mask;+  syncMasterButtons();+  Object.keys(WIDGET_META).forEach(wid => setWidgetMask(wid, mask));+}++function toggleGlobalBit(bit) {+  globalMask ^= (1 << bit);+  syncMasterButtons();+  const turnOn = (globalMask & (1 << bit)) !== 0;+  Object.keys(WIDGET_META).forEach(wid => {+    const cur = widgetMasks[wid] || 0;+    const next = turnOn ? (cur | (1 << bit)) : (cur & ~(1 << bit));+    setWidgetMask(wid, next);+  });+}++function setHeroMask(mask) {+  heroMask = mask;+  const well = document.getElementById('hero-svg-well');+  if (well) {+    well.innerHTML = unpackSvg('hero', mask);+    well.classList.toggle('light-theme', (mask & 1) !== 0);+  }+  const st = document.getElementById('hero-status');+  if (st) setLabel(st, 'Composite · ' + describeMaskShort(mask));+  const cd = document.getElementById('hero-code-preview');+  if (cd) cd.textContent = buildHaskellCode('compositeDashboardView', mask, false);+  document.querySelectorAll('#hero-toggles .style-chip').forEach(btn => {+    const b = parseInt(btn.getAttribute('data-hbit'), 10);+    btn.classList.toggle('active', (mask & (1 << b)) !== 0);+  });+}+function toggleHeroBit(bit) { setHeroMask(heroMask ^ (1 << bit)); }++const STATE_NAMES = [+  ['Resting', 'Default fill and border from the widget surface.'],+  ['Hovered', 'Pointer over the Action Button: fill becomes styleHoverBg.'],+  ['Pressed', 'Left button held on the Action Button: fill becomes styleActiveBg.'],+  ['Focused', 'Keyboard focus on the Action Button: a 2px themeFocusRing is drawn outside it.'],+  ['Focused input', 'Clicked textInput: border becomes themeAccent, fill becomes styleActiveBg, caret shown.'],+  ['Open select', 'Clicked select: the closed box uses themeButton, the open menu uses themePopup.']+];++function updateStateWorkbench() {+  const idx = stateMode * 32 + stateStyleMask;+  const well = document.getElementById('state-svg-well');+  if (well) well.innerHTML = unpackSvg('state', idx);+  const info = STATE_NAMES[stateMode];+  const sNames = [];+  if (stateStyleMask & 1) sNames.push('buttonStyle');+  if (stateStyleMask & 2) sNames.push('inputStyle');+  if (stateStyleMask & 4) sNames.push('popupStyle');+  if (stateStyleMask & 8) sNames.push('accentColor');+  if (stateStyleMask & 16) sNames.push('disabledWhen True');+  const lbl = document.getElementById('state-active-label');+  if (lbl) setLabel(lbl, 'State: ' + info[0] + ' · ' + (sNames.length ? sNames.join(' + ') : 'defaultTheme'));+  const codeEl = document.getElementById('state-code-preview');+  if (codeEl) codeEl.textContent = '-- ' + info[0] + (sNames.length ? ' with ' + sNames.join(', ') : ' under defaultTheme');+  document.querySelectorAll('#state-mode-pills .state-pill').forEach(btn => {+    btn.classList.toggle('active', parseInt(btn.getAttribute('data-state'), 10) === stateMode);+  });+  document.querySelectorAll('#state-style-toggles .style-chip').forEach(btn => {+    const b = parseInt(btn.getAttribute('data-sbit'), 10);+    btn.classList.toggle('active', (stateStyleMask & (1 << b)) !== 0);+  });+  const ins = document.getElementById('state-inspector');+  if (ins) {+    let msg = '<div class="ins-item"><strong>' + info[0] + ':</strong> ' + info[1] + '</div>';+    if ((stateStyleMask & 16) && stateMode > 0) {+      msg += '<div class="ins-item"><span class="chip-tag impact-surprise">Suppressed</span> disabledWhen blocks hover, press, focus and menus in this subtree.</div>';+    }+    if (stateMode === 5 && (stateStyleMask & 4)) {+      msg += '<div class="ins-item"><span class="chip-tag impact-primary">popupStyle</span> The open menu uses themePopup; the closed select uses themeButton.</div>';+    }+    ins.innerHTML = msg;+  }+}+function setStateMode(m) { stateMode = m; updateStateWorkbench(); }+function toggleStateStyle(b) { stateStyleMask ^= (1 << b); updateStateWorkbench(); }+function resetStateWorkbench() { stateMode = 0; stateStyleMask = 0; updateStateWorkbench(); }++function setTypoMask(mask) {+  typoMask = mask;+  const well = document.getElementById('typo-svg-well');+  if (well) well.innerHTML = unpackSvg('typo', mask);+  const parts = [];+  if (mask & 1) parts.push('fontBold');+  if (mask & 2) parts.push('fontItalic');+  if (mask & 4) parts.push('fontUnderline');+  if (mask & 8) parts.push('fontStrike');+  if (mask & 16) parts.push('fontTone Danger');+  if (mask & 32) parts.push('fontSize 16');+  const lbl = document.getElementById('typo-active-label');+  if (lbl) setLabel(lbl, parts.length ? 'Active (' + parts.length + '): ' + parts.join(' . ') : 'No modifiers');+  const cd = document.getElementById('typo-code-preview');+  if (cd) cd.textContent = 'let m = ' + (parts.length ? parts.join(' . ') : 'id');+  document.querySelectorAll('#typo-toggles .style-chip').forEach(btn => {+    const b = parseInt(btn.getAttribute('data-tbit'), 10);+    btn.classList.toggle('active', (mask & (1 << b)) !== 0);+  });+}+function toggleTypoBit(b) { setTypoMask(typoMask ^ (1 << b)); }++function setTrapView(tid, mode, btn) {+  const wrap = document.getElementById('trap-vis-' + tid);+  const badBox = document.getElementById('trap-bad-' + tid);+  const goodBox = document.getElementById('trap-good-' + tid);+  if (!wrap || !badBox || !goodBox) return;+  btn.parentElement.querySelectorAll('.mini-btn').forEach(b => b.classList.remove('active'));+  btn.classList.add('active');+  if (mode === 'bad') {+    wrap.classList.add('single-view');+    badBox.classList.remove('hidden-compare');+    goodBox.classList.add('hidden-compare');+  } else if (mode === 'good') {+    wrap.classList.add('single-view');+    badBox.classList.add('hidden-compare');+    goodBox.classList.remove('hidden-compare');+  } else {+    wrap.classList.remove('single-view');+    badBox.classList.remove('hidden-compare');+    goodBox.classList.remove('hidden-compare');+  }+}++function filterGlossary(cat, btn) {+  document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));+  btn.classList.add('active');+  document.querySelectorAll('.filter-item').forEach(el => {+    if (cat === 'all') {+      el.classList.remove('hidden-by-filter');+    } else {+      const cats = (el.getAttribute('data-cat') || '').split(/\s+/);+      if (cats.includes(cat)) {+        el.classList.remove('hidden-by-filter');+      } else {+        el.classList.add('hidden-by-filter');+      }+    }+  });+}++Object.keys(WIDGET_META).forEach(wid => renderWidgetNotes(wid, -1));+updateStateWorkbench();
+ lib/NanoUI/Draw/FrameSvg.hs view
@@ -0,0 +1,460 @@+-- |+-- Module      : NanoUI.Draw.FrameSvg+-- Description : Export whole painted nano-ui frames to SVG+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- Render a whole painted frame of any view to an SVG document.+--+-- Paint lowers every widget straight to the vertex buffer. With+-- 'setDrawRecordOps' on, the shape emitters also record each solid shape they+-- draw, and each image, as the 'DrawOp' that draws it, under its layer and+-- clip. Drawings lower to the same emitters, so their shapes are recorded+-- with the widgets'. This module renders the recorded ops through+-- "NanoUI.Draw.Svg", with the text from 'collectRasterSpans'.+--+-- Call 'enableSvgExport' on the context before running frames. It records+-- the shapes, moves all text (including text inside drawings) onto the+-- raster spans consumed here, and draws rounded shapes round. Images, in+-- widgets and drawings alike, resolve their id through 'fsImageUri'.+--+-- > enableSvgExport ctx+-- > (_, dd, _) <- runFrame ctx inp view+-- > svg <- frameToSvg defaultFrameSvgConfig ctx inp dd+--+-- Text is fitted to the widths the context measured. A context from+-- 'NanoUI.Testing.newPixelContext' measures in a 16 px monospace grid, so+-- for text that reads like the app's, run the frames inside a backend+-- session (@withSdl@) that measures with the real font.+module NanoUI.Draw.FrameSvg+  ( FrameSvgConfig (..)+  , defaultFrameSvgConfig+  , enableSvgExport+  , frameToSvg+  )+where++import Control.Monad (forM, unless)+import Data.Bits (xor)+import Data.IORef (readIORef)+import Data.IntMap.Strict qualified as IM+import Data.List (find, partition, sortOn)+import Data.Map.Strict qualified as M+import Data.Primitive.PrimArray (PrimArray)+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Word (Word32, Word64)+import Numeric (showHex)+import NanoUI+  ( Color (..)+  , FontVariant (..)+  , Input (..)+  , Rect (..)+  , Size (..)+  , colorA+  , rectIntersect+  )+import NanoUI.Widgets.Custom (DrawOp (..))+import NanoUI.Backend+  ( DrawData (..)+  , FontMetrics (..)+  , Layer (..)+  , collectRasterSpans+  , textNodeFontStyle+  , textNodeFontVariant+  , textNodeFontWeight+  , textNodeTextDecoration+  )+import NanoUI.Draw.Svg (SvgConfig (..), defaultSvgConfig, renderDrawOpsSvg)+import NanoUI.Draw.Svg.Attr+  ( attr+  , escapeXml+  , fillAttrs+  , fmtNum+  , fontStyleAttrs+  , numAttr+  , rectEl+  )+import NanoUI.Internal.Context+  ( Context (..)+  , RecordedOp (..)+  , activeEffectNodes+  , drawRecordedOps+  , getDrawRecordOps+  , lookupShaderEffectAt+  , setDrawExternalText+  , setDrawRecordOps+  , setDrawSquareGeometry+  )+import NanoUI.Internal.Context.Types (SpanCacheEntry (..))+import NanoUI.Internal.Layout.Arena+  ( NodeType (..)+  , arenaCount+  , getNodeRect+  , getNodeType+  , getStyleIdx+  , hasCenteredLabel+  , nodeFontBits+  )+import NanoUI.Internal.Path (ringBox)+import NanoUI.Internal.Shader (ShaderEffectEntry (..))++-- | Options for 'frameToSvg'.+data FrameSvgConfig = FrameSvgConfig+  { fsPrecision :: !Int+  -- ^ Maximum decimal places for coordinates and lengths (clamped to+  -- @0..6@). One or two digits suits a whole window.+  , fsFontFamily :: !Text+  -- ^ The @font-family@ spans render in. Text is fitted to its measured+  -- width with @textLength@, so any family that lays out similarly to the+  -- context's font reads correctly.+  , fsImageUri :: !(Int -> Maybe Text)+  -- ^ As 'svgImageUri': resolves an image's id ('NanoUI.ImageId') to an+  -- @href@ or data URI. Images without a resolution are omitted.+  , fsIdPrefix :: !Text+  -- ^ Prepended to every clip and gradient id in the document, so several+  -- documents inlined in one page keep their ids apart. Empty, the default,+  -- takes a prefix from a hash of the document, which differs between+  -- documents that differ.+  }++-- | One decimal place, a sans-serif stack, no image resolver, and an id+-- prefix from the document's hash.+defaultFrameSvgConfig :: FrameSvgConfig+defaultFrameSvgConfig =+  FrameSvgConfig+    { fsPrecision = 1+    , fsFontFamily = "Inter, 'Segoe UI', system-ui, sans-serif"+    , fsImageUri = const Nothing+    , fsIdPrefix = T.empty+    }++-- | Render the frame 'NanoUI.Backend.runFrame' returned for @inp@ into a standalone SVG+-- document sized to the input's window. Page text draws over the page's+-- shapes, and overlay shapes and text over both, in paint order for each.+--+-- Fails if the context was not recording shapes ('enableSvgExport'), which+-- would export the text alone.+frameToSvg :: FrameSvgConfig -> Context -> Input -> DrawData -> IO Text+frameToSvg cfg0 ctx inp dd = do+  recording <- getDrawRecordOps ctx+  unless recording $+    ioError (userError "frameToSvg: the context does not record shapes; call enableSvgExport before running the frame")+  let+    autoPrefix = T.null (fsIdPrefix cfg0)+    -- An automatic prefix is filled in once the document is known. The+    -- placeholder holds a character that text and attribute values always+    -- carry escaped, so it can only be one of the ids.+    cfg = if autoPrefix then cfg0 {fsIdPrefix = idPlaceholder} else cfg0+  (pageSpans, overlaySpans) <- collectRasterSpans ctx inp+  spanStyles <- collectSpanStyles ctx+  opacityZones <- collectSvgOpacityZones ctx+  recorded <- drawRecordedOps ctx+  let+    (pageShapes, overlayShapes) = frameShapes recorded+    Size vw vh = inputWindowSize inp+    p = max 0 (min 6 (fsPrecision cfg))+    fm = ctxFontMetrics ctx+    sizeRatio = ctxFontSize ctx / fmLineHeight fm+    vp = Rect 0 0 vw vh+    -- Each render numbers its ids from 1, so each has its own prefix.+    render scope runs =+      mconcat+        [ let subScope = if i == 0 then scope else scope <> T.pack (show i)+              inner = TB.fromText . renderDrawOpsSvg (fragCfg subScope) vp $ smallArrayFromList ops+           in if null ops+                then mempty+                else+                  if alpha < 0.9999+                    then "<g" <> attr "opacity" (fmtNum p alpha) <> ">" <> inner <> "</g>"+                    else inner+        | (i, (alpha, ops)) <- zip [0 :: Int ..] runs+        ]+    fragCfg scope =+      defaultSvgConfig+        { svgStandalone = False+        , svgPrecision = p+        , svgImageUri = fsImageUri cfg+        , svgIdPrefix = fsIdPrefix cfg <> scope+        }+    tclip = TB.fromText (fsIdPrefix cfg) <> "tclip_"+    (pageTextDefs, pageTextBody, nextTClip) = spanTexts p (fsFontFamily cfg) fm sizeRatio spanStyles opacityZones tclip 1 pageSpans+    (overlayTextDefs, overlayTextBody, lastTClip) = spanTexts p (fsFontFamily cfg) fm sizeRatio spanStyles opacityZones tclip nextTClip overlaySpans+    allDefs+      | lastTClip == 1 = mempty+      | otherwise = "<defs>" <> pageTextDefs <> overlayTextDefs <> "</defs>"+    doc =+      "<svg xmlns=\"http://www.w3.org/2000/svg\""+        <> numAttr 0 "width" vw+        <> numAttr 0 "height" vh+        <> attr "viewBox" ("0 0 " <> fmtNum 0 vw <> " " <> fmtNum 0 vh)+        <> ">"+        <> allDefs+        <> solidRect p vp (drawClear dd)+        <> render "s" pageShapes+        <> pageTextBody+        <> render "o" overlayShapes+        <> overlayTextBody+        <> "</svg>"+    out = TL.toStrict (TB.toLazyText doc)+  pure (if autoPrefix then T.replace idPlaceholder (documentIdPrefix out) out else out)++-- | Turn on what 'frameToSvg' reads from a context: shape recording+-- ('setDrawRecordOps'), text as spans ('setDrawExternalText'), and rounded+-- geometry ('setDrawSquareGeometry' off). Call it before running the frames+-- to export.+enableSvgExport :: Context -> IO ()+enableSvgExport ctx = do+  setDrawRecordOps ctx True+  setDrawExternalText ctx True+  setDrawSquareGeometry ctx False++-- | Stands for the automatic id prefix while the document is built.+idPlaceholder :: Text+idPlaceholder = "<id>"++-- | An id prefix from an FNV-1a hash of a document, as eight hex digits.+documentIdPrefix :: Text -> Text+documentIdPrefix t =+  let h = T.foldl' (\acc c -> (acc `xor` fromIntegral (fromEnum c)) * 16777619) (2166136261 :: Word32) t+      hex = showHex h ""+   in "n" <> T.pack (replicate (8 - length hex) '0' <> hex) <> "-"++--------------------------------------------------------------------------------+-- Shapes the paint recorded+--------------------------------------------------------------------------------++-- | The recorded shapes in paint order (layer by layer, as the commands+-- run), split into page shapes ('LayerBackground', 'LayerContent') and+-- overlay shapes ('LayerOverlay', 'LayerChrome'), grouped into consecutive+-- opacity runs for SVG @\<g opacity\>@ export.+frameShapes :: [RecordedOp] -> ([(Float, [DrawOp])], [(Float, [DrawOp])])+frameShapes recorded = (opacityRuns page, opacityRuns overlay)+ where+  (page, overlay) =+    partition (\(RecordedOp layer _ _ _) -> layer < LayerOverlay) $+      sortOn (\(RecordedOp layer _ _ _) -> layer) recorded+  opacityRuns [] = []+  opacityRuns (r@(RecordedOp _ _ a _) : rs) =+    let (same, rest) = span (\(RecordedOp _ _ a' _) -> abs (a' - a) < 1.0e-4) rs+     in (a, clipRuns (r : same)) : opacityRuns rest++-- | Ops cut to their clips: a rect (an upright or level stroke among them)+-- is cut to it, a shape inside it stands alone, one outside it is dropped,+-- and a run of shapes overhanging one clip share a 'PushClip' group.+clipRuns :: [RecordedOp] -> [DrawOp]+clipRuns = go . concatMap cut+ where+  cut (RecordedOp _ clip _ op) = case asRect op of+    FillRect r col -> [(Nothing, FillRect r' col) | Just r' <- [rectIntersect clip r]]+    _ -> case opBounds op of+      Just b+        | rectIntersect clip b == Nothing -> []+        | fullyInside b clip -> [(Nothing, op)]+      _ -> [(Just clip, op)]+  go [] = []+  go ((Nothing, op) : rest) = op : go rest+  go ((Just c, op) : rest) =+    let (same, rest') = span ((== Just c) . fst) rest+     in PushClip c : op : map snd same ++ PopClip : go rest'++-- | A straight stroke along an axis as the rect it fills; any other op as+-- it is.+asRect :: DrawOp -> DrawOp+asRect op = case op of+  Stroke x0 y0 x1 y1 bw col -> segment x0 y0 x1 y1 bw col+  StrokeLineAA x0 y0 x1 y1 bw col -> segment x0 y0 x1 y1 bw col+  _ -> op+ where+  segment x0 y0 x1 y1 bw col+    | x0 == x1 = FillRect (Rect (x0 - bw / 2) (min y0 y1) bw (abs (y1 - y0))) col+    | y0 == y1 = FillRect (Rect (min x0 x1) (y0 - bw / 2) (abs (x1 - x0)) bw) col+    | otherwise = op++-- | The box an op draws within, for the ops the emitters record; a rotated+-- image has none, and goes in its clip's group.+opBounds :: DrawOp -> Maybe Rect+opBounds = \case+  FillRect r _ -> Just r+  FillRoundedRect r _ _ -> Just r+  StrokeRoundedRect r _ _ _ -> Just r+  FillQuadGradient r _ _ _ _ -> Just r+  DrawImage r 0 _ _ _ _ _ _ -> Just r+  Stroke x0 y0 x1 y1 bw _ -> Just (segmentBox x0 y0 x1 y1 bw)+  StrokeLineAA x0 y0 x1 y1 bw _ -> Just (segmentBox x0 y0 x1 y1 bw)+  FillPolygon pts _ _ _ -> pointsBox 0 pts+  StrokePolyline pts w _ _ _ _ _ -> pointsBox (w / 2) pts+  _ -> Nothing+ where+  segmentBox x0 y0 x1 y1 bw =+    let hw = bw / 2 in Rect (min x0 x1 - hw) (min y0 y1 - hw) (abs (x1 - x0) + bw) (abs (y1 - y0) + bw)++-- | The box around x/y pairs, grown by @pad@ on every side.+pointsBox :: Float -> PrimArray Float -> Maybe Rect+pointsBox pad pts+  | x0 > x1 = Nothing+  | otherwise = Just (Rect (x0 - pad) (y0 - pad) (x1 - x0 + 2 * pad) (y1 - y0 + 2 * pad))+ where+  (x0, y0, x1, y1) = ringBox pts++--------------------------------------------------------------------------------+-- Text from the raster spans+--------------------------------------------------------------------------------++-- | Packed font-style codes for 'NodeText' spans, keyed by their exact+-- rects, and for text fields, buttons and selects, whose spans lie inside+-- them ('nodeFontBits').+collectSpanStyles :: Context -> IO (M.Map RectKey Word64, [(Rect, Word64)])+collectSpanStyles ctx = do+  sc <- readIORef (ctxSpanCache ctx)+  let+    textStyles =+      M.fromList+        [ (rectKey r, sceStyle e)+        | e <- IM.elems sc+        , sceStyle e /= 0+        , (r, _, _, _) <- sceSpans e+        ]+    na = ctxNodeArena ctx+  n <- arenaCount na+  inputStyles <-+    forM [0 .. n - 1] $ \i -> do+      nt <- getNodeType na i+      if nt == NodeTextInput || hasCenteredLabel nt+        then do+          si <- nodeFontBits nt <$> getStyleIdx na i+          if si /= 0+            then Just . (,si) <$> getNodeRect na i+            else pure Nothing+        else pure Nothing+  pure (textStyles, [st | Just st <- inputStyles])+++-- | Collect active Tier 2 'seeSvgOpacity' containers as @(bounds, opacity)@+-- pairs so text spans inside @withShader groupOpacity@ fade with their group.+collectSvgOpacityZones :: Context -> IO [(Rect, Float)]+collectSvgOpacityZones ctx = do+  effNodes <- activeEffectNodes ctx+  if null effNodes+    then pure []+    else do+      let na = ctxNodeArena ctx+      zones <-+        forM effNodes $ \idx -> do+          mEntry <- lookupShaderEffectAt ctx idx+          case mEntry >>= seeSvgOpacity of+            Just op | op < 0.9999 -> Just . (,max 0 (min 1 op)) <$> getNodeRect na idx+            _ -> pure Nothing+      pure [z | Just z <- zones]++-- | Every span as clipped group and fitted text. Spans whose line box is+-- not fully inside their clip share one @clipPath@ per clip.+spanTexts ::+  Int -> Text -> FontMetrics -> Float -> (M.Map RectKey Word64, [(Rect, Word64)]) -> [(Rect, Float)] -> TB.Builder -> Int -> [(Rect, Text, Color, Color, Rect)] -> (TB.Builder, TB.Builder, Int)+spanTexts p fontFam fm ratio (textStyles, inputStyles) opacityZones clipPrefix startId spans = (defs, body, nextId)+ where+  baseLineH = fmLineHeight fm+  spaceAdv = fmAdvance fm ' '+  lookupStyle r0 = case M.lookup (rectKey r0) textStyles of+    Just si -> si+    Nothing -> maybe 0 snd (find (fullyInside r0 . fst) inputStyles)+  opacityFor (Rect x y w h) =+    let cx = x + w / 2+        cy = y + h / 2+        inZone (Rect zx zy zw zh) = cx >= zx && cx <= zx + zw && cy >= zy && cy <= zy + zh+     in foldl' (\acc (zr, op) -> if inZone zr then acc * op else acc) 1 opacityZones+  fontAttrs si =+    attr "font-family" (TB.fromText fam)+      <> fontStyleAttrs (textNodeFontWeight si) (textNodeFontStyle si) (textNodeTextDecoration si)+   where+    fam = case textNodeFontVariant si of+      FontMono -> "'Cascadia Mono', 'JetBrains Mono', monospace"+      _ -> fontFam+  trimSpan (Rect x y w h) t0 =+    let+      lead = T.length (T.takeWhile (== ' ') t0)+      trail = T.length (T.takeWhileEnd (== ' ') t0)+      t = T.strip t0+      spW = if baseLineH > 0 then spaceAdv * (h / baseLineH) else spaceAdv+      x' = x + fromIntegral lead * spW+      w' = max 1 (w - fromIntegral (lead + trail) * spW)+    in+      (Rect x' y w' h, t)+  kept =+    [ (r', t', fg, c, lookupStyle r, opacityFor r)+    | (r, t, fg, _, c) <- spans+    , let (r', t') = trimSpan r t+    , not (T.null t')+    , rectW r > 0.5+    , rectH r > 0.5+    , rectIntersect r c /= Nothing+    ]+  (defs, wrapClip, nextId) = clipDefs p clipPrefix startId [c | (r, _, _, c, _, _) <- kept, not (fullyInside r c)]+  body = mconcat (map el kept)+  el (r@(Rect x y w h), t, fg, c, si, op)+    | fullyInside r c = textEl+    | otherwise = wrapClip c textEl+   where+    textEl =+      "<text"+        <> numAttr p "x" x+        <> numAttr p "y" (y + h / 2)+        <> attr "dominant-baseline" "central"+        <> numAttr p "font-size" (h * ratio)+        <> fontAttrs si+        <> attr "xml:space" "preserve"+        <> fillAttrs p fg+        <> (if op < 0.9999 then attr "opacity" (fmtNum p op) else mempty)+        <> numAttr p "textLength" (max 1 w)+        <> attr "lengthAdjust" "spacing"+        <> ">"+        <> escapeXml t+        <> "</text>"++--------------------------------------------------------------------------------+-- SVG fragments+--------------------------------------------------------------------------------++-- | A rect's fields, as an ordered key.+type RectKey = (Float, Float, Float, Float)++rectKey :: Rect -> RectKey+rectKey (Rect x y w h) = (x, y, w, h)++-- | One @clipPath@ per distinct clip, numbered from @startId@ under @prefix@+-- in order of first use; a wrapper putting a fragment in its clip's group;+-- and the next free number.+clipDefs :: Int -> TB.Builder -> Int -> [Rect] -> (TB.Builder, Rect -> TB.Builder -> TB.Builder, Int)+clipDefs p prefix startId clips = (defs, wrap, startId + M.size ids)+ where+  (ids, ordered) = foldl' assign (M.empty, []) clips+  assign acc@(m, os) c+    | M.member (rectKey c) m = acc+    | otherwise = let i = startId + M.size m in (M.insert (rectKey c) i m, (c, i) : os)+  clipRef i = prefix <> TB.fromString (show i)+  defs =+    mconcat+      [ "<clipPath id=\"" <> clipRef i <> "\"><rect"+          <> numAttr p "x" (rectX c)+          <> numAttr p "y" (rectY c)+          <> numAttr p "width" (rectW c)+          <> numAttr p "height" (rectH c)+          <> "/></clipPath>"+      | (c, i) <- reverse ordered+      ]+  wrap c b =+    "<g clip-path=\"url(#" <> clipRef (M.findWithDefault 0 (rectKey c) ids) <> ")\">" <> b <> "</g>"++-- | A filled rect, or nothing for a transparent or empty one.+solidRect :: Int -> Rect -> Color -> TB.Builder+solidRect p r@(Rect _ _ w h) col+  | colorA col == 0 || w <= 0.01 || h <= 0.01 = mempty+  | otherwise = rectEl p r col++fullyInside :: Rect -> Rect -> Bool+fullyInside (Rect x y w h) (Rect sx sy sw sh) =+  x >= sx && y >= sy && x + w <= sx + sw && y + h <= sy + sh
+ lib/NanoUI/Draw/Svg.hs view
@@ -0,0 +1,697 @@+{-# LANGUAGE StrictData #-}++-- |+-- Module      : NanoUI.Draw.Svg+-- Description : Render nano-ui DrawOp arrays to SVG+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- Render 'DrawOp' arrays to SVG. Build the ops with a canvas+-- ("NanoUI.Widgets.Custom"), a 'NanoUI.Widgets.Custom.drawing', or a diagrams-lib backend+-- ("NanoUI.Diagrams.Backend"), then export them as vector graphics:+--+-- > let ops = runCanvasFor cdc $ do+-- >       drawRoundedRect r 8 (colorRGBA 37 99 235 255)+-- >       drawText (V2 20 20) AlignCenter AlignMiddle "Ready" colorWhite+-- > TIO.writeFile "badge.svg" (drawOpsToSvg r ops)+--+-- 'renderDrawOpsSvg' takes a 'SvgConfig': @svgStandalone = False@ emits an+-- inner @\<g\>@ fragment for embedding in a larger document, 'svgPrecision'+-- bounds coordinate digits, and 'svgImageUri' resolves 'DrawOp' image ids to+-- @href@ URIs (images without a resolution are omitted).+--+-- Ops draw in array order, as paint does. Degenerate geometry (zero sizes,+-- non-finite coordinates, fully transparent colours) draws nothing.+module NanoUI.Draw.Svg+  ( SvgConfig (..)+  , defaultSvgConfig+  , renderDrawOpsSvg+  , drawOpsToSvg+  )+where++import Data.Bits (shiftL, (.|.))+import Data.List (intersperse, sortOn)+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, sizeofPrimArray)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Word (Word32)+import NanoUI+  ( Color (..)+  , FontVariant (..)+  , Rect (..)+  , TextFont (..)+  , colorA+  , colorB+  , colorG+  , colorR+  , colorToHex+  , lerpColor+  )+import NanoUI.Widgets.Custom (DrawOp (..))+import NanoUI.Draw.Svg.Attr+  ( attr+  , escapeXml+  , fillAttrs+  , finite+  , fmtNum+  , fmtPt+  , fontStyleAttrs+  , lineEl+  , numAttr+  , opacityAttr+  , polygonEl+  , rectEl+  , roundedRectEl+  , roundedStrokeEl+  , strokeAttrs+  )+import NanoUI.Internal.Path+  ( LineCap (..)+  , LineJoin (..)+  , Shade (..)+  )++-- | Options for 'renderDrawOpsSvg'.+data SvgConfig = SvgConfig+  { svgStandalone :: !Bool+  -- ^ Wrap the output in an outer @\<svg\>@ element with @viewBox@ and+  -- namespace when 'True', or emit an inner @\<g\>@ fragment when 'False'.+  , svgPrecision :: !Int+  -- ^ Maximum decimal places for coordinates and lengths (clamped to @0..6@).+  -- Trailing fractional zeros are omitted.+  , svgImageUri :: !(Int -> Maybe Text)+  -- ^ Resolve an image or texture id to an @href@ or data URI for 'DrawImage'.+  -- When it returns 'Nothing', the image op is omitted.+  , svgIdPrefix :: !Text+  -- ^ Prepended to every @clip_N@ and @grad_N@ id, so several renders placed+  -- in one document, or one page, keep their ids apart.+  }++-- | Standalone SVG with 2 decimal places, no image resolver, and no id+-- prefix.+defaultSvgConfig :: SvgConfig+defaultSvgConfig =+  SvgConfig+    { svgStandalone = True+    , svgPrecision = 2+    , svgImageUri = const Nothing+    , svgIdPrefix = T.empty+    }++-- | Render draw ops over the given viewport rectangle as an SVG document+-- with 'defaultSvgConfig'.+drawOpsToSvg :: Rect -> SmallArray DrawOp -> Text+drawOpsToSvg = renderDrawOpsSvg defaultSvgConfig++-- | Render draw ops into an SVG document or @\<g\>@ fragment.+renderDrawOpsSvg :: SvgConfig -> Rect -> SmallArray DrawOp -> Text+renderDrawOpsSvg cfg (Rect vx0 vy0 vw0 vh0) ops =+  TL.toStrict . TB.toLazyText $+    if svgStandalone cfg+      then+        "<svg xmlns=\"http://www.w3.org/2000/svg\""+          <> numAttr p "width" vw+          <> numAttr p "height" vh+          <> attr+            "viewBox"+            (fmtNum p vx <> " " <> fmtNum p vy <> " " <> fmtNum p vw <> " " <> fmtNum p vh)+          <> ">"+          <> defsBlock+          <> body+          <> "</svg>"+      else "<g>" <> defsBlock <> body <> "</g>"+ where+  !p = max 0 (min 6 (svgPrecision cfg))+  !pfx = TB.fromText (svgIdPrefix cfg)+  !vx = if finite vx0 then vx0 else 0+  !vy = if finite vy0 then vy0 else 0+  !vw = if finite vw0 && vw0 > 0 then vw0 else 0+  !vh = if finite vh0 && vh0 > 0 then vh0 else 0+  !n = sizeofSmallArray ops+  !(defs, body) = walk 0 0 0 0 mempty mempty+  defsBlock+    | defsEmpty = mempty+    | otherwise = "<defs>" <> defs <> "</defs>"+  defsEmpty = TL.null (TB.toLazyText defs)+  closeClips k = mconcat (replicate k "</g>")++  walk ::+    Int -> Int -> Int -> Int -> TB.Builder -> TB.Builder -> (TB.Builder, TB.Builder)+  walk !i !clips !nextClip !nextGrad !dAcc !bAcc+    | i >= n = (dAcc, bAcc <> closeClips clips)+    | otherwise =+        case indexSmallArray ops i of+          PushClip (Rect x y w h) ->+            let+              !cid = nextClip + 1+              !cidStr = pfx <> "clip_" <> TB.fromString (show cid)+              !(cx, cy, cw, ch)+                | all finite [x, y, w, h] && w > 0 && h > 0 = (x, y, w, h)+                | otherwise = (0, 0, 0, 0)+              clipDef =+                "<clipPath id=\""+                  <> cidStr+                  <> "\"><rect"+                  <> numAttr p "x" cx+                  <> numAttr p "y" cy+                  <> numAttr p "width" cw+                  <> numAttr p "height" ch+                  <> "/></clipPath>"+              clipOpen = "<g clip-path=\"url(#" <> cidStr <> ")\">"+             in+              walk (i + 1) (clips + 1) cid nextGrad (dAcc <> clipDef) (bAcc <> clipOpen)+          PopClip+            | clips > 0 -> walk (i + 1) (clips - 1) nextClip nextGrad dAcc (bAcc <> "</g>")+            | otherwise -> walk (i + 1) 0 nextClip nextGrad dAcc bAcc+          FillQuadGradient r@(Rect x y w h) tl tr br bl+            | not (w > 0 && h > 0 && all finite [x, y, w, h]) ->+                walk (i + 1) clips nextClip nextGrad dAcc bAcc+            | all (\c -> colorA c == 0) [tl, tr, br, bl] ->+                walk (i + 1) clips nextClip nextGrad dAcc bAcc+            | tl == tr && tr == br && br == bl ->+                walk (i + 1) clips nextClip nextGrad dAcc (bAcc <> emitOp p cfg (FillRect r tl))+            | otherwise ->+                let+                  !gid = nextGrad + 1+                  !gidStr = gradId gid+                  !(coords, stops)+                    | tl == bl && tr == br =+                        ( attr "x1" "0%" <> attr "y1" "0%" <> attr "x2" "100%" <> attr "y2" "0%"+                        , stopElem p "0%" tl <> stopElem p "100%" tr+                        )+                    | tl == tr && bl == br =+                        ( attr "x1" "0%" <> attr "y1" "0%" <> attr "x2" "0%" <> attr "y2" "100%"+                        , stopElem p "0%" tl <> stopElem p "100%" bl+                        )+                    | otherwise =+                        ( attr "x1" "0%" <> attr "y1" "0%" <> attr "x2" "100%" <> attr "y2" "100%"+                        , stopElem p "0%" tl+                            <> stopElem p "50%" (lerpColor tr bl 0.5)+                            <> stopElem p "100%" br+                        )+                  gradRect =+                    "<rect"+                      <> numAttr p "x" x+                      <> numAttr p "y" y+                      <> numAttr p "width" w+                      <> numAttr p "height" h+                      <> gradFill gidStr+                      <> "/>"+                 in+                  walk (i + 1) clips nextClip gid (dAcc <> gradientDef gidStr coords stops) (bAcc <> gradRect)+          -- A canvas 'Linear' fill is one gradient cut into triangles at its+          -- stops; draw it as one, so the seams between triangles never show.+          FillPolygon pts rings tris (Shaded cs)+            | Just d <- ringsPathData p pts rings+            , Just ((x1, y1), (x2, y2), stops) <- linearShade pts tris cs ->+                let+                  !gid = nextGrad + 1+                  !gidStr = gradId gid+                  gradDef =+                    gradientDef+                      gidStr+                      ( attr "gradientUnits" "userSpaceOnUse"+                          <> numAttr p "x1" x1+                          <> numAttr p "y1" y1+                          <> numAttr p "x2" x2+                          <> numAttr p "y2" y2+                      )+                      (foldMap (\(t, col) -> stopElem p (fmtNum p (t * 100) <> "%") col) stops)+                  el =+                    "<path"+                      <> attr "d" d+                      <> attr "fill-rule" "evenodd"+                      <> gradFill gidStr+                      <> "/>"+                 in+                  walk (i + 1) clips nextClip gid (dAcc <> gradDef) (bAcc <> el)+          op -> walk (i + 1) clips nextClip nextGrad dAcc (bAcc <> emitOp p cfg op)++  gradId g = pfx <> "grad_" <> TB.fromString (show g)+  gradFill gidStr = attr "fill" ("url(#" <> gidStr <> ")")+  gradientDef gidStr attrs stops =+    "<linearGradient id=\"" <> gidStr <> "\"" <> attrs <> ">" <> stops <> "</linearGradient>"++emitOp :: Int -> SvgConfig -> DrawOp -> TB.Builder+emitOp p cfg = \case+  FillRect r@(Rect x y w h) col+    | w > 0 && h > 0 && colorA col > 0 && all finite [x, y, w, h] -> rectEl p r col+    | otherwise -> mempty+  FillRoundedRect rect@(Rect x y w h) r col+    | w > 0 && h > 0 && colorA col > 0 && all finite [x, y, w, h, r] -> roundedRectEl p rect r col+    | otherwise -> mempty+  FillTriangle x0 y0 x1 y1 x2 y2 col+    | colorA col > 0+    , all finite [x0, y0, x1, y1, x2, y2]+    , abs ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) > 0 ->+        polygonEl p [(x0, y0), (x1, y1), (x2, y2)] col+    | otherwise -> mempty+  FillCircle cx cy r col+    | r > 0 && colorA col > 0 && all finite [cx, cy, r] ->+        "<circle"+          <> numAttr p "cx" cx+          <> numAttr p "cy" cy+          <> numAttr p "r" r+          <> fillAttrs p col+          <> "/>"+    | otherwise -> mempty+  Stroke x0 y0 x1 y1 bw col -> emitLine p x0 y0 x1 y1 bw col+  StrokeLineAA x0 y0 x1 y1 bw col -> emitLine p x0 y0 x1 y1 bw col+  StrokeRoundedRect rect@(Rect x y w h) r bw col+    | w > 0 && h > 0 && bw > 0 && colorA col > 0 && all finite [x, y, w, h, r, bw] ->+        roundedStrokeEl p rect r bw col+    | otherwise -> mempty+  StrokeCircle cx cy r bw col+    -- As 'StrokeRoundedRect': the border never exceeds the radius, so the+    -- stroked circle is always at least half of it wide.+    | r > 0 && bw > 0 && colorA col > 0 && all finite [cx, cy, r, bw] ->+        let+          !ibw = min bw r+          !ir = r - ibw * 0.5+         in+          "<circle"+            <> numAttr p "cx" cx+            <> numAttr p "cy" cy+            <> numAttr p "r" ir+            <> strokeAttrs p col ibw+            <> attr "fill" "none"+            <> "/>"+    | otherwise -> mempty+  FillPolygon pts rings tris shade -> emitPolygon p pts rings tris shade+  StrokePolyline pts w closed cap join limit shade ->+    emitPolyline p pts w closed cap join limit shade+  DrawImage (Rect x y w h) angle tex _u0 _v0 _u1 _v1 col+    | w > 0 && h > 0 && colorA col > 0 && all finite [x, y, w, h] ->+        case svgImageUri cfg tex of+          Nothing -> mempty+          Just uri ->+            let+              rotAttr+                | finite angle && angle /= 0 =+                    let+                      !deg = angle * 180 / pi+                      !cx = x + w * 0.5+                      !cy = y + h * 0.5+                     in+                      attr+                        "transform"+                        ("rotate(" <> fmtNum p deg <> " " <> fmtNum p cx <> " " <> fmtNum p cy <> ")")+                | otherwise = mempty+             in+              "<image"+                <> numAttr p "x" x+                <> numAttr p "y" y+                <> numAttr p "width" w+                <> numAttr p "height" h+                <> attr "preserveAspectRatio" "none"+                <> attr "href" (escapeXml uri)+                <> opacityAttr p "opacity" (colorA col)+                <> rotAttr+                <> "/>"+    | otherwise -> mempty+  DrawText x y ax ay txt col -> emitText p x y ax ay 1 Nothing txt col+  DrawTextStyled x y font txt col -> emitText p x y 0 1 1 (Just font) txt col+  DrawTextAligned x y ax ay scale font txt col ->+    emitText p x y ax ay scale (Just font) txt col+  FillQuadGradient {} -> mempty+  PushClip {} -> mempty+  PopClip -> mempty++emitLine ::+  Int -> Float -> Float -> Float -> Float -> Float -> Color -> TB.Builder+emitLine p x0 y0 x1 y1 bw col+  | bw > 0+  , colorA col > 0+  , all finite [x0, y0, x1, y1, bw]+  , let dx = x1 - x0; dy = y1 - y0 in dx * dx + dy * dy >= 1.0e-6 =+      lineEl p x0 y0 x1 y1 bw col+  | otherwise = mempty++emitPolygon ::+  Int+  -> PrimArray Float+  -> PrimArray Int+  -> PrimArray Int+  -> Shade+  -> TB.Builder+emitPolygon p pts rings tris shade =+  case uniformShade n shade of+    Just col+      | colorA col > 0+      , Just d <- ringsPathData p pts rings ->+          "<path"+            <> attr "d" d+            <> attr "fill-rule" "evenodd"+            <> fillAttrs p col+            <> "/>"+      | otherwise -> mempty+    Nothing ->+      case shade of+        Shaded cs+          | shadedValid pts tris cs ->+              foldMap+                ( \k ->+                    let+                      !i0 = indexPrimArray tris k+                      !i1 = indexPrimArray tris (k + 1)+                      !i2 = indexPrimArray tris (k + 2)+                      !col =+                        averageColor3+                          (Color (indexPrimArray cs i0))+                          (Color (indexPrimArray cs i1))+                          (Color (indexPrimArray cs i2))+                     in+                      if colorA col == 0+                        then mempty+                        else+                          polygonEl p [pt i0, pt i1, pt i2] col+                )+                [0, 3 .. nt - 3]+        _ -> mempty+ where+  !n = sizeofPrimArray pts `div` 2+  !nt = sizeofPrimArray tris - sizeofPrimArray tris `mod` 3+  pt i = (indexPrimArray pts (2 * i), indexPrimArray pts (2 * i + 1))++-- | Whether a 'Shaded' polygon is well formed: a whole triangle, finite+-- points, a colour for each, and triangles that name only those points.+shadedValid :: PrimArray Float -> PrimArray Int -> PrimArray Word32 -> Bool+shadedValid pts tris cs =+  sizeofPrimArray tris >= 3 && sizeofPrimArray cs >= n && pointsFinite n pts && trianglesValid n tris+ where+  !n = sizeofPrimArray pts `div` 2++-- | Whether the first @m@ points are finite.+pointsFinite :: Int -> PrimArray Float -> Bool+pointsFinite m pts = and [finite (indexPrimArray pts k) | k <- [0 .. 2 * m - 1]]++-- | Whether every index of every whole triangle names one of @n@ points.+trianglesValid :: Int -> PrimArray Int -> Bool+trianglesValid n tris =+  and [t >= 0 && t < n | k <- [0 .. nt - 1], let t = indexPrimArray tris k]+ where+  !nt = sizeofPrimArray tris - sizeofPrimArray tris `mod` 3++-- | The rings of a 'FillPolygon' as path data, outline first, or 'Nothing' when+-- the rings or their points are malformed.+ringsPathData :: Int -> PrimArray Float -> PrimArray Int -> Maybe TB.Builder+ringsPathData p pts rings+  | ringsValid && pointsFinite nOut pts =+      Just (joinNonEmpty " " [ringPath r | r <- [0 .. nr - 1]])+  | otherwise = Nothing+ where+  !n = sizeofPrimArray pts `div` 2+  !nr = sizeofPrimArray rings - 1+  ringAt r = indexPrimArray rings r+  !nOut = if nr >= 1 then ringAt nr else 0+  ringsValid =+    n >= 3+      && nr >= 1+      && ringAt 0 == 0+      && nOut <= n+      && and [ringAt r + 3 <= ringAt (r + 1) | r <- [0 .. nr - 1]]+  ptAt i = fmtPt p (indexPrimArray pts (2 * i)) (indexPrimArray pts (2 * i + 1))+  ringPath r =+    let+      !from = ringAt r+      !to = ringAt (r + 1)+     in+      if to - from < 3+        then mempty+        else+          "M"+            <> ptAt from+            <> foldMap (\i -> " L" <> ptAt i) [from + 1 .. to - 1]+            <> " Z"++-- | The single linear gradient a shaded polygon's colours follow, as its+-- start and end points and its stops (offset in @0..1@, colour). A canvas+-- 'NanoUI.Path.Linear' fill has one: its triangles are split at the+-- gradient's stops, so each is coloured along the gradient's axis alone.+-- A four-corner gradient has none, and gives 'Nothing'.+--+-- The axis is the dominant direction of the triangles' colour gradients,+-- weighted by squared area: 8-bit colours pin a large triangle's gradient+-- down, and a sliver's hardly at all. Along the axis, each triangle's+-- middle corner must then take the blend of the other two, within two+-- colour levels. The stops are the vertices' colours in order along the+-- axis, less those a straight blend of their neighbours already gives.+linearShade ::+  PrimArray Float -> PrimArray Int -> PrimArray Word32 -> Maybe ((Float, Float), (Float, Float), [(Float, Color)])+linearShade pts tris cs+  | n < 3 || not (shadedValid pts tris cs) = Nothing+  | sxx + syy <= 1.0e-12 || span' < 1.0e-3 = Nothing+  | not (all followsAxis triangles) || not (sameWhereLevel samples) = Nothing+  | otherwise =+      Just+        ( (ux * tMin, uy * tMin)+        , (ux * tMax, uy * tMax)+        , [((t - tMin) / span', col) | (t, col) <- simplify samples]+        )+ where+  !n = sizeofPrimArray pts `div` 2+  !nt = sizeofPrimArray tris - sizeofPrimArray tris `mod` 3+  px i = indexPrimArray pts (2 * i)+  py i = indexPrimArray pts (2 * i + 1)+  colourAt i = Color (indexPrimArray cs i)+  channels :: Color -> [Float]+  channels c = map fromIntegral [colorR c, colorG c, colorB c, colorA c]+  triangles =+    [ (i0, i1, i2)+    | k <- [0, 3 .. nt - 3]+    , let+        i0 = indexPrimArray tris k+        i1 = indexPrimArray tris (k + 1)+        i2 = indexPrimArray tris (k + 2)+    ]+  -- Per channel, the colour gradient across one triangle and its squared+  -- doubled area. Colour is affine across a triangle, so three corners fix+  -- it.+  triangleGradients (i0, i1, i2)+    | abs det <= 1.0e-6 = []+    | otherwise =+        [ ((dc1 * dy2 - dc2 * dy1) / det, (dx1 * dc2 - dx2 * dc1) / det, det * det)+        | (c0, c1, c2) <- zip3 (channels (colourAt i0)) (channels (colourAt i1)) (channels (colourAt i2))+        , let+            dc1 = c1 - c0+            dc2 = c2 - c0+        ]+   where+    dx1 = px i1 - px i0+    dy1 = py i1 - py i0+    dx2 = px i2 - px i0+    dy2 = py i2 - py i0+    det = dx1 * dy2 - dx2 * dy1+  gradients = concatMap triangleGradients triangles+  (sxx, sxy, syy) =+    foldl'+      (\(!a, !b, !c) (gx, gy, w) -> (a + w * gx * gx, b + w * gx * gy, c + w * gy * gy))+      (0, 0, 0)+      gradients+  angle = 0.5 * atan2 (2 * sxy) (sxx - syy)+  ux = cos angle+  uy = sin angle+  along i = ux * px i + uy * py i+  followsAxis (i0, i1, i2) = case sortOn fst [(along i, colourAt i) | i <- [i0, i1, i2]] of+    [(t0, c0), (t1, c1), (t2, c2)]+      | t2 - t0 < 1.0e-4 -> closeColour 2 c0 c1 && closeColour 2 c0 c2+      | otherwise -> closeColour 2 c1 (lerpColor c0 c2 ((t1 - t0) / (t2 - t0)))+    _ -> False+  samples = sortOn fst [(along i, colourAt i) | i <- [0 .. n - 1]]+  tMin = minimum (map fst samples)+  tMax = maximum (map fst samples)+  span' = tMax - tMin+  -- Vertices at the same place along the axis share a colour.+  sameWhereLevel ss =+    and [closeColour 3 a b | ((ta, a), (tb, b)) <- zip ss (drop 1 ss), tb - ta < 0.05]+  closeColour tol a b = and (zipWith (\x y -> abs (x - y) <= tol) (channels a) (channels b))+  -- Keep a sample only where a straight blend from the last kept one to a+  -- later one would miss a colour in between by over a level.+  simplify = \case+    s0 : s1 : rest -> s0 : thin s0 [] s1 rest+    ss -> ss+  thin _ _ s [] = [s]+  thin kept mids s (next : more)+    | fits kept (s : mids) next = thin kept (s : mids) next more+    | otherwise = s : thin s [] next more+  fits (t0, c0) mids (t1, c1) =+    t1 - t0 > 1.0e-4+      && all (\(t, c) -> closeColour 1 c (lerpColor c0 c1 ((t - t0) / (t1 - t0)))) mids++emitPolyline ::+  Int+  -> PrimArray Float+  -> Float+  -> Bool+  -> LineCap+  -> LineJoin+  -> Float+  -> Shade+  -> TB.Builder+emitPolyline p pts w closed cap join limit shade+  | n < 2 || not (w > 0) || not (finite w && finite limit) || not (pointsFinite n pts) =+      mempty+  | otherwise =+      case uniformShade n shade of+        Just col+          | colorA col > 0 ->+              let+                indices = [0 .. n - 1] ++ [0 | closed]+                pointsStr =+                  joinNonEmpty " " [ptAt i | i <- indices]+               in+                "<polyline"+                  <> attr "points" pointsStr+                  <> styleAttrs col+                  <> "/>"+          | otherwise -> mempty+        Nothing ->+          case shade of+            Shaded cs+              | sizeofPrimArray cs >= n ->+                  let+                    pairs = zip [0 .. n - 1] ([1 .. n - 1] ++ [0 | closed])+                   in+                    foldMap+                      ( \(i, j) ->+                          let+                            !col =+                              lerpColor+                                (Color (indexPrimArray cs i))+                                (Color (indexPrimArray cs j))+                                0.5+                           in+                            if colorA col == 0+                              then mempty+                              else+                                "<line"+                                  <> numAttr p "x1" (px i)+                                  <> numAttr p "y1" (py i)+                                  <> numAttr p "x2" (px j)+                                  <> numAttr p "y2" (py j)+                                  <> styleAttrs col+                                  <> "/>"+                      )+                      pairs+            _ -> mempty+ where+  !n = sizeofPrimArray pts `div` 2+  px i = indexPrimArray pts (2 * i)+  py i = indexPrimArray pts (2 * i + 1)+  ptAt i = fmtPt p (px i) (py i)+  capStr = case cap of+    ButtCap -> "butt"+    SquareCap -> "square"+    RoundCap -> "round"+  joinStr = case join of+    MiterJoin -> "miter"+    RoundJoin -> "round"+    BevelJoin -> "bevel"+  styleAttrs col =+    attr "fill" "none"+      <> strokeAttrs p col w+      <> attr "stroke-linecap" capStr+      <> attr "stroke-linejoin" joinStr+      <> numAttr p "stroke-miterlimit" limit++emitText ::+  Int+  -> Float+  -> Float+  -> Float+  -> Float+  -> Float+  -> Maybe TextFont+  -> Text+  -> Color+  -> TB.Builder+emitText p x y ax ay scale mFont txt col+  | T.null txt+      || colorA col == 0+      || not (all finite [x, y, ax, ay, scale] && scale > 0) =+      mempty+  | otherwise =+      "<text"+        <> numAttr p "x" x+        <> numAttr p "y" y+        <> attr "text-anchor" anchor+        <> attr "dominant-baseline" baseline+        <> fontAttrs+        <> fillAttrs p col+        <> ">"+        <> escapeXml txt+        <> "</text>"+ where+  -- The nearest of the three anchors SVG names: fractions below 0.25 and+  -- above 0.75 snap to the outer ones, covering the values 'drawText' and+  -- its alignment helpers produce (0, 0.5, 1, and the baseline's -1).+  anchor+    | ax < 0.25 = "start"+    | ax <= 0.75 = "middle"+    | otherwise = "end"+  baseline+    | ay < 0.25 = "alphabetic"+    | ay <= 0.75 = "central"+    | otherwise = "hanging"+  fontAttrs = case mFont of+    Nothing -> mempty+    Just font ->+      let+        baseSz = textFontSize font+        sz+          | baseSz > 0 = baseSz * scale+          | baseSz < 0 = 16 * negate baseSz * scale+          | scale /= 1 = 16 * scale+          | otherwise = 0+        sizeAttr = if sz > 0 then numAttr p "font-size" sz else mempty+        familyAttr = case textFontVariant font of+          FontMono -> attr "font-family" "monospace"+          _ -> mempty+       in+        sizeAttr+          <> familyAttr+          <> fontStyleAttrs (textFontWeight font) (textFontStyle font) (textFontDecoration font)++-- | Extract a single color when the shade is flat or all vertex colors match.+uniformShade :: Int -> Shade -> Maybe Color+uniformShade n = \case+  Flat c -> Just c+  Shaded cs+    | n > 0 && sizeofPrimArray cs >= n ->+        let+          !w0 = indexPrimArray cs 0+         in+          if all (\i -> indexPrimArray cs i == w0) [1 .. n - 1]+            then Just (Color w0)+            else Nothing+    | otherwise -> Nothing++averageColor3 :: Color -> Color -> Color -> Color+averageColor3 a b c =+  let+    avg f =+      (fromIntegral (f a) + fromIntegral (f b) + fromIntegral (f c) + 1) `div` 3 ::+        Word32+   in+    Color+      ( (avg colorR `shiftL` 24)+          .|. (avg colorG `shiftL` 16)+          .|. (avg colorB `shiftL` 8)+          .|. avg colorA+      )++joinNonEmpty :: TB.Builder -> [TB.Builder] -> TB.Builder+joinNonEmpty sep = mconcat . intersperse sep++stopElem :: Int -> TB.Builder -> Color -> TB.Builder+stopElem p offset col =+  "<stop"+    <> attr "offset" offset+    <> attr "stop-color" (TB.fromText (colorToHex col))+    <> opacityAttr p "stop-opacity" (colorA col)+    <> "/>"
+ lib/NanoUI/Draw/Svg/Attr.hs view
@@ -0,0 +1,177 @@+-- | SVG attribute, number and element builders shared by "NanoUI.Draw.Svg"+-- and "NanoUI.Draw.FrameSvg". Each takes the precision @p@ (decimal places)+-- first. The element builders emit unconditionally; callers guard degenerate+-- geometry first.+module NanoUI.Draw.Svg.Attr+  ( attr+  , numAttr+  , fmtNum+  , fmtPt+  , fillAttrs+  , strokeAttrs+  , opacityAttr+  , fontStyleAttrs+  , escapeXml+  , finite+  , rectEl+  , roundedRectEl+  , roundedStrokeEl+  , lineEl+  , polygonEl+  )+where++import Data.List (intersperse)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy.Builder qualified as TB+import Data.Word (Word8)+import NanoUI+  ( Color+  , FontStyle (..)+  , FontWeight (..)+  , Rect (..)+  , TextDecoration (..)+  , colorA+  , colorToHex+  )++attr :: TB.Builder -> TB.Builder -> TB.Builder+attr k v = " " <> k <> "=\"" <> v <> "\""++numAttr :: Int -> TB.Builder -> Float -> TB.Builder+numAttr p k v = attr k (fmtNum p v)++fmtPt :: Int -> Float -> Float -> TB.Builder+fmtPt p x y = fmtNum p x <> "," <> fmtNum p y++fillAttrs :: Int -> Color -> TB.Builder+fillAttrs p col =+  attr "fill" (TB.fromText (colorToHex col))+    <> opacityAttr p "fill-opacity" (colorA col)++strokeAttrs :: Int -> Color -> Float -> TB.Builder+strokeAttrs p col bw =+  attr "stroke" (TB.fromText (colorToHex col))+    <> opacityAttr p "stroke-opacity" (colorA col)+    <> numAttr p "stroke-width" bw++-- | The named opacity attribute unless the colour is opaque. Uses at least+-- three digits: a step of 1/255 is just under 0.004.+opacityAttr :: Int -> TB.Builder -> Word8 -> TB.Builder+opacityAttr p name a+  | a < 255 = numAttr (max 3 p) name (fromIntegral a / 255)+  | otherwise = mempty++-- | The weight, slant and decoration attributes of a font, each omitted at+-- its default.+fontStyleAttrs :: FontWeight -> FontStyle -> TextDecoration -> TB.Builder+fontStyleAttrs weight slant deco = weightAttr <> styleAttr <> decoAttr+ where+  weightAttr = case weight of+    WeightNormal -> mempty+    WeightBold -> attr "font-weight" "bold"+    WeightLight -> attr "font-weight" "300"+    WeightMedium -> attr "font-weight" "500"+    WeightSemiBold -> attr "font-weight" "600"+    WeightExtraBold -> attr "font-weight" "800"+    WeightBlack -> attr "font-weight" "900"+  styleAttr = case slant of+    FontStyleNormal -> mempty+    FontStyleItalic -> attr "font-style" "italic"+    FontStyleOblique -> attr "font-style" "oblique"+  decoAttr = case deco of+    DecorationNone -> mempty+    DecorationUnderline -> attr "text-decoration" "underline"+    DecorationStrikethrough -> attr "text-decoration" "line-through"+    DecorationUnderlineStrike -> attr "text-decoration" "underline line-through"++finite :: Float -> Bool+finite v = not (isNaN v || isInfinite v)++-- | Decimal digits, rounded half up, without trailing zeros or exponents.+fmtNum :: Int -> Float -> TB.Builder+fmtNum p v+  | not (finite v) = "0"+  | n == 0 = "0"+  | frac == 0 = sign <> TB.fromString (show whole)+  | otherwise =+      let+        raw = show frac+        padded = replicate (p - length raw) '0' ++ raw+        trimmed = reverse (dropWhile (== '0') (reverse padded))+       in+        sign <> TB.fromString (show whole) <> "." <> TB.fromString trimmed+ where+  !scale = 10 ^ p :: Integer+  !mag = floor (abs (realToFrac v :: Double) * fromIntegral scale + 0.5) :: Integer+  !n = if v < 0 then negate mag else mag+  !sign = if n < 0 then "-" else mempty+  !(whole, frac) = quotRem mag scale++escapeXml :: Text -> TB.Builder+escapeXml = T.foldl' (\acc c -> acc <> escapeChar c) mempty+ where+  escapeChar = \case+    '&' -> "&amp;"+    '<' -> "&lt;"+    '>' -> "&gt;"+    '"' -> "&quot;"+    '\'' -> "&apos;"+    c -> TB.singleton c++rectEl :: Int -> Rect -> Color -> TB.Builder+rectEl p r col = rectGeom p r <> fillAttrs p col <> "/>"++-- | A filled rectangle with corners of radius @r@, limited to half the+-- shorter side.+roundedRectEl :: Int -> Rect -> Float -> Color -> TB.Builder+roundedRectEl p rect@(Rect _ _ w h) r col =+  let+    !rad = min (max 0 r) (min (w * 0.5) (h * 0.5))+   in+    rectGeom p rect+      <> (if rad > 0 then numAttr p "rx" rad else mempty)+      <> fillAttrs p col+      <> "/>"++-- | A border of width @bw@ inset inside the rectangle, as paint draws it:+-- the stroke is centred on a rectangle half the border in from each side.+roundedStrokeEl :: Int -> Rect -> Float -> Float -> Color -> TB.Builder+roundedStrokeEl p (Rect x y w h) r bw col =+  let+    !ibw = min bw (min (w * 0.5) (h * 0.5))+    !rad = min (max 0 r) (min (w * 0.5) (h * 0.5))+    !rx = max 0 (rad - ibw * 0.5)+   in+    rectGeom p (Rect (x + ibw * 0.5) (y + ibw * 0.5) (max 0 (w - ibw)) (max 0 (h - ibw)))+      <> (if rx > 0 then numAttr p "rx" rx else mempty)+      <> strokeAttrs p col ibw+      <> attr "fill" "none"+      <> "/>"++lineEl :: Int -> Float -> Float -> Float -> Float -> Float -> Color -> TB.Builder+lineEl p x0 y0 x1 y1 bw col =+  "<line"+    <> numAttr p "x1" x0+    <> numAttr p "y1" y0+    <> numAttr p "x2" x1+    <> numAttr p "y2" y1+    <> strokeAttrs p col bw+    <> "/>"++polygonEl :: Int -> [(Float, Float)] -> Color -> TB.Builder+polygonEl p pts col =+  "<polygon"+    <> attr "points" (mconcat (intersperse " " [fmtPt p x y | (x, y) <- pts]))+    <> fillAttrs p col+    <> "/>"++-- | An open @<rect@ tag with its position and size.+rectGeom :: Int -> Rect -> TB.Builder+rectGeom p (Rect x y w h) =+  "<rect"+    <> numAttr p "x" x+    <> numAttr p "y" y+    <> numAttr p "width" w+    <> numAttr p "height" h
+ nano-ui-svg.cabal view
@@ -0,0 +1,123 @@+cabal-version:      3.4+name:               nano-ui-svg+version:            0.2.0.0+synopsis:           SVG export for nano-ui frames and DrawOp arrays+description:+    Renders nano-ui DrawOp sequences (from canvases, custom widgets, paths,+    and diagrams) into standalone SVG documents or <g> fragments with zero+    extra dependencies.+license:            MIT+license-file:       LICENSE+author:             goolord+maintainer:         zacharyachurchill@gmail.com+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:+    CHANGELOG.md+    README.md+data-files:+    assets/glossary.css+    assets/glossary.js+-- The golden documents nano-ui-svg-test compares exported frames with.+extra-source-files:+    test/golden/*.svg++source-repository head+    type:     git+    location: https://github.com/goolord/nano-ui.git+    subdir:   packages/nano-ui-svg++flag glossary+    description: Build the interactive book glossary generator (needs SDL3, diagrams-lib, lucid2, and microaeson).+    manual: True+    default: False++common extensions+    default-language: GHC2024+    default-extensions:+        OverloadedStrings++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++library+    import:           extensions+    import:           warnings+    exposed-modules:+        NanoUI.Draw.Svg+        NanoUI.Draw.FrameSvg+    other-modules:+        NanoUI.Draw.Svg.Attr+    build-depends:+        base >=4.20 && <4.23,+        containers >=0.7 && <0.9,+        nano-ui ^>=0.2,+        primitive ^>=0.9,+        text ^>=2.1+    hs-source-dirs:   lib++test-suite nano-ui-svg-test+    import:           extensions+    import:           warnings+    type:             exitcode-stdio-1.0+    main-is:          Main.hs+    if os(windows)+        ghc-options:  -optl-mconsole+    build-depends:+        base >=4.20 && <4.23,+        bytestring ^>=0.12,+        nano-ui ^>=0.2,+        nano-ui-svg,+        primitive ^>=0.9,+        text ^>=2.1+    hs-source-dirs:   test++executable nano-ui-svg-glossary+    import:           extensions+    import:           warnings+    if !flag(glossary)+        buildable:    False+    main-is:          Glossary.hs+    other-modules:    CanvasExamples+                      ChartExamples+                      Glossary.BookVisuals+                      Glossary.Html+                      Glossary.Render+                      Glossary.Specimens+                      LayoutExamples+                      Paths_nano_ui_svg+    autogen-modules:  Paths_nano_ui_svg+    ghc-options:      -threaded -rtsopts "-with-rtsopts=-N1"+    if os(windows)+        ghc-options:  -optl-mconsole+    build-depends:+        base >=4.20 && <4.23,+        containers >=0.7 && <0.9,+        nano-ui ^>=0.2,+        nano-ui-svg,+        text ^>=2.1+    if flag(glossary)+        build-depends:+            bytestring ^>=0.12,+            diagrams-lib >=1.6 && <1.7,+            directory ^>=1.3,+            lucid2 ^>=0.0.20260427,+            microaeson >=0.1 && <0.2,+            nano-ui-diagrams ^>=0.2,+            nano-ui-sdl ^>=0.2,+            nano-ui-ttf ^>=0.2+    hs-source-dirs:   app
+ test/Main.hs view
@@ -0,0 +1,385 @@+{-# LANGUAGE DataKinds #-}+module Main (main) where++import Control.Exception (IOException, try)+import Control.Monad (forM_, unless, void, when)+import Data.ByteString qualified as BS+import Data.Maybe (isJust)+import Data.Primitive.PrimArray (primArrayFromList)+import Data.Primitive.SmallArray (SmallArray, smallArrayFromList)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import NanoUI+import NanoUI.Backend (colorToWord32, monospaceMetrics)+import NanoUI.Draw.FrameSvg (FrameSvgConfig (..), defaultFrameSvgConfig, enableSvgExport, frameToSvg)+import NanoUI.Draw.Svg+import NanoUI.Internal.Path (Shade (Shaded))+import NanoUI.Internal.Shader (Shader (..), emptyShaderProgram, rawLayerShader)+import NanoUI.Path (LineCap (ButtCap), LineJoin (MiterJoin))+import NanoUI.Path qualified as P+import NanoUI.Testing (newPixelContext)+import NanoUI.Widgets.Custom (DrawOp (..), runCanvasFor)+import NanoUI.Testing.Assert (require, run2Frames, withInput)+import System.Environment (lookupEnv)++-- | Fail on the first needle the document lacks.+contains :: Text -> [Text] -> IO ()+contains doc = mapM_ (\n -> require ("missing " <> show n <> " in " <> show doc) (T.isInfixOf n doc))++main :: IO ()+main = do+  testStandaloneAndPrecision+  testPrimitiveShapes+  testPathsAndShaded+  testGradientsAndClips+  testTextAndImages+  testFrameToSvg+  testGoldens+  putStrLn "nano-ui-svg tests passed."++cdc :: CustomDrawContext+cdc = CustomDrawContext False False False False False defaultTheme (monospaceMetrics 16)++vp :: Rect+vp = Rect 0 0 100 80++-- | A bare @\<g\>@ fragment of the ops.+fragment :: SmallArray DrawOp -> Text+fragment = renderDrawOpsSvg defaultSvgConfig {svgStandalone = False} vp++red, green, blue, halfBlue :: Color+red = colorRGBA 255 0 0 255+green = colorRGBA 0 255 0 255+blue = colorRGBA 0 0 255 255+halfBlue = colorRGBA 0 0 255 128++-- | Standalone documents, precision, and ops that draw nothing.+testStandaloneAndPrecision :: IO ()+testStandaloneAndPrecision = do+  let+    ops = smallArrayFromList [FillRect (Rect 10.256 (-0.0001) 30.5 40) red]+    standalone = drawOpsToSvg vp ops+    atPrecision p = renderDrawOpsSvg defaultSvgConfig {svgStandalone = False, svgPrecision = p} vp ops+    rectAt x w = "<g><rect x=\"" <> x <> "\" y=\"0\" width=\"" <> w <> "\" height=\"40\" fill=\"#ff0000\"/></g>"+  require "standalone header" $+    T.isPrefixOf "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"80\" viewBox=\"0 0 100 80\">" standalone+  require "standalone footer, no empty defs" (T.isSuffixOf "</svg>" standalone && not (T.isInfixOf "<defs>" standalone))+  -- Precision 2 by default, and no negative zero.+  contains standalone ["<rect x=\"10.26\" y=\"0\" width=\"30.5\" height=\"40\" fill=\"#ff0000\"/>"]+  require "precision 1" (atPrecision 1 == rectAt "10.3" "30.5")+  require "precision 0" (atPrecision 0 == rectAt "10" "31")+  let+    nan = 0 / 0+    inf = 1 / 0+    degenerate =+      [ FillRect (Rect 0 0 0 10) red+      , FillRect (Rect nan 0 10 10) red+      , FillRect (Rect 0 0 10 10) colorTransparent+      , FillCircle 10 10 (-2) red+      , FillTriangle 0 0 5 5 10 10 red+      , Stroke 1 1 1 1 2 red+      , Stroke 0 0 10 10 0 red+      , DrawText 0 0 0 0 "" red+      , DrawText inf 0 0 0 "x" red+      ]+  require "degenerate ops emit nothing" (fragment (smallArrayFromList degenerate) == "<g></g>")++testPrimitiveShapes :: IO ()+testPrimitiveShapes =+  contains+    ( drawOpsToSvg vp . smallArrayFromList $+        [ FillRoundedRect (Rect 0 0 20 10) 4 halfBlue+        , FillRoundedRect (Rect 0 0 20 10) 0 red+        , FillCircle 50 40 12 red+        , FillTriangle 0 0 10 0 5 8 green+        , Stroke 1 2 3 4 1.5 red+        , StrokeLineAA 5 6 7 8 2 halfBlue+        , StrokeRoundedRect (Rect 10 20 40 30) 6 4 red+        , StrokeCircle 50 50 20 4 green+        ]+    )+    [ "<rect x=\"0\" y=\"0\" width=\"20\" height=\"10\" rx=\"4\" fill=\"#0000ff\" fill-opacity=\"0.502\"/>"+    , "<rect x=\"0\" y=\"0\" width=\"20\" height=\"10\" fill=\"#ff0000\"/>"+    , "<circle cx=\"50\" cy=\"40\" r=\"12\" fill=\"#ff0000\"/>"+    , "<polygon points=\"0,0 10,0 5,8\" fill=\"#00ff00\"/>"+    , "<line x1=\"1\" y1=\"2\" x2=\"3\" y2=\"4\" stroke=\"#ff0000\" stroke-width=\"1.5\"/>"+    , "<line x1=\"5\" y1=\"6\" x2=\"7\" y2=\"8\" stroke=\"#0000ff\" stroke-opacity=\"0.502\" stroke-width=\"2\"/>"+    , -- Strokes are inset inside their bounds.+      "<rect x=\"12\" y=\"22\" width=\"36\" height=\"26\" rx=\"4\" stroke=\"#ff0000\" stroke-width=\"4\" fill=\"none\"/>"+    , "<circle cx=\"50\" cy=\"50\" r=\"18\" stroke=\"#00ff00\" stroke-width=\"4\" fill=\"none\"/>"+    ]++testPathsAndShaded :: IO ()+testPathsAndShaded = do+  let+    flatSvg = drawOpsToSvg vp . runCanvasFor cdc $ do+      drawPathWith P.EvenOdd (P.rect (Rect 0 0 40 40) <> P.rect (Rect 10 10 20 20)) (P.Solid red)+      drawStrokePathWith+        (P.stroke 3) {P.strokeCap = P.RoundCap, P.strokeJoin = P.BevelJoin, P.strokeMiterLimit = 5}+        (P.polyline [V2 0 0, V2 10 5, V2 20 0])+        (P.Solid green)+      drawStrokePath (P.polygon [V2 0 0, V2 10 0, V2 10 10]) 2 red+  contains+    flatSvg+    [ "<path d=\"M0,0 L40,0 L40,40 L0,40 Z M10,30 L30,30 L30,10 L10,10 Z\" fill-rule=\"evenodd\" fill=\"#ff0000\"/>"+    , "<polyline points=\"0,0 10,5 20,0\" fill=\"none\" stroke=\"#00ff00\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"bevel\" stroke-miterlimit=\"5\"/>"+    , -- A closed polyline repeats its start point.+      "<polyline points=\"0,0 10,0 10,10 0,0\" fill=\"none\" stroke=\"#ff0000\" stroke-width=\"2\" stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-miterlimit=\"4\"/>"+    ]+  let+    gradPaint = P.Linear (V2 0 0) (V2 20 0) [(0, red), (1, green)]+    shadedSvg = drawOpsToSvg vp . runCanvasFor cdc $ do+      drawPathWith P.NonZero (P.rect (Rect 0 0 20 10)) gradPaint+      drawStrokePathWith (P.stroke 2) (P.polyline [V2 0 0, V2 10 0, V2 20 0]) gradPaint+  -- A linear gradient fill is one gradient path; a shaded polyline is segment lines.+  contains+    shadedSvg+    [ "<linearGradient id=\"grad_1\" gradientUnits=\"userSpaceOnUse\" x1=\"0\" y1=\"0\" x2=\"20\" y2=\"0\"><stop offset=\"0%\" stop-color=\"#ff0000\"/><stop offset=\"100%\" stop-color=\"#00ff00\"/></linearGradient>"+    , "fill=\"url(#grad_1)\""+    , "<line x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""+    ]+  require "a gradient fill fell back to triangles" (not (T.isInfixOf "<polygon points=" shadedSvg))+  -- Four different corners follow no single linear gradient, so the+  -- triangles are emitted one by one.+  let+    cornersSvg =+      drawOpsToSvg vp $+        smallArrayFromList+          [ FillPolygon+              (primArrayFromList [0, 0, 20, 0, 20, 20, 0, 20])+              (primArrayFromList [0, 4])+              (primArrayFromList [0, 1, 2, 0, 2, 3])+              (Shaded (primArrayFromList (map colorToWord32 [red, green, blue, colorRGBA 255 255 0 255])))+          ]+  require "four-corner shaded polygon falls back to triangles" $+    T.isInfixOf "<polygon points=" cornersSvg && not (T.isInfixOf "linearGradient" cornersSvg)+  -- A shaded op whose vertex colours all match is one flat shape.+  let+    redW = colorToWord32 red+    uniform = StrokePolyline (primArrayFromList [0, 0, 10, 0, 10, 10]) 2 False ButtCap MiterJoin 4 (Shaded (primArrayFromList [redW, redW, redW]))+  require "uniform shaded polyline collapses to one polyline" $+    fragment (smallArrayFromList [uniform])+      == "<g><polyline points=\"0,0 10,0 10,10\" fill=\"none\" stroke=\"#ff0000\" stroke-width=\"2\" stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-miterlimit=\"4\"/></g>"++testGradientsAndClips :: IO ()+testGradientsAndClips = do+  contains+    ( drawOpsToSvg vp . runCanvasFor cdc $ do+        withClip (Rect 5 5 50 50) $ do+          drawLinearGradientH (Rect 5 5 20 10) red green+          drawLinearGradientV (Rect 5 20 20 10) red halfBlue+          drawQuadGradient (Rect 5 35 20 10) red green halfBlue colorWhite+        drawQuadGradient (Rect 60 5 10 10) red red red red+    )+    [ "<defs>"+    , "<clipPath id=\"clip_1\"><rect x=\"5\" y=\"5\" width=\"50\" height=\"50\"/></clipPath>"+    , "<linearGradient id=\"grad_1\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\"><stop offset=\"0%\" stop-color=\"#ff0000\"/><stop offset=\"100%\" stop-color=\"#00ff00\"/></linearGradient>"+    , "<linearGradient id=\"grad_2\" x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\"><stop offset=\"0%\" stop-color=\"#ff0000\"/><stop offset=\"100%\" stop-color=\"#0000ff\" stop-opacity=\"0.502\"/></linearGradient>"+    , -- A quad gradient is approximated diagonally.+      "<linearGradient id=\"grad_3\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">"+    , "<g clip-path=\"url(#clip_1)\"><rect x=\"5\" y=\"5\" width=\"20\" height=\"10\" fill=\"url(#grad_1)\"/>"+    , -- A uniform quad gradient is a solid rect.+      "<rect x=\"60\" y=\"5\" width=\"10\" height=\"10\" fill=\"#ff0000\"/>"+    ]+  -- An unclosed PushClip and a stray PopClip stay well-formed.+  require "unbalanced clips" $+    fragment (smallArrayFromList [PopClip, PushClip (Rect 0 0 10 10), FillRect (Rect 1 1 2 2) red])+      == "<g><defs><clipPath id=\"clip_1\"><rect x=\"0\" y=\"0\" width=\"10\" height=\"10\"/></clipPath></defs><g clip-path=\"url(#clip_1)\"><rect x=\"1\" y=\"1\" width=\"2\" height=\"2\" fill=\"#ff0000\"/></g></g>"++testTextAndImages :: IO ()+testTextAndImages = do+  let+    styledFont = TextFont 18 FontMono WeightBold FontStyleItalic DecorationUnderline False+    strikeFont =+      defaultTextFont+        { textFontSize = 12+        , textFontWeight = WeightSemiBold+        , textFontStyle = FontStyleOblique+        , textFontDecoration = DecorationUnderlineStrike+        }+  contains+    ( drawOpsToSvg vp . smallArrayFromList $+        [ DrawText 10 20 0.5 (-1) "a < b & \"c\" > 'd'" red+        , DrawTextStyled 5 6 styledFont "mono" green+        , DrawTextAligned 30 40 1 0.5 2 strikeFont "scaled" halfBlue+        ]+    )+    [ "<text x=\"10\" y=\"20\" text-anchor=\"middle\" dominant-baseline=\"alphabetic\" fill=\"#ff0000\">a &lt; b &amp; &quot;c&quot; &gt; &apos;d&apos;</text>"+    , "<text x=\"5\" y=\"6\" text-anchor=\"start\" dominant-baseline=\"hanging\" font-size=\"18\" font-family=\"monospace\" font-weight=\"bold\" font-style=\"italic\" text-decoration=\"underline\" fill=\"#00ff00\">mono</text>"+    , "<text x=\"30\" y=\"40\" text-anchor=\"end\" dominant-baseline=\"central\" font-size=\"24\" font-weight=\"600\" font-style=\"oblique\" text-decoration=\"underline line-through\" fill=\"#0000ff\" fill-opacity=\"0.502\">scaled</text>"+    ]+  let+    images =+      smallArrayFromList+        [ DrawImage (Rect 10 20 30 40) 0 1 0 0 1 1 red+        , DrawImage (Rect 0 0 20 20) (pi / 2) 2 0 0 1 1 halfBlue+        , DrawImage (Rect 0 0 10 10) 0 99 0 0 1 1 red+        ]+    uri = \case+      1 -> Just "https://example.com/a.png?x=1&y=2"+      2 -> Just "data:image/png;base64,AAAA"+      _ -> Nothing+    resolved = renderDrawOpsSvg defaultSvgConfig {svgImageUri = uri} vp images+  require "an image with an unknown id was drawn" (T.count "<image" resolved == 2)+  contains+    resolved+    [ "<image x=\"10\" y=\"20\" width=\"30\" height=\"40\" preserveAspectRatio=\"none\" href=\"https://example.com/a.png?x=1&amp;y=2\"/>"+    , "<image x=\"0\" y=\"0\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"data:image/png;base64,AAAA\" opacity=\"0.502\" transform=\"rotate(90 10 10)\"/>"+    ]++-- | A whole frame of ordinary widgets renders through 'frameToSvg', which+-- 'enableSvgExport' sets up: chrome as rects, a canvas as the shapes it+-- paints, labels as text, and clip ids under a per-document prefix.+testFrameToSvg :: IO ()+testFrameToSvg = do+  let+    inp = withInput 240 200+    circle = canvas (fixedWH 60 60) (\(Rect x y _ _) -> drawCircle (V2 (x + 30) (y + 30)) 12 red)+    ui :: Int -> NanoUI ()+    ui n = column $ do+      label "Frame label"+      labelWith fontBold "Bold label"+      _ <- buttonWith fontBold "Strong"+      _ <- circle+      -- Text longer than its field overhangs the field's clip.+      textInputConfigured+        defaultTextInputConfig {ticLayout = fixedW 80}+        (constVar ("A value far too long for its field " <> T.pack (show n)))+    exportOf ctx cfg view = run2Frames ctx inp view >>= \(_, dd, _) -> frameToSvg cfg ctx inp dd+  bare <- newPixelContext+  (_, bareDraw, _) <- run2Frames bare inp (ui 0)+  refused <- try @IOException (frameToSvg defaultFrameSvgConfig bare inp bareDraw)+  require "frameToSvg refuses a context that records no shapes" (either (const True) (const False) refused)+  ctx <- newPixelContext+  enableSvgExport ctx+  svg1 <- exportOf ctx defaultFrameSvgConfig (ui 0)+  svg2 <- exportOf ctx defaultFrameSvgConfig (ui 10)+  named <- exportOf ctx defaultFrameSvgConfig {fsIdPrefix = "mine-"} (ui 0)+  let+    fill c = "fill=\"" <> colorToHex c <> "\""+    lastId svg = T.takeWhile (/= '"') (snd (T.breakOnEnd "clipPath id=\"" svg))+    textEl t = snd (T.breakOnEnd "<text" (fst (T.breakOn (">" <> t <> "</text>") svg1)))+  require "frame svg header" (T.isPrefixOf "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"240\" height=\"200\"" svg1)+  contains svg1 $+    [fill (pageBackground defaultTheme), "<rect ", "rx=\"12\" fill=\"#ff0000\""]+      <> [">" <> t <> "</text>" | t <- ["Frame label", "Bold label", "Strong"]]+  forM_ ["Bold label", "Strong"] $ \t ->+    require (T.unpack t <> " does not export bold") (T.isInfixOf "font-weight=\"bold\"" (textEl t))+  require "an overflowing field exports a clip id" (T.isInfixOf "clipPath id=" svg1)+  require "no placeholder is left in the document" (not (T.isInfixOf "<id>" svg1))+  require "documents that differ have different ids" (lastId svg1 /= lastId svg2)+  require "ids carry the document prefix" (T.isPrefixOf "n" (lastId svg1) && T.isInfixOf "-tclip_" (lastId svg1))+  require "a set prefix is kept" (T.isPrefixOf "mine-" (lastId named))+  -- A page scoped onto the panel surface exports that surface.+  panelSvg <- exportOf ctx defaultFrameSvgConfig (styled panelPage (ui 0))+  contains panelSvg [fill (styleBg (themePanel defaultTheme))]+  -- A drawing in a modal draws over the modal's panel, in its layer.+  modalSvg <- exportOf ctx defaultFrameSvgConfig (modal (constVar True) "Dialog" (() <$ circle))+  let (_, afterPanel) = T.breakOnEnd (fill (styleBg (themeFloatingWindow defaultTheme))) modalSvg+  require "modal drawing over its panel" (T.isInfixOf "rx=\"12\" fill=\"#ff0000\"" afterPanel)+  -- Widget images export under their id.+  (iid, _, _) <- run2Frames ctx inp $ do+    i <- freshImageId+    _ <- registerImageRgba i 2 2 (BS.replicate 16 255)+    pure i+  imageSvg <- exportOf ctx defaultFrameSvgConfig {fsImageUri = \_ -> Just "data:image/png;base64,AA=="} (image (fixedWH 20 20) iid)+  require "widget image under its id" (T.isInfixOf "<image " imageSvg)+  -- Subtree opacity effects export as a native SVG <g opacity="..."> group,+  -- and text spans inside the subtree carry matching opacity.+  let opacityEffect :: Shader 'LayerEffect Float+      opacityEffect = (rawLayerShader (const (V2 0 0)) emptyShaderProgram) {shaderSvgOpacity = Just id}+  opacitySvg <- exportOf ctx defaultFrameSvgConfig (columnWith tight (withShader opacityEffect 0.5 (box (fixedWH 40 30) red >> label "Faded")))+  contains opacitySvg ["<g opacity=\"0.5\">", "fill=\"#ff0000\"", "</g>", "opacity=\"0.5\"", ">Faded</text>"]++-- | Whole frames of representative views, exported headlessly and compared+-- with the documents committed under @test/golden@. With+-- @NANO_UI_UPDATE_GOLDEN=1@ set, the documents are written instead, for a+-- change that means to alter the export. Line ends are compared as @\n@,+-- whatever a checkout made of them.+testGoldens :: IO ()+testGoldens = do+  update <- isJust <$> lookupEnv "NANO_UI_UPDATE_GOLDEN"+  forM_ goldenViews $ \(name, w, h, ui) -> do+    ctx <- newPixelContext+    enableSvgExport ctx+    -- The pointer is off the window, so nothing shows a hover.+    let inp = (withInput w h) {inputMousePos = V2 (-10) (-10)}+    (_, dd, _) <- run2Frames ctx inp ui+    svg <- frameToSvg defaultFrameSvgConfig ctx inp dd+    let path = "test/golden/" <> name <> ".svg"+        normal = T.replace "\r\n" "\n"+    if update+      then BS.writeFile path (TE.encodeUtf8 (svg <> "\n"))+      else do+        found <- try @IOException (BS.readFile path)+        case found of+          Left _ -> require ("missing golden " <> path <> "; run with NANO_UI_UPDATE_GOLDEN=1 to write it") False+          Right bytes -> do+            let want = T.stripEnd (normal (TE.decodeUtf8 bytes))+                got = normal svg+            unless (want == got) $ do+              let common = length (takeWhile id (zipWith (==) (T.unpack want) (T.unpack got)))+                  around t = T.take 160 (T.drop (max 0 (common - 40)) t)+              putStrLn ("golden " <> path <> " differs at character " <> show common)+              putStrLn ("  want: " <> T.unpack (around want))+              putStrLn ("  got:  " <> T.unpack (around got))+              require ("golden " <> path <> " differs; run with NANO_UI_UPDATE_GOLDEN=1 if the change is meant") False+  when update (putStrLn "golden documents written")++-- | Five views: a form, a table under tabs, a modal over a page, nested+-- layout containers, and a canvas beside a tree and a select.+goldenViews :: [(FilePath, Float, Float, NanoUI ())]+goldenViews =+  [ ( "form"+    , 320+    , 240+    , columnWith (padAll 10 . gap 6) $ do+        labelWith fontBold "Settings"+        textInput (constVar "name")+        checkbox "Enabled" (constVar True)+        slider 0 100 (constVar 40)+        rowWith (gap 6) (void (button "Save") >> void (button "Cancel"))+    )+  , ( "tabs-table"+    , 360+    , 200+    , tabs (constVar (0 :: Int))+        [ tab 0 "People" (table "people" (headed "Name" fst <> headed "City" snd) [("Ada" :: Text, "London" :: Text), ("Lin", "Taipei"), ("Sam", "Lagos")] (constVar (SortCol 0 SortAsc)))+        , tab 1 "Other" (label "other")+        ]+    )+  , ( "modal"+    , 320+    , 240+    , column $ do+        label "Behind the dialog"+        void (button "Behind")+        modal (constVar True) "Confirm" $ do+          label "Delete the file?"+          rowWith (gap 6) (void (button "Delete") >> void (button "Keep"))+    )+  , ( "layout"+    , 320+    , 240+    , columnWith (padAll 8 . gap 6 . fillW) $ do+        rowWith (gap 4 . fillW) $ do+          panelWith (fixedWH 60 40) (label "A")+          spacer (Grow 1) (Fixed 10)+          panelWith (fixedWH 60 40) (label "B")+        separator+        gridWith 3 (gap 4 . fillW) (mapM_ (\i -> label (T.pack ("cell " <> show i))) [1 .. 6 :: Int])+        callout (colorRGBA 40 120 200 255) (label "A note in a callout")+    )+  , ( "canvas"+    , 320+    , 200+    , rowWith (padAll 8 . gap 8) $ do+        _ <- canvas (fixedWH 80 80) $ \(Rect x y w h) -> do+          drawCircle (V2 (x + w / 2) (y + h / 2)) 30 (colorRGBA 220 60 60 255)+          drawRect (Rect (x + 10) (y + 10) 20 20) (colorRGBA 40 160 80 255)+        column $ do+          tree "files" (smallArrayFromList [TreeItem "src" [TreeItem "Main.hs" []], TreeItem "README" []]) (constVar 1)+          selectWith (fixedW 120) ["one", "two", "three"] (constVar 1)+    )+  ]
+ test/golden/canvas.svg view
@@ -0,0 +1,1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200" viewBox="0 0 320 200"><rect x="0" y="0" width="320" height="200" fill="#18181b"/><g><rect x="99" y="98" width="120" height="24" rx="2" fill="#34343a"/><rect x="99.5" y="98.5" width="119" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/><path d="M206.8,109.1 L215.2,109.1 L211,112.6 Z" fill-rule="evenodd" fill="#f8f7f5"/><rect x="99" y="64" width="150" height="26" fill="#1f1f23"/><rect x="99" y="37" width="150" height="27" fill="#374862"/><rect x="99" y="11" width="150" height="26" fill="#1f1f23"/><polyline points="106.7,22 111.2,27.1 115.7,22" fill="none" stroke="#f8f7f5" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="4"/><rect x="18" y="18" width="60" height="60" rx="30" fill="#dc3c3c"/><rect x="18" y="18" width="20" height="20" fill="#28a050"/></g><text x="123.4" y="24" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="48" lengthAdjust="spacing">src</text><text x="137" y="50.5" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="112" lengthAdjust="spacing">Main.hs</text><text x="123.4" y="77" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="96" lengthAdjust="spacing">README</text><text x="119" y="110" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="48" lengthAdjust="spacing">two</text></svg>
+ test/golden/form.svg view
@@ -0,0 +1,1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect x="0" y="0" width="320" height="240" fill="#18181b"/><g><rect x="115" y="113" width="128" height="24" rx="2" fill="#34343a"/><rect x="115.5" y="113.5" width="127" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/><rect x="13" y="113" width="96" height="24" rx="2" fill="#34343a"/><rect x="13.5" y="113.5" width="95" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/><rect x="10.5" y="90.5" width="235" height="9" rx="2.5" stroke="#464850" stroke-width="1" fill="none"/><rect x="11" y="91" width="234" height="8" rx="2" fill="#24252a"/><rect x="11" y="91" width="93.6" height="8" rx="2" fill="#589cf6"/><rect x="96.4" y="87" width="16" height="16" rx="8" fill="#ffffff"/><rect x="95.9" y="86.5" width="17" height="17" rx="8.5" stroke="#464850" stroke-width="1" fill="none"/><rect x="10" y="62" width="18.4" height="18.4" rx="5.3" fill="#589cf6"/><rect x="10.8" y="62.8" width="16.9" height="16.9" rx="4.5" stroke="#589cf6" stroke-width="1.5" fill="none"/><line x1="14" y1="71.6" x2="17.7" y2="75.2" stroke="#ffffff" stroke-width="2"/><line x1="17.7" y1="75.2" x2="24.4" y2="67.2" stroke="#ffffff" stroke-width="2"/><rect x="13" y="70.6" width="2" height="2" rx="1" fill="#ffffff"/><rect x="16.7" y="74.2" width="2" height="2" rx="1" fill="#ffffff"/><rect x="23.3" y="66.1" width="2" height="2" rx="1" fill="#ffffff"/><rect x="10" y="32" width="236" height="24" rx="2" fill="#121215"/><rect x="10.5" y="32.5" width="235" height="23" rx="1.5" stroke="#464850" stroke-width="1" fill="none"/></g><text x="10" y="18" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" font-weight="bold" xml:space="preserve" fill="#eceae6" textLength="128" lengthAdjust="spacing">Settings</text><text x="30" y="44" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="64" lengthAdjust="spacing">name</text><text x="36.4" y="71" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="112" lengthAdjust="spacing">Enabled</text><text x="29" y="125" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="64" lengthAdjust="spacing">Save</text><text x="131" y="125" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="96" lengthAdjust="spacing">Cancel</text></svg>
+ test/golden/layout.svg view
@@ -0,0 +1,1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect x="0" y="0" width="320" height="240" fill="#18181b"/><g><rect x="8" y="115" width="304" height="28" rx="2" fill="#232c39"/><rect x="8.5" y="115.5" width="303" height="27" rx="1.5" stroke="#2878c8" stroke-width="1" fill="none"/><rect x="8" y="60" width="304" height="1" fill="#3e4048"/><rect x="249" y="11" width="60" height="40" rx="2" fill="#222226"/><rect x="249.5" y="11.5" width="59" height="39" rx="1.5" stroke="#36363e" stroke-width="1" fill="none"/><rect x="11" y="11" width="60" height="40" rx="2" fill="#222226"/><rect x="11.5" y="11.5" width="59" height="39" rx="1.5" stroke="#36363e" stroke-width="1" fill="none"/></g><text x="14" y="22" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="16" lengthAdjust="spacing">A</text><text x="252" y="22" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="16" lengthAdjust="spacing">B</text><text x="11" y="78" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 1</text><text x="112" y="78" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 2</text><text x="212" y="78" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 3</text><text x="11" y="98" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 4</text><text x="112" y="98" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 5</text><text x="212" y="98" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">cell 6</text><text x="18" y="129" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="284" lengthAdjust="spacing">A note in a callout</text></svg>
+ test/golden/modal.svg view
@@ -0,0 +1,1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect x="0" y="0" width="320" height="240" fill="#18181b"/><g><rect x="3" y="27" width="128" height="24" rx="2" fill="#34343a"/><rect x="3.5" y="27.5" width="127" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/></g><text x="3" y="11" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="272" lengthAdjust="spacing">Behind the dialog</text><text x="19" y="39" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="96" lengthAdjust="spacing">Behind</text><g><rect x="0" y="0" width="320" height="240" fill="#08080a" fill-opacity="0.69"/><rect x="25" y="66" width="276" height="115" rx="2" fill="#000000" fill-opacity="0.282"/><rect x="22" y="63" width="276" height="115" rx="2" fill="#222226"/><rect x="22.5" y="63.5" width="275" height="114" rx="1.5" stroke="#36363e" stroke-width="1" fill="none"/><rect x="32" y="112" width="256" height="54" fill="#222226"/><rect x="169" y="139" width="96" height="24" rx="2" fill="#34343a"/><rect x="169.5" y="139.5" width="95" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/><rect x="35" y="139" width="128" height="24" rx="2" fill="#34343a"/><rect x="35.5" y="139.5" width="127" height="23" rx="1.5" stroke="#4a4c54" stroke-width="1" fill="none"/><rect x="22" y="103" width="276" height="1" fill="#3e4048"/><line x1="277.2" y1="78" x2="287.2" y2="88" stroke="#9e9e9e" stroke-width="1.5"/><rect x="276.4" y="77.2" width="1.5" height="1.5" rx="0.8" fill="#9e9e9e"/><rect x="286.5" y="87.3" width="1.5" height="1.5" rx="0.8" fill="#9e9e9e"/><line x1="277.2" y1="88" x2="287.2" y2="78" stroke="#9e9e9e" stroke-width="1.5"/><rect x="276.4" y="87.3" width="1.5" height="1.5" rx="0.8" fill="#9e9e9e"/><rect x="286.5" y="77.2" width="1.5" height="1.5" rx="0.8" fill="#9e9e9e"/></g><text x="32" y="83" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="112" lengthAdjust="spacing">Confirm</text><text x="32" y="120" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="256" lengthAdjust="spacing">Delete the file?</text><text x="51" y="151" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="96" lengthAdjust="spacing">Delete</text><text x="185" y="151" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="64" lengthAdjust="spacing">Keep</text></svg>
+ test/golden/tabs-table.svg view
@@ -0,0 +1,1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="360" height="200" viewBox="0 0 360 200"><rect x="0" y="0" width="360" height="200" fill="#18181b"/><g><defs><clipPath id="n14e70f60-sclip_1"><rect x="1" y="43" width="358" height="113"/></clipPath></defs><rect x="0" y="42" width="360" height="115" rx="2" fill="#222226"/><rect x="0.5" y="42.5" width="359" height="114" rx="1.5" stroke="#36363e" stroke-width="1" fill="none"/><rect x="1" y="71" width="358" height="85" fill="#18181b"/><rect x="181" y="129" width="178" height="27" fill="#1f1f23"/><rect x="180" y="129" width="1" height="27" fill="#3e4048"/><rect x="1" y="129" width="179" height="27" fill="#1f1f23"/><rect x="1" y="128" width="358" height="1" fill="#3e4048"/><rect x="181" y="100" width="178" height="28" fill="#2c2c31"/><rect x="180" y="100" width="1" height="28" fill="#3e4048"/><rect x="1" y="100" width="179" height="28" fill="#2c2c31"/><rect x="1" y="99" width="358" height="1" fill="#3e4048"/><rect x="181" y="71" width="178" height="28" fill="#1f1f23"/><rect x="180" y="71" width="1" height="28" fill="#3e4048"/><rect x="1" y="71" width="179" height="28" fill="#1f1f23"/><rect x="1" y="43" width="358" height="28" fill="#121215"/><g clip-path="url(#n14e70f60-sclip_1)"><rect x="0.5" y="42.5" width="359" height="28" stroke="#464850" stroke-width="1" fill="none"/></g><rect x="1" y="70" width="358" height="1" fill="#3e4048"/><rect x="181" y="43" width="178" height="27" fill="#2c2c31"/><rect x="181" y="43" width="178" height="27" fill="#2c2c31"/><rect x="180" y="43" width="1" height="27" fill="#3e4048"/><rect x="1" y="43" width="179" height="27" fill="#2c2c31"/><rect x="1" y="43" width="179" height="27" fill="#2c2c31"/><rect x="1" y="68" width="179" height="2" fill="#589cf6"/><path d="M164,59.5 L174,59.5 L169,52.5 Z" fill-rule="evenodd" fill="#f8f7f5"/><rect x="0" y="29" width="360" height="1" fill="#3e4048"/><rect x="0" y="28" width="120" height="2" rx="1" fill="#589cf6"/></g><text x="12" y="15" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">People</text><text x="134" y="15" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#c5c2bb" textLength="80" lengthAdjust="spacing">Other</text><text x="6" y="56" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#f8f7f5" textLength="64" lengthAdjust="spacing">Name</text><text x="187" y="56" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#b0aca4" textLength="64" lengthAdjust="spacing">City</text><text x="6" y="85" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="48" lengthAdjust="spacing">Ada</text><text x="187" y="85" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">London</text><text x="6" y="114" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="48" lengthAdjust="spacing">Lin</text><text x="187" y="114" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="96" lengthAdjust="spacing">Taipei</text><text x="6" y="143" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="48" lengthAdjust="spacing">Sam</text><text x="187" y="143" dominant-baseline="central" font-size="16" font-family="Inter, 'Segoe UI', system-ui, sans-serif" xml:space="preserve" fill="#eceae6" textLength="80" lengthAdjust="spacing">Lagos</text></svg>