Skip to content

rowReorder ​

Adds a grip to every row. Drag it — or focus it and press Space, then the arrow keys — to move the row; onEnd saves the new order, and a failed save puts the row back.

js
import { Datagrid, column, rowReorder, reorderColumn } from "@akinozgen17/datagrids";
import { agents } from "./data.js";

const rows = agents(12).map((r, i) => ({ ...r, position: i + 1 }));
const out = document.querySelector("#mod-row-reorder-out");

new Datagrid("#mod-row-reorder", {
  label: "Patrol order",
  columns: [
    reorderColumn(),
    column.number("position", { title: "#" }),
    column.text("name", { title: "Name" }),
    column.text("unit", { title: "Unit" }),
  ],
  data: rows,
  sort: [["position", "asc"]],
  pageSize: 8,
  use: [
    rowReorder({
      orderKey: "position",
      onEnd: async ({ key, from, to, prevKey, nextKey }) => {
        out.textContent = `PATCH /patrols/${key}/order ${JSON.stringify({ from, to, prevKey, nextKey })}`;
        await new Promise((r) => setTimeout(r, 300)); // the save
      },
    }),
  ],
});
html
<table id="mod-row-reorder"></table>
<div class="demo-output" id="mod-row-reorder-out" aria-live="polite">Drag a row by its grip, or focus a grip and press Space, then the arrow keys.</div>

When to use it ​

Use it for lists whose order is data: priorities, playlists, patrol routes, menu items. Skip it for lists sorted by a value (date, amount) — moving rows there means nothing.

Usage ​

Add reorderColumn() for a dedicated grip column (or let the grip sit in the first data column) and save in onEnd:

js
import { Datagrid, column, rowReorder, reorderColumn } from "@akinozgen17/datagrids";

const grid = new Datagrid("#patrols", {
  label: "Patrol order",
  columns: [reorderColumn(), column.number("position", { title: "#" }), column.text("name", { title: "Name" })],
  data: rows,
  sort: [["position", "asc"]],
  use: [
    rowReorder({
      orderKey: "position",
      onEnd: ({ key, prevKey, nextKey }) =>
        grid.action(`/patrols/${key}/move`, { method: "PATCH", body: { after: prevKey, before: nextKey }, reload: false }),
    }),
  ],
});
  • Moving is allowed while the grid is unsorted or sorted by orderKey. Sorted by any other column, the grips are disabled and explain why ("Sort by “#” to move rows").
  • Not while rows are hidden: a search or an active filter (grid.filters()) turns the grips off ("Clear the search and filters to move rows"). The order of a partial list would say nothing about the hidden rows, and onEnd would save it as if it did.
  • Client grids: the row moves in the data at once; while sorted by orderKey, the order values of the touched rows are renumbered. Server grids: the row moves on screen, and the page reloads (keeping the page) after onEnd resolves — the server's order is the truth.
  • A rejected onEnd puts the row back and shows the error (notify adapter or the error banner).

onEnd receives { row, key, from, to, offset, prevKey, nextKey, rows }: indexes are zero-based within the current page (offset + index = absolute position); prevKey / nextKey are the new neighbours, which is all a "place between" endpoint needs.

Options ​

OptionTypeDefaultDescription
onEnd(e: RowReorderEnd) => unknown— (required)Saves the move; a rejected promise reverts it.
orderKeystringnoneColumn key that stands for the stored order (moving is allowed while sorted by it).
handlestringreorderColumn(), else the first visible data columnColumn that holds the grip.
label(row) => stringthe first text column's valueRow name in the grip's name and the announcements.
messagesPartial<RowReorderMessages>locale (en / tr)Grip name, instructions, announcements, the sorted / filtered / virtual reasons, save errors.
canbooleantruePermission flag: false → no grips.

reorderColumn(options?) creates the grip column: narrow, not sortable, searchable, exportable or hideable, with a visually hidden "Order" header.

API added to the grid ​

Available as grid.rowReorder (typed: grid.module(rowReorder)).

MemberReturnsDescription
enabled()booleantrue while grips are active (no search or filter, not sorted by another column, nothing saving).
move(key, to)Promise<boolean>Moves a row of the current page to index to, through the same path as a drag.

Events ​

EventPayloadWhen
beforeReorderRowReorderEnd + cancel()Before the move is applied; cancel() puts the row back.
reorderRowReorderEndAfter onEnd resolved.
reordererrorRowReorderEnd + erroronEnd rejected; the row is back in place.

Accessibility ​

  • Each grip is a native <button aria-pressed> named "Move: Jill Valentine", described by the instructions. Keyboard: Space / Enter picks the row up, ↑ ↓ Home End move it, Space / Enter drops it, Esc (or Tab) cancels.
  • Every step is announced: "Jill Valentine picked up, position 3 of 8", "… dropped, position 1 of 8", "Move cancelled".
  • Disabled grips stay focusable (aria-disabled) and say why when activated; the row being saved is aria-busy.
  • Dragging near the edge of the page or of a maxHeight frame scrolls it; Esc cancels a drag.

Replaces in DataTables ​

DataTablesdatagrids
RowReorder extension, rowReorder: { dataSrc: "position" } (1.10 / 2.x / 3.x)rowReorder({ orderKey: "position", onEnd })
row-reorder event + an $.ajax saveonEnd (a rejection reverts)
rowReorder.selectorreorderColumn() or handle

Gotchas ​

  • The grips are greyed out. The grid is sorted by another column (sort by orderKey or clear the sort), or a search or filter is active (clear it). The grip's tooltip names the reason.
  • Rows only move within the page. Moves are page-local; raise the page size for long manual orderings.
  • The order jumped back after the save on a server grid. The reload shows the server's order: the endpoint did not store the move.

Released under the MIT License.