-
Notifications
You must be signed in to change notification settings - Fork 0
/
useGridCellEditing.new.ts
533 lines (456 loc) · 19.3 KB
/
useGridCellEditing.new.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import * as React from 'react';
import { unstable_useEventCallback as useEventCallback } from '@mui/utils';
import {
useGridApiEventHandler,
useGridApiOptionHandler,
GridSignature,
} from '../../utils/useGridApiEventHandler';
import { GridEventListener } from '../../../models/events/gridEventListener';
import {
GridEditModes,
GridCellModes,
GridEditingState,
GridEditCellProps,
} from '../../../models/gridEditRowModel';
import { GridApiCommunity } from '../../../models/api/gridApiCommunity';
import { DataGridProcessedProps } from '../../../models/props/DataGridProps';
import {
GridNewCellEditingApi,
GridStopCellEditModeParams,
GridStartCellEditModeParams,
GridCellModesModel,
GridCellModesModelProps,
GridNewEditingSharedApi,
} from '../../../models/api/gridEditingApi';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { gridEditRowsStateSelector } from './gridEditRowsSelector';
import { GridRowId } from '../../../models/gridRows';
import { isPrintableKey } from '../../../utils/keyboardUtils';
import { buildWarning } from '../../../utils/warning';
import { gridRowsIdToIdLookupSelector } from '../rows/gridRowsSelector';
import { deepClone } from '../../../utils/utils';
import {
GridCellEditStartParams,
GridCellEditStopParams,
GridCellEditStartReasons,
GridCellEditStopReasons,
} from '../../../models/params/gridEditCellParams';
const missingOnProcessRowUpdateErrorWarning = buildWarning(
[
'MUI: A call to `processRowUpdate` threw an error which was not handled because `onProcessRowUpdateError` is missing.',
'To handle the error pass a callback to the `onProcessRowUpdateError` prop, e.g. `<DataGrid onProcessRowUpdateError={(error) => ...} />`.',
'For more detail, see http://mui.com/components/data-grid/editing/#persistence.',
],
'error',
);
export const useGridCellEditing = (
apiRef: React.MutableRefObject<GridApiCommunity>,
props: Pick<
DataGridProcessedProps,
| 'editMode'
| 'processRowUpdate'
| 'onCellEditStart'
| 'onCellEditStop'
| 'cellModesModel'
| 'onCellModesModelChange'
| 'onProcessRowUpdateError'
| 'signature'
| 'disableIgnoreModificationsIfProcessingProps'
>,
) => {
const [cellModesModel, setCellModesModel] = React.useState<GridCellModesModel>({});
const cellModesModelRef = React.useRef(cellModesModel);
const prevCellModesModel = React.useRef<GridCellModesModel>({});
const {
processRowUpdate,
onProcessRowUpdateError,
cellModesModel: cellModesModelProp,
onCellModesModelChange,
signature,
} = props;
const runIfEditModeIsCell =
<Args extends any[]>(callback: (...args: Args) => void) =>
(...args: Args) => {
if (props.editMode === GridEditModes.Cell) {
callback(...args);
}
};
const throwIfNotEditable = React.useCallback(
(id: GridRowId, field: string) => {
const params = apiRef.current.getCellParams(id, field);
if (!apiRef.current.isCellEditable(params)) {
throw new Error(`MUI: The cell with id=${id} and field=${field} is not editable.`);
}
},
[apiRef],
);
const throwIfNotInMode = React.useCallback(
(id: GridRowId, field: string, mode: GridCellModes) => {
if (apiRef.current.getCellMode(id, field) !== mode) {
throw new Error(`MUI: The cell with id=${id} and field=${field} is not in ${mode} mode.`);
}
},
[apiRef],
);
const handleCellDoubleClick = React.useCallback<GridEventListener<'cellDoubleClick'>>(
(params, event) => {
if (!params.isEditable) {
return;
}
if (params.cellMode === GridCellModes.Edit) {
return;
}
const newParams: GridCellEditStartParams = {
...params,
reason: GridCellEditStartReasons.cellDoubleClick,
};
apiRef.current.publishEvent('cellEditStart', newParams, event);
},
[apiRef],
);
const handleCellFocusOut = React.useCallback<GridEventListener<'cellFocusOut'>>(
(params, event) => {
if (params.cellMode === GridCellModes.View) {
return;
}
if (apiRef.current.getCellMode(params.id, params.field) === GridCellModes.View) {
return;
}
const newParams = { ...params, reason: GridCellEditStopReasons.cellFocusOut };
apiRef.current.publishEvent('cellEditStop', newParams, event);
},
[apiRef],
);
const handleCellKeyDown = React.useCallback<GridEventListener<'cellKeyDown'>>(
(params, event) => {
if (params.cellMode === GridCellModes.Edit) {
// Wait until IME is settled for Asian languages like Japanese and Chinese
// TODO: `event.which` is depricated but this is a temporary workaround
if (event.which === 229) {
return;
}
let reason: GridCellEditStopReasons | undefined;
if (event.key === 'Escape') {
reason = GridCellEditStopReasons.escapeKeyDown;
} else if (event.key === 'Enter') {
reason = GridCellEditStopReasons.enterKeyDown;
} else if (event.key === 'Tab') {
reason = event.shiftKey
? GridCellEditStopReasons.shiftTabKeyDown
: GridCellEditStopReasons.tabKeyDown;
event.preventDefault(); // Prevent going to the next element in the tab sequence
}
if (reason) {
const newParams: GridCellEditStopParams = { ...params, reason };
apiRef.current.publishEvent('cellEditStop', newParams, event);
}
} else if (params.isEditable) {
let reason: GridCellEditStartReasons | undefined;
if (event.key === ' ' && event.shiftKey) {
return; // Shift + Space is used to select the row
}
if (isPrintableKey(event)) {
reason = GridCellEditStartReasons.printableKeyDown;
} else if ((event.ctrlKey || event.metaKey) && event.key === 'v') {
reason = GridCellEditStartReasons.printableKeyDown;
} else if (event.key === 'Enter') {
reason = GridCellEditStartReasons.enterKeyDown;
} else if (event.key === 'Delete' || event.key === 'Backspace') {
// Delete on Windows, Backspace on macOS
reason = GridCellEditStartReasons.deleteKeyDown;
}
if (reason) {
const newParams: GridCellEditStartParams = { ...params, reason, key: event.key };
apiRef.current.publishEvent('cellEditStart', newParams, event);
}
}
},
[apiRef],
);
const handleCellEditStart = React.useCallback<GridEventListener<'cellEditStart'>>(
(params) => {
const { id, field, reason, key } = params;
const startCellEditModeParams: GridStartCellEditModeParams = { id, field };
if (reason === GridCellEditStartReasons.printableKeyDown) {
if (React.version.startsWith('18')) {
startCellEditModeParams.initialValue = key; // In React 17, cleaning the input is enough
} else {
startCellEditModeParams.deleteValue = true;
}
} else if (reason === GridCellEditStartReasons.deleteKeyDown) {
startCellEditModeParams.deleteValue = true;
}
apiRef.current.startCellEditMode(startCellEditModeParams);
},
[apiRef],
);
const handleCellEditStop = React.useCallback<GridEventListener<'cellEditStop'>>(
(params) => {
const { id, field, reason } = params;
apiRef.current.unstable_runPendingEditCellValueMutation(id, field);
let cellToFocusAfter: GridStopCellEditModeParams['cellToFocusAfter'];
if (reason === GridCellEditStopReasons.enterKeyDown) {
cellToFocusAfter = 'below';
} else if (reason === GridCellEditStopReasons.tabKeyDown) {
cellToFocusAfter = 'right';
} else if (reason === GridCellEditStopReasons.shiftTabKeyDown) {
cellToFocusAfter = 'left';
}
let ignoreModifications = reason === 'escapeKeyDown';
const editingState = gridEditRowsStateSelector(apiRef.current.state);
if (
editingState[id][field].isProcessingProps &&
!props.disableIgnoreModificationsIfProcessingProps
) {
// The user wants to stop editing the cell but we can't wait for the props to be processed.
// In this case, discard the modifications.
ignoreModifications = true;
}
apiRef.current.stopCellEditMode({
id,
field,
ignoreModifications,
cellToFocusAfter,
});
},
[apiRef, props.disableIgnoreModificationsIfProcessingProps],
);
useGridApiEventHandler(apiRef, 'cellDoubleClick', runIfEditModeIsCell(handleCellDoubleClick));
useGridApiEventHandler(apiRef, 'cellFocusOut', runIfEditModeIsCell(handleCellFocusOut));
useGridApiEventHandler(apiRef, 'cellKeyDown', runIfEditModeIsCell(handleCellKeyDown));
useGridApiEventHandler(apiRef, 'cellEditStart', runIfEditModeIsCell(handleCellEditStart));
useGridApiEventHandler(apiRef, 'cellEditStop', runIfEditModeIsCell(handleCellEditStop));
useGridApiOptionHandler(apiRef, 'cellEditStart', props.onCellEditStart);
useGridApiOptionHandler(apiRef, 'cellEditStop', props.onCellEditStop);
const getCellMode = React.useCallback<GridNewCellEditingApi['getCellMode']>(
(id, field) => {
const editingState = gridEditRowsStateSelector(apiRef.current.state);
const isEditing = editingState[id] && editingState[id][field];
return isEditing ? GridCellModes.Edit : GridCellModes.View;
},
[apiRef],
);
const updateCellModesModel = useEventCallback((newModel: GridCellModesModel) => {
const isNewModelDifferentFromProp = newModel !== props.cellModesModel;
if (onCellModesModelChange && isNewModelDifferentFromProp) {
const details = signature === GridSignature.DataGridPro ? { api: apiRef.current } : {};
onCellModesModelChange(newModel, details);
}
if (props.cellModesModel && isNewModelDifferentFromProp) {
return; // The prop always win
}
setCellModesModel(newModel);
cellModesModelRef.current = newModel;
apiRef.current.publishEvent('cellModesModelChange', newModel);
});
const updateFieldInCellModesModel = React.useCallback(
(id: GridRowId, field: string, newProps: GridCellModesModelProps | null) => {
// We use the ref because it always contain the up-to-date value, different from the state
// that needs a rerender to reflect the new value
const newModel = { ...cellModesModelRef.current };
if (newProps !== null) {
newModel[id] = { ...newModel[id], [field]: { ...newProps } };
} else {
const { [field]: fieldToRemove, ...otherFields } = newModel[id]; // Ensure that we have a new object, not a reference
newModel[id] = otherFields;
if (Object.keys(newModel[id]).length === 0) {
delete newModel[id];
}
}
updateCellModesModel(newModel);
},
[updateCellModesModel],
);
const updateOrDeleteFieldState = React.useCallback(
(id: GridRowId, field: string, newProps: GridEditCellProps | null) => {
apiRef.current.setState((state) => {
const newEditingState: GridEditingState = { ...state.editRows };
if (newProps !== null) {
newEditingState[id] = { ...newEditingState[id], [field]: { ...newProps } };
} else {
delete newEditingState[id][field];
if (Object.keys(newEditingState[id]).length === 0) {
delete newEditingState[id];
}
}
return { ...state, editRows: newEditingState };
});
apiRef.current.forceUpdate();
},
[apiRef],
);
const startCellEditMode = React.useCallback<GridNewCellEditingApi['startCellEditMode']>(
(params) => {
const { id, field, ...other } = params;
throwIfNotEditable(id, field);
throwIfNotInMode(id, field, GridCellModes.View);
updateFieldInCellModesModel(id, field, { mode: GridCellModes.Edit, ...other });
},
[throwIfNotEditable, throwIfNotInMode, updateFieldInCellModesModel],
);
const updateStateToStartCellEditMode = useEventCallback<[GridStartCellEditModeParams], void>(
(params) => {
const { id, field, deleteValue, initialValue } = params;
let newValue = apiRef.current.getCellValue(id, field);
if (deleteValue || initialValue) {
newValue = deleteValue ? '' : initialValue;
}
const newProps = {
value: newValue,
error: false,
isProcessingProps: false,
};
updateOrDeleteFieldState(id, field, newProps);
apiRef.current.setCellFocus(id, field);
},
) as GridNewCellEditingApi['startCellEditMode'];
const stopCellEditMode = React.useCallback<GridNewCellEditingApi['stopCellEditMode']>(
(params) => {
const { id, field, ...other } = params;
throwIfNotInMode(id, field, GridCellModes.Edit);
updateFieldInCellModesModel(id, field, { mode: GridCellModes.View, ...other });
},
[throwIfNotInMode, updateFieldInCellModesModel],
);
const updateStateToStopCellEditMode = useEventCallback<[GridStopCellEditModeParams], void>(
async (params) => {
const { id, field, ignoreModifications, cellToFocusAfter = 'none' } = params;
throwIfNotInMode(id, field, GridCellModes.Edit);
apiRef.current.unstable_runPendingEditCellValueMutation(id, field);
const finishCellEditMode = () => {
updateOrDeleteFieldState(id, field, null);
updateFieldInCellModesModel(id, field, null);
if (cellToFocusAfter !== 'none') {
apiRef.current.unstable_moveFocusToRelativeCell(id, field, cellToFocusAfter);
}
};
if (ignoreModifications) {
finishCellEditMode();
return;
}
const editingState = gridEditRowsStateSelector(apiRef.current.state);
const { error, isProcessingProps } = editingState[id][field];
if (error || isProcessingProps) {
// Attempt to change cell mode to "view" was not successful
// Update previous mode to allow another attempt
prevCellModesModel.current[id][field].mode = GridCellModes.Edit;
// Revert the mode in the cellModesModel prop back to "edit"
updateFieldInCellModesModel(id, field, { mode: GridCellModes.Edit });
return;
}
const rowUpdate = apiRef.current.unstable_getRowWithUpdatedValuesFromCellEditing(id, field);
if (processRowUpdate) {
const handleError = (errorThrown: any) => {
prevCellModesModel.current[id][field].mode = GridCellModes.Edit;
// Revert the mode in the cellModesModel prop back to "edit"
updateFieldInCellModesModel(id, field, { mode: GridCellModes.Edit });
if (onProcessRowUpdateError) {
onProcessRowUpdateError(errorThrown);
} else {
missingOnProcessRowUpdateErrorWarning();
}
};
try {
const row = apiRef.current.getRow(id)!;
Promise.resolve(processRowUpdate(rowUpdate, row))
.then((finalRowUpdate) => {
apiRef.current.updateRows([finalRowUpdate]);
finishCellEditMode();
})
.catch(handleError);
} catch (errorThrown) {
handleError(errorThrown);
}
} else {
apiRef.current.updateRows([rowUpdate]);
finishCellEditMode();
}
},
) as GridNewCellEditingApi['stopCellEditMode'];
const setCellEditingEditCellValue = React.useCallback<
GridNewCellEditingApi['unstable_setCellEditingEditCellValue']
>(
async (params) => {
const { id, field, value, debounceMs, unstable_skipValueParser: skipValueParser } = params;
throwIfNotEditable(id, field);
throwIfNotInMode(id, field, GridCellModes.Edit);
const column = apiRef.current.getColumn(field);
const row = apiRef.current.getRow(id)!;
let parsedValue = value;
if (column.valueParser && !skipValueParser) {
parsedValue = column.valueParser(value, apiRef.current.getCellParams(id, field));
}
let editingState = gridEditRowsStateSelector(apiRef.current.state);
let newProps: GridEditCellProps = {
...editingState[id][field],
value: parsedValue,
changeReason: debounceMs ? 'debouncedSetEditCellValue' : 'setEditCellValue',
};
if (column.preProcessEditCellProps) {
const hasChanged = value !== editingState[id][field].value;
newProps = { ...newProps, isProcessingProps: true };
updateOrDeleteFieldState(id, field, newProps);
newProps = await Promise.resolve(
column.preProcessEditCellProps({ id, row, props: newProps, hasChanged }),
);
}
// Check again if the cell is in edit mode because the user may have
// discarded the changes while the props were being processed.
if (apiRef.current.getCellMode(id, field) === GridCellModes.View) {
return false;
}
editingState = gridEditRowsStateSelector(apiRef.current.state);
newProps = { ...newProps, isProcessingProps: false };
// We don't update the value with the one coming from the props pre-processing
// because when the promise resolves it may be already outdated. The only
// exception to this rule is when there's no pre-processing.
newProps.value = column.preProcessEditCellProps ? editingState[id][field].value : parsedValue;
updateOrDeleteFieldState(id, field, newProps);
editingState = gridEditRowsStateSelector(apiRef.current.state);
return !editingState[id]?.[field]?.error;
},
[apiRef, throwIfNotEditable, throwIfNotInMode, updateOrDeleteFieldState],
);
const getRowWithUpdatedValuesFromCellEditing = React.useCallback<
GridNewCellEditingApi['unstable_getRowWithUpdatedValuesFromCellEditing']
>(
(id, field) => {
const column = apiRef.current.getColumn(field);
const editingState = gridEditRowsStateSelector(apiRef.current.state);
const { value } = editingState[id][field];
const row = apiRef.current.getRow(id)!;
return column.valueSetter ? column.valueSetter({ value, row }) : { ...row, [field]: value };
},
[apiRef],
);
const editingApi: Omit<GridNewCellEditingApi, keyof GridNewEditingSharedApi> = {
getCellMode,
startCellEditMode,
stopCellEditMode,
unstable_setCellEditingEditCellValue: setCellEditingEditCellValue,
unstable_getRowWithUpdatedValuesFromCellEditing: getRowWithUpdatedValuesFromCellEditing,
};
useGridApiMethod(apiRef, editingApi, 'EditingApi');
React.useEffect(() => {
if (cellModesModelProp) {
updateCellModesModel(cellModesModelProp);
}
}, [cellModesModelProp, updateCellModesModel]);
React.useEffect(() => {
const idToIdLookup = gridRowsIdToIdLookupSelector(apiRef);
// Update the ref here because updateStateToStopCellEditMode may change it later
const copyOfPrevCellModes = prevCellModesModel.current;
prevCellModesModel.current = deepClone(cellModesModel); // Do a deep-clone because the attributes might be changed later
Object.entries(cellModesModel).forEach(([id, fields]) => {
Object.entries(fields).forEach(([field, params]) => {
const prevMode = copyOfPrevCellModes[id]?.[field]?.mode || GridCellModes.View;
const originalId = idToIdLookup[id] ?? id;
if (params.mode === GridCellModes.Edit && prevMode === GridCellModes.View) {
updateStateToStartCellEditMode({ id: originalId, field, ...params });
} else if (params.mode === GridCellModes.View && prevMode === GridCellModes.Edit) {
updateStateToStopCellEditMode({ id: originalId, field, ...params });
}
});
});
}, [apiRef, cellModesModel, updateStateToStartCellEditMode, updateStateToStopCellEditMode]);
};