@linzjs/step-ag-grid 33.0.0 → 34.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.
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@linzjs/step-ag-grid",
3
3
  "repository": "github:linz/step-ag-grid.git",
4
4
  "license": "MIT",
5
- "version": "33.0.0",
5
+ "version": "34.0.0",
6
6
  "keywords": [
7
7
  "aggrid",
8
8
  "ag-grid",
@@ -0,0 +1,300 @@
1
+ import { renderHook } from '@testing-library/react';
2
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
3
+
4
+ import { usePostSortRowsHook } from './PostSortRowsHook';
5
+
6
+ const makeApi = (
7
+ columnState: { colId: string; sort?: string | null; sortIndex?: number | null }[] = [],
8
+ colDefs: Record<
9
+ string,
10
+ {
11
+ equals?: (a: unknown, b: unknown) => boolean;
12
+ comparator?: (a: unknown, b: unknown, nodeA: unknown, nodeB: unknown, isDescending: boolean) => number;
13
+ }
14
+ > = {},
15
+ ) => ({
16
+ isDestroyed: () => false,
17
+ getColumnState: () => columnState,
18
+ getQuickFilter: () => undefined,
19
+ getCellValue: ({ rowNode, colKey }: any) => rowNode.data[colKey],
20
+ getColumn: (colId: string) => ({ getColDef: () => colDefs[colId] ?? {} }),
21
+ applyColumnState: vi.fn(),
22
+ });
23
+
24
+ const makeNode = (data: unknown) => ({ data }) as any;
25
+
26
+ const sortedByName = [{ colId: 'name', sort: 'asc', sortIndex: 0 }];
27
+
28
+ describe('usePostSortRowsHook - sorted-column value comparison', () => {
29
+ test('does not throw when a row holds a self-reference, even unsorted', () => {
30
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid: vi.fn() }));
31
+ const postSortRows = result.current;
32
+
33
+ const selfRefData: any = { id: '1', name: 'a' };
34
+ selfRefData.self = selfRefData; // circular reference, not part of the sort
35
+
36
+ const nodes = [makeNode(selfRefData), makeNode({ id: '2', name: 'b' })];
37
+
38
+ expect(() => postSortRows({ api: makeApi(sortedByName) as any, nodes } as any)).not.toThrow();
39
+ });
40
+
41
+ test('does not throw when the sorted column value itself is self-referential', () => {
42
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid: vi.fn() }));
43
+ const postSortRows = result.current;
44
+
45
+ const circularName: any = { label: 'a' };
46
+ circularName.self = circularName;
47
+ const data: any = { id: '1', name: circularName };
48
+
49
+ const nodes = [makeNode(data), makeNode({ id: '2', name: { label: 'b' } })];
50
+
51
+ expect(() => postSortRows({ api: makeApi(sortedByName) as any, nodes } as any)).not.toThrow();
52
+ });
53
+
54
+ test('detects an edit to the sorted column value', () => {
55
+ const setStaleGrid = vi.fn();
56
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
57
+ const postSortRows = result.current;
58
+
59
+ const api = makeApi(sortedByName);
60
+ const rowA: any = { id: '1', name: 'a' };
61
+ const rowB: any = { id: '2', name: 'b' };
62
+ const nodes = [makeNode(rowA), makeNode(rowB)];
63
+
64
+ // First call backs up the initial hash/order.
65
+ postSortRows({ api: api as any, nodes } as any);
66
+ setStaleGrid.mockClear();
67
+
68
+ // Same data again: nothing changed.
69
+ postSortRows({ api: api as any, nodes } as any);
70
+ expect(setStaleGrid).not.toHaveBeenCalledWith(true);
71
+
72
+ // Edit the sorted field - AG Grid hands back the naturally re-sorted (rowA now after rowB)
73
+ // array, which is what should get flagged as stale (and reverted to the original order).
74
+ rowA.name = 'z';
75
+ const editedNodes = [makeNode(rowB), makeNode(rowA)];
76
+ postSortRows({ api: api as any, nodes: editedNodes } as any);
77
+
78
+ expect(setStaleGrid).toHaveBeenCalledWith(true);
79
+ expect(editedNodes.map((node) => node.data.id)).toEqual(['1', '2']);
80
+ });
81
+
82
+ test('editing an unsorted field does not mark the sort stale', () => {
83
+ const setStaleGrid = vi.fn();
84
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
85
+ const postSortRows = result.current;
86
+
87
+ const api = makeApi(sortedByName);
88
+ const rowA: any = { id: '1', name: 'a', other: 'x' };
89
+ const rowB: any = { id: '2', name: 'b', other: 'y' };
90
+ const nodes = [makeNode(rowA), makeNode(rowB)];
91
+
92
+ postSortRows({ api: api as any, nodes } as any);
93
+ setStaleGrid.mockClear();
94
+
95
+ // Edit a field that isn't part of the sort - shouldn't flag the sort as stale.
96
+ rowA.other = 'x-edited';
97
+ postSortRows({ api: api as any, nodes } as any);
98
+
99
+ expect(setStaleGrid).not.toHaveBeenCalledWith(true);
100
+ });
101
+
102
+ test('respects a custom colDef.equals on the sorted column', () => {
103
+ const setStaleGrid = vi.fn();
104
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
105
+ const postSortRows = result.current;
106
+
107
+ // Case-insensitive equality for the sorted column.
108
+ const api = makeApi(sortedByName, {
109
+ name: { equals: (a, b) => `${a}`.toLowerCase() === `${b}`.toLowerCase() },
110
+ });
111
+ const rowA: any = { id: '1', name: 'a' };
112
+ const rowB: any = { id: '2', name: 'b' };
113
+
114
+ // Initial natural sort order: a, b.
115
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
116
+ setStaleGrid.mockClear();
117
+
118
+ // Only a case change - still naturally sorts the same way - custom equals says this is unchanged.
119
+ rowA.name = 'A';
120
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
121
+ expect(setStaleGrid).not.toHaveBeenCalledWith(true);
122
+
123
+ // A real value change that would naturally re-sort rowA after rowB - AG Grid hands back nodes in
124
+ // that new natural order, which is what should get flagged as stale (and reverted to old order).
125
+ rowA.name = 'z';
126
+ const thirdCallNodes = [makeNode(rowB), makeNode(rowA)];
127
+ postSortRows({ api: api as any, nodes: thirdCallNodes } as any);
128
+ expect(setStaleGrid).toHaveBeenCalledWith(true);
129
+ expect(thirdCallNodes.map((n) => n.data.id)).toEqual(['1', '2']);
130
+ });
131
+
132
+ test('falls back to colDef.comparator when there is no equals', () => {
133
+ const setStaleGrid = vi.fn();
134
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
135
+ const postSortRows = result.current;
136
+
137
+ // Comparator sorts by the value's length only - two values of the same length are "equal".
138
+ const api = makeApi(sortedByName, {
139
+ name: { comparator: (a, b) => `${a}`.length - `${b}`.length },
140
+ });
141
+ const rowA: any = { id: '1', name: 'aa' };
142
+ const rowB: any = { id: '2', name: 'bbb' };
143
+
144
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
145
+ setStaleGrid.mockClear();
146
+
147
+ // Different characters, same length - the comparator says this is unchanged.
148
+ rowA.name = 'zz';
149
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
150
+ expect(setStaleGrid).not.toHaveBeenCalledWith(true);
151
+
152
+ // A length change - the comparator says this really is different, and naturally re-sorts rowA
153
+ // after rowB.
154
+ rowA.name = 'zzzz';
155
+ const thirdCallNodes = [makeNode(rowB), makeNode(rowA)];
156
+ postSortRows({ api: api as any, nodes: thirdCallNodes } as any);
157
+ expect(setStaleGrid).toHaveBeenCalledWith(true);
158
+ expect(thirdCallNodes.map((n) => n.data.id)).toEqual(['1', '2']);
159
+ });
160
+
161
+ test('comparator receives the pre-edit snapshot node and the current live node', () => {
162
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid: vi.fn() }));
163
+ const postSortRows = result.current;
164
+
165
+ // Ignores the raw values entirely and only reads nodeA/nodeB, to prove which node objects
166
+ // the hook actually passes through when checking a row's own previous value against its
167
+ // current one.
168
+ const comparator = vi.fn((_a, _b, nodeA: any, nodeB: any) => (nodeA.data.name === nodeB.data.name ? 0 : 1));
169
+ const api = makeApi(sortedByName, { name: { comparator } });
170
+ const rowA: any = { id: '1', name: 'aa' };
171
+ const rowB: any = { id: '2', name: 'bbb' };
172
+
173
+ // First call backs up rowA's pre-edit data as the snapshot node.
174
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
175
+ comparator.mockClear();
176
+
177
+ // The row's data object is replaced (not mutated in place) - realistic for immutable-style
178
+ // updates, and the only way to distinguish the snapshot node from the current live node, since
179
+ // the hook's snapshot wraps the data object by reference rather than deep-cloning it.
180
+ const rowAEdited: any = { id: '1', name: 'zz' };
181
+ postSortRows({ api: api as any, nodes: [makeNode(rowAEdited), makeNode(rowB)] } as any);
182
+
183
+ // First call is for row 1: its own previous value vs current value.
184
+ expect(comparator).toHaveBeenCalled();
185
+ const [, , nodeA, nodeB] = comparator.mock.calls[0];
186
+ // nodeA is the frozen pre-edit snapshot ("aa"); nodeB is the current live node ("zz").
187
+ expect((nodeA as any).data.name).toBe('aa');
188
+ expect((nodeB as any).data.name).toBe('zz');
189
+ });
190
+
191
+ test('prefers equals over comparator when a column defines both', () => {
192
+ const setStaleGrid = vi.fn();
193
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
194
+ const postSortRows = result.current;
195
+
196
+ const comparator = vi.fn((a, b) => `${a}`.length - `${b}`.length);
197
+ const api = makeApi(sortedByName, {
198
+ name: { equals: (a, b) => a === b, comparator },
199
+ });
200
+ const rowA: any = { id: '1', name: 'aa' };
201
+ const rowB: any = { id: '2', name: 'bbb' };
202
+
203
+ postSortRows({ api: api as any, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
204
+ setStaleGrid.mockClear();
205
+ comparator.mockClear();
206
+
207
+ // Same length, different value - equals (===) says changed; comparator would have said unchanged.
208
+ // AG Grid hands back the naturally re-sorted order for this genuine change.
209
+ rowA.name = 'zz';
210
+ const thirdCallNodes = [makeNode(rowB), makeNode(rowA)];
211
+ postSortRows({ api: api as any, nodes: thirdCallNodes } as any);
212
+
213
+ expect(comparator).not.toHaveBeenCalled();
214
+ expect(setStaleGrid).toHaveBeenCalledWith(true);
215
+ expect(thirdCallNodes.map((n) => n.data.id)).toEqual(['1', '2']);
216
+ });
217
+
218
+ test('with no sort configured, retains prior array order when an update reorders the same rows', () => {
219
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid: vi.fn() }));
220
+ const postSortRows = result.current;
221
+
222
+ const api = makeApi([]); // no column sorted - "sort" is just array order
223
+ const rowA = { id: '1', name: 'a' };
224
+ const rowB = { id: '2', name: 'b' };
225
+ const rowC = { id: '3', name: 'c' };
226
+
227
+ const firstNodes = [makeNode(rowA), makeNode(rowB), makeNode(rowC)];
228
+ postSortRows({ api: api as any, nodes: firstNodes } as any);
229
+
230
+ // A data refresh comes back with the same rows in a different order.
231
+ const reordered = [makeNode(rowC), makeNode(rowA), makeNode(rowB)];
232
+ postSortRows({ api: api as any, nodes: reordered } as any);
233
+
234
+ expect(reordered.map((n) => n.data.id)).toEqual(['1', '2', '3']);
235
+ });
236
+
237
+ test('with no sort configured, a new row is placed at the end even if AgGrid handed it back in the middle', () => {
238
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid: vi.fn() }));
239
+ const postSortRows = result.current;
240
+
241
+ const api = makeApi([]);
242
+ const rowA = { id: '1', name: 'a' };
243
+ const rowB = { id: '2', name: 'b' };
244
+
245
+ const firstNodes = [makeNode(rowA), makeNode(rowB)];
246
+ postSortRows({ api: api as any, nodes: firstNodes } as any);
247
+
248
+ // New row shows up in the middle of the incoming array, plus the existing rows are reordered too.
249
+ const rowC = { id: '3', name: 'c' };
250
+ const withNewRow = [makeNode(rowB), makeNode(rowC), makeNode(rowA)];
251
+ postSortRows({ api: api as any, nodes: withNewRow } as any);
252
+
253
+ expect(withNewRow.map((n) => n.data.id)).toEqual(['1', '2', '3']);
254
+ });
255
+ });
256
+
257
+ describe('usePostSortRowsHook - deferred stale-sort restoration', () => {
258
+ beforeEach(() => vi.useFakeTimers());
259
+ afterEach(() => vi.useRealTimers());
260
+
261
+ test('restores the sort state active when the row went stale, not the newly clicked one', () => {
262
+ const setStaleGrid = vi.fn();
263
+ const { result } = renderHook(() => usePostSortRowsHook({ setStaleGrid }));
264
+ const postSortRows = result.current;
265
+
266
+ // Mutable so it can be updated in place to simulate the user clicking the sort header,
267
+ // while the api (and its applyColumnState mock) stays the same single instance throughout.
268
+ const columnState = [{ colId: 'name', sort: 'asc', sortIndex: 0 }];
269
+ const api = makeApi(columnState) as any;
270
+ const rowA: any = { id: '1', name: 'a' };
271
+ const rowB: any = { id: '2', name: 'b' };
272
+
273
+ // First call backs up the initial hash/order.
274
+ postSortRows({ api, nodes: [makeNode(rowA), makeNode(rowB)] } as any);
275
+ setStaleGrid.mockClear();
276
+
277
+ // Edit the sorted field: AG Grid hands back the naturally re-sorted order, which goes stale.
278
+ rowA.name = 'z';
279
+ const staleNodes = [makeNode(rowB), makeNode(rowA)];
280
+ postSortRows({ api, nodes: staleNodes } as any);
281
+
282
+ expect(setStaleGrid).toHaveBeenCalledWith(true);
283
+ expect(api.applyColumnState).not.toHaveBeenCalled();
284
+
285
+ // User clicks the stale sort header, flipping its direction.
286
+ columnState[0] = { colId: 'name', sort: 'desc', sortIndex: 0 };
287
+ postSortRows({ api, nodes: staleNodes } as any);
288
+
289
+ expect(setStaleGrid).toHaveBeenCalledWith(false);
290
+ // Restoration is deferred to a fresh top-level event - not applied synchronously.
291
+ expect(api.applyColumnState).not.toHaveBeenCalled();
292
+
293
+ vi.runAllTimers();
294
+
295
+ // Restores the asc state that was active when the row went stale, not the desc state just clicked.
296
+ expect(api.applyColumnState).toHaveBeenCalledWith({
297
+ state: [{ colId: 'name', sort: 'asc', sortIndex: 0 }],
298
+ });
299
+ });
300
+ });
@@ -1,7 +1,7 @@
1
1
  import { IRowNode } from 'ag-grid-community';
