UNPKG

react-konva-grid

Version:

Canvas grid to render large set of tabular data with virtualization.

71 lines 2.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); /** * useSelection hook to enable selection in datagrid * @param initialSelection */ const useSelection = (options = {}) => { const { gridRef, initialSelections = [] } = options; const [selections, setSelections] = react_1.useState(initialSelections); const selectionStart = react_1.useRef(); const isSelectionMode = react_1.useRef(); const handleMouseDown = react_1.useCallback((e) => { /* Exit early if grid is not initialized */ if (!gridRef || !gridRef.current) return; /* Activate selection mode */ isSelectionMode.current = true; const { rowIndex, columnIndex } = gridRef.current.getCellCoordsFromOffsets(e.clientX, e.clientY); /* To cater to merged Cells, get the bounds from internal fn */ const bounds = gridRef.current.getCellBounds({ rowIndex, columnIndex }); /** * Save the initial Selection in ref * so we can adjust the bounds in mousemove */ selectionStart.current = bounds; /* Add selection to state */ setSelections([bounds]); }, []); /** * Mousemove handler */ const handleMouseMove = react_1.useCallback((e) => { /* Exit if user is not in selection mode */ if (!isSelectionMode.current || !gridRef) return; /* Get the current selection */ const _selectionStart = selectionStart.current; /* Exit early */ if (!_selectionStart) return; const { rowIndex, columnIndex, } = gridRef.current.getCellCoordsFromOffsets(e.clientX, e.clientY); /* Get new bounds */ const bounds = gridRef.current.getCellBounds({ rowIndex, columnIndex }); setSelections((prevSelection) => { return prevSelection.map((selection) => { return { top: Math.min(bounds.top, _selectionStart.top), bottom: Math.max(bounds.bottom, _selectionStart.bottom), left: Math.min(bounds.left, _selectionStart.left), right: Math.max(bounds.right, _selectionStart.right), }; }); }); }, [isSelectionMode]); /** * Mouse up handler */ const handleMouseUp = react_1.useCallback(() => { /* Reset selection mode */ isSelectionMode.current = false; }, []); return { selections, onMouseDown: handleMouseDown, onMouseMove: handleMouseMove, onMouseUp: handleMouseUp, }; }; exports.default = useSelection; //# sourceMappingURL=useSelection.js.map