UNPKG

@mantine/core

Version:

React components library focused on usability, accessibility and developer experience

1 lines 2.17 kB
{"version":3,"file":"create-use-external-events.cjs","names":[],"sources":["../../../../src/core/utils/create-use-external-events/create-use-external-events.ts"],"sourcesContent":["import { useIsomorphicEffect } from '@mantine/hooks';\n\nfunction dispatchEvent<T>(type: string, detail?: T) {\n window.dispatchEvent(new CustomEvent(type, { detail }));\n}\n\nexport function createUseExternalEvents<Handlers extends Record<string, (detail: any) => void>>(\n prefix: string\n) {\n function _useExternalEvents(events: Handlers) {\n const handlers = Object.keys(events).reduce<any>((acc, eventKey) => {\n acc[`${prefix}:${eventKey}`] = (event: CustomEvent) => events[eventKey](event.detail);\n return acc;\n }, {});\n\n useIsomorphicEffect(() => {\n Object.keys(handlers).forEach((eventKey) => {\n window.removeEventListener(eventKey, handlers[eventKey]);\n window.addEventListener(eventKey, handlers[eventKey]);\n });\n\n return () =>\n Object.keys(handlers).forEach((eventKey) => {\n window.removeEventListener(eventKey, handlers[eventKey]);\n });\n }, [handlers]);\n }\n\n function createEvent<EventKey extends keyof Handlers>(event: EventKey) {\n type Parameter = Parameters<Handlers[EventKey]>[0];\n\n return (...payload: Parameter extends undefined ? [undefined?] : [Parameter]) =>\n dispatchEvent(`${prefix}:${String(event)}`, payload[0]);\n }\n\n return [_useExternalEvents, createEvent] as const;\n}\n"],"mappings":";;;;AAEA,SAAS,cAAiB,MAAc,QAAY;CAClD,OAAO,cAAc,IAAI,YAAY,MAAM,EAAE,OAAO,CAAC,CAAC;AACxD;AAEA,SAAgB,wBACd,QACA;CACA,SAAS,mBAAmB,QAAkB;EAC5C,MAAM,WAAW,OAAO,KAAK,MAAM,EAAE,QAAa,KAAK,aAAa;GAClE,IAAI,GAAG,OAAO,GAAG,eAAe,UAAuB,OAAO,UAAU,MAAM,MAAM;GACpF,OAAO;EACT,GAAG,CAAC,CAAC;EAEL,CAAA,GAAA,eAAA,2BAA0B;GACxB,OAAO,KAAK,QAAQ,EAAE,SAAS,aAAa;IAC1C,OAAO,oBAAoB,UAAU,SAAS,SAAS;IACvD,OAAO,iBAAiB,UAAU,SAAS,SAAS;GACtD,CAAC;GAED,aACE,OAAO,KAAK,QAAQ,EAAE,SAAS,aAAa;IAC1C,OAAO,oBAAoB,UAAU,SAAS,SAAS;GACzD,CAAC;EACL,GAAG,CAAC,QAAQ,CAAC;CACf;CAEA,SAAS,YAA6C,OAAiB;EAGrE,QAAQ,GAAG,YACT,cAAc,GAAG,OAAO,GAAG,OAAO,KAAK,KAAK,QAAQ,EAAE;CAC1D;CAEA,OAAO,CAAC,oBAAoB,WAAW;AACzC"}