NgramsTable.purs 30.9 KB
Newer Older
1 2
module Gargantext.Components.NgramsTable
  ( MainNgramsTableProps
3
  , CommonProps
4 5
  , mainNgramsTable
  ) where
6

7 8
import Gargantext.Prelude

9
import Data.Array as A
10
import Data.Either (Either)
11
import Data.FunctorWithIndex (mapWithIndex)
12
import Data.Lens (to, view, (%~), (.~), (^.), (^?))
13
import Data.Lens.At (at)
14
import Data.Lens.Common (_Just)
15
import Data.Lens.Fold (folded)
16
import Data.Lens.Index (ix)
17 18
import Data.Map (Map)
import Data.Map as Map
19
import Data.Maybe (Maybe(..), fromMaybe, isNothing, maybe)
20
import Data.Monoid.Additive (Additive(..))
21
import Data.Ord.Down (Down(..))
22
import Data.Sequence (Seq, length) as Seq
23 24
import Data.Set (Set)
import Data.Set as Set
25
import Data.Tuple (Tuple(..))
26
import Data.Tuple.Nested ((/\))
27
import Effect (Effect)
28
import Effect.Aff (Aff)
29
import Gargantext.Components.App.Data (Boxes)
30
import Gargantext.Components.NgramsTable.Components as NTC
31
import Gargantext.Components.NgramsTable.Core (Action(..), CoreAction(..), CoreState, Dispatch, NgramsElement(..), NgramsPatch(..), NgramsTable, NgramsTerm, PageParams, PatchMap(..), Versioned(..), VersionedNgramsTable, VersionedWithCountNgramsTable, _NgramsElement, _NgramsRepoElement, _NgramsTable, _children, _list, _ngrams, _ngrams_repo_elements, _ngrams_scores, _occurrences, _root, addNewNgramA, applyNgramsPatches, applyPatchSet, chartsAfterSync, commitPatch, convOrderBy, coreDispatch, filterTermSize, fromNgramsPatches, ngramsRepoElementToNgramsElement, ngramsTermText, normNgram, patchSetFromMap, replace, singletonNgramsTablePatch, syncResetButtons, toVersioned)
32
import Gargantext.Components.NgramsTable.Loader (useLoaderWithCacheAPI)
33
import Gargantext.Components.Nodes.Lists.Types as NT
34 35
import Gargantext.Components.Table as TT
import Gargantext.Components.Table.Types as TT
36
import Gargantext.Config.REST (AffRESTError, logRESTError)
37
import Gargantext.Hooks.Loader (useLoaderBox)
Alexandre Delanoë's avatar
Alexandre Delanoë committed
38
import Gargantext.Routes (SessionRoute(..)) as R
39
import Gargantext.Sessions (Session, get)
40
import Gargantext.Types (CTabNgramType, OrderBy(..), SearchQuery, TabType, TermList(..), TermSize, termLists, termSizes)
41
import Gargantext.Utils (queryMatchesLabel, toggleSet, sortWith)
42
import Gargantext.Utils.CacheAPI as GUC
43
import Gargantext.Utils.Reactix as R2
44
import Gargantext.Utils.Seq as Seq
James Laver's avatar
James Laver committed
45
import Gargantext.Utils.Toestand as T2
46 47 48 49
import Reactix as R
import Reactix.DOM.HTML as H
import Toestand as T
import Unsafe.Coerce (unsafeCoerce)
50

James Laver's avatar
James Laver committed
51 52
here :: R2.Here
here = R2.here "Gargantext.Components.NgramsTable"
53

54 55
type State =
  CoreState (
56
    ngramsChildren   :: Map NgramsTerm Boolean
57 58 59 60
                     -- ^ Used only when grouping.
                     --   This updates the children of `ngramsParent`,
                     --   ngrams set to `true` are to be added, and `false` to
                     --   be removed.
61
  , ngramsParent     :: Maybe NgramsTerm -- Nothing means we are not currently grouping terms
62 63 64 65 66 67
  , ngramsSelection  :: Set NgramsTerm
                     -- ^ The set of selected checkboxes of the first column.
  )

initialState :: VersionedNgramsTable -> State
initialState (Versioned {version}) = {
68
    ngramsChildren:   Map.empty
69 70 71
  , ngramsLocalPatch: mempty
  , ngramsParent:     Nothing
  , ngramsSelection:  mempty
72 73 74 75 76
  , ngramsStagePatch: mempty
  , ngramsValidPatch: mempty
  , ngramsVersion:    version
  }

