{"version":3,"file":"react-dom-event.cjs","sources":["../../src/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { createContext, createElement, useContext, useEffect, useState } from 'react';\n\nexport type EventTypes = MouseEvent | TouchEvent | KeyboardEvent;\nexport type HandlerType = (event: EventTypes) => void;\n\nexport type EventContextType = {\n  subscribe: (handler: HandlerType) => void;\n};\n\nexport const EventContext = createContext<EventContextType | undefined>(undefined);\n\nexport type EventProviderProps = {\n  events?: string[];\n  children?: ReactNode;\n};\nexport function EventProvider({ events = ['click'], children }: EventProviderProps) {\n  const state = useState<HandlerType[]>([]);\n  const handlers = state[0]; // reduce transpiled array helpers\n\n  function onEvent(event: EventTypes) {\n    handlers.forEach((handler: HandlerType) => handler(event));\n  }\n  function subscribe(handler: HandlerType) {\n    handlers.push(handler);\n    return () => handlers.splice(handlers.indexOf(handler), 1);\n  }\n\n  useEffect(() => {\n    events.forEach((event) => window.document.addEventListener(event, onEvent, true));\n\n    return () => events.forEach((event) => window.document.removeEventListener(event, onEvent, true));\n  });\n\n  return createElement(\n    EventContext.Provider,\n    {\n      value: {\n        subscribe,\n      },\n    },\n    children\n  );\n}\n\nexport function useEvent(handler: HandlerType, dependencies: unknown[]) {\n  const context = useContext(EventContext);\n  if (!context) {\n    throw new Error('react-dom-event: subscribe not found on context. You might be missing the EventProvider or have multiple instances of react-dom-event');\n  }\n\n  useEffect(() => context.subscribe(handler), [context.subscribe, handler, ...dependencies]);\n}\n"],"names":["EventContext","createContext","undefined","EventProvider","events","children","state","useState","handlers","onEvent","event","forEach","handler","subscribe","push","splice","indexOf","useEffect","window","document","addEventListener","removeEventListener","createElement","Provider","value","useEvent","dependencies","context","useContext","Error"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,MAAMA,YAAAA,GAAeC,mBAAAA,CAA4CC,SAAAA;EAMjE,SAASC,cAAc,KAAoD,EAAA;EAApD,IAAA,IAAA,aAAA,GAAA,KAAA,CAAEC,QAAAA,MAAAA,GAAA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