@platform/react
Version:
React refs and helpers.
38 lines (37 loc) • 1.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useClickWithin = exports.useClickOutside = void 0;
var react_1 = require("react");
function useClickOutside(stage, ref, callback) {
(0, react_1.useEffect)(function () {
var handler = function (e) {
var _a;
if (callback && !((_a = ref.current) === null || _a === void 0 ? void 0 : _a.contains(e.target)))
callback(e);
};
var event = asEventName(stage);
document === null || document === void 0 ? void 0 : document.addEventListener(event, handler, true);
return function () { return document === null || document === void 0 ? void 0 : document.removeEventListener(event, handler, true); };
}, [stage, ref, callback]);
}
exports.useClickOutside = useClickOutside;
function useClickWithin(stage, ref, callback) {
(0, react_1.useEffect)(function () {
var handler = function (e) {
var _a;
if (callback && ((_a = ref.current) === null || _a === void 0 ? void 0 : _a.contains(e.target)))
callback(e);
};
var event = asEventName(stage);
document === null || document === void 0 ? void 0 : document.addEventListener(event, handler, true);
return function () { return document === null || document === void 0 ? void 0 : document.removeEventListener(event, handler, true); };
}, [stage, ref, callback]);
}
exports.useClickWithin = useClickWithin;
function asEventName(stage) {
if (stage === 'down')
return 'mousedown';
if (stage == 'up')
return 'mouseup';
throw new Error("'".concat(stage, "' not supported"));
}