react-selectable-box
Version:
A React component used hooks that allows you to select elements in the drag area using the mouse
353 lines (352 loc) • 17.4 kB
JavaScript
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { SelectableContext } from "./context";
import useContainer from "./hooks/useContainer";
import useEvent from "./hooks/useEvent";
import useLatest from "./hooks/useLatest";
import useScroll from "./hooks/useScroll";
import { checkInRange, getClientXY } from "./utils";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function defaultCompareFn(a, b) {
return a === b;
}
function Selectable(_ref, ref) {
var _propsScrollContainer, _propsScrollContainer2;
var value = _ref.value,
virtualItems = _ref.virtualItems,
disabled = _ref.disabled,
_ref$mode = _ref.mode,
mode = _ref$mode === void 0 ? 'add' : _ref$mode,
children = _ref.children,
_ref$selectStartRange = _ref.selectStartRange,
selectStartRange = _ref$selectStartRange === void 0 ? 'all' : _ref$selectStartRange,
scrollSpeed = _ref.scrollSpeed,
propsScrollContainer = _ref.scrollContainer,
propsDragContainer = _ref.dragContainer,
boxStyle = _ref.boxStyle,
boxClassName = _ref.boxClassName,
_ref$compareFn = _ref.compareFn,
compareFn = _ref$compareFn === void 0 ? defaultCompareFn : _ref$compareFn,
allowTextSelection = _ref.allowTextSelection,
onStart = _ref.onStart,
onEnd = _ref.onEnd;
if (process.env.NODE_ENV === 'development' && selectStartRange !== 'all') {
console.warn('[Selectable] selectStartRange is deprecated, please use onStart to prevent selection start instead.');
}
var _useState = useState(false),
_useState2 = _slicedToArray(_useState, 2),
isDragging = _useState2[0],
setIsDragging = _useState2[1];
var _useState3 = useState({
x: 0,
y: 0
}),
_useState4 = _slicedToArray(_useState3, 2),
startCoords = _useState4[0],
setStartCoords = _useState4[1];
var _useState5 = useState({
x: 0,
y: 0
}),
_useState6 = _slicedToArray(_useState5, 2),
moveCoords = _useState6[0],
setMoveCoords = _useState6[1];
var selectingValue = useRef([]);
var _useState7 = useState(null),
_useState8 = _slicedToArray(_useState7, 2),
startTarget = _useState8[0],
setStartTarget = _useState8[1];
var startInside = useRef(false);
var moveClient = useRef({
x: 0,
y: 0
});
var boxRef = useRef(null);
var unmountItemsInfo = useRef(new Map());
var scrollInfo = useRef({
scrollTop: 0,
scrollLeft: 0
});
var _useState9 = useState(false),
_useState10 = _slicedToArray(_useState9, 2),
isCanceled = _useState10[0],
setIsCanceled = _useState10[1];
var getInnerScrollContainer = typeof propsScrollContainer === 'function' ? propsScrollContainer : propsScrollContainer === null || propsScrollContainer === void 0 ? void 0 : (_propsScrollContainer = propsScrollContainer.inner) === null || _propsScrollContainer === void 0 ? void 0 : _propsScrollContainer.getContainer;
var innerScrollContainer = useContainer(getInnerScrollContainer);
var outerScrollContainer = useContainer(_typeof(propsScrollContainer) === 'object' ? propsScrollContainer === null || propsScrollContainer === void 0 ? void 0 : (_propsScrollContainer2 = propsScrollContainer.outer) === null || _propsScrollContainer2 === void 0 ? void 0 : _propsScrollContainer2.getContainer : undefined, false);
var dragContainer = useContainer(propsDragContainer || getInnerScrollContainer);
var _useScroll = useScroll(scrollSpeed, propsScrollContainer),
smoothScroll = _useScroll.smoothScroll,
cancelScroll = _useScroll.cancelScroll;
var startCoordsRef = useLatest(startCoords);
var isDraggingRef = useLatest(isDragging);
var selectStartRangeRef = useLatest(selectStartRange);
var allowTextSelectionRef = useLatest(allowTextSelection);
var top = Math.max(0, Math.min(startCoords.y, moveCoords.y));
var left = Math.max(0, Math.min(startCoords.x, moveCoords.x));
var width = isDragging ? Math.abs(startCoords.x - Math.max(0, moveCoords.x)) : 0;
var height = isDragging ? Math.abs(startCoords.y - Math.max(0, moveCoords.y)) : 0;
var boxPosition = useMemo(function () {
return {
top: top,
left: left,
width: width,
height: height
};
}, [top, left, width, height]);
var virtual = !!virtualItems;
React.useImperativeHandle(ref, function () {
return {
cancel: function cancel() {
setIsCanceled(true);
setIsDragging(false);
}
};
});
var handleStart = useEvent(function (event) {
return onStart === null || onStart === void 0 ? void 0 : onStart(event);
});
var handleEnd = useEvent(function () {
if (onEnd) {
if (virtual) {
unmountItemsInfo.current.forEach(function (info, item) {
if (virtualItems.some(function (i) {
return compareFn(i, item);
})) {
var isInRange = checkInRange(info.rule, {
width: info.rect.width,
height: info.rect.height,
top: info.rect.top + info.scrollTop - scrollInfo.current.scrollTop,
left: info.rect.left + info.scrollLeft - scrollInfo.current.scrollLeft
}, innerScrollContainer, boxPosition, boxRef);
if (isInRange && !info.disabled) {
selectingValue.current.push(item);
} else {
selectingValue.current = selectingValue.current.filter(function (i) {
return !compareFn(i, item);
});
}
}
});
}
var added = [];
var removed = [];
selectingValue.current.forEach(function (i) {
if (value !== null && value !== void 0 && value.some(function (val) {
return compareFn(val, i);
})) {
if (mode === 'remove' || mode === 'reverse') {
removed.push(i);
}
} else {
if (mode === 'add' || mode === 'reverse') {
added.push(i);
}
}
});
onEnd(selectingValue.current, {
added: added,
removed: removed
});
}
});
useEffect(function () {
var isMouseDowning = false;
var scrollContainerOriginPosition = '';
var reset = function reset() {
setIsDragging(false);
setIsCanceled(false);
setStartTarget(null);
isMouseDowning = false;
startInside.current = false;
selectingValue.current = [];
};
if (disabled || !innerScrollContainer || !dragContainer || isCanceled) {
reset();
return;
}
var onMouseMove = function onMouseMove(e) {
if (isMouseDowning) {
// Prevent scroll on mobile
if (window.TouchEvent && e instanceof TouchEvent) {
e.preventDefault();
}
var _getClientXY = getClientXY(e),
clientX = _getClientXY.clientX,
clientY = _getClientXY.clientY;
moveClient.current = {
x: clientX,
y: clientY
};
var _innerScrollContainer = innerScrollContainer.getBoundingClientRect(),
_left = _innerScrollContainer.left,
_top = _innerScrollContainer.top;
var x = Math.min(clientX - _left + innerScrollContainer.scrollLeft, innerScrollContainer.scrollWidth);
var y = Math.min(clientY - _top + innerScrollContainer.scrollTop, innerScrollContainer.scrollHeight);
setMoveCoords({
x: x,
y: y
});
smoothScroll(e);
if (!isDraggingRef.current) {
var shouldDraggingStart = true;
if (selectStartRangeRef.current === 'outside') {
shouldDraggingStart = !startInside.current;
} else if (selectStartRangeRef.current === 'inside') {
shouldDraggingStart = startInside.current;
}
var boxWidth = Math.abs(startCoordsRef.current.x - x);
var boxHeight = Math.abs(startCoordsRef.current.y - y);
// prevent trigger when click too fast
// https://github.com/linxianxi/react-selectable-box/issues/5
if (shouldDraggingStart && (boxWidth > 1 || boxHeight > 1)) {
var shouldStart = handleStart(e);
if (shouldStart === false) {
reset();
} else {
setIsDragging(true);
scrollContainerOriginPosition = getComputedStyle(innerScrollContainer).position;
// default position in browser is `static`
if (innerScrollContainer !== document.body && scrollContainerOriginPosition === 'static') {
innerScrollContainer.style.position = 'relative';
}
}
}
}
}
};
var innerScrollListenerElement = innerScrollContainer === document.body ? document : innerScrollContainer;
var outerScrollListenerElement = outerScrollContainer === document.body ? document : outerScrollContainer;
var onScroll = function onScroll(e) {
var target = e.target;
scrollInfo.current = {
scrollTop: target.scrollTop,
scrollLeft: target.scrollLeft
};
if (isDraggingRef.current) {
var containerRect = innerScrollContainer.getBoundingClientRect();
var x = Math.min(moveClient.current.x - containerRect.left + innerScrollContainer.scrollLeft, innerScrollContainer.scrollWidth);
var y = Math.min(moveClient.current.y - containerRect.top + innerScrollContainer.scrollTop, innerScrollContainer.scrollHeight);
setMoveCoords({
x: x,
y: y
});
}
};
var onOuterScroll = function onOuterScroll() {
onScroll({
target: innerScrollContainer
});
};
var onMouseUp = function onMouseUp() {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('touchmove', onMouseMove);
window.removeEventListener('touchend', onMouseUp);
if (isDraggingRef.current) {
innerScrollContainer.style.position = scrollContainerOriginPosition;
cancelScroll();
handleEnd();
}
reset();
};
var onMouseDown = function onMouseDown(e) {
var isMouseEvent = e instanceof MouseEvent;
if (isMouseEvent && e.button !== 0) {
return;
}
// Disable text selection, but it will prevent default scroll behavior when mouse move, so we used `useScroll`
// And it will prevent click events on mobile devices, so don't trigger it
if (isMouseEvent && !allowTextSelectionRef.current) {
e.preventDefault();
}
isMouseDowning = true;
if (selectStartRangeRef.current !== 'all') {
setStartTarget(e.target);
}
var _getClientXY2 = getClientXY(e),
clientX = _getClientXY2.clientX,
clientY = _getClientXY2.clientY;
var _innerScrollContainer2 = innerScrollContainer.getBoundingClientRect(),
left = _innerScrollContainer2.left,
top = _innerScrollContainer2.top;
setStartCoords({
x: clientX - left + innerScrollContainer.scrollLeft,
y: clientY - top + innerScrollContainer.scrollTop
});
window.addEventListener('mousemove', onMouseMove, {
passive: false
});
window.addEventListener('mouseup', onMouseUp);
window.addEventListener('touchmove', onMouseMove, {
passive: false
});
window.addEventListener('touchend', onMouseUp);
};
dragContainer.addEventListener('mousedown', onMouseDown);
dragContainer.addEventListener('touchstart', onMouseDown);
innerScrollListenerElement.addEventListener('scroll', onScroll);
outerScrollListenerElement === null || outerScrollListenerElement === void 0 ? void 0 : outerScrollListenerElement.addEventListener('scroll', onOuterScroll);
return function () {
if (scrollContainerOriginPosition) {
innerScrollContainer.style.position = scrollContainerOriginPosition;
}
cancelScroll();
dragContainer.removeEventListener('mousedown', onMouseDown);
dragContainer.removeEventListener('touchstart', onMouseDown);
innerScrollListenerElement.removeEventListener('scroll', onScroll);
outerScrollListenerElement === null || outerScrollListenerElement === void 0 ? void 0 : outerScrollListenerElement.removeEventListener('scroll', onOuterScroll);
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('touchmove', onMouseMove);
window.removeEventListener('touchend', onMouseUp);
};
}, [disabled, innerScrollContainer, outerScrollContainer, dragContainer, isCanceled]);
var contextValue = useMemo(function () {
return {
value: value,
selectingValue: selectingValue,
isDragging: isDragging,
boxPosition: boxPosition,
mode: mode,
innerScrollContainer: innerScrollContainer,
startTarget: startTarget,
startInside: startInside,
unmountItemsInfo: unmountItemsInfo,
virtual: virtual,
boxRef: boxRef,
compareFn: compareFn
};
}, [value, isDragging, boxPosition, mode, innerScrollContainer, startTarget, unmountItemsInfo, virtual, boxRef, compareFn]);
return /*#__PURE__*/_jsxs(SelectableContext.Provider, {
value: contextValue,
children: [children, isDragging && innerScrollContainer && /*#__PURE__*/createPortal( /*#__PURE__*/_jsx("div", {
ref: boxRef,
className: boxClassName,
style: _objectSpread({
position: 'absolute',
zIndex: 9999,
top: 0,
left: 0,
transform: "translate(".concat(left, "px, ").concat(top, "px)"),
width: width,
height: height,
backgroundColor: 'rgba(22, 119, 255, 0.3)'
}, boxStyle)
}), innerScrollContainer)]
});
}
export default /*#__PURE__*/React.forwardRef(Selectable);