packages feed

geomancy-layout-0.2.0: test/Spec.hs

{-# LANGUAGE OverloadedStrings #-}

import Prelude

import Data.Foldable (toList)

import Test.Tasty
import Test.Tasty.HUnit
import System.Directory (createDirectoryIfMissing)

import Geomancy.Layout.Alignment (Alignment(..), pattern End, pattern Middle)
import Geomancy.Layout.Alignment qualified as Alignment
import Geomancy.Layout.Box (Box(..))
import Geomancy.Layout.Box qualified as Box
import Geomancy.Layout.View (View(..), ViewSize(..))
import Geomancy.Layout.View qualified as View
import Geomancy.Vec2 (Vec2, vec2, withVec2)
import Geomancy.Vec4 (vec4)

import Lucid.Svg (renderToFile)

import Examples
import Menu.Grids (interplay, spans, tracks)
import Menu.Harbour (harbour)
import Menu.Iron (iron)
import Menu.Jungle (jungle)
import Menu.Kit (UI)
import Menu.Probe (invariants)
import Menu.Svg (renderMenu)

main :: IO ()
main = do
  createDirectoryIfMissing True "examples/menus"
  createDirectoryIfMissing True "examples/grid"
  defaultMain tests

tests :: TestTree
tests = testGroup "geomancy-layout"
  [ examples
  , showcases
  , stacks
  , frames
  , aspects
  , grids
  , clearances
  ]

examples :: TestTree
examples = testGroup "Examples"
  [ testCase "Tree" $ toSVGfile "examples/Tree.svg" exampleTree
  , testCase "Halves" $ toSVGfile "examples/Halves.svg" exampleHalves
  , testCase "Overflow" $ toSVGfile "examples/Overflow.svg" exampleOverflow
  , testCase "Framed" $ toSVGfile "examples/Framed.svg" exampleFramed
  , testCase "Nested" $ toSVGfile "examples/Nested.svg" exampleNested
  , testCase "Dynamic" $ toSVGfile "examples/Dynamic.svg" exampleDynamic
  , testCase "DynamicVert" $ toSVGfile "examples/DynamicVert.svg" exampleDynamicVert
  ]

showcases :: TestTree
showcases = testGroup "Showcases"
  [ showcase "examples/menus" "Harbour" harbour
  , showcase "examples/menus" "Iron" iron
  , showcase "examples/menus" "Jungle" jungle
  , showcase "examples/grid" "Tracks" tracks
  , showcase "examples/grid" "Spans" spans
  , showcase "examples/grid" "Interplay" interplay
  ]

showcase :: FilePath -> String -> UI -> TestTree
showcase directory name tree =
  testCase name do
    let file suffix = directory <> "/" <> name <> suffix <> ".svg"
    renderToFile (file "") (renderMenu False screen placed)
    renderToFile (file "-outline") (renderMenu True screen placed)
    invariants screen placed @?= []
  where
    screen = vec2 1920 1080
    placed = View.layout Box{position = screen / 2, size = screen} tree

stacks :: TestTree
stacks = testGroup "Stacks"
  [ testCase "Main-axis alignment moves the run" $
      childBoxes exampleScreenBox (View.hstack 0 (Alignment $ vec2 End Middle) [square "a"])
        @?= [Box{position = vec2 750 300, size = vec2 100 50}]

  , testCase "A spacer under a zero proposal stays empty" $ do
      let
        zeroHigh = Box{position = vec2 100 0, size = vec2 200 0}
        tree = View.vstack_ [View.frame_ (vec2 200 50) (View () "a"), View.spacer_ :: View () Static]
      fst (View.suspend zeroHigh.size $ View.measure tree) @?= vec2 200 50
      map (.size) (childBoxes zeroHigh tree) @?= [vec2 200 50, vec2 0 0]

  , testCase "Spacers follow their stack through modifiers" $
      (View.measure $ View.hstack_ [View.padding_ 5 (View.spacer_ :: View () Static)]).ann
        @?= View.range_ (vec2 10 10) (vec2 (1 / 0) 10)

  , testCase "Negative spacing never makes a stack's size negative" $ do
      let
        tree = View.hstack (-30) Alignment.leftTop [View.frame_ (vec2 10 10) (View () "a"), View.frame_ (vec2 10 10) (View () "b")] :: View () Static
        measured = (View.measure tree).ann
      (measured.minWidth, measured.maxWidth) @?= (Just 0, Just 0)
      fst (View.suspend (vec2 400 100) $ View.measure tree) @?= vec2 0 10

  , testCase "Parent-sized views get what their siblings leave" $
      map Box.width (childBoxes row $ View.hstack_ [leaf 100 100, View.viewFun View.parent_ \proposed -> (proposed, const ())])
        @?= [100, 300]

  , testCase "Long stacks place their last child where they report" $ do
      let
        root = Box{position = vec2 50 0, size = vec2 100 10}
        tree = View.vstack 3.7 Alignment.leftTop $ replicate 5000 (View.frame_ (vec2 10 20.3) (View () "x")) :: View () Static
        reported = fst (View.suspend root.size $ View.measure tree)
        lastBottom = Box.withTRBL (last $ childBoxes root tree) \_t _r b _l -> b
        top = Box.withTRBL root \t _r _b _l -> t
      assertBool (show (lastBottom - top, reported)) $
        abs (lastBottom - top - snd' reported) < 0.5

  , testCase "Traversal runs back to front" $ do
      toList
        ( View.overlay Alignment.centerBottom (View.view_ "label") $
            View.background Alignment.center (View.view_ "gradient") $
              View.padding_ 4 $
                View.background Alignment.center (View.view_ "circle") $
                  View.padding_ 6 (View.view_ "icon")
        )
        @?= ["gradient", "circle", "icon", "label" :: String]
      toList (View.zstack_ [View.view_ "back", View.view_ "front"]) @?= ["back", "front" :: String]
      toList (View.grid_ [[View.view_ "a", View.view_ "b"], [View.view_ "c"]]) @?= ["a", "b", "c" :: String]
  ]
  where
    square label = View.frame_ (vec2 100 50) (View () label) :: View () Static
    leaf lo hi =
      View.viewFun
        (View.range_ (vec2 lo 10) (vec2 hi 10))
        \proposed -> withVec2 proposed \w _h -> (vec2 (min hi $ max lo w) 10, const ())

frames :: TestTree
frames = testGroup "Flexible frames"
  [ testCase "Size like SwiftUI's flexible frame" $ do
      sized (View.between (vec2 0 44) (vec2 (1 / 0) 44)) @?= vec2 400 44
      sized View.unbounded @?= vec2 30 20
      sized (View.fillWidth View.unbounded) @?= vec2 400 20
      sized View.unbounded{View.frameMinWidth = Just 50} @?= vec2 50 20
      sized View.unbounded{View.frameMaxWidth = Just 80} @?= vec2 80 20
      sized View.unbounded{View.frameMinWidth = Just 100, View.frameMaxWidth = Just 50} @?= vec2 100 20

  , testCase "Measure the range they can report" $ do
      measured (View.between (vec2 0 64) (vec2 (1 / 0) 64)) @?= View.range_ (vec2 0 64) (vec2 (1 / 0) 64)
      measured View.unbounded @?= View.fixed_ (vec2 30 20)
      measured (View.fillWidth View.unbounded) @?= View.range_ (vec2 30 20) (vec2 (1 / 0) 20)
      measured View.unbounded{View.frameMinWidth = Just 50} @?= View.fixed_ (vec2 50 20)
      measured View.unbounded{View.frameMaxWidth = Just 80} @?= View.range_ (vec2 30 20) (vec2 80 20)
      measured View.unbounded{View.frameMinWidth = Just 100, View.frameMaxWidth = Just 50} @?= View.range_ (vec2 50 20) (vec2 100 20)
      (View.measure $ View.flexible_ (View.between 60 100) Alignment.center (View.viewFun View.parent_ \proposed -> (proposed, const ()))).ann
        @?= View.range_ 60 100
  ]
  where
    framed bounds = View.flexible_ bounds Alignment.center (View.frame_ (vec2 30 20) (View () "a") :: View () Static)
    sized bounds =
      case childBoxes row (View.hstack_ [framed bounds]) of
        [box] -> box.size
        _ -> vec2 (-1) (-1)
    measured bounds = (View.measure $ framed bounds).ann

aspects :: TestTree
aspects = testGroup "Aspect ratio"
  [ testCase "Letterboxes content that cannot take the ratio" $ do
      wrapped [] 1 1 capped @?= (vec2 120 120, vec2 120 120)
      wrapped [] 1 1 tile @?= (vec2 30 30, vec2 30 20)
      wrapped [piece (View.fixed_ (vec2 50 20)) (const (vec2 50 20))] 1 1 View.spacer_ @?= (vec2 200 200, vec2 200 0)
      wrapped [] 1 1 textLike @?= (vec2 100 100, vec2 100 20)
      case View.layout screen (View.hstack_ [View.aspect_ 1 tile]) of
        HStack{children = [AspectRatio{ann, inner}]} ->
          (ann, inner.ann) @?= (Box{position = vec2 15 100, size = vec2 30 30}, Box{position = vec2 15 100, size = vec2 30 20})
        _ -> assertFailure "expected a row holding an AspectRatio"

  , testCase "Measures the range it can report" $ do
      (View.measure $ View.aspect_ 1 tile).ann @?= View.fixed_ (vec2 30 30)
      (View.measure $ View.aspect_ 1 capped).ann @?= View.range_ (vec2 0 0) (vec2 120 120)

  , testCase "Only a positive finite quotient counts" $ do
      wrapped [] (-4) (-1) art @?= (vec2 400 100, vec2 400 100)
      wrapped [] (-1) 1 tile @?= (vec2 30 20, vec2 30 20)
      wrapped [] 1 0 tile @?= (vec2 30 20, vec2 30 20)
      wrapped [] 0 0 art @?= (vec2 400 200, vec2 400 200)
      (View.measure $ View.aspect_ 0 tile).ann @?= View.fixed_ (vec2 30 20)
  ]
  where
    screen = Box{position = vec2 200 100, size = vec2 400 200}
    piece size answer = View.viewFun size \proposed -> (answer proposed, const ())
    art = piece View.infinite_ id
    capped = piece (View.range_ (vec2 0 0) (vec2 120 (1 / 0))) \proposed -> withVec2 proposed \w h -> vec2 (min 120 w) h
    tile = piece (View.fixed_ (vec2 30 20)) (const (vec2 30 20))
    textLike = piece (View.range_ (vec2 10 20) (vec2 100 20)) \proposed -> withVec2 proposed \w _h -> vec2 (max 10 $ min 100 w) 20
    wrapped before aw ah child =
      case View.layout screen (View.hstack_ $ before <> [View.aspect_ (vec2 aw ah) child]) of
        HStack{children} | AspectRatio{ann, inner} <- last children -> (ann.size, inner.ann.size)
        _ -> (vec2 (-1) (-1), vec2 (-1) (-1))

grids :: TestTree
grids = testGroup "Grid"
  [ testCase "Unsized cells count only their minimum" $
      (View.measure $ View.grid_ [[tile 30 20], [View.viewFun (View.range_ (vec2 40 0) (vec2 (1 / 0) (1 / 0))) \proposed -> (proposed, const ())]]).ann.minWidth
        @?= Just 40

  , testCase "Gaps follow the clearances cells ask for" $ do
      let tree = View.grid 4 0 Alignment.leftTop [[edgy 3 10 0 2 30 20, edgy 5 0 1 6 30 20]]
      reported (vec2 400 200) tree @?= vec2 70 20
      (View.measure tree).ann.clearance @?= Box.TRBL (vec4 5 0 1 2)
      reported (vec2 400 200) (View.grid 0 0 Alignment.leftTop [[View.span_ 2 1 (edgy 0 10 0 0 60 20), tile 20 20], [tile 30 20, tile 30 20, tile 20 20]])
        @?= vec2 90 40

  , testCase "Spanning cells get room before open tracks and fill capped tracks first" $ do
      map Box.width (cells (Box{position = vec2 50 10, size = vec2 100 20}) $ View.grid_ [[label, View.spacer_]])
        @?= [100, 0]
      map Box.width (cells screen $ View.grid_ [[View.span_ 2 1 label], [tile 30 20, tile 30 20, View.spacer_]])
        @?= [100, 30, 30, 300]
      map (.position) (drop 1 $ cells (Box{position = vec2 50 20, size = vec2 100 40}) $ View.grid_ [[View.span_ 2 1 (tile 100 20)], [tile 30 20, capped]])
        @?= [vec2 17.5 30, vec2 67.5 30]
      reported (vec2 400 200) (View.grid_ [[View.span_ 2 1 (View.aspect_ (vec2 2 1) art)], [tile 50 20, tile 50 20]])
        @?= vec2 100 70

  , testCase "Span edge cases" $ do
      reported (vec2 400 200) (View.grid_ [[View.span_ 2 2 (tile 60 60), tile 20 20], [tile 20 20]]) @?= vec2 80 60
      reported (vec2 400 200) (View.grid_ [[View.span_ 1 3 (tile 20 40), tile 20 20]]) @?= vec2 40 40
      reported (vec2 400 200) (View.grid_ [[View.padding_ 0 (View.span_ 2 1 (tile 100 20))], [tile 30 20, tile 30 20]]) @?= vec2 100 40
      (View.measure $ View.grid_ [[View.span_ 2 1 label]]).ann @?= View.range_ (vec2 10 20) (vec2 100 20)
      (View.measure $ View.span_ 2 2 (tile 30 20)).ann @?= View.fixed_ (vec2 30 20)

  , testCase "Reported sizes stay inside the measured range" $
      sequence_
        [ assertBool (show (offer, size, range)) $ inside size range
        | tree <- samples
        , let range = (View.measure tree).ann
        , offer <- [vec2 0 0, vec2 (orZero range.minWidth) (orZero range.minHeight), vec2 400 200, vec2 1e6 1e6]
        , let size = reported offer tree
        ]

  , testCase "Degenerate grids report sane sizes" $
      sequence_
        [ assertBool (show size) $ withVec2 size \w h -> not (isNaN w || isNaN h) && w >= 0 && h >= 0
        | tree <- [View.grid_ [], View.grid_ [[]], View.grid_ [[View.spacer_, View.spacer_], [View.spacer_]], View.grid (-50) (-50) Alignment.center [[tile 30 20, tile 30 20], [tile 30 20]]]
        , offer <- [vec2 0 0, vec2 400 200]
        , let size = reported offer tree
        ]
  ]
  where
    screen = Box{position = vec2 200 100, size = vec2 400 200}
    tile w h = View.viewFun (View.fixed_ (vec2 w h)) \_proposed -> (vec2 w h, const ())
    art = View.viewFun View.infinite_ \proposed -> (proposed, const ())
    label = View.viewFun (View.range_ (vec2 10 20) (vec2 100 20)) \proposed -> withVec2 proposed \w _h -> (vec2 (max 10 $ min 100 w) 20, const ())
    capped = View.viewFun (View.range_ (vec2 0 20) (vec2 60 20)) \proposed -> withVec2 proposed \w _h -> (vec2 (min 60 w) 20, const ())
    edgy t r b l w h = View.viewFun (View.fixed_ (vec2 w h)){clearance = Box.TRBL (vec4 t r b l)} \_proposed -> (vec2 w h, const ())
    samples =
      [ View.grid 5 7 Alignment.leftTop [[View.spacer_, tile 40 30], [tile 20 20, art]]
      , View.grid_ [[View.span_ 2 1 (tile 100 20)], [tile 30 20, capped]]
      , View.grid_ [[View.span_ 2 1 label], [tile 30 20, tile 30 20, View.spacer_]]
      , View.grid_ [[View.span_ 2 1 (View.aspect_ (vec2 2 1) art)], [tile 50 20, tile 50 20]]
      , View.grid_ [[tile 20 20, View.span_ 1 2 (tile 20 40)], [View.span_ 2 1 (tile 40 20)]]
      , View.grid_ [[View.span_ 2 1 label, tile 20 20], [tile 20 20, View.span_ 2 1 label]]
      ]
    reported offer tree = fst (View.suspend offer $ View.measure tree)
    cells root tree =
      case View.layout root tree of
        Grid{rows} -> map (.ann) (concat rows)
        _ -> []
    orZero = maybe 0 id
    inside size range =
      withVec2 size \w h ->
        within w range.minWidth range.maxWidth && within h range.minHeight range.maxHeight
    within value lo hi = maybe True (<= value + 0.01) lo && maybe True (>= value - 0.01) hi

clearances :: TestTree
clearances = testGroup "Clearance"
  [ testCase "Gaps take the larger of spacing and clearance" $ do
      tops (View.vstack 4 Alignment.leftTop [block 10 0 10, block 10 6 0]) @?= [0, 20]
      tops (View.vstack 12 Alignment.leftTop [block 10 0 10, block 10 6 0]) @?= [0, 22]
      tops (View.vstack (-4) Alignment.leftTop [block 10 0 0, block 10 0 0]) @?= [0, 6]
      tops (View.vstack (-4) Alignment.leftTop [block 10 0 0, block 10 6 0]) @?= [0, 16]

  , testCase "Padding counts toward clearance" $ do
      (View.measure $ View.padding_ (vec4 2 0 0 0) (block 10 6 6)).ann.clearance @?= Box.TRBL (vec4 4 0 6 0)
      tops (View.vstack 0 Alignment.leftTop [block 20 0 0, View.padding_ (vec4 1 0 0 0) (block 20 10 0)]) @?= [0, 29]
      tops (View.vstack 0 Alignment.leftTop [block 20 0 0, View.padding_ (vec4 12 0 0 0) (block 20 10 0)]) @?= [0, 20]
      tops (View.vstack 0 Alignment.leftTop [block 10 0 0, View.padding_ (vec4 (-5) 0 0 0) (block 10 0 0)]) @?= [0, 10]
  ]
  where
    block height top bottom =
      View.viewFun
        (View.fixed_ (vec2 100 height)){clearance = Box.TRBL (vec4 top 0 bottom 0)}
        \_proposed -> (vec2 100 height, const ())
    tops tree =
      [ Box.withTRBL box \t _r _b _l -> t
      | box <- childBoxes Box{position = vec2 50 50, size = vec2 100 100} tree
      ]

row :: Box
row = Box{position = vec2 200 50, size = vec2 400 100}

snd' :: Vec2 -> Float
snd' v = withVec2 v \_x y -> y

childBoxes :: View.LayoutView stuff => Box -> View () stuff -> [Box]
childBoxes root tree =
  case View.layout root tree of
    HStack{children} -> map (.ann) children
    VStack{children} -> map (.ann) children
    ZStack{children} -> map (.ann) children
    _ -> []