@olenbetong/appframe-ds 1.4.1 → 1.6.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.
@@ -1,14 +1,22 @@
1
1
  import "./LookupGrid.css";
2
2
 
3
+ import { ArrowDownIcon, ArrowUpIcon } from "@navikt/aksel-icons";
3
4
  import type { LookupColumn } from "@olenbetong/appframe-react";
4
5
 
5
6
  import clsx from "clsx";
6
- import { useEffect, useMemo } from "react";
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
8
  import { List, type RowComponentProps, useListRef } from "react-window";
8
9
  import { getLocalizedString } from "../i18n.js";
9
10
 
10
11
  const ROW_HEIGHT = 40;
11
12
  const HEADER_HEIGHT = 40;
13
+ /** Narrowest a column can be made, and what a flexible column counts for in the minimum width */
14
+ const MIN_COLUMN_WIDTH = 80;
15
+
16
+ export type LookupGridSort = {
17
+ field: string;
18
+ direction: "asc" | "desc";
19
+ };
12
20
 
13
21
  export interface LookupGridProps<T extends Record<string, unknown>> {
14
22
  columns: LookupColumn<T>[];
@@ -19,18 +27,49 @@ export interface LookupGridProps<T extends Record<string, unknown>> {
19
27
  getItemId: (item: T | undefined) => string | undefined;
20
28
  isItemSelected?: (item: T) => boolean;
21
29
  onSelectItem: (item: T) => void;
30
+ /**
31
+ * The column the rows are sorted by, shown with an arrow in its header
32
+ */
33
+ sort?: LookupGridSort;
34
+ /**
35
+ * Called with the field of a header the user clicked. When left out the headers are plain text.
36
+ */
37
+ onSort?: (field: string) => void;
22
38
  }
23
39
 
24
- function getColumnWidth<T extends Record<string, unknown>>(column: LookupColumn<T>) {
40
+ /** The track for one column in `grid-template-columns`; a width the user dragged wins over the configured one */
41
+ function getColumnTrack<T extends Record<string, unknown>>(column: LookupColumn<T>, resizedWidth: number | undefined) {
42
+ if (resizedWidth !== undefined) {
43
+ return `${resizedWidth}px`;
44
+ }
25
45
  if (typeof column.width === "number") {
26
46
  return `${column.width}px`;
27
47
  }
28
48
 
29
- return column.width ?? "minmax(80px, 1fr)";
49
+ return column.width ?? `minmax(${MIN_COLUMN_WIDTH}px, 1fr)`;
50
+ }
51
+
52
+ /** What a column contributes to the narrowest width the grid can be laid out in */
53
+ function getColumnMinWidth<T extends Record<string, unknown>>(
54
+ column: LookupColumn<T>,
55
+ resizedWidth: number | undefined,
56
+ ) {
57
+ if (resizedWidth !== undefined) {
58
+ return resizedWidth;
59
+ }
60
+ if (typeof column.width === "number") {
61
+ return column.width;
62
+ }
63
+ if (typeof column.width === "string" && /^\d+(\.\d+)?px$/.test(column.width)) {
64
+ return Number.parseFloat(column.width);
65
+ }
66
+
67
+ return MIN_COLUMN_WIDTH;
30
68
  }
31
69
 
32
- type LookupGridRowProps<T extends Record<string, unknown>> = Omit<LookupGridProps<T>, "height"> & {
70
+ type LookupGridRowProps<T extends Record<string, unknown>> = Omit<LookupGridProps<T>, "height" | "sort" | "onSort"> & {
33
71
  gridTemplateColumns: string;
72
+ minWidth: number;
34
73
  };
35
74
 
36
75
  function LookupGridRow<T extends Record<string, unknown>>({
@@ -41,6 +80,7 @@ function LookupGridRow<T extends Record<string, unknown>>({
41
80
  currentIndex,
42
81
  currentColumn,
43
82
  gridTemplateColumns,
83
+ minWidth,
44
84
  getItemId,
45
85
  isItemSelected,
46
86
  onSelectItem,
@@ -54,7 +94,7 @@ function LookupGridRow<T extends Record<string, unknown>>({
54
94
  role="row"
55
95
  aria-selected={active}
56
96
  className={clsx("ObLookupGrid-row", active && "active", isItemSelected?.(item) && "selected")}
57
- style={{ ...style, gridTemplateColumns }}
97
+ style={{ ...style, gridTemplateColumns, minWidth }}
58
98
  onClick={() => onSelectItem(item)}
59
99
  id={itemId}
60
100
  >
@@ -65,13 +105,77 @@ function LookupGridRow<T extends Record<string, unknown>>({
65
105
  key={column.field}
66
106
  title={String(item[column.field] ?? "")}
67
107
  >
68
- {column.renderCell ? column.renderCell(item[column.field], item) : String(item[column.field] ?? "")}
108
+ {/* The cell is a flex container, so the ellipsis has to be on an element inside it */}
109
+ <span className="ObLookupGrid-cellText">
110
+ {column.renderCell ? column.renderCell(item[column.field], item) : String(item[column.field] ?? "")}
111
+ </span>
69
112
  </div>
70
113
  ))}
71
114
  </div>
72
115
  );
73
116
  }
74
117
 
118
+ type ColumnResizerProps = {
119
+ onResize: (delta: number) => void;
120
+ /** Called with the handle, whose parent is the header cell being resized */
121
+ onResizeStart: (handle: HTMLElement) => void;
122
+ onResizeEnd: () => void;
123
+ onReset: () => void;
124
+ };
125
+
126
+ /**
127
+ * The drag handle at the end of a header cell. Pointer capture keeps the drag alive when the
128
+ * pointer leaves the handle; a double click puts the column back to its configured width.
129
+ */
130
+ function ColumnResizer({ onResize, onResizeStart, onResizeEnd, onReset }: ColumnResizerProps) {
131
+ let startX = useRef(0);
132
+
133
+ return (
134
+ // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a drag handle; the grid is keyboard navigable by cell
135
+ <div
136
+ role="separator"
137
+ aria-orientation="vertical"
138
+ aria-label={getLocalizedString("Resize column")}
139
+ className="ObLookupGrid-resizer"
140
+ onClick={(event) => event.stopPropagation()}
141
+ onDoubleClick={(event) => {
142
+ event.stopPropagation();
143
+ onReset();
144
+ }}
145
+ onPointerDown={(event) => {
146
+ if (event.button !== 0) return;
147
+ event.preventDefault();
148
+ event.stopPropagation();
149
+ event.currentTarget.setPointerCapture(event.pointerId);
150
+ startX.current = event.clientX;
151
+ onResizeStart(event.currentTarget);
152
+ }}
153
+ onPointerMove={(event) => {
154
+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
155
+ onResize(event.clientX - startX.current);
156
+ }}
157
+ onPointerUp={(event) => {
158
+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
159
+ event.currentTarget.releasePointerCapture(event.pointerId);
160
+ onResizeEnd();
161
+ }}
162
+ onPointerCancel={onResizeEnd}
163
+ />
164
+ );
165
+ }
166
+
167
+ /**
168
+ * The grid variant of the lookup popup: a header row and a virtualised list of rows, laid out
169
+ * with the same `grid-template-columns`.
170
+ *
171
+ * Only the list scrolls. It scrolls both ways when the columns are wider than the popup, and
172
+ * the header follows it sideways with a transform, so the header never needs a scrollbar of
173
+ * its own. The list reserves its vertical scrollbar gutter, and the header row is given the
174
+ * list's inner width, so flexible (`1fr`) columns line up between the two.
175
+ *
176
+ * Columns can be resized by dragging the handle at the end of a header cell. The widths live
177
+ * in the grid, so they last for as long as the popup is open.
178
+ */
75
179
  export function LookupGrid<T extends Record<string, unknown>>({
76
180
  columns,
77
181
  data,
@@ -81,9 +185,23 @@ export function LookupGrid<T extends Record<string, unknown>>({
81
185
  getItemId,
82
186
  isItemSelected,
83
187
  onSelectItem,
188
+ sort,
189
+ onSort,
84
190
  }: LookupGridProps<T>) {
85
191
  let listRef = useListRef(null);
86
- let gridTemplateColumns = useMemo(() => columns.map(getColumnWidth).join(" "), [columns]);
192
+ let headerRowRef = useRef<HTMLDivElement>(null);
193
+ let [resizedWidths, setResizedWidths] = useState<Partial<Record<string, number>>>({});
194
+ let [resizing, setResizing] = useState<{ field: string; startWidth: number } | null>(null);
195
+ let [listInnerWidth, setListInnerWidth] = useState<number>();
196
+
197
+ let gridTemplateColumns = useMemo(
198
+ () => columns.map((column) => getColumnTrack(column, resizedWidths[column.field])).join(" "),
199
+ [columns, resizedWidths],
200
+ );
201
+ let minWidth = useMemo(
202
+ () => columns.reduce((sum, column) => sum + getColumnMinWidth(column, resizedWidths[column.field]), 0),
203
+ [columns, resizedWidths],
204
+ );
87
205
 
88
206
  useEffect(() => {
89
207
  if (currentIndex >= 0 && currentIndex < data.length) {
@@ -91,22 +209,103 @@ export function LookupGrid<T extends Record<string, unknown>>({
91
209
  }
92
210
  }, [currentIndex, data.length, listRef]);
93
211
 
212
+ // The header row is as wide as the list's inner (client) width, so 1fr columns match the rows
213
+ useEffect(() => {
214
+ let element = listRef.current?.element;
215
+ if (!element) return;
216
+
217
+ let measure = () => setListInnerWidth(element.clientWidth);
218
+ measure();
219
+
220
+ let observer = new ResizeObserver(measure);
221
+ observer.observe(element);
222
+
223
+ return () => observer.disconnect();
224
+ }, [listRef, height]);
225
+
226
+ let handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
227
+ if (headerRowRef.current) {
228
+ headerRowRef.current.style.transform = `translateX(${-event.currentTarget.scrollLeft}px)`;
229
+ }
230
+ }, []);
231
+
232
+ function startResize(field: string, cell: HTMLElement) {
233
+ setResizing({ field, startWidth: cell.getBoundingClientRect().width });
234
+ }
235
+
236
+ function resizeBy(delta: number) {
237
+ if (!resizing) return;
238
+ let { field, startWidth } = resizing;
239
+ let width = Math.max(MIN_COLUMN_WIDTH, Math.round(startWidth + delta));
240
+ setResizedWidths((widths) => (widths[field] === width ? widths : { ...widths, [field]: width }));
241
+ }
242
+
243
+ function resetWidth(field: string) {
244
+ setResizedWidths(({ [field]: _removed, ...rest }) => rest);
245
+ }
246
+
94
247
  return (
95
- <div role="grid" aria-label={getLocalizedString("Search results")} className="ObLookupGrid-root">
96
- <div role="row" className="ObLookupGrid-header" style={{ gridTemplateColumns }}>
97
- {columns.map((column) => (
98
- <div role="columnheader" className="ObLookupGrid-headerCell" key={column.field}>
99
- {column.headerName ?? column.field}
100
- </div>
101
- ))}
248
+ <div
249
+ role="grid"
250
+ aria-label={getLocalizedString("Search results")}
251
+ className="ObLookupGrid-root"
252
+ data-resizing={resizing ? "" : undefined}
253
+ >
254
+ <div className="ObLookupGrid-header">
255
+ <div
256
+ role="row"
257
+ ref={headerRowRef}
258
+ className="ObLookupGrid-headerRow"
259
+ style={{ gridTemplateColumns, minWidth, width: listInnerWidth }}
260
+ >
261
+ {columns.map((column) => {
262
+ let sortable = !!onSort && column.sortable !== false;
263
+ let sorted = sort?.field === column.field ? sort.direction : undefined;
264
+ let label = column.headerName ?? column.field;
265
+ let SortIcon = sorted === "desc" ? ArrowDownIcon : ArrowUpIcon;
266
+
267
+ return (
268
+ <div
269
+ role="columnheader"
270
+ className="ObLookupGrid-headerCell"
271
+ key={column.field}
272
+ aria-sort={sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : undefined}
273
+ >
274
+ {sortable ? (
275
+ <button
276
+ type="button"
277
+ className={clsx("ObLookupGrid-sortButton", sorted && "sorted")}
278
+ // Keeps the focus in the search field, so typing carries on after a click
279
+ onMouseDown={(event) => event.preventDefault()}
280
+ onClick={() => onSort?.(column.field)}
281
+ tabIndex={-1}
282
+ >
283
+ <span className="ObLookupGrid-headerText">{label}</span>
284
+ <SortIcon className="ObLookupGrid-sortIcon" aria-hidden />
285
+ </button>
286
+ ) : (
287
+ <span className="ObLookupGrid-headerText">{label}</span>
288
+ )}
289
+ <ColumnResizer
290
+ onResizeStart={(handle) => startResize(column.field, handle.parentElement as HTMLElement)}
291
+ onResize={resizeBy}
292
+ onResizeEnd={() => setResizing(null)}
293
+ onReset={() => resetWidth(column.field)}
294
+ />
295
+ </div>
296
+ );
297
+ })}
298
+ </div>
102
299
  </div>
103
300
  <List<LookupGridRowProps<T>>
104
301
  role="rowgroup"
105
302
  listRef={listRef}
303
+ className="ObLookupGrid-list"
106
304
  style={{ height: Math.max(0, height - HEADER_HEIGHT) }}
107
305
  rowCount={data.length}
108
306
  rowHeight={ROW_HEIGHT}
109
307
  overscanCount={5}
308
+ onScroll={handleScroll}
110
309
  rowComponent={LookupGridRow}
111
310
  rowProps={{
112
311
  columns,
@@ -114,6 +313,7 @@ export function LookupGrid<T extends Record<string, unknown>>({
114
313
  currentIndex,
115
314
  currentColumn,
116
315
  gridTemplateColumns,
316
+ minWidth,
117
317
  getItemId,
118
318
  isItemSelected,
119
319
  onSelectItem,
@@ -27,12 +27,9 @@
27
27
  * Font size is deliberately never set: `ds-input` inherits its font size when a
28
28
  * `data-size` attribute is present, so referencing `--ds-font-size-*` here — which
29
29
  * `data-size` rescales — would render the text smaller than a `Textfield` or
30
- * `Select` of the same size. Only the padding varies per size.
30
+ * `Select` of the same size. Only the padding varies per size, and only for the
31
+ * sizes Designsystemet components come in (sm, md, lg; xs and xl are typography-only).
31
32
  */
32
- .ObAutocomplete-root[data-size="xs"] {
33
- --obAutocomplete-padding: 0.125rem;
34
- }
35
-
36
33
  .ObAutocomplete-root[data-size="sm"] {
37
34
  --obAutocomplete-padding: 0.25rem;
38
35
  }
@@ -0,0 +1,42 @@
1
+ import { useField } from "@olenbetong/appframe-react";
2
+
3
+ import { NumberInput, type NumberInputProps } from "../input/NumberInput.js";
4
+
5
+ export type BoundNumberInputProps = Omit<NumberInputProps, "value" | "onChange" | "onKeyDown"> & {
6
+ /**
7
+ * Name of the number field in the data object from context
8
+ */
9
+ field: string;
10
+ /**
11
+ * Called with the new value before it is written to the data object
12
+ */
13
+ onChange?: (value: number | null) => void;
14
+ };
15
+
16
+ /**
17
+ * A `NumberInput` bound to a number field of the data object from `DataObjectProvider`
18
+ * via `useField`. Escape resets the field, and a conversion error from the data object is
19
+ * shown below the input unless an `error` is passed.
20
+ *
21
+ * @example
22
+ * ```jsx
23
+ * <BoundNumberInput field="TotHrs" label="Total hours" step={0.25} min={0} max={24} />
24
+ * ```
25
+ */
26
+ export function BoundNumberInput({ field, onChange: onChangeProp, error: errorProp, ...props }: BoundNumberInputProps) {
27
+ let { error, value, onChange, onKeyDown } = useField<any, any>(field);
28
+
29
+ return (
30
+ <NumberInput
31
+ name={field}
32
+ {...props}
33
+ error={errorProp ?? error ?? undefined}
34
+ value={typeof value === "number" ? value : null}
35
+ onChange={(next) => {
36
+ onChangeProp?.(next);
37
+ onChange({ target: { value: next } });
38
+ }}
39
+ onKeyDown={(event) => onKeyDown(event)}
40
+ />
41
+ );
42
+ }
@@ -2,6 +2,7 @@ export * from "./BoundCheckbox.js";
2
2
  export * from "./BoundDatePicker.js";
3
3
  export * from "./BoundDateTimePicker.js";
4
4
  export * from "./BoundInput.js";
5
+ export * from "./BoundNumberInput.js";
5
6
  export * from "./BoundNumericTextField.js";
6
7
  export * from "./BoundSelect.js";
7
8
  export * from "./BoundSwitch.js";
@@ -10,6 +10,7 @@ import {
10
10
  type GridApi,
11
11
  type GridFilterModel,
12
12
  type GridGroupNode,
13
+ type GridRowParams,
13
14
  useGridApiRef,
14
15
  } from "@mui/x-data-grid-premium";
15
16
  import { type DataObject, uid } from "@olenbetong/appframe-data";
@@ -41,7 +42,7 @@ import {
41
42
  GridToolbarResetLayoutButton,
42
43
  } from "./Toolbar.js";
43
44
  import type { AfGridColumn } from "./useAfColumns.js";
44
- import { type AfGridColDef, useAfColumns } from "./useAfColumns.js";
45
+ import { type AfGridColDef, type AfGridRowAction, useAfColumns } from "./useAfColumns.js";
45
46
  import { useAfCurrentIndex } from "./useAfCurrentIndex.js";
46
47
  import { useAfData } from "./useAfData.js";
47
48
  import { useAfFilterFields } from "./useAfFilterFields.js";
@@ -56,6 +57,7 @@ import {
56
57
  settingsLoaded,
57
58
  useAfPersistedState,
58
59
  } from "./useAfPersistedState.js";
60
+ import { useAfKeepFocusAfterEdit } from "./useAfKeepFocusAfterEdit.js";
59
61
  import { useAfRowEditModel } from "./useAfRowEditModel.js";
60
62
  import { useAfRowGrouping } from "./useAfRowGrouping.js";
61
63
  import { useAfServerAggregation } from "./useAfServerAggregation.js";
@@ -103,6 +105,7 @@ export type {
103
105
  AfGridColumn,
104
106
  AfGridExcelExportOptions,
105
107
  AfGridNewItemRowPosition,
108
+ AfGridRowAction,
106
109
  };
107
110
  export type { AfGridGrouping, AfGridGroupingProps } from "./useAfRowGrouping.js";
108
111
 
@@ -156,6 +159,14 @@ export type AfGridProps = {
156
159
  bindIndex?: boolean;
157
160
  columns: AfGridColumn[];
158
161
  dataObject: DataObject<any>;
162
+ /**
163
+ * Extra buttons for each row in the grid's own actions column, after edit and delete. They
164
+ * show while the row is not being edited, and the column is added for them even when the data
165
+ * object allows neither updates nor deletes. An actions column of your own replaces that
166
+ * column, built-in actions included, and loses their keyboard navigation; use this instead.
167
+ * Keep the function stable (`useCallback`): a new one rebuilds the columns.
168
+ */
169
+ getRowActions?: (params: GridRowParams) => AfGridRowAction[];
159
170
  /**
160
171
  * The layout version of the grid. Persisted grid state will only be restored
161
172
  * if the version matches.
@@ -282,6 +293,7 @@ function AfGrid_(props: AfGridProps) {
282
293
  apiRef: apiRefProp,
283
294
  bindIndex,
284
295
  columns: columnsProp,
296
+ getRowActions,
285
297
  disableServerSorting,
286
298
  disableInsert,
287
299
  disableDelete,
@@ -336,6 +348,7 @@ function AfGrid_(props: AfGridProps) {
336
348
  let [isFilterBuilderOpen, setFilterBuilderOpen] = useState(false);
337
349
  let [isColumnsPanelOpen, setColumnsPanelOpen] = useState(false);
338
350
  let editProps = useAfRowEditModel({ dataObject, disableEdit, idField, apiRef, newItemRow });
351
+ useAfKeepFocusAfterEdit(apiRef);
339
352
  let data = useAfData(dataObject, { getData });
340
353
  useAfCurrentIndex({
341
354
  apiRef,
@@ -351,6 +364,7 @@ function AfGrid_(props: AfGridProps) {
351
364
  disableDelete,
352
365
  columnsProp,
353
366
  idField,
367
+ getRowActions,
354
368
  });
355
369
  let filterFields = useAfFilterFields(dataObject, columnsProp);
356
370
 
@@ -100,8 +100,15 @@ function BaseButton(props: GridSlotProps["baseButton"]) {
100
100
  function BaseIconButton(props: GridSlotProps["baseIconButton"]) {
101
101
  let { children, size, label, color: _color, edge: _edge, touchRippleRef: _touchRippleRef, ...other } = props;
102
102
 
103
+ // `GridActionsCellItem` names its button through `aria-label`, not `label`; keep it
103
104
  return (
104
- <Button {...(other as any)} icon variant="tertiary" data-size={dsSize(size)} aria-label={label}>
105
+ <Button
106
+ {...(other as any)}
107
+ icon
108
+ variant="tertiary"
109
+ data-size={dsSize(size)}
110
+ aria-label={label ?? (other as any)["aria-label"]}
111
+ >
105
112
  {children}
106
113
  </Button>
107
114
  );
@@ -4,6 +4,21 @@ import { afterEach, describe, expect, it, vi } from "vitest";
4
4
  import { dsBaseSlots } from "./index.js";
5
5
 
6
6
  const BaseSkeleton = dsBaseSlots.baseSkeleton as React.ComponentType<Record<string, unknown>>;
7
+ const BaseIconButton = dsBaseSlots.baseIconButton as React.ComponentType<Record<string, unknown>>;
8
+
9
+ describe("baseIconButton", () => {
10
+ it("keeps the aria-label GridActionsCellItem names its button with", () => {
11
+ let { getByRole } = render(<BaseIconButton aria-label="Edit">x</BaseIconButton>);
12
+
13
+ expect(getByRole("button")).toHaveAttribute("aria-label", "Edit");
14
+ });
15
+
16
+ it("prefers the label prop", () => {
17
+ let { getByRole } = render(<BaseIconButton label="Save">x</BaseIconButton>);
18
+
19
+ expect(getByRole("button")).toHaveAttribute("aria-label", "Save");
20
+ });
21
+ });
7
22
 
8
23
  describe("baseSkeleton", () => {
9
24
  afterEach(() => {
@@ -15,6 +15,7 @@ import {
15
15
  type GridRowParams,
16
16
  getAggregationFooterRowIdFromGroupId,
17
17
  gridEditRowsStateSelector,
18
+ gridVisibleColumnDefinitionsSelector,
18
19
  useGridApiContext,
19
20
  useGridSelector,
20
21
  } from "@mui/x-data-grid-premium";
@@ -244,6 +245,21 @@ const GridActionItem = React.forwardRef<
244
245
  });
245
246
 
246
247
  export type AfGridColumn = string | AfGridColDef;
248
+
249
+ /**
250
+ * An extra button in the grid's actions column, next to edit and delete. Shown only while the row
251
+ * is not being edited, and reached with the arrow keys like the built-in actions.
252
+ */
253
+ export type AfGridRowAction = {
254
+ key: string;
255
+ icon: React.ReactElement;
256
+ /** The button's accessible name and tooltip, and its text in the overflow menu. */
257
+ label: string;
258
+ onClick: () => void;
259
+ disabled?: boolean;
260
+ /** Puts the action in the column's overflow menu instead of showing it as a button. */
261
+ showInMenu?: boolean;
262
+ };
247
263
  const muiColumnTypes = ["string", "number", "date", "dateTime", "boolean", "singleSelect", "actions"];
248
264
 
249
265
  export type useAfColumnsOptions = {
@@ -253,6 +269,7 @@ export type useAfColumnsOptions = {
253
269
  dataObject: DataObject<any>;
254
270
  columnsProp: AfGridColumn[];
255
271
  idField: string;
272
+ getRowActions?: (params: GridRowParams) => AfGridRowAction[];
256
273
  };
257
274
 
258
275
  export function useAfColumns({
@@ -262,6 +279,7 @@ export function useAfColumns({
262
279
  disableDelete,
263
280
  columnsProp,
264
281
  idField,
282
+ getRowActions,
265
283
  }: useAfColumnsOptions): GridColDef[] {
266
284
  let { allowUpdate, allowDelete } = usePermissions(dataObject);
267
285
 
@@ -277,13 +295,26 @@ export function useAfColumns({
277
295
  idField,
278
296
  });
279
297
 
298
+ // The edit, save and cancel buttons disappear as the row changes mode, taking the focus with
299
+ // them. Editing starts in the first editable column, and leaving edit mode puts the grid's
300
+ // focus on the row's actions cell, which `useAfKeepFocusAfterEdit` then restores.
280
301
  const handleEditClick = (id: GridRowId) => (event: React.MouseEvent<any>) => {
281
302
  event.stopPropagation();
282
- apiRef.current?.startRowEditMode({ id });
303
+ let api = apiRef.current;
304
+ if (!api) return;
305
+
306
+ let fieldToFocus = gridVisibleColumnDefinitionsSelector(apiRef).find(
307
+ (column) => column.editable && column.type !== "actions",
308
+ )?.field;
309
+ if (fieldToFocus) {
310
+ api.setCellFocus(id, fieldToFocus);
311
+ }
312
+ api.startRowEditMode({ id, fieldToFocus });
283
313
  };
284
314
 
285
315
  const handleSaveClick = (id: GridRowId) => async (event: React.MouseEvent<any>) => {
286
316
  event.stopPropagation();
317
+ apiRef.current?.setCellFocus(id, "actions");
287
318
  apiRef.current?.stopRowEditMode({ id });
288
319
  };
289
320
 
@@ -294,6 +325,7 @@ export function useAfColumns({
294
325
 
295
326
  const handleCancelClick = (id: GridRowId) => (event: React.MouseEvent<any>) => {
296
327
  event.stopPropagation();
328
+ apiRef.current?.setCellFocus(id, "actions");
297
329
  apiRef.current?.stopRowEditMode({ id, ignoreModifications: true });
298
330
 
299
331
  const row = apiRef.current?.getRow(id);
@@ -302,12 +334,13 @@ export function useAfColumns({
302
334
  }
303
335
  };
304
336
 
305
- if (!columns.find((c) => c.type === "actions") && (allowDelete || allowUpdate)) {
337
+ if (!columns.find((c) => c.type === "actions") && (allowDelete || allowUpdate || getRowActions)) {
306
338
  columns.push({
307
339
  field: "actions",
308
340
  type: "actions",
309
341
  headerName: getLocalizedString("Actions"),
310
- getActions: ({ id }: GridRowParams) => {
342
+ getActions: (params: GridRowParams) => {
343
+ let { id } = params;
311
344
  // The new item row only exists while inserting is allowed, so its save and
312
345
  // cancel actions do not depend on the update permission, and it has nothing
313
346
  // to edit or delete in view mode.
@@ -339,6 +372,33 @@ export function useAfColumns({
339
372
  return actions;
340
373
  }
341
374
 
375
+ let rowActions = (getRowActions?.(params) ?? []).map(({ key, icon, label, onClick, disabled, showInMenu }) =>
376
+ showInMenu ? (
377
+ <GridActionItem
378
+ key={key}
379
+ icon={icon}
380
+ label={label}
381
+ onClick={onClick}
382
+ disabled={disabled}
383
+ showInMenu
384
+ mode={GridRowModes.View}
385
+ dataObject={dataObject}
386
+ rowId={id}
387
+ />
388
+ ) : (
389
+ <GridActionItem
390
+ key={key}
391
+ icon={icon}
392
+ label={label}
393
+ onClick={onClick}
394
+ disabled={disabled}
395
+ mode={GridRowModes.View}
396
+ dataObject={dataObject}
397
+ rowId={id}
398
+ />
399
+ ),
400
+ );
401
+
342
402
  return [
343
403
  <GridActionItem
344
404
  key="edit"
@@ -360,6 +420,7 @@ export function useAfColumns({
360
420
  rowId={id}
361
421
  requireDelete
362
422
  />,
423
+ ...rowActions,
363
424
  ...actions,
364
425
  ];
365
426
  },
@@ -367,5 +428,5 @@ export function useAfColumns({
367
428
  }
368
429
 
369
430
  return columns;
370
- }, [columnsProp, disableDelete, disableEdit, allowUpdate, allowDelete, idField, dataObject, apiRef]);
431
+ }, [columnsProp, disableDelete, disableEdit, allowUpdate, allowDelete, idField, dataObject, apiRef, getRowActions]);
371
432
  }