Corpus.purs 17.9 KB
Newer Older
1
module Gargantext.Components.Nodes.Corpus where
2

3 4
import Data.Argonaut (class DecodeJson, decodeJson, encodeJson)
import Data.Argonaut.Parser (jsonParser)
5
import Data.Array as A
6
import Data.Either (Either(..))
7
import Data.List as List
8
import Data.Maybe (Maybe(..), fromMaybe)
9
import Data.Tuple (Tuple(..), fst, snd)
10
import Data.Tuple.Nested ((/\))
11
import DOM.Simple.Console (log2)
12
import Effect (Effect)
13 14
import Effect.Aff (Aff, launchAff_, throwError)
import Effect.Class (liftEffect)
15
import Effect.Exception (error)
16
import Reactix as R
17
import Reactix.DOM.HTML as H
18

19
import Gargantext.Prelude
20

21
import Gargantext.Components.CodeEditor as CE
22
import Gargantext.Components.InputWithEnter (inputWithEnter)
23
import Gargantext.Components.Node (NodePoly(..), HyperdataList)
24
import Gargantext.Components.Nodes.Corpus.Types (CorpusData, FTField, Field(..), FieldType(..), Hash, Hyperdata(..), defaultField, defaultHaskell', defaultPython', defaultJSON', defaultMarkdown')
25
import Gargantext.Data.Array as GDA
26
import Gargantext.Hooks.Loader (useLoader)
27
import Gargantext.Routes (SessionRoute(NodeAPI, Children))
28
import Gargantext.Sessions (Session, get, put, sessionId)
29
import Gargantext.Types (NodeType(..), AffTableResult)
30
import Gargantext.Utils.Crypto as Crypto
31
import Gargantext.Utils.Reactix as R2
32
import Gargantext.Utils.Reload as GUR
Nicolas Pouillard's avatar
Nicolas Pouillard committed
33

34
thisModule :: String
35 36
thisModule = "Gargantext.Components.Nodes.Corpus"

37 38
type Props =
  ( nodeId  :: Int
39 40
  , session :: Session
  )
41

42
type KeyProps =
43 44
  ( key :: String
  | Props
45 46
  )

47
corpusLayout :: Record Props -> R.Element
48 49
corpusLayout props = R.createElement corpusLayoutCpt props []

50
corpusLayoutCpt :: R.Component Props
51
corpusLayoutCpt = R.hooksComponentWithModule thisModule "corpusLayout" cpt
52
  where
53 54 55 56 57 58 59 60 61 62
    cpt { nodeId, session } _ = do
      let sid = sessionId session

      pure $ corpusLayoutWithKey { key: show sid <> "-" <> show nodeId, nodeId, session }


corpusLayoutWithKey :: Record KeyProps -> R.Element
corpusLayoutWithKey props = R.createElement corpusLayoutWithKeyCpt props []

corpusLayoutWithKeyCpt :: R.Component KeyProps
63
corpusLayoutWithKeyCpt = R.hooksComponentWithModule thisModule "corpusLayoutWithKey" cpt
64 65
  where
    cpt { nodeId, session } _ = do
66
      reload <- GUR.new
67

68
      useLoader {nodeId, reload: GUR.value reload, session} loadCorpusWithReload $
69
        \corpus -> corpusLayoutView {corpus, nodeId, reload, session}
70

71 72
type ViewProps =
  ( corpus  :: NodePoly Hyperdata
73
  , reload  :: GUR.ReloadS
74 75 76
  | Props
  )

77 78
-- We need FTFields with indices because it's the only way to identify the
-- FTField element inside a component (there are no UUIDs and such)
79 80
type Index = Int
type FTFieldWithIndex = Tuple Index FTField
81
type FTFieldsWithIndex = List.List FTFieldWithIndex
82

83 84 85 86
corpusLayoutView :: Record ViewProps -> R.Element
corpusLayoutView props = R.createElement corpusLayoutViewCpt props []

corpusLayoutViewCpt :: R.Component ViewProps
87
corpusLayoutViewCpt = R.hooksComponentWithModule thisModule "corpusLayoutView" cpt
88
  where
89
    cpt {corpus: (NodePoly {hyperdata: Hyperdata {fields}}), nodeId, reload, session} _ = do
90
      let fieldsWithIndex = List.mapWithIndex (\idx -> \t -> Tuple idx t) fields
91
      fieldsS <- R.useState' fieldsWithIndex
92 93 94 95 96 97 98 99 100
      fieldsRef <- R.useRef fields

      -- handle props change of fields
      R.useEffect1' fields $ do
        if R.readRef fieldsRef == fields then
          pure unit
        else do
          R.setRef fieldsRef fields
          snd fieldsS $ const fieldsWithIndex
