@olenbetong/appframe-ds 0.9.0 → 1.0.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/package.json +22 -17
  3. package/scripts/copyAssets.mjs +3 -0
  4. package/src/autocomplete/Autocomplete.css +13 -0
  5. package/src/autocomplete/Autocomplete.tsx +3 -1
  6. package/src/autocomplete/Combobox.tsx +16 -3
  7. package/src/binding/BoundTextField.tsx +9 -1
  8. package/src/filter/FieldFilterPanel.css +25 -2
  9. package/src/grid/AfGridColumnsPanel.tsx +1 -1
  10. package/src/grid/AfGridContext.tsx +1 -1
  11. package/src/grid/AfGridError.tsx +1 -1
  12. package/src/grid/AfHeaderFilterCell.tsx +1 -1
  13. package/src/grid/Toolbar.tsx +1 -1
  14. package/src/grid/editing.ts +17 -7
  15. package/src/grid/filter.ts +1 -1
  16. package/src/grid/index.css +59 -1
  17. package/src/grid/index.tsx +126 -18
  18. package/src/grid/localization.ts +1 -1
  19. package/src/grid/slots/index.tsx +27 -2
  20. package/src/grid/theme.tsx +3 -50
  21. package/src/grid/useAfColumns.tsx +103 -45
  22. package/src/grid/useAfCurrentIndex.ts +13 -5
  23. package/src/grid/useAfGridApi.ts +6 -1
  24. package/src/grid/useAfKeyBindings.ts +1 -1
  25. package/src/grid/useAfNewItemRow.ts +258 -0
  26. package/src/grid/useAfPagination.ts +2 -2
  27. package/src/grid/useAfPersistedState.ts +9 -1
  28. package/src/grid/useAfRowEditModel.ts +20 -12
  29. package/src/grid/useAfRowGrouping.ts +47 -0
  30. package/src/grid/useAfServerAggregation.ts +145 -0
  31. package/src/grid/useAfSortModel.ts +15 -3
  32. package/src/layout/AppMenuDrawer.css +70 -0
  33. package/src/layout/AppMenuDrawer.tsx +122 -0
  34. package/src/layout/index.tsx +1 -0
  35. package/src/mdi/Mdi.css +138 -0
  36. package/src/mdi/Mdi.test.tsx +87 -0
  37. package/src/mdi/Mdi.tsx +141 -0
  38. package/src/mdi/MdiConfirmCloseDialog.tsx +47 -0
  39. package/src/mdi/MdiContext.tsx +59 -0
  40. package/src/mdi/MdiDocumentContext.tsx +60 -0
  41. package/src/mdi/MdiPanel.tsx +61 -0
  42. package/src/mdi/MdiRestore.test.tsx +82 -0
  43. package/src/mdi/MdiTab.tsx +30 -0
  44. package/src/mdi/controller.test.ts +382 -0
  45. package/src/mdi/controller.ts +656 -0
  46. package/src/mdi/dockviewHost.ts +132 -0
  47. package/src/mdi/fakeHost.ts +200 -0
  48. package/src/mdi/host.ts +44 -0
  49. package/src/mdi/ids.test.ts +20 -0
  50. package/src/mdi/ids.ts +18 -0
  51. package/src/mdi/index.ts +31 -0
  52. package/src/mdi/layoutRestore.test.ts +156 -0
  53. package/src/mdi/layoutRestore.ts +311 -0
  54. package/src/mdi/layoutSpec.test.ts +143 -0
  55. package/src/mdi/layoutSpec.ts +214 -0
  56. package/src/mdi/layoutStore.test.ts +93 -0
  57. package/src/mdi/layoutStore.ts +99 -0
  58. package/src/mdi/memorySettingsStore.ts +21 -0
  59. package/src/mdi/registry.ts +34 -0
  60. package/src/mdi/testTypes.ts +37 -0
  61. package/src/mdi/theme.ts +22 -0
  62. package/src/mdi/types.ts +214 -0
  63. package/src/page/Page.css +10 -2
  64. package/src/page/PageBlock.css +5 -0
  65. package/src/page/PageBlock.tsx +14 -0
  66. package/src/page/PageHeader.css +0 -60
  67. package/src/page/PageHeader.tsx +6 -74
  68. package/src/test/happy-dom-document-class.ts +24 -0
  69. package/src/test/setup.ts +4 -0
  70. package/src/theme/useDsColorScheme.ts +53 -0
@@ -0,0 +1,258 @@
1
+ import {
2
+ type DataGridPremiumProps as DataGridProps,
3
+ type GridApi,
4
+ type GridEventListener,
5
+ type GridPinnedRowsProp,
6
+ type GridRowId,
7
+ GridRowModes,
8
+ gridFocusCellSelector,
9
+ gridVisibleColumnDefinitionsSelector,
10
+ } from "@mui/x-data-grid-premium";
11
+ import { getLocalizedString } from "@olenbetong/appframe-core";
12
+ import { type DataObject, uid } from "@olenbetong/appframe-data";
13
+ import { setDataObjectField, usePermissions } from "@olenbetong/appframe-react";
14
+
15
+ import type React from "react";
16
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
17
+
18
+ import type { AfGridApi } from "./useAfGridApi.js";
19
+
20
+ /**
21
+ * Row id of the new item row. It never collides with a data row, whose id is
22
+ * either the data object's uid or the value of the id field.
23
+ */
24
+ export const NEW_ITEM_ROW_ID = "AfGrid-newItemRow";
25
+
26
+ export const NEW_ITEM_ROW_CLASS = "AfGrid-newItemRow";
27
+
28
+ /**
29
+ * Where the new item row is shown. `none` turns it off, and the Add button falls
30
+ * back to appending an unsaved row to the data.
31
+ */
32
+ export type AfGridNewItemRowPosition = "top" | "bottom" | "none";
33
+
34
+ export function isNewItemRow(id: GridRowId | null | undefined): boolean {
35
+ return id === NEW_ITEM_ROW_ID;
36
+ }
37
+
38
+ export type useAfNewItemRowOptions = {
39
+ apiRef: React.RefObject<GridApi | null>;
40
+ dataObject: DataObject<any>;
41
+ position: AfGridNewItemRowPosition;
42
+ disableInsert?: boolean;
43
+ pinnedRows?: GridPinnedRowsProp;
44
+ getRowClassName?: DataGridProps["getRowClassName"];
45
+ };
46
+
47
+ export type AfNewItemRow = {
48
+ /** True when the row is rendered, i.e. inserting is allowed and it is not turned off */
49
+ enabled: boolean;
50
+ /**
51
+ * Saves the values the user entered in the new item row as a new record at
52
+ * index -1 on the data object. Returns the blank row the grid should show
53
+ * in the new item row afterwards. Throws if the save fails, so the grid keeps
54
+ * the row in edit mode with the entered values.
55
+ */
56
+ save: (record: Record<string, unknown>) => Promise<Record<string, unknown>>;
57
+ /** Focuses the new item row and starts editing it. Returns false when the row is not rendered. */
58
+ start: () => boolean;
59
+ /** Props to spread onto the grid */
60
+ gridProps: Pick<DataGridProps, "pinnedRows" | "getRowClassName">;
61
+ /** Style for the grid root, carrying the overlay text as a CSS custom property */
62
+ rootStyle: React.CSSProperties;
63
+ };
64
+
65
+ /**
66
+ * A DevExpress-style new item row: a single non-data row pinned above or below
67
+ * the data, showing an overlay text until the user starts editing it. The row
68
+ * lives outside the data set, so sorting, filtering, paging and grouping leave
69
+ * it alone.
70
+ *
71
+ * When editing starts the data object's current index moves to -1, the
72
+ * framework's new record, so bound forms and child data objects follow. The
73
+ * entered values are only written to the data object when the row is
74
+ * committed, exactly like edits to existing rows.
75
+ */
76
+ export function useAfNewItemRow({
77
+ apiRef,
78
+ dataObject,
79
+ position,
80
+ disableInsert,
81
+ pinnedRows: pinnedRowsProp,
82
+ getRowClassName: getRowClassNameProp,
83
+ }: useAfNewItemRowOptions): AfNewItemRow {
84
+ let { allowInsert } = usePermissions(dataObject);
85
+ let enabled = position !== "none" && allowInsert && !disableInsert;
86
+ // Bumped after a save, so the pinned row is replaced by a blank one
87
+ let [generation, setGeneration] = useState(0);
88
+ // The row that was current before editing started, restored when the edit is cancelled
89
+ let previousIndex = useRef(-1);
90
+ let wasEditing = useRef(false);
91
+
92
+ let row = useMemo(() => {
93
+ if (!enabled) return null;
94
+ // `getData(-1)` is a blank record with every field set to null
95
+ return { ...(dataObject.getData(-1) as Record<string, unknown>), [uid]: NEW_ITEM_ROW_ID, generation };
96
+ }, [enabled, dataObject, generation]);
97
+
98
+ let beginNewRecord = useCallback(() => {
99
+ if (dataObject.getCurrentIndex() !== -1) {
100
+ previousIndex.current = dataObject.getCurrentIndex();
101
+ dataObject.setCurrentIndex(-1);
102
+ }
103
+ }, [dataObject]);
104
+
105
+ let cancelNewRecord = useCallback(() => {
106
+ if (dataObject.getCurrentIndex() !== -1) return;
107
+
108
+ dataObject.cancelEdit();
109
+
110
+ let index = previousIndex.current;
111
+ if (index >= 0 && index < dataObject.getDataLength()) {
112
+ dataObject.setCurrentIndex(index);
113
+ }
114
+ }, [dataObject]);
115
+
116
+ let start = useCallback(() => {
117
+ let api = apiRef.current;
118
+ if (!enabled || !api) return false;
119
+
120
+ let visibleColumns = gridVisibleColumnDefinitionsSelector(apiRef);
121
+ let firstEditable = visibleColumns.find((c) => c.editable === true) ?? visibleColumns[0];
122
+ if (!firstEditable) return false;
123
+
124
+ api.setCellFocus(NEW_ITEM_ROW_ID, firstEditable.field);
125
+ if (api.getRowMode(NEW_ITEM_ROW_ID) !== GridRowModes.Edit) {
126
+ api.startRowEditMode({ id: NEW_ITEM_ROW_ID, fieldToFocus: firstEditable.field });
127
+ }
128
+
129
+ return true;
130
+ }, [apiRef, enabled]);
131
+
132
+ let save = useCallback(
133
+ async (record: Record<string, unknown>) => {
134
+ beginNewRecord();
135
+
136
+ for (let field in record) {
137
+ let value = record[field];
138
+ if (value === undefined || value === null) continue;
139
+ if (dataObject.getFields(field)) {
140
+ setDataObjectField(dataObject, field, value);
141
+ }
142
+ }
143
+
144
+ let blankRow = { ...(dataObject.getData(-1) as Record<string, unknown>), [uid]: NEW_ITEM_ROW_ID };
145
+
146
+ if (!dataObject.isDirty()) {
147
+ // Nothing was entered, so committing the row is the same as cancelling it
148
+ cancelNewRecord();
149
+ return blankRow;
150
+ }
151
+
152
+ let focusBefore = gridFocusCellSelector(apiRef);
153
+
154
+ try {
155
+ await dataObject.endEdit();
156
+ } catch (error) {
157
+ // The framework keeps a failed new record in storage as an unsaved row.
158
+ // The grid keeps the draft in the new item row instead, so the unsaved
159
+ // row is dropped and the current index goes back to the new record.
160
+ if (dataObject.getCurrentIndex() >= 0 && dataObject.isNewRecord(dataObject.getCurrentIndex())) {
161
+ dataObject.cancelEdit();
162
+ }
163
+ // Not through `beginNewRecord`, which would record the row the framework
164
+ // landed on as the one to restore on cancel
165
+ dataObject.setCurrentIndex(-1);
166
+ throw error;
167
+ }
168
+
169
+ setGeneration((g) => g + 1);
170
+
171
+ // The created row is the current row now; move the focus there once the
172
+ // grid has rendered it, so the user can keep working from where it landed.
173
+ let createdIndex = dataObject.getCurrentIndex();
174
+ if (createdIndex >= 0 && focusBefore) {
175
+ let createdRow = dataObject.getData(createdIndex) as any;
176
+ let createdId: GridRowId = createdRow[uid];
177
+ setTimeout(() => {
178
+ let api = apiRef.current;
179
+ if (!api || !api.getRow(createdId)) return;
180
+ let rowIndex = api.getRowIndexRelativeToVisibleRows(createdId);
181
+ if (rowIndex >= 0) api.scrollToIndexes({ rowIndex });
182
+ api.setCellFocus(createdId, focusBefore.field);
183
+ });
184
+ }
185
+
186
+ return blankRow;
187
+ },
188
+ [apiRef, dataObject, beginNewRecord, cancelNewRecord],
189
+ );
190
+
191
+ useEffect(() => {
192
+ if (!enabled) return;
193
+
194
+ // Moves the data object to the new record when editing starts, whether the
195
+ // user started it or `start` did, and discards it when the edit is cancelled.
196
+ // A commit goes through `save` instead.
197
+ const handleRowModesModelChange: GridEventListener<"rowModesModelChange"> = (model) => {
198
+ let entry = model[NEW_ITEM_ROW_ID] as { mode: GridRowModes; ignoreModifications?: boolean } | undefined;
199
+ let isEditing = entry?.mode === GridRowModes.Edit;
200
+
201
+ if (isEditing && !wasEditing.current) {
202
+ beginNewRecord();
203
+ } else if (!isEditing && wasEditing.current && entry?.ignoreModifications === true) {
204
+ // Deferred until the grid has left edit mode and put the focus back on the
205
+ // cell, so that a bound current index moves the focus from a mounted cell
206
+ // instead of from an editor that is about to be unmounted.
207
+ setTimeout(cancelNewRecord);
208
+ }
209
+
210
+ wasEditing.current = isEditing;
211
+ };
212
+
213
+ return apiRef.current?.subscribeEvent("rowModesModelChange", handleRowModesModelChange);
214
+ }, [apiRef, enabled, beginNewRecord, cancelNewRecord]);
215
+
216
+ let pinnedRows = useMemo<GridPinnedRowsProp | undefined>(() => {
217
+ if (!row) return pinnedRowsProp;
218
+
219
+ // The new item row sits next to the data, inside any rows the consumer pinned
220
+ return {
221
+ top: position === "top" ? [...(pinnedRowsProp?.top ?? []), row] : pinnedRowsProp?.top,
222
+ bottom: position === "bottom" ? [row, ...(pinnedRowsProp?.bottom ?? [])] : pinnedRowsProp?.bottom,
223
+ };
224
+ }, [row, position, pinnedRowsProp]);
225
+
226
+ let getRowClassName = useCallback<NonNullable<DataGridProps["getRowClassName"]>>(
227
+ (params) => {
228
+ let className = getRowClassNameProp?.(params) ?? "";
229
+ return params.id === NEW_ITEM_ROW_ID ? `${className} ${NEW_ITEM_ROW_CLASS}`.trim() : className;
230
+ },
231
+ [getRowClassNameProp],
232
+ );
233
+
234
+ let rootStyle = useMemo<React.CSSProperties>(
235
+ () =>
236
+ ({
237
+ // Read by the overlay's `content`, so the text is localized without a DOM node
238
+ "--AfGrid-newItemRowText": JSON.stringify(getLocalizedString("Click here to add a new row")),
239
+ }) as React.CSSProperties,
240
+ [],
241
+ );
242
+
243
+ useEffect(() => {
244
+ if (apiRef.current) {
245
+ (apiRef.current as AfGridApi).startNewItemRow = start;
246
+ }
247
+ }, [apiRef, start]);
248
+
249
+ return {
250
+ enabled,
251
+ save,
252
+ start,
253
+ gridProps: enabled
254
+ ? { pinnedRows, getRowClassName }
255
+ : { pinnedRows: pinnedRowsProp, getRowClassName: getRowClassNameProp },
256
+ rootStyle,
257
+ };
258
+ }
@@ -1,4 +1,4 @@
1
- import type { DataGridProProps, GridPaginationModel } from "@mui/x-data-grid-pro";
1
+ import type { DataGridPremiumProps, GridPaginationModel } from "@mui/x-data-grid-premium";
2
2
  import type { DataObject } from "@olenbetong/appframe-data";
3
3
  import { useDataLength, usePaging, useParameter } from "@olenbetong/appframe-react";
4
4
 
@@ -10,7 +10,7 @@ import { useMemo } from "react";
10
10
  *
11
11
  * @param dataObject Data object grid is used with
12
12
  */
13
- export function useAfPagination(dataObject: DataObject<any>): Partial<DataGridProProps> {
13
+ export function useAfPagination(dataObject: DataObject<any>): Partial<DataGridPremiumProps> {
14
14
  let paging = usePaging(dataObject);
15
15
  let maxRecords = useParameter(dataObject, "maxRecords");
16
16
  let dataLength = useDataLength(dataObject);
@@ -1,4 +1,4 @@
1
- import type { GridApi, GridInitialState, GridPaginationModel } from "@mui/x-data-grid-pro";
1
+ import type { GridApi, GridInitialState, GridPaginationModel } from "@mui/x-data-grid-premium";
2
2
 
3
3
  import localforage from "localforage";
4
4
  import { useEffect, useState } from "react";
@@ -54,6 +54,12 @@ function removeNonPersistedState(state: GridInitialState, config?: StatePersiste
54
54
  if (config?.pinnedColumns !== false) {
55
55
  newState.pinnedColumns = state.pinnedColumns;
56
56
  }
57
+ if (config?.rowGrouping !== false) {
58
+ newState.rowGrouping = state.rowGrouping;
59
+ }
60
+ if (config?.aggregation !== false) {
61
+ newState.aggregation = state.aggregation;
62
+ }
57
63
  if (config?.columns?.columnVisibilityModel !== false) {
58
64
  columns.columnVisibilityModel = state.columns?.columnVisibilityModel;
59
65
  }
@@ -166,8 +172,10 @@ setTimeout(() => {
166
172
  }, 2000);
167
173
 
168
174
  export type StatePersistenceConfig = {
175
+ aggregation?: boolean;
169
176
  density?: boolean;
170
177
  pinnedColumns?: boolean;
178
+ rowGrouping?: boolean;
171
179
  columns?: {
172
180
  columnVisibilityModel?: boolean;
173
181
  dimensions?: boolean;
@@ -1,18 +1,20 @@
1
1
  import {
2
- type DataGridProProps as DataGridProps,
2
+ type DataGridPremiumProps as DataGridProps,
3
3
  type GridApi,
4
4
  type GridEventListener,
5
5
  type GridRowId,
6
6
  GridRowModes,
7
7
  gridFocusCellSelector,
8
8
  gridVisibleColumnFieldsSelector,
9
- } from "@mui/x-data-grid-pro";
10
- import type { DataObject } from "@olenbetong/appframe-data";
9
+ } from "@mui/x-data-grid-premium";
10
+ import { type DataObject, uid } from "@olenbetong/appframe-data";
11
11
  import { setDataObjectField } from "@olenbetong/appframe-react";
12
12
 
13
13
  import type React from "react";
14
14
  import { useCallback, useEffect } from "react";
15
15
 
16
+ import { type AfNewItemRow, isNewItemRow } from "./useAfNewItemRow.js";
17
+
16
18
  function localDateAsUtcDate(date: Date) {
17
19
  const utcDate = new Date(date);
18
20
  console.log("year", utcDate, utcDate.getUTCFullYear(), date.getFullYear());
@@ -33,12 +35,12 @@ export type AfRowEditModelProps<T extends Record<string, unknown> = Record<strin
33
35
  dataObject: DataObject<T>;
34
36
  idField: string;
35
37
  disableEdit: boolean;
38
+ /** The new item row, when the grid renders one. Commits on that row are saved through it. */
39
+ newItemRow?: AfNewItemRow;
36
40
  };
37
41
 
38
- const uid: any = globalThis.af?.data?.uid ?? Symbol();
39
-
40
42
  /**
41
- * Binds a MUI DataGridPro row editing model to a data object. Editing will not affect the
43
+ * Binds a MUI DataGridPremium row editing model to a data object. Editing will not affect the
42
44
  * data object until a save event is triggered. If saving fails, will attempt to go back
43
45
  * into edit mode with the unsaved changes.
44
46
  */
@@ -47,11 +49,16 @@ export function useAfRowEditModel<T extends Record<string, unknown> = Record<str
47
49
  dataObject,
48
50
  idField,
49
51
  disableEdit,
52
+ newItemRow,
50
53
  }: AfRowEditModelProps<T>): Partial<DataGridProps> {
51
54
  let processRowUpdate = useCallback(
52
55
  async (newRow: any, oldRow: any) => {
53
56
  let { id, isNew, ...record } = newRow;
54
- id = (record as any)[(af as any).data.uid] ?? (record as any)[idField] ?? id;
57
+ id = (record as any)[uid] ?? (record as any)[idField] ?? id;
58
+
59
+ if (isNewItemRow(id) && newItemRow) {
60
+ return newItemRow.save(record);
61
+ }
55
62
 
56
63
  if (isNew) {
57
64
  let savedRow = await dataObject.addRow(newRow);
@@ -90,7 +97,7 @@ export function useAfRowEditModel<T extends Record<string, unknown> = Record<str
90
97
 
91
98
  return savedNewRow;
92
99
  },
93
- [dataObject, idField],
100
+ [dataObject, idField, newItemRow],
94
101
  );
95
102
 
96
103
  useEffect(() => {
@@ -98,12 +105,15 @@ export function useAfRowEditModel<T extends Record<string, unknown> = Record<str
98
105
  // to remove it manually if editing is cancelled
99
106
  const handleRowModesModelChange: GridEventListener<"rowModesModelChange"> = (model) => {
100
107
  for (let id of Object.keys(model)) {
108
+ // The new item row is not in the data object; `useAfNewItemRow` handles it
109
+ if (isNewItemRow(id)) continue;
110
+
101
111
  if (model[id].mode === GridRowModes.View && (model[id] as any)?.ignoreModifications === true) {
102
112
  let row = apiRef.current?.getRow(id);
103
113
  if (row?.isNew) {
104
114
  let focusBefore = gridFocusCellSelector(apiRef);
105
115
 
106
- apiRef.current?.updateRows([{ [(af as any).data.uid]: id, id, _action: "delete" } as any]);
116
+ apiRef.current?.updateRows([{ [uid]: id, id, _action: "delete" } as any]);
107
117
 
108
118
  setTimeout(() => {
109
119
  if (focusBefore && dataObject.getDataLength()) {
@@ -117,9 +127,7 @@ export function useAfRowEditModel<T extends Record<string, unknown> = Record<str
117
127
  // MUI grid only reverts changes on editable fields, while for example lookups can have edited
118
128
  // values that are not editable, so we need to manually revert those changes
119
129
  let index = dataObject.findIndex((r) => (r as any)[uid] === id || (r as any)[idField] === id);
120
- apiRef.current?.updateRows([
121
- { [(af as any).data.uid]: id, id, ...(dataObject.getData(index) as any) } as any,
122
- ]);
130
+ apiRef.current?.updateRows([{ [uid]: id, id, ...(dataObject.getData(index) as any) } as any]);
123
131
  }
124
132
  }
125
133
  }
@@ -0,0 +1,47 @@
1
+ import type { GridAggregationModel, GridInitialState, GridRowGroupingModel } from "@mui/x-data-grid-premium";
2
+
3
+ import { useState } from "react";
4
+
5
+ export type AfGridGroupingProps = {
6
+ aggregationModel: GridAggregationModel;
7
+ onAggregationModelChange: (model: GridAggregationModel) => void;
8
+ rowGroupingModel: GridRowGroupingModel;
9
+ onRowGroupingModelChange: (model: GridRowGroupingModel) => void;
10
+ };
11
+
12
+ export type AfGridGrouping = {
13
+ /**
14
+ * True while at least one column is grouped. The grid uses this to fall back
15
+ * to client side sorting, which row grouping requires.
16
+ */
17
+ isGrouping: boolean;
18
+ gridProps: AfGridGroupingProps;
19
+ };
20
+
21
+ /**
22
+ * Holds the row grouping and aggregation models in component state so the grid
23
+ * knows when a grouping is active, and seeds them from the restored layout.
24
+ *
25
+ * Both features are computed on the client, over the rows the grid has been
26
+ * given. With a dynamically loading data object that is the current page only,
27
+ * so a grouped grid usually wants `maxRecords` high enough to hold the whole
28
+ * result, or `dynamicLoading` turned off.
29
+ */
30
+ export function useAfRowGrouping(initialState: GridInitialState): AfGridGrouping {
31
+ let [rowGroupingModel, setRowGroupingModel] = useState<GridRowGroupingModel>(
32
+ () => initialState.rowGrouping?.model ?? [],
33
+ );
34
+ let [aggregationModel, setAggregationModel] = useState<GridAggregationModel>(
35
+ () => initialState.aggregation?.model ?? {},
36
+ );
37
+
38
+ return {
39
+ isGrouping: rowGroupingModel.length > 0,
40
+ gridProps: {
41
+ aggregationModel,
42
+ onAggregationModelChange: setAggregationModel,
43
+ rowGroupingModel,
44
+ onRowGroupingModelChange: setRowGroupingModel,
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,145 @@
1
+ import type { GridAggregationModel } from "@mui/x-data-grid-premium";
2
+ import type { DataObject } from "@olenbetong/appframe-data";
3
+ import { useEffect, useMemo, useState } from "react";
4
+
5
+ /**
6
+ * MUI's aggregation function names mapped onto the SQL aggregates the data API understands.
7
+ *
8
+ * `size` counts rows rather than values, and the data API has no aggregate that skips nulls
9
+ * differently, so it is left to the client — the grid already knows the row count.
10
+ */
11
+ const SQL_AGGREGATES: Record<string, string> = {
12
+ sum: "SUM",
13
+ avg: "AVG",
14
+ min: "MIN",
15
+ max: "MAX",
16
+ };
17
+
18
+ export type AfServerAggregationResult = {
19
+ /** Aggregated value per field, for the whole filtered result rather than the loaded page. */
20
+ values: Record<string, unknown>;
21
+ loading: boolean;
22
+ error: string | null;
23
+ };
24
+
25
+ const EMPTY: AfServerAggregationResult = { values: {}, loading: false, error: null };
26
+
27
+ /**
28
+ * Reads the fields the aggregation model can be answered server side, as data API field
29
+ * definitions. A field the data object does not have — a calculated column, say — is skipped:
30
+ * the server cannot aggregate something it never sends.
31
+ */
32
+ function getAggregateFields(dataObject: DataObject<any>, model: GridAggregationModel) {
33
+ let fields: Array<{ name: string; aggregate: string }> = [];
34
+
35
+ for (let [name, functionName] of Object.entries(model)) {
36
+ let aggregate = SQL_AGGREGATES[functionName];
37
+ if (!aggregate) continue;
38
+ if (!dataObject.getFields(name)) continue;
39
+
40
+ fields.push({ name, aggregate });
41
+ }
42
+
43
+ return fields;
44
+ }
45
+
46
+ /**
47
+ * Totals for the whole filtered result, not just the rows the grid is holding.
48
+ *
49
+ * MUI aggregates over the rows it has been given. On a dynamically loading data object that is
50
+ * the current page, so a sum over a paged grid is a sum of one page — which looks like a total
51
+ * and is not one. This asks the server for the real thing with a second, cheap retrieve: the same
52
+ * view under the same filters, requesting only the aggregates, returning a single row.
53
+ *
54
+ * The request goes straight to the data handler rather than through the data object, so the
55
+ * grid's own data and parameters are untouched.
56
+ *
57
+ * @param dataObject The grid's data object
58
+ * @param model The grid's aggregation model
59
+ * @param enabled Whether to load at all
60
+ */
61
+ export function useAfServerAggregation(
62
+ dataObject: DataObject<any>,
63
+ model: GridAggregationModel,
64
+ enabled: boolean,
65
+ ): AfServerAggregationResult {
66
+ let [result, setResult] = useState<AfServerAggregationResult>(EMPTY);
67
+
68
+ // The model is an object rebuilt on every render, so key the effect on its content.
69
+ let modelKey = useMemo(() => JSON.stringify(model ?? {}), [model]);
70
+
71
+ /*
72
+ * The totals have to follow the grid's filters exactly. Rather than mirroring every parameter
73
+ * that can move them, this reloads whenever the data object does — which is precisely when a
74
+ * filter, a where clause or a master row changed.
75
+ */
76
+ let [reloadCount, setReloadCount] = useState(0);
77
+
78
+ useEffect(() => {
79
+ if (!enabled) return;
80
+
81
+ let controller = new AbortController();
82
+
83
+ function reload() {
84
+ setReloadCount((count) => count + 1);
85
+ }
86
+
87
+ dataObject.attachEvent("onDataLoaded", reload, { signal: controller.signal });
88
+ dataObject.attachEvent("onAfterSave", reload, { signal: controller.signal });
89
+ dataObject.attachEvent("onRecordDeleted", reload, { signal: controller.signal });
90
+
91
+ return () => controller.abort();
92
+ }, [dataObject, enabled]);
93
+
94
+ useEffect(() => {
95
+ let fields = getAggregateFields(dataObject, JSON.parse(modelKey));
96
+
97
+ if (!enabled || fields.length === 0) {
98
+ setResult(EMPTY);
99
+ return;
100
+ }
101
+
102
+ let controller = new AbortController();
103
+ let cancelled = false;
104
+
105
+ setResult((current) => ({ ...current, loading: true, error: null }));
106
+
107
+ dataObject.dataHandler
108
+ .retrieve(
109
+ {
110
+ fields,
111
+ // No groupBy: one row holding the aggregates over everything that matches.
112
+ maxRecords: 1,
113
+ whereClause: dataObject.getParameter("whereClause"),
114
+ whereObject: dataObject.getParameter("whereObject"),
115
+ filterString: dataObject.getParameter("filterString"),
116
+ filterObject: dataObject.getParameter("filterObject"),
117
+ masterChildCriteria: dataObject.getParameter("masterChildCriteria"),
118
+ } as any,
119
+ { signal: controller.signal },
120
+ )
121
+ .then((rows: any[]) => {
122
+ if (cancelled) return;
123
+
124
+ setResult({ values: (rows?.[0] as Record<string, unknown>) ?? {}, loading: false, error: null });
125
+ })
126
+ .catch((cause: unknown) => {
127
+ if (cancelled || controller.signal.aborted) return;
128
+
129
+ /*
130
+ * Not every view can be aggregated — one built on a UNION or holding a computed
131
+ * column the server will not sum. Falling back to the client's page total is
132
+ * wrong in a quieter way than showing an error banner over a working grid, so
133
+ * the failure is reported to the caller and the grid keeps its own numbers.
134
+ */
135
+ setResult({ values: {}, loading: false, error: String((cause as Error)?.message ?? cause) });
136
+ });
137
+
138
+ return () => {
139
+ cancelled = true;
140
+ controller.abort();
141
+ };
142
+ }, [dataObject, modelKey, enabled, reloadCount]);
143
+
144
+ return result;
145
+ }
@@ -1,4 +1,4 @@
1
- import type { DataGridProProps, GridCallbackDetails, GridSortModel } from "@mui/x-data-grid-pro";
1
+ import type { DataGridPremiumProps, GridCallbackDetails, GridSortModel } from "@mui/x-data-grid-premium";
2
2
  import type { DataObject, RetrieveParameters, SortOrder } from "@olenbetong/appframe-data";
3
3
  import { useParameter } from "@olenbetong/appframe-react";
4
4
  import { useCallback, useMemo } from "react";
@@ -37,11 +37,19 @@ export function useAfSortModel({
37
37
  dataObject,
38
38
  columns,
39
39
  disableServerSorting = false,
40
+ isGrouping = false,
40
41
  }: {
41
42
  dataObject: DataObject<any>;
42
43
  columns: AfGridColumn[];
43
44
  disableServerSorting?: boolean;
44
- }): Partial<DataGridProProps> {
45
+ /**
46
+ * True while a row grouping is active. Grouped rows are built and ordered on
47
+ * the client, so the grid has to sort locally — but the model stays
48
+ * controlled and keeps writing through to the data object, so the sort order
49
+ * still matches what an Excel export produces.
50
+ */
51
+ isGrouping?: boolean;
52
+ }): Partial<DataGridPremiumProps> {
45
53
  let sortOrder = useParameter(dataObject, "sortOrder");
46
54
  let sortModel = useMemo(() => {
47
55
  let sortModel = afSortOrderToMuiSortModel(dataObject, sortOrder);
@@ -68,5 +76,9 @@ export function useAfSortModel({
68
76
  [dataObject, columns],
69
77
  );
70
78
 
71
- return disableServerSorting ? {} : { sortingMode: "server", sortModel, onSortModelChange };
79
+ if (disableServerSorting) {
80
+ return {};
81
+ }
82
+
83
+ return { sortingMode: isGrouping ? "client" : "server", sortModel, onSortModelChange };
72
84
  }