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

import Gargantext.Prelude

5 6 7 8 9
import Data.Int (fromString)
import Data.Maybe (Maybe(..))
import Effect.Aff (launchAff_)
import Effect.Class (liftEffect)
import Gargantext.Config.REST (AffRESTError)
10
import Gargantext.Routes (SessionRoute(NodeAPI))
11
import Gargantext.Sessions (Session, put)
12
import Gargantext.Types as GT
13
import Gargantext.Utils.Array as GUA
14
import Gargantext.Utils.Reactix as R2
15
import Gargantext.Utils.Toestand as GUT
16 17 18
import Reactix as R
import Reactix.DOM.HTML as H
import Simple.JSON as JSON
19 20 21 22 23 24 25 26 27

type Score = Int
type DocID = Int

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

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

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
54
        liftEffect $ GUT.reload reloadS
55 56 57 58

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

59
    choices = [ Nothing ] <> (Just <$> GUA.range 5 100 5)
60 61 62 63 64 65 66 67 68 69 70 71 72

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

    readChoice = fromString


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

73 74 75
instance JSON.WriteForeign ScoreQuery where
  writeImpl (ScoreQuery post) = JSON.writeImpl { nts_nodesId: post.nodeIds
                                               , nts_score: post.score }
76

77
putScore :: Session -> GT.NodeID -> ScoreQuery -> AffRESTError (Array Int)
78 79 80 81
putScore session nodeId = put session $ scoreRoute nodeId
  where
    scoreRoute :: GT.NodeID -> SessionRoute
    scoreRoute nodeId = NodeAPI GT.Node (Just nodeId) "score"