2
2
  import { ColumnState } from 'ag-grid-community';
3
3
  import { PostSortRowsParams } from 'ag-grid-community';
4
- import { isEmpty } from 'lodash-es';
4
+ import { defer, isEmpty } from 'lodash-es';
5
5
  import { useCallback, useContext, useRef } from 'react';
6
6
 
7
7
  import { GridContext } from '../contexts/GridContext';
@@ -25,7 +25,9 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
25
25
  const lastSortOrderHash = useRef<string>('');
26
26
 
27
27
  // Used to detect if sort order was the same, has the direction changed
28
- const previousRowSortIndexRef = useRef<Record<string, { index: number; hash: string } | undefined>>({});
28
+ const previousRowSortIndexRef = useRef<
29
+ Record<string, { index: number; values: unknown[]; node: IRowNode } | undefined>
30
+ >({});
29
31
 
30
32
  // stale sort is when there's a sort and user edits a row
31
33
  // this applies a class to the div wrapping the grid which in turn adds a * beside the sort arrow
@@ -40,27 +42,87 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
40
42
  return useCallback(
41
43
  ({ api, nodes }: PostSortRowsParams) => {
42
44
  // Grid is destroyed
43
- if (!api) return;
45
+ if (!api || api.isDestroyed()) {
46
+ return;
47
+ }
44
48
 
45
49
  const previousRowSortIndex = previousRowSortIndexRef.current;
46
50
 
47
- const hashNode = (node: IRowNode | undefined) => {
48
- return node ? JSON.stringify(node.data) : '';
51
+ const copyCurrentSortSettings = (): ColumnState[] => {
52
+ return api.getColumnState().map((row) => ({ colId: row.colId, sort: row.sort, sortIndex: row.sortIndex }));
49
53
  };
50
54
 
51
- const copyCurrentSortSettings = (): ColumnState[] =>
52
- api.getColumnState().map((row) => ({ colId: row.colId, sort: row.sort, sortIndex: row.sortIndex }));
55
+ // Only the currently sorted columns' values can affect where a row belongs, so that's all we
56
+ // need to compare to detect a change relevant to stale-sort detection.
57
+ const currentSortState = copyCurrentSortSettings();
58
+ const sortedColIds = currentSortState
59
+ .filter((col) => col.sort)
60
+ .sort((a, b) => (a.sortIndex ?? 0) - (b.sortIndex ?? 0))
61
+ .map((col) => col.colId);
62
+
63
+ // Use each column's own `equals` (falling back to its sort `comparator`, then to the grid's
64
+ // default `===`) rather than stringifying values - this respects whatever notion of equality
65
+ // the column already defines.
66
+ const sortColumnEquals: Record<string, (a: unknown, b: unknown, nodeA: IRowNode, nodeB: IRowNode) => boolean> =
67
+ {};
68
+ sortedColIds.forEach((colId) => {
69
+ const colDef = api.getColumn(colId)?.getColDef();
70
+ if (colDef?.equals) {
71
+ const equals = colDef.equals;
72
+ sortColumnEquals[colId] = (a, b) => equals(a, b);
73
+ } else if (colDef?.comparator) {
74
+ const comparator = colDef.comparator;
75
+ // isDescending doesn't matter here - we only care whether the comparator considers the two
76
+ // values equivalent (0), not which direction they'd sort in.
77
+ sortColumnEquals[colId] = (a, b, nodeA, nodeB) => comparator(a, b, nodeA, nodeB, false) === 0;
78
+ } else {
79
+ sortColumnEquals[colId] = (a, b) => a === b;
80
+ }
81
+ });
82
+
83
+ const getSortValues = (node: IRowNode | undefined): unknown[] =>
84
+ node ? sortedColIds.map((colId) => api.getCellValue({ rowNode: node, colKey: colId })) : [];
85
+
86
+ // A comparator wants the row node too (some use it, e.g. to tie-break) - but by the time this
87
+ // callback runs, AgGrid has already mutated the node in place with the new data, so there's no
88
+ // real "previous node" left to hand it. This lightweight stand-in (same id, snapshotted data) is
89
+ // the best available substitute; it satisfies comparators that only read a couple of fields off
90
+ // nodeA/nodeB and won't behave correctly for one that relies on other IRowNode behaviour.
91
+ const snapshotNode = (node: IRowNode | undefined): IRowNode | undefined =>
92
+ node ? ({ data: node.data, id: node.id } as unknown as IRowNode) : undefined;
93
+
94
+ const sortValuesChanged = (
95
+ previous: { values: unknown[]; node: IRowNode } | undefined,
96
+ node: IRowNode,
97
+ currentValues: unknown[],
98
+ ) =>
99
+ !previous ||
100
+ sortedColIds.some(
101
+ (colId, i) => !sortColumnEquals[colId](previous.values[i], currentValues[i], previous.node, node),
102
+ );
53
103
 
54
104
  const backupSortOrder = () => {
55
- for (const x in previousRowSortIndex) delete previousRowSortIndex[x];
56
- nodes.forEach((node, index) => (previousRowSortIndex[`${node.data.id}`] = { index, hash: hashNode(node) }));
105
+ for (const x in previousRowSortIndex) {
106
+ delete previousRowSortIndex[x];
107
+ }
108
+ nodes.forEach(
109
+ (node, index) =>
110
+ (previousRowSortIndex[`${node.data.id}`] = {
111
+ index,
112
+ values: getSortValues(node),
113
+ node: snapshotNode(node)!,
114
+ }),
115
+ );
57
116
  };
58
117
 
59
118
  // Check if column is the first sorted column. Note: column is preconfigured to sort its sortIndex is null not 1
60
- const isFirstSortColumn = (row: ColumnState) => row.sort && [0, null].includes(row.sortIndex ?? null);
119
+ const isFirstSortColumn = (row: ColumnState) => {
120
+ return row.sort && [0, null].includes(row.sortIndex ?? null);
121
+ };
61
122
 
62
- const isSameColumnAndDifferentSort = (col1: ColumnState | undefined, col2: ColumnState | undefined) =>
63
- col1 && col2 && col1.colId === col2.colId && col1.sort != col2.sort;
123
+ const isSameColumnAndDifferentSort = (col1: ColumnState | undefined, col2: ColumnState | undefined) => {
124
+ return col1 && col2 && col1.colId === col2.colId && col1.sort != col2.sort;
125
+ };
64
126
 
65
127
  const restorePreviousSortColumnState = () => api.applyColumnState({ state: previousColSort.current });
66
128
 
@@ -78,12 +140,15 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
78
140
  previousColSort.current = copyCurrentSortSettings();
79
141
  }
80
142
 
81
- const newSortOrder = JSON.stringify(copyCurrentSortSettings());
143
+ const newSortOrder = JSON.stringify(currentSortState);
82
144
  let sortOrderChanged = newSortOrder != lastSortOrderHash.current;
83
145
 
84
- const quickFilter = api.getQuickFilter();
146
+ // api.getQuickFilter() returns undefined (not '') when no quick filter is set - normalize before
147
+ // comparing, otherwise '' (the initial ref value) never equals undefined and this looks "changed"
148
+ // on every single call for a grid that never uses the quick filter feature.
149
+ const quickFilter = api.getQuickFilter() ?? '';
85
150
  if (previousQuickFilter.current != quickFilter) {
86
- previousQuickFilter.current = quickFilter ?? '';
151
+ previousQuickFilter.current = quickFilter;
87
152
  sortOrderChanged = true;
88
153
  }
89
154
 
@@ -92,7 +157,7 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
92
157
  }
93
158
 
94
159
  if (sortOrderChanged) {
95
- const thisFirstCol = copyCurrentSortSettings().find(isFirstSortColumn);
160
+ const thisFirstCol = currentSortState.find(isFirstSortColumn);
96
161
  const previousFirstCol = previousColSort.current.find(isFirstSortColumn);
97
162
 
98
163
  // Change to sort can be: (in the context of stale sort do...)
@@ -111,7 +176,12 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
111
176
 
112
177
  // trigger a recapture of sort order
113
178
  lastSortOrderHash.current = '';
114
- restorePreviousSortColumnState();
179
+ // applyColumnState() here would be a no-op if called synchronously - we're still inside AgGrid's
180
+ // current sort pass (this callback runs as part of it), and it won't start a fresh one re-entrantly.
181
+ // Defer so it runs as a new, top-level event once the current pass has finished.
182
+ defer(() => {
183
+ restorePreviousSortColumnState();
184
+ });
115
185
  } else {
116
186
  // Sort was on a different column so clear sort and sort like normal
117
187
  if (sortWasStale.current) {
@@ -131,7 +201,7 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
131
201
  for (const node of nodes) {
132
202
  const psr = previousRowSortIndex[`${node.data.id}`];
133
203
  if (psr) {
134
- if (psr.hash != hashNode(node)) {
204
+ if (sortValuesChanged(psr, node, getSortValues(node))) {
135
205
  if (firstChangedNodeIndex === -1) firstChangedNodeIndex = index;
136
206
  changedRowCount++;
137
207
  }
@@ -146,17 +216,22 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
146
216
  if (changedRowCount === 0 && newRowCount === 1) {
147
217
  // insert new row at end
148
218
  const newIndex = index - 1;
149
- previousRowSortIndex[`${lastNewNode?.data.id}`] = { index: newIndex, hash: hashNode(lastNewNode) };
219
+ previousRowSortIndex[`${lastNewNode?.data.id}`] = {
220
+ index: newIndex,
221
+ values: getSortValues(lastNewNode),
222
+ node: snapshotNode(lastNewNode)!,
223
+ };
150
224
  wasStale = true;
151
225
  } else if (changedRowCount === 2 && newRowCount === 0) {
152
226
  // This must be a swap rows (sometimes it's not, needs further attention)
153
227
  backupSortOrder();
154
228
  wasStale = false;
155
229
  } else if (changedRowCount > 1 && newRowCount === 1) {
156
- // This must be a insert so, insert new row near the row that changed
230
+ // This must be an insert so, insert new row near the row that changed
157
231
  previousRowSortIndex[`${lastNewNode?.data.id}`] = {
158
232
  index: firstChangedNodeIndex + 0.5,
159
- hash: hashNode(lastNewNode),
233
+ values: getSortValues(lastNewNode),
234
+ node: snapshotNode(lastNewNode)!,
160
235
  };
161
236
  wasStale = true;
162
237
  // For some reason AgGrid mis-positions the inserted row.
@@ -164,10 +239,38 @@ export const usePostSortRowsHook = ({ setStaleGrid }: PostSortRowsHookProps) =>
164
239
  redrawRows();
165
240
  }
166
241
  } else if (changedRowCount == 1 && newRowCount === 0) {
167
- // User edited one row so, do nothing, retain sort
242
+ // User edited one row so, do nothing, retain sort. Refresh this row's stored values (keeping its
243
+ // retained index) so a *different* row edited afterward isn't miscounted as "2 rows changed" against
244
+ // this row's now-stale values, which would misfire the swap-detection branch above and silently drop
245
+ // the retained order.
246
+ const changedNode = nodes[firstChangedNodeIndex];
247
+ const previousEntry = changedNode && previousRowSortIndex[`${changedNode.data.id}`];
248
+ if (changedNode && previousEntry) {
249
+ previousRowSortIndex[`${changedNode.data.id}`] = {
250
+ index: previousEntry.index,
251
+ values: getSortValues(changedNode),
252
+ node: snapshotNode(changedNode)!,
253
+ };
254
+ }
168
255
  wasStale = true;
169
- } else if (changedRowCount !== 0 || newRowCount != 0) {
170
- // too many rows changed, resort
256
+ } else if (
257
+ changedRowCount === 0 &&
258
+ newRowCount === 0 &&
259
+ nodes.length === Object.keys(previousRowSortIndex).length
260
+ ) {
261
+ // No row's sort values look changed and no rows were added/removed, but that doesn't mean nothing needs
262
+ // checking: AgGrid invokes postSortRows once per data update with a pass-through (not actually
263
+ // re-sorted) `nodes` array, then again after the forced refreshClientSideRowModel() call in
264
+ // GridContextProvider (needed to get AgGrid to actually run the sort stage after a plain data update)
265
+ // with a genuinely freshly-sorted array. By that second call the "changedRowCount == 1" branch above has
266
+ // already refreshed the edited row's stored values on the first (pass-through) call, so it no longer looks
267
+ // "changed" here - this may be our first chance to see the row's real new position. Fall through to the
268
+ // position-based stillStale check below instead of treating this as "nothing to do".
269
+ wasStale = true;
270
+ } else {
271
+ // Either too many rows changed, or rows were removed with nothing else changing (changedRowCount and
272
+ // newRowCount are both 0 in the deletion case) - either way, resort and refresh the backup so we don't
273
+ // leave stale ids for removed rows in previousRowSortIndex.
171
274
  backupSortOrder();
172
275
  }
173
276
 
@@ -11,13 +11,14 @@ import {
11
11
  import { CellEditorCommon } from '../GridCell';
12
12
  import { useGridPopoverHook } from '../GridPopoverHook';
13
13
  import { GridBaseRow } from '../types';
14
+ import { MaybePromise } from '../../utils/util';
14
15
 
15
16
  export interface GridFormTextInputProps<TData extends GridBaseRow>
16
17
  extends TextInputValidatorProps<TData>, CellEditorCommon {
17
18
  placeholder?: string;
18
19
  units?: string;
19
20
  width?: string | number;
20
- onSave?: (props: { selectedRows: TData[]; value: string }) => Promise<boolean>;
21
+ onSave?: (props: { selectedRows: TData[]; value: string }) => MaybePromise<boolean>;
21
22
  helpText?: string;
22
23
  disableUnicodeCharacterFilter?: boolean;
23
24
  }
@@ -767,15 +767,11 @@ export const GridContextProvider = <TData extends GridBaseRow>(props: PropsWithC
767
767
  }
768
768
 
769
769
  if (ok) {
770
- //const cell = gridApi.getFocusedCell();
771
- //if (cell && gridApi.getFocusedCell() == null) {
772
- // !gridApi.isDestroyed && gridApi.setFocusedCell(cell.rowIndex, cell.column);
773
- // }
774
-
775
- // This is needed to trigger postSortRowsHook
776
- if (!gridApi.isDestroyed) {
777
- gridApi.refreshClientSideRowModel();
778
- }
770
+ defer(() => {
771
+ if (!gridApi.isDestroyed()) {
772
+ gridApi.refreshClientSideRowModel();
773
+ }
774
+ });
779
775
  }
780
776
 
781
777
  void (async () => {
@@ -406,6 +406,7 @@ export const MenuList = ({
406
406
  useEffect(() => {
407
407
  if (!isOpen) {
408
408
  dispatch(HoverActionTypes.RESET, undefined, 0);
409
+ // oxlint-disable-next-line react/set-state-in-effect
409
410
  if (!closeTransition) setOverflowData(undefined);
410
411
  return () => {};
411
412
  }
@@ -49,7 +49,9 @@ const GridInlineTextTemplate: StoryFn<typeof Grid<IFormTestRow>> = (props: GridP
49
49
  editorParams: {
50
50
  placeholder: 'Enter some text...',
51
51
  onSave: ({ selectedRowIds, value }) => {
52
- setRowData(rowData.map((data) => (selectedRowIds.includes(data.id) ? { ...data, text1: value } : data)));
52
+ setRowData((current) =>
53
+ current.map((data) => (selectedRowIds.includes(data.id) ? { ...data, text1: value } : data)),
54
+ );
53
55
  return true;
54
56
  },
55
57
  },
@@ -70,14 +72,16 @@ const GridInlineTextTemplate: StoryFn<typeof Grid<IFormTestRow>> = (props: GridP
70
72
  return null;
71
73
  },
72
74
  onSave: ({ selectedRowIds, value }) => {
73
- setRowData(rowData.map((data) => (selectedRowIds.includes(data.id) ? { ...data, text2: value } : data)));
75
+ setRowData((current) =>
76
+ current.map((data) => (selectedRowIds.includes(data.id) ? { ...data, text2: value } : data)),
77
+ );
74
78
  return true;
75
79
  },
76
80
  },
77
81
  },
78
82
  ),
79
83
  GridPopoverMenu(
80
- {},
84
+ { colId: 'menu' },
81
85
  {
82
86
  multiEdit: true,
83
87
  editorParams: {
@@ -102,25 +106,27 @@ const GridInlineTextTemplate: StoryFn<typeof Grid<IFormTestRow>> = (props: GridP
102
106
  },
103
107
  ),
104
108
  ],
105
- [rowData],
109
+ [],
106
110
  );
107
111
 
108
112
  const addRowAction = useCallback(async () => {
109
113
  await wait(1000);
110
114
 
111
- const lastRow = rowData[rowData.length - 1];
112
115
  // eslint-disable-next-line @typescript-eslint/require-await
113
116
  await selectRowsWithFlashDiff(async () => {
114
- setRowData([
115
- ...rowData,
116
- {
117
- id: (lastRow?.id ?? 0) + 1,
118
- text1: '?',
119
- text2: '?',
120
- },
121
- ]);
117
+ setRowData((current) => {
118
+ const lastRow = current[current.length - 1];
119
+ return [
120
+ ...current,
121
+ {
122
+ id: (lastRow?.id ?? 0) + 1,
123
+ text1: '?',
124
+ text2: '?',
125
+ },
126
+ ];
127
+ });
122
128
  });
123
- }, [rowData, selectRowsWithFlashDiff]);
129
+ }, [selectRowsWithFlashDiff]);
124
130
 
125
131
  return (
126
132
  <>