@sincpro/web-ui 2.17.0 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -360,7 +360,7 @@ The parts: `button`, `icon-button`, `control`, `popover`, `menu`, `menu.trigger`
360
360
  `board.stat`, `board.stat.value`, `activity.changes`, `file-list`, `file-list.file`, `file-value`, `metric`, `metric.detail`, `tag`, `tags.item`, `search`, `search.field`, `search.chip`, `search.facet-mark`,
361
361
  `search.panel`, `search.suggestions`, `search.suggestion`, `search.record`, `search.recent`,
362
362
  `search.advanced`, `search.keys`, `search.completion`, `search.undo`, `search.slash`, `search-entry`, `search-entry.keys`, `table`, `table.pile`, `yes-no`,
363
- `table.head`, `row.ways`, `topbar`, `topbar.brand`, `topbar.menus`, `topbar.actions`, `topbar.user`,
363
+ `table.head`, `table.grip`, `row.ways`, `topbar`, `topbar.brand`, `topbar.menus`, `topbar.actions`, `topbar.user`,
364
364
  `frame`, `frame.banner`, `frame.bar`, `frame.sidebar`, `frame.main`, `banner`, `banner.action`,
365
365
  `inbox`, `inbox.item` (with `data-unread`), `kbd`, `plans`, `plan` (with `data-highlight`, `data-current`), `plan.highlight`, `plan.price`,
366
366
  `plan.features`, `plan.action`, `qr`, `price`, `price.before`, `range-slider`, `rating`, `gallery`,
@@ -178,7 +178,7 @@ export type GroupColumn<T> = {
178
178
  /** How that key is read. */
179
179
  labelOf: (key: string) => string;
180
180
  };
181
- export declare function DataTable<T extends object>({ data, columns, getRowId, sort, onSortChange, levels, selected, onSelectedChange, height, onRowClick, rowActions, totals, collapsed, onGroupToggle, piles, onMore, create, copyable, }: {
181
+ export declare function DataTable<T extends object>({ data, columns, getRowId, sort, onSortChange, levels, selected, onSelectedChange, height, onRowClick, rowActions, totals, collapsed, onGroupToggle, piles, onMore, create, copyable, onReorder, }: {
182
182
  data: readonly T[];
183
183
  columns: readonly DataColumn<T>[];
184
184
  getRowId: (row: T) => string;
@@ -227,4 +227,14 @@ export declare function DataTable<T extends object>({ data, columns, getRowId, s
227
227
  /** The cells' copy buttons, on by default. `false` takes them off the whole table; a
228
228
  * column turns its own off with `copy: false`. */
229
229
  copyable?: boolean;
230
+ /**
231
+ * The records are in an order a person sets by hand (a `sequence`): a grip at the start of
232
+ * each row drags it, Alt + ↑ / ↓ moves it — `EditableTable`'s, the same `useRowReorder`.
233
+ * `before` is the row it lands in front of, `null` the end: one move, true on a page too.
234
+ *
235
+ * Off while grouped (the piles decide the order) and while sorted by a column (a row
236
+ * dropped would jump back to where the sort puts it): the order shown has to be the one
237
+ * being changed.
238
+ */
239
+ onReorder?: (id: string, before: string | null) => void;
230
240
  }): import("react").JSX.Element;
@@ -10,6 +10,7 @@ import { EditRow, firstControl } from "./EditableTable.js";
10
10
  import { levelNameOf } from "./levels.js";
11
11
  import { PileFootLine } from "./PileFootLine.js";
12
12
  import { RowActions } from "./RowActions.js";
13
+ import { useRowReorder } from "./rowReorder.js";
13
14
  import { useRowWindow } from "./rowWindow.js";
14
15
  import { SelectBox, Table, Td, Th, THead, Tr } from "./Table.js";
15
16
  import { YesNo } from "../value/YesNo.js";
@@ -222,7 +223,7 @@ function entriesOfPiles(piles, columns, keyOf, collapsed, onToggle, onMore) {
222
223
  ];
223
224
  });
224
225
  }
225
- export function DataTable({ data, columns, getRowId, sort, onSortChange, levels, selected, onSelectedChange, height, onRowClick, rowActions, totals = false, collapsed, onGroupToggle, piles, onMore, create, copyable = true, }) {
226
+ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels, selected, onSelectedChange, height, onRowClick, rowActions, totals = false, collapsed, onGroupToggle, piles, onMore, create, copyable = true, onReorder, }) {
226
227
  const copy = useUiCopy();
227
228
  const draft = create?.draft ?? null;
228
229
  const draftRow = useRef(null);
@@ -397,7 +398,15 @@ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels,
397
398
  };
398
399
  });
399
400
  const selecting = onSelectedChange !== undefined;
400
- const width = columns.length + (selecting ? 1 : 0) + (rowActions === undefined ? 0 : 1);
401
+ const reorder = useRowReorder({
402
+ order: entries.flatMap((entry) => (entry.kind === "row" ? [entry.id] : [])),
403
+ onReorder,
404
+ enabled: (levels ?? []).length === 0 && piles === undefined && (sort ?? []).length === 0,
405
+ });
406
+ const width = columns.length +
407
+ (selecting ? 1 : 0) +
408
+ (reorder.on ? 1 : 0) +
409
+ (rowActions === undefined ? 0 : 1);
401
410
  /* Past a few hundred rows only the ones in view are drawn — see `rowWindow.tsx`. It
402
411
  windows what is DRAWN, pile headers included and folded rows left out: that is the
403
412
  sequence a person scrolls through. */
@@ -418,7 +427,7 @@ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels,
418
427
  first one that sums, and from there each column says what the pile adds up to UNDER
419
428
  itself — Odoo's grouped list. With no column that sums, the name spans the row. */
420
429
  const firstSum = columns.findIndex((c) => c.aggregate !== undefined && c.numeric === true);
421
- const lead = selecting ? 1 : 0;
430
+ const lead = (selecting ? 1 : 0) + (reorder.on ? 1 : 0);
422
431
  const labelSpan = firstSum < 0 ? width : Math.max(1, lead + firstSum);
423
432
  const sumsFrom = firstSum < 0 ? columns.length : labelSpan - lead;
424
433
  const all = leaves.length > 0 && leaves.every((id) => selected?.has(id) === true);
@@ -435,7 +444,7 @@ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels,
435
444
  ? {
436
445
  rowCount: 1 + entries.length + (draft === null ? 0 : 1) + (totals ? 1 : 0),
437
446
  }
438
- : {}), children: [_jsxs(THead, { ...(view.on ? { rowIndex: 1 } : {}), children: [selecting ? (_jsx(Th, { width: 36, children: _jsx(SelectBox, { label: copy.selection.all, checked: all, indeterminate: some, onChange: (v) => onSelectedChange?.(v ? new Set(leaves) : new Set()) }) })) : null, columns.map((c) => (_jsx(Th, { sortKey: c.sortable === false ? undefined : c.id, sort: sort, onSort: onSortChange, numeric: c.numeric, width: c.width, children: c.header }, c.id))), rowActions === undefined ? null : (_jsx("td", { className: "w-px border-b border-line-strong" }))] }), _jsxs("tbody", { ref: view.body.ref, children: [view.rows.flatMap((slot, at) => {
447
+ : {}), children: [_jsxs(THead, { ...(view.on ? { rowIndex: 1 } : {}), children: [reorder.on ? _jsx("td", { className: "w-0 border-b border-line-strong" }) : null, selecting ? (_jsx(Th, { width: 36, children: _jsx(SelectBox, { label: copy.selection.all, checked: all, indeterminate: some, onChange: (v) => onSelectedChange?.(v ? new Set(leaves) : new Set()) }) })) : null, columns.map((c) => (_jsx(Th, { sortKey: c.sortable === false ? undefined : c.id, sort: sort, onSort: onSortChange, numeric: c.numeric, width: c.width, children: c.header }, c.id))), rowActions === undefined ? null : (_jsx("td", { className: "w-px border-b border-line-strong" }))] }), _jsxs("tbody", { ref: view.body.ref, ...reorder.body, children: [view.rows.flatMap((slot, at) => {
439
448
  const entry = entries[slot.index];
440
449
  if (entry === undefined)
441
450
  return [];
@@ -469,7 +478,7 @@ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels,
469
478
  const id = entry.id;
470
479
  return [
471
480
  gap,
472
- _jsxs(Tr, { ...(windowed === undefined ? {} : { windowed }), selected: selected?.has(id) === true, onClick: onRowClick === undefined ? undefined : () => onRowClick(original), children: [selecting ? (_jsx(Td, { children: _jsx(SelectBox, { label: copy.selection.row, checked: selected?.has(id) === true, onChange: (v) => toggle(id, v) }) })) : null, columns.map((c) => {
481
+ _jsxs(Tr, { ...(windowed === undefined ? {} : { windowed }), selected: selected?.has(id) === true, onClick: onRowClick === undefined ? undefined : () => onRowClick(original), ...(reorder.on ? { rowId: id, line: reorder.line(id) } : {}), children: [reorder.on ? _jsx(Td, { fit: true, children: reorder.grip(id) }) : null, selecting ? (_jsx(Td, { children: _jsx(SelectBox, { label: copy.selection.row, checked: selected?.has(id) === true, onChange: (v) => toggle(id, v) }) })) : null, columns.map((c) => {
473
482
  const t = c.tone?.(original);
474
483
  const n = c.note?.(original);
475
484
  const edit = c.edit?.when?.(original) === false ? undefined : c.edit;
@@ -489,10 +498,10 @@ export function DataTable({ data, columns, getRowId, sort, onSortChange, levels,
489
498
  create.onCommit(draft);
490
499
  start();
491
500
  return true;
492
- }, children: [selecting ? _jsx("td", { className: DRAFT_CELL }) : null, columns.map((c) => (_jsx("td", { ...(c.input === undefined ? {} : { "data-edit": "" }), className: `${DRAFT_CELL} ${c.numeric === true ? "text-right tabular-nums" : ""}`, children: c.input?.(draft, (next) => {
501
+ }, children: [reorder.on ? _jsx("td", { className: DRAFT_CELL }) : null, selecting ? _jsx("td", { className: DRAFT_CELL }) : null, columns.map((c) => (_jsx("td", { ...(c.input === undefined ? {} : { "data-edit": "" }), className: `${DRAFT_CELL} ${c.numeric === true ? "text-right tabular-nums" : ""}`, children: c.input?.(draft, (next) => {
493
502
  touched.current = true;
494
503
  create.onChange(next);
495
- }) ?? null }, c.id))), rowActions === undefined ? null : _jsx("td", { className: DRAFT_CELL })] }))] }), footer === null ? null : (_jsx("tfoot", { className: "sticky bottom-0 z-10 bg-ground", children: _jsxs("tr", { className: "border-t border-line-strong", "aria-rowindex": view.on ? 2 + entries.length + (draft === null ? 0 : 1) : undefined, children: [selecting ? _jsx("td", {}) : null, columns.map((c, i) => {
504
+ }) ?? null }, c.id))), rowActions === undefined ? null : _jsx("td", { className: DRAFT_CELL })] }))] }), footer === null ? null : (_jsx("tfoot", { className: "sticky bottom-0 z-10 bg-ground", children: _jsxs("tr", { className: "border-t border-line-strong", "aria-rowindex": view.on ? 2 + entries.length + (draft === null ? 0 : 1) : undefined, children: [reorder.on ? _jsx("td", {}) : null, selecting ? _jsx("td", {}) : null, columns.map((c, i) => {
496
505
  const value = footer[i] ?? null;
497
506
  return (_jsx("td", { className: `px-3 py-1.5 text-meta font-semibold text-ink ${c.numeric === true ? "text-right tabular-nums" : ""}`, children: i === 0 && value === null ? (_jsxs("span", { className: "text-muted", children: [data.length.toLocaleString(copy.locale), " ", data.length === 1 ? copy.table.row : copy.table.rows] })) : value === null ? null : (aggregateLabel(copy, c, value)) }, c.id));
498
507
  }), rowActions === undefined ? null : _jsx("td", {})] }) }))] }));
@@ -10,9 +10,10 @@ import { IconButton } from "../button/Button.js";
10
10
  import { NoteCard, NoteRegistryContext, } from "../field/note.js";
11
11
  import { Flag } from "../notice/Flag.js";
12
12
  import { sectionLines, stackPlaces, tabTarget, } from "./editRules.js";
13
+ import { useRowReorder } from "./rowReorder.js";
13
14
  import { useRowWindow } from "./rowWindow.js";
14
15
  import { HEADER_TEXT } from "./Table.js";
15
- import { AlertCircle, GripVertical, Plus, Trash2 } from "lucide-react";
16
+ import { AlertCircle, Plus, Trash2 } from "lucide-react";
16
17
  import { Fragment, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, } from "react";
17
18
  import { useKeyboard } from "react-aria";
18
19
  export { sectionLines, stackPlaces, tabTarget };
@@ -393,8 +394,6 @@ groupTotal, height, layout = "auto", onOpen, onDiscard, bands, adds, flag, onReo
393
394
  /* The rows in the order they are drawn: what the arrows walk. */
394
395
  const order = drawn.flatMap((entry) => entry.row === undefined ? [] : [getRowId(entry.row)]);
395
396
  const stop = active !== null && order.includes(active) ? active : (order[0] ?? null);
396
- /* REORDER — a grip at the start of each row. Dragged, the row shows where it would land (a
397
- line over the row it goes in front of); Alt + ↑ / ↓ on the grip does the same by keyboard. */
398
397
  /* The notes of the rows the window does not draw. A drawn row's mark registers its note
399
398
  with the record (`NoteCard`); one scrolled out of the window would vanish from the
400
399
  record's activity — «2 avisos» for a document that has nine. The table registers those
@@ -454,51 +453,20 @@ groupTotal, height, layout = "auto", onOpen, onDiscard, bands, adds, flag, onReo
454
453
  for (const noteId of ownNotes.current)
455
454
  registry?.drop(noteId);
456
455
  }, [registry]);
457
- const reorderable = onReorder !== undefined && grouping === undefined && !stacked;
456
+ /* The row's move — `useRowReorder`, shared with `DataTable`. Off while grouped (the piles
457
+ decide the order) and on a phone's cards. */
458
+ const reorder = useRowReorder({
459
+ order,
460
+ onReorder,
461
+ enabled: grouping === undefined && !stacked,
462
+ });
463
+ const reorderable = reorder.on;
458
464
  /* Every cell of a row, the grip and the trash: what a spacer row spans. */
459
465
  const width = columns.length + (onRemove === undefined ? 0 : 1) + (reorderable ? 1 : 0);
460
- /* A ref and not state: `dragover` can arrive before React re-renders after `dragstart`. */
461
- const dragged = useRef(null);
462
- const [landing, setLanding] = useState(undefined);
463
- const after = (id) => order[order.indexOf(id) + 1] ?? null;
464
- const land = (id, before) => {
465
- if (before === id || before === after(id))
466
- return;
467
- onReorder?.(id, before);
468
- };
469
- const overRow = (event) => {
470
- if (dragged.current === null)
471
- return;
472
- const tr = event.target.closest("tr[data-row-id]");
473
- if (tr === null)
474
- return;
475
- event.preventDefault();
476
- const id = tr.dataset["rowId"] ?? "";
477
- const box = tr.getBoundingClientRect();
478
- setLanding(event.clientY < box.top + box.height / 2 ? id : after(id));
479
- };
480
- const lineOver = (id) => (landing === id ? "border-t-2 border-t-primary" : "");
481
- const grip = (id, mark) => (_jsx("td", { className: `w-0 py-1 pr-0 pl-1 align-middle ${mark} ${lineOver(id)}`, children: _jsx("button", { type: "button", draggable: true, "aria-label": copy.editable.reorder, title: copy.editable.reorderHint, "aria-keyshortcuts": "Alt+ArrowUp Alt+ArrowDown", ...(editable && stop !== id ? { tabIndex: -1 } : {}), onClick: (event) => event.stopPropagation(), onKeyDown: (event) => {
482
- if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown"))
483
- return;
484
- event.preventDefault();
485
- event.stopPropagation();
486
- const at = order.indexOf(id);
487
- if (event.key === "ArrowUp" && at > 0)
488
- land(id, order[at - 1] ?? null);
489
- if (event.key === "ArrowDown" && at < order.length - 1)
490
- land(id, order[at + 2] ?? null);
491
- }, onDragStart: (event) => {
492
- event.dataTransfer.setData("text/plain", id);
493
- event.dataTransfer.effectAllowed = "move";
494
- const tr = event.currentTarget.closest("tr");
495
- if (tr !== null)
496
- event.dataTransfer.setDragImage(tr, 16, 16);
497
- dragged.current = id;
498
- }, onDragEnd: () => {
499
- dragged.current = null;
500
- setLanding(undefined);
501
- }, className: "flex cursor-grab items-center rounded-control p-0.5 text-muted opacity-40 transition-opacity duration-(--duration-instant) group-hover/row:opacity-100 hover:text-ink focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-primary active:cursor-grabbing", children: _jsx(GripVertical, { "aria-hidden": true, className: "size-(--size-icon-sm)", strokeWidth: 2 }) }) }));
466
+ const lineOver = reorder.line;
467
+ /* Only the row holding the tab stop offers its grip to `Tab`; the others are reached with
468
+ the arrows first. */
469
+ const grip = (id, mark) => (_jsx("td", { className: `w-0 py-1 pr-0 pl-1 align-middle ${mark} ${lineOver(id)}`, children: reorder.grip(id, { tabbable: !(editable && stop !== id) }) }));
502
470
  /* The focus a row is waiting for, once it is drawn: opened by the keyboard (its first or
503
471
  last control), or reached by a jump (`Home`, `End`) past what the window draws. Every
504
472
  render and not on `editing` alone: a row outside the window shows up a render or two
@@ -785,18 +753,7 @@ groupTotal, height, layout = "auto", onOpen, onDiscard, bands, adds, flag, onReo
785
753
  least: a name cut with «…» asks for no width of its own. */
786
754
  places[ci] === "title" && c.width === undefined
787
755
  ? "min-w-(--size-cell-title)"
788
- : ""}`, children: c.header }, c.id))), onRemove === undefined ? null : (_jsx("td", { className: "w-0 border-b border-line-strong" }))] }) }), _jsxs("tbody", { ref: view.body.ref, ...(reorderable
789
- ? {
790
- onDragOver: overRow,
791
- onDrop: (event) => {
792
- event.preventDefault();
793
- if (dragged.current !== null && landing !== undefined)
794
- land(dragged.current, landing);
795
- dragged.current = null;
796
- setLanding(undefined);
797
- },
798
- }
799
- : {}), children: [rows.length === 0 ? (_jsx("tr", { children: _jsx("td", { colSpan: columns.length +
756
+ : ""}`, children: c.header }, c.id))), onRemove === undefined ? null : (_jsx("td", { className: "w-0 border-b border-line-strong" }))] }) }), _jsxs("tbody", { ref: view.body.ref, ...reorder.body, children: [rows.length === 0 ? (_jsx("tr", { children: _jsx("td", { colSpan: columns.length +
800
757
  (onRemove === undefined ? 0 : 1) +
801
758
  (reorderable ? 1 : 0), className: `text-meta text-muted italic ${cell}`, children: emptyText }) })) : (view.rows.flatMap((slot, at) => {
802
759
  const entry = drawn[slot.index];
@@ -47,12 +47,18 @@ export declare function Th({ children, sortKey, sort, onSort, numeric, align, wi
47
47
  * system scale instead of pinning a size in pixels. */
48
48
  width?: number | string;
49
49
  }): import("react").JSX.Element;
50
- export declare function Tr({ children, onClick, selected, windowed, }: {
50
+ export declare function Tr({ children, onClick, selected, windowed, rowId, line, }: {
51
51
  children: ReactNode;
52
52
  onClick?: () => void;
53
53
  selected?: boolean;
54
54
  /** Set by a table that draws only the rows in view (`useRowWindow`). */
55
55
  windowed?: WindowedRow;
56
+ /** The row's id as `data-row-id`: what a drag reads to know which row it is over
57
+ * (`useRowReorder`). */
58
+ rowId?: string;
59
+ /** A class every cell of the row carries — the line where a dragged row would land
60
+ * (`useRowReorder`'s `line`). On the cells: a separated table draws no border on a row. */
61
+ line?: string;
56
62
  }): import("react").JSX.Element;
57
63
  /**
58
64
  * A row that opens its own detail underneath.
@@ -92,8 +98,11 @@ mono,
92
98
  * number is of another kind»; tinting the cell says «look here», which is
93
99
  * something else — and in a table of forty rows by six columns, colored text
94
100
  * gets lost. */
95
- tone, title, }: {
101
+ tone, title, fit, }: {
96
102
  children: ReactNode;
103
+ /** As narrow as what it holds, without the side padding: a cell for a control — the grip
104
+ * that moves the row — and not for a value. */
105
+ fit?: boolean;
97
106
  numeric?: boolean;
98
107
  /** Pushes without saying it is a number. See the note on `Th`. */
99
108
  align?: "left" | "right";
@@ -100,7 +100,10 @@ export function Th({ children, sortKey, sort, onSort, numeric = false, align, wi
100
100
  /** The wash of a row lives on the cells, not on the `<tr>`. A background on the
101
101
  * row paints edge to edge; on the cells the ends can round and the table's
102
102
  * padding keeps the mark off the card. */
103
- const RowMark = createContext({ selected: false, interactive: false });
103
+ const RowMark = createContext({
104
+ selected: false,
105
+ interactive: false,
106
+ });
104
107
  const ROW_WASH = "group-hover/row:bg-ink/4";
105
108
  const ROW_ON = "bg-primary/8";
106
109
  /* The hover wash only where a click does something: on a read-only row it promised a click
@@ -108,8 +111,12 @@ const ROW_ON = "bg-primary/8";
108
111
  function rowWash({ selected, interactive }) {
109
112
  return selected ? ROW_ON : interactive ? ROW_WASH : "";
110
113
  }
111
- export function Tr({ children, onClick, selected = false, windowed, }) {
112
- return (_jsx(RowMark.Provider, { value: { selected, interactive: onClick !== undefined }, children: _jsx("tr", { ...windowed, onClick: onClick, className: `group/row ${onClick === undefined ? "" : "cursor-pointer"}`, children: children }) }));
114
+ export function Tr({ children, onClick, selected = false, windowed, rowId, line, }) {
115
+ return (_jsx(RowMark.Provider, { value: {
116
+ selected,
117
+ interactive: onClick !== undefined,
118
+ ...(line === undefined ? {} : { line }),
119
+ }, children: _jsx("tr", { ...windowed, ...(rowId === undefined ? {} : { "data-row-id": rowId }), onClick: onClick, className: `group/row ${onClick === undefined ? "" : "cursor-pointer"}`, children: children }) }));
113
120
  }
114
121
  /**
115
122
  * A row that opens its own detail underneath.
@@ -149,9 +156,9 @@ mono = false,
149
156
  * number is of another kind»; tinting the cell says «look here», which is
150
157
  * something else — and in a table of forty rows by six columns, colored text
151
158
  * gets lost. */
152
- tone, title, }) {
159
+ tone, title, fit = false, }) {
153
160
  const mark = useContext(RowMark);
154
- return (_jsx("td", { title: title, className: `border-b border-line px-3 py-1.5 text-meta text-ink first:rounded-l-control last:rounded-r-control ${(align ?? (numeric ? "right" : "left")) === "right" ? "text-right" : "text-left"} ${mono ? "font-mono tabular-nums" : numeric ? "tabular-nums whitespace-nowrap" : ""} ${tone === undefined ? rowWash(mark) : CELL_TONE[tone]}`, children: children }));
161
+ return (_jsx("td", { title: title, className: `border-b border-line py-1.5 text-meta text-ink first:rounded-l-control last:rounded-r-control ${fit ? "w-0 pr-0 pl-1 align-middle" : "px-3"} ${(align ?? (numeric ? "right" : "left")) === "right" ? "text-right" : "text-left"} ${mono ? "font-mono tabular-nums" : numeric ? "tabular-nums whitespace-nowrap" : ""} ${tone === undefined ? rowWash(mark) : CELL_TONE[tone]} ${mark.line ?? ""}`, children: children }));
155
162
  }
156
163
  /** The selection checkbox, with its third state.
157
164
  *
@@ -0,0 +1,25 @@
1
+ import { type HTMLAttributes, type ReactNode } from "react";
2
+ /** What a table wires to let its rows be moved. */
3
+ export interface RowReorder {
4
+ /** Whether rows move: `onReorder` given and the table allows it (not grouped, not sorted). */
5
+ readonly on: boolean;
6
+ /** For the `tbody`: where a dragged row would land, and the drop. Empty when off. */
7
+ readonly body: Pick<HTMLAttributes<HTMLElement>, "onDragOver" | "onDrop">;
8
+ /** The landing line, for EVERY cell of row `id`: over it when the row lands in front of
9
+ * it, under it when it is the last one and the row goes to the end. */
10
+ line: (id: string) => string;
11
+ /** The grip of row `id`: the button, without its cell — each table draws its own. With
12
+ * `tabbable: false` it leaves the tab order (a grid that walks its rows with arrows). */
13
+ grip: (id: string, options?: {
14
+ tabbable?: boolean;
15
+ }) => ReactNode;
16
+ }
17
+ /** A grip at the start of each row that drags it, and Alt + ↑ / ↓ that moves it. `order` is
18
+ * the ids in the order they are drawn — every one, drawn by the row window or not. */
19
+ export declare function useRowReorder({ order, onReorder, enabled, }: {
20
+ order: readonly string[];
21
+ onReorder: ((id: string, before: string | null) => void) | undefined;
22
+ /** The table's own conditions: off while grouped (the piles decide the order) or sorted
23
+ * by a column (a row dropped would jump back to where the sort puts it). */
24
+ enabled?: boolean;
25
+ }): RowReorder;
@@ -0,0 +1,99 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useUiCopy } from "../../foundations/copy.js";
4
+ import { GripVertical } from "lucide-react";
5
+ import { useLayoutEffect, useRef, useState, } from "react";
6
+ /* Over the row it goes in front of; under the last one for the end. Cells only: a border on
7
+ a `tr` is not drawn in a separated table. */
8
+ const OVER = "border-t-2 border-t-primary";
9
+ const UNDER = "border-b-2 border-b-primary";
10
+ /** A grip at the start of each row that drags it, and Alt + ↑ / ↓ that moves it. `order` is
11
+ * the ids in the order they are drawn — every one, drawn by the row window or not. */
12
+ export function useRowReorder({ order, onReorder, enabled = true, }) {
13
+ const copy = useUiCopy();
14
+ const on = onReorder !== undefined && enabled;
15
+ /* A ref and not state: `dragover` can arrive before React re-renders after `dragstart`. */
16
+ const dragged = useRef(null);
17
+ /* `undefined` while nothing is dragged; `null` is «to the end». */
18
+ const [landing, setLanding] = useState(undefined);
19
+ /* The row moved by keyboard, to give its grip the focus back: React moves the row's node
20
+ and a focused node that is moved loses the focus. */
21
+ const moved = useRef(null);
22
+ const signature = order.join("\u0000");
23
+ useLayoutEffect(() => {
24
+ const want = moved.current;
25
+ /* Only once the order came back changed: `onReorder` may answer after a round trip. */
26
+ if (want === null || want.was === signature)
27
+ return;
28
+ moved.current = null;
29
+ const grip = want.body.querySelector(`tr[data-row-id="${CSS.escape(want.id)}"] [data-ui="table.grip"]`);
30
+ if (grip !== null && document.activeElement !== grip)
31
+ grip.focus();
32
+ }, [signature]);
33
+ const after = (id) => order[order.indexOf(id) + 1] ?? null;
34
+ const land = (id, before) => {
35
+ if (before === id || before === after(id))
36
+ return;
37
+ onReorder?.(id, before);
38
+ };
39
+ const end = () => {
40
+ dragged.current = null;
41
+ setLanding(undefined);
42
+ };
43
+ if (!on)
44
+ return { on, body: {}, line: () => "", grip: () => null };
45
+ const last = order[order.length - 1];
46
+ return {
47
+ on,
48
+ body: {
49
+ onDragOver: (event) => {
50
+ if (dragged.current === null)
51
+ return;
52
+ const tr = event.target.closest("tr[data-row-id]");
53
+ const id = tr?.dataset["rowId"];
54
+ /* Only the rows of `order`: a row being written, a pile, a spacer are not places. */
55
+ if (tr === null || id === undefined || !order.includes(id))
56
+ return;
57
+ event.preventDefault();
58
+ const box = tr.getBoundingClientRect();
59
+ setLanding(event.clientY < box.top + box.height / 2 ? id : after(id));
60
+ },
61
+ onDrop: (event) => {
62
+ event.preventDefault();
63
+ if (dragged.current !== null && landing !== undefined)
64
+ land(dragged.current, landing);
65
+ end();
66
+ },
67
+ },
68
+ line: (id) => (landing === id ? OVER : landing === null && id === last ? UNDER : ""),
69
+ grip: (id, options) => (_jsx("button", { type: "button", draggable: true, "data-ui": "table.grip", "aria-label": copy.editable.reorder, title: copy.editable.reorderHint, "aria-keyshortcuts": "Alt+ArrowUp Alt+ArrowDown", ...(options?.tabbable === false ? { tabIndex: -1 } : {}),
70
+ /* The row may open on a click; the grip is not the row. */
71
+ onClick: (event) => event.stopPropagation(), onKeyDown: (event) => {
72
+ if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown"))
73
+ return;
74
+ event.preventDefault();
75
+ event.stopPropagation();
76
+ const at = order.indexOf(id);
77
+ const to = event.key === "ArrowUp"
78
+ ? at > 0
79
+ ? (order[at - 1] ?? null)
80
+ : undefined
81
+ : at < order.length - 1
82
+ ? (order[at + 2] ?? null)
83
+ : undefined;
84
+ if (to === undefined)
85
+ return;
86
+ const body = event.currentTarget.closest("tbody");
87
+ if (body !== null)
88
+ moved.current = { id, was: signature, body };
89
+ land(id, to);
90
+ }, onDragStart: (event) => {
91
+ event.dataTransfer.setData("text/plain", id);
92
+ event.dataTransfer.effectAllowed = "move";
93
+ const tr = event.currentTarget.closest("tr");
94
+ if (tr !== null)
95
+ event.dataTransfer.setDragImage(tr, 16, 16);
96
+ dragged.current = id;
97
+ }, onDragEnd: end, className: "flex cursor-grab items-center rounded-control p-0.5 text-muted opacity-40 transition-opacity duration-(--duration-instant) group-hover/row:opacity-100 hover:text-ink focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-primary active:cursor-grabbing", children: _jsx(GripVertical, { "aria-hidden": true, className: "size-(--size-icon-sm)", strokeWidth: 2 }) })),
98
+ };
99
+ }
@@ -47,6 +47,11 @@ type TableProps<T extends object> = {
47
47
  /** Write a new record as one more row of the table (Odoo's editable
48
48
  * list). See `DataTable`'s header. */
49
49
  create?: DataTableCreate<T>;
50
+ /** The records are in an order a person sets by hand (a `sequence`): a grip at the start of
51
+ * each row of the table drags it, Alt + ↑ / ↓ moves it. `before` is the row it lands in
52
+ * front of, `null` the end. Off while grouped or sorted by a column, and in the phone's
53
+ * rows — see `DataTable`'s `onReorder`. */
54
+ onReorder?: (id: string, before: string | null) => void;
50
55
  };
51
56
  /** The board. Without `card`, the card comes from what `List.Rows` already says: the
52
57
  * name, the `meta` and the chips. Writing it anyway is declaring that THIS list
@@ -151,6 +151,10 @@ export function List({ items, keyOf, embedded, surface, group, selection: select
151
151
  ? {}
152
152
  : { rowActions: table.rowActions }),
153
153
  ...(table.create === undefined || readOnly ? {} : { create: table.create }),
154
+ /* Read-only: moving a record is writing its position. */
155
+ ...(table.onReorder === undefined || readOnly
156
+ ? {}
157
+ : { onReorder: table.onReorder }),
154
158
  ...(table.visibleColumnIds === undefined
155
159
  ? {}
156
160
  : { visibleColumnIds: table.visibleColumnIds }),
@@ -1,5 +1,5 @@
1
1
  import type { ListViewProps } from "./types.js";
2
- export declare function ListView<T extends object>({ items, keyOf, identity, crumbs, embedded, surface: requestedSurface, metrics, filters, search, pagination, views, actions: written, dock, row, rowHeader, columns, visibleColumnIds, onVisibleColumnIdsChange, card, tiles, boardStages, calendar, gantt, timeline, sheet, report, pivot, chart, faces, present: requested, presents, onPresentChange, sort, onSortChange, sortable, totals, rowActions, create, group, selection, onOpen, onPeek, openTargets, onOpenIn, rowClick, onChoose, state, filtered, empty, children, }: ListViewProps<T>): import("react").JSX.Element;
2
+ export declare function ListView<T extends object>({ items, keyOf, identity, crumbs, embedded, surface: requestedSurface, metrics, filters, search, pagination, views, actions: written, dock, row, rowHeader, columns, visibleColumnIds, onVisibleColumnIdsChange, card, tiles, boardStages, calendar, gantt, timeline, sheet, report, pivot, chart, faces, present: requested, presents, onPresentChange, sort, onSortChange, sortable, totals, rowActions, onReorder, create, group, selection, onOpen, onPeek, openTargets, onOpenIn, rowClick, onChoose, state, filtered, empty, children, }: ListViewProps<T>): import("react").JSX.Element;
3
3
  /** What a list offers when it fails and can be retried. */
4
4
  export declare function RetryAction({ onRetry }: {
5
5
  onRetry: () => void;
@@ -90,7 +90,7 @@ const PRESENT_ICONS = [
90
90
  { id: "gantt", icon: ChartGantt },
91
91
  { id: "timeline", icon: CalendarRange },
92
92
  ];
93
- export function ListView({ items, keyOf, identity, crumbs, embedded = false, surface: requestedSurface, metrics, filters, search, pagination, views, actions: written, dock, row, rowHeader, columns, visibleColumnIds, onVisibleColumnIdsChange, card, tiles, boardStages, calendar, gantt, timeline, sheet, report, pivot, chart, faces, present: requested = "rows", presents, onPresentChange, sort, onSortChange, sortable, totals = false, rowActions, create, group, selection, onOpen, onPeek, openTargets, onOpenIn, rowClick = "peek", onChoose, state, filtered = false, empty, children, }) {
93
+ export function ListView({ items, keyOf, identity, crumbs, embedded = false, surface: requestedSurface, metrics, filters, search, pagination, views, actions: written, dock, row, rowHeader, columns, visibleColumnIds, onVisibleColumnIdsChange, card, tiles, boardStages, calendar, gantt, timeline, sheet, report, pivot, chart, faces, present: requested = "rows", presents, onPresentChange, sort, onSortChange, sortable, totals = false, rowActions, onReorder, create, group, selection, onOpen, onPeek, openTargets, onOpenIn, rowClick = "peek", onChoose, state, filtered = false, empty, children, }) {
94
94
  const wide = useMemo(() => [
95
95
  ...WIDE_PRESENTS,
96
96
  ...(faces ?? []).filter((f) => f.wide === true).map((f) => f.id),
@@ -423,7 +423,7 @@ export function ListView({ items, keyOf, identity, crumbs, embedded = false, sur
423
423
  ...(onOpen === undefined || choosing ? {} : { open: onOpen }),
424
424
  })) : present === "table" && shownColumns !== undefined ? (
425
425
  /* The table receives EVERYTHING that belongs to the set: see `TablePresentation`. */
426
- _jsx(TablePresentation, { items: items, columns: shownColumns, keyOf: keyOf, levels: groupLevels, ...(sort === undefined ? {} : { sort }), ...(onSortChange === undefined ? {} : { onSortChange }), ...(group === undefined ? {} : { group }), ...(selection === undefined ? {} : { selection }), totals: totals, ...(rowActions === undefined ? {} : { rowActions }), ...(create === undefined ? {} : { create }), ...(onPeek === undefined || choosing ? {} : { onPeek }), ...(onOpen === undefined || choosing ? {} : { onOpen }), ...(openTargets === undefined || onOpenIn === undefined || choosing
426
+ _jsx(TablePresentation, { items: items, columns: shownColumns, keyOf: keyOf, levels: groupLevels, ...(sort === undefined ? {} : { sort }), ...(onSortChange === undefined ? {} : { onSortChange }), ...(group === undefined ? {} : { group }), ...(selection === undefined ? {} : { selection }), totals: totals, ...(rowActions === undefined ? {} : { rowActions }), ...(onReorder === undefined || choosing ? {} : { onReorder }), ...(create === undefined ? {} : { create }), ...(onPeek === undefined || choosing ? {} : { onPeek }), ...(onOpen === undefined || choosing ? {} : { onOpen }), ...(openTargets === undefined || onOpenIn === undefined || choosing
427
427
  ? {}
428
428
  : { openTargets, onOpenIn }), ...(choosing ? { onChoose } : {}), rowClick: rowClick })) : present === "sheet" && sheetSpec !== undefined ? (
429
429
  /* The sheet receives the set by INDEX and not an already built matrix: see `SheetPresentation`. */
@@ -15,14 +15,14 @@ type TableProps<T extends object> = {
15
15
  levels: NonNullable<Parameters<typeof DataTable<T>>[0]["levels"]>;
16
16
  group?: ListGroup<T>;
17
17
  totals: boolean;
18
- } & Pick<ListViewProps<T>, "sort" | "onSortChange" | "selection" | "rowActions" | "create" | "onPeek" | "onOpen" | "openTargets" | "onOpenIn"> & {
18
+ } & Pick<ListViewProps<T>, "sort" | "onSortChange" | "selection" | "rowActions" | "create" | "onReorder" | "onPeek" | "onOpen" | "openTargets" | "onOpenIn"> & {
19
19
  rowClick?: "peek" | "open";
20
20
  onChoose?: (item: T) => void;
21
21
  };
22
22
  /** The table receives EVERYTHING that belongs to the set —sorting, selection, grouping,
23
23
  * which columns are on screen— and not a trimmed down version: that was exactly the trap
24
24
  * this archetype exists to avoid, that switching presentation loses capabilities. */
25
- export declare function TablePresentation<T extends object>({ items, columns, keyOf, levels, group, totals, sort, onSortChange, selection, rowActions, create, onPeek, onOpen, openTargets, onOpenIn, rowClick, onChoose, }: TableProps<T>): import("react").JSX.Element;
25
+ export declare function TablePresentation<T extends object>({ items, columns, keyOf, levels, group, totals, sort, onSortChange, selection, rowActions, create, onReorder, onPeek, onOpen, openTargets, onOpenIn, rowClick, onChoose, }: TableProps<T>): import("react").JSX.Element;
26
26
  type SheetProps<T extends object> = {
27
27
  spec: ListSheet<T>;
28
28
  /** The flattened bands and rows when the set is grouped; `null` when it is not. */
@@ -15,7 +15,7 @@ const OPEN_ICON = {
15
15
  /** The table receives EVERYTHING that belongs to the set —sorting, selection, grouping,
16
16
  * which columns are on screen— and not a trimmed down version: that was exactly the trap
17
17
  * this archetype exists to avoid, that switching presentation loses capabilities. */
18
- export function TablePresentation({ items, columns, keyOf, levels, group, totals, sort, onSortChange, selection, rowActions, create, onPeek, onOpen, openTargets, onOpenIn, rowClick = "peek", onChoose, }) {
18
+ export function TablePresentation({ items, columns, keyOf, levels, group, totals, sort, onSortChange, selection, rowActions, create, onReorder, onPeek, onOpen, openTargets, onOpenIn, rowClick = "peek", onChoose, }) {
19
19
  const copy = useUiCopy();
20
20
  const press = onChoose ?? (rowClick === "open" ? (onOpen ?? onPeek) : (onPeek ?? onOpen));
21
21
  /* The row's ways in go FIRST among its actions, so they are always the inline ones and
@@ -86,7 +86,7 @@ export function TablePresentation({ items, columns, keyOf, levels, group, totals
86
86
  selection.toggle(id);
87
87
  }
88
88
  },
89
- }), ...(totals ? { totals: true } : {}), ...(withOpeners === undefined ? {} : { rowActions: withOpeners }), ...(create === undefined ? {} : { create }), ...(press === undefined ? {} : { onRowClick: press }) }));
89
+ }), ...(totals ? { totals: true } : {}), ...(withOpeners === undefined ? {} : { rowActions: withOpeners }), ...(create === undefined ? {} : { create }), ...(onReorder === undefined ? {} : { onReorder }), ...(press === undefined ? {} : { onRowClick: press }) }));
90
90
  }
91
91
  /** The sheet receives the set by INDEX and not a ready-made matrix: `SheetTable` is
92
92
  * virtualized precisely so as not to materialize a million rows, and handing it copies
@@ -380,6 +380,11 @@ export type ListViewProps<T extends object> = {
380
380
  * columns that declare `input` get a control in that row. See `DataTable`'s header.
381
381
  * While a record is being written the table shows even if the set is empty. */
382
382
  create?: DataTableCreate<T>;
383
+ /** The records are in an order a person sets by hand (a `sequence`): a grip at the start of
384
+ * each row of the table drags it, Alt + ↑ / ↓ moves it. `before` is the row it lands in
385
+ * front of, `null` the end. Off while grouped or sorted by a column, and in the phone's
386
+ * rows — see `DataTable`'s `onReorder`. */
387
+ onReorder?: (id: string, before: string | null) => void;
383
388
  /** The board presentation: the card of one record, with what a press on it does. */
384
389
  card?: (item: T, ways: CardWays) => ReactNode;
385
390
  /** The board by stages: one column each, cards moved between them. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-ui",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "An enterprise web design system for business software — ERPs, back offices, management tools — in React and Tailwind: tokens, primitives, components and the two views every management screen is made of.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",