101 102

      pure $ H.div {} [
103
        H.div { className: "row" } [
104
           H.div { className: "btn btn-secondary " <> (saveEnabled fieldsWithIndex fieldsS)
105 106
                 , on: { click: onClickSave {fields: fieldsS, nodeId, reload, session} }
                 } [
107
              H.span { className: "fa fa-floppy-o" } [  ]
108 109
              ]
           ]
110 111 112
        , H.div {} [ fieldsCodeEditor { fields: fieldsS
                                      , nodeId
                                      , session } ]
113
        , H.div { className: "row" } [
114
           H.div { className: "btn btn-secondary"
115 116
                 , on: { click: onClickAdd fieldsS }
                 } [
117
              H.span { className: "fa fa-plus" } [  ]
118 119
              ]
           ]
120
        ]
121

122
    saveEnabled :: FTFieldsWithIndex -> R.State FTFieldsWithIndex -> String
123 124
    saveEnabled fs (fsS /\ _) = if fs == fsS then "disabled" else "enabled"

125
    onClickSave :: forall e. { fields :: R.State FTFieldsWithIndex
126
                       , nodeId :: Int
127
                       , reload :: GUR.ReloadS
128
                       , session :: Session } -> e -> Effect Unit
129
    onClickSave {fields: (fieldsS /\ _), nodeId, reload, session} _ = do
130 131 132 133 134
      log2 "[corpusLayoutViewCpt] onClickSave fieldsS" fieldsS
      launchAff_ do
        saveCorpus $ { hyperdata: Hyperdata {fields: (\(Tuple _ f) -> f) <$> fieldsS}
                     , nodeId
                     , session }
135
        liftEffect $ GUR.bump reload
136

137
    onClickAdd :: forall e. R.State FTFieldsWithIndex -> e -> Effect Unit
138
    onClickAdd (_ /\ setFieldsS) _ = do
139
      setFieldsS $ \fieldsS -> List.snoc fieldsS $ Tuple (List.length fieldsS) defaultField
140 141 142

type FieldsCodeEditorProps =
  (
143
    fields :: R.State FTFieldsWithIndex
144 145 146 147 148 149 150
    | LoadProps
  )

fieldsCodeEditor :: Record FieldsCodeEditorProps -> R.Element
fieldsCodeEditor props = R.createElement fieldsCodeEditorCpt props []

fieldsCodeEditorCpt :: R.Component FieldsCodeEditorProps
151
fieldsCodeEditorCpt = R.hooksComponentWithModule thisModule "fieldsCodeEditorCpt" cpt
152
  where
153
    cpt {nodeId, fields: fS@(fields /\ _), session} _ = do
154 155 156
      masterKey <- R.useState' 0

      pure $ H.div {} $ List.toUnfoldable (editors masterKey)
157
      where
158
        editors masterKey =
159
          (\(Tuple idx field) ->
160 161 162 163 164 165 166 167 168 169
            fieldCodeEditorWrapper { canMoveDown: idx < (List.length fields - 1)
                                   , canMoveUp: idx > 0
                                   , field
                                   , key: (show $ fst masterKey) <> "-" <> (show idx)
                                   , onChange: onChange fS idx
                                   , onMoveDown: onMoveDown masterKey fS idx
                                   , onMoveUp: onMoveUp masterKey fS idx
                                   , onRemove: onRemove fS idx
                                   , onRename: onRename fS idx
                                   }) <$> fields
170 171

    onChange :: R.State FTFieldsWithIndex -> Index -> FieldType -> Effect Unit
172 173
    onChange (_ /\ setFields) idx typ = do
      setFields $ \fields ->
174 175
        fromMaybe fields $
          List.modifyAt idx (\(Tuple _ (Field f)) -> Tuple idx (Field $ f { typ = typ })) fields
176

177
    onMoveDown :: GUR.ReloadS -> R.State FTFieldsWithIndex -> Index -> Unit -> Effect Unit
178 179
    onMoveDown (_ /\ setMasterKey) (fs /\ setFields) idx _ = do
      setMasterKey $ (+) 1
180
      setFields $ recomputeIndices <<< (GDA.swapList idx (idx + 1))
181

182
    onMoveUp :: GUR.ReloadS -> R.State FTFieldsWithIndex -> Index -> Unit -> Effect Unit
183 184
    onMoveUp (_ /\ setMasterKey) (_ /\ setFields) idx _ = do
      setMasterKey $ (+) 1
185
      setFields $ recomputeIndices <<< (GDA.swapList idx (idx - 1))
186

