-- | Utility functions.
module Brick.Util
  ( clamp
  , on
  , fg
  , bg
  , style
  , clOffset
  )
where

import Lens.Micro ((&), (%~))
#if !(MIN_VERSION_base(4,11,0))
import Data.Monoid ((<>))
#endif
import Graphics.Vty

import Brick.Types.Internal (Location(..), CursorLocation(..), cursorLocationL)

-- | Given a minimum value and a maximum value, clamp a value to that
-- range (values less than the minimum map to the minimum and values
-- greater than the maximum map to the maximum).
--
-- >>> clamp 1 10 11
-- 10
-- >>> clamp 1 10 2
-- 2
-- >>> clamp 5 10 1
-- 5
clamp :: (Ord a)
      => a
      -- ^ The minimum value
      -> a
      -- ^ The maximum value
      -> a
      -- ^ The value to clamp
      -> a
clamp :: forall a. Ord a => a -> a -> a -> a
clamp a
mn a
mx a
val = a -> a -> a
forall a. Ord a => a -> a -> a
max a
mn (a -> a -> a
forall a. Ord a => a -> a -> a
min a
val a
mx)

-- | Build an attribute from a foreground color and a background color.
-- Intended to be used infix.
on :: Color
   -- ^ The foreground color
   -> Color
   -- ^ The background color
   -> Attr
on :: Color -> Color -> Attr
on Color
f Color
b = Attr
defAttr Attr -> Color -> Attr
`withForeColor` Color
f
                 Attr -> Color -> Attr
`withBackColor` Color
b

-- | Create an attribute from the specified foreground color (the
-- background color is the "default").
fg :: Color -> Attr
fg :: Color -> Attr
fg = (Attr
defAttr Attr -> Color -> Attr
`withForeColor`)

-- | Create an attribute from the specified background color (the
-- foreground color is the "default").
bg :: Color -> Attr
bg :: Color -> Attr
bg = (Attr
defAttr Attr -> Color -> Attr
`withBackColor`)

-- | Create an attribute from the specified style (the colors are the
-- "default").
style :: Style -> Attr
style :: Style -> Attr
style = (Attr
defAttr Attr -> Style -> Attr
`withStyle`)

-- | Add a 'Location' offset to the specified 'CursorLocation'.
clOffset :: CursorLocation n -> Location -> CursorLocation n
clOffset :: forall n. CursorLocation n -> Location -> CursorLocation n
clOffset CursorLocation n
cl Location
off = CursorLocation n
cl CursorLocation n
-> (CursorLocation n -> CursorLocation n) -> CursorLocation n
forall a b. a -> (a -> b) -> b
& (Location -> Identity Location)
-> CursorLocation n -> Identity (CursorLocation n)
forall n (f :: * -> *).
Functor f =>
(Location -> f Location)
-> CursorLocation n -> f (CursorLocation n)
cursorLocationL ((Location -> Identity Location)
 -> CursorLocation n -> Identity (CursorLocation n))
-> (Location -> Location) -> CursorLocation n -> CursorLocation n
forall s t a b. ASetter s t a b -> (a -> b) -> s -> t
%~ (Location -> Location -> Location
forall a. Semigroup a => a -> a -> a
<> Location
off)