NgramsTable.purs 29.7 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.AutoUpdate (autoUpdateElt)
31
import Gargantext.Components.NgramsTable.Components as NTC
32
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)
33
import Gargantext.Components.NgramsTable.Loader (useLoaderWithCacheAPI)
34
import Gargantext.Components.Nodes.Lists.Types as NT
35 36
import Gargantext.Components.Table as TT
import Gargantext.Components.Table.Types as TT
37
import Gargantext.Config.REST (RESTError, logRESTError)
38
import Gargantext.Hooks.Loader (useLoaderBox)
Alexandre Delanoë's avatar
Alexandre Delanoë committed
39
import Gargantext.Routes (SessionRoute(..)) as R
40
import Gargantext.Sessions (Session, get)
41
import Gargantext.Types (CTabNgramType, OrderBy(..), SearchQuery, TabType, TermList(..), TermSize, termLists, termSizes)
42
import Gargantext.Utils (queryMatchesLabel, toggleSet, sortWith)
43
import Gargantext.Utils.CacheAPI as GUC
44
import Gargantext.Utils.Reactix as R2
45
import Gargantext.Utils.Seq as Seq
James Laver's avatar
James Laver committed
46
import Gargantext.Utils.Toestand as T2
47 48 49 50
import Reactix as R
import Reactix.DOM.HTML as H
import Toestand as T
import Unsafe.Coerce (unsafeCoerce)
51

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

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

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

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

93
type PreConversionRows = Seq.Seq NgramsElement
94

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

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

122 123 124 125 126 127 128 129 130 131 132 133 134 135
      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
                           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

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

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

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

249
-- NEXT
250

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

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

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

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

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

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

loadedNgramsTableHeader :: R2.Component LoadedNgramsTableHeaderProps
loadedNgramsTableHeader = R.createElement loadedNgramsTableHeaderCpt
loadedNgramsTableHeaderCpt :: R.Component LoadedNgramsTableHeaderProps
loadedNgramsTableHeaderCpt = here.component "loadedNgramsTableHeader" cpt where
  cpt { searchQuery } _ = do
    pure $ R.fragment
292 293
      [ H.h4 { style: { textAlign : "center" } }
        [ H.span { className: "fa fa-hand-o-down" } []
294 295 296 297 298 299 300 301 302
        , 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
303
  cpt { afterSync
304 305
      , boxes: { errors
               , tasks }
306 307 308 309 310 311 312 313 314
      , 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
315 316 317 318 319
    params <- T.useFocused (_.params) (\a b -> b { params = a }) path
    params'@{ orderBy } <- T.useLive T.unequal params
    searchQuery <- T.useFocused (_.searchQuery) (\a b -> b { searchQuery = a }) path
    searchQuery' <- T.useLive T.unequal searchQuery

320 321 322 323 324 325 326 327 328 329 330 331 332
    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
        rows = ngramsTableOrderWith orderBy (
                 Seq.mapMaybe rowMap $
333 334 335
                   Map.toUnfoldable (ngramsTable ^. _NgramsTable <<< _ngrams_repo_elements)
               )
        rowsFilter :: NgramsElement -> Maybe NgramsElement
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        rowsFilter ngramsElement =
          if displayRow { ngramsElement
                        , ngramsParentRoot
                        , searchQuery: searchQuery'
                        , state: state'
                        , termListFilter
                        , termSizeFilter } then
            Just ngramsElement
          else
            Nothing

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

352 353 354 355 356 357 358 359 360 361 362 363 364
        -- 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
365
                                      , ngramsTable } []
366 367 368 369 370
          , delete: false
          }

        allNgramsSelected = allNgramsSelectedOnFirstPage ngramsSelection filteredRows

371 372
        totalRecords = fromMaybe (Seq.length rows) mTotalRows

373
        afterSync' _ = do
374
          chartsAfterSync path' errors tasks unit
375
          afterSync unit
376

377 378 379
        syncResetButton = syncResetButtons { afterSync: afterSync'
                                           , ngramsLocalPatch
                                           , performAction: performAction <<< CoreAction }
380 381

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

391 392 393 394 395 396 397 398
        ngramsParentRoot :: Maybe NgramsTerm
        ngramsParentRoot =
          (\np -> ngramsTable ^? at np
                            <<< _Just
                            <<< _NgramsRepoElement
                            <<< _root
                            <<< _Just
            ) =<< ngramsParent
399

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

424 425 426 427 428 429 430
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
431

432 433 434 435
-- 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
436

437 438 439
type MkDispatchProps = (
    filteredRows :: PreConversionRows
  , path         :: PageParams
440 441
  , state        :: T.Box State
  , state'       :: State
442 443 444 445 446
  )

mkDispatch :: Record MkDispatchProps -> (Action -> Effect Unit)
mkDispatch { filteredRows
           , path
447
           , state
448 449 450
           , state': { ngramsChildren
                     , ngramsParent
                     , ngramsSelection } } = performAction