187
    onRemove :: R.State FTFieldsWithIndex -> Index -> Unit -> Effect Unit
188 189
    onRemove (_ /\ setFields) idx _ = do
      setFields $ \fields ->
190
        fromMaybe fields $ List.deleteAt idx fields
191

192
    onRename :: R.State FTFieldsWithIndex -> Index -> String -> Effect Unit
193 194
    onRename (_ /\ setFields) idx newName = do
      setFields $ \fields ->
195
        fromMaybe fields $ List.modifyAt idx (\(Tuple _ (Field f)) -> Tuple idx (Field $ f { name = newName })) fields
196

197 198
    recomputeIndices :: FTFieldsWithIndex -> FTFieldsWithIndex
    recomputeIndices = List.mapWithIndex $ \idx -> \(Tuple _ t) -> Tuple idx t
199

200
hash :: FTFieldWithIndex -> Hash
201
hash (Tuple idx f) = Crypto.hash $ "--idx--" <> (show idx) <> "--field--" <> (show f)
202

203 204
type FieldCodeEditorProps =
  (
205 206 207
    canMoveDown :: Boolean
  , canMoveUp :: Boolean
  , field :: FTField
208
  , key :: String
209
  , onChange :: FieldType -> Effect Unit
210 211
  , onMoveDown :: Unit -> Effect Unit
  , onMoveUp :: Unit -> Effect Unit
212
  , onRemove :: Unit -> Effect Unit
213
  , onRename :: String -> Effect Unit
214 215 216 217 218 219
  )

fieldCodeEditorWrapper :: Record FieldCodeEditorProps -> R.Element
fieldCodeEditorWrapper props = R.createElement fieldCodeEditorWrapperCpt props []

fieldCodeEditorWrapperCpt :: R.Component FieldCodeEditorProps
220
fieldCodeEditorWrapperCpt = R.hooksComponentWithModule thisModule "fieldCodeEditorWrapperCpt" cpt
221
  where
222
    cpt props@{canMoveDown, canMoveUp, field: Field {name, typ}, onMoveDown, onMoveUp, onRemove, onRename} _ = do
223 224 225 226 227 228 229 230
      pure $ H.div { className: "row card" } [
        H.div { className: "card-header" } [
          H.div { className: "code-editor-heading row" } [
              H.div { className: "col-sm-4" } [
                renameable {onRename, text: name}
              ]
            , H.div { className: "col-sm-7" } []
            , H.div { className: "buttons-right col-sm-1" } [
231 232 233
                H.div { className: "btn btn-danger"
                      , on: { click: \_ -> onRemove unit }
                      } [
234
                  H.span { className: "fa fa-trash" } [  ]
235
                  ]
236 237
              , moveDownButton canMoveDown
              , moveUpButton canMoveUp
238
              ]
239 240
            ]
         ]
241
        , H.div { className: "card-body" } [
242 243 244
           fieldCodeEditor props
           ]
        ]
245 246 247
      where
        moveDownButton false = H.div {} []
        moveDownButton true =
248
          H.div { className: "btn btn-secondary"
249 250
                , on: { click: \_ -> onMoveDown unit }
                } [
251
            H.span { className: "fa fa-arrow-down" } [  ]
252 253 254
            ]
        moveUpButton false = H.div {} []
        moveUpButton true =
255
          H.div { className: "btn btn-secondary"
256 257
                , on: { click: \_ -> onMoveUp unit }
                } [
258
            H.span { className: "fa fa-arrow-up" } [  ]
259
            ]
260

261 262 263 264 265 266 267 268 269 270
type RenameableProps =
  (
    onRename :: String -> Effect Unit
  , text :: String
  )

renameable :: Record RenameableProps -> R.Element
renameable props = R.createElement renameableCpt props []

renameableCpt :: R.Component RenameableProps
271
renameableCpt = R.hooksComponentWithModule thisModule "renameableCpt" cpt
272 273 274 275
  where
    cpt {onRename, text} _ = do
      isEditing <- R.useState' false
      state <- R.useState' text
276 277 278 279 280 281 282 283 284
      textRef <- R.useRef text

      -- handle props change of text
      R.useEffect1' text $ do
        if R.readRef textRef == text then
          pure unit
        else do
          R.setRef textRef text
          snd state $ const text
285 286

      pure $ H.div { className: "renameable" } [
287
        renameableText { isEditing, onRename, state }
288
      ]
289 290 291 292 293 294 295 296 297 298 299 300

type RenameableTextProps =
  (
    isEditing :: R.State Boolean
  , onRename :: String -> Effect Unit
  , state :: R.State String
  )

