"use client" import * as React from "react" import { ROW_DRAG_COLUMN_KEY, type RowMove } from "./row-reorder-handle" import type { ColumnDef } from "./types" import { resolvedColumnLabel } from "./table-helpers" import type { RowDragState } from "./data-table-rows" /** * Row and column reordering: drag, Alt+Arrow keys and the Move menus. Owns the live * announcement. Rows move among the rows shown; columns move among free * (unpinned, unlocked) visible columns. */ export function useDataTableReorder>({ colOrder, colPins, columns, data, displayCols, getRowId, getRowIdProp, groupBy, lockedPins, onRowsReorder, setColOrder, sortKey, tableRootRef, }: { colOrder: string[] colPins: Record columns: ColumnDef[] data: TData[] displayCols: ColumnDef[] getRowId: >(row: TData, index: number, getIdFn?: ((r: TData, i: number) => string | number) | undefined) => string | number getRowIdProp: ((row: TData, index: number) => string | number) | undefined groupBy: string | null lockedPins: Record onRowsReorder: ((next: TData[], change: { rowId: string | number; from: number; to: number; }) => void) | undefined setColOrder: React.Dispatch> sortKey: string tableRootRef: React.RefObject }) { // ── Row reorder (opt-in via `onRowsReorder`) ────────────────────────────── const rowReorderDisabledReason = !onRowsReorder ? undefined : sortKey ? "Clear sorting to reorder rows" : groupBy ? "Remove grouping to reorder rows" : undefined if (process.env.NODE_ENV !== "production" && onRowsReorder && !columns.some(c => c.key === ROW_DRAG_COLUMN_KEY)) { console.warn('DataTable: onRowsReorder needs a drag column. Add `withRowDragColumn(columns)` (or `ROW_DRAG_COLUMN`) to `columns`.') } const rowDataIndex = React.useMemo( () => new Map(data.map((r, i) => [r, i] as const)), [data], ) const [rowDrag, setRowDrag] = React.useState(null) // The ref gates drag handlers (so they never depend on a re-render landing // mid-drag); the state only paints the drop line. const rowDragRef = React.useRef(null) function setRowDragBoth(next: typeof rowDrag) { rowDragRef.current = next setRowDrag(next) } const refocusRowHandle = React.useRef(null) function commitRowMove(scope: TData[], from: number, to: number) { if (!onRowsReorder || from === to || from < 0 || to < 0 || to >= scope.length) return const slots: number[] = [] for (const r of scope) { const i = rowDataIndex.get(r) if (i === undefined) return slots.push(i) } slots.sort((a, b) => a - b) const reordered = [...scope] const [moved] = reordered.splice(from, 1) reordered.splice(to, 0, moved) const next = [...data] reordered.forEach((r, i) => { next[slots[i]] = r }) const rowId = getRowId(moved, from, getRowIdProp) refocusRowHandle.current = String(rowId) onRowsReorder(next, { rowId, from, to }) setReorderAnnouncement(`Row moved to position ${to + 1} of ${scope.length}`) } function moveRowBy(scope: TData[], from: number, move: RowMove) { const to = move === "up" ? from - 1 : move === "down" ? from + 1 : move === "top" ? 0 : scope.length - 1 commitRowMove(scope, from, to) } React.useEffect(() => { const id = refocusRowHandle.current if (id === null) return refocusRowHandle.current = null const el = tableRootRef.current?.querySelector(`[data-dt-row-handle="${CSS.escape(id)}"]`) el?.focus() }) /** * Keyboard / single-pointer alternative to drag-reorder (WCAG 2.1.1, 2.5.7). * Moves a free (unpinned, unlocked) column one visible slot left or right * (`delta` is in visual terms; RTL flips it), skipping hidden columns, and * announces the result. */ const [reorderAnnouncement, setReorderAnnouncement] = React.useState("") function reorderTargetFor(key: string, delta: -1 | 1): string | null { const free = displayCols.filter(c => !colPins[c.key] && !lockedPins[c.key]).map(c => c.key) const i = free.indexOf(key) if (i < 0) return null return free[i + delta] ?? null } function moveColumnBy(col: ColumnDef, delta: -1 | 1, rtl = false) { const step: -1 | 1 = rtl ? (delta === -1 ? 1 : -1) : delta const target = reorderTargetFor(col.key, step) const label = resolvedColumnLabel(col) if (!target) { setReorderAnnouncement(`${label} is already the ${delta === -1 ? "first" : "last"} movable column`) return } const order = [...colOrder] const from = order.indexOf(col.key) order.splice(from, 1) order.splice(order.indexOf(target) + (step === 1 ? 1 : 0), 0, col.key) setColOrder(order) const free = order.filter(k => displayCols.some(c => c.key === k && !colPins[k] && !lockedPins[k])) setReorderAnnouncement(`${label} moved to position ${free.indexOf(col.key) + 1} of ${free.length}`) } function onHeaderKeyDown(col: ColumnDef, e: React.KeyboardEvent) { if (!e.altKey || (e.key !== "ArrowLeft" && e.key !== "ArrowRight")) return if (colPins[col.key] || lockedPins[col.key]) return e.preventDefault() const rtl = getComputedStyle(e.currentTarget).direction === "rtl" const delta = e.key === "ArrowLeft" ? -1 : 1 moveColumnBy(col, delta, rtl) // The moved re-mounts in a new slot only if keyed poorly; keys are stable, // so focus stays on the control the user was on. } return { commitRowMove, moveColumnBy, moveRowBy, onHeaderKeyDown, reorderAnnouncement, reorderTargetFor, rowDrag, rowDragRef, rowReorderDisabledReason, setRowDrag, setRowDragBoth, } }