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

import Prelude
4

5
import DOM.Simple as DOM
6
import DOM.Simple.Console (log2)
7 8
import DOM.Simple.Document (document)
import DOM.Simple.Element as Element
9
import DOM.Simple.Event as DE
10
import DOM.Simple.Types (class IsNode)
11 12 13 14 15
import Data.Argonaut as Argonaut
import Data.Argonaut as Json
import Data.Argonaut.Core (Json)
import Data.Either (hush)
import Data.Function.Uncurried (Fn2, runFn2)
16
import Data.Maybe (Maybe(..), fromJust, fromMaybe, isJust)
17 18 19
import Data.Nullable (Nullable, null, toMaybe)
import Data.Tuple (Tuple(..))
import Data.Tuple.Nested ((/\))
20
import Effect (Effect)
21
import Effect.Console (logShow)
22
import Effect.Aff (Aff, launchAff, launchAff_, killFiber)
23
import Effect.Class (liftEffect)
24
import Effect.Exception (error)
Mudada's avatar
Mudada committed
25
import Effect.Uncurried (EffectFn1, EffectFn2, EffectFn3, mkEffectFn1, mkEffectFn2, runEffectFn1, runEffectFn2, runEffectFn3)
26
import Effect.Unsafe (unsafePerformEffect)
27
import FFI.Simple ((..), (...), (.=), defineProperty, delay, args2, args3)
28
import Partial.Unsafe (unsafePartial)
29 30 31
import React (class ReactPropFields, Children, ReactClass, ReactElement)
import React as React
import Reactix as R
32
import Reactix.DOM.HTML (ElemFactory, createDOM, text)
33
import Reactix.DOM.HTML as H
34
import Reactix.React (react)
35 36 37
import Reactix.SyntheticEvent as RE
import Reactix.Utils (currySecond, hook, tuple)
import Unsafe.Coerce (unsafeCoerce)
38 39
import Web.File.Blob (Blob)
import Web.File.File as WF
40
import Web.File.FileList (FileList, item)
41 42 43
import Web.HTML (window)
import Web.HTML.Window (localStorage)
import Web.Storage.Storage (Storage, getItem, setItem)
44

45 46 47 48 49 50
-- TODO Reactix should export this definition
type HooksComponent props = Record props -> Array R.Element -> R.Hooks R.Element

hooksComponent :: forall props. String -> String -> HooksComponent props -> R.Component props
hooksComponent module' name c = R.hooksComponent (module' <> "." <> name) c

51 52 53 54 55
newtype Point = Point { x :: Number, y :: Number }

-- a setter function, for useState
type Setter t = (t -> t) -> Effect Unit
-- a reducer function living in effector, for useReductor
56
type Actor s a = (a -> s -> Effect s)
57 58 59 60 61 62 63 64 65 66 67

-- | Turns a ReactElement into aReactix Element
-- | buff (v.) to polish
buff :: ReactElement -> R.Element
buff = unsafeCoerce

-- | Turns a Reactix Element into a ReactElement.
-- | scuff (v.) to spoil the gloss or finish of.
scuff :: R.Element -> ReactElement
scuff = unsafeCoerce

68 69
-- class ToElement a where
--   toElement :: a -> R.Element
70

71 72
-- instance toElementElement :: ToElement R.Element where
--   toElement = identity
73

74 75
-- instance toElementReactElement :: ToElement ReactElement where
--   toElement = buff
76

77 78
-- instance toElementArray :: ToElement a => ToElement (Array a) where
--   toElement = R.fragment <<< map toElement
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

createElement' :: forall required given
                . ReactPropFields required given
               => ReactClass { children :: Children | required }
               -> Record given -> Array R.Element -> R.Element
createElement' reactClass props children =
  buff $ React.createElement reactClass props $ scuff <$> children

{-
instance isComponentReactClass
      :: R.IsComponent (ReactClass { children :: Children
                                   | props
                                   }) props (Array R.Element) where
  createElement reactClass props children =
    React.createElement reactClass props children
-}

-- | Turns an aff into a useEffect-compatible Effect (Effect Unit)
affEffect :: forall a. String -> Aff a -> Effect (Effect Unit)
affEffect errmsg aff = do
    fiber <- launchAff aff
    pure $ launchAff_ $ killFiber (error errmsg) fiber

mousePosition :: RE.SyntheticEvent DE.MouseEvent -> Point
mousePosition e = Point { x: RE.clientX e, y: RE.clientY e }

domMousePosition :: DE.MouseEvent -> Point
domMousePosition = mousePosition <<< unsafeCoerce
-- | This is naughty, it quietly mutates the input and returns it
named :: forall o. String -> o -> o
named = flip $ defineProperty "name"

overState :: forall t. (t -> t) -> R.State t -> Effect Unit
overState f (_state /\ setState) = setState f

select :: ElemFactory
115
select = createDOM "select"
116 117

