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

6
import Data.Array as A
7
import Data.FunctorWithIndex (mapWithIndex)
8
import Data.Lens (Lens', to, (%~), (.~), (^.), (^?))
9
import Data.Lens.At (at)
10
import Data.Lens.Common (_Just)
11
import Data.Lens.Fold (folded)
12
import Data.Lens.Index (ix)
13
import Data.Lens.Record (prop)
14
import Data.List (List, filter, length) as L
15 16
import Data.Map (Map)
import Data.Map as Map
17
import Data.Maybe (Maybe(..), isNothing, maybe)
18
import Data.Monoid.Additive (Additive(..))
19
import Data.Ord.Down (Down(..))
20 21
import Data.Set (Set)
import Data.Set as Set
22
import Data.Symbol (SProxy(..))
23
import Data.Tuple (Tuple(..), fst, snd)
24
import Data.Tuple.Nested ((/\))
25
import Effect (Effect)
26
import Effect.Aff (Aff)
27
import Gargantext.Components.AutoUpdate (autoUpdateElt)
28
import Gargantext.Components.NgramsTable.Components as NTC
29
import Gargantext.Components.NgramsTable.Core
30
import Gargantext.Components.NgramsTable.Loader (useLoaderWithCacheAPI)
31
import Gargantext.Components.Table as T
32
import Gargantext.Prelude (class Show, Unit, bind, const, discard, identity, map, mempty, not, pure, show, unit, (#), ($), (&&), (/=), (<$>), (<<<), (<>), (=<<), (==), (||), read)
Alexandre Delanoë's avatar
Alexandre Delanoë committed
33
import Gargantext.Routes (SessionRoute(..)) as R
34
import Gargantext.Sessions (Session, get)
35
import Gargantext.Types (CTabNgramType, OrderBy(..), SearchQuery, TabType, TermList(..), TermSize, termLists, termSizes)
36
import Gargantext.Utils (queryMatchesLabel, toggleSet)
37
import Gargantext.Utils.CacheAPI as GUC
38
import Gargantext.Utils.List (sortWith) as L
39
import Gargantext.Utils.Reactix as R2
Alexandre Delanoë's avatar
Alexandre Delanoë committed
40 41 42
import Reactix (Component, Element, State, createElement, fragment, hooksComponent, useState') as R
import Reactix.DOM.HTML as H
import Unsafe.Coerce (unsafeCoerce)
43

44
type State' =
45 46
  CoreState
  ( ngramsParent     :: Maybe NgramsTerm -- Nothing means we are not currently grouping terms
47 48 49 50 51
  , ngramsChildren   :: Map NgramsTerm Boolean
                     -- ^ Used only when grouping.
                     --   This updates the children of `ngramsParent`,
                     --   ngrams set to `true` are to be added, and `false` to
                     --   be removed.
52 53
  , ngramsSelection  :: Set NgramsTerm
                     -- ^ The set of selected checkboxes of the first column.
54
  )
55

56
_ngramsChildren :: forall row. Lens' { ngramsChildren :: Map NgramsTerm Boolean | row } (Map NgramsTerm Boolean)
57 58
_ngramsChildren = prop (SProxy :: SProxy "ngramsChildren")

59 60 61
_ngramsSelection :: forall row. Lens' { ngramsSelection :: Set NgramsTerm | row } (Set NgramsTerm)
_ngramsSelection = prop (SProxy :: SProxy "ngramsSelection")

62 63
initialState' :: VersionedNgramsTable -> State'
initialState' (Versioned {version}) =
64 65 66 67
  { ngramsChildren:   mempty
  , ngramsLocalPatch: mempty
  , ngramsParent:     Nothing
  , ngramsSelection:  mempty
68 69
  , ngramsStagePatch: mempty
  , ngramsValidPatch: mempty
70
  , ngramsVersion:    version
71 72
  }

73 74
type State =
  CoreState (
75
    ngramsChildren   :: Map NgramsTerm Boolean
76 77 78 79
                     -- ^ Used only when grouping.
                     --   This updates the children of `ngramsParent`,
                     --   ngrams set to `true` are to be added, and `false` to
                     --   be removed.
80
  , ngramsParent     :: Maybe NgramsTerm -- Nothing means we are not currently grouping terms
81 82 83 84 85 86
  , ngramsSelection  :: Set NgramsTerm
                     -- ^ The set of selected checkboxes of the first column.
  )

initialState :: VersionedNgramsTable -> State
initialState (Versioned {version}) = {
87 88 89 90
    ngramsChildren:   mempty
  , ngramsLocalPatch: mempty
  , ngramsParent:     Nothing
  , ngramsSelection:  mempty
91 92 93 94 95
  , ngramsStagePatch: mempty
  , ngramsValidPatch: mempty
  , ngramsVersion:    version
  }

96 97 98 99 100 101 102 103
setTermListSetA :: NgramsTable -> Set NgramsTerm -> TermList -> Action
setTermListSetA ngramsTable ns new_list =
  CommitPatch $ fromNgramsPatches $ PatchMap $ mapWithIndex f $ toMap ns
  where
    f :: NgramsTerm -> Unit -> NgramsPatch
    f n unit = NgramsPatch { patch_list, patch_children: mempty }
      where
        cur_list = ngramsTable ^? at n <<< _Just <<< _NgramsElement <<< _list
104
        patch_list = maybe mempty (\c -> replace c new_list) cur_list
105 106 107 108 109 110 111
    toMap :: forall a. Set a -> Map a Unit
    toMap = unsafeCoerce
    -- TODO https://github.com/purescript/purescript-ordered-collections/pull/21
    -- toMap = Map.fromFoldable

addNewNgramA :: NgramsTerm -> Action
addNewNgramA ngram = CommitPatch $ addNewNgram ngram CandidateTerm
112

113
type PreConversionRows = L.List (Tuple NgramsTerm NgramsElement)
114

115
type TableContainerProps =
116 117 118 119 120 121 122
  ( dispatch         :: Dispatch
  , ngramsChildren   :: Map NgramsTerm Boolean
  , ngramsParent     :: Maybe NgramsTerm
  , ngramsSelection  :: Set NgramsTerm
  , ngramsTable      :: NgramsTable
  , path             :: R.State PageParams
  , tabNgramType     :: CTabNgramType
123
  )
124

125 126 127 128 129 130 131 132 133 134 135 136 137
tableContainer :: Record TableContainerProps -> Record T.TableContainerProps -> R.Element
tableContainer p q = R.createElement (tableContainerCpt p) q []

tableContainerCpt :: Record TableContainerProps -> R.Component T.TableContainerProps
tableContainerCpt { dispatch
                  , ngramsChildren
                  , ngramsParent
                  , ngramsSelection
                  , ngramsTable: ngramsTableCache
                  , path: {searchQuery, termListFilter, termSizeFilter} /\ setPath
                  , tabNgramType
                  } = R.hooksComponent "G.C.NT.tableContainer" cpt
  where
138
    cpt props _ = do
139 140 141 142
      pure $ H.div {className: "container-fluid"} [
        H.div {className: "jumbotron1"}
        [ R2.row
          [ H.div {className: "panel panel-default"}
143 144 145 146 147 148
            [ H.div {className: "panel-heading"} [
              R2.row
              [ H.div {className: "col-md-2", style: {marginTop: "6px"}}
                [
                  if A.null props.tableBody && searchQuery /= "" then
                    H.li { className: "list-group-item" } [
149
                      H.button { className: "btn btn-primary"
150 151 152 153 154
                                , on: { click: const $ dispatch
                                      $ addNewNgramA
                                      $ normNgram tabNgramType searchQuery
                                      }
                                }
155
                      [ H.text ("Add " <> searchQuery) ]
156 157 158 159 160 161 162
                    ] 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)
163
                              , on: {change: setTermListFilter <<< read <<< R2.unsafeEventValue}}
164 165 166 167 168 169 170
                    (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)
171
                              , on: {change: setTermSizeFilter <<< read <<< R2.unsafeEventValue}}
172 173 174 175 176 177 178 179 180 181 182 183 184
                    (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" } [
                    --    ]
                    ]
                    ]
185
                  ]
186
                ]
187 188 189 190 191 192 193
              , H.div {className: "col-md-4", style: {marginTop : "6px", marginBottom : "1px"}} [
                   H.li {className: "list-group-item"} [
                        props.pageSizeDescription
                      , props.paginationLinks
                      ]
                   ]
              ]
194
              ]
195
            , editor
196 197 198 199 200
            , if (selectionsExist ngramsSelection) then
                H.li {className: "list-group-item"} [
                  selectButtons true
                ] else
                H.div {} []
201 202 203
            , H.div {id: "terms_table", className: "panel-body"}
              [ H.table {className: "table able"}
                [ H.thead {className: "tableHeader"} [props.tableHead]
204 205
                , H.tbody {} props.tableBody
                ]
206

207 208 209 210 211 212 213 214 215 216 217
              , 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
                      ]
                    ]
                 ]
              ]
218 219
            ]
          ]
220 221
        ]
      ]
222 223 224
    -- WHY setPath     f = origSetPageParams (const $ f path)
    setTermListFilter x = setPath $ _ { termListFilter = x }
    setTermSizeFilter x = setPath $ _ { termSizeFilter = x }
225
    setSelection = dispatch <<< setTermListSetA ngramsTableCache ngramsSelection
226

227 228
    editor = H.div {} $ maybe [] f ngramsParent
      where
229 230 231 232 233 234 235 236 237 238 239 240 241 242
        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"]
                   , H.button { className: "btn btn-secondary"
                              , on: {click: (const $ dispatch $ SetParentResetChildren Nothing)}
                              } [H.text "Cancel"]
                   ]
243 244 245 246 247 248
          where
            ngramsTable = ngramsTableCache # at ngrams
                          <<< _Just
                          <<< _NgramsElement
                          <<< _children
                          %~ applyPatchSet (patchSetFromMap ngramsChildren)
249
            ngramsClick {depth: 1, ngrams: child} = Just $ dispatch $ ToggleChild false child
250 251 252
            ngramsClick _ = Nothing
            ngramsEdit  _ = Nothing

253 254 255 256 257
    selectionsExist :: Set NgramsTerm -> Boolean
    selectionsExist = not <<< Set.isEmpty

    selectButtons false = H.div {} []
    selectButtons true =
258
      H.div {} [
259
        H.button { className: "btn btn-primary"
260
                , on: { click: const $ setSelection MapTerm }
261
                } [ H.text "Map" ]
262
        , H.button { className: "btn btn-primary"
263
                  , on: { click: const $ setSelection StopTerm }
264
                  } [ H.text "Stop" ]
265
        , H.button { className: "btn btn-primary"
266
                  , on: { click: const $ setSelection CandidateTerm }
267
                  } [ H.text "Candidate" ]
268 269
      ]

270
-- NEXT
271
type Props =
272
  ( path         :: R.State PageParams
273
  , state        :: R.State State
274
  , tabNgramType :: CTabNgramType
275
  , versioned    :: VersionedNgramsTable
276
  , withAutoUpdate :: Boolean
277 278
  )

279 280
loadedNgramsTable :: Record Props -> R.Element
loadedNgramsTable p = R.createElement loadedNgramsTableCpt p []
281

282 283
loadedNgramsTableCpt :: R.Component Props
loadedNgramsTableCpt = R.hooksComponent "G.C.NT.loadedNgramsTable" cpt
284
  where
285
    cpt { path: path@(path'@{searchQuery, scoreType, params, termListFilter, termSizeFilter} /\ setPath)
286 287 288 289 290 291
        , state: (state@{ ngramsChildren
                        , ngramsLocalPatch
                        , ngramsParent
                        , ngramsSelection
                        , ngramsVersion } /\ setState)
        , tabNgramType
292
        , versioned: Versioned { data: initTable }
293
        , withAutoUpdate } _ = do
294

295
      pure $ R.fragment $
296
        autoUpdate <> resetSaveButtons <> [
297 298 299 300 301
          H.h4 {style: {textAlign : "center"}} [
              H.span {className: "glyphicon glyphicon-hand-down"} []
            , H.text "Extracted Terms"
            ]
        , search
302
        , T.table { colNames
303 304 305 306 307 308 309 310
                  , container: tableContainer { dispatch: performAction
                                              , ngramsChildren
                                              , ngramsParent
                                              , ngramsSelection
                                              , ngramsTable
                                              , path
                                              , tabNgramType
                                              }
311
                  , params: params /\ setParams -- TODO-LENS
312
                  , rows: filteredConvertedRows
313
                  , totalRecords
314 315 316 317
                  , wrapColElts: wrapColElts { allNgramsSelected
                                             , dispatch: performAction
                                             , ngramsSelection
                                             }
318
                  }
319
        ] <> resetSaveButtons
320
      where
321
        autoUpdate :: Array R.Element
322
        autoUpdate = if withAutoUpdate then [ R2.buff $ autoUpdateElt { duration: 5000, effect: performAction Synchronize } ] else []
323
        resetButton :: R.Element
324
        resetButton = H.button { className: "btn btn-primary"
325
                               , on: { click: \_ -> performAction ResetPatches } } [ H.text "Reset" ]
326
        saveButton :: R.Element
327
        saveButton = H.button { className: "btn btn-primary"
328
                              , on: { click: \_ -> performAction Synchronize }} [ H.text "Save" ]
329
        resetSaveButtons :: Array R.Element
330
        resetSaveButtons = if ngramsLocalPatch == mempty then [] else
331 332
          [ H.div {} [ resetButton, saveButton ] ]

333 334 335 336 337 338 339 340 341
        setParentResetChildren :: Maybe NgramsTerm -> State -> State
        setParentResetChildren p = _ { ngramsParent = p, ngramsChildren = mempty }

        performAction :: Action -> Effect Unit
        performAction (SetParentResetChildren p) =
          setState $ setParentResetChildren p
        performAction (ToggleChild b c) =
          setState $ \s@{ ngramsChildren: nc } -> s { ngramsChildren = newNC nc }
          where
342
            newNC nc = Map.alter (maybe (Just b) (const Nothing)) c nc
343 344 345 346 347
        performAction (ToggleSelect c) =
          setState $ \s@{ ngramsSelection: ns } -> s { ngramsSelection = toggleSet c ns }
        performAction ToggleSelectAll =
          setState toggler
          where
348
            toggler s =
349 350 351 352
              if allNgramsSelected then
                s { ngramsSelection = Set.empty :: Set NgramsTerm }
              else
                s { ngramsSelection = selectNgramsOnFirstPage filteredRows }
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        performAction Synchronize = syncPatchesR path' (state /\ setState)
        performAction (CommitPatch pt) =
          commitPatchR (Versioned {version: ngramsVersion, data: pt}) (state /\ setState)
        performAction ResetPatches =
          setState $ \s -> s { ngramsLocalPatch = { ngramsNewElems: mempty, ngramsPatches: mempty } }
        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
              setState $ setParentResetChildren Nothing
              commitPatchR (Versioned {version: ngramsVersion, data: pt}) (state /\ setState)

370
        totalRecords = L.length rows
371 372 373 374 375
        filteredConvertedRows :: T.Rows
        filteredConvertedRows = convertRow <$> filteredRows
        filteredRows :: PreConversionRows
        filteredRows = T.filterRows { params } rows
        rows :: PreConversionRows
376 377 378 379 380
        rows = orderWith (
          addOccT <$> (
             L.filter rowsFilterT $ Map.toUnfoldable (ngramsTable ^. _NgramsTable)
             )
          )
381
        rowsFilter :: NgramsElement -> Boolean
382
        rowsFilter = displayRow state searchQuery ngramsTable ngramsParentRoot termListFilter termSizeFilter
383 384 385 386 387 388 389
        rowsFilterT = rowsFilter <<< snd
        addOccWithFilter ne ngramsElement =
          if rowsFilter ngramsElement then
            Just $ addOcc ne ngramsElement
          else
            Nothing
        addOcc ne ngramsElement =
390
          let Additive occurrences = sumOccurrences ngramsTable ngramsElement in
391 392
          ngramsElement # _NgramsElement <<< _occurrences .~ occurrences
        addOccT (Tuple ne ngramsElement) = Tuple ne $ addOcc ne ngramsElement
393

394 395
        allNgramsSelected = allNgramsSelectedOnFirstPage ngramsSelection filteredRows

396
        ngramsTable = applyNgramsPatches state initTable
397
        roots = rootsOf ngramsTable
398 399 400 401 402 403 404 405
        ngramsParentRoot :: Maybe NgramsTerm
        ngramsParentRoot =
          (\np -> ngramsTable ^? at np
                            <<< _Just
                            <<< _NgramsElement
                            <<< _root
                            <<< _Just
            ) =<< ngramsParent
406

407
        convertRow (Tuple ngrams ngramsElement) =
408 409 410 411 412 413 414
          { row: NTC.renderNgramsItem { dispatch: performAction
                                      , ngrams
                                      , ngramsElement
                                      , ngramsLocalPatch
                                      , ngramsParent
                                      , ngramsSelection
                                      , ngramsTable }
415 416
          , delete: false
          }
417 418
        orderWith =
          case convOrderBy <$> params.orderBy of
419 420 421 422
            Just ScoreAsc  -> L.sortWith \x -> (snd x)        ^. _NgramsElement <<< _occurrences
            Just ScoreDesc -> L.sortWith \x -> Down $ (snd x) ^. _NgramsElement <<< _occurrences
            Just TermAsc   -> L.sortWith \x -> (snd x)        ^. _NgramsElement <<< _ngrams
            Just TermDesc  -> L.sortWith \x -> Down $ (snd x) ^. _NgramsElement <<< _ngrams
423 424 425 426
            _              -> identity -- the server ordering is enough here

        colNames = T.ColumnName <$> ["Select", "Map", "Stop", "Terms", "Score"] -- see convOrderBy
        -- This is used to *decorate* the Select header with the checkbox.
427
        wrapColElts scProps (T.ColumnName "Select") = const [NTC.selectionCheckbox scProps]
428 429
        wrapColElts _       (T.ColumnName "Score")  = (_ <> [H.text ("(" <> show scoreType <> ")")])
        wrapColElts _       _                       = identity
430 431
        setParams f = setPath $ \p@{params: ps} -> p {params = f ps}

432
        search :: R.Element
433 434 435
        search = NTC.searchInput { key: "search-input"
                                 , onSearch: setSearchQuery
                                 , searchQuery: searchQuery }
436 437 438
        setSearchQuery :: String -> Effect Unit
        setSearchQuery x    = setPath $ _ { searchQuery    = x }

439

440
displayRow :: State -> SearchQuery -> NgramsTable -> Maybe NgramsTerm -> Maybe TermList -> Maybe TermSize -> NgramsElement -> Boolean
441 442 443 444
displayRow state@{ ngramsChildren
                 , ngramsLocalPatch
                 , ngramsParent }
           searchQuery
445
           ngramsTable
446
           ngramsParentRoot
447
           termListFilter
448
           termSizeFilter
449
           (NgramsElement {ngrams, root, list}) =
450 451 452 453 454 455 456 457 458 459 460
  (
      isNothing root
    -- ^ Display only nodes without parents
    && maybe true (_ == list) termListFilter
    -- ^ 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
461 462
    && filterTermSize termSizeFilter ngrams
    -- ^ and which satisfies the chosen term size
463 464 465 466 467 468 469
    || 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.
470

471

472 473 474 475 476 477 478
allNgramsSelectedOnFirstPage :: Set NgramsTerm -> PreConversionRows -> Boolean
allNgramsSelectedOnFirstPage selected rows = selected == (selectNgramsOnFirstPage rows)

selectNgramsOnFirstPage :: PreConversionRows -> Set NgramsTerm
selectNgramsOnFirstPage rows = Set.fromFoldable $ fst <$> rows


479
type MainNgramsTableProps =
480
  ( nodeId        :: Int
481 482 483
    -- ^ This node can be a corpus or contact.
  , defaultListId :: Int
  , tabType       :: TabType
484
  , session       :: Session
485
  , tabNgramType  :: CTabNgramType
486
  , withAutoUpdate :: Boolean
487
  )
488

489 490
mainNgramsTable :: Record MainNgramsTableProps -> R.Element
mainNgramsTable props = R.createElement mainNgramsTableCpt props []
491

492
mainNgramsTableCpt :: R.Component MainNgramsTableProps
493
mainNgramsTableCpt = R.hooksComponent "G.C.NT.mainNgramsTable" cpt
494
  where
495
    cpt props@{nodeId, defaultListId, tabType, session, tabNgramType, withAutoUpdate} _ = do
496
      let path = initialPageParams session nodeId [defaultListId] tabType
497

498 499 500 501 502 503 504
      useLoaderWithCacheAPI {
          cacheEndpoint: versionEndpoint props
        , handleResponse
        , mkRequest
        , path
        , renderer: \versioned -> mainNgramsTablePaint { path, tabNgramType, versioned, withAutoUpdate }
        }
505

506 507 508
    versionEndpoint :: Record MainNgramsTableProps -> PageParams -> Aff Version
    versionEndpoint { defaultListId, nodeId, session, tabType } _ = get session $ R.GetNgramsTableVersion { listId: defaultListId, tabType } (Just nodeId)

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    mkRequest :: PageParams -> GUC.Request
    mkRequest path@{ session } = GUC.makeGetRequest session $ url path
      where
        url { listIds
            , nodeId
            , params: { limit, offset, orderBy }
            , searchQuery
            , scoreType
            , tabType
            , termListFilter
            , termSizeFilter
            } = R.GetNgrams { limit
                            , listIds
                            , offset: Just offset
                            , orderBy: convOrderBy <$> orderBy
                            , searchQuery
                            , tabType
                            , termListFilter
                            , termSizeFilter } (Just nodeId)

    handleResponse :: VersionedNgramsTable -> VersionedNgramsTable
    handleResponse v = v

    pathNoLimit :: PageParams -> PageParams
533 534
    pathNoLimit path@{ params } = path { params = params { limit = 100000 }
                                       , termListFilter = Nothing }
535

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
type MainNgramsTablePaintProps =
  (
    path :: PageParams
  , tabNgramType  :: CTabNgramType
  , versioned :: VersionedNgramsTable
  , withAutoUpdate :: Boolean
  )

mainNgramsTablePaint :: Record MainNgramsTablePaintProps -> R.Element
mainNgramsTablePaint p = R.createElement mainNgramsTablePaintCpt p []

mainNgramsTablePaintCpt :: R.Component MainNgramsTablePaintProps
mainNgramsTablePaintCpt = R.hooksComponent "G.C.NT.mainNgramsTablePaint" cpt
  where
    cpt {path, tabNgramType, versioned, withAutoUpdate} _ = do
      pathS <- R.useState' path
552
      state <- R.useState' $ initialState versioned
553
      pure $ loadedNgramsTable {
554
        path: pathS
555
      , state
556 557 558 559 560
      , tabNgramType
      , versioned
      , withAutoUpdate
      }

561 562 563
sumOccurrences :: NgramsTable -> NgramsElement -> Additive Int
sumOccurrences ngramsTable (NgramsElement {occurrences, children}) =
    Additive occurrences <> children ^. folded <<< to (sumOccurrences' ngramsTable)
564 565 566 567
    where
      sumOccurrences' :: NgramsTable -> NgramsTerm -> Additive Int
      sumOccurrences' nt label =
          nt ^. ix label <<< to (sumOccurrences nt)
568

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