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.ts 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { IStore } from '../../app/types';
  2. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app/actionTypes';
  3. import MiddlewareRegistry from '../redux/MiddlewareRegistry';
  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: Function | null = 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: IStore['dispatch'], event: any) {
  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 }: { dispatch: IStore['dispatch']; }) {
  53. _stopListeningForUserInteraction();
  54. userInteractionListener = _onUserInteractionReceived.bind(null, dispatch);
  55. // @ts-ignore
  56. window.addEventListener('mousedown', userInteractionListener);
  57. // @ts-ignore
  58. window.addEventListener('keydown', userInteractionListener);
  59. }
  60. /**
  61. * De-registers listeners for user interaction with the page.
  62. *
  63. * @private
  64. * @returns {void}
  65. */
  66. function _stopListeningForUserInteraction() {
  67. // @ts-ignore
  68. window.removeEventListener('mousedown', userInteractionListener);
  69. // @ts-ignore
  70. window.removeEventListener('keydown', userInteractionListener);
  71. userInteractionListener = null;
  72. }