77 78
setTermListSetA :: NgramsTable -> Set NgramsTerm -> TermList -> Action
setTermListSetA ngramsTable ns new_list =
79
  CoreAction $ CommitPatch $ fromNgramsPatches $ PatchMap $ mapWithIndex f $ toMap ns
80 81
  where
    f :: NgramsTerm -> Unit -> NgramsPatch
82
    f n _unit = NgramsPatch { patch_list, patch_children: mempty }
83
      where
84
        cur_list = ngramsTable ^? at n <<< _Just <<< _NgramsRepoElement <<< _list
85
        patch_list = maybe mempty (replace new_list) cur_list
86 87 88
    toMap :: forall a. Set a -> Map a Unit
    toMap = unsafeCoerce
    -- TODO https://github.com/purescript/purescript-ordered-collections/pull/21
89
    --      https://github.com/purescript/purescript-ordered-collections/pull/31
90 91
    -- toMap = Map.fromFoldable

92
type PreConversionRows = Seq.Seq NgramsElement
93

94
type TableContainerProps =
95 96 97 98 99
  ( dispatch         :: Dispatch
  , ngramsChildren   :: Map NgramsTerm Boolean
  , ngramsParent     :: Maybe NgramsTerm
  , ngramsSelection  :: Set NgramsTerm
  , ngramsTable      :: NgramsTable
100
  , path             :: T.Box PageParams
101
  , tabNgramType     :: CTabNgramType
102
  , syncResetButton  :: Array R.Element
103
  )
104

105
tableContainer :: Record TableContainerProps -> Record TT.TableContainerProps -> R.Element
106
tableContainer p q = R.createElement (tableContainerCpt p) q []
107
tableContainerCpt :: Record TableContainerProps -> R.Component TT.TableContainerProps
108 109 110 111 112
tableContainerCpt { dispatch
                  , ngramsChildren
                  , ngramsParent
                  , ngramsSelection
                  , ngramsTable: ngramsTableCache
113
                  , path
114
                  , tabNgramType
115
                  , syncResetButton
James Laver's avatar
James Laver committed
116
                  } = here.component "tableContainer" cpt
117
  where
118
    cpt props _ = do
119 120
      { searchQuery, termListFilter, termSizeFilter } <- T.useLive T.unequal path

121 122 123 124 125 126 127 128
      pure $ H.div {className: "container-fluid"} [
        R2.row
        [ H.div {className: "card col-12"}
          [ H.div {className: "card-header"}
            [
              R2.row [ H.div {className: "col-md-2", style: {marginTop: "6px"}}
                       [ H.div {} syncResetButton
                       , if A.null props.tableBody && searchQuery /= "" then
129
                       -- , if (not $ Set.member (normNgram tabNgramType searchQuery) ngramsSelection) && searchQuery /= "" then
130 131 132 133 134 135
                           H.li { className: "list-group-item" } [
                             H.button { className: "btn btn-primary"
                                      , on: { click: const $ dispatch
                                              $ CoreAction
                                              $ addNewNgramA
                                              (normNgram tabNgramType searchQuery)
136
                                              MapTerm
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
                                            }
                                      }
                             [ H.text ("Add " <> searchQuery) ]
                             ] else H.div {} []
                       ]
                     , H.div {className: "col-md-2", style: {marginTop : "6px"}}
                       [ H.li {className: "list-group-item"}
                         [ R2.select { id: "picklistmenu"
                                     , className: "form-control custom-select"
                                     , defaultValue: (maybe "" show termListFilter)
                                     , on: {change: setTermListFilter <<< read <<< R.unsafeEventValue}}
                           (map optps1 termLists)]
                       ]
                     , H.div {className: "col-md-2", style: {marginTop : "6px"}}
                       [ H.li {className: "list-group-item"}
                         [ R2.select {id: "picktermtype"
                                     , className: "form-control custom-select"
                                     , defaultValue: (maybe "" show termSizeFilter)
                                     , on: {change: setTermSizeFilter <<< read <<< R.unsafeEventValue}}
                           (map optps1 termSizes)]
                       ]
                     , H.div { className: "col-md-2", style: { marginTop: "6px" } }
                       [ H.li {className: "list-group-item"}
                         [ H.div { className: "form-inline" }
                           [ H.div { className: "form-group" }
                             [ props.pageSizeControl
                             , H.label {} [ H.text " items" ]
                               --   H.div { className: "col-md-6" } [ props.pageSizeControl ]
                               -- , H.div { className: "col-md-6" } [
                               --    ]
167 168
                             ]
                           ]
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
                         ]
                       ]
                     , H.div {className: "col-md-4", style: {marginTop : "6px", marginBottom : "1px"}}
                       [ H.li {className: "list-group-item"}
                         [ props.pageSizeDescription
                         , props.paginationLinks
                         ]
                       ]
                     ]
            ]
          , editor
          , if (selectionsExist ngramsSelection)
            then H.li {className: "list-group-item"}
                 [selectButtons true]
            else H.div {} []
184
          , H.div {id: "terms_table", className: "card-body"}
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            [ H.table {className: "table able"}
              [ H.thead {className: ""} [props.tableHead]
              , H.tbody {} props.tableBody
              ]
            , H.li {className: "list-group-item"}
              [ H.div { className: "row" }
                [ H.div { className: "col-md-4" }
                  [selectButtons (selectionsExist ngramsSelection)]
                , H.div {className: "col-md-4 col-md-offset-4"}
                  [props.paginationLinks]
                ]
              ]
            ]
          ]
        ]
      ]
