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

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