createListeners.tsx 988 B

1234567891011121314151617181920212223242526272829303132333435
  1. export function createListeners(type: 'window' | 'document') {
  2. const eventTarget = type === 'window' ? window : document;
  3. let listeners: Array<Record<string, any>> = [];
  4. const handler = <K extends keyof GlobalEventHandlersEventMap>(
  5. eventData: Record<string, any>,
  6. event: K
  7. ) => {
  8. const filteredListeners = listeners.filter(listener =>
  9. listener.hasOwnProperty(event)
  10. );
  11. if (eventData?.key === 'Escape') {
  12. return filteredListeners[1]?.[event]?.(eventData);
  13. }
  14. return filteredListeners[0]?.[event]?.(eventData);
  15. };
  16. eventTarget.addEventListener = jest.fn((event, cb) => {
  17. listeners.push({
  18. [event]: cb,
  19. });
  20. });
  21. eventTarget.removeEventListener = jest.fn(event => {
  22. listeners = listeners.filter(listener => !listener.hasOwnProperty(event));
  23. });
  24. return {
  25. mouseDown: (domEl: HTMLElement) => handler({target: domEl}, 'mousedown'),
  26. keyDown: (key: KeyboardEvent['key']) => handler({key}, 'keydown'),
  27. };
  28. }