201
    -- WHY setPath     f = origSetPageParams (const $ f path)
202 203
    setTermListFilter x = T.modify (_ { termListFilter = x }) path
    setTermSizeFilter x = T.modify (_ { termSizeFilter = x }) path
204
    setSelection = dispatch <<< setTermListSetA ngramsTableCache ngramsSelection
205

Alexandre Delanoë's avatar
Alexandre Delanoë committed
206
    editor = H.div {} $ maybe [] edit ngramsParent
207
      where
Alexandre Delanoë's avatar
Alexandre Delanoë committed
208
        edit ngrams = [ H.p {} [H.text $ "Editing " <> ngramsTermText ngrams]
209 210 211 212 213 214 215
                   , NTC.renderNgramsTree { ngramsTable
                                          , ngrams
                                          , ngramsStyle: []
                                          , ngramsClick
                                          , ngramsEdit
                                          }
                   , H.button { className: "btn btn-primary"
216 217
                              , on: {click: (const $ do
                                               dispatch AddTermChildren)}
218
                              } [H.text "Save"]
219
                   , H.button { className: "btn btn-primary"
220 221 222
                              , on: {click: (const $ dispatch $ SetParentResetChildren Nothing)}
                              } [H.text "Cancel"]
                   ]
223 224 225
          where
            ngramsTable = ngramsTableCache # at ngrams
                          <<< _Just
226
                          <<< _NgramsRepoElement
227 228
                          <<< _children
                          %~ applyPatchSet (patchSetFromMap ngramsChildren)
229
            ngramsClick {depth: 1, ngrams: child} = Just $ dispatch $ ToggleChild false child
230 231 232
            ngramsClick _ = Nothing
            ngramsEdit  _ = Nothing

233 234 235 236 237
    selectionsExist :: Set NgramsTerm -> Boolean
    selectionsExist = not <<< Set.isEmpty

    selectButtons false = H.div {} []
    selectButtons true =
238
      H.div {} [
239
        H.button { className: "btn btn-primary"
240
                , on: { click: const $ setSelection MapTerm }
241
                } [ H.text "Map" ]
242
        , H.button { className: "btn btn-primary"
243
                  , on: { click: const $ setSelection StopTerm }
244
                  } [ H.text "Stop" ]
245
        , H.button { className: "btn btn-primary"
246
                  , on: { click: const $ setSelection CandidateTerm }
247
                  } [ H.text "Candidate" ]
248 249
      ]

250
-- NEXT
251

252 253 254
type CommonProps =
  ( afterSync      :: Unit -> Aff Unit
  , boxes          :: Boxes
255 256
  , tabNgramType   :: CTabNgramType
  , withAutoUpdate :: Boolean
257 258
  )

259
type PropsNoReload =
James Laver's avatar
James Laver committed
260 261
  ( cacheState :: NT.CacheState
  , mTotalRows :: Maybe Int
262
  , path       :: T.Box PageParams
263
  , state      :: T.Box State
James Laver's avatar
James Laver committed
264
  , versioned  :: VersionedNgramsTable
265
  | CommonProps
266 267
  )

268
type Props =
269 270 271 272 273
  ( reloadForest   :: T2.ReloadS
  , reloadRoot     :: T2.ReloadS
  | PropsNoReload )

