react-selectable-box
Version:
A React component used hooks that allows you to select elements in the drag area using the mouse
346 lines (345 loc) • 16.1 kB
JavaScript
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 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 _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 useMergedState from "./hooks/useMergedState";
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 defaultValue = _ref.defaultValue,
propsValue = _ref.value,
items = _ref.items,
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,
getContainer = _ref.getContainer,
propsScrollContainer = _ref.scrollContainer,
propsDragContainer = _ref.dragContainer,
boxStyle = _ref.boxStyle,
boxClassName = _ref.boxClassName,
_ref$compareFn = _ref.compareFn,
compareFn = _ref$compareFn === void 0 ? defaultCompareFn : _ref$compareFn,
onStart = _ref.onStart,
onEnd = _ref.onEnd;
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 _useMergedState = useMergedState(defaultValue || [], {
value: propsValue
}),
_useMergedState2 = _slicedToArray(_useMergedState, 2),
value = _useMergedState2[0],
setValue = _useMergedState2[1];
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 scrollContainer = useContainer(propsScrollContainer || getContainer);
var dragContainer = useContainer(propsDragContainer || propsScrollContainer || getContainer);
var _useScroll = useScroll(scrollSpeed),
smoothScroll = _useScroll.smoothScroll,
cancelScroll = _useScroll.cancelScroll;
var startCoordsRef = useLatest(startCoords);
var isDraggingRef = useLatest(isDragging);
var selectStartRangeRef = useLatest(selectStartRange);
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 = !!items;
if (process.env.NODE_ENV === 'development' && getContainer) {
console.error('[react-selectable-box]: getContainer will be deprecated in the future, use scrollContainer instead');
}
React.useImperativeHandle(ref, function () {
return {
cancel: function cancel() {
setIsCanceled(true);
setIsDragging(false);
}
};
});
var handleStart = useEvent(function (event) {
onStart === null || onStart === void 0 ? void 0 : onStart(event);
});
var handleEnd = useEvent(function () {
if (onEnd) {
if (virtual) {
unmountItemsInfo.current.forEach(function (info, item) {
if (items.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
}, scrollContainer, 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 || !scrollContainer || !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 _scrollContainer$getB = scrollContainer.getBoundingClientRect(),
_left = _scrollContainer$getB.left,
_top = _scrollContainer$getB.top;
var x = Math.min(clientX - _left + scrollContainer.scrollLeft, scrollContainer.scrollWidth);
var y = Math.min(clientY - _top + scrollContainer.scrollTop, scrollContainer.scrollHeight);
setMoveCoords({
x: x,
y: y
});
smoothScroll(e, scrollContainer);
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)) {
setIsDragging(true);
scrollContainerOriginPosition = getComputedStyle(scrollContainer).position;
// default position in browser is `static`
if (scrollContainer !== document.body && scrollContainerOriginPosition === 'static') {
scrollContainer.style.position = 'relative';
}
handleStart(e);
}
}
}
};
var scrollListenerElement = scrollContainer === document.body ? document : scrollContainer;
var onScroll = function onScroll(e) {
var target = e.target;
scrollInfo.current = {
scrollTop: target.scrollTop,
scrollLeft: target.scrollLeft
};
if (isDraggingRef.current && scrollContainer) {
var containerRect = scrollContainer.getBoundingClientRect();
var x = Math.min(moveClient.current.x - containerRect.left + scrollContainer.scrollLeft, scrollContainer.scrollWidth);
var y = Math.min(moveClient.current.y - containerRect.top + scrollContainer.scrollTop, scrollContainer.scrollHeight);
setMoveCoords({
x: x,
y: y
});
}
};
var onMouseUp = function onMouseUp() {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('touchmove', onMouseMove);
window.removeEventListener('touchend', onMouseUp);
if (isDraggingRef.current) {
scrollContainer.style.position = scrollContainerOriginPosition;
cancelScroll();
setValue(selectingValue.current);
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) {
e.preventDefault();
}
isMouseDowning = true;
if (selectStartRangeRef.current !== 'all') {
setStartTarget(e.target);
}
var _getClientXY2 = getClientXY(e),
clientX = _getClientXY2.clientX,
clientY = _getClientXY2.clientY;
var _scrollContainer$getB2 = scrollContainer.getBoundingClientRect(),
left = _scrollContainer$getB2.left,
top = _scrollContainer$getB2.top;
setStartCoords({
x: clientX - left + scrollContainer.scrollLeft,
y: clientY - top + scrollContainer.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);
scrollListenerElement.addEventListener('scroll', onScroll);
return function () {
if (scrollContainerOriginPosition) {
scrollContainer.style.position = scrollContainerOriginPosition;
}
cancelScroll();
dragContainer.removeEventListener('mousedown', onMouseDown);
dragContainer.removeEventListener('touchstart', onMouseDown);
scrollListenerElement.removeEventListener('scroll', onScroll);
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('touchmove', onMouseMove);
window.removeEventListener('touchend', onMouseUp);
};
}, [disabled, scrollContainer, dragContainer, isCanceled]);
var contextValue = useMemo(function () {
return {
value: value,
selectingValue: selectingValue,
isDragging: isDragging,
boxPosition: boxPosition,
mode: mode,
scrollContainer: scrollContainer,
startTarget: startTarget,
startInside: startInside,
unmountItemsInfo: unmountItemsInfo,
virtual: virtual,
boxRef: boxRef,
compareFn: compareFn
};
}, [value, isDragging, boxPosition, mode, scrollContainer, startTarget, unmountItemsInfo, virtual, boxRef, compareFn]);
return /*#__PURE__*/_jsxs(SelectableContext.Provider, {
value: contextValue,
children: [children, isDragging && scrollContainer && /*#__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)
}), scrollContainer)]
});
}
export default /*#__PURE__*/React.forwardRef(Selectable);