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

import Prelude
4

arturo's avatar
arturo committed
5 6 7 8 9
import ConvertableOptions as CO
import Data.Array as A
import Data.Either (hush)
import Data.Function.Uncurried (Fn1, runFn1, Fn2, runFn2)
import Data.Maybe (Maybe(..), fromJust, fromMaybe)
10
import Data.Maybe as Maybe
11
import Data.Nullable (Nullable, notNull, null, toMaybe)
arturo's avatar
arturo committed
12 13
import Data.Tuple (Tuple)
import Data.Tuple.Nested ((/\))
14 15 16 17 18 19
import DOM.Simple as DOM
import DOM.Simple.Console (log2)
import DOM.Simple.Document (document)
import DOM.Simple.Element as Element
import DOM.Simple.Event as DE
import DOM.Simple.Types (class IsNode, class IsElement, DOMRect)
20 21
import Effect (Effect)
import Effect.Aff (Aff, launchAff, launchAff_, killFiber)
22
import Effect.Class (liftEffect)
23
import Effect.Exception (error)
24
import Effect.Uncurried (EffectFn1, EffectFn2, EffectFn3, mkEffectFn1, mkEffectFn2, runEffectFn1, runEffectFn2, runEffectFn3)
25
import FFI.Simple (applyTo, args2, args3, defineProperty, delay, getProperty, (..), (...), (.=))
arturo's avatar
arturo committed
26 27
import Gargantext.Utils.Console (RowConsole)
import Gargantext.Utils.Console as Console
28
import Partial.Unsafe (unsafePartial)
29 30
import React (class ReactPropFields, Children, ReactClass, ReactElement)
import React as React
arturo's avatar
arturo committed
31
import React.SyntheticEvent as SE
32
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 Simple.JSON as JSON
39
import Toestand as T
40
import Unsafe.Coerce (unsafeCoerce)
41 42
import Web.File.Blob (Blob)
import Web.File.File as WF
43
import Web.File.FileList (FileList, item)
44 45 46
import Web.HTML (window)
import Web.HTML.Window (localStorage)
import Web.Storage.Storage (Storage, getItem, setItem)
47

arturo's avatar
arturo committed
48
-- | UI Component type with only required props and children
49 50
type Component p = Record p -> Array R.Element -> R.Element

arturo's avatar
arturo committed
51
-- | UI Component type with only required props and no child
52 53
type Leaf p = Record p -> R.Element

arturo's avatar
arturo committed
54
leafComponent :: forall p. (R.Component p) -> Record p -> R.Element
55 56
leafComponent cpt p = R.createElement cpt p []

arturo's avatar
arturo committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
-- | UI Component type containing optional props and children
type OptComponent options props provided = CO.Defaults (Record options) (Record provided) (Record props)
  => Record provided -> Array R.Element -> R.Element

-- | UI Component type containing optional props and no child
type OptLeaf options props provided = CO.Defaults (Record options) (Record provided) (Record props)
  => Record provided -> R.Element

component :: forall cpt p. R.IsComponent cpt p (Array R.Element)
  => cpt -> Record p -> Array R.Element -> R.Element
component cpt props children = R.createElement cpt props children

leaf :: forall cpt p. R.IsComponent cpt p (Array R.Element)
  => cpt -> Record p -> R.Element
leaf cpt props = R.createElement cpt props []

optComponent :: forall r r' cpt p.
     CO.Defaults r r' (Record p)
  => R.IsComponent cpt p (Array R.Element)
  => cpt -> r -> r' -> Array R.Element -> R.Element
optComponent cpt options props children = R.createElement cpt props' children where
  props' = CO.defaults options props

optLeaf :: forall r r' cpt p.
     CO.Defaults r r' (Record p)
  => R.IsComponent cpt p (Array R.Element)
  => cpt -> r -> r' -> R.Element
optLeaf cpt options props = R.createElement cpt props' [] where
  props' = CO.defaults options props

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

type Module = String

91
type Here =
92
  { component   :: forall p. String -> R.HooksComponent p -> R.Component p
arturo's avatar
arturo committed
93 94 95 96
  , ntComponent :: forall p. String -> NTHooksComponent p -> NTComponent p
  , name        :: Module
  | RowConsole
  }
97 98 99