loadedNgramsTable :: R2.Component PropsNoReload
274
loadedNgramsTable = R.createElement loadedNgramsTableCpt
275
loadedNgramsTableCpt :: R.Component PropsNoReload
James Laver's avatar
James Laver committed
276
loadedNgramsTableCpt = here.component "loadedNgramsTable" cpt where
277 278
  cpt props@{ path } _ = do
    searchQuery <- T.useFocused (_.searchQuery) (\a b -> b { searchQuery = a }) path
279

280 281 282 283 284
    pure $ R.fragment $
      [ loadedNgramsTableHeader { searchQuery } []
      , loadedNgramsTableBody props [] ]

type LoadedNgramsTableHeaderProps =
285
  ( searchQuery :: T.Box SearchQuery )
286 287 288 289 290 291 292

loadedNgramsTableHeader :: R2.Component LoadedNgramsTableHeaderProps
loadedNgramsTableHeader = R.createElement loadedNgramsTableHeaderCpt
loadedNgramsTableHeaderCpt :: R.Component LoadedNgramsTableHeaderProps
loadedNgramsTableHeaderCpt = here.component "loadedNgramsTableHeader" cpt where
  cpt { searchQuery } _ = do
    pure $ R.fragment
293 294
      [ H.h4 { style: { textAlign : "center" } }
        [ H.span { className: "fa fa-hand-o-down" } []
295 296 297 298 299 300 301 302 303
        , H.text "Extracted Terms" ]
      , NTC.searchInput { key: "search-input"
                        , searchQuery }
      ]

loadedNgramsTableBody :: R2.Component PropsNoReload
loadedNgramsTableBody = R.createElement loadedNgramsTableBodyCpt
loadedNgramsTableBodyCpt :: R.Component PropsNoReload
loadedNgramsTableBodyCpt = here.component "loadedNgramsTableBody" cpt where
304
  cpt { afterSync
305 306
      , boxes: { errors
               , tasks }
307 308 309 310 311 312 313 314 315
      , cacheState
      , mTotalRows
      , path
      , state
      , tabNgramType
      , versioned: Versioned { data: initTable }
      , withAutoUpdate } _ = do
    state'@{ ngramsChildren, ngramsLocalPatch, ngramsParent, ngramsSelection } <- T.useLive T.unequal state
    path'@{ scoreType, termListFilter, termSizeFilter } <- T.useLive T.unequal path
316 317
    params <- T.useFocused (_.params) (\a b -> b { params = a }) path
    params'@{ orderBy } <- T.useLive T.unequal params
318 319
    searchQueryFocused <- T.useFocused (_.searchQuery) (\a b -> b { searchQuery = a }) path
    searchQuery <- T.useLive T.unequal searchQueryFocused
320

321 322 323 324 325 326 327 328 329 330 331
    let ngramsTable = applyNgramsPatches state' initTable
        rowMap (Tuple ng nre) =
          let ng_scores :: Map NgramsTerm (Additive Int)
              ng_scores = ngramsTable ^. _NgramsTable <<< _ngrams_scores
              Additive s = ng_scores ^. at ng <<< _Just
              addOcc ne =
                let Additive occurrences = sumOccurrences ngramsTable (ngramsElementToNgramsOcc ne) in
                ne # _NgramsElement <<< _occurrences .~ occurrences
          in
          addOcc <$> rowsFilter (ngramsRepoElementToNgramsElement ng s nre)
        rows :: PreConversionRows
332 333 334 335 336 337 338
        rows = ngramsTableOrderWith orderBy (Seq.mapMaybe rowMap nres)
        nres = Map.toUnfoldable (ngramsTable ^. _NgramsTable <<< _ngrams_repo_elements)
        rootOfMatch (Tuple ng nre) =
          if queryMatchesLabel searchQuery (ngramsTermText ng)
          then Just (fromMaybe ng (nre ^. _NgramsRepoElement <<< _root))
          else Nothing
        rootsWithMatches = Set.fromFoldable (Seq.mapMaybe rootOfMatch nres)
339
        rowsFilter :: NgramsElement -> Maybe NgramsElement