renameableText :: Record RenameableTextProps -> R.Element
renameableText props = R.createElement renameableTextCpt props []

renameableTextCpt :: R.Component RenameableTextProps
301
renameableTextCpt = R.hooksComponentWithModule thisModule "renameableTextCpt" cpt
302 303
  where
    cpt {isEditing: (false /\ setIsEditing), state: (text /\ _)} _ = do
304 305 306 307 308 309 310
      pure $ H.div { className: "input-group" } [
        H.input { className: "form-control"
                , defaultValue: text
                , disabled: 1
                , type: "text" }
        , H.div { className: "btn input-group-append"
                , on: { click: \_ -> setIsEditing $ const true } } [
311
           H.span { className: "fa fa-pencil" } []
312
           ]
313
        ]
314
    cpt {isEditing: (true /\ setIsEditing), onRename, state: (text /\ setText)} _ = do
315
      pure $ H.div { className: "input-group" } [
316
          inputWithEnter {
317
              autoFocus: false
318
             , autoSave: false
319 320
             , className: "form-control text"
             , defaultValue: text
321 322
             , onEnter: submit
             , onValueChanged: setText <<< const
323 324 325
             , placeholder: ""
             , type: "text"
             }
326
        , H.div { className: "btn input-group-append"
327
                 , on: { click: submit } } [
328
           H.span { className: "fa fa-floppy-o" } []
329
           ]
330
        ]
331 332 333 334
      where
        submit _ = do
          setIsEditing $ const false
          onRename text
335

336 337 338 339
fieldCodeEditor :: Record FieldCodeEditorProps -> R.Element
fieldCodeEditor props = R.createElement fieldCodeEditorCpt props []

fieldCodeEditorCpt :: R.Component FieldCodeEditorProps
340
fieldCodeEditorCpt = R.hooksComponentWithModule thisModule "fieldCodeEditorCpt" cpt
341
  where
342 343
    cpt {field: Field {typ: typ@(Haskell {haskell})}, onChange} _ = do
      pure $ CE.codeEditor {code: haskell, defaultCodeType: CE.Haskell, onChange: changeCode onChange typ}
344 345 346 347

    cpt {field: Field {typ: typ@(Python {python})}, onChange} _ = do
      pure $ CE.codeEditor {code: python, defaultCodeType: CE.Python, onChange: changeCode onChange typ}

348 349
    cpt {field: Field {typ: typ@(JSON j)}, onChange} _ = do
      pure $ CE.codeEditor {code, defaultCodeType: CE.JSON, onChange: changeCode onChange typ}
350 351
      where
        code = R2.stringify (encodeJson j) 2
352

353 354 355
    cpt {field: Field {typ: typ@(Markdown {text})}, onChange} _ = do
      pure $ CE.codeEditor {code: text, defaultCodeType: CE.Markdown, onChange: changeCode onChange typ}

356
-- Performs the matrix of code type changes
357 358 359 360 361
-- (FieldType -> Effect Unit) is the callback function for fields array
-- FieldType is the current element that we will modify
-- CE.CodeType is the editor code type (might have been the cause of the trigger)
-- CE.Code is the editor code (might have been the cause of the trigger)
changeCode :: (FieldType -> Effect Unit) -> FieldType -> CE.CodeType -> CE.Code -> Effect Unit
362 363 364
changeCode onc (Haskell hs)        CE.Haskell  c = onc $ Haskell $ hs { haskell = c }
changeCode onc (Haskell hs)        CE.Python   c = onc $ Python   $ defaultPython'   { python  = c }
changeCode onc (Haskell {haskell}) CE.JSON     c = onc $ JSON     $ defaultJSON'     { desc = haskell }
365
changeCode onc (Haskell {haskell}) CE.Markdown c = onc $ Markdown $ defaultMarkdown' { text = haskell }
366 367 368 369 370 371 372 373 374 375 376

changeCode onc (Python hs)       CE.Python   c = onc $ Python  $ hs { python  = c }
changeCode onc (Python hs)       CE.Haskell  c = onc $ Haskell $ defaultHaskell' { haskell = c }
changeCode onc (Python {python}) CE.JSON     c = onc $ JSON     $ defaultJSON' { desc = python }
changeCode onc (Python {python}) CE.Markdown c = onc $ Markdown $ defaultMarkdown' { text = python }

changeCode onc (Markdown md) CE.Haskell  c = onc $ Haskell  $ defaultHaskell'  { haskell = c }
changeCode onc (Markdown md) CE.Python   c = onc $ Python   $ defaultPython'   { python  = c }
changeCode onc (Markdown md) CE.JSON     c = onc $ Markdown $ defaultMarkdown' { text    = c }
changeCode onc (Markdown md) CE.Markdown c = onc $ Markdown $ md               { text    = c }

