@olenbetong/appframe-ds 1.4.0 → 1.5.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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @olenbetong/appframe-ds
2
2
 
3
+ ## 1.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1cae272: AfGrid takes `getRowActions`: extra buttons for each row in the grid's own actions column, after edit and delete, with the same keyboard navigation. An actions column of the app's own replaced the built-in one.
8
+
9
+ ### Patch Changes
10
+
11
+ - 1cae272: AfGrid's row action buttons (edit, delete, save, cancel and any from `getRowActions`) have their labels as accessible names again; the icon button slot overwrote them with nothing. Starting edit with the edit button now focuses the first editable cell, and save and cancel leave the focus on the row's actions cell instead of the page.
12
+ - 1cae272: AfGrid keeps the keyboard focus on the cell when a row or cell leaves edit mode. Chrome dropped it to the page after Escape (or saving), so the arrow keys scrolled the page instead of moving between cells.
13
+
14
+ ## 1.4.1
15
+
16
+ ### Patch Changes
17
+
18
+ - b0630e5: Dialog motion: the opening transition now also plays for `ob-dialog-motion` elements (the app menu). Their starting style was a separate, less specific rule than the open state and lost to it, so they appeared without the transition and only faded on close.
19
+
3
20
  ## 1.4.0
4
21
 
5
22
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olenbetong/appframe-ds",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Components that bind Designsystemet components to Appframe data objects",
5
5
  "type": "module",
6
6
  "types": "./es/index.d.ts",
@@ -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
  }
@@ -0,0 +1,64 @@
1
+ import { type GridApi, gridFocusCellSelector } from "@mui/x-data-grid-premium";
2
+
3
+ import type React from "react";
4
+ import { useEffect } from "react";
5
+
6
+ /** How long after a row or cell changes mode a focus loss is still blamed on it. */
7
+ const EDIT_STOP_WINDOW_MS = 1000;
8
+
9
+ /**
10
+ * Keeps the keyboard focus in the grid when a row or cell enters or leaves edit mode.
11
+ *
12
+ * Two things drop the focus to `<body>`, after which the arrow keys scroll the page instead of
13
+ * moving between cells: when editing stops (Escape, Enter), the grid moves the focus from the
14
+ * editor back to the cell and Chrome then takes it from that cell with no script involved; and the
15
+ * edit, save and cancel buttons are removed while they have the focus. This puts the focus back on
16
+ * the cell the grid's own focus state points at - but only right after a mode change, and only
17
+ * when the focus was lost from that cell, so a click outside the grid (which clears that state)
18
+ * keeps the focus where it went.
19
+ */
20
+ export function useAfKeepFocusAfterEdit(apiRef: React.RefObject<GridApi | null>) {
21
+ useEffect(() => {
22
+ let api = apiRef.current;
23
+ let root = api?.rootElementRef?.current;
24
+ if (!api || !root) return;
25
+
26
+ let lastModeChange = 0;
27
+ let markModeChange = () => {
28
+ lastModeChange = Date.now();
29
+ };
30
+
31
+ let handleFocusOut = (event: FocusEvent) => {
32
+ if (event.relatedTarget || Date.now() - lastModeChange > EDIT_STOP_WINDOW_MS) return;
33
+ let lostFrom = (event.target as HTMLElement).closest?.<HTMLElement>(".MuiDataGrid-row");
34
+ if (!lostFrom) return;
35
+
36
+ setTimeout(() => {
37
+ let doc = root.ownerDocument;
38
+ if (doc.activeElement !== doc.body) return;
39
+
40
+ // The focus state may have moved on to another cell of the same row (the save and
41
+ // cancel buttons move it to the actions cell), so restore whatever it points at.
42
+ let focused = gridFocusCellSelector(apiRef);
43
+ if (!focused || String(focused.id) !== lostFrom.dataset.id) return;
44
+
45
+ let cell = apiRef.current?.getCellElement(focused.id, focused.field);
46
+ if (!cell) return;
47
+
48
+ let target = cell.querySelector<HTMLElement>('[tabindex="0"]') ?? cell;
49
+ target.focus({ preventScroll: true });
50
+ }, 0);
51
+ };
52
+
53
+ let unsubscribers = [
54
+ api.subscribeEvent("rowModesModelChange", markModeChange),
55
+ api.subscribeEvent("cellModesModelChange", markModeChange),
56
+ ];
57
+ root.addEventListener("focusout", handleFocusOut);
58
+
59
+ return () => {
60
+ for (let unsubscribe of unsubscribers) unsubscribe();
61
+ root.removeEventListener("focusout", handleFocusOut);
62
+ };
63
+ }, [apiRef]);
64
+ }
@@ -45,6 +45,17 @@
45
45
  animation: none;
46
46
  transition-duration: var(--ob-dialog-enter-duration);
47
47
  transition-timing-function: ease-out;
48
+
49
+ /*
50
+ * Nested so it has exactly this rule's selector. A separate @starting-style rule for
51
+ * `.ob-dialog-motion[open]` is less specific than this one, whose `:is()` takes the
52
+ * specificity of `.ds-dialog:is(...)`, and loses to it: the dialog then has no
53
+ * starting frame and appears without the transition.
54
+ */
55
+ @starting-style {
56
+ opacity: 0;
57
+ translate: 0 var(--ob-dialog-offset);
58
+ }
48
59
  }
49
60
 
50
61
  &::backdrop {
@@ -60,18 +71,9 @@
60
71
  opacity: 1;
61
72
  transition-duration: var(--ob-dialog-enter-duration);
62
73
  transition-timing-function: ease-out;
63
- }
64
- }
65
74
 
66
- @starting-style {
67
- .ds-dialog:is(:not([data-placement]), [data-placement="center"])[open],
68
- .ob-dialog-motion[open] {
69
- opacity: 0;
70
- translate: 0 var(--ob-dialog-offset);
71
- }
72
-
73
- .ds-dialog:is(:not([data-placement]), [data-placement="center"])[open]::backdrop,
74
- .ob-dialog-motion[open]::backdrop {
75
- opacity: 0;
75
+ @starting-style {
76
+ opacity: 0;
77
+ }
76
78
  }
77
79
  }