@elastic/eui
Version:
Elastic UI Component Library
48 lines (46 loc) • 1.77 kB
JavaScript
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { useRef, useEffect } from 'react';
/**
* A hook that tracks whether the pointer is currently down/pressed.
* Useful for detecting text selection in progress.
*/
export function useIsPointerDown(container) {
var isPointerDownRef = useRef(false);
useEffect(function () {
var handlePointerDown = function handlePointerDown(event) {
if (container !== null && container !== void 0 && container.current && !container.current.contains(event.target)) {
return;
}
isPointerDownRef.current = true;
};
var handlePointerUpOrCancel = function handlePointerUpOrCancel() {
isPointerDownRef.current = false;
};
var handleVisibilityChange = function handleVisibilityChange() {
if (document.visibilityState === 'hidden') {
isPointerDownRef.current = false;
}
};
var controller = new AbortController();
var options = {
capture: true,
signal: controller.signal
};
document.addEventListener('pointerdown', handlePointerDown, options);
document.addEventListener('pointerup', handlePointerUpOrCancel, options);
document.addEventListener('pointercancel', handlePointerUpOrCancel, options);
document.addEventListener('visibilitychange', handleVisibilityChange, {
signal: controller.signal
});
return function () {
controller.abort();
};
}, [container]);
return isPointerDownRef;
}