here :: Module -> Here
here mod =
arturo's avatar
arturo committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  { component   : R.hooksComponentWithModule mod
  , ntComponent : ntHooksComponentWithModule mod
  , name        : mod
  , log         : Console.print   Console.Main mod Console.Log
  , log2        : Console.print2  Console.Main mod Console.Log
  , log3        : Console.print3  Console.Main mod Console.Log
  , error       : Console.print   Console.Main mod Console.Error
  , error2      : Console.print2  Console.Main mod Console.Error
  , error3      : Console.print3  Console.Main mod Console.Error
  , warn        : Console.print   Console.Main mod Console.Warn
  , warn2       : Console.print2  Console.Main mod Console.Warn
  , warn3       : Console.print3  Console.Main mod Console.Warn
  , info        : Console.print   Console.Main mod Console.Info
  , info2       : Console.print2  Console.Main mod Console.Info
  , info3       : Console.print3  Console.Main mod Console.Info
  }
116

117 118 119 120 121 122 123 124
-- 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

125 126 127
instance componentIsNTComponent
  :: NTIsComponent (NTComponent props) props (Array R.Element) where
    ntCreateElement = R.rawCreateElement
128 129 130 131 132 133 134 135

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

136 137 138 139
ntHooksComponentWithModule
 :: forall props. Module -> String -> NTHooksComponent props -> NTComponent props
ntHooksComponentWithModule module' name c =
  ntHooksComponent (module' <> "." <> name) c
140 141 142 143 144 145 146 147

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

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

148 149 150
newtype Point = Point { x :: Number, y :: Number }

-- a reducer function living in effector, for useReductor
151
type Actor s a = (a -> s -> Effect s)
152 153 154 155 156 157 158 159 160 161 162

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

163 164
-- class ToElement a where
--   toElement :: a -> R.Element
165

166
-- instance ToElement R.Element where
167
--   toElement = identity
168

169
-- instance ToElement ReactElement where
170
--   toElement = buff
171

172
-- instance ToElement a => ToElement (Array a) where
173
--   toElement = R.fragment <<< map toElement
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

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 }

200 201 202 203 204 205 206
mouseClickInElement :: DE.MouseEvent -> DOM.Element -> Boolean
mouseClickInElement e el = x <= cx && cx <= x + width && y <= cy && cy <= y + height
  where
    { x, y, width, height } = Element.boundingRect el
    cx = DE.clientX e
    cy = DE.clientY e

207 208 209 210 211 212 213 214 215
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

216 217 218
small :: ElemFactory
small = createDOM "small"

219
select :: ElemFactory
220
select = createDOM "select"
221 222

menu :: ElemFactory
223
menu = createDOM "menu"
224

225 226 227 228 229 230
frame :: ElemFactory
frame = createDOM "frame"

frameset :: ElemFactory
frameset = createDOM "frameset"

231 232 233 234 235 236
keyCode :: forall event. event -> Effect Int
keyCode = runEffectFn1 _keyCode

foreign import _keyCode
  :: forall e. EffectFn1 e Int

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
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]
267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
-- 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 $ \_ ->
293
    pure $ currySecond $ tuple $ react ... "useReducer" $ args3 (mkEffectFn2 (flip f)) j (mkEffectFn1 i)
294 295 296 297 298 299 300 301

-- | 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
302 303 304 305 306 307 308 309 310

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]
311 312 313 314 315 316 317

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
318

319
effectLink :: Effect Unit -> String -> R.Element
320
effectLink eff msg = H.a { on: {click: const eff} } [H.text msg]
321 322 323 324 325 326 327 328 329 330 331 332 333 334

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)
335
    R.unsafeHooksEffect (R.setRef oRef $ Just new)
336
    pure new
337

338 339 340 341 342
inputFile :: forall e. Int -> e -> Maybe WF.File
inputFile n e = item n $ ((el .. "files") :: FileList)
  where
    el = e .. "target"

343
-- | Get blob from an 'onchange' e.target event
344 345 346 347 348 349 350 351 352 353
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
354

355 356 357 358 359 360 361 362
foreign import _preventDefault :: forall e. EffectFn1 e Unit
preventDefault :: forall e. DE.IsEvent e => e -> Effect Unit
preventDefault = runEffectFn1 _preventDefault

