Score.purs 2.65 KB
Newer Older
1 2 3 4
module Gargantext.Components.Score where

import Data.Argonaut (class DecodeJson, class EncodeJson, decodeJson, jsonEmptyObject, (.:), (:=), (~>), encodeJson)
import Data.Int (fromString)
5
import Data.Either (Either)
6 7 8 9 10 11
import Data.Maybe (Maybe(..), maybe)
import DOM.Simple.Console (log2)
import Effect.Aff (Aff, launchAff_)
import Effect.Class (liftEffect)
import Reactix as R
import Reactix.DOM.HTML as H
12
import Simple.JSON as JSON
13 14 15

import Gargantext.Prelude

16
import Gargantext.Config.REST (RESTError)
17 18 19
import Gargantext.Routes (SessionRoute(NodeAPI))
import Gargantext.Sessions (Session, sessionId, get, delete, put)
import Gargantext.Types as GT
20
import Gargantext.Utils.Array as GUA
21
import Gargantext.Utils.Reactix as R2
22
import Gargantext.Utils.Toestand as GUT
23 24 25 26 27 28 29 30 31

type Score = Int
type DocID = Int

thisModule :: String
thisModule = "Gargantext.Components.Score"

type Props = (
    docId       ::DocID
32
  , key :: String
33 34 35
  , nodeId      :: GT.NodeID
  , score       :: Maybe Score
  , session     :: Session
36
  , tableReload :: GUT.ReloadS
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  )

type Choice = Maybe Score

scoreEl :: R2.Component Props
scoreEl = R.createElement scoreElCpt

scoreElCpt :: R.Component Props
scoreElCpt = R.hooksComponentWithModule thisModule "scoreEl" cpt
  where
    cpt { docId, nodeId, score, session, tableReload } _ = do
      pure $ R2.select { className: "form-control"
                       , defaultValue: showChoice score
                       , on: { change: onChange session nodeId docId tableReload }
                       } (map option choices)

    onChange session nodeId docId reloadS e = do
      -- TODO change score via api
      let query = ScoreQuery { nodeIds: [ docId ]
                             , score: readChoice $ R.unsafeEventValue e }
      launchAff_ $ do
        _ <- putScore session nodeId query
59
        liftEffect $ GUT.reload reloadS
60 61 62 63

    option :: Choice -> R.Element
    option c = H.option { value: showChoice c } [ H.text $ showChoice c ]

64
    choices = [ Nothing ] <> (Just <$> GUA.range 5 100 5)
65 66 67 68 69 70 71 72 73 74 75 76 77

    showChoice :: Choice -> String
    showChoice Nothing = "-"
    showChoice (Just c) = show c

    readChoice = fromString


newtype ScoreQuery =
  ScoreQuery { nodeIds :: Array DocID
             , score   :: Choice
             }

78 79 80
instance JSON.WriteForeign ScoreQuery where
  writeImpl (ScoreQuery post) = JSON.writeImpl { nts_nodesId: post.nodeIds
                                               , nts_score: post.score }
81

82
putScore :: Session -> GT.NodeID -> ScoreQuery -> Aff (Either RESTError (Array Int))
83 84 85 86
putScore session nodeId = put session $ scoreRoute nodeId
  where
    scoreRoute :: GT.NodeID -> SessionRoute
    scoreRoute nodeId = NodeAPI GT.Node (Just nodeId) "score"