UNPKG

@ackplus/react-tanstack-data-table

Version:

A powerful React data table component built with MUI and TanStack Table

280 lines (279 loc) 12 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.DraggableHeaderMemo = void 0; exports.DraggableHeader = DraggableHeader; const jsx_runtime_1 = require("react/jsx-runtime"); const icons_material_1 = require("@mui/icons-material"); const material_1 = require("@mui/material"); const react_table_1 = require("@tanstack/react-table"); const react_1 = __importStar(require("react")); const slot_helpers_1 = require("../../utils/slot-helpers"); function DraggableHeader(props) { const { header, enableSorting = true, draggable = false, onColumnReorder, containerSx, sortIconProps, alignment, slots, slotProps, ...otherProps } = props; const [isDragging, setIsDragging] = (0, react_1.useState)(false); const [dragOver, setDragOver] = (0, react_1.useState)(false); const autoScrollIntervalRef = (0, react_1.useRef)(null); const dragStartPositionRef = (0, react_1.useRef)(null); const headerElementRef = (0, react_1.useRef)(null); // Extract slot-specific props with enhanced merging const sortIconAscSlotProps = (0, slot_helpers_1.extractSlotProps)(slotProps, 'sortIconAsc'); const sortIconDescSlotProps = (0, slot_helpers_1.extractSlotProps)(slotProps, 'sortIconDesc'); const SortIconAscSlot = (0, slot_helpers_1.getSlotComponent)(slots, 'sortIconAsc', icons_material_1.ArrowUpwardOutlined); const SortIconDescSlot = (0, slot_helpers_1.getSlotComponent)(slots, 'sortIconDesc', icons_material_1.ArrowDownwardOutlined); // Auto-scroll configuration const AUTO_SCROLL_THRESHOLD = 50; // Distance from edge to trigger scroll const AUTO_SCROLL_SPEED = 10; // Pixels per scroll interval const AUTO_SCROLL_INTERVAL = 16; // ~60fps const justifyContent = (0, react_1.useMemo)(() => { return alignment === 'left' ? 'flex-start' : alignment === 'right' ? 'flex-end' : 'center'; }, [alignment]); const findScrollableContainer = (0, react_1.useCallback)((element) => { // Start from the provided element or try to find the current table let searchElement = element; if (!searchElement) { // Start from the header element if available if (headerElementRef.current) { searchElement = headerElementRef.current.closest('table'); } } if (!searchElement) { // Find the table that contains our header const tables = Array.from(document.querySelectorAll('table')); for (const table of tables) { // Check if this table contains a header with our ID const headerExists = table.querySelector('th'); // fallback if (headerExists) { searchElement = table; break; } } } if (!searchElement) { // Last resort: use the first table found searchElement = document.querySelector('table'); } if (!searchElement) return null; // Walk up the DOM tree to find the scrollable container let container = searchElement; while (container && container !== document.body) { const styles = window.getComputedStyle(container); if (styles.overflowX === 'auto' || styles.overflowX === 'scroll') { return container; } container = container.parentElement; } return null; }, []); const startAutoScroll = (0, react_1.useCallback)((direction) => { if (autoScrollIntervalRef.current) { clearInterval(autoScrollIntervalRef.current); } const container = findScrollableContainer(); if (!container) return; autoScrollIntervalRef.current = setInterval(() => { const scrollAmount = direction === 'left' ? -AUTO_SCROLL_SPEED : AUTO_SCROLL_SPEED; const newScrollLeft = container.scrollLeft + scrollAmount; // Check bounds if (direction === 'left' && newScrollLeft <= 0) { container.scrollLeft = 0; clearInterval(autoScrollIntervalRef.current); autoScrollIntervalRef.current = null; } else if (direction === 'right' && newScrollLeft >= container.scrollWidth - container.clientWidth) { container.scrollLeft = container.scrollWidth - container.clientWidth; clearInterval(autoScrollIntervalRef.current); autoScrollIntervalRef.current = null; } else { container.scrollLeft = newScrollLeft; } }, AUTO_SCROLL_INTERVAL); }, [findScrollableContainer]); const stopAutoScroll = (0, react_1.useCallback)(() => { if (autoScrollIntervalRef.current) { clearInterval(autoScrollIntervalRef.current); autoScrollIntervalRef.current = null; } }, []); const checkAutoScroll = (0, react_1.useCallback)((clientX) => { const container = findScrollableContainer(); if (!container) return; const containerRect = container.getBoundingClientRect(); const leftEdge = containerRect.left + AUTO_SCROLL_THRESHOLD; const rightEdge = containerRect.right - AUTO_SCROLL_THRESHOLD; if (clientX < leftEdge) { startAutoScroll('left'); } else if (clientX > rightEdge) { startAutoScroll('right'); } else { stopAutoScroll(); } }, [findScrollableContainer, startAutoScroll, stopAutoScroll]); const handleDragStart = (e) => { if (!draggable) return; e.dataTransfer.setData('text/plain', header.id); e.dataTransfer.effectAllowed = 'move'; setIsDragging(true); dragStartPositionRef.current = { x: e.clientX, y: e.clientY }; }; const handleDrag = (e) => { if (!draggable || !dragStartPositionRef.current) return; checkAutoScroll(e.clientX); }; const getSortIcon = () => { if (!enableSorting) return null; const sortDirection = header.column.getIsSorted(); const mergedSortIconProps = (0, slot_helpers_1.mergeSlotProps)({ fontSize: 'small', }, sortIconProps || {}); // Only show icons when column is actually sorted if (sortDirection === 'asc') { return ((0, jsx_runtime_1.jsx)(SortIconAscSlot, { ...(0, slot_helpers_1.mergeSlotProps)(mergedSortIconProps, sortIconAscSlotProps) })); } if (sortDirection === 'desc') { return ((0, jsx_runtime_1.jsx)(SortIconDescSlot, { ...(0, slot_helpers_1.mergeSlotProps)(mergedSortIconProps, sortIconDescSlotProps) })); } // Don't show any icon when not sorted return null; }; const handleDragEnd = () => { setIsDragging(false); setDragOver(false); stopAutoScroll(); dragStartPositionRef.current = null; }; const handleDragOver = (e) => { if (!draggable) return; e.preventDefault(); e.dataTransfer.dropEffect = 'move'; setDragOver(true); // Check for auto-scroll during drag over checkAutoScroll(e.clientX); }; const handleDragLeave = () => { setDragOver(false); // Don't stop auto-scroll on drag leave as the drag might continue outside this element }; const handleDrop = (e) => { if (!draggable) return; e.preventDefault(); const draggedColumnId = e.dataTransfer.getData('text/plain'); if (draggedColumnId !== header.id && onColumnReorder) { onColumnReorder(draggedColumnId, header.id); } setDragOver(false); stopAutoScroll(); }; const handleSort = () => { if (!enableSorting || !header.column.getCanSort()) return; const currentSort = header.column.getIsSorted(); if (currentSort === false) { header.column.toggleSorting(false); // asc } else if (currentSort === 'asc') { header.column.toggleSorting(true); // desc } else { header.column.clearSorting(); // none } }; const getCursor = () => { if (draggable) return 'grab'; if (enableSorting && header.column.getCanSort()) return 'pointer'; return 'default'; }; // Merge all props for maximum flexibility const mergedContainerProps = (0, slot_helpers_1.mergeSlotProps)({ ref: headerElementRef, sx: { display: 'flex', alignItems: 'center', justifyContent: justifyContent, gap: 1, cursor: getCursor(), userSelect: 'none', opacity: isDragging ? 0.5 : 1, backgroundColor: dragOver ? 'rgba(25, 118, 210, 0.08)' : 'transparent', borderLeft: dragOver ? '2px solid #1976d2' : 'none', padding: dragOver ? '0 0 0 -2px' : '0', width: '100%', height: '100%', minWidth: '0', '&:active': { cursor: draggable ? 'grabbing' : 'pointer', }, '.header-content': { display: 'block', flex: 1, minWidth: 0, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', }, ...containerSx, }, draggable: draggable, onDragStart: handleDragStart, onDrag: handleDrag, onDragEnd: handleDragEnd, onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, onClick: enableSorting ? handleSort : undefined, }, otherProps); if (!draggable && !enableSorting) { return (0, react_table_1.flexRender)(header.column.columnDef.header, header.getContext()); } return ((0, jsx_runtime_1.jsx)(material_1.Box, { ...mergedContainerProps, children: (0, jsx_runtime_1.jsxs)(material_1.Box, { component: "span", className: 'header-wrapper', sx: { display: 'inline-flex', gap: 1, }, children: [(0, jsx_runtime_1.jsx)(material_1.Box, { component: "span", className: 'header-content', children: (0, react_table_1.flexRender)(header.column.columnDef.header, header.getContext()) }), getSortIcon()] }) })); } // Memoize component to prevent unnecessary re-renders exports.DraggableHeaderMemo = react_1.default.memo(DraggableHeader);