340 341 342
        rowsFilter ngramsElement =
          if displayRow { ngramsElement
                        , ngramsParentRoot
343
                        , rootsWithMatches
344 345 346 347 348 349 350 351 352 353 354
                        , state: state'
                        , termListFilter
                        , termSizeFilter } then
            Just ngramsElement
          else
            Nothing

        performAction = mkDispatch { filteredRows
                                   , path: path'
                                   , state
                                   , state' }
355

356 357 358 359 360 361 362 363 364 365 366 367 368
        -- filteredRows :: PreConversionRows
        -- no need to filter offset if cache is off
        filteredRows = if cacheState == NT.CacheOn then TT.filterRows { params: params' } rows else rows
        filteredConvertedRows :: TT.Rows
        filteredConvertedRows = convertRow <$> filteredRows

        convertRow ngramsElement =
          { row: NTC.renderNgramsItem { dispatch: performAction
                                      , ngrams: ngramsElement ^. _NgramsElement <<< _ngrams
                                      , ngramsElement
                                      , ngramsLocalPatch
                                      , ngramsParent
                                      , ngramsSelection
369
                                      , ngramsTable } []
370 371 372 373 374
          , delete: false
          }

        allNgramsSelected = allNgramsSelectedOnFirstPage ngramsSelection filteredRows

375 376
        totalRecords = fromMaybe (Seq.length rows) mTotalRows

377
        afterSync' _ = do
378
          chartsAfterSync path' errors tasks unit
379
          afterSync unit
380

381 382 383
        syncResetButton = syncResetButtons { afterSync: afterSync'
                                           , ngramsLocalPatch
                                           , performAction: performAction <<< CoreAction }
384 385

        -- autoUpdate :: Array R.Element
386 387 388 389 390 391 392 393
--         autoUpdate = if withAutoUpdate then
--                        [ R2.buff
--                        $ autoUpdateElt
--                          { duration: 5000
--                          , effect: performAction $ CoreAction $ Synchronize { afterSync: afterSync' }
--                          }
--                        ]
--                      else []
394

395 396 397 398 399 400 401 402
        ngramsParentRoot :: Maybe NgramsTerm
        ngramsParentRoot =
          (\np -> ngramsTable ^? at np
                            <<< _Just
                            <<< _NgramsRepoElement
                            <<< _root
                            <<< _Just
            ) =<< ngramsParent
403

404 405 406 407 408 409 410 411 412 413
    pure $ R.fragment
      [ TT.table
        { colNames
        , container: tableContainer
          { dispatch: performAction
          , ngramsChildren
          , ngramsParent
          , ngramsSelection
          , ngramsTable
          , path
414
          , syncResetButton: [ syncResetButton ]
415 416 417 418 419 420 421 422
          , tabNgramType }
        , params
        , rows: filteredConvertedRows
        , syncResetButton: [ syncResetButton ]
        , totalRecords
        , wrapColElts:
          wrapColElts { allNgramsSelected, dispatch: performAction, ngramsSelection } scoreType
        }
423
      , syncResetButton
James Laver's avatar
James Laver committed
424
      ]
425
      where
426
        colNames = TT.ColumnName <$> ["Show", "Select", "Map", "Stop", "Terms", "Score"] -- see convOrderBy
427

428 429 430 431 432 433 434
ngramsTableOrderWith orderBy =
  case convOrderBy <$> orderBy of
    Just ScoreAsc  -> sortWith \x -> x        ^. _NgramsElement <<< _occurrences
    Just ScoreDesc -> sortWith \x -> Down $ x ^. _NgramsElement <<< _occurrences
    Just TermAsc   -> sortWith \x -> x        ^. _NgramsElement <<< _ngrams
    Just TermDesc  -> sortWith \x -> Down $ x ^. _NgramsElement <<< _ngrams
    _              -> identity -- the server ordering is enough here
435

436 437 438 439
-- This is used to *decorate* the Select header with the checkbox.
wrapColElts scProps _         (TT.ColumnName "Select") = const [NTC.selectionCheckbox scProps]
wrapColElts _       scoreType (TT.ColumnName "Score")  = (_ <> [H.text ("(" <> show scoreType <> ")")])
wrapColElts _       _         _                        = identity
440

441 442 443
type MkDispatchProps = (
    filteredRows :: PreConversionRows
  , path         :: PageParams
444 445
  , state        :: T.Box State
  , state'       :: State
446 447 448 449 450
  )

mkDispatch :: Record MkDispatchProps -> (Action -> Effect Unit)
mkDispatch { filteredRows
           , path
451
           , state
452 453 454
           , state': { ngramsChildren
                     , ngramsParent
                     , ngramsSelection } } = performAction
455 456 457 458
  where
    allNgramsSelected = allNgramsSelectedOnFirstPage ngramsSelection filteredRows

    setParentResetChildren :: Maybe NgramsTerm -> State -> State
459
    setParentResetChildren p = _ { ngramsParent = p, ngramsChildren = Map.empty }
460 461 462

    performAction :: Action -> Effect Unit
    performAction (SetParentResetChildren p) =
463
      T.modify_ (setParentResetChildren p) state
464
    performAction (ToggleChild b c) =
465
      T.modify_ (\s@{ ngramsChildren: nc } -> s { ngramsChildren = newNC nc }) state
466 467 468
      where
        newNC nc = Map.alter (maybe (Just b) (const Nothing)) c nc
    performAction (ToggleSelect c) =
469
      T.modify_ (\s@{ ngramsSelection: ns } -> s { ngramsSelection = toggleSet c ns }) state
470
    performAction ToggleSelectAll =
471
      T.modify_ toggler state
472 473 474 475 476 477
      where
        toggler s =
          if allNgramsSelected then
            s { ngramsSelection = Set.empty :: Set NgramsTerm }
          else
            s { ngramsSelection = selectNgramsOnFirstPage filteredRows }
478
    performAction AddTermChildren = do
479 480 481 482 483
      case ngramsParent of
        Nothing ->
          -- impossible but harmless
          pure unit
        Just parent -> do
484
          here.log2 "[performAction] AddTermChildren, parent" parent
Alexandre Delanoë's avatar
Alexandre Delanoë committed
485
          here.log2 "[performAction] AddTermChildren, ngramsChildren" ngramsChildren
486 487 488
          let pc = patchSetFromMap ngramsChildren
              pe = NgramsPatch { patch_list: mempty, patch_children: pc }
              pt = singletonNgramsTablePatch parent pe
489
          T.modify_ (setParentResetChildren Nothing) state
490 491 492 493 494 495 496 497 498
          here.log2 "[performAction] pt" pt
          let ppt = case (A.head $ Set.toUnfoldable $ Map.keys ngramsChildren) of
                Nothing -> mempty
                Just h  ->
                  let pp = NgramsPatch { patch_list: mempty
                                       , patch_children: patchSetFromMap $ Map.mapMaybe (\v -> Just $ not v) ngramsChildren }
                  in
                  singletonNgramsTablePatch h pp
          here.log2 "[performAction] pt with patchSetFromMap" $ pt <> ppt
499
          commitPatch (pt {-<> ppt-}) state
500 501 502 503 504
    performAction (CoreAction a) = coreDispatch path state a


displayRow :: { ngramsElement    :: NgramsElement
              , ngramsParentRoot :: Maybe NgramsTerm
505
              , rootsWithMatches :: Set NgramsTerm
506 507 508 509 510
              , state            :: State
              , termListFilter   :: Maybe TermList
              , termSizeFilter   :: Maybe TermSize } -> Boolean
displayRow { ngramsElement: NgramsElement {ngrams, root, list}
           , ngramsParentRoot
511 512 513
           , state: { ngramsChildren
                    , ngramsLocalPatch
                    , ngramsParent }
514
           , rootsWithMatches
515 516
           , termListFilter
           , termSizeFilter } =
517 518 519 520 521 522 523 524
    -- See these issues about the evolution of this filtering.
    -- * https://gitlab.iscpif.fr/gargantext/purescript-gargantext/issues/340
    -- * https://gitlab.iscpif.fr/gargantext/haskell-gargantext/issues/87
       isNothing root
    -- ^ Display only nodes without parents.
    && Set.member ngrams rootsWithMatches
    -- ^ and which matches the search query.
    && maybe true (_ == list) termListFilter
525 526 527 528 529 530 531
    -- ^ and which matches the ListType filter.
    && ngramsChildren ^. at ngrams /= Just true
    -- ^ and which are not scheduled to be added already
    && Just ngrams /= ngramsParent
    -- ^ and which are not our new parent
    && Just ngrams /= ngramsParentRoot
    -- ^ and which are not the root of our new parent
532 533
    && filterTermSize termSizeFilter ngrams
    -- ^ and which satisfies the chosen term size
534 535 536 537
    || ngramsChildren ^. at ngrams == Just false
    -- ^ unless they are scheduled to be removed.
    || NTC.tablePatchHasNgrams ngramsLocalPatch ngrams
    -- ^ unless they are being processed at the moment.
538

539 540 541 542
allNgramsSelectedOnFirstPage :: Set NgramsTerm -> PreConversionRows -> Boolean
allNgramsSelectedOnFirstPage selected rows = selected == (selectNgramsOnFirstPage rows)

selectNgramsOnFirstPage :: PreConversionRows -> Set NgramsTerm
543
selectNgramsOnFirstPage rows = Set.fromFoldable $ (view $ _NgramsElement <<< _ngrams) <$> rows
544 545


546
type MainNgramsTableProps = (
547 548
    cacheState    :: T.Box NT.CacheState
  , defaultListId :: Int
549
    -- ^ This node can be a corpus or contact.
550 551 552
  , path          :: T.Box PageParams
  , session       :: Session
  , tabType       :: TabType
553
  | CommonProps
554
  )
555

556 557
mainNgramsTable :: R2.Component MainNgramsTableProps
mainNgramsTable = R.createElement mainNgramsTableCpt
558
mainNgramsTableCpt :: R.Component MainNgramsTableProps
James Laver's avatar
James Laver committed
559
mainNgramsTableCpt = here.component "mainNgramsTable" cpt
560
  where
561
    cpt props@{ cacheState } _ = do
562
      cacheState' <- T.useLive T.unequal cacheState
563 564

      -- let path = initialPageParams session nodeId [defaultListId] tabType
565

566
      case cacheState' of
567 568 569 570 571 572 573 574 575 576 577 578 579
        NT.CacheOn -> pure $ mainNgramsTableCacheOn props []
        NT.CacheOff -> pure $ mainNgramsTableCacheOff props []

mainNgramsTableCacheOn :: R2.Component MainNgramsTableProps
mainNgramsTableCacheOn = R.createElement mainNgramsTableCacheOnCpt
mainNgramsTableCacheOnCpt :: R.Component MainNgramsTableProps
mainNgramsTableCacheOnCpt = here.component "mainNgramsTableCacheOn" cpt where
  cpt { afterSync
      , boxes
      , defaultListId
      , path
      , tabNgramType
      , withAutoUpdate } _ = do
580

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    -- let path = initialPageParams session nodeId [defaultListId] tabType

    path' <- T.useLive T.unequal path
    let render versioned = mainNgramsTablePaint { afterSync
                                                , boxes
                                                , cacheState: NT.CacheOn
                                                , path
                                                , tabNgramType
                                                , versioned
                                                , withAutoUpdate } []
    useLoaderWithCacheAPI {
        cacheEndpoint: versionEndpoint { defaultListId, path: path' }
      , errorHandler
      , handleResponse
      , mkRequest
      , path: path'
      , renderer: render
      }
  versionEndpoint { defaultListId, path: { nodeId, tabType, session } } _ = get session $ R.GetNgramsTableVersion { listId: defaultListId, tabType } (Just nodeId)
600
  errorHandler = logRESTError here "[mainNgramsTable]"
601 602 603 604 605 606 607 608 609 610 611 612
  mkRequest :: PageParams -> GUC.Request
  mkRequest path@{ session } = GUC.makeGetRequest session $ url path
    where
      url { listIds
          , nodeId
          , tabType
          } = R.GetNgramsTableAll { listIds
                                  , tabType } (Just nodeId)
  handleResponse :: VersionedNgramsTable -> VersionedNgramsTable
  handleResponse v = v

mainNgramsTableCacheOff :: R2.Component MainNgramsTableProps
613
mainNgramsTableCacheOff = R.createElement mainNgramsTableCacheOffCpt
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
mainNgramsTableCacheOffCpt :: R.Component MainNgramsTableProps
mainNgramsTableCacheOffCpt = here.component "mainNgramsTableCacheOff" cpt where
  cpt { afterSync
      , boxes
      , defaultListId
      , path
      , tabNgramType
      , withAutoUpdate } _ = do
    let render versionedWithCount = mainNgramsTablePaintNoCache { afterSync
                                                                , boxes
                                                                , cacheState: NT.CacheOff
                                                                , path
                                                                , tabNgramType
                                                                , versionedWithCount
                                                                , withAutoUpdate } []
    useLoaderBox { errorHandler
                 , loader
                 , path
                 , render }

634
  errorHandler = logRESTError here "[mainNgramsTable]"
635 636

  -- NOTE With cache off
637
  loader :: PageParams -> AffRESTError VersionedWithCountNgramsTable
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
  loader { listIds
         , nodeId
         , params: { limit, offset }
         , searchQuery
         , session
         , tabType
         , termListFilter
         , termSizeFilter
         } =
    get session $ R.GetNgrams params (Just nodeId)
    where
      params = { limit
               , listIds
               , offset: Just offset
               , orderBy: Nothing  -- TODO
               , searchQuery
               , tabType
               , termListFilter
               , termSizeFilter
               }

659

660
type MainNgramsTablePaintProps = (
661 662 663
    cacheState :: NT.CacheState
  , path       :: T.Box PageParams
  , versioned  :: VersionedNgramsTable
664
  | CommonProps
665 666
  )

667 668
mainNgramsTablePaint :: R2.Component MainNgramsTablePaintProps
mainNgramsTablePaint = R.createElement mainNgramsTablePaintCpt
669
mainNgramsTablePaintCpt :: R.Component MainNgramsTablePaintProps
James Laver's avatar
James Laver committed
670
mainNgramsTablePaintCpt = here.component "mainNgramsTablePaint" cpt
671
  where
672
    cpt { afterSync
673
        , boxes
674 675 676 677 678
        , cacheState
        , path
        , tabNgramType
        , versioned
        , withAutoUpdate } _ = do
679
      state <- T.useBox $ initialState versioned
680

681
      pure $ loadedNgramsTable { afterSync
682
                               , boxes
683
                               , cacheState
684
                               , mTotalRows: Nothing
685
                               , path
686 687 688 689
                               , state
                               , tabNgramType
                               , versioned
                               , withAutoUpdate
690
                               } []
691

692 693
type MainNgramsTablePaintNoCacheProps = (
    cacheState         :: NT.CacheState
694
  , path               :: T.Box PageParams
695
  , versionedWithCount :: VersionedWithCountNgramsTable
696
  | CommonProps
697 698
  )

699 700
mainNgramsTablePaintNoCache :: R2.Component MainNgramsTablePaintNoCacheProps
mainNgramsTablePaintNoCache = R.createElement mainNgramsTablePaintNoCacheCpt
701
mainNgramsTablePaintNoCacheCpt :: R.Component MainNgramsTablePaintNoCacheProps
James Laver's avatar
James Laver committed
702
mainNgramsTablePaintNoCacheCpt = here.component "mainNgramsTablePaintNoCache" cpt
703
  where
704
    cpt { afterSync
705
        , boxes
706 707 708 709 710
        , cacheState
        , path
        , tabNgramType
        , versionedWithCount
        , withAutoUpdate } _ = do
711
      -- TODO This is lame, make versionedWithCount a proper box?
712 713
      let count /\ versioned = toVersioned versionedWithCount

714
      state <- T.useBox $ initialState versioned
715

716 717 718 719 720 721 722 723 724
      pure $ loadedNgramsTable { afterSync
                               , boxes
                               , cacheState
                               , mTotalRows: Just count
                               , path
                               , state
                               , tabNgramType
                               , versioned
                               , withAutoUpdate } []
725

Nicolas Pouillard's avatar
Nicolas Pouillard committed
726 727 728 729 730 731
type NgramsOcc = { occurrences :: Additive Int, children :: Set NgramsTerm }

ngramsElementToNgramsOcc :: NgramsElement -> NgramsOcc
ngramsElementToNgramsOcc (NgramsElement {occurrences, children}) = {occurrences: Additive occurrences, children}

sumOccurrences :: NgramsTable -> NgramsOcc -> Additive Int
732
sumOccurrences nt = sumOccChildren mempty
733
    where
734 735 736 737 738 739 740 741 742 743 744
      sumOccTerm :: Set NgramsTerm -> NgramsTerm -> Additive Int
      sumOccTerm seen label
        | Set.member label seen = Additive 0 -- TODO: Should not happen, emit a warning/error.
        | otherwise =
            sumOccChildren (Set.insert label seen)
                           { occurrences: nt ^. _NgramsTable <<< _ngrams_scores <<< ix label
                           , children:    nt ^. ix label <<< _NgramsRepoElement <<< _children
                           }
      sumOccChildren :: Set NgramsTerm -> NgramsOcc -> Additive Int
      sumOccChildren seen {occurrences, children} =
        occurrences <> children ^. folded <<< to (sumOccTerm seen)
745

746
optps1 :: forall a. Show a => { desc :: String, mval :: Maybe a } -> R.Element
747
optps1 { desc, mval } = H.option { value: value } [H.text desc]
748
  where value = maybe "" show mval