UNPKG

reblend-ui

Version:

Utilities for creating robust overlay components

62 lines (60 loc) 2.26 kB
"use strict"; exports.__esModule = true; exports.default = void 0; var _listen = require("dom-helpers/listen"); var _ownerDocument = require("dom-helpers/ownerDocument"); var _reblendjs = require("reblendjs"); var _reblendHooks = require("reblend-hooks"); var _useClickOutside = require("./useClickOutside"); var _utils = require("./utils"); const noop = () => {}; /** * The `useRootClose` hook registers your callback on the document * when rendered. Powers the `<Overlay/>` component. This is used achieve modal * style behavior where your callback is triggered when the user tries to * interact with the rest of the document or hits the `esc` key. * * @param {Ref<HTMLElement>| HTMLElement} ref The element boundary * @param {function} onRootClose * @param {object=} options * @param {boolean=} options.disabled * @param {string=} options.clickTrigger The DOM event name (click, mousedown, etc) to attach listeners on */ function useRootClose(ref, onRootClose, { disabled, clickTrigger } = {}) { const onClose = onRootClose || noop; this.state.onClose = onClose; _useClickOutside.default.bind(this)(ref, this.state.onClose, { disabled, clickTrigger }); const handleKeyUp = _reblendHooks.useEventCallback.bind(this)(e => { if ((0, _utils.isEscKey)(e)) { this.state.onClose(e); } }); this.state.handleKeyUp = handleKeyUp; _reblendjs.useEffect.bind(this)(() => { if (disabled || ref == null) return undefined; const doc = (0, _ownerDocument.default)((0, _useClickOutside.getRefTarget)(ref)); // Store the current event to avoid triggering handlers immediately // https://github.com/facebook/react/issues/20074 let currentEvent = (doc.defaultView || window).event; const removeKeyupListener = (0, _listen.default)(doc, 'keyup', e => { // skip if this event is the same as the one running when we added the handlers if (e === currentEvent) { currentEvent = undefined; return; } this.state.handleKeyUp(e); }); return () => { removeKeyupListener(); }; }, (() => [ref, disabled, this.state.handleKeyUp]).bind(this)); return; } /* @Reblend: Transformed from function to class */ var _default = exports.default = useRootClose;