451 452 453 454
  where
    allNgramsSelected = allNgramsSelectedOnFirstPage ngramsSelection filteredRows

    setParentResetChildren :: Maybe NgramsTerm -> State -> State
455
    setParentResetChildren p = _ { ngramsParent = p, ngramsChildren = Map.empty }
456 457 458

    performAction :: Action -> Effect Unit
    performAction (SetParentResetChildren p) =
459
      T.modify_ (setParentResetChildren p) state
460
    performAction (ToggleChild b c) =
461
      T.modify_ (\s@{ ngramsChildren: nc } -> s { ngramsChildren = newNC nc }) state
462 463 464
      where
        newNC nc = Map.alter (maybe (Just b) (const Nothing)) c nc
    performAction (ToggleSelect c) =
465
      T.modify_ (\s@{ ngramsSelection: ns } -> s { ngramsSelection = toggleSet c ns }) state
466
    performAction ToggleSelectAll =
467
      T.modify_ toggler state
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
      where
        toggler s =
          if allNgramsSelected then
            s { ngramsSelection = Set.empty :: Set NgramsTerm }
          else
            s { ngramsSelection = selectNgramsOnFirstPage filteredRows }
    performAction AddTermChildren =
      case ngramsParent of
        Nothing ->
          -- impossible but harmless
          pure unit
        Just parent -> do
          let pc = patchSetFromMap ngramsChildren
              pe = NgramsPatch { patch_list: mempty, patch_children: pc }
              pt = singletonNgramsTablePatch parent pe
483 484 485 486 487 488 489 490 491 492 493 494 495
          T.modify_ (setParentResetChildren Nothing) state
          commitPatch pt state
    performAction (CoreAction a) = coreDispatch path state a


displayRow :: { ngramsElement    :: NgramsElement
              , ngramsParentRoot :: Maybe NgramsTerm
              , searchQuery      :: SearchQuery
              , state            :: State
              , termListFilter   :: Maybe TermList
              , termSizeFilter   :: Maybe TermSize } -> Boolean
displayRow { ngramsElement: NgramsElement {ngrams, root, list}
           , ngramsParentRoot
496 497 498
           , state: { ngramsChildren
                    , ngramsLocalPatch
                    , ngramsParent }
499 500 501
           , searchQuery
           , termListFilter
           , termSizeFilter } =
502
  (
503
    -- isNothing root
504
    -- ^ Display only nodes without parents
505 506
    -- ^^ (?) allow child nodes to be searched (see #340)
       maybe true (_ == list) termListFilter
507 508 509 510 511 512 513
    -- ^ 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
514 515
    && filterTermSize termSizeFilter ngrams
    -- ^ and which satisfies the chosen term size
516 517 518 519 520 521 522
    || ngramsChildren ^. at ngrams == Just false
    -- ^ unless they are scheduled to be removed.
    || NTC.tablePatchHasNgrams ngramsLocalPatch ngrams
    -- ^ unless they are being processed at the moment.
  )
    && queryMatchesLabel searchQuery (ngramsTermText ngrams)
    -- ^ and which matches the search query.
523

524

525 526 527 528
allNgramsSelectedOnFirstPage :: Set NgramsTerm -> PreConversionRows -> Boolean
allNgramsSelectedOnFirstPage selected rows = selected == (selectNgramsOnFirstPage rows)

selectNgramsOnFirstPage :: PreConversionRows -> Set NgramsTerm
529
selectNgramsOnFirstPage rows = Set.fromFoldable $ (view $ _NgramsElement <<< _ngrams) <$> rows
530 531


532
type MainNgramsTableProps = (
533 534
    cacheState    :: T.Box NT.CacheState
  , defaultListId :: Int
535
    -- ^ This node can be a corpus or contact.
536 537 538
  , path          :: T.Box PageParams
  , session       :: Session
  , tabType       :: TabType
539
  | CommonProps
540
  )
541

542 543
mainNgramsTable :: R2.Component MainNgramsTableProps
mainNgramsTable = R.createElement mainNgramsTableCpt
544
mainNgramsTableCpt :: R.Component MainNgramsTableProps
James Laver's avatar
James Laver committed
545
mainNgramsTableCpt = here.component "mainNgramsTable" cpt
546
  where
547
    cpt props@{ cacheState } _ = do
548
      cacheState' <- T.useLive T.unequal cacheState
549 550

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

552
      case cacheState' of
553 554 555 556 557 558 559 560 561 562 563 564 565
        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
566

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    -- 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)
586
  errorHandler = logRESTError here "[mainNgramsTable]"
587 588 589 590 591 592 593 594 595 596 597 598
  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
599
mainNgramsTableCacheOff = R.createElement mainNgramsTableCacheOffCpt
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
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 }

620
  errorHandler = logRESTError here "[mainNgramsTable]"
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

  -- NOTE With cache off
  loader :: PageParams -> Aff (Either RESTError VersionedWithCountNgramsTable)
  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
               }

645

646
type MainNgramsTablePaintProps = (
647 648 649
    cacheState :: NT.CacheState
  , path       :: T.Box PageParams
  , versioned  :: VersionedNgramsTable
650
  | CommonProps
651 652
  )

653 654
mainNgramsTablePaint :: R2.Component MainNgramsTablePaintProps
mainNgramsTablePaint = R.createElement mainNgramsTablePaintCpt
655
mainNgramsTablePaintCpt :: R.Component MainNgramsTablePaintProps
James Laver's avatar
James Laver committed
656
mainNgramsTablePaintCpt = here.component "mainNgramsTablePaint" cpt
657
  where
658
    cpt { afterSync
659
        , boxes
660 661 662 663 664
        , cacheState
        , path
        , tabNgramType
        , versioned
        , withAutoUpdate } _ = do
665
      state <- T.useBox $ initialState versioned
666

667
      pure $ loadedNgramsTable { afterSync
668
                               , boxes
669
                               , cacheState
670
                               , mTotalRows: Nothing
671
                               , path
672 673 674 675
                               , state
                               , tabNgramType
                               , versioned
                               , withAutoUpdate
676
                               } []
677

678 679
type MainNgramsTablePaintNoCacheProps = (
    cacheState         :: NT.CacheState
680
  , path               :: T.Box PageParams
681
  , versionedWithCount :: VersionedWithCountNgramsTable
682
  | CommonProps
683 684
  )

685 686
mainNgramsTablePaintNoCache :: R2.Component MainNgramsTablePaintNoCacheProps
mainNgramsTablePaintNoCache = R.createElement mainNgramsTablePaintNoCacheCpt
687
mainNgramsTablePaintNoCacheCpt :: R.Component MainNgramsTablePaintNoCacheProps
James Laver's avatar
James Laver committed
688
mainNgramsTablePaintNoCacheCpt = here.component "mainNgramsTablePaintNoCache" cpt
689
  where
690
    cpt { afterSync
691
        , boxes
692 693 694 695 696
        , cacheState
        , path
        , tabNgramType
        , versionedWithCount
        , withAutoUpdate } _ = do
697
      -- TODO This is lame, make versionedWithCount a proper box?
698 699
      let count /\ versioned = toVersioned versionedWithCount

700
      state <- T.useBox $ initialState versioned
701

702 703 704 705 706 707 708 709 710
      pure $ loadedNgramsTable { afterSync
                               , boxes
                               , cacheState
                               , mTotalRows: Just count
                               , path
                               , state
                               , tabNgramType
                               , versioned
                               , withAutoUpdate } []
711

Nicolas Pouillard's avatar
Nicolas Pouillard committed
712 713 714 715 716 717
type NgramsOcc = { occurrences :: Additive Int, children :: Set NgramsTerm }

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

sumOccurrences :: NgramsTable -> NgramsOcc -> Additive Int
718
sumOccurrences nt = sumOccChildren mempty
719
    where
720 721 722 723 724 725 726 727 728 729 730
      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)
731

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