FacetsTable.purs 14.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
module Gargantext.Components.FacetsTable where

import Affjax (defaultRequest, request)
import Affjax.RequestBody (RequestBody(..))
import Affjax.ResponseFormat (printResponseFormatError)
import Affjax.ResponseFormat as ResponseFormat
import Control.Monad.Cont.Trans (lift)
import Data.Argonaut (class DecodeJson, class EncodeJson, decodeJson, encodeJson, jsonEmptyObject, (.?), (:=), (~>))
import Data.Array (drop, take, (:), filter)
import Data.Either (Either(..))
import Data.Foldable (intercalate)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
import Data.HTTP.Method (Method(..))
import Data.Maybe (Maybe(..), maybe)
import Data.Set (Set)
import Data.Set as Set
import Data.Tuple (Tuple(..))
import Effect (Effect)
import Effect.Aff (Aff)
import Effect.Class (liftEffect)
import React as React
import React (ReactClass, ReactElement, Children)
------------------------------------------------------------------------
import Gargantext.Prelude
import Gargantext.Config (End(..), NodeType(..), OrderBy(..), Path(..), TabType, toUrl)
import Gargantext.Config.REST (put, post, deleteWithBody)
import Gargantext.Components.Loader as Loader
import Gargantext.Components.Table as T
import Gargantext.Utils.DecodeMaybe ((.|))
import React.DOM (a, br', button, div, i, input, p, text, span)
import React.DOM.Props (_type, className, href, onClick, placeholder, style, checked, target)
import Thermite (PerformAction, Render, Spec, defaultPerformAction, modifyState_, simpleSpec, hideState)
------------------------------------------------------------------------
-- TODO: Search is pending
-- TODO: Fav is pending
-- TODO: Sort is Pending
-- TODO: Filter is Pending

type NodeID = Int
type TotalRecords = Int

newtype SearchQuery = SearchQuery
  { query :: Array String
  , id    :: Int
  }

instance encodeJsonSearchQuery :: EncodeJson SearchQuery where
  encodeJson (SearchQuery post)
     = "query"     := post.query
    ~> "corpus_id" := post.id
    ~> jsonEmptyObject

newtype SearchResults = SearchResults { results :: Array Response }

instance decodeSearchResults :: DecodeJson SearchResults where
  decodeJson json = do
    obj     <- decodeJson json
    results <- obj .? "results"
    pure $ SearchResults {results}

type Props =
  { nodeId :: Int
  , query :: Array String
  , totalRecords :: Int
  , chart :: ReactElement
67
  , container :: T.TableContainerProps -> Array ReactElement
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 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 167 168 169 170 171
  }

type State =
  { documentIdsToDelete :: Set Int
  , documentIdsDeleted  :: Set Int
  }

initialState :: State
initialState =
  { documentIdsToDelete: mempty
  , documentIdsDeleted:  mempty
  }

data Action
  = MarkFavorites (Array Int)
  | ToggleDocumentToDelete Int
  | Trash

newtype Pair = Pair
  { id    :: Int
  , label :: String
  }

derive instance genericPair :: Generic Pair _

instance showPair :: Show Pair where
  show = genericShow

newtype DocumentsView
  = DocumentsView
    { id     :: Int
    , date   :: String
    , title  :: String
    , source :: String
    , score  :: Int
    , pairs  :: Array Pair
    , delete :: Boolean
    }


derive instance genericDocumentsView :: Generic DocumentsView _

instance showDocumentsView :: Show DocumentsView where
  show = genericShow

newtype Response = Response
  { id        :: Int
  , date      :: String
  , hyperdata :: Hyperdata
  , score     :: Int
  , pairs     :: Array Pair
  }


newtype Hyperdata = Hyperdata
  { title  :: String
  , source :: String
  }

--instance decodeHyperdata :: DecodeJson Hyperdata where
--  decodeJson json = do
--    obj    <- decodeJson json
--    title  <- obj .? "title"
--    source <- obj .? "source"
--    pure $ Hyperdata { title,source }
--instance decodeResponse :: DecodeJson Response where
--  decodeJson json = do
--    obj        <- decodeJson json
--    cid        <- obj .? "id"
--    created    <- obj .? "created"
--    favorite   <- obj .? "favorite"
--    ngramCount <- obj .? "ngramCount"
--    hyperdata  <- obj .? "hyperdata"
--    pure $ Response { cid, created, favorite, ngramCount, hyperdata }


instance decodePair :: DecodeJson Pair where
  decodeJson json = do
    obj   <- decodeJson json
    id    <- obj .? "id"
    label <- obj .? "label"
    pure $ Pair { id, label }

instance decodeHyperdata :: DecodeJson Hyperdata where
  decodeJson json = do
    obj    <- decodeJson json
    title  <- obj .| "title"
    source <- obj .| "source"
    pure $ Hyperdata { title,source }

instance decodeResponse :: DecodeJson Response where
  decodeJson json = do
    obj       <- decodeJson json
    id        <- obj .? "id"
    -- date      <- obj .? "date" -- TODO
    date      <- pure "2018"
    score     <- obj .? "score"
    hyperdata <- obj .? "hyperdata"
    pairs     <- obj .? "pairs"
    pure $ Response { id, date, score, hyperdata, pairs }



-- | Filter
172
-- TODO: unused
173 174 175 176 177 178 179 180
filterSpec :: forall state props action. Spec state props action
filterSpec = simpleSpec defaultPerformAction render
  where
    render d p s c = [div [ className "col-md-2", style {textAlign : "center", marginLeft : "0px", paddingLeft : "0px"}] [ text "    Filter "
                     , input [className "form-control", placeholder "Filter here"]
                     ]]

docViewSpec :: Spec {} Props Void
181
docViewSpec = hideState (const initialState) layoutDocviewGraph
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

-- | Main layout of the Documents Tab of a Corpus
layoutDocview :: Spec State Props Action
layoutDocview = simpleSpec performAction render
  where
    performAction :: PerformAction State Props Action
    performAction (MarkFavorites nids) {nodeId} _ =
      void $ lift $ putFavorites nodeId (FavoriteQuery {favorites: nids})
    --TODO add array of delete rows here
    performAction (ToggleDocumentToDelete nid) _ _ =
      modifyState_ \state -> state {documentIdsToDelete = toggleSet nid state.documentIdsToDelete}
    performAction Trash {nodeId} {documentIdsToDelete} = do
      void $ lift $ deleteDocuments nodeId (DeleteDocumentQuery {documents: Set.toUnfoldable documentIdsToDelete})
      modifyState_ \{documentIdsToDelete, documentIdsDeleted} ->
        { documentIdsToDelete: mempty
        , documentIdsDeleted: documentIdsDeleted <> documentIdsToDelete
        }

    render :: Render State Props Action
201
    render dispatch {nodeId, query, totalRecords, chart, container} deletionState _ =
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
      [ br'
      , div [ style {textAlign : "center"}] [ text "    Filter "
                     , input [className "form-control", style {width : "120px", display : "inline-block"}, placeholder "Filter here"]
                     ]
      , p [] [text ""]
      , br'
      , div [className "container1"]
        [ div [className "row"]
          [ chart
          , div [className "col-md-12"]
            [ pageLoader
                { path: initialPageParams {nodeId, query}
                , totalRecords
                , deletionState
                , dispatch
217
                , container
218 219 220 221 222 223 224 225 226 227 228 229 230 231
                }
            ]
          , div [className "col-md-12"]
             [ button [ style {backgroundColor: "peru", padding : "9px", color : "white", border : "white", float: "right"}
                      , onClick $ (\_ -> dispatch Trash)
                      ]
               [  i [className "glyphitem glyphicon glyphicon-trash", style {marginRight : "9px"}] []
               ,  text "Trash it !"
               ]
             ]
          ]
        ]
      ]

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250


layoutDocviewGraph :: Spec State Props Action
layoutDocviewGraph = simpleSpec performAction render
  where
    performAction :: PerformAction State Props Action
    performAction (MarkFavorites nids) {nodeId} _ =
      void $ lift $ putFavorites nodeId (FavoriteQuery {favorites: nids})
    --TODO add array of delete rows here
    performAction (ToggleDocumentToDelete nid) _ _ =
      modifyState_ \state -> state {documentIdsToDelete = toggleSet nid state.documentIdsToDelete}
    performAction Trash {nodeId} {documentIdsToDelete} = do
      void $ lift $ deleteDocuments nodeId (DeleteDocumentQuery {documents: Set.toUnfoldable documentIdsToDelete})
      modifyState_ \{documentIdsToDelete, documentIdsDeleted} ->
        { documentIdsToDelete: mempty
        , documentIdsDeleted: documentIdsDeleted <> documentIdsToDelete
        }

    render :: Render State Props Action
251
    render dispatch {nodeId, query, totalRecords, chart, container} deletionState _ =
252 253 254 255 256 257 258 259 260 261 262 263 264
      [ br'

      , p [] [text ""]
      , br'
      , div [className "container-fluid"]
        [ div [className "row"]
          [ chart
          , div [className "col-md-12"]
            [ pageLoader
                { path: initialPageParams {nodeId, query}
                , totalRecords
                , deletionState
                , dispatch
265
                , container
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                }
            , button [ style {backgroundColor: "peru", padding : "9px", color : "white", border : "white", float: "right"}
                      , onClick $ (\_ -> dispatch Trash)
                      ]
               [  i [className "glyphitem glyphicon glyphicon-trash", style {marginRight : "9px"}] []
               ,  text "Trash it !"
               ]
            ]

          ]
        ]
      ]



281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
type PageParams = {nodeId :: Int, query :: Array String, params :: T.Params}

initialPageParams :: {nodeId :: Int, query :: Array String} -> PageParams
initialPageParams {nodeId, query} = {nodeId, query, params: T.initialParams}

loadPage :: PageParams -> Aff (Array DocumentsView)
loadPage {nodeId, query, params: {limit, offset, orderBy}} = do
  logs "loading documents page: loadPage with Offset and limit"
  let url = toUrl Back (Search { offset, limit, orderBy: convOrderBy <$> orderBy }) Nothing
  SearchResults res <- post url $ SearchQuery {id: nodeId, query}
  pure $ res2corpus <$> res.results
  where
    res2corpus :: Response -> DocumentsView
    res2corpus (Response { id, date, score, pairs
                         , hyperdata: Hyperdata {title, source}
                         }) =
      DocumentsView
        { id
        , date
        , title
        , source
        , score
        , pairs
        , delete : false
        }
    convOrderBy (T.ASC  (T.ColumnName "Date")) = DateAsc
    convOrderBy (T.DESC (T.ColumnName "Date")) = DateDesc
    convOrderBy (T.ASC  (T.ColumnName "Title")) = TitleAsc
    convOrderBy (T.DESC (T.ColumnName "Title")) = TitleDesc

    convOrderBy _ = DateAsc -- TODO

type PageLoaderProps row =
  { path :: PageParams
  , totalRecords :: Int
  , dispatch :: Action -> Effect Unit
  , deletionState :: State
318
  , container :: T.TableContainerProps -> Array ReactElement
319 320 321 322 323 324 325 326
  | row
  }

renderPage :: forall props path.
              Render (Loader.State {nodeId :: Int, query :: Array String | path} (Array DocumentsView))
                     { totalRecords :: Int
                     , dispatch :: Action -> Effect Unit
                     , deletionState :: State
327
                     , container :: T.TableContainerProps -> Array ReactElement
328 329 330 331
                     | props
                     }
                     (Loader.Action PageParams)
renderPage _ _ {loaded: Nothing} _ = [] -- TODO loading spinner
332
renderPage loaderDispatch { totalRecords, dispatch, container
333 334 335 336 337
                          , deletionState: {documentIdsToDelete, documentIdsDeleted}}
                          {currentPath: {nodeId, query}, loaded: Just res} _ =
  [ T.tableElt
      { rows
      , setParams: \params -> liftEffect $ loaderDispatch (Loader.SetPath {nodeId, query, params})
338
      , container
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
      , colNames:
          T.ColumnName <$>
          [ ""
          , "Date"
          , "Title"
          , "Source"
          , "Authors"
          , "Delete"
          ]
      , totalRecords
      }
  ]
  where
    -- TODO: how to interprete other scores?
    fa 0 = "far "
    fa _ = "fas "
    isChecked id = Set.member id documentIdsToDelete
    isDeleted (DocumentsView {id}) = Set.member id documentIdsDeleted
    pairUrl (Pair {id,label})
      | id > 1    = [a [href (toUrl Front NodeContact (Just id)), target "blank"] [text label]]
      | otherwise = [text label]
    comma = span [] [text ", "]
    rows = (\(DocumentsView {id,score,title,source,date,pairs,delete}) ->
                let
                  strikeIfDeleted
                    | delete    = [style {textDecoration : "line-through"}]
                    | otherwise = []
                in
                { row:
                    [ div []
                      [ a [ className $ fa score <> "fa-star"
                          , onClick $ const $ dispatch $ MarkFavorites [id]
                          ] []
                      ]
                    -- TODO show date: Year-Month-Day only
                    , div strikeIfDeleted [text date]
                    , a (strikeIfDeleted <> [ href (toUrl Front Url_Document (Just id))
                                            , target "blank"])
                        [ text title ]
                    , div strikeIfDeleted [text source]
                    , div strikeIfDeleted $ intercalate [comma] $ pairUrl <$> pairs
                    , input [ _type "checkbox"
                            , checked (isChecked id)
                            , onClick $ const $ dispatch $ ToggleDocumentToDelete id]
                    ]
                , delete: true
                }) <$> filter (not <<< isDeleted) res

pageLoaderClass :: ReactClass (PageLoaderProps (children :: Children))
pageLoaderClass = Loader.createLoaderClass' "PageLoader" loadPage renderPage

pageLoader :: PageLoaderProps () -> ReactElement
pageLoader props = React.createElement pageLoaderClass props []

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

newtype FavoriteQuery = FavoriteQuery
                        { favorites :: Array Int
                        }

instance encodeJsonFQuery :: EncodeJson FavoriteQuery where
  encodeJson (FavoriteQuery post)
     = "favorites" := post.favorites
       ~> jsonEmptyObject

newtype DeleteDocumentQuery = DeleteDocumentQuery
  {
    documents :: Array Int
  }


instance encodeJsonDDQuery :: EncodeJson DeleteDocumentQuery where
  encodeJson (DeleteDocumentQuery post)
     = "documents" := post.documents
       ~> jsonEmptyObject

putFavorites :: Int -> FavoriteQuery -> Aff (Array Int)
putFavorites nodeId = put (toUrl Back Node (Just nodeId) <> "/favorites")

deleteFavorites :: Int -> FavoriteQuery -> Aff (Array Int)
deleteFavorites nodeId = deleteWithBody (toUrl Back Node (Just nodeId) <> "/favorites")

deleteDocuments :: Int -> DeleteDocumentQuery -> Aff (Array Int)
deleteDocuments nodeId = deleteWithBody (toUrl Back Node (Just nodeId) <> "/documents")

-- TODO: not optimal but Data.Set lacks some function (Set.alter)
toggleSet :: forall a. Ord a => a -> Set a -> Set a
toggleSet a s
  | Set.member a s = Set.delete a s
  | otherwise      = Set.insert a s