@react-hook/click
Version:
```jsx harmony import useClick from '@react-hook/click'
90 lines (73 loc) • 3.15 kB
JavaScript
;
exports.__esModule = true;
exports.default = exports.CLICK_TYPES = void 0;
var React = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("react"));
var _latest = /*#__PURE__*/_interopRequireDefault( /*#__PURE__*/require("@react-hook/latest"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function useClick(conditions, callback) {
const storedConditions = (0, _latest.default)(conditions);
const storedCallback = (0, _latest.default)(callback);
return React.useCallback(e => {
if (isClickOfType(e, Array.isArray(storedConditions.current) ? storedConditions.current : [storedConditions.current]) === true) {
const {
left,
top
} = e.target.getBoundingClientRect();
storedCallback.current(e, {
x: e.clientX - Math.floor(left),
y: e.clientY - Math.floor(top),
count: e.detail
});
}
}, [storedCallback, storedConditions]);
}
function _ref(o) {
return o.trim();
}
function isClickOfType(e, types) {
let i = 0;
let j;
for (; i < types.length; i++) {
const type = types[i];
if (type.indexOf('|') > -1) {
const ors = type.split('|').map(_ref);
let orSatisfied = true;
for (j = 0; j < ors.length; j++) {
orSatisfied = isClickOfType(e, [ors[j]]);
if (orSatisfied) break;
}
if (!orSatisfied) return false;
} else {
const props = type.split('+');
for (j = 0; j < props.length; j++) {
const prop = props[j] in CLICK_TYPES ? CLICK_TYPES[props[j]] : props[j];
const [propName, propValue] = prop.split('=');
if (propValue !== void 0) {
if (String(e[propName]) !== String(propValue)) {
return false;
}
} else if (e[propName] === false) {
return false;
}
}
}
}
return true;
}
const CLICK_TYPES = {
single: 'detail=1',
double: 'detail=2',
triple: 'detail=3',
left: 'button=0',
middle: 'button=1',
right: 'button=2',
shift: 'shiftKey',
control: 'ctrlKey',
meta: 'metaKey',
alt: 'altKey'
};
exports.CLICK_TYPES = CLICK_TYPES;
var _default = useClick;
exports.default = _default;