377 378 379
changeCode onc (JSON j@{desc}) CE.Haskell c = onc $ Haskell $ defaultHaskell' { haskell = haskell }
  where
    haskell = R2.stringify (encodeJson j) 2
380 381 382
changeCode onc (JSON j@{desc}) CE.Python c = onc $ Python $ defaultPython' { python = toCode }
  where
    toCode = R2.stringify (encodeJson j) 2
383 384 385 386 387 388 389 390 391
changeCode onc (JSON j) CE.JSON c = do
  case jsonParser c of
    Left err -> log2 "[fieldCodeEditor'] cannot parse json" c
    Right j' -> case decodeJson j' of
      Left err -> log2 "[fieldCodeEditor'] cannot decode json" j'
      Right j'' -> onc $ JSON j''
changeCode onc (JSON j) CE.Markdown c = onc $ Markdown $ defaultMarkdown' { text = text }
  where
    text = R2.stringify (encodeJson j) 2
392 393 394



395

396 397
type LoadProps =
  ( nodeId  :: Int
398 399
  , session :: Session
  )
400

401
loadCorpus' :: Record LoadProps -> Aff (NodePoly Hyperdata)
402
loadCorpus' {nodeId, session} = get session $ NodeAPI Corpus (Just nodeId) ""
403

404
-- Just to make reloading effective
405
loadCorpusWithReload :: {reload :: GUR.Reload  | LoadProps} -> Aff (NodePoly Hyperdata)
406
loadCorpusWithReload {nodeId, session} = loadCorpus' {nodeId, session}
407

408 409 410 411 412 413
type SaveProps = (
  hyperdata :: Hyperdata
  | LoadProps
  )

saveCorpus :: Record SaveProps -> Aff Unit
414 415 416
saveCorpus {hyperdata, nodeId, session} = do
  id_ <- (put session (NodeAPI Corpus (Just nodeId) "") hyperdata) :: Aff Int
  pure unit
417

418 419
loadCorpus :: Record LoadProps -> Aff CorpusData
loadCorpus {nodeId, session} = do
420 421
  -- fetch corpus via lists parentId
  (NodePoly {parentId: corpusId} :: NodePoly {}) <- get session nodePolyRoute
422 423 424
  corpusNode     <-  get session $ corpusNodeRoute     corpusId ""
  defaultListIds <- (get session $ defaultListIdsRoute corpusId)
                    :: forall a. DecodeJson a => AffTableResult (NodePoly a)
425
  case (A.head defaultListIds.docs :: Maybe (NodePoly HyperdataList)) of
426 427 428 429 430
    Just (NodePoly { id: defaultListId }) ->
      pure {corpusId, corpusNode, defaultListId}
    Nothing ->
      throwError $ error "Missing default list"
  where
431
    nodePolyRoute       = NodeAPI Corpus (Just nodeId) ""
432 433
    corpusNodeRoute     = NodeAPI Corpus <<< Just
    defaultListIdsRoute = Children NodeList 0 1 Nothing <<< Just
434 435 436


loadCorpusWithChild :: Record LoadProps -> Aff CorpusData
437
loadCorpusWithChild { nodeId: childId, session } = do
438 439 440 441 442 443 444
  -- fetch corpus via lists parentId
  (NodePoly {parentId: corpusId} :: NodePoly {}) <- get session $ listNodeRoute childId ""
  corpusNode     <-  get session $ corpusNodeRoute     corpusId ""
  defaultListIds <- (get session $ defaultListIdsRoute corpusId)
                    :: forall a. DecodeJson a => AffTableResult (NodePoly a)
  case (A.head defaultListIds.docs :: Maybe (NodePoly HyperdataList)) of
    Just (NodePoly { id: defaultListId }) ->
445
      pure { corpusId, corpusNode, defaultListId }
446 447 448 449 450 451 452
    Nothing ->
      throwError $ error "Missing default list"
  where
    corpusNodeRoute     = NodeAPI Corpus <<< Just
    listNodeRoute       = NodeAPI Node <<< Just
    defaultListIdsRoute = Children NodeList 0 1 Nothing <<< Just

453 454 455

type LoadWithReloadProps =
  (
456
    reload :: GUR.Reload
457 458 459 460 461 462 463
  | LoadProps
  )


-- Just to make reloading effective
loadCorpusWithChildAndReload :: Record LoadWithReloadProps -> Aff CorpusData
loadCorpusWithChildAndReload {nodeId, reload, session} = loadCorpusWithChild {nodeId, session}