Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F102280241
useRootClose.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Wed, Feb 19, 01:40
Size
1 KB
Mime Type
text/x-java
Expires
Fri, Feb 21, 01:40 (4 h, 40 m)
Engine
blob
Format
Raw Data
Handle
24322873
Attached To
rOACCT Open Access Compliance Check Tool (OACCT)
useRootClose.js
View Options
import listen from 'dom-helpers/listen';
import ownerDocument from 'dom-helpers/ownerDocument';
import { useEffect } from 'react';
import useEventCallback from '@restart/hooks/useEventCallback';
import useClickOutside, { getRefTarget } from './useClickOutside';
const escapeKeyCode = 27;
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;
useClickOutside(ref, onClose, {
disabled,
clickTrigger
});
const handleKeyUp = useEventCallback(e => {
if (e.keyCode === escapeKeyCode) {
onClose(e);
}
});
useEffect(() => {
if (disabled || ref == null) return undefined;
const doc = ownerDocument(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 = listen(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;
}
handleKeyUp(e);
});
return () => {
removeKeyupListener();
};
}, [ref, disabled, handleKeyUp]);
}
export default useRootClose;
Event Timeline
Log In to Comment