Utils.purs 2.09 KB
Newer Older
1
module Gargantext.Utils where
2 3

import Prelude
4
import Data.Either (Either(..))
5
import Data.Lens (Lens', lens)
6
import Data.Newtype (class Newtype, unwrap, wrap)
7 8
import Data.Set as Set
import Data.Set (Set)
9
import Data.String as S
10

11 12 13
-- | TODO (hard coded)
csrfMiddlewareToken :: String
csrfMiddlewareToken = "Wy52D2nor8kC1r1Y4GrsrSIxQ2eqW8UwkdiQQshMoRwobzU4uldknRUhP0j4WcEM"
James Laver's avatar
James Laver committed
14

15 16 17 18 19 20
setterv :: forall nt record field.
           Newtype nt record
           => (record -> field -> record)
           -> field
           -> nt
           -> nt
21 22
setterv fn v t = (setter (flip fn v) t)

23 24 25 26 27
setter :: forall nt record.
          Newtype nt record
          => (record -> record)
          -> nt
          -> nt
28 29
setter fn = wrap <<< fn <<< unwrap

30 31 32 33 34
getter :: forall record field nt.
          Newtype nt record
          => (record -> field)
          -> nt
          -> field
35
getter fn = fn <<< unwrap
36 37 38 39 40 41

-- TODO: not optimal but Data.Set lacks some function (Set.alter)
toggleSet :: forall a. Ord a => a -> Set a -> Set a
toggleSet a s
  | Set.member a s = Set.delete a s
  | otherwise      = Set.insert a s
42 43 44 45 46 47 48 49 50 51

-- Default sort order is ascending, we may want descending
invertOrdering :: Ordering -> Ordering
invertOrdering LT = GT
invertOrdering GT = LT
invertOrdering EQ = EQ

-- A lens that always returns unit
_unit :: forall s. Lens' s Unit
_unit = lens (\_ -> unit) (\s _ -> s)
52

53
glyphicon :: String -> String
54
glyphicon t = "btn glyphitem fa fa-" <> t
55

56 57 58
glyphiconActive :: String -> Boolean -> String
glyphiconActive icon b = glyphicon icon <> if b then " active" else ""

59 60 61 62
-- | Format a number with specified amount of zero-padding
zeroPad :: Int -> Int -> String
zeroPad pad num = zeros <> (show num)
  where
63
    numDigits = S.length $ show num
64 65 66
    zeros = if numDigits < pad then zeros' (pad - numDigits) else ""
    zeros' 0 = ""
    zeros' n = "0" <> (zeros' (n - 1))
67 68 69 70 71

queryMatchesLabel :: String -> String -> Boolean
queryMatchesLabel q l = S.contains (S.Pattern $ normalize q) (normalize l)
  where
    normalize = S.toLower
72 73 74 75 76


mapLeft :: forall l m r. (l -> m) -> Either l r -> Either m r
mapLeft f (Left  l) = Left (f l)
mapLeft _ (Right r) = Right r