Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 19x 88x 33x 88x 88x 88x 88x 88x 6x 6x 6x 88x 19x 1x 18x 18x 18x 18x 18x 16x 2x 2x 18x 88x 11x 15x 4x 23x 23x 4x 19x 10x 10x 9x 5x 5x 12x | import React, { useRef, useState } from 'react';
import { Alert, Box, MenuItem, TextField } from '@mui/material';
import { useStrings } from '../../strings';
import { EditableTableCellV2, EditableTableColumnV2 } from './types';
type Props<TData extends object> = {
cell: EditableTableCellV2<TData>;
column: EditableTableColumnV2<TData>;
onClose: () => void;
};
const EditableCellV2 = <TData extends object>({ cell, column, onClose }: Props<TData>) => {
const strings = useStrings();
const [value, setValue] = useState(() => cell.getValue<string | number | null>() ?? '');
const [isSaving, setIsSaving] = useState(false);
const [failed, setFailed] = useState(false);
const finished = useRef(false);
const config = column.editConfig;
const cancel = () => {
Eif (!isSaving) {
finished.current = true;
onClose();
}
};
const save = async (nextValue: unknown) => {
if (finished.current) {
return;
}
finished.current = true;
setIsSaving(true);
setFailed(false);
try {
await config?.onSave?.(cell.row.original, nextValue, column.id);
onClose();
} catch {
finished.current = false;
setFailed(true);
} finally {
setIsSaving(false);
}
};
return (
<Box onClick={(event) => event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()}>
{config?.editVariant === 'custom' && config.customEditComponent ? (
config.customEditComponent({ ...cell.getContext(), save, cancel, isSaving })
) : (
<TextField
autoFocus
fullWidth
size='small'
select={config?.editVariant === 'select'}
value={value}
disabled={isSaving}
error={failed}
slotProps={{ htmlInput: { 'aria-label': column.header } }}
onChange={(event) => setValue(event.target.value)}
onBlur={() => void save(value)}
onKeyDown={(event) => {
event.stopPropagation();
if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {
return;
}
if (event.key === 'Enter' && config?.editVariant !== 'select') {
event.preventDefault();
void save(value);
} else if (event.key === 'Escape') {
event.preventDefault();
cancel();
}
}}
>
{config?.editVariant === 'select' &&
config.selectOptions?.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
)}
{failed && <Alert severity='error'>{strings.UNABLE_TO_SAVE_CHANGES_PLEASE_TRY_AGAIN}</Alert>}
</Box>
);
};
export default EditableCellV2;
|