menu :: ElemFactory
118
menu = createDOM "menu"
119 120

effToggler :: forall e. R.State Boolean -> EffectFn1 e Unit
121
effToggler (value /\ setValue) = mkEffectFn1 $ \_ -> setValue $ const $ not value
122 123 124 125

unsafeEventValue :: forall event. event -> String
unsafeEventValue e = (unsafeCoerce e).target.value

126 127 128 129 130 131
keyCode :: forall event. event -> Effect Int
keyCode = runEffectFn1 _keyCode

foreign import _keyCode
  :: forall e. EffectFn1 e Int

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
nullRef :: forall t. R.Hooks (R.Ref (Nullable t))
nullRef = R.useRef null

nothingRef :: forall t. R.Hooks (R.Ref (Maybe t))
nothingRef = R.useRef Nothing

useLayoutEffect1' :: forall a. a -> (Unit -> Effect Unit) -> R.Hooks Unit
useLayoutEffect1' a f = R.useLayoutEffect1 a $ do
  liftEffect $ f unit
  pure $ pure unit

useLayoutRef :: forall a b. (a -> b) -> b -> R.Ref a -> R.Hooks (R.Ref b)
useLayoutRef fn init ref = do
  new <- R.useRef init
  let old = R.readRef ref
  useLayoutEffect1' old $ \_ -> R.setRef new (fn old)
  pure new

usePositionRef :: R.Ref (Nullable DOM.Element) -> R.Hooks (R.Ref (Maybe DOM.DOMRect))
usePositionRef = useLayoutRef (map Element.boundingRect <<< toMaybe) Nothing

readPositionRef :: R.Ref (Nullable DOM.Element) -> Maybe DOM.DOMRect
readPositionRef el = do
  let posRef = R.readRef el
  Element.boundingRect <$> toMaybe posRef

unsafeEventTarget :: forall event. event -> DOM.Element
unsafeEventTarget e = (unsafeCoerce e).target

getElementById :: String -> Effect (Maybe DOM.Element)
getElementById = (flip delay) h
  where
    h id = pure $ toMaybe $ document ... "getElementById" $ [id]
165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
-- We just assume it works, so make sure it's in the html
getPortalHost :: R.Hooks DOM.Element
getPortalHost = R.unsafeHooksEffect $ delay unit $ \_ -> pure $ document ... "getElementById" $ ["portal"]

useLayoutEffectOnce :: Effect (Effect Unit) -> R.Hooks Unit
useLayoutEffectOnce e = R.unsafeUseLayoutEffect e []

singleParent :: forall props. R.Component props -> Record props -> R.Element -> R.Element
singleParent cpt props child = R.createElement cpt props [ child ]

childless :: forall props. R.Component props -> Record props -> R.Element
childless cpt props = R.createElement cpt props []

showText :: forall s. Show s => s -> R.Element
showText = text <<< show

----- Reactix's new effectful reducer: sneak-peek because anoe wants to demo on tuesday

-- | Like a reducer, but lives in Effect
type Reductor state action = Tuple state (action -> Effect Unit)

-- | Like useReductor, but lives in Effect
useReductor :: forall s a i. Actor s a -> (i -> Effect s) -> i -> R.Hooks (Reductor s a)
useReductor f i j =
  hook $ \_ ->
191
    pure $ currySecond $ tuple $ react ... "useReducer" $ args3 (mkEffectFn2 (flip f)) j (mkEffectFn1 i)
192 193 194 195 196 197 198 199

-- | Like `useReductor`, but takes an initial state instead of an
-- | initialiser function and argument
useReductor' :: forall s a. Actor s a -> s -> R.Hooks (Reductor s a)
useReductor' r = useReductor r pure

render :: R.Element -> DOM.Element -> Effect Unit
render e d = delay unit $ \_ -> pure $ R.reactDOM ... "render" $ args2 e d
200 201 202 203 204 205 206 207 208

addRootElement :: DOM.Element -> Effect Unit
addRootElement = runEffectFn1 _addRootElement

foreign import _addRootElement
  :: EffectFn1 DOM.Element Unit

appendChild :: forall n m. IsNode n => IsNode m => n -> m -> Effect Unit
appendChild n c = delay unit $ \_ -> pure $ n ... "appendChild" $ [c]
209 210 211 212 213 214 215 216 217

appendChildToParentId :: forall c. IsNode c => String -> c -> Effect Unit
appendChildToParentId ps c = delay unit $ \_ -> do
  parentEl <- getElementById ps
  log2 "[appendChildToParentId] ps" ps
  log2 "[appendChildToParentId] parentEl" parentEl
  case parentEl of
    Nothing -> pure unit
    Just el -> appendChild el c
218

219 220
effectLink :: Effect Unit -> String -> R.Element
effectLink eff msg = H.a {on: {click: const eff}} [H.text msg]
221 222 223 224 225 226 227 228 229 230 231 232 233 234

