diff --git a/changelog.md b/changelog.md index 4c8d9b1c..ddc5cfe3 100644 --- a/changelog.md +++ b/changelog.md @@ -13,7 +13,8 @@ - **Breaking** Full-width _Navbar_ (`containerWidth={false}`) now uses a 12px side gutter instead of 24px (16px on small screens), so a default-size menu `IconButton` at its left edge lines up with _SidebarNav_'s item icons. Centred Navbars keep the 24px gutter. - **Breaking** _User_ no longer renders a `flexGrow` spacer before itself, which added an extra gap next to sibling controls in a `Navbar` slot. If you placed `User` directly in a flex container and relied on it pushing itself to the right, add your own spacer. -- `DiamondDSIntegrations.mrtOptions({ onRowReorder })` adds row reordering: drag with a drop line between rows, plus Move up/down in the row menu. +- `DiamondDSIntegrations.mrtOptions({ onRowReorder })` adds row reordering: drag with a drop line between rows, plus Move to top/up/down/bottom in the row menu, announced to screen readers. `isRowMovable` locks rows. +- `useRowReorder` adds a toggleable reorder mode to MRT tables. ### Fixed diff --git a/dev/src/App.tsx b/dev/src/App.tsx index 5c250c07..6ee9d318 100644 --- a/dev/src/App.tsx +++ b/dev/src/App.tsx @@ -2,7 +2,6 @@ import * as React from "react"; import { AppBar, Box, - Button, Checkbox, Chip, Container, @@ -50,6 +49,7 @@ import { ThemeProvider, DiamondDSTheme, DiamondDSIntegrations, + useRowReorder, } from "../../src/index"; import type { Theme } from "@mui/material/styles"; import type { TypographyProps } from "@mui/material/Typography"; @@ -205,14 +205,16 @@ export const MidLevelMrtExample = () => { export const AdvancedMrtExample = () => { const [rows, setRows] = React.useState(data); - const [reorderMode, setReorderMode] = React.useState(false); - const moveRow = (fromIndex: number, toIndex: number) => - setRows((prev) => { - const next = [...prev]; - next.splice(toIndex, 0, next.splice(fromIndex, 1)[0]); - return next; - }); + const reorder = useRowReorder({ + onReorder: (fromIndex, toIndex) => + setRows((prev) => { + const next = [...prev]; + next.splice(toIndex, 0, next.splice(fromIndex, 1)[0]); + return next; + }), + isRowMovable: (experiment) => experiment.status !== "Completed", + }); const table = useMaterialReactTable({ columns: mrtColumns, @@ -221,38 +223,13 @@ export const AdvancedMrtExample = () => { enableDensityToggle: false, enableFullScreenToggle: false, enableHiding: true, - // Reorder mode swaps checkboxes for drag handles; sorting is off so it can't fight the manual order - enableRowSelection: !reorderMode, - enableRowOrdering: reorderMode, - enableSorting: !reorderMode, + enableRowSelection: true, getRowId: (row) => row.id, initialState: { rowSelection: { "EXP-1003": true } }, - // MRT only builds column order on mount, so pin the active display column to the left - state: { - columnOrder: [ - reorderMode ? "mrt-row-drag" : "mrt-row-select", - ...mrtColumns.map((column) => column.accessorKey as string), - ], - }, - renderTopToolbarCustomActions: ({ table }) => ( - - ), + renderTopToolbarCustomActions: reorder.renderToggleButton, mrtTheme: DiamondDSIntegrations.mrtTheme, - ...DiamondDSIntegrations.mrtOptions({ - onRowReorder: reorderMode ? moveRow : undefined, - }), + ...DiamondDSIntegrations.mrtOptions({ fullWidth: true }), + ...reorder.tableOptions, }); return ; @@ -532,8 +509,8 @@ const ComponentsPage = () => { Top toolbar, row selection, sorting and pagination. The{" "} - Reorder toggle swaps the checkboxes for drag handles and - turns sorting off while active. + Reorder rows toggle shows drag handles and a row menu, + and turns sorting off while active. Completed experiments are locked. diff --git a/src/components/MUI/DataDisplay/Table-2.MaterialReactTableGuidance.mdx b/src/components/MUI/DataDisplay/Table-2.MaterialReactTableGuidance.mdx index 5e477cfd..798f3976 100644 --- a/src/components/MUI/DataDisplay/Table-2.MaterialReactTableGuidance.mdx +++ b/src/components/MUI/DataDisplay/Table-2.MaterialReactTableGuidance.mdx @@ -333,42 +333,59 @@ enableHiding: true`}

