UNPKG

react-konva-grid

Version:

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

70 lines 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); /** * Auto sizer hook * @param param0 * @param deps * * TODO * Dynamically resize columns after user has scrolled down/view port changed ? */ const useAutoSizer = ({ gridRef, getValue, initialVisibleRows = 20, }) => { const autoSizer = react_1.useRef(AutoSizerCanvas()); const [viewport, setViewport] = react_1.useState({ rowStartIndex: 0, rowStopIndex: 0, columnStartIndex: 0, columnStopIndex: 0, }); /* Update any styles, fonts if necessary */ react_1.useEffect(() => { autoSizer.current.setFont(); }, []); const getValueRef = react_1.useRef(getValue); /* Keep it in sync */ getValueRef.current = getValue; const getColumnWidth = react_1.useCallback((columnIndex) => { const { rowStartIndex, rowStopIndex } = viewport; const visibleRows = rowStopIndex || initialVisibleRows; let start = rowStartIndex; let maxWidth = 0; while (start < visibleRows) { const value = getValueRef.current({ rowIndex: start, columnIndex, }); const metrics = autoSizer.current.measureText(value); if (metrics) { if (metrics.width > maxWidth) maxWidth = metrics.width + 10; } start++; } return Math.max(20, maxWidth); }, [viewport, initialVisibleRows]); const handleViewChange = react_1.useCallback((cells) => { setViewport(cells); }, []); return { columnWidth: getColumnWidth, onViewChange: handleViewChange, }; }; /* Canvas element */ const AutoSizerCanvas = () => { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); return { context, measureText: (text) => { return context === null || context === void 0 ? void 0 : context.measureText(text); }, setFont: (font = "12px Arial") => { if (context) context.font = font; }, }; }; exports.default = useAutoSizer; //# sourceMappingURL=useAutoSizer.js.map