Reactix.purs 13.1 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 DOM.Simple.Console (log2)
21
import Effect (Effect)
22
import Effect.Console (logShow)
23
import Effect.Aff (Aff, launchAff, launchAff_, killFiber)
24
import Effect.Class (liftEffect)
25
import Effect.Exception (error)
Mudada's avatar
Mudada committed
26
import Effect.Uncurried (EffectFn1, EffectFn2, EffectFn3, mkEffectFn1, mkEffectFn2, runEffectFn1, runEffectFn2, runEffectFn3)
27
import Effect.Unsafe (unsafePerformEffect)
28
import FFI.Simple ((..), (...), (.=), defineProperty, delay, args2, args3)
29
import Partial.Unsafe (unsafePartial)
30 31 32
import React (class ReactPropFields, Children, ReactClass, ReactElement)
import React as React
import Reactix as R
33
import Reactix.DOM.HTML (ElemFactory, createDOM, text)
34
import Reactix.DOM.HTML as H
35
import Reactix.React (react)
36 37
import Reactix.SyntheticEvent as RE
import Reactix.Utils (currySecond, hook, tuple)
38
import Toestand as T
39
import Unsafe.Coerce (unsafeCoerce)
40 41
import Web.File.Blob (Blob)
import Web.File.File as WF
42
import Web.File.FileList (FileList, item)
43 44 45
import Web.HTML (window)
import Web.HTML.Window (localStorage)
import Web.Storage.Storage (Storage, getItem, setItem)
46

47 48
type Module = String

49 50
type Component p = Record p -> Array R.Element -> R.Element

51 52 53
type Leaf p = Record p -> R.Element

type Here =
54 55 56 57
  { component   :: forall p. String -> R.HooksComponent p -> R.Component p
  , log         :: forall l. l -> Effect Unit
  , log2        :: forall l. String -> l -> Effect Unit
  , ntComponent :: forall p. String -> NTHooksComponent p -> NTComponent p }
58 59 60

here :: Module -> Here
here mod =
61 62 63 64
  { component:   R.hooksComponentWithModule mod
  , log:         log2 ("[" <> mod <> "]")
  , log2:        \msg -> log2 ("[" <> mod <> "] " <> msg)
  , ntComponent: ntHooksComponentWithModule mod }
65

66 67 68 69 70 71 72 73
-- newtypes
type NTHooksComponent props = props -> Array R.Element -> R.Hooks R.Element
newtype NTComponent p = NTComponent (EffectFn1 p R.Element)

class NTIsComponent component (props :: Type) children
  | component -> props, component -> children where
  ntCreateElement :: component -> props -> children -> R.Element

74 75 76
instance componentIsNTComponent
  :: NTIsComponent (NTComponent props) props (Array R.Element) where
    ntCreateElement = R.rawCreateElement
77 78 79 80 81 82 83 84

-- | Turns a `HooksComponent` function into a Component
ntHooksComponent :: forall props. String -> NTHooksComponent props -> NTComponent props
ntHooksComponent name c = NTComponent $ named name $ mkEffectFn1 c'
  where
    c' :: props -> Effect R.Element
    c' props = R.runHooks $ c props (children props)

85 86 87 88
ntHooksComponentWithModule
 :: forall props. Module -> String -> NTHooksComponent props -> NTComponent props
ntHooksComponentWithModule module' name c =
  ntHooksComponent (module' <> "." <> name) c
89 90 91 92 93 94 95 96

---------------------------
-- TODO Copied from reactix, export these:
children :: forall a. a -> Array R.Element
children a = react .. "Children" ... "toArray" $ [ (a .. "children") ]

---------------------------

97 98 99
newtype Point = Point { x :: Number, y :: Number }

-- a reducer function living in effector, for useReductor
100
type Actor s a = (a -> s -> Effect s)
101 102 103 104 105 106 107 108 109 110 111

-- | 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

112 113
-- class ToElement a where
--   toElement :: a -> R.Element
114

115 116
-- instance toElementElement :: ToElement R.Element where
--   toElement = identity
117

118 119
-- instance toElementReactElement :: ToElement ReactElement where
--   toElement = buff
120

121 122
-- instance toElementArray :: ToElement a => ToElement (Array a) where
--   toElement = R.fragment <<< map toElement
123 124 125 126 127 128 129 130 131 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

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

158 159 160
small :: ElemFactory
small = createDOM "small"

161
select :: ElemFactory
162
select = createDOM "select"
163 164

menu :: ElemFactory
165
menu = createDOM "menu"
166

167 168 169 170 171 172
frame :: ElemFactory
frame = createDOM "frame"

frameset :: ElemFactory
frameset = createDOM "frameset"

173 174 175 176 177 178
keyCode :: forall event. event -> Effect Int
keyCode = runEffectFn1 _keyCode

foreign import _keyCode
  :: forall e. EffectFn1 e Int

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
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

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

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
-- 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 $ \_ ->
235
    pure $ currySecond $ tuple $ react ... "useReducer" $ args3 (mkEffectFn2 (flip f)) j (mkEffectFn1 i)
236 237 238 239 240 241 242 243

-- | 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
244 245 246 247 248 249 250 251 252

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]
253 254 255 256 257 258 259

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

261
effectLink :: Effect Unit -> String -> R.Element
262
effectLink eff msg = H.a { on: {click: const eff} } [H.text msg]
263 264 265 266 267 268 269 270 271 272 273 274 275 276

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)
277
    R.unsafeHooksEffect (R.setRef oRef $ Just new)
278
    pure new
279

280 281 282 283 284
inputFile :: forall e. Int -> e -> Maybe WF.File
inputFile n e = item n $ ((el .. "files") :: FileList)
  where
    el = e .. "target"

285
-- | Get blob from an 'onchange' e.target event
286 287 288 289 290 291 292 293 294 295
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
296 297 298 299 300

-- | 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)
301
    pure $ WF.toBlob ff
302 303 304

blur :: DOM.Element -> Effect Unit
blur el = el ... "blur" $ []
305 306 307 308

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

309
col :: Int -> Array R.Element -> R.Element
310
col n children = H.div { className : "col-md-" <> show n } children
311 312 313 314 315 316 317 318 319 320

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
321 322 323 324 325

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

foreign import _stringify :: Fn2 Json Int String
326 327 328 329 330 331 332 333 334

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

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

type LocalStorageKey = String

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
loadLocalStorageState :: forall s. Argonaut.DecodeJson s => LocalStorageKey -> T.Box s -> Effect Unit
loadLocalStorageState key cell = do
  storage <- getls
  item :: Maybe String <- getItem key storage
  let json = hush <<< Argonaut.jsonParser =<< item
  let parsed = hush <<< Argonaut.decodeJson =<< json
  case parsed of
    Nothing -> pure unit
    Just p  -> void $ T.write p cell

listenLocalStorageState :: forall s. Argonaut.EncodeJson s => LocalStorageKey -> T.Change s -> Effect Unit
listenLocalStorageState key { old, new } = do
  let json = Json.stringify $ Argonaut.encodeJson new
  storage <- getls
  setItem key json storage
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368

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
369

370 371 372 373
foreign import _setCookie :: EffectFn1 String Unit

setCookie :: String -> Effect Unit
setCookie = runEffectFn1 _setCookie
374 375 376 377 378

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

setIndeterminateCheckbox :: R.Element -> Boolean -> Effect R.Element
381
setIndeterminateCheckbox el val = pure $ (el .= "indeterminate") val
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400


-- A "trigger" is a ref to a function which is used to make changes without
-- modifying too much DOM.
-- This is to escape passing explicit state to nested child components.
type Trigger a = R.Ref (Maybe (a -> Effect Unit))

callTrigger :: forall a. Trigger a -> a -> Effect Unit
callTrigger tRef arg = case R.readRef tRef of
  Nothing -> do
    log2 "[callTrigger] trigger is empty" tRef
    pure unit
  Just t  -> t arg

setTrigger :: forall a. Trigger a -> (a -> Effect Unit) -> Effect Unit
setTrigger tRef fun = R.setRef tRef $ Just fun

clearTrigger :: forall a. Trigger a -> Effect Unit
clearTrigger tRef = R.setRef tRef Nothing