Pass onRowReorder to{" "} - DiamondDSIntegrations.mrtOptions() while reorder mode is - active. It adds drag handles, a drop line between rows, and{" "} - Move up / Move down in the row menu. Sorting - is turned off while it is set. + DiamondDSIntegrations.mrtOptions(). It adds drag handles, a + drop line between rows, and a row menu with Move to top,{" "} + Move up, Move down and{" "} + Move to bottom. Moves are announced to screen readers. Sorting + and ranked search results are turned off while it is set.

onRowReorder receives positions in the source data, so it - stays correct across pages and filters. + stays correct across pages and filters. Set getRowId: it + keeps rows, and keyboard focus after a menu move, with the right record when + the data changes. With a typed lambda, give the type:{" "} + mrtOptions<Task>(...). Pass{" "} + isRowMovable to lock rows: they get no handle or menu and + can't be dropped on, though they shift when rows move across them.

-
-  {`const [reorderMode, setReorderMode] = useState(false);
+

+ For a reorder mode that users switch on and off, use{" "} + useRowReorder. The drag and menu columns show only while it + is on. +

-const moveRow = (fromIndex: number, toIndex: number) => - setRows((prev) => { - const next = [...prev]; - next.splice(toIndex, 0, next.splice(fromIndex, 1)[0]); - return next; - }); +
+  {`const [rows, setRows] = useState(data);
+
+const reorder = useRowReorder({
+  onReorder: (fromIndex, toIndex) =>
+    setRows((prev) => {
+      const next = [...prev];
+      next.splice(toIndex, 0, next.splice(fromIndex, 1)[0]);
+      return next;
+    }),
+  isRowMovable: (task) => task.status === "Queued",
+});
 
 const table = useMaterialReactTable({
   columns,
   data: rows,
-  enableRowSelection: !reorderMode,
+  getRowId: (row) => row.id,
+  renderTopToolbarCustomActions: reorder.renderToggleButton,
   mrtTheme: DiamondDSIntegrations.mrtTheme,
-  ...DiamondDSIntegrations.mrtOptions({
-    onRowReorder: reorderMode ? moveRow : undefined,
-  }),
+  ...DiamondDSIntegrations.mrtOptions(),
+  ...reorder.tableOptions,
 });`}
 

- onRowReorder also sets the row action menu and{" "} - muiTableBodyCellProps. If the table has its own row actions, - combine them rather than replacing the reorder items: + tableOptions sets state.columnVisibility, + the row action menu and muiTableBodyCellProps. If the table + has its own, combine them rather than replacing the reorder ones. A table with + its own row actions should use{" "} + mrtOptions({"{ onRowReorder }"}) and merge the menu items:

@@ -376,7 +393,6 @@ const table = useMaterialReactTable({
 
 const table = useMaterialReactTable({
   ...dsOptions,
-  enableRowActions: true,
   renderRowActionMenuItems: (props) => [
     ...myRowActions(props),
     ...(dsOptions.renderRowActionMenuItems?.(props) ?? []),
diff --git a/src/index.ts b/src/index.ts
index 5775fa6f..5ecc3e11 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -32,6 +32,7 @@ export * from "./themes/BaseTheme";
 export * from "./themes/DiamondTheme";
 export * from "./themes/DiamondDSTheme";
 export * from "./themes/DiamondDSIntegrations";
+export * from "./themes/useRowReorder";
 export * from "./themes/GenericTheme";
 export * from "./themes/ThemeProvider";
 export * from "./themes/ThemeManager";
diff --git a/src/themes/DiamondDSIntegrations.test.ts b/src/themes/DiamondDSIntegrations.test.ts
index 4a0f92e8..07e151fb 100644
--- a/src/themes/DiamondDSIntegrations.test.ts
+++ b/src/themes/DiamondDSIntegrations.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
 import type React from "react";
 import { DiamondDSIntegrations } from "./DiamondDSIntegrations";
 
@@ -52,78 +52,261 @@ describe("DiamondDSIntegrations.mrtOptions", () => {
     );
   });
 
+  beforeEach(() => vi.useFakeTimers());
+  afterEach(() => vi.useRealTimers());
+
+  const makeRows = () => [
+    { id: "a", index: 3, original: { locked: false } },
+    { id: "b", index: 5, original: { locked: true } },
+    { id: "c", index: 8, original: { locked: false } },
+  ];
+  const tableFor = (
+    rows: ReturnType,
+    state: object = {},
+    pageSize = 10,
+  ) => ({
+    getCoreRowModel: () => ({ rows }),
+    getPrePaginationRowModel: () => ({ rows }),
+    getState: () => ({ pagination: { pageSize }, ...state }),
+    setPageIndex: vi.fn(),
+    options: {},
+    refs: { tableContainerRef: { current: null as HTMLElement | null } },
+  });
+  const dragEvent = (button: Element, dropEffect: string) =>
+    ({
+      dataTransfer: { dropEffect },
+      currentTarget: button,
+    }) as unknown as React.DragEvent;
+  const renderRows = (rows: ReturnType) => {
+    document.body.innerHTML = `${rows
+      .map(
+        (r) =>
+          ``,
+      )
+      .join("")}
`; + return Array.from(document.querySelectorAll("tr")); + }; + it("drags a row, showing the drop edge and reporting source-data indices", () => { const onRowReorder = vi.fn(); const { muiRowDragHandleProps } = DiamondDSIntegrations.mrtOptions({ onRowReorder, }); - const rows = [ - { id: "a", index: 3 }, - { id: "b", index: 5 }, - { id: "c", index: 8 }, - ]; - document.body.innerHTML = `${rows - .map((r) => ``) - .join("")}
`; - const [trA, , trC] = Array.from(document.querySelectorAll("tr")); - // MRT tracks the dragged and hovered rows itself during a native drag - const table = { - getRowModel: () => ({ rows }), - getPrePaginationRowModel: () => ({ rows }), - getState: () => ({ draggingRow: rows[0], hoveredRow: rows[2] }), - }; - const dragEvent = (dropEffect: string) => - ({ - dataTransfer: { dropEffect }, - currentTarget: trA.querySelector("button")!, - }) as unknown as React.DragEvent; + const rows = makeRows(); + const [trA, , trC] = renderRows(rows); + const table = tableFor(rows, { draggingRow: rows[0], hoveredRow: rows[2] }); + const button = trA.querySelector("button")!; + const handle = () => muiRowDragHandleProps!({ row: rows[0], table }); - muiRowDragHandleProps!({ table }).onDragStart(dragEvent("move")); + handle().onDragStart(dragEvent(button, "move")); trC.cells[0].dispatchEvent(new Event("dragover", { bubbles: true })); expect(trA.hasAttribute("data-dragging")).toBe(true); expect(trC.dataset.dropEdge).toBe("bottom"); // MRT rebuilds the handle props mid-drag, so end on a fresh copy - muiRowDragHandleProps!({ table }).onDragEnd(dragEvent("move")); + handle().onDragEnd(dragEvent(button, "move")); expect(onRowReorder).toHaveBeenCalledWith(3, 8); + const status = document.querySelector("[data-ds-row-reorder-status]"); + expect(status?.textContent).toBe(""); + vi.advanceTimersByTime(250); + expect(status?.textContent).toBe("Row moved to position 3 of 3"); expect(trA.hasAttribute("data-dragging")).toBe(false); expect(trC.hasAttribute("data-drop-edge")).toBe(false); // A cancelled drag cleans up without moving onRowReorder.mockClear(); - muiRowDragHandleProps!({ table }).onDragStart(dragEvent("move")); - muiRowDragHandleProps!({ table }).onDragEnd(dragEvent("none")); + handle().onDragStart(dragEvent(button, "move")); + handle().onDragEnd(dragEvent(button, "none")); expect(onRowReorder).not.toHaveBeenCalled(); expect(trA.hasAttribute("data-dragging")).toBe(false); }); - it("offers Move up/down menu items that call onRowReorder", () => { + it("finds the dropped rows by id, so a data change mid-drag can't move the wrong row", () => { const onRowReorder = vi.fn(); - const { renderRowActionMenuItems } = DiamondDSIntegrations.mrtOptions({ + const { muiRowDragHandleProps } = DiamondDSIntegrations.mrtOptions({ onRowReorder, }); - // Page 2 shows `c` only; source-data indices differ from positions - const allRows = [ - { id: "a", index: 4 }, - { id: "b", index: 7 }, - { id: "c", index: 2 }, - ]; - const table = { - getRowModel: () => ({ rows: allRows.slice(2) }), - getPrePaginationRowModel: () => ({ rows: allRows }), - }; - const [up, down] = renderRowActionMenuItems!({ - closeMenu: () => {}, - row: allRows[2], - table, + const [a, , c] = makeRows(); + const button = document.createElement("button"); + const drop = (rows: ReturnType) => + muiRowDragHandleProps!({ + row: a, + table: tableFor(rows, { draggingRow: a, hoveredRow: c }), + }).onDragEnd(dragEvent(button, "move")); + + // The dragged row was removed + drop([c]); + expect(onRowReorder).not.toHaveBeenCalled(); + + // The target row moved: its current index is used, not the one it had + drop([a, { ...c, index: 1 }]); + expect(onRowReorder).toHaveBeenCalledWith(3, 1); + }); + + it("locks rows that aren't movable", () => { + const onRowReorder = vi.fn(); + const options = DiamondDSIntegrations.mrtOptions<{ locked: boolean }>({ + onRowReorder, + isRowMovable: (row) => !row.locked, }); + const rows = makeRows(); + const [trA, trB] = renderRows(rows); + const table = tableFor(rows); + + expect( + options.muiRowDragHandleProps!({ row: rows[1], table }), + ).toMatchObject({ draggable: false, sx: { display: "none" } }); + expect( + options.muiTableBodyCellProps!({ column: { id: "x" }, row: rows[1] })[ + "data-immovable" + ], + ).toBe(""); + expect( + options.renderRowActionMenuItems!({ + closeMenu: () => {}, + row: rows[1], + table, + }), + ).toEqual([]); + + // Dragging over a locked row refuses the drop and draws no line or MRT box + options.muiRowDragHandleProps!({ row: rows[0], table }).onDragStart( + dragEvent(trA.querySelector("button")!, "move"), + ); + const dataTransfer = { dropEffect: "move" }; + trB.cells[0].dispatchEvent( + Object.assign(new Event("dragover", { bubbles: true }), { dataTransfer }), + ); + expect(dataTransfer.dropEffect).toBe("none"); + expect(trB.dataset.dropEdge).toBe("none"); + }); + + it("offers menu moves that skip locked rows and call onRowReorder", () => { + const onRowReorder = vi.fn(); + const { renderRowActionMenuItems } = DiamondDSIntegrations.mrtOptions<{ + locked: boolean; + }>({ onRowReorder, isRowMovable: (row) => !row.locked }); + // Source-data indices differ from positions; `b` is locked + const rows = makeRows(); + const table = tableFor(rows); + const itemsFor = (row: (typeof rows)[number]) => + renderRowActionMenuItems!({ closeMenu: () => {}, row, table }); + const [top, up, down, bottom] = itemsFor(rows[2]); + expect(top.props.disabled).toBe(false); expect(down.props.disabled).toBe(true); + expect(bottom.props.disabled).toBe(true); up.props.onClick(); - expect(onRowReorder).toHaveBeenCalledWith(2, 7); + expect(onRowReorder).toHaveBeenLastCalledWith(8, 3); + + itemsFor(rows[0])[3].props.onClick(); + expect(onRowReorder).toHaveBeenLastCalledWith(3, 8); + expect(itemsFor(rows[0])[0].props.disabled).toBe(true); + }); + + it("stops tracking when the dragged row is removed mid-drag", () => { + const { muiRowDragHandleProps } = DiamondDSIntegrations.mrtOptions({ + onRowReorder: vi.fn(), + }); + const rows = makeRows(); + const [trA, , trC] = renderRows(rows); + muiRowDragHandleProps!({ row: rows[0], table: tableFor(rows) }).onDragStart( + dragEvent(trA.querySelector("button")!, "move"), + ); + + // MRT's dragend never arrives for a removed row + trA.remove(); + trC.cells[0].dispatchEvent(new Event("dragover", { bubbles: true })); + + expect(trC.hasAttribute("data-drop-edge")).toBe(false); + + // A new drag also ends one that never got its dragend + const [trB] = renderRows(rows); + const handle = (i: number) => + muiRowDragHandleProps!({ row: rows[i], table: tableFor(rows) }); + handle(0).onDragStart(dragEvent(trB.querySelector("button")!, "move")); + const [, trB2] = Array.from(document.querySelectorAll("tr")); + handle(1).onDragStart(dragEvent(trB2.querySelector("button")!, "move")); + expect(trB.hasAttribute("data-dragging")).toBe(false); + }); + + it("follows a row moved to another page and focuses its actions button", () => { + const { renderRowActionMenuItems } = DiamondDSIntegrations.mrtOptions({ + onRowReorder: vi.fn(), + }); + // The consumer has applied the move: `a` now sits on page 2 (size 2) + const [a, b, c] = makeRows(); + const table = tableFor([b, c, a], {}, 2); + // A second table shows a row with the same id; it must not count as ours + document.body.innerHTML = `
`; + const mine = document.getElementById("mine")!; + table.refs.tableContainerRef.current = mine; + // Page 2 renders once the table asks for it + table.setPageIndex.mockImplementation(() => { + mine.innerHTML = `
`; + }); + + renderRowActionMenuItems!({ + closeMenu: () => {}, + row: a, + table, + })[0].props.onClick(); + vi.runAllTimers(); + + expect(table.setPageIndex).toHaveBeenCalledWith(1); + expect(document.activeElement).toBe(mine.querySelector("button")); + }); + + it("doesn't change pages when pagination is off or server-side", () => { + const { renderRowActionMenuItems } = DiamondDSIntegrations.mrtOptions({ + onRowReorder: vi.fn(), + }); + const [a, b, c] = makeRows(); + document.body.innerHTML = ""; + + for (const options of [ + { enablePagination: false }, + { manualPagination: true }, + ]) { + const table = { ...tableFor([b, c, a], {}, 2), options }; + renderRowActionMenuItems!({ + closeMenu: () => {}, + row: a, + table, + })[0].props.onClick(); + vi.runAllTimers(); + expect(table.setPageIndex).not.toHaveBeenCalled(); + } + }); + + it("announces inside the table's dialog, which keeps the rest of the page hidden", () => { + const { renderRowActionMenuItems } = DiamondDSIntegrations.mrtOptions({ + onRowReorder: vi.fn(), + }); + const rows = makeRows(); + const table = tableFor(rows); + document.body.innerHTML = `
`; + table.refs.tableContainerRef.current = document.getElementById("mine"); + + renderRowActionMenuItems!({ closeMenu: () => {}, row: rows[0], table }); + + expect( + document.querySelector('[role="dialog"] > [data-ds-row-reorder-status]'), + ).not.toBeNull(); + }); + + it("keeps the reorder columns out of the Show/Hide menu and off ranked search", () => { + const options = DiamondDSIntegrations.mrtOptions({ onRowReorder: vi.fn() }); + + expect(options.enableGlobalFilterRankedResults).toBe(false); + for (const id of ["mrt-row-drag", "mrt-row-actions"] as const) + expect(options.displayColumnDefOptions[id]).toEqual({ + enableHiding: false, + visibleInShowHideMenu: false, + }); }); }); diff --git a/src/themes/DiamondDSIntegrations.ts b/src/themes/DiamondDSIntegrations.ts index 9bfcad63..3cad27bc 100644 --- a/src/themes/DiamondDSIntegrations.ts +++ b/src/themes/DiamondDSIntegrations.ts @@ -69,16 +69,19 @@ export const DiamondDSIntegrations = { }, // fullWidth drops the border/radius for tables with no surrounding container. - // `onRowReorder` receives source-data indices (MRT's `row.index`) on drop. - mrtOptions(options?: { + // `onRowReorder` receives source-data indices (MRT's `row.index`) on drop; + // `isRowMovable` locks rows out of it. Use `useRowReorder` for a toggleable mode. + mrtOptions(options?: { fullWidth?: boolean; onRowReorder?: (fromIndex: number, toIndex: number) => void; + isRowMovable?: (row: TData) => boolean; }) { const headCellBackgroundColor = "var(--ds-surface-container)"; - const { fullWidth = false, onRowReorder } = options ?? {}; + const { fullWidth = false, onRowReorder, isRowMovable } = options ?? {}; return { - ...(onRowReorder && mrtRowReorderOptions(onRowReorder)), + ...(onRowReorder && + mrtRowReorderOptions(onRowReorder, { isRowMovable })), // muiTableContainerProps overrides MuiTableContainer's themed // border/radius per-instance; Paper's radius must still match it below // (Paper clips its content, so a mismatch cuts the container's corners @@ -89,6 +92,14 @@ export const DiamondDSIntegrations = { // Recentres the auto-generated selection checkbox; its header cell // otherwise gets vertical-align: top with 0 bottom padding. displayColumnDefOptions: { + // Reorder columns are switched by `useRowReorder`, not picked by the + // user. Here, not in the reorder options, so a spread of those can't + // replace this whole object. `enableHiding` keeps "Hide all" off them. + "mrt-row-drag": { enableHiding: false, visibleInShowHideMenu: false }, + "mrt-row-actions": { + enableHiding: false, + visibleInShowHideMenu: false, + }, "mrt-row-select": { muiTableHeadCellProps: { sx: { diff --git a/src/themes/mrtRowReorder.tsx b/src/themes/mrtRowReorder.tsx index fe9be24e..bc027fee 100644 --- a/src/themes/mrtRowReorder.tsx +++ b/src/themes/mrtRowReorder.tsx @@ -3,19 +3,94 @@ import { MenuItem } from "@mui/material"; // Minimal MRT shapes, so `material-react-table` isn't a dependency. // `index` is the row's position in the source data, across pages and filters. -type MrtRow = { id: string; index: number }; -type MrtReorderTable = { - getRowModel: () => { rows: MrtRow[] }; - getPrePaginationRowModel: () => { rows: MrtRow[] }; -}; - -type MrtDragTable = MrtReorderTable & { +type MrtRow = { id: string; index: number; original: TData }; +type MrtReorderTable = { + getCoreRowModel: () => { rows: MrtRow[] }; + getPrePaginationRowModel: () => { rows: MrtRow[] }; getState: () => { - draggingRow?: MrtRow | null; - hoveredRow?: Partial | null; + draggingRow?: { id: string } | null; + hoveredRow?: { id?: string } | null; + pagination: { pageSize: number }; }; + setPageIndex: (pageIndex: number) => void; + options: { enablePagination?: boolean; manualPagination?: boolean }; + refs: { tableContainerRef: { current: HTMLElement | null } }; +}; + +const ANNOUNCER = "data-ds-row-reorder-status"; + +// Inside the table's modal (Dialog, Drawer) if it has one: MUI keeps the rest +// of the page aria-hidden while a modal is open. Created before the first +// move, as screen readers often skip a live region inserted with its message. +const getAnnouncer = (table: MrtReorderTable) => { + if (typeof document === "undefined") return null; + const host = + table.refs.tableContainerRef.current?.closest( + '[role="dialog"], [role="presentation"]', + ) ?? document.body; + let region = host.querySelector(`:scope > [${ANNOUNCER}]`); + if (!region) { + region = document.createElement("div"); + region.setAttribute(ANNOUNCER, ""); + region.setAttribute("role", "status"); + region.style.cssText = + "position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap"; + host.appendChild(region); + } + return region; +}; + +// Delayed: MUI marks the rest of the page aria-hidden while the row menu is +// open, and a live region changed in that window stays silent. Clearing first +// lets a repeated message be read again. +const announce = (table: MrtReorderTable, message: string) => { + const region = getAnnouncer(table); + if (!region) return; + region.textContent = ""; + setTimeout(() => { + region.textContent = message; + }, 250); }; +// Scoped to this table: default row ids ("0", "1", ...) repeat across tables. +const findCell = (table: MrtReorderTable, rowId: string) => + Array.from( + (table.refs.tableContainerRef.current ?? document).querySelectorAll( + "td[data-row-id]", + ), + ).find((cell) => cell.getAttribute("data-row-id") === rowId); + +const focusActionsButton = ( + table: MrtReorderTable, + rowId: string, + tries = 10, +) => { + const button = findCell(table, rowId) + ?.closest("tr") + ?.querySelector('td[data-column-id="mrt-row-actions"] button'); + if (button) button.focus(); + else if (tries > 0) + setTimeout(() => focusActionsButton(table, rowId, tries - 1), 50); +}; + +// A menu move can take the row to another page. Follow it there and put +// focus back on its actions button, which MUI can't restore once the old +// one has unmounted. If the row is still on screen, MUI handles focus. +const followRow = (table: MrtReorderTable, rowId: string) => + setTimeout(() => { + const { enablePagination, manualPagination } = table.options; + if (enablePagination === false || manualPagination) return; + if (findCell(table, rowId)) return; + const position = table + .getPrePaginationRowModel() + .rows.findIndex((r) => r.id === rowId); + if (position < 0) return; + table.setPageIndex( + Math.floor(position / table.getState().pagination.pageSize), + ); + focusActionsButton(table, rowId); + }); + // Marks the dragged row and the drop edge on the hovered row while MRT's // native drag runs; `muiTableBodyRowProps` styles both attributes. // Module-level: MRT rebuilds the handle props mid-drag, so the onDragEnd @@ -26,87 +101,160 @@ const trackDropEdge = (sourceRow: HTMLElement) => { let targetRow: HTMLElement | null = null; sourceRow.setAttribute("data-dragging", ""); + const stop = () => { + document.removeEventListener("dragover", onDragOver); + sourceRow.removeAttribute("data-dragging"); + targetRow?.removeAttribute("data-drop-edge"); + }; + const onDragOver = (e: DragEvent) => { - const tr = (e.target as Element | null) - ?.closest("td[data-row-id]") - ?.closest("tr"); - if (!tr || tr === targetRow) return; + // No dragend arrives if the data change removed the dragged row + if (!sourceRow.isConnected) return stop(); + const cell = (e.target as Element | null)?.closest("td[data-row-id]"); + const tr = cell?.closest("tr"); + if (!cell || !tr) return; + // On the document because MRT's cells set their own dragover handling + const locked = cell.hasAttribute("data-immovable"); + if (locked && e.dataTransfer) e.dataTransfer.dropEffect = "none"; + const next = tr === sourceRow ? null : tr; + if (next === targetRow) return; targetRow?.removeAttribute("data-drop-edge"); - targetRow = tr === sourceRow ? null : tr; + targetRow = next; // Line on the edge the row will land on: below when moving down const isBelow = sourceRow.compareDocumentPosition(tr) & Node.DOCUMENT_POSITION_FOLLOWING; - targetRow?.setAttribute("data-drop-edge", isBelow ? "bottom" : "top"); + // "none" for a locked row: no line, but MRT's own dashed box is replaced + targetRow?.setAttribute( + "data-drop-edge", + locked ? "none" : isBelow ? "bottom" : "top", + ); }; document.addEventListener("dragover", onDragOver); - return () => { - document.removeEventListener("dragover", onDragOver); - sourceRow.removeAttribute("data-dragging"); - targetRow?.removeAttribute("data-drop-edge"); - }; + return stop; }; // MRT options behind `mrtOptions({ onRowReorder })`: row drag plus a -// Move up/down row menu as the non-drag alternative (WCAG 2.5.7). -export const mrtRowReorderOptions = ( +// row menu of moves as the non-drag alternative (WCAG 2.5.7). +// `isRowMovable` locks rows: no handle, no drop onto them, no menu. +export const mrtRowReorderOptions = ( onRowReorder: (fromIndex: number, toIndex: number) => void, -) => ({ - enableRowOrdering: true, - // A sort would put moved rows straight back - enableSorting: false, - muiRowDragHandleProps: ({ table }: { table: MrtDragTable }) => ({ - onDragStart: (event: React.DragEvent) => { - // Move, not copy: drops the browser's + cursor - event.dataTransfer.effectAllowed = "move"; - const sourceRow = event.currentTarget.closest("tr"); - if (sourceRow) stopTracking = trackDropEdge(sourceRow); + { + isRowMovable = () => true, + }: { isRowMovable?: (row: TData) => boolean } = {}, +) => { + const move = ( + from: MrtRow, + to: MrtRow, + table: MrtReorderTable, + ) => { + const rows = table.getPrePaginationRowModel().rows; + onRowReorder(from.index, to.index); + const position = rows.findIndex((r) => r.id === to.id) + 1; + announce(table, `Row moved to position ${position} of ${rows.length}`); + }; + + return { + enableRowOrdering: true, + // A sort, or a search ranking rows by relevance, would put moved rows + // straight back + enableSorting: false, + enableGlobalFilterRankedResults: false, + muiRowDragHandleProps: ({ + row, + table, + }: { + row: MrtRow; + table: MrtReorderTable; + }) => { + const movable = isRowMovable(row.original); + return { + draggable: movable, + // Reordering by keyboard is the row menu, so the handle is no tab stop + tabIndex: -1, + "aria-hidden": true, + sx: movable ? undefined : { display: "none" }, + onDragStart: (event: React.DragEvent) => { + // Move, not copy: drops the browser's + cursor + event.dataTransfer.effectAllowed = "move"; + getAnnouncer(table); + stopTracking(); + const sourceRow = event.currentTarget.closest("tr"); + if (sourceRow) stopTracking = trackDropEdge(sourceRow); + }, + onDragEnd: (event: React.DragEvent) => { + stopTracking(); + stopTracking = () => {}; + // "none" when the drag was cancelled (Escape, or released outside) + if (event.dataTransfer.dropEffect === "none") return; + const { draggingRow, hoveredRow } = table.getState(); + if (!draggingRow || !hoveredRow?.id) return; + // By id, so a data change mid-drag can't move the wrong row + const rows = table.getCoreRowModel().rows; + const from = rows.find((r) => r.id === draggingRow.id); + const to = rows.find((r) => r.id === hoveredRow.id); + if (from && to && from.id !== to.id && isRowMovable(to.original)) + move(from, to, table); + }, + }; }, - onDragEnd: (event: React.DragEvent) => { - stopTracking(); - stopTracking = () => {}; - // "none" when the drag was cancelled (Escape, or released outside) - if (event.dataTransfer.dropEffect === "none") return; - const { draggingRow, hoveredRow } = table.getState(); - if (draggingRow && hoveredRow?.id && hoveredRow.id !== draggingRow.id) - onRowReorder(draggingRow.index, hoveredRow.index as number); + // Lets the drag find the hovered row. `className` is there so + // the return type shares a prop with MUI's `TableCellProps`. + muiTableBodyCellProps: ({ + column, + row, + }: { + column: { id: string }; + row: MrtRow; + }): { + className?: string; + "data-column-id": string; + "data-row-id": string; + "data-immovable"?: ""; + } => ({ + "data-column-id": column.id, + "data-row-id": row.id, + ...(isRowMovable(row.original) ? {} : { "data-immovable": "" as const }), + }), + enableRowActions: true, + positionActionsColumn: "last" as const, + renderRowActionMenuItems: ({ + closeMenu, + row, + table, + }: { + closeMenu: () => void; + row: MrtRow; + table: MrtReorderTable; + }) => { + // No items: MRT leaves out the row's actions button + if (!isRowMovable(row.original)) return []; + getAnnouncer(table); + // Across pages, so the first/last row of a page can move + const movable = table + .getPrePaginationRowModel() + .rows.filter((r) => isRowMovable(r.original)); + const position = movable.findIndex((r) => r.id === row.id); + const item = (key: string, label: string, to?: MrtRow) => ( + { + closeMenu(); + if (!to) return; + move(row, to, table); + followRow(table, row.id); + }} + > + {label} + + ); + return [ + item("move-top", "Move to top", movable[0]), + item("move-up", "Move up", movable[position - 1]), + item("move-down", "Move down", movable[position + 1]), + item("move-bottom", "Move to bottom", movable[movable.length - 1]), + ]; }, - }), - // Lets the drag find the hovered row. `className` is there so - // the return type shares a prop with MUI's `TableCellProps`. - muiTableBodyCellProps: ({ - row, - }: { - row: MrtRow; - }): { className?: string; "data-row-id": string } => ({ - "data-row-id": row.id, - }), - enableRowActions: true, - positionActionsColumn: "last" as const, - renderRowActionMenuItems: ({ - closeMenu, - row, - table, - }: { - closeMenu: () => void; - row: MrtRow; - table: MrtReorderTable; - }) => { - // Neighbours across pages, so the first/last row of a page can move - const rows = table.getPrePaginationRowModel().rows; - const position = rows.findIndex((r) => r.id === row.id); - const [above, below] = [rows[position - 1], rows[position + 1]]; - const move = (to: MrtRow) => { - closeMenu(); - onRowReorder(row.index, to.index); - }; - return [ - move(above)}> - Move up - , - move(below)}> - Move down - , - ]; - }, -}); + }; +}; diff --git a/src/themes/useRowReorder.test.tsx b/src/themes/useRowReorder.test.tsx new file mode 100644 index 00000000..32050a1a --- /dev/null +++ b/src/themes/useRowReorder.test.tsx @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from "vitest"; +import { renderHook, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useRowReorder } from "./useRowReorder"; + +describe("useRowReorder", () => { + it("shows the drag and menu columns and turns sorting off only while reordering", async () => { + const { result } = renderHook(() => useRowReorder({ onReorder: vi.fn() })); + const resetSorting = vi.fn(); + const visibility = () => result.current.tableOptions.state.columnVisibility; + + expect(visibility()).toMatchObject({ + "mrt-row-drag": false, + "mrt-row-actions": false, + }); + expect(result.current.tableOptions.enableSorting).toBe(true); + expect(result.current.tableOptions.enableGlobalFilterRankedResults).toBe( + true, + ); + + render( + <> + {result.current.renderToggleButton({ table: { resetSorting } })} + + , + ); + + await userEvent.click(screen.getByRole("button", { name: "Reorder rows" })); + + expect(visibility()).toMatchObject({ + "mrt-row-drag": true, + "mrt-row-actions": true, + }); + expect(result.current.tableOptions.enableSorting).toBe(false); + expect(result.current.tableOptions.enableGlobalFilterRankedResults).toBe( + false, + ); + expect(resetSorting).toHaveBeenCalled(); + expect(result.current.isReordering).toBe(true); + + // Other columns' visibility is kept, but not these two + await userEvent.click(screen.getByRole("button", { name: "Hide columns" })); + + expect(visibility()).toMatchObject({ + scientist: false, + "mrt-row-drag": true, + }); + }); +}); diff --git a/src/themes/useRowReorder.tsx b/src/themes/useRowReorder.tsx new file mode 100644 index 00000000..0942b297 --- /dev/null +++ b/src/themes/useRowReorder.tsx @@ -0,0 +1,59 @@ +import { useState } from "react"; +import { Button } from "@mui/material"; +import { mrtRowReorderOptions } from "./mrtRowReorder"; + +// Reorder mode for a Material React Table: the drag and row-menu columns show +// only while it is on, and sorting is off. Spread `tableOptions` after +// `DiamondDSIntegrations.mrtOptions()`, which styles the drop line. +// `tableOptions.state` holds `columnVisibility`; merge it with any `state` of your own. +export const useRowReorder = ({ + onReorder, + isRowMovable, + label = "Reorder rows", +}: { + onReorder: (fromIndex: number, toIndex: number) => void; + isRowMovable?: (row: TData) => boolean; + label?: string; +}) => { + const [isReordering, setIsReordering] = useState(false); + const [columnVisibility, setColumnVisibility] = useState< + Record + >({}); + + const tableOptions = { + ...mrtRowReorderOptions(onReorder, { isRowMovable }), + enableSorting: !isReordering, + enableGlobalFilterRankedResults: !isReordering, + onColumnVisibilityChange: setColumnVisibility, + state: { + columnVisibility: { + ...columnVisibility, + "mrt-row-drag": isReordering, + "mrt-row-actions": isReordering, + }, + }, + }; + + // For `renderTopToolbarCustomActions` + const renderToggleButton = ({ + table, + }: { + table: { resetSorting: () => void }; + }) => ( + + ); + + return { isReordering, tableOptions, renderToggleButton }; +};