foreign import _stopPropagation :: forall e. EffectFn1 e Unit
stopPropagation :: forall e. DE.IsEvent e => e -> Effect Unit
stopPropagation = runEffectFn1 _stopPropagation

363 364 365 366
-- | 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)
367
    pure $ WF.toBlob ff
368

369
foreign import _blur :: EffectFn1 DOM.Element Unit
370
blur :: DOM.Element -> Effect Unit
371
blur = runEffectFn1 _blur
372 373 374 375

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

376
col :: Int -> Array R.Element -> R.Element
377
col n children = H.div { className : "col-md-" <> show n } children
378 379 380 381 382 383 384 385 386 387

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
388

389
stringify :: forall a. a -> Int -> String
390 391
stringify j indent = runFn2 _stringify j indent

392
foreign import _stringify :: forall a. Fn2 a Int String
393 394 395 396 397 398 399

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

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

400 401 402
appParamsKey :: LocalStorageKey
appParamsKey = "garg-app-params"

403 404 405 406 407 408
graphParamsKey :: LocalStorageKey
graphParamsKey = "garg-graph-params"

phyloParamsKey :: LocalStorageKey
phyloParamsKey = "garg-phylo-params"

409 410
type LocalStorageKey = String

411
loadLocalStorageState :: forall s. JSON.ReadForeign s => LocalStorageKey -> T.Box s -> Effect Unit
412 413 414
loadLocalStorageState key cell = do
  storage <- getls
  item :: Maybe String <- getItem key storage
415 416
  -- let json = hush <<< Argonaut.jsonParser =<< item
  -- let parsed = hush <<< Argonaut.decodeJson =<< json
arturo's avatar
arturo committed
417
  let parsed = hush <<< JSON.readJSON $ Maybe.fromMaybe "" item
418 419 420 421
  case parsed of
    Nothing -> pure unit
    Just p  -> void $ T.write p cell

422 423 424 425 426 427 428 429 430 431
loadLocalStorageState' :: forall s.
     JSON.ReadForeign s
  => LocalStorageKey
  -> s
  -> Effect s
loadLocalStorageState' key default = do
  (item :: Maybe String) <- getls >>= getItem key
  let parsed = hush <<< JSON.readJSON $ Maybe.fromMaybe "" item
  pure $ Maybe.fromMaybe default parsed

432
listenLocalStorageState :: forall s. JSON.WriteForeign s => LocalStorageKey -> T.Change s -> Effect Unit
433
listenLocalStorageState key { old, new } = do
434 435
  --let json = Json.stringify $ Argonaut.encodeJson new
  let json = JSON.writeJSON new
436 437
  storage <- getls
  setItem key json storage
438

439 440 441 442 443 444 445 446 447
setLocalStorageState :: forall s.
     JSON.WriteForeign s
  => LocalStorageKey
  -> s
  -> Effect Unit
setLocalStorageState key s =
  let json = JSON.writeJSON s
  in getls >>= setItem key json

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
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
466

467 468 469 470
foreign import _setCookie :: EffectFn1 String Unit

setCookie :: String -> Effect Unit
setCookie = runEffectFn1 _setCookie
471 472 473 474 475

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

setIndeterminateCheckbox :: R.Element -> Boolean -> Effect R.Element
478
setIndeterminateCheckbox el val = pure $ (el .= "indeterminate") val
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497


-- 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
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

type Rect =
  ( x :: Number
  , y :: Number
  , width :: Number
  , height :: Number )

foreign import _domRectFromRect :: Fn1 (Record Rect) DOMRect

domRectFromRect :: Record Rect -> DOMRect
domRectFromRect = runFn1 _domRectFromRect

boundingRect :: forall e. IsElement e => Array e -> DOMRect
boundingRect els =
  case A.uncons els of
    Nothing -> domRectFromRect { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }
    Just { head, tail } ->
      let br = Element.boundingRect head
      in
      case tail of
        [] -> br
        _  ->
          let brs = boundingRect tail
              minx = min br.left brs.left
              maxx = max br.right brs.right
              miny = min br.top brs.top
              maxy = max br.bottom brs.bottom
          in
           domRectFromRect { x: minx
                           , y: miny
                           , width: maxx - minx
                           , height: maxy - miny }
530

arturo's avatar
arturo committed
531 532
--------------------------------------