useCache :: forall i o. Eq i => i -> (i -> R.Hooks o) -> R.Hooks o
useCache i f = do
  iRef <- R.useRef Nothing
  oRef <- R.useRef Nothing
  let currI = R.readRef iRef
  let currO = R.readRef oRef
  if currI == Just i then
    case currO of
      Nothing -> f i -- this one shouldn't happen, but purescript
      Just v -> pure v
  else do
    new <- f i
    R.unsafeHooksEffect (R.setRef iRef $ Just i)
235
    R.unsafeHooksEffect (R.setRef oRef $ Just new)
236
    pure new
237

238 239 240 241 242
inputFile :: forall e. Int -> e -> Maybe WF.File
inputFile n e = item n $ ((el .. "files") :: FileList)
  where
    el = e .. "target"

243
-- | Get blob from an 'onchange' e.target event
244 245 246 247 248 249 250 251 252 253
inputFileBlob n e = unsafePartial $ do
  let ff = fromJust $ inputFile n e
  pure $ WF.toBlob ff

inputFileNameWithBlob :: forall e. Int -> e -> Maybe {blob :: Blob, name :: String}
inputFileNameWithBlob n e = case ff of
    Nothing -> Nothing
    Just f  -> Just {blob: WF.toBlob f, name: WF.name f}
  where
    ff = inputFile n e
254 255 256 257 258

-- | Get blob from a drop event
--dataTransferFileBlob :: forall e. DE.IsEvent e => RE.SyntheticEvent e -> Effect Blob
dataTransferFileBlob e = unsafePartial $ do
    let ff = fromJust $ item 0 $ ((e .. "dataTransfer" .. "files") :: FileList)
259
    pure $ WF.toBlob ff
260 261 262

blur :: DOM.Element -> Effect Unit
blur el = el ... "blur" $ []
263 264 265 266

row :: Array R.Element -> R.Element
row children = H.div { className: "row" } children

267
col :: Int -> Array R.Element -> R.Element
268
col n children = H.div { className : "col-md-" <> show n } children
269 270 271 272 273 274 275 276 277 278

innerText :: DOM.Element -> String
innerText e = e .. "innerText"

foreign import data Selection :: Type

getSelection :: Unit -> Effect Selection
getSelection = runEffectFn1 _getSelection

foreign import _getSelection :: EffectFn1 Unit Selection
279 280 281 282 283

stringify :: Json -> Int -> String
stringify j indent = runFn2 _stringify j indent

foreign import _stringify :: Fn2 Json Int String
284 285 286 287 288 289 290 291 292 293 294

getls :: Effect Storage
getls = window >>= localStorage

openNodesKey :: LocalStorageKey
openNodesKey = "garg-open-nodes"

type LocalStorageKey = String

useLocalStorageState :: forall s. Argonaut.DecodeJson s => Argonaut.EncodeJson s => LocalStorageKey -> s -> R.Hooks (R.State s)
useLocalStorageState key s = do
295 296
  -- we need to synchronously get the initial state from local storage
  Tuple state setState' <- R.useState \_ -> unsafePerformEffect do
297 298 299
    item :: Maybe String <- getItem key =<< getls
    let json = hush <<< Argonaut.jsonParser =<< item
    let parsed = hush <<< Argonaut.decodeJson =<< json
300
    pure $ fromMaybe s parsed
301 302 303

  let
    setState update = do
304
      let new = update state
305 306 307 308 309 310
      setState' (\_ -> new)
      let json = Json.stringify $ Argonaut.encodeJson new
      storage <- getls
      setItem key json storage

  pure (Tuple state setState)
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

getMessageDataStr :: DE.MessageEvent -> String
getMessageDataStr = getMessageData

getMessageOrigin :: DE.MessageEvent -> String
getMessageOrigin me = me .. "origin"

getMessageData :: forall o. DE.MessageEvent -> o
getMessageData me = me .. "data"

foreign import _postMessage
  :: forall r. EffectFn3 r String String Unit

postMessage :: forall r. R.Ref (Nullable r) -> String -> Effect Unit
postMessage ref msg = do
  case (R.readNullableRef ref) of
    (Just ifr) -> do
      runEffectFn3 _postMessage ifr msg (ifr .. "src")
    (Nothing) -> pure unit
Mudada's avatar
Mudada committed
330

331 332 333 334
foreign import _setCookie :: EffectFn1 String Unit

setCookie :: String -> Effect Unit
setCookie = runEffectFn1 _setCookie
335 336 337 338 339

focus :: Nullable R.Element -> Effect Unit
focus nEl = case toMaybe nEl of
  Nothing -> pure unit
  Just el -> el ... "focus" $ []
340 341

setIndeterminateCheckbox :: R.Element -> Boolean -> Effect R.Element
342
setIndeterminateCheckbox el val = pure $ (el .= "indeterminate") val