UNPKG

@wordpress/compose

Version:
64 lines (63 loc) 1.97 kB
// packages/compose/src/higher-order/with-global-events/index.js import { Component, forwardRef } from "@wordpress/element"; import deprecated from "@wordpress/deprecated"; import { createHigherOrderComponent } from "../../utils/create-higher-order-component"; import Listener from "./listener"; import { jsx } from "react/jsx-runtime"; var listener = new Listener(); function withGlobalEvents(eventTypesToHandlers) { deprecated("wp.compose.withGlobalEvents", { since: "5.7", alternative: "useEffect" }); return createHigherOrderComponent((WrappedComponent) => { class Wrapper extends Component { constructor(props) { super(props); this.handleEvent = this.handleEvent.bind(this); this.handleRef = this.handleRef.bind(this); } componentDidMount() { Object.keys(eventTypesToHandlers).forEach((eventType) => { listener.add(eventType, this); }); } componentWillUnmount() { Object.keys(eventTypesToHandlers).forEach((eventType) => { listener.remove(eventType, this); }); } handleEvent(event) { const handler = eventTypesToHandlers[ /** @type {keyof GlobalEventHandlersEventMap} */ event.type ]; if (typeof this.wrappedRef[handler] === "function") { this.wrappedRef[handler](event); } } handleRef(el) { this.wrappedRef = el; if (this.props.forwardedRef) { this.props.forwardedRef(el); } } render() { return /* @__PURE__ */ jsx( WrappedComponent, { ...this.props.ownProps, ref: this.handleRef } ); } } return forwardRef((props, ref) => { return /* @__PURE__ */ jsx(Wrapper, { ownProps: props, forwardedRef: ref }); }); }, "withGlobalEvents"); } export { withGlobalEvents as default }; //# sourceMappingURL=index.js.map