arturo's avatar
arturo committed
533
-- | One-liner `when` simplifying render writing
534
-- | (best for one child)
arturo's avatar
arturo committed
535 536 537
when :: Boolean -> R.Element -> R.Element
when true m  = m
when false _ = mempty
538

arturo's avatar
arturo committed
539
-- | One-liner `when` simplifying render writing
540
-- | (best for multiple children)
arturo's avatar
arturo committed
541 542 543
when' :: Boolean -> Array (R.Element) -> R.Element
when' true m  = R.fragment m
when' false _ = mempty
544 545 546 547 548 549 550 551 552 553 554 555

-- | Toestand `useLive` automatically sets to "unchanged" behavior
useLive' :: forall box b. T.Read box b => Eq b => box -> R.Hooks b
useLive' = T.useLive T.unequal

-- | Toestand `useBox` + `useLive'` shorthand following same patterns as
-- | React StateHooks API
useBox' :: forall b. Eq b => b -> R.Hooks (Tuple b (T.Box b))
useBox' default = do
  box <- T.useBox default
  b <- useLive' box
  pure $ b /\ box
556 557 558 559 560 561 562 563 564 565 566 567 568

-- | Reactix `fragment` with key support
-- |
-- | (!) provided key won't be displayed within Chromium ReactJS widget's
-- |     Components section
fragmentWithKey :: String -> Array R.Element -> R.Element
fragmentWithKey key es = R.rawCreateElement (R.react .. "Fragment") { key } es

-- | Create portal via a `Maybe DOM.Element
createPortal' :: Maybe DOM.Element -> Array R.Element -> R.Element
createPortal' Nothing     _        = mempty
createPortal' (Just host) children = R.createPortal children host

arturo's avatar
arturo committed
569
-- | Render a `mempty` Element if provided `Maybe` is `Nothing`
arturo's avatar
arturo committed
570 571
fromMaybe :: forall a. Maybe a -> (a -> R.Element) -> R.Element
fromMaybe m render = case m of
arturo's avatar
arturo committed
572 573 574 575
  Nothing -> mempty
  Just a  -> render a


576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
--------------------------------------

-- @XXX: FFI.Simple `(...)` throws error (JavaScript issue)
--       need to decompose computation
--
--       (?) chained prototype property issue?
applyTo_ :: forall src arg res. src -> String -> Array arg -> res
applyTo_ src name args =
  let fn = getProperty name src
  in applyTo fn src args

infixl 4 applyTo_ as ~~

-- @XXX: DOM.Simple lack of "ClassList" module
addClass :: forall el. el -> Array String -> Effect Unit
addClass el args = pure $ (el .. "classList") ~~ "add" $ args

removeClass :: forall el. el -> Array String -> Effect Unit
removeClass el args = pure $ (el .. "classList") ~~ "remove" $ args
arturo's avatar
arturo committed
595 596 597 598 599 600 601 602 603 604 605 606

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

-- | Check if trying to opening in a new tab
-- | https://stackoverflow.com/a/20087506/6003907
externalOpeningFlag :: SE.SyntheticMouseEvent -> Effect Boolean
externalOpeningFlag event = ado
  ctrlKey     <- SE.ctrlKey event
  shiftKey    <- SE.shiftKey event
  metaKey     <- SE.metaKey event
  middleClick <- SE.button event
  in ctrlKey || shiftKey || metaKey || (middleClick == 1.0)
607 608 609 610 611 612 613

foreign import _triggerEvent
  :: forall e. EffectFn2 e String Unit

triggerEvent :: forall el. el -> String -> Effect Unit
triggerEvent = runEffectFn2 _triggerEvent
-------------------------------------------------------
614 615 616
getInputValue :: R.Ref (Nullable DOM.Element) -> String
getInputValue elNullableRef = case toMaybe (R.readRef elNullableRef) of
  Nothing -> ""
617
  Just el ->
618 619
    el .. "value"

620 621 622 623 624 625 626
setInputValue :: R.Ref (Nullable DOM.Element) -> String -> Effect Unit
setInputValue elNullableRef val = case toMaybe (R.readRef elNullableRef) of
  Nothing -> pure unit
  Just el -> do
    _ <- pure $ (el .= "value") val
    triggerEvent el "change"
    triggerEvent el "input"