You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // @flow
  2. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app';
  3. import { MiddlewareRegistry } from '../redux';
  4. import {
  5. SET_USER_INTERACTION_LISTENER,
  6. USER_INTERACTION_RECEIVED
  7. } from './actionTypes';
  8. /**
  9. * Implements the entry point of the middleware of the feature base/user-interaction.
  10. *
  11. * @param {Store} store - The redux store.
  12. * @returns {Function}
  13. */
  14. MiddlewareRegistry.register(store => next => action => {
  15. switch (action.type) {
  16. case APP_WILL_MOUNT:
  17. _startListeningForUserInteraction(store);
  18. break;
  19. case APP_WILL_UNMOUNT:
  20. case USER_INTERACTION_RECEIVED:
  21. _stopListeningForUserInteraction(store);
  22. break;
  23. }
  24. return next(action);
  25. });
  26. /**
  27. * Registers listeners to notify redux of any user interaction with the page.
  28. *
  29. * @param {Object} store - The redux store.
  30. * @private
  31. * @returns {void}
  32. */
  33. function _startListeningForUserInteraction(store) {
  34. const userInteractionListener = event => {
  35. if (event.isTrusted) {
  36. store.dispatch({
  37. type: USER_INTERACTION_RECEIVED
  38. });
  39. _stopListeningForUserInteraction(store);
  40. }
  41. };
  42. window.addEventListener('mousedown', userInteractionListener);
  43. window.addEventListener('keydown', userInteractionListener);
  44. store.dispatch({
  45. type: SET_USER_INTERACTION_LISTENER,
  46. userInteractionListener
  47. });
  48. }
  49. /**
  50. * Un-registers listeners intended to notify when the user has interacted with
  51. * the page.
  52. *
  53. * @param {Object} store - The redux store.
  54. * @private
  55. * @returns {void}
  56. */
  57. function _stopListeningForUserInteraction({ getState, dispatch }) {
  58. const { userInteractionListener } = getState()['features/base/app'];
  59. if (userInteractionListener) {
  60. window.removeEventListener('mousedown', userInteractionListener);
  61. window.removeEventListener('keydown', userInteractionListener);
  62. dispatch({
  63. type: SET_USER_INTERACTION_LISTENER,
  64. userInteractionListener: undefined
  65. });
  66. }
  67. }