All Projects → noderaider → Redux Idle Monitor

noderaider / Redux Idle Monitor

Licence: mit
A Redux component to schedule events at stages of user idleness across multiple browser tabs.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Redux Idle Monitor

Repatch
Dispatch reducers
Stars: ✭ 516 (+391.43%)
Mutual labels:  middleware, dispatch
Rexlin600.github.io
系列博客、涵盖领域广、不定时更新、欢迎加入
Stars: ✭ 102 (-2.86%)
Mutual labels:  middleware
Tower
async fn(Request) -> Result<Response, Error>
Stars: ✭ 1,305 (+1142.86%)
Mutual labels:  middleware
Rye
A tiny http middleware for Golang with added handlers for common needs.
Stars: ✭ 95 (-9.52%)
Mutual labels:  middleware
Depictr
A middleware for rendering static pages when crawled by search engines
Stars: ✭ 92 (-12.38%)
Mutual labels:  middleware
Dotweb
Simple and easy go web micro framework
Stars: ✭ 1,354 (+1189.52%)
Mutual labels:  middleware
Chi
lightweight, idiomatic and composable router for building Go HTTP services
Stars: ✭ 10,581 (+9977.14%)
Mutual labels:  middleware
Express Recaptcha
Implementation of google recaptcha v2 & V3 solutions for express.js
Stars: ✭ 104 (-0.95%)
Mutual labels:  middleware
Redux Search
Redux bindings for client-side search
Stars: ✭ 1,377 (+1211.43%)
Mutual labels:  middleware
Min
A minimalistic web framework with route grouping and middleware chaining
Stars: ✭ 95 (-9.52%)
Mutual labels:  middleware
Asyncrun.vim
🚀 Run Async Shell Commands in Vim 8.0 / NeoVim and Output to the Quickfix Window !!
Stars: ✭ 1,332 (+1168.57%)
Mutual labels:  dispatch
Laravel Localize Middleware
Configurable localization middleware for your Laravel >=5.1 application
Stars: ✭ 92 (-12.38%)
Mutual labels:  middleware
Sunset.css
This library offers a collection of different CSS-powered transitions.
Stars: ✭ 99 (-5.71%)
Mutual labels:  transition
Microstates
Composable state primitives for JavaScript
Stars: ✭ 1,312 (+1149.52%)
Mutual labels:  transition
Rxcache
A local reactive cache for Java and Android. Now, it supports heap memory、off-heap memory and disk cache.
Stars: ✭ 102 (-2.86%)
Mutual labels:  middleware
Connect Cas2
NodeJS implement of CAS(Central Authentication Service) client.
Stars: ✭ 91 (-13.33%)
Mutual labels:  middleware
Transformationlayout
🌠 Transform into a different view or activity using morphing animations.
Stars: ✭ 1,329 (+1165.71%)
Mutual labels:  transition
Twig
Twig - less is more's web server for golang
Stars: ✭ 98 (-6.67%)
Mutual labels:  middleware
Tesla
The flexible HTTP client library for Elixir, with support for middleware and multiple adapters.
Stars: ✭ 1,588 (+1412.38%)
Mutual labels:  middleware
Redux Favicon
Redux middleware that displays colourful notification badges in the favicon area.
Stars: ✭ 103 (-1.9%)
Mutual labels:  middleware

NPM

A React component and Redux connector to add functionality to invoke events at various stages of idleness during a users session.

NPM

⚡️ Now supports realtime synchronization across tabs when user is active. Tested IE10+ / Edge, Chrome, FireFox

npm i -S redux-idle-monitor

Can be used standalone with redux or in tandem with react-redux-idle-monitor to track whether a user is idle and progress them through a set of idle status actions with varying timeouts.

See a working demo in a real project at redux-webpack-boilerplate


How it works

redux-idle-monitor works similiar to other redux libraries (e.g. redux-form) except that it exports a configure function that accepts options from the library consumer and returns an object with middleware, reducer, and actions keys. The input options allow redux-idle-monitor to configure the idle statuses that will occur at varying times of idleness within your app as well as actions to dispatch when your users transition to an active status, or any one of your configured idle statuses.

middleware - The middleware that gets returned from configure handles listening for and scheduling idle status events, and enabling and disabling the detection of user activity. It should be added to your redux middleware array in both development and production versions. redux-idle-monitor requires you to be using thunk-middleware at this time (I'd like to add saga support soon). When process.env.NODE_ENV !== 'production' additional assertions are made throughout redux-idle-monitor that will be removed in your production build if you use UglifyJS or similiar mangler.

reducer - The reducer that gets returned from configure should be imported into your reducer tree as a top level 'idle' node (the same way that you would import redux-form or react-redux-router). At this time, the idle node cannot be changed, but if its a common request, it can be modified to support other arrangements easily.

actions - The actions object that is returned from configure contains start and stop actions that can be dispatched from anywhere in your app that has access to your stores dispatch function. redux-idle-monitor does not start monitoring user activity until you dispatch the start action. Good places to run these might be in the same area that your app authorizes users (start monitoring whether the user is idle when authorized and stop when the user is logged out).


Configuration

The best way to configure redux-idle-monitor and then use the configured middleware, reducer, and actions within your app are to create a redux-idle-monitor component directory in the same area of your app that you configure your redux store. For this example, I've put it in src/state/components/redux-idle-monitor. Create an index.js file to house your configuration:

src/state/components/redux-idle-monitor/index.js

import configure from 'redux-idle-monitor'
import { IDLE_STATUSES } from './constants'
import { idleStatusDelay, activeStatusAction, idleStatusAction } from './actions'

// These are the default events that will trigger user active status but can be customized if provided.
const activeEvents =  [ 'mousemove', 'keydown', 'wheel', 'DOMMouseScroll', 'mouseWheel', 'mousedown', 'touchstart', 'touchmove', 'MSPointerDown', 'MSPointerMove' ]

const opts =  { appName: 'todo-app'
              , IDLE_STATUSES
              , idleStatusDelay
              , activeStatusAction
              , idleStatusAction
              , activeEvents
              }

const { middleware, reducer, actions } = configure(opts)
export { middleware, reducer, actions }
Configurable Constants

As shown above this is importing an IDLE_STATUSES constant from constants.js. IDLE_STATUSES are a simple array of string constant statuses that are used for the idleStatus property of redux idle state. The initial value for idleStatus will always be ACTIVE and from there it will progress through your configured IDLE_STATUSES in order until it reaches the final one where it will progress no further. Here is an example of what the constants.js could look like:

src/state/components/react-idle-monitor/constants.js

export const IDLESTATUS_AWAY = 'AWAY'
export const IDLESTATUS_INACTIVE = 'INACTIVE'
export const IDLESTATUS_EXPIRED = 'EXPIRED'

export const IDLE_STATUSES = [IDLESTATUS_AWAY, IDLESTATUS_INACTIVE, IDLESTATUS_EXPIRED]
Configurable Actions

In addition, we are also importing idleStatusDelay, activeStatusAction, and idleStatusAction from actions.js within the same directory.

src/state/components/react-idle-monitor/actions.js

import { IDLESTATUS_AWAY, IDLESTATUS_INACTIVE, IDLESTATUS_EXPIRED } from './constants'

//...

export const idleStatusDelay = idleStatus => (dispatch, getState) => {
  if(idleStatus === IDLESTATUS_AWAY)
    return 20000 // User becomes away after 20 seconds inactivity
  if(idleStatus === IDLESTATUS_INACTIVE)
    return getInactiveDelayFromDB() // Call database to look up the users delay time
  if(idleStatus === IDLESTATUS_EXPIRED)
    return 60000 // Log them out after another minute after they enter the inactive status
}

export const activeStatusAction = (dispatch, getState) => alert('welcome back!')

export const idleStatusAction = idleStatus => (dispatch, getState) => {
  if(idleStatus === IDLESTATUS_AWAY)
    console.info('user is away...')
  if(idleStatus === IDLESTATUS_INACTIVE)
    alert('You still there or what??')
  if(idleStatus === IDLESTATUS_EXPIRED)
    dispatch(logout())
}


idleStatusDelay: (idleStatus) => (dispatch, getState) => delay

where

typeof delay === 'number'

  • accepts idleStatus string argument and returns a thunk action that will return the delay for any idle status that you've configured.
  • gets dispatched by idle middleware to get the number of milliseconds of user idleness that must occur before transitioning into the specified idle status.
  • if user activity is detected the user will transition back to the ACTIVE state.
  • will throw if the thunk action does not return a number type for any idleStatus specified in the IDLE_STATUSES array.

activeStatusAction: (dispatch, getState) => void

  • returns logic to be executed in your app whenever the user enters the ACTIVE status.
  • dispatched by idle middleware only when the user has transitioned to one of your idle statuses and then back into the ACTIVE status.

idleStatusAction: (idleStatus) => (dispatch, getState) => void

  • accepts idleStatus string argument and returns a thunk action to run app logic that should occur when user enters one of your configured idle statuses.
  • should contain logic that handles every configured idle status that was passed in the IDLE_STATUSES array when configured.
  • run logic to show the user alerts, screensavers, auto-logout etc. from here.

Integration

Now you must import import the configured reducer into your top level combineReducers as the 'idle' node like so (api and errors are two of your other top level reducers in this example).

src/state/reducers/index.js

import { combineReducers } from 'redux'
import { api } from './api'
import { errors } from './errors'
import { reducer as form } from 'redux-form'
import { reducer as idle } from '../components/redux-idle-monitor'

const rootReducer = combineReducers({ api
                                    , errors
                                    , form
                                    , idle
                                    })
export default rootReducer

The last step is to import the idle middleware into your store and dispatch the start action when you want to start monitoring user idleness.

src/state/store/configureStore.js

import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from '../reducers'
import DevTools from '../../containers/DevTools'
import { middleware as idleMiddleware } from '../components/redux-idle-monitor'
import { actions as idleActions } from '../comonents/redux-idle-monitor'

import { thunk, readyStatePromise, createLogger, crashReporter } from 'redux-middleware'

const logger = createLogger()

const composeStore = compose( applyMiddleware(thunk, idleMiddleware, readyStatePromise, logger, crashReporter)
                            , DevTools.instrument()
                            )(createStore)

export default function configureStore() {
  const store = composeStore(rootReducer)

  // Will start the idle monitoring when the user logs in, and stop it if the user is signed out.
  store.subscribe(() => {
    let previousIsAuthorized = currentIsAuthorized
    let state = store.getState()
    // calls a function that selects whether the user is authorized from the current state
    currentIsAuthorized = selectIsAuthorized(state)

    if(currentIsAuthorized !== previousIsAuthorized)
      store.dispatch((currentIsAuthorized ? idleActions.start : idleActions.stop)())
  })
  return store
}

You're done. Please open an issue if there are any features that you would like to see added.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].