Core.purs 42.9 KB
Newer Older
1 2
module Gargantext.Components.NgramsTable.Core
  ( PageParams
3
  , CoreParams
4 5
  , NgramsElement(..)
  , _NgramsElement
6
  , NgramsRepoElementT
7 8 9
  , NgramsRepoElement(..)
  , _NgramsRepoElement
  , ngramsRepoElementToNgramsElement
10
  , NgramsTable(..)
11
  , NewElems
12
  , NgramsPatch(..)
13
  , NgramsPatches
14
  , _NgramsTable
15
  , NgramsTerm(..)
16
  , normNgram
17
  , ngramsTermText
18
  , findNgramRoot
19
  , findNgramTermList
20 21
  , Version
  , Versioned(..)
22 23 24
  , Count
  , VersionedWithCount(..)
  , toVersioned
25
  , VersionedNgramsPatches
26
  , AsyncNgramsChartsUpdate(..)
27
  , VersionedNgramsTable
28
  , VersionedWithCountNgramsTable
29
  , NgramsTablePatch
30
  , CoreState
31
  , HighlightElement
32 33 34
  , highlightNgrams
  , initialPageParams
  , loadNgramsTable
35
  , loadNgramsTableAll
36 37 38 39 40
  , convOrderBy
  , Replace(..) -- Ideally we should keep the constructors hidden
  , replace
  , PatchSet(..)
  , PatchMap(..)
41
  , _PatchMap
42 43
  , patchSetFromMap
  , applyPatchSet
44
--, applyNgramsTablePatch -- re-export only if we have a good reason not to use applyNgramsPatches
45
  , applyNgramsPatches
46
  , rootsOf
47 48 49
  , singletonPatchMap
  , fromNgramsPatches
  , singletonNgramsTablePatch
50
  , isEmptyNgramsTablePatch
51 52 53 54 55 56
  , _list
  , _occurrences
  , _children
  , _ngrams
  , _parent
  , _root
Nicolas Pouillard's avatar
Nicolas Pouillard committed
57 58
  , _ngrams_repo_elements
  , _ngrams_scores
59
  , commitPatch
60
  , putNgramsPatches
61
  , postNgramsChartsAsync
62
  , syncPatches
63 64 65 66 67 68
  , addNewNgramP
  , addNewNgramA
  , setTermListP
  , setTermListA
  , CoreAction(..)
  , CoreDispatch
69 70
  , Action(..)
  , Dispatch
71
  , coreDispatch
72 73
  , isSingleNgramsTerm
  , filterTermSize
74 75

  -- Reset Button TODO put elsewhere this file is too big
76 77
  , SyncResetButtonsProps
  , syncResetButtons
78
  , chartsAfterSync
arturo's avatar
arturo committed
79
  , useAutoSync
80 81 82
  )
  where

83 84
import Gargantext.Prelude

85
import Control.Monad.State (class MonadState, execState)
86 87
import Data.Array (head)
import Data.Array as A
88
import Data.Bifunctor (lmap)
89
import Data.Either (Either(..))
90
import Data.Eq.Generic (genericEq)
91 92
import Data.Foldable (class Foldable, foldMap, foldl, foldr)
import Data.FoldableWithIndex (class FoldableWithIndex, foldMapWithIndex, foldlWithIndex, foldrWithIndex)
93
import Data.Generic.Rep (class Generic)
James Laver's avatar
James Laver committed
94
import Data.Lens (Iso', Lens', use, view, (%=), (%~), (.~), (?=), (^?))
95
import Data.Lens.At (class At, at)
96
import Data.Lens.Common (_Just)
97
import Data.Lens.Fold (folded, traverseOf_)
98
import Data.Lens.Index (class Index, ix)
99
import Data.Lens.Iso.Newtype (_Newtype)
100
import Data.Lens.Record (prop)
101
import Data.List ((:), List(Nil))
102
import Data.List as L
103 104
import Data.Map (Map)
import Data.Map as Map
Nicolas Pouillard's avatar
Nicolas Pouillard committed
105
import Data.Maybe (Maybe(..), fromMaybe, fromMaybe', isJust)
Nicolas Pouillard's avatar
Nicolas Pouillard committed
106
import Data.Monoid.Additive (Additive(..))
107
import Data.Newtype (class Newtype)
108
import Data.Ord.Generic (genericCompare)
109 110
import Data.Set (Set)
import Data.Set as Set
111
import Data.Show.Generic (genericShow)
112
import Data.String as S
113
import Data.String.Common as DSC
114 115
import Data.String.Regex (Regex, regex, replace) as R
import Data.String.Regex.Flags (global, multiline) as R
116
import Data.String.Utils as SU
117
import Data.Symbol (SProxy(..))
118
import Data.These (These(..))
Nicolas Pouillard's avatar
Nicolas Pouillard committed
119
import Data.Traversable (for, traverse_, traverse)
120
import Data.TraversableWithIndex (traverseWithIndex)
121
import Data.Tuple (Tuple(..))
122 123
import Data.Tuple.Nested ((/\))
import Effect (Effect)
124
import Effect.Aff (Aff, launchAff_)
125
import Effect.Class (liftEffect)
126
import Effect.Exception.Unsafe (unsafeThrow)
127
import FFI.Simple.Functions (delay)
128
import Foreign as F
129
import Foreign.Object as FO
130
import Gargantext.AsyncTasks as GAT
131
import Gargantext.Components.Table as T
132
import Gargantext.Components.Table.Types as T
arturo's avatar
arturo committed
133
import Gargantext.Config.REST (AffRESTError, RESTError)
134
import Gargantext.Config.Utils (handleRESTError)
135
import Gargantext.Routes (SessionRoute(..))
136
import Gargantext.Sessions (Session, get, post, put)
137
import Gargantext.Types (AsyncTask, AsyncTaskType(..), AsyncTaskWithType(..), CTabNgramType(..), FrontendError, ListId, OrderBy(..), ScoreType(..), TabSubType(..), TabType(..), TermList(..), TermSize(..))
138
import Gargantext.Utils.Either (eitherMap)
139
import Gargantext.Utils.KarpRabin (indicesOfAny)
James Laver's avatar
James Laver committed
140
import Gargantext.Utils.Reactix as R2
141 142 143
import Partial (crashWith)
import Partial.Unsafe (unsafePartial)
import Reactix (Component, Element, createElement) as R
144
import Reactix as R
145
import Reactix.DOM.HTML as H
146 147
import Simple.JSON as JSON
import Toestand as T
148

James Laver's avatar
James Laver committed
149 150
here :: R2.Here
here = R2.here "Gargantext.Components.NgramsTable.Core"
151

152 153
type Endo a = a -> a

154 155 156 157 158 159 160 161

-- | Main Types
type Version = Int

newtype Versioned a = Versioned
  { version :: Version
  , data    :: a
  }
162
derive instance Generic (Versioned a) _
163 164 165 166
derive instance Newtype (Versioned a) _
instance Eq a => Eq (Versioned a) where eq = genericEq
derive newtype instance JSON.ReadForeign a => JSON.ReadForeign (Versioned a)
derive newtype instance JSON.WriteForeign a => JSON.WriteForeign (Versioned a)
167 168 169 170 171 172 173 174
------------------------------------------------------------------------
type Count = Int

newtype VersionedWithCount a = VersionedWithCount
  { version :: Version
  , count   :: Count
  , data    :: a
  }
175
derive instance Generic (VersionedWithCount a) _
176 177 178 179
derive instance Newtype (VersionedWithCount a) _
instance Eq a => Eq (VersionedWithCount a) where eq = genericEq
derive newtype instance JSON.ReadForeign a => JSON.ReadForeign (VersionedWithCount a)
derive newtype instance JSON.WriteForeign a => JSON.WriteForeign (VersionedWithCount a)
180 181 182

toVersioned :: forall a. VersionedWithCount a -> Tuple Count (Versioned a)
toVersioned (VersionedWithCount { count, data: d, version }) = Tuple count $ Versioned { data: d, version }
183 184 185 186 187 188 189

------------------------------------------------------------------------
-- TODO replace by NgramsPatches directly
type NgramsTablePatch = { ngramsPatches :: NgramsPatches }

newtype PatchMap k p = PatchMap (Map k p)

190 191 192 193 194 195 196 197 198 199 200 201 202 203
derive instance Generic (PatchMap k p) _
derive instance Newtype (PatchMap k p) _
derive instance (Eq k, Eq p) => Eq (PatchMap k p)

-- TODO generalize
instance JSON.WriteForeign p => JSON.WriteForeign (PatchMap NgramsTerm p) where
  writeImpl (PatchMap m) =
    JSON.writeImpl $ FO.fromFoldable $ map (lmap ngramsTermText) (Map.toUnfoldable m :: Array _)
instance (JSON.ReadForeign p, Monoid p) => JSON.ReadForeign (PatchMap NgramsTerm p) where
  readImpl f = do
    inst <- JSON.readImpl f
    pure $ PatchMap $ foldlWithIndex (\k m v -> Map.insert (NormNgramsTerm k) v m) Map.empty (inst :: FO.Object p)
    -- TODO we assume that the ngrams are already normalized ^^^^^^^^^^^^^

204 205 206 207 208 209 210 211 212 213 214
type NgramsPatches = PatchMap NgramsTerm NgramsPatch

data NgramsPatch
  = NgramsReplace
      { patch_old :: Maybe NgramsRepoElement
      , patch_new :: Maybe NgramsRepoElement
      }
  | NgramsPatch
      { patch_children :: PatchSet NgramsTerm
      , patch_list     :: Replace TermList
      }
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
derive instance Generic NgramsPatch _
derive instance Eq NgramsPatch
instance Monoid NgramsPatch where
  mempty = NgramsPatch { patch_children: mempty, patch_list: mempty }
instance Semigroup NgramsPatch where
  append (NgramsReplace p) (NgramsReplace q)
    | p.patch_old /= q.patch_new = unsafeThrow "append/NgramsPatch: old != new"
    | otherwise                  = ngramsReplace q.patch_old p.patch_new
  append (NgramsPatch p)   (NgramsPatch q) = NgramsPatch
    { patch_children: p.patch_children <> q.patch_children
    , patch_list:     p.patch_list     <> q.patch_list
    }
  append (NgramsPatch p) (NgramsReplace q) = ngramsReplace q.patch_old (q.patch_new # _Just <<< _Newtype %~ applyNgramsPatch' p)
  append (NgramsReplace p) (NgramsPatch q) = ngramsReplace (p.patch_old # _Just <<< _Newtype %~ applyNgramsPatch' (invert q)) p.patch_new
instance JSON.WriteForeign NgramsPatch where
  writeImpl (NgramsReplace { patch_old, patch_new }) = JSON.writeImpl { patch_old, patch_new }
  writeImpl (NgramsPatch { patch_children, patch_list }) = JSON.writeImpl { patch_children, patch_list }
instance JSON.ReadForeign NgramsPatch where
  readImpl f = do
    inst :: { patch_old :: Maybe NgramsRepoElement
            , patch_new :: Maybe NgramsRepoElement
            , patch_children :: PatchSet NgramsTerm
            , patch_list :: Replace TermList } <- JSON.readImpl f
    -- TODO handle empty fields
    -- TODO handle patch_new
    if isJust inst.patch_new || isJust inst.patch_old then
      pure $ NgramsReplace { patch_old: inst.patch_old, patch_new: inst.patch_new }
    else do
      pure $ NgramsPatch { patch_list: inst.patch_list, patch_children: inst.patch_children }
244 245 246

------------------------------------------------------------------------
newtype NgramsTerm = NormNgramsTerm String
247
derive instance Generic NgramsTerm _
248 249 250 251 252 253 254
derive instance Newtype NgramsTerm _
instance Eq NgramsTerm where eq = genericEq
instance Ord NgramsTerm where compare = genericCompare
instance Show NgramsTerm where show = genericShow
derive newtype instance JSON.ReadForeign NgramsTerm
derive newtype instance JSON.WriteForeign NgramsTerm
derive newtype instance Monoid NgramsTerm
255 256 257

------------------------------------------------------------------------

258 259
type CoreParams s =
  { nodeId  :: Int
260
    -- ^ This node can be a corpus or contact.
261 262
  , listIds :: Array Int
  , tabType :: TabType
263
  , session :: Session
264
  | s
265 266
  }

267 268
type PageParams =
  CoreParams
269 270
    ( params         :: T.Params
    , searchQuery    :: String
271 272
    , termListFilter :: Maybe TermList -- Nothing means all
    , termSizeFilter :: Maybe TermSize -- Nothing means all
273
    , scoreType      :: ScoreType
274 275
    )

276 277
initialPageParams :: Session -> Int -> Array Int -> TabType -> PageParams
initialPageParams session nodeId listIds tabType =
278 279
  { listIds
  , nodeId
280
  , params
281 282
  , tabType
  , termSizeFilter: Nothing
283
  , termListFilter: Just MapTerm
284
  , searchQuery: ""
285
  , scoreType: Occurrences
286
  , session
287
  }
288
  where
289
    params = T.initialParams { orderBy = Just (T.DESC $ T.ColumnName "Score") }
290

291 292 293 294 295 296 297 298 299 300 301 302 303



ngramsTermText :: NgramsTerm -> String
ngramsTermText (NormNgramsTerm t) = t

-- TODO
normNgramInternal :: CTabNgramType -> String -> String
normNgramInternal CTabAuthors    = identity
normNgramInternal CTabSources    = identity
normNgramInternal CTabInstitutes = identity
normNgramInternal CTabTerms      = S.toLower <<< R.replace wordBoundaryReg " "

304 305 306
normNgramWithTrim :: CTabNgramType -> String -> String
normNgramWithTrim nt = DSC.trim <<< normNgramInternal nt

307
normNgram :: CTabNgramType -> String -> NgramsTerm
308
normNgram tabType = NormNgramsTerm <<< normNgramWithTrim tabType
309 310 311

-----------------------------------------------------------------------------------
newtype NgramsElement = NgramsElement
312 313 314 315 316 317 318
  { ngrams      :: NgramsTerm -- HERE
  , size        :: Int -- MISSING
  , list        :: TermList -- ok
  , root        :: Maybe NgramsTerm -- ok
  , parent      :: Maybe NgramsTerm -- ok
  , children    :: Set NgramsTerm -- ok
  , occurrences :: Int -- HERE
319 320
  }

321
derive instance Eq NgramsElement
322 323


324
_parent :: forall parent row. Lens' { parent :: parent | row } parent
325
_parent = prop (SProxy :: SProxy "parent")
326 327

_root :: forall root row. Lens' { root :: root | row } root
328
_root   = prop (SProxy :: SProxy "root")
329 330

_ngrams :: forall row. Lens' { ngrams :: NgramsTerm | row } NgramsTerm
331 332 333 334 335 336 337 338 339 340 341
_ngrams = prop (SProxy :: SProxy "ngrams")

_children :: forall row. Lens' { children :: Set NgramsTerm | row } (Set NgramsTerm)
_children = prop (SProxy :: SProxy "children")

_occurrences :: forall row. Lens' { occurrences :: Int | row } Int
_occurrences = prop (SProxy :: SProxy "occurrences")

_list :: forall a row. Lens' { list :: a | row } a
_list = prop (SProxy :: SProxy "list")

Nicolas Pouillard's avatar
Nicolas Pouillard committed
342 343 344 345 346 347
_ngrams_repo_elements :: forall a row. Lens' { ngrams_repo_elements :: a | row } a
_ngrams_repo_elements = prop (SProxy :: SProxy "ngrams_repo_elements")

_ngrams_scores :: forall a row. Lens' { ngrams_scores :: a | row } a
_ngrams_scores = prop (SProxy :: SProxy "ngrams_scores")

348 349
derive instance Newtype NgramsElement _
derive instance Generic NgramsElement _
350
instance Show NgramsElement where show = genericShow
351

352 353
_NgramsElement  :: Iso' NgramsElement {
    children    :: Set NgramsTerm
354
  , size        :: Int
355 356 357 358 359 360
  , list        :: TermList
  , ngrams      :: NgramsTerm
  , occurrences :: Int
  , parent      :: Maybe NgramsTerm
  , root        :: Maybe NgramsTerm
  }
361 362
_NgramsElement = _Newtype

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
instance JSON.ReadForeign NgramsElement where
  readImpl f = do
    inst :: { children :: Array NgramsTerm
            , size :: Int
            , list :: TermList
            , ngrams :: NgramsTerm
            , occurrences :: Int
            , parent :: Maybe NgramsTerm
            , root :: Maybe NgramsTerm }<- JSON.readImpl f
    pure $ NgramsElement $ inst { children = Set.fromFoldable inst.children }
instance JSON.WriteForeign NgramsElement where
  writeImpl (NgramsElement ne) =
    JSON.writeImpl $ ne { children = Set.toUnfoldable ne.children :: Array _ }

type NgramsRepoElementT =
  ( size :: Int
379 380 381
  , list     :: TermList
  , root     :: Maybe NgramsTerm
  , parent   :: Maybe NgramsTerm
382 383 384 385
  )
newtype NgramsRepoElement = NgramsRepoElement
  { children :: Set NgramsTerm
  | NgramsRepoElementT }
386
derive instance Generic NgramsRepoElement _
387 388 389 390 391 392 393 394 395 396
derive instance Newtype NgramsRepoElement _
derive instance Eq NgramsRepoElement
instance JSON.ReadForeign NgramsRepoElement where
  readImpl f = do
    inst :: { children :: Array NgramsTerm | NgramsRepoElementT } <- JSON.readImpl f
    pure $ NgramsRepoElement $ inst { children = Set.fromFoldable inst.children }
instance JSON.WriteForeign NgramsRepoElement where
  writeImpl (NgramsRepoElement nre) =
    JSON.writeImpl $ nre { children = Set.toUnfoldable nre.children :: Array _ }
instance Show NgramsRepoElement where show = genericShow
397 398 399 400 401 402 403 404 405 406 407

_NgramsRepoElement  :: Iso' NgramsRepoElement {
    children    :: Set NgramsTerm
  , size        :: Int
  , list        :: TermList
  , parent      :: Maybe NgramsTerm
  , root        :: Maybe NgramsTerm
--  , occurrences :: Int
  }
_NgramsRepoElement = _Newtype

Nicolas Pouillard's avatar
Nicolas Pouillard committed
408
ngramsRepoElementToNgramsElement :: NgramsTerm -> Int -> NgramsRepoElement -> NgramsElement
409
ngramsRepoElementToNgramsElement ngrams occurrences (NgramsRepoElement { children, list, parent, root, size }) =
410
  NgramsElement
411
  { children
412
  , list
413
  , ngrams
Nicolas Pouillard's avatar
Nicolas Pouillard committed
414
  , occurrences
415 416 417
  , parent
  , root
  , size -- TODO should we assert that size(ngrams) == size?
418 419
  }

420
-----------------------------------------------------------------------------------
Nicolas Pouillard's avatar
Nicolas Pouillard committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
{-
  NgramsRepoElement does not have the occurrences field.
  Instead NgramsTable has a ngrams_scores map.

  Pro:
  * Does not encumber NgramsRepoElement with the score which is not part of repo.
  * Enables for multiple scores through multiple maps.
  Cons:
  * Having a map on the side is equivalent to a `occurrences :: Maybe Int`, which is
    less precise.
  * It is a tiny bit less performant to access the score.
-}
newtype NgramsTable = NgramsTable
  { ngrams_repo_elements :: Map NgramsTerm NgramsRepoElement
  , ngrams_scores        :: Map NgramsTerm (Additive Int)
  }
437

438 439
derive instance Newtype NgramsTable _
derive instance Generic NgramsTable _
440 441
instance Eq NgramsTable where eq = genericEq
instance Show NgramsTable where show = genericShow
442

Nicolas Pouillard's avatar
Nicolas Pouillard committed
443 444 445 446
_NgramsTable :: Iso' NgramsTable
                     { ngrams_repo_elements :: Map NgramsTerm NgramsRepoElement
                     , ngrams_scores        :: Map NgramsTerm (Additive Int)
                     }
447 448
_NgramsTable = _Newtype

449
instance Index NgramsTable NgramsTerm NgramsRepoElement where
Nicolas Pouillard's avatar
Nicolas Pouillard committed
450
  ix k = _NgramsTable <<< _ngrams_repo_elements <<< ix k
451

452
instance At NgramsTable NgramsTerm NgramsRepoElement where
Nicolas Pouillard's avatar
Nicolas Pouillard committed
453
  at k = _NgramsTable <<< _ngrams_repo_elements <<< at k
454

455 456 457
instance JSON.ReadForeign NgramsTable where
  readImpl ff = do
    inst <- JSON.readImpl ff
458
    pure $ NgramsTable
459 460
      { ngrams_repo_elements: Map.fromFoldable $ f <$> (inst :: Array NgramsElement)
      , ngrams_scores:        Map.fromFoldable $ g <$> inst
Nicolas Pouillard's avatar
Nicolas Pouillard committed
461
      }
462
    where
Nicolas Pouillard's avatar
Nicolas Pouillard committed
463 464 465
      f (NgramsElement {ngrams, size, list, root, parent, children}) =
        Tuple ngrams (NgramsRepoElement {size, list, root, parent, children})
      g (NgramsElement e) = Tuple e.ngrams (Additive e.occurrences)
466

Nicolas Pouillard's avatar
Nicolas Pouillard committed
467
{- NOT USED
468
instance EncodeJson NgramsTable where
Nicolas Pouillard's avatar
Nicolas Pouillard committed
469 470
  encodeJson (NgramsTable {ngrams_repo_elements, ngrams_scores}) = encodeJson $ Map.values ... TODO
-}
471 472
-----------------------------------------------------------------------------------

Nicolas Pouillard's avatar
Nicolas Pouillard committed
473 474 475 476 477 478 479 480 481 482
lookupRootList :: NgramsTerm -> NgramsTable -> Maybe TermList
lookupRootList ngram (NgramsTable {ngrams_repo_elements: elts}) =
  case Map.lookup ngram elts of
    Nothing -> Nothing
    Just (NgramsRepoElement {list, root: Nothing}) -> Just list
    Just (NgramsRepoElement {root: Just root}) ->
      case Map.lookup root elts of
        Nothing -> Nothing
        Just (NgramsRepoElement {list}) -> Just list -- assert root == Nothing

483 484 485
wordBoundaryChars :: String
wordBoundaryChars = "[ .,;:!?'\\{}()]"

486
wordBoundaryReg :: R.Regex
487
wordBoundaryReg = case R.regex ("(" <> wordBoundaryChars <> ")") (R.global <> R.multiline) of
488 489
  Left e  -> unsafePartial $ crashWith e
  Right r -> r
490

491
wordBoundaryReg2 :: R.Regex
492
wordBoundaryReg2 = case R.regex ("(" <> wordBoundaryChars <> ")\\1") (R.global <> R.multiline) of
493 494 495
  Left e  -> unsafePartial $ crashWith e
  Right r -> r

496 497
type HighlightElement = Tuple String (List (Tuple NgramsTerm TermList))
type HighlightAccumulator = List HighlightElement
498

499 500
-- TODO: while this function works well with word boundaries,
--       it inserts too many spaces.
501
highlightNgrams :: CTabNgramType -> NgramsTable -> String -> Array HighlightElement
Nicolas Pouillard's avatar
Nicolas Pouillard committed
502
highlightNgrams ntype table@(NgramsTable {ngrams_repo_elements: elts}) input0 =
503
    -- trace {pats, input0, input, ixs} \_ ->
504
    A.fromFoldable ((\(s /\ ls)-> undb s /\ ls) <$> unsafePartial (foldl goFold ((input /\ Nil) : Nil) ixs))
505
  where
506
    spR x = " " <> R.replace wordBoundaryReg "$1$1" x <> " "
507
    -- reR = R.replace wordBoundaryReg " "
508
    db = S.replaceAll (S.Pattern " ") (S.Replacement "  ")
509
    sp x = " " <> db x <> " "
510
    undb = R.replace wordBoundaryReg2 "$1"
511
    input = spR input0
Nicolas Pouillard's avatar
Nicolas Pouillard committed
512
    pats = A.fromFoldable (Map.keys elts)
513
    ixs = indicesOfAny (sp <<< ngramsTermText <$> pats) (normNgramInternal ntype input)
514

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    splitAcc :: Partial => Int -> HighlightAccumulator
             -> Tuple HighlightAccumulator HighlightAccumulator
    splitAcc i = go 0 Nil
      where
      go j pref acc =
        case compare i j of
          LT -> crashWith "highlightNgrams: splitAcc': i < j"
          EQ -> L.reverse pref /\ acc
          GT ->
            case acc of
              Nil -> crashWith "highlightNgrams: splitAcc': acc=Nil" -- pref /\ Nil
              elt@(s /\ ls) : elts ->
                let slen = S.length s in
                case compare i (j + slen) of
                  LT -> let {before: s0, after: s1} = S.splitAt (i - j) s in
                        L.reverse ((s0 /\ ls) : pref) /\ ((s1 /\ ls) : elts)
                  EQ -> L.reverse (elt : pref) /\ elts
                  GT -> go (j + slen) (elt : pref) elts


    extractInputTextMatch :: Int -> Int -> String -> String
    extractInputTextMatch i len input = undb $ S.take len $ S.drop (i + 1) input

    addNgramElt ng ne_list (elt /\ elt_lists) = (elt /\ ((ng /\ ne_list) : elt_lists))

    goAcc :: Partial => Int -> HighlightAccumulator -> Tuple NgramsTerm Int -> HighlightAccumulator
    goAcc i acc (pat /\ lpat) =
542
      case lookupRootList pat table of
543
        Nothing ->
544 545 546
          crashWith "highlightNgrams: pattern missing from table"
        Just ne_list ->
          let
547 548 549 550
            (acc0 /\ acc1_2) = splitAcc i acc
            (acc1 /\ acc2) = splitAcc (lpat + 1) acc1_2
            text = extractInputTextMatch i lpat input
            ng = normNgram ntype text
551
          in
552 553
            acc0 <> (addNgramElt ng ne_list <$> acc1) <> acc2

554
    goFold :: Partial => HighlightAccumulator -> Tuple Int (Array Int) -> HighlightAccumulator
555 556 557 558 559
    goFold acc (Tuple i pis) = foldl (goAcc i) acc $
                           --  A.sortWith snd $
                               map (\pat -> pat /\ S.length (db (ngramsTermText pat))) $
                               fromMaybe' (\_ -> crashWith "highlightNgrams: out of bounds pattern") $
                               traverse (A.index pats) pis
560 561 562 563

-----------------------------------------------------------------------------------

type VersionedNgramsTable = Versioned NgramsTable
564
type VersionedWithCountNgramsTable = VersionedWithCount NgramsTable
565 566 567 568 569 570

-----------------------------------------------------------------------------------
data Replace a
  = Keep
  | Replace { old :: a, new :: a }

571 572
derive instance Generic (Replace a) _

573 574 575 576 577
replace :: forall a. Eq a => a -> a -> Replace a
replace old new
  | old == new = Keep
  | otherwise  = Replace { old, new }

578
derive instance Eq a => Eq (Replace a)
579

580
instance Eq a => Semigroup (Replace a) where
581 582
  append Keep p = p
  append p Keep = p
583
  append (Replace { old }) (Replace { new }) | old /= new = unsafeThrow "old != new"
584
  append (Replace { new }) (Replace { old }) = replace old new
585

586
instance Eq a => Monoid (Replace a) where mempty = Keep
587 588 589 590 591 592 593

applyReplace :: forall a. Eq a => Replace a -> a -> a
applyReplace Keep a = a
applyReplace (Replace { old, new }) a
  | a == old  = new
  | otherwise = a

594 595 596 597 598 599 600
instance JSON.WriteForeign a => JSON.WriteForeign (Replace a) where
  writeImpl Keep = JSON.writeImpl { tag: "Keep" }
  writeImpl (Replace {old, new}) = JSON.writeImpl { old, new, tag: "Replace" }
instance (JSON.ReadForeign a, Eq a) => JSON.ReadForeign (Replace a) where
  readImpl f = do
    impl :: { old :: Maybe a, new :: Maybe a }  <- JSON.readImpl f
    case Tuple impl.old impl.new of
601 602
      Tuple (Just old) (Just new) -> pure $ replace old new
      Tuple Nothing Nothing       -> pure Keep
603
      _                           -> F.fail $ F.ForeignError "decodeJsonReplace"
604 605 606 607 608 609 610 611

-- Representing a PatchSet as `Map a Boolean` would have the advantage
-- of enforcing rem and add to be disjoint.
newtype PatchSet a = PatchSet
  { rem :: Set a
  , add :: Set a
  }

612 613 614
derive instance Generic (PatchSet a) _
derive instance Newtype (PatchSet a) _

615
instance Ord a => Semigroup (PatchSet a) where
616 617 618 619 620
  append (PatchSet p) (PatchSet q) = PatchSet
    { rem: q.rem <> p.rem
    , add: Set.difference q.add p.rem <> p.add
    }

621
instance Ord a => Monoid (PatchSet a) where
622 623
  mempty = PatchSet { rem: Set.empty, add: Set.empty }

624 625 626
instance JSON.WriteForeign a => JSON.WriteForeign (PatchSet a) where
  writeImpl (PatchSet {rem, add}) = JSON.writeImpl { rem: (Set.toUnfoldable rem :: Array a)
                                                   , add: (Set.toUnfoldable add :: Array a) }
627

628 629
instance (Ord a, JSON.ReadForeign a) => JSON.ReadForeign (PatchSet a) where
  readImpl f = do
630
    -- TODO handle empty fields
631 632 633
    inst :: { rem :: Array a, add :: Array a } <- JSON.readImpl f
    let rem = mkSet inst.rem
        add = mkSet inst.add
634 635 636 637 638 639 640 641 642 643 644 645 646
    pure $ PatchSet { rem, add }
   where
    mkSet :: forall b. Ord b => Array b -> Set b
    mkSet = Set.fromFoldable

applyPatchSet :: forall a. Ord a => PatchSet a -> Set a -> Set a
applyPatchSet (PatchSet p) s = Set.difference s p.rem <> p.add

patchSetFromMap :: forall a. Ord a => Map a Boolean -> PatchSet a
patchSetFromMap m = PatchSet { rem: Map.keys (Map.filter not m)
                             , add: Map.keys (Map.filter identity m) }
  -- TODO Map.partition would be nice here

647 648 649
-- TODO shall we normalise as in replace? shall we make a type class Replaceable?
ngramsReplace :: Maybe NgramsRepoElement -> Maybe NgramsRepoElement -> NgramsPatch
ngramsReplace patch_old patch_new = NgramsReplace {patch_old, patch_new}
650

651
derive instance Eq (PatchSet NgramsTerm)
652

653 654 655 656 657 658
-- TODO
invert :: forall a. a -> a
invert _ = unsafeThrow "invert: TODO"



659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
applyNgramsPatch' :: forall row.
                          { patch_children :: PatchSet NgramsTerm
                          , patch_list     :: Replace TermList
                          } ->
                     Endo { list     :: TermList
                          , children :: Set NgramsTerm
                          | row
                          }
applyNgramsPatch' p e =
  e { list     = applyReplace p.patch_list e.list
    , children = applyPatchSet p.patch_children e.children
    }

applyNgramsPatch :: NgramsPatch -> Maybe NgramsRepoElement -> Maybe NgramsRepoElement
applyNgramsPatch (NgramsReplace {patch_new}) _ = patch_new
applyNgramsPatch (NgramsPatch p)           m = m # _Just <<< _Newtype %~ applyNgramsPatch' p
675 676


677 678 679
fromMap :: forall k p. Ord k => Eq p => Monoid p => Map k p -> PatchMap k p
fromMap = PatchMap <<< Map.filter (\v -> v /= mempty)

680
instance (Ord k, Eq p, Monoid p) => Semigroup (PatchMap k p) where
681
  append (PatchMap p) (PatchMap q) = fromMap $ Map.unionWith append p q
682

683
instance (Ord k, Eq p, Monoid p) => Monoid (PatchMap k p) where
684 685 686 687 688
  mempty = PatchMap Map.empty

_PatchMap :: forall k p. Iso' (PatchMap k p) (Map k p)
_PatchMap = _Newtype

689
{-
690
instance Functor (PatchMap k) where
691
  map f (PatchMap m) = PatchMap (map f m) -- NO NORM: fromMap would not typecheck
692

693
instance FunctorWithIndex k (PatchMap k) where
694 695
  mapWithIndex f (PatchMap m) = PatchMap (mapWithIndex f m) -- NO NORM: fromMap would not typecheck
-}
696

697
instance Foldable (PatchMap k) where
698 699 700 701
  foldr f z (PatchMap m) = foldr f z m
  foldl f z (PatchMap m) = foldl f z m
  foldMap f (PatchMap m) = foldMap f m

702
instance FoldableWithIndex k (PatchMap k) where
703 704 705 706
  foldrWithIndex f z (PatchMap m) = foldrWithIndex f z m
  foldlWithIndex f z (PatchMap m) = foldlWithIndex f z m
  foldMapWithIndex f (PatchMap m) = foldMapWithIndex f m

707 708
{- fromMap is preventing these to type check:

709
instance Ord k => Traversable (PatchMap k) where
710 711 712
  traverse f (PatchMap m) = fromMap <$> traverse f m
  sequence (PatchMap m) = fromMap <$> sequence m

713
instance Ord k => TraversableWithIndex k (PatchMap k) where
714 715
  traverseWithIndex f (PatchMap m) = fromMap <$> traverseWithIndex f m
-}
716

717 718 719 720
traversePatchMapWithIndex :: forall f a b k.
                             Applicative f => Ord k => Eq b => Monoid b =>
                             (k -> a -> f b) -> PatchMap k a -> f (PatchMap k b)
traversePatchMapWithIndex f (PatchMap m) = fromMap <$> traverseWithIndex f m
721

722 723 724
singletonPatchMap :: forall k p. k -> p -> PatchMap k p
singletonPatchMap k p = PatchMap (Map.singleton k p)

725 726 727
isEmptyPatchMap :: forall k p. PatchMap k p -> Boolean
isEmptyPatchMap (PatchMap p) = Map.isEmpty p

728 729
mergeMap :: forall k a b c. Ord k => (k -> These a b -> Maybe c) -> Map k a -> Map k b -> Map k c
mergeMap f m1 m2 = Map.mapMaybeWithKey f (Map.unionWith g (This <$> m1) (That <$> m2))
730
  where
731 732 733 734
    g (This p) (That v) = Both p v
    g x _ = x -- impossible

applyPatchMap :: forall k p v. Ord k => (p -> Maybe v -> Maybe v) -> PatchMap k p -> Map k v -> Map k v
735
{-
736 737 738 739 740
applyPatchMap applyPatchValue (PatchMap pm) m = mergeMap f pm m
  where
    f _ (This pv)   = applyPatchValue pv Nothing
    f _ (That v)    = Just v
    f _ (Both pv v) = applyPatchValue pv (Just v)
741 742 743 744
-}
applyPatchMap applyPatchValue (PatchMap pm) m =
    foldl go m (Map.toUnfoldable pm :: List (Tuple k p))
  where
James Laver's avatar
James Laver committed
745
    go m' (Tuple k pv) = Map.alter (applyPatchValue pv) k m'
746

747
type VersionedNgramsPatches = Versioned NgramsPatches
748

749 750 751 752
newtype AsyncNgramsChartsUpdate = AsyncNgramsChartsUpdate {
    listId  :: Maybe ListId
  , tabType :: TabType
  }
753 754 755 756 757
derive instance Generic AsyncNgramsChartsUpdate _
derive instance Newtype AsyncNgramsChartsUpdate _
instance JSON.WriteForeign AsyncNgramsChartsUpdate where
  writeImpl (AsyncNgramsChartsUpdate { listId, tabType }) =
    JSON.writeImpl { list_id: listId, tab_type: tabType }
758 759 760

type NewElems = Map NgramsTerm TermList

761
----------------------------------------------------------------------------------
762 763 764
isEmptyNgramsTablePatch :: NgramsTablePatch -> Boolean
isEmptyNgramsTablePatch {ngramsPatches} = isEmptyPatchMap ngramsPatches

765
fromNgramsPatches :: NgramsPatches -> NgramsTablePatch
766
fromNgramsPatches ngramsPatches = {ngramsPatches}
767

768 769 770 771
findNgramRoot :: NgramsTable -> NgramsTerm -> NgramsTerm
findNgramRoot (NgramsTable m) n =
  fromMaybe n (m.ngrams_repo_elements ^? at n <<< _Just <<< _NgramsRepoElement <<< _root <<< _Just)

772
findNgramTermList :: NgramsTable -> NgramsTerm -> Maybe TermList
773 774 775
findNgramTermList (NgramsTable m) n = m.ngrams_repo_elements ^? at r <<< _Just <<< _NgramsRepoElement <<< _list
  where
    r = findNgramRoot (NgramsTable m) n
776

777 778
singletonNgramsTablePatch :: NgramsTerm -> NgramsPatch -> NgramsTablePatch
singletonNgramsTablePatch n p = fromNgramsPatches $ singletonPatchMap n p
779

780
rootsOf :: NgramsTable -> Set NgramsTerm
Nicolas Pouillard's avatar
Nicolas Pouillard committed
781
rootsOf (NgramsTable m) = Map.keys $ Map.mapMaybe isRoot m.ngrams_repo_elements
782
  where
783
    isRoot (NgramsRepoElement { parent }) = parent
784 785 786 787 788

type RootParent = { root :: NgramsTerm, parent :: NgramsTerm }

type ReParent a = forall m. MonadState NgramsTable m => a -> m Unit

789 790 791 792 793 794
reRootMaxDepth :: Int
reRootMaxDepth = 100 -- TODO: this is a hack

reRootChildren :: Int -> NgramsTerm -> ReParent NgramsTerm
reRootChildren 0         _    _     = pure unit -- TODO: this is a hack
reRootChildren max_depth root ngram = do
795
  nre <- use (at ngram)
796 797
  traverseOf_ (_Just <<< _NgramsRepoElement <<< _children <<< folded) (\child -> do
    at child <<< _Just <<< _NgramsRepoElement <<< _root ?= root
798
    reRootChildren (max_depth - 1) root child) nre
799 800 801

reParent :: Maybe RootParent -> ReParent NgramsTerm
reParent mrp child = do
802 803
  at child <<< _Just <<< _NgramsRepoElement %= ((_parent .~ (view _parent <$> mrp)) <<<
                                                (_root   .~ (view _root   <$> mrp)))
804
  reRootChildren reRootMaxDepth (fromMaybe child (mrp ^? _Just <<< _root)) child
805 806 807 808 809 810

-- reParentNgramsPatch :: NgramsTerm -> ReParent NgramsPatch
-- ^ GHC would have accepted this type. Here reParentNgramsPatch checks but
--   not its usage in reParentNgramsTablePatch.
reParentNgramsPatch :: forall m. MonadState NgramsTable m
                    => NgramsTerm -> NgramsPatch -> m Unit
811
reParentNgramsPatch _      (NgramsReplace _) = pure unit -- TODO
812 813 814 815
reParentNgramsPatch parent (NgramsPatch {patch_children: PatchSet {rem, add}}) = do
  -- root_of_parent <- use (at parent <<< _Just <<< _NgramsElement <<< _root)
  -- ^ TODO this does not type checks, we do the following two lines instead:
  s <- use (at parent)
816
  let root_of_parent = s ^? (_Just <<< _NgramsRepoElement <<< _root <<< _Just)
817
  let rp = { root: fromMaybe parent root_of_parent, parent }
818 819 820
  traverse_ (reParent Nothing) rem
  traverse_ (reParent $ Just rp) add

821
reParentNgramsTablePatch :: ReParent NgramsPatches
822
reParentNgramsTablePatch = void <<< traversePatchMapWithIndex reParentNgramsPatch
823

824
{-
825 826 827 828 829 830 831 832 833 834 835 836
newElemsTable :: NewElems -> Map NgramsTerm NgramsElement
newElemsTable = mapWithIndex newElem
  where
    newElem ngrams list =
      NgramsElement
        { ngrams
        , list
        , occurrences: 1
        , parent:      Nothing
        , root:        Nothing
        , children:    mempty
        }
837
-}
838

839
applyNgramsTablePatch :: NgramsTablePatch -> NgramsTable -> NgramsTable
840
applyNgramsTablePatch { ngramsPatches } (NgramsTable m) =
841
  execState (reParentNgramsTablePatch ngramsPatches) $
Nicolas Pouillard's avatar
Nicolas Pouillard committed
842 843
  NgramsTable $ m { ngrams_repo_elements =
                      applyPatchMap applyNgramsPatch ngramsPatches m.ngrams_repo_elements }
844

845 846 847
applyNgramsPatches :: forall s. CoreState s -> NgramsTable -> NgramsTable
applyNgramsPatches {ngramsLocalPatch, ngramsStagePatch, ngramsValidPatch} =
  applyNgramsTablePatch (ngramsLocalPatch <> ngramsStagePatch <> ngramsValidPatch)
848
  -- First the valid patch, then the stage patch, and finally the local patch.
849 850 851
-----------------------------------------------------------------------------------

type CoreState s =
852 853 854 855 856 857 858
  { ngramsLocalPatch :: NgramsTablePatch
                     -- ^ These patches are local and not yet staged.
  , ngramsStagePatch :: NgramsTablePatch
                     -- ^ These patches are staged (scheduled for synchronization).
                     --   Requests are being performed at the moment.
  , ngramsValidPatch :: NgramsTablePatch
                     -- ^ These patches have been synchronized with the server.
859 860 861 862
  , ngramsVersion    :: Version
  | s
  }

863
{-
864 865
postNewNgrams :: forall s. Array NgramsTerm -> Maybe TermList -> CoreParams s -> Aff Unit
postNewNgrams newNgrams mayList {nodeId, listIds, tabType, session} =
866
  when (not (A.null newNgrams)) $ do
867
    (_ :: Array Unit) <- post session p newNgrams
868
    pure unit
869
  where p = PutNgrams tabType (head listIds) mayList (Just nodeId)
870

871 872
postNewElems :: forall s. NewElems -> CoreParams s -> Aff Unit
postNewElems newElems params = void $ traverseWithIndex postNewElem newElems
873
  where
874
    postNewElem ngrams list = postNewNgrams [ngrams] (Just list) params
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
-}

newNgramPatch :: TermList -> NgramsPatch
newNgramPatch list =
  NgramsReplace
  { patch_old: Nothing
  , patch_new:
      Just $ NgramsRepoElement
      { size: 1 -- TODO
      , list
      , root:     Nothing
      , parent:   Nothing
      , children: mempty
      -- , occurrences: 0 -- TODO
      }
  }
891

892 893
addNewNgramP :: NgramsTerm -> TermList -> NgramsTablePatch
addNewNgramP ngrams list =
894
  { ngramsPatches: singletonPatchMap ngrams (newNgramPatch list) }
895

896 897 898 899 900 901 902 903 904 905 906
addNewNgramA :: NgramsTerm -> TermList -> CoreAction
addNewNgramA ngrams list = CommitPatch $ addNewNgramP ngrams list

setTermListP :: NgramsTerm -> Replace TermList -> NgramsTablePatch
setTermListP ngram patch_list = singletonNgramsTablePatch ngram pe
  where
    pe = NgramsPatch { patch_list, patch_children: mempty }

setTermListA :: NgramsTerm -> Replace TermList -> CoreAction
setTermListA ngram termList = CommitPatch $ setTermListP ngram termList

907
putNgramsPatches :: forall s. CoreParams s -> VersionedNgramsPatches -> AffRESTError VersionedNgramsPatches
908
putNgramsPatches { listIds, nodeId, session, tabType } = put session putNgrams
909
  where putNgrams = PutNgrams tabType (head listIds) Nothing (Just nodeId)
910

911 912 913 914 915
syncPatches :: forall p s. CoreParams p -> T.Box (CoreState s) -> (Unit -> Aff Unit) -> Effect Unit
syncPatches props state callback = do
  { ngramsLocalPatch: ngramsLocalPatch@{ ngramsPatches }
  , ngramsStagePatch
  , ngramsVersion } <- T.read state
916
  when (isEmptyNgramsTablePatch ngramsStagePatch) $ do
917
    let pt = Versioned { data: ngramsPatches, version: ngramsVersion }
918
    launchAff_ $ do
919 920
      ePatches <- putNgramsPatches props pt
      case ePatches of
arturo's avatar
arturo committed
921
        Left err -> liftEffect $ here.warn2 "[syncPatches] RESTError" err
922 923 924
        Right (Versioned { data: newPatch, version: newVersion }) -> do
          callback unit
          liftEffect $ do
arturo's avatar
arturo committed
925
            here.log2 "[syncPatches] setting state, newVersion" newVersion
926 927 928 929 930 931 932 933
            T.modify_ (\s ->
              -- I think that sometimes this setState does not fully go through.
              -- This is an issue because the version number does not get updated and the subsequent calls
              -- can mess up the patches.
              s {
                  ngramsLocalPatch = fromNgramsPatches mempty
                , ngramsStagePatch = fromNgramsPatches mempty
                , ngramsValidPatch = fromNgramsPatches newPatch <> ngramsLocalPatch <> s.ngramsValidPatch
934
                              -- First the already valid patch, then the local patch, then the newly received newPatch.
935 936
                , ngramsVersion    = newVersion
                }) state
arturo's avatar
arturo committed
937
            here.log2 "[syncPatches] ngramsVersion" newVersion
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
    pure unit

{-
syncPatchesAsync :: forall p s. CoreParams p -> R.State (CoreState s) -> (Unit -> Aff Unit) -> Effect Unit
syncPatchesAsync props@{ listIds, tabType }
                 ({ ngramsLocalPatch: ngramsLocalPatch@{ ngramsPatches }
                  , ngramsStagePatch
                  , ngramsValidPatch
                  , ngramsVersion
                  } /\ setState) callback = do
  when (isEmptyNgramsTablePatch ngramsStagePatch) $ do
    let patch = Versioned { data: ngramsPatches, version: ngramsVersion }
    launchAff_ $ do
      Versioned { data: newPatch, version: newVersion } <- postNgramsPatchesAsync props patch
      callback unit
      liftEffect $ do
arturo's avatar
arturo committed
954
        here.log2 "[syncPatches] setting state, newVersion" newVersion
955 956 957 958 959 960 961 962
        setState $ \s ->
          s {
              ngramsLocalPatch = fromNgramsPatches mempty
            , ngramsStagePatch = fromNgramsPatches mempty
            , ngramsValidPatch = fromNgramsPatches newPatch <> ngramsLocalPatch <> s.ngramsValidPatch
                              -- First the already valid patch, then the local patch, then the newly received newPatch.
            , ngramsVersion    = newVersion
            }
arturo's avatar
arturo committed
963
        here.log2 "[syncPatches] ngramsVersion" newVersion
964
-}
965

966 967 968
commitPatch :: forall s. NgramsTablePatch -> T.Box (CoreState s) -> Effect Unit
commitPatch tablePatch state = do
  T.modify_ (\s -> s { ngramsLocalPatch = tablePatch <> s.ngramsLocalPatch }) state
969
    -- First we apply the patches we have locally and then the new patch (tablePatch).
970

971
loadNgramsTable :: PageParams -> AffRESTError VersionedNgramsTable
972
loadNgramsTable
973 974 975 976
  { nodeId
  , listIds
  , session
  , tabType }
977
  = get session query
978 979 980 981 982 983 984 985 986 987 988
    where
      query = GetNgramsTableAll { listIds
                                , tabType } (Just nodeId)
  -- where query = GetNgrams { limit
  --                         , offset: Just offset
  --                         , listIds
  --                         , orderBy: convOrderBy <$> orderBy
  --                         , searchQuery
  --                         , tabType
  --                         , termListFilter
  --                         , termSizeFilter } (Just nodeId)
989

990 991
type NgramsListByTabType = Map TabType VersionedNgramsTable

992
loadNgramsTableAll :: PageParams -> AffRESTError NgramsListByTabType
993
loadNgramsTableAll { nodeId, listIds, session } = do
994 995 996 997 998 999 1000
  let
    cTagNgramTypes =
      [ CTabTerms
      , CTabSources
      , CTabAuthors
      , CTabInstitutes
      ]
1001
    query tabType = GetNgramsTableAll { listIds, tabType } (Just nodeId)
1002

1003
  ret <- Map.fromFoldable <$> for cTagNgramTypes \cTagNgramType -> do
1004
    let tabType = TabCorpus $ TabNgramType cTagNgramType
1005
    result :: Either RESTError VersionedNgramsTable <- get session $ query tabType
1006
    pure $ Tuple tabType result
1007

1008 1009
  pure $ eitherMap ret

1010
convOrderBy :: T.OrderByDirection T.ColumnName -> OrderBy
1011 1012
convOrderBy (T.ASC  (T.ColumnName "Score")) = ScoreAsc
convOrderBy (T.DESC (T.ColumnName "Score")) = ScoreDesc
1013 1014
convOrderBy (T.ASC  _) = TermAsc
convOrderBy (T.DESC _) = TermDesc
1015

1016 1017
data CoreAction
  = CommitPatch NgramsTablePatch
1018
  | Synchronize { afterSync  :: Unit -> Aff Unit }
1019
  | ResetPatches
1020 1021

data Action
1022
  = CoreAction CoreAction
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
  | SetParentResetChildren (Maybe NgramsTerm)
  -- ^ This sets `ngramsParent` and resets `ngramsChildren`.
  | ToggleChild Boolean NgramsTerm
  -- ^ Toggles the NgramsTerm in the `PatchSet` `ngramsChildren`.
  -- If the `Boolean` is `true` it means we want to add it if it is not here,
  -- if it is `false` it is meant to be removed if not here.
  | AddTermChildren
  | ToggleSelect NgramsTerm
  -- ^ Toggles the NgramsTerm in the `Set` `ngramsSelection`.
  | ToggleSelectAll


1035
type CoreDispatch = CoreAction -> Effect Unit
1036
type Dispatch = Action -> Effect Unit
1037

1038
coreDispatch :: forall p s. CoreParams p -> T.Box (CoreState s) -> CoreDispatch
1039 1040
coreDispatch path state (Synchronize { afterSync }) =
  syncPatches path state afterSync
1041 1042 1043
coreDispatch _ state (CommitPatch pt) =
  commitPatch pt state
coreDispatch _ state ResetPatches =
1044
  T.modify_ (_ { ngramsLocalPatch = { ngramsPatches: mempty } }) state
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
isSingleNgramsTerm :: NgramsTerm -> Boolean
isSingleNgramsTerm nt = isSingleTerm $ ngramsTermText nt
  where
    isSingleTerm :: String -> Boolean
    isSingleTerm s = A.length words == 1
      where
        words = A.filter (not S.null) $ DSC.trim <$> (SU.words s)

filterTermSize :: Maybe TermSize -> NgramsTerm -> Boolean
filterTermSize (Just MonoTerm)  nt = isSingleNgramsTerm nt
filterTermSize (Just MultiTerm) nt = not $ isSingleNgramsTerm nt
1057
filterTermSize _                _  = true
1058

1059 1060 1061

------------------------------------------------------------------------
-- | Reset Button
1062
type SyncResetButtonsProps =
1063
  ( afterSync        :: Unit -> Aff Unit
1064
  , ngramsLocalPatch :: NgramsTablePatch
1065
  , performAction    :: CoreDispatch
1066 1067 1068 1069
  )

syncResetButtons :: Record SyncResetButtonsProps -> R.Element
syncResetButtons p = R.createElement syncResetButtonsCpt p []
1070
syncResetButtonsCpt :: R.Component SyncResetButtonsProps
James Laver's avatar
James Laver committed
1071
syncResetButtonsCpt = here.component "syncResetButtons" cpt
1072
  where
1073
    cpt { afterSync, ngramsLocalPatch, performAction } _ = do
1074 1075
      synchronizing <- T.useBox false
      synchronizing' <- T.useLive T.unequal synchronizing
1076 1077 1078

      let
        hasChanges = ngramsLocalPatch /= mempty
1079
        hasChangesClass = if hasChanges then "" else " disabled"
1080

1081 1082
        synchronizingClass = if synchronizing' then " disabled" else ""

1083 1084
        resetClick _ = do
          performAction ResetPatches
1085 1086

        synchronizeClick _ = delay unit $ \_ -> do
1087
          T.write_ true synchronizing
1088 1089
          performAction $ Synchronize { afterSync: newAfterSync }

1090 1091
        newAfterSync x = do
          afterSync x
1092
          liftEffect $ T.write_ false synchronizing
1093

1094 1095
      pure $ H.div { className: "btn-toolbar" }
        [ H.div { className: "btn-group mr-2" }
1096
          [ H.button { className: "btn btn-danger " <> hasChangesClass <> synchronizingClass
1097 1098 1099 1100
                     , on: { click: resetClick }
                     } [ H.text "Reset" ]
          ]
        , H.div { className: "btn-group mr-2" }
1101
          [ H.button { className: "btn btn-primary " <> hasChangesClass <> synchronizingClass
1102 1103
                     , on: { click: synchronizeClick }
                     } [ H.text "Sync" ]
1104
          ]
1105
        ]
1106

arturo's avatar
arturo committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
------------------------------------------------------------------


type AutoSyncInput s =
  ( state  :: T.Box (CoreState s)
  , action :: CoreDispatch
  )

type AutoSyncOutput =
  -- @XXX: cannot use an Either here due to the mecanism of `syncPatches` only
  --       returning an `Aff Unit`
  -- ( result :: T.Box (Maybe (Either RESTError Unit))
  ( result    :: T.Box (Maybe Unit)
  , onPending :: T.Box Boolean
  )

useAutoSync :: forall s.
     Record (AutoSyncInput s)
  -> R.Hooks (Record AutoSyncOutput)
useAutoSync { state, action } = do
  -- States
  onPending <- T.useBox false
  result    <- T.useBox Nothing

  ngramsLocalPatch <-
    T.useFocused
      (_.ngramsLocalPatch)
      (\a b -> b { ngramsLocalPatch = a }) state

  -- Computed
  let
    exec { new } =
      let hasChanges = new /= mempty
      in when hasChanges do
        T.write_ true onPending
        T.write_ Nothing result
        action $ Synchronize
          { afterSync: onSuccess
          }

    onSuccess _ = liftEffect do
      T.write_ false onPending
      T.write_ (Just unit) result

  -- Hooks
  R.useEffectOnce' $ T.listen exec ngramsLocalPatch

  -- Output
  pure
    { onPending
    , result
    }

------------------------------------------------------------------
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

type ResetButton = (Unit -> Aff Unit)
               -> { ngramsPatches :: PatchMap NgramsTerm NgramsPatch }
               -> (Action -> Effect Unit)
               -> Array R.Element

chartsAfterSync :: forall props discard.
  { listIds :: Array Int
  , nodeId  :: Int
  , session :: Session
  , tabType :: TabType
  | props
  }
1174
  -> T.Box (Array FrontendError)
1175
  -> T.Box GAT.Storage
1176 1177
  -> discard
  -> Aff Unit
1178 1179 1180
chartsAfterSync path'@{ nodeId } errors tasks _ = do
  eTask <- postNgramsChartsAsync path'
  handleRESTError errors eTask $ \task -> liftEffect $ do
arturo's avatar
arturo committed
1181
    here.log2 "[chartsAfterSync] Synchronize task" task
1182
    GAT.insert nodeId task tasks
1183

1184
postNgramsChartsAsync :: forall s. CoreParams s -> AffRESTError AsyncTaskWithType
1185
postNgramsChartsAsync { listIds, nodeId, session, tabType } = do
1186
    eTask :: Either RESTError AsyncTask <- post session putNgramsAsync acu
1187
    pure $ (\task -> AsyncTaskWithType { task, typ: UpdateNgramsCharts }) <$> eTask
1188 1189 1190 1191
  where
    acu = AsyncNgramsChartsUpdate { listId: head listIds
                                  , tabType }
    putNgramsAsync = PostNgramsChartsAsync (Just nodeId)