Score.purs 2.45 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

type Score = Int
type DocID = Int

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

arturo's avatar
arturo committed
26 27
type Props =
  ( docId       ::DocID
28 29 30
  , nodeId      :: GT.NodeID
  , score       :: Maybe Score
  , session     :: Session
31
  , tableReload :: GUT.ReloadS
32 33 34 35
  )

type Choice = Maybe Score

arturo's avatar
arturo committed
36
scoreEl :: R2.Component ( key :: String | Props )
37
scoreEl = R.createElement scoreElCpt
arturo's avatar
arturo committed
38
scoreElCpt :: R.Component ( key :: String | Props )
39 40 41 42 43 44 45 46 47 48 49 50 51 52
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
53
        liftEffect $ GUT.reload reloadS
54 55 56 57

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

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

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

    readChoice = fromString


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

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

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