drf-react-by-schema 0.22.4 → 0.23.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 (94) hide show
  1. package/dist/@types/index.d.ts +25 -14
  2. package/dist/@types/index.d.ts.map +1 -1
  3. package/dist/api.d.ts +7 -11
  4. package/dist/api.d.ts.map +1 -1
  5. package/dist/api.js +50 -28
  6. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.d.ts +4 -21
  7. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.d.ts.map +1 -1
  8. package/dist/components/DataGridBySchemaEditable/BooleanInputCell.js +64 -19
  9. package/dist/components/DataGridBySchemaEditable/CustomToolbar.d.ts.map +1 -1
  10. package/dist/components/DataGridBySchemaEditable/CustomToolbar.js +6 -4
  11. package/dist/components/DataGridBySchemaEditable/DataGridDesktop.d.ts +8 -8
  12. package/dist/components/DataGridBySchemaEditable/DataGridDesktop.d.ts.map +1 -1
  13. package/dist/components/DataGridBySchemaEditable/DataGridDesktop.js +234 -737
  14. package/dist/components/DataGridBySchemaEditable/DataGridMobile.js +1 -1
  15. package/dist/components/DataGridBySchemaEditable/FileInputCell.d.ts +4 -21
  16. package/dist/components/DataGridBySchemaEditable/FileInputCell.d.ts.map +1 -1
  17. package/dist/components/DataGridBySchemaEditable/FileInputCell.js +62 -21
  18. package/dist/components/DataGridBySchemaEditable/FooterToolbar.d.ts +5 -1
  19. package/dist/components/DataGridBySchemaEditable/FooterToolbar.d.ts.map +1 -1
  20. package/dist/components/DataGridBySchemaEditable/FooterToolbar.js +18 -2
  21. package/dist/components/DataGridBySchemaEditable/GridDateInput.d.ts +4 -9
  22. package/dist/components/DataGridBySchemaEditable/GridDateInput.d.ts.map +1 -1
  23. package/dist/components/DataGridBySchemaEditable/GridDateInput.js +125 -5
  24. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts +4 -9
  25. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts.map +1 -1
  26. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.js +51 -7
  27. package/dist/components/DataGridBySchemaEditable/GridGenericInput.d.ts +8 -0
  28. package/dist/components/DataGridBySchemaEditable/GridGenericInput.d.ts.map +1 -0
  29. package/dist/components/DataGridBySchemaEditable/GridGenericInput.js +30 -0
  30. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts +4 -7
  31. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts.map +1 -1
  32. package/dist/components/DataGridBySchemaEditable/GridPatternInput.js +59 -5
  33. package/dist/components/DataGridBySchemaEditable/InputInterval.d.ts +2 -2
  34. package/dist/components/DataGridBySchemaEditable/InputInterval.d.ts.map +1 -1
  35. package/dist/components/DataGridBySchemaEditable/InputInterval.js +23 -4
  36. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts +4 -1
  37. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts.map +1 -1
  38. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.js +72 -25
  39. package/dist/components/DataGridBySchemaEditable/hooks/useDataGridActions.d.ts +34 -0
  40. package/dist/components/DataGridBySchemaEditable/hooks/useDataGridActions.d.ts.map +1 -0
  41. package/dist/components/DataGridBySchemaEditable/hooks/useDataGridActions.js +170 -0
  42. package/dist/components/DataGridBySchemaEditable/hooks/useOptionsAC.d.ts +14 -0
  43. package/dist/components/DataGridBySchemaEditable/hooks/useOptionsAC.d.ts.map +1 -0
  44. package/dist/components/DataGridBySchemaEditable/hooks/useOptionsAC.js +67 -0
  45. package/dist/components/DataGridBySchemaEditable/hooks/usePreparedColumns.d.ts +9 -0
  46. package/dist/components/DataGridBySchemaEditable/hooks/usePreparedColumns.d.ts.map +1 -0
  47. package/dist/components/DataGridBySchemaEditable/hooks/usePreparedColumns.js +68 -0
  48. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.d.ts +33 -0
  49. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.d.ts.map +1 -0
  50. package/dist/components/DataGridBySchemaEditable/hooks/useProcessRowUpdate.js +219 -0
  51. package/dist/components/DataGridBySchemaEditable/hooks/useRowMode.d.ts +18 -0
  52. package/dist/components/DataGridBySchemaEditable/hooks/useRowMode.d.ts.map +1 -0
  53. package/dist/components/DataGridBySchemaEditable/hooks/useRowMode.js +43 -0
  54. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.d.ts +30 -0
  55. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.d.ts.map +1 -0
  56. package/dist/components/DataGridBySchemaEditable/utils/columnFactory.js +180 -0
  57. package/dist/components/DataGridBySchemaEditable.d.ts +2 -1
  58. package/dist/components/DataGridBySchemaEditable.d.ts.map +1 -1
  59. package/dist/components/DataGridBySchemaEditable.js +5 -4
  60. package/dist/components/GenericModelList.d.ts.map +1 -1
  61. package/dist/components/GenericModelList.js +13 -8
  62. package/dist/components/GenericRelatedModelList.d.ts.map +1 -1
  63. package/dist/components/GenericRelatedModelList.js +13 -8
  64. package/dist/components/GenericRelatedModelListTable.d.ts +3 -2
  65. package/dist/components/GenericRelatedModelListTable.d.ts.map +1 -1
  66. package/dist/components/GenericRelatedModelListTable.js +3 -3
  67. package/dist/components/details/DetailBySchema.js +2 -2
  68. package/dist/components/details/DetailFieldBySchema.d.ts.map +1 -1
  69. package/dist/components/details/DetailFieldBySchema.js +3 -0
  70. package/dist/components/forms/DialogFormBySchema.d.ts +4 -3
  71. package/dist/components/forms/DialogFormBySchema.d.ts.map +1 -1
  72. package/dist/components/forms/FieldBySchema.d.ts.map +1 -1
  73. package/dist/components/forms/Form.d.ts +4 -3
  74. package/dist/components/forms/Form.d.ts.map +1 -1
  75. package/dist/components/forms/Form.js +3 -2
  76. package/dist/components/forms/FormBySchema.d.ts +3 -2
  77. package/dist/components/forms/FormBySchema.d.ts.map +1 -1
  78. package/dist/components/forms/FormBySchema.js +3 -2
  79. package/dist/context/APIWrapper.d.ts.map +1 -1
  80. package/dist/context/APIWrapper.js +35 -29
  81. package/dist/context/APIWrapperContext.d.ts +17 -14
  82. package/dist/context/APIWrapperContext.d.ts.map +1 -1
  83. package/dist/context/APIWrapperContext.js +12 -10
  84. package/dist/context/DRFReactBySchemaProvider.d.ts.map +1 -1
  85. package/dist/context/DRFReactBySchemaProvider.js +2 -1
  86. package/dist/styles/grid.d.ts +3 -0
  87. package/dist/styles/grid.d.ts.map +1 -0
  88. package/dist/styles/grid.js +42 -0
  89. package/dist/styles/theme.d.ts.map +1 -1
  90. package/dist/styles/theme.js +17 -7
  91. package/dist/utils.d.ts +2 -2
  92. package/dist/utils.d.ts.map +1 -1
  93. package/dist/utils.js +24 -28
  94. package/package.json +9 -8
@@ -32,776 +32,260 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
45
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
46
37
  };
47
38
  Object.defineProperty(exports, "__esModule", { value: true });
48
39
  const react_1 = __importStar(require("react"));
49
- const dayjs_1 = __importDefault(require("dayjs"));
50
40
  const x_data_grid_1 = require("@mui/x-data-grid");
51
- const string_mask_1 = __importDefault(require("string-mask"));
41
+ const Check_1 = __importDefault(require("@mui/icons-material/Check"));
42
+ const Close_1 = __importDefault(require("@mui/icons-material/Close"));
43
+ const Edit_1 = __importDefault(require("@mui/icons-material/Edit"));
44
+ const Delete_1 = __importDefault(require("@mui/icons-material/Delete"));
52
45
  const Box_1 = __importDefault(require("@mui/material/Box"));
53
- const Typography_1 = __importDefault(require("@mui/material/Typography"));
54
46
  const CircularProgress_1 = __importDefault(require("@mui/material/CircularProgress"));
55
- const Edit_1 = __importDefault(require("@mui/icons-material/Edit"));
56
- const Bolt_1 = __importDefault(require("@mui/icons-material/Bolt"));
57
- const Visibility_1 = __importDefault(require("@mui/icons-material/Visibility"));
58
- const Clear_1 = __importDefault(require("@mui/icons-material/Clear"));
59
- const Check_1 = __importDefault(require("@mui/icons-material/Check"));
60
- const Undo_1 = __importDefault(require("@mui/icons-material/Undo"));
61
47
  const styles_1 = require("../../styles");
62
- const api_1 = require("../../api");
63
- const utils_1 = require("../../utils");
64
- const utils_2 = require("./utils");
65
- const DRFReactBySchemaContext_1 = require("../../context/DRFReactBySchemaContext");
66
48
  const APIWrapperContext_1 = require("../../context/APIWrapperContext");
49
+ const utils_1 = require("../../utils");
67
50
  const CustomToolbar_1 = require("./CustomToolbar");
68
- const SelectEditInputCell_1 = require("./SelectEditInputCell");
69
- const GridDateInput_1 = require("./GridDateInput");
70
- const GridDecimalInput_1 = require("./GridDecimalInput");
71
- const GridPatternInput_1 = require("./GridPatternInput");
72
- const BooleanInputCell_1 = require("./BooleanInputCell");
73
- const FileInputCell_1 = require("./FileInputCell");
74
51
  const FooterToolbar_1 = require("./FooterToolbar");
75
- function DataGridDesktop({ schema, dataGrid, setDataGrid, rowCount = 0, columns, model, name = Math.floor(Math.random() * 1000000).toString(), indexField = 'nome', addExistingModel, indexFieldMinWidth = 350, indexFieldBasePath = '', indexFieldViewBasePath, stateToLink = {}, minWidth = 80, loading, modelParent, modelParentId, customColumnOperations, customFieldFormLayouts, customLinkDestination, LinkComponent, onProcessRow, onDataChange, onEditModel, isEditable = false, hasBulkSelect = false, onSelectActions, isAutoHeight = false, hideFooterPagination = false, setVisibleRows, paginationModel = undefined, setPaginationModel = undefined, hideFooterComponent, hideToolbarComponent, tableAutoHeight, actions = ['editInline', 'remove'], customActions, hideColumnsButton, hideFilterButton, hideDensityButton, hideExportButton, hideQuickFilterBar, optionsAC: optionsACExternal, emptyItem, handleDeleteClick, setSnackBar, yupValidationSchema, }) {
76
- const { serverEndPoint } = (0, DRFReactBySchemaContext_1.useDRFReactBySchema)();
77
- const { onEditModel: APIOnEditModel, setDialog, onEditRelatedModelSave, onEditModelDataGridSave, } = (0, APIWrapperContext_1.useAPIWrapper)();
78
- const [preparedColumns, setPreparedColumns] = (0, react_1.useState)(null);
52
+ const useOptionsAC_1 = require("./hooks/useOptionsAC");
53
+ const usePreparedColumns_1 = require("./hooks/usePreparedColumns");
54
+ const useDataGridActions_1 = require("./hooks/useDataGridActions");
55
+ const useProcessRowUpdate_1 = require("./hooks/useProcessRowUpdate");
56
+ function DataGridDesktop({ schema, dataGrid, setDataGrid, rowCount = 0, columns, columnVisibilityModel, model, name = Math.floor(Math.random() * 1000000).toString(), indexField = 'nome', addExistingModel, indexFieldMinWidth = 350, indexFieldBasePath = '', indexFieldViewBasePath, stateToLink = {}, minWidth = 80, loading, modelParent, modelParentId, customColumnOperations, customFieldFormLayouts, customLinkDestination, LinkComponent, onProcessRow, onDataChange, onEditModel, isEditable = false, hasBulkSelect, onSelectActions, sx: sxProp, isAutoHeight, defaultValues, hideFooterPagination, setVisibleRows, paginationModel, setPaginationModel, hideFooterComponent, hideToolbarComponent, tableAutoHeight, actions = ['editInline', 'remove'], customActions, hideColumnsButton, hideFilterButton, hideDensityButton, hideExportButton, hideQuickFilterBar, optionsAC: optionsACExternal, extraValidators, emptyItem, handleDeleteClick, setSnackBar, yupValidationSchema, }) {
79
57
  const [dataGridLoading, setDataGridLoading] = (0, react_1.useState)(false);
80
- const [rowModesModel, setRowModesModel] = (0, react_1.useState)();
58
+ const [isRowEditing, setIsRowEditing] = (0, react_1.useState)();
59
+ const [validationErrors, setValidationErrors] = (0, react_1.useState)({});
81
60
  const [selectionModel, setSelectionModel] = (0, react_1.useState)([]);
82
61
  const [selectionModelIds, setSelectionModelIds] = (0, react_1.useState)([]);
83
- const optionsAC = (0, react_1.useRef)(null);
84
62
  const processingRow = (0, react_1.useRef)(null);
85
- const visibleRows = (0, react_1.useRef)('');
63
+ const apiRef = (0, x_data_grid_1.useGridApiRef)();
64
+ const handleStopEditing = () => {
65
+ setIsRowEditing(undefined);
66
+ };
67
+ const handleStartEditing = (id) => {
68
+ setIsRowEditing(id);
69
+ };
70
+ const { setDialog, onEditModel: APIOnEditModel } = (0, APIWrapperContext_1.useAPIWrapper)();
86
71
  if (!onEditModel) {
87
72
  onEditModel = APIOnEditModel;
88
73
  }
89
- const updateOptionsAC = () => __awaiter(this, void 0, void 0, function* () {
90
- var _a;
91
- optionsAC.current = {};
92
- for (const col of columns) {
93
- if (optionsACExternal && col.field in optionsACExternal) {
94
- optionsAC.current[col.field] = optionsACExternal[col.field];
95
- continue;
96
- }
97
- if (!schema[col.field]) {
98
- continue;
99
- }
100
- const fieldSchema = schema[col.field];
101
- if (['field', 'nested object'].includes(fieldSchema.type) &&
102
- !(col.field in optionsAC.current)) {
103
- const options = yield (0, api_1.getAutoComplete)({
104
- model: col.field,
105
- serverEndPoint,
106
- });
107
- if (options) {
108
- optionsAC.current[col.field] = options;
109
- continue;
110
- }
111
- console.log(`Couldn't load autocomplete options from '${col.field}'`);
112
- continue;
113
- }
114
- if (fieldSchema.type === 'choice' && !(col.field in optionsAC.current)) {
115
- optionsAC.current[col.field] = fieldSchema.choices || [];
116
- continue;
117
- }
118
- if (fieldSchema.type === 'list' && !(col.field in optionsAC.current)) {
119
- optionsAC.current[col.field] = ((_a = fieldSchema.child) === null || _a === void 0 ? void 0 : _a.choices) || [];
120
- continue;
121
- }
122
- if (col.field === indexField && addExistingModel && !optionsAC.current[col.field]) {
123
- const options = yield (0, api_1.getAutoComplete)({
124
- model: addExistingModel,
125
- serverEndPoint,
126
- });
127
- if (options) {
128
- optionsAC.current[col.field] = options;
129
- continue;
130
- }
131
- if (!(col.field in optionsAC.current)) {
132
- delete optionsAC.current[col.field];
133
- }
134
- }
74
+ const handleSaveRow = (0, react_1.useCallback)((id) => {
75
+ if (id) {
76
+ apiRef.current.stopRowEditMode({ id });
135
77
  }
136
- });
137
- const ActionElement = ({ Icon, label }) => (
138
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
139
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { icon: Icon, label: label, color: "inherit", showInMenu: false, placeholder: "" }));
140
- const initColumns = () => __awaiter(this, void 0, void 0, function* () {
141
- const actionCols = [];
142
- if (isEditable) {
143
- const handleSaveClick = (id) => () => {
144
- if (id) {
145
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View } }));
146
- }
147
- };
148
- const handleCancelClick = (id) => () => {
149
- if (id) {
150
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View, ignoreModifications: true } }));
151
- }
152
- setDataGrid((currentDataGrid) => {
153
- const editedRow = currentDataGrid.data.find((row) => row.id === id);
154
- if (editedRow && editedRow.isNew) {
155
- return Object.assign(Object.assign({}, currentDataGrid), { data: currentDataGrid.data.filter((row) => row.id !== id) });
156
- }
157
- return currentDataGrid;
158
- });
159
- };
160
- const handleEditInlineClick = (id) => () => {
161
- if (id) {
162
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.Edit } }));
163
- }
164
- };
165
- actionCols.push({
166
- field: 'actions',
167
- headerName: '',
168
- type: 'actions',
169
- getActions: ({ id }) => {
170
- var _a;
171
- if (!id) {
172
- return [];
173
- }
174
- const isInEditMode = ((_a = rowModesModel === null || rowModesModel === void 0 ? void 0 : rowModesModel[id]) === null || _a === void 0 ? void 0 : _a.mode) === x_data_grid_1.GridRowModes.Edit;
175
- if (isInEditMode) {
176
- return [
177
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
178
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `save_${id}`, icon: react_1.default.createElement(Check_1.default, null), label: "Salvar", onClick: handleSaveClick(id), color: "success", showInMenu: false, placeholder: "" }),
179
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
180
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `cancel_${id}`, icon: react_1.default.createElement(Undo_1.default, null), label: "Cancelar", onClick: handleCancelClick(id), color: "inherit", showInMenu: false, placeholder: "" }),
181
- ];
182
- }
183
- const actionItems = [];
184
- actions.forEach((action) => {
185
- switch (action) {
186
- case 'editInline':
187
- actionItems.push(
188
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
189
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `editInline_${id}`, icon: actions.includes('edit') ? react_1.default.createElement(Bolt_1.default, null) : react_1.default.createElement(Edit_1.default, null), label: "Editar essa linha na tabela", onClick: handleEditInlineClick(id), color: "inherit", showInMenu: false, placeholder: "" }));
190
- break;
191
- case 'remove':
192
- actionItems.push(
193
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
194
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `remove_${id}`, icon: react_1.default.createElement(Clear_1.default, null), label: "Apagar essa linha", onClick: handleDeleteClick(id), color: "error", showInMenu: false, placeholder: "" }));
195
- break;
196
- case 'edit':
197
- if (!LinkComponent) {
198
- console.log('you must pass LinkComponent prop to navigate externally');
199
- break;
200
- }
201
- actionItems.push(react_1.default.createElement(LinkComponent, { key: `edit_${id}`, to: (0, utils_2.buildEditPath)(indexFieldBasePath, id), state: stateToLink },
202
- react_1.default.createElement(ActionElement, { Icon: react_1.default.createElement(Edit_1.default, null), label: "Editar esse item em janela separada" })));
203
- break;
204
- case 'view':
205
- if (!LinkComponent) {
206
- console.log('you must pass LinkComponent prop to navigate externally');
207
- break;
208
- }
209
- if (!indexFieldViewBasePath) {
210
- console.log('For view action to work, you must supply indexFieldViewBasePath prop!');
211
- break;
212
- }
213
- actionItems.push(react_1.default.createElement(LinkComponent, { key: `view_${id}`, to: `${indexFieldViewBasePath}${id}`, state: stateToLink },
214
- react_1.default.createElement(ActionElement, { Icon: react_1.default.createElement(Visibility_1.default, null), label: "Visualizar esse item em janela separada" })));
215
- break;
216
- }
217
- });
218
- // React.ReactElement<any, string | React.JSXElementConstructor<any>>
219
- // React.ReactElement<any, string | React.JSXElementConstructor<any>>
220
- if (customActions) {
221
- customActions.forEach((customAction) => {
222
- actionItems.push(
223
- // @ts-expect-error - Ignore missing event handlers (they don't actually exist)
224
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `${customAction.key}_${id}`, icon: customAction.icon, label: customAction.label, onClick: () => customAction.handleClick(dataGrid.data.find((row) => row.id === id)), showInMenu: false, placeholder: "" }));
225
- });
226
- }
227
- return actionItems;
228
- },
229
- });
230
- }
231
- const cols = [...actionCols, ...columns];
232
- const colsPromises = cols.map((col) => __awaiter(this, void 0, void 0, function* () {
233
- if (!schema[col.field]) {
234
- return col;
235
- }
236
- const fieldSchema = schema[col.field];
237
- const isIndexField = indexField !== '' && col.field === indexField;
238
- let column = col;
239
- if (isIndexField) {
240
- col.isIndexField = true;
241
- }
242
- column.editable =
243
- isEditable &&
244
- !col.disabled &&
245
- (!fieldSchema.read_only || ['field', 'nested object'].includes(fieldSchema.type));
246
- if (['field', 'nested object'].includes(fieldSchema.type)) {
247
- column.creatable =
248
- 'related_editable' in fieldSchema ? fieldSchema.related_editable : column.creatable;
249
- }
250
- switch (fieldSchema.type) {
251
- case 'date':
252
- column.type = 'date';
253
- const dateFormat = (0, utils_1.buildDateFormatBySchema)(fieldSchema.date_views);
254
- column.valueFormatter = (params) => params.value ? (0, dayjs_1.default)(params.value).format(dateFormat) : '';
255
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
256
- type: 'date',
257
- });
258
- if (isEditable && !col.disabled) {
259
- column.renderEditCell = (params) => (react_1.default.createElement(GridDateInput_1.GridDateInput, Object.assign({}, params, { column: column, dateViews: fieldSchema.date_views })));
260
- break;
261
- }
262
- break;
263
- case 'datetime':
264
- column.type = 'dateTime';
265
- column.minWidth = 180;
266
- column.valueFormatter = (params) => params.value ? (0, dayjs_1.default)(params.value).format('DD/MM/YYYY HH:mm') : '';
267
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
268
- type: 'date',
269
- });
270
- break;
271
- case 'nested object':
272
- column.minWidth = 150;
273
- if (isEditable && !col.disabled) {
274
- column.valueFormatter = (params) => {
275
- return !params.value ? '' : params.value.label;
276
- };
277
- // column.filterable = false;
278
- column.sortComparator = (v1, v2, param1, param2) => {
279
- return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.label, v2.label, param1, param2);
280
- };
281
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: fieldSchema.type, options: optionsAC.current && col.field in optionsAC.current
282
- ? optionsAC.current[col.field]
283
- : [], isIndexField: isIndexField, onEditModel: onEditModel, fieldsLayout: customFieldFormLayouts && col.field in customFieldFormLayouts
284
- ? customFieldFormLayouts[col.field]
285
- : undefined, setDialog: setDialog })));
286
- break;
287
- }
288
- column.valueGetter = (params) => {
289
- return !params.value ? '' : params.value.label;
290
- };
291
- break;
292
- case 'field':
293
- column.orderable = false;
294
- if (isEditable && !col.disabled) {
295
- column.minWidth = 300;
296
- column.valueFormatter = (params) => {
297
- return !params.value || !Array.isArray(params.value)
298
- ? ''
299
- : params.value.map((val) => val.label).join(', ');
300
- };
301
- column.filterable = false;
302
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: fieldSchema.type, options: optionsAC.current && col.field in optionsAC.current
303
- ? optionsAC.current[col.field]
304
- : [], isIndexField: isIndexField, multiple: fieldSchema.many || false, setDialog: setDialog })));
305
- break;
306
- }
307
- column.valueGetter = (params) => {
308
- return !params.value || !Array.isArray(params.value)
309
- ? ''
310
- : params.value.map((val) => val.label).join(', ');
311
- };
312
- break;
313
- case 'choice':
314
- if (isEditable && !col.disabled) {
315
- column.minWidth = 150;
316
- column.valueFormatter = (params) => {
317
- return !params.value ? '' : params.value.display_name;
318
- };
319
- column.filterable = false;
320
- column.sortComparator = (v1, v2, param1, param2) => {
321
- return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.display_name, v2.display_name, param1, param2);
322
- };
323
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: fieldSchema.type, options: optionsAC.current && col.field in optionsAC.current
324
- ? optionsAC.current[col.field]
325
- : [], isIndexField: isIndexField, setDialog: setDialog })));
326
- break;
327
- }
328
- column.valueGetter = (params) => {
329
- return !params.value ? '' : params.value.display_name;
330
- };
331
- break;
332
- case 'list':
333
- column.orderable = false;
334
- if (isEditable && !col.disabled) {
335
- column.minWidth = 300;
336
- column.valueFormatter = (params) => {
337
- return !params.value || !Array.isArray(params.value)
338
- ? ''
339
- : params.value.map((val) => val.value.display_name).join(', ');
340
- };
341
- column.filterable = false;
342
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: fieldSchema.type, options: optionsAC.current && col.field in optionsAC.current
343
- ? optionsAC.current[col.field]
344
- : [], isIndexField: isIndexField, multiple: true, setDialog: setDialog })));
345
- break;
346
- }
347
- column.valueGetter = (params) => {
348
- return !params.value || !Array.isArray(params.value)
349
- ? ''
350
- : params.value.map((val) => val.label).join(', ');
351
- };
352
- break;
353
- case 'boolean':
354
- if (isEditable && !col.disabled) {
355
- column.valueFormatter = (params) => {
356
- return params.value ? 'Sim' : 'Não';
357
- };
358
- column.renderEditCell = (params) => react_1.default.createElement(BooleanInputCell_1.BooleanInputCell, Object.assign({}, params, { column: column }));
359
- break;
360
- }
361
- column.valueGetter = (params) => {
362
- return params.value ? 'Sim' : 'Não';
363
- };
364
- break;
365
- case 'decimal':
366
- case 'float':
367
- const decimalScale = fieldSchema.decimal_places || 2;
368
- const prefix = fieldSchema.prefix || '';
369
- const suffix = fieldSchema.suffix || '';
370
- const isCurrency = fieldSchema.is_currency;
371
- column.type = 'number';
372
- column.valueFormatter = (params) => {
373
- return !params.value
374
- ? ''
375
- : parseFloat(params.value).toLocaleString('pt-BR', {
376
- minimumFractionDigits: decimalScale,
377
- maximumFractionDigits: decimalScale,
378
- });
379
- };
380
- if (isEditable && !col.disabled) {
381
- column.renderEditCell = (params) => (react_1.default.createElement(GridDecimalInput_1.GridDecimalInput, Object.assign({}, params, { decimalPlaces: decimalScale, isCurrency: isCurrency, prefix: prefix, suffix: suffix, column: column })));
382
- }
383
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
384
- type: 'float',
385
- });
386
- break;
387
- case 'number':
388
- case 'integer':
389
- column.type = 'number';
390
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
391
- type: 'number',
392
- });
393
- break;
394
- case 'image upload':
395
- case 'file upload':
396
- column.filterable = false;
397
- column.orderable = false;
398
- const accept = fieldSchema.allowed_mime_types
399
- ? fieldSchema.allowed_mime_types.join(', ')
400
- : fieldSchema.type === 'image upload'
401
- ? '/image*'
402
- : '*';
403
- column.minWidth = 200;
404
- column.valueFormatter = (params) => {
405
- var _a;
406
- return !((_a = params.value) === null || _a === void 0 ? void 0 : _a.name)
407
- ? ''
408
- : `${params.value.name.split('/').pop()} (${(0, utils_1.formatFileSize)(params.value.size)})`;
409
- };
410
- column.renderCell = (params) => {
411
- var _a, _b;
412
- return (react_1.default.createElement(react_1.default.Fragment, null, !((_a = params.value) === null || _a === void 0 ? void 0 : _a.name) ? null : ((_b = params.value) === null || _b === void 0 ? void 0 : _b.url) &&
413
- fieldSchema.type === 'image upload' ? (react_1.default.createElement("img", { src: `${serverEndPoint === null || serverEndPoint === void 0 ? void 0 : serverEndPoint.url}${params.value.url}`, alt: params.value.name, title: params.value.name, style: {
414
- width: '100%',
415
- maxHeight: '100px',
416
- objectFit: 'cover',
417
- } })) : (react_1.default.createElement(Typography_1.default, { variant: "body2", sx: { mb: 1 } },
418
- params.value.name.split('/').pop(),
419
- " (",
420
- (0, utils_1.formatFileSize)(params.value.size),
421
- ")"))));
422
- };
423
- if (isEditable && !col.disabled) {
424
- column.renderEditCell = (params) => (react_1.default.createElement(FileInputCell_1.FileInputCell, Object.assign({ accept: accept, fileType: fieldSchema.type, column: column, required: (0, utils_1.isFieldRequired)(fieldSchema) }, params)));
425
- }
426
- break;
427
- }
428
- if (indexFieldMinWidth && !column.minWidth) {
429
- column.minWidth = col.field === indexField ? indexFieldMinWidth : minWidth;
430
- }
431
- if (indexField) {
432
- if (col.field === indexField) {
433
- column.flex = 1;
434
- column.renderCell = (params) => {
435
- if (LinkComponent && customLinkDestination && !actions.includes('edit')) {
436
- return (react_1.default.createElement(LinkComponent, { to: `${customLinkDestination(params)}`, state: stateToLink }, params.formattedValue));
437
- }
438
- if (!LinkComponent ||
439
- !indexFieldBasePath ||
440
- actions.includes('edit') ||
441
- (['field', 'nested object'].includes(fieldSchema.type) &&
442
- (!params.row[col.field] || !params.row[col.field].id))) {
443
- return react_1.default.createElement(react_1.default.Fragment, null, params.formattedValue);
444
- }
445
- const targetId = ['field', 'nested object'].includes(fieldSchema.type)
446
- ? params.row[col.field].id.toString()
447
- : params.row.id.toString();
448
- return (react_1.default.createElement(LinkComponent, { to: (0, utils_2.buildEditPath)(indexFieldBasePath, targetId), state: stateToLink }, params.formattedValue));
449
- };
450
- if (isEditable &&
451
- !col.disabled &&
452
- optionsAC.current &&
453
- col.field in optionsAC.current &&
454
- addExistingModel) {
455
- column.renderEditCell = (params) => {
456
- if (!(0, utils_1.isTmpId)(params.id)) {
457
- return react_1.default.createElement(x_data_grid_1.GridEditInputCell, Object.assign({}, params));
458
- }
459
- return (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: fieldSchema.type, options: optionsAC.current && col.field in optionsAC.current
460
- ? optionsAC.current[col.field]
461
- : [], isIndexField: true, setDialog: setDialog })));
462
- };
463
- }
464
- }
465
- }
466
- // format numbers:
467
- if (column.patternFormat) {
468
- column.valueFormatter = (params) => {
469
- if (!params.value || typeof params.value !== 'string') {
470
- return params.value;
471
- }
472
- const formattedValue = new string_mask_1.default(column.patternFormat, {}).apply(params.value);
473
- return formattedValue;
474
- };
475
- if (isEditable && !col.disabled) {
476
- column.renderEditCell = (params) => (react_1.default.createElement(GridPatternInput_1.GridPatternInput, Object.assign({}, params, { patternFormat: column.patternFormat })));
477
- }
478
- }
479
- // Custom column operations:
480
- if (customColumnOperations) {
481
- column = yield customColumnOperations(column);
482
- }
483
- // Finally!
484
- return column;
485
- }));
486
- const finalCols = yield Promise.all(colsPromises);
487
- setPreparedColumns(finalCols);
488
- });
489
- const handleAddItems = (numberOfRows = 1) => {
490
- const newRows = [];
491
- for (let i = 0; i < numberOfRows; i++) {
492
- const id = (0, utils_1.getTmpId)();
493
- newRows.push(Object.assign(Object.assign({}, emptyItem), { id }));
494
- }
495
- const newData = tableAutoHeight
496
- ? [...dataGrid.data, ...newRows]
497
- : [...newRows, ...dataGrid.data];
498
- if (onDataChange) {
499
- onDataChange(newData);
500
- }
501
- setDataGrid({
502
- data: newData,
503
- });
504
- setRowModesModel((oldModel) => {
505
- const newModel = Object.assign({}, oldModel);
506
- newRows.map((newRow) => {
507
- newModel[newRow.id] = { mode: x_data_grid_1.GridRowModes.Edit, fieldToFocus: indexField };
508
- });
509
- return newModel;
510
- });
511
- if (!tableAutoHeight) {
512
- // Ugly hack to scroll to top, since scroll to cell is only available in Pro
513
- const el = document.querySelector(`.dataGrid_${name} .MuiDataGrid-virtualScroller`);
514
- if (el) {
515
- el.scrollTop = 0;
516
- setTimeout(() => {
517
- el.scrollTop = 0;
518
- }, 10);
78
+ }, [apiRef]);
79
+ const handleCancelRow = (0, react_1.useCallback)((id) => {
80
+ if (id) {
81
+ apiRef.current.stopRowEditMode({ id, ignoreModifications: true });
82
+ handleStopEditing();
83
+ if ((0, utils_1.isTmpId)(id)) {
84
+ const newData = dataGrid.data.filter(({ id: rowId }) => id !== rowId);
85
+ setDataGrid({ data: newData });
519
86
  }
520
87
  }
521
- };
522
- const bulkUpdateData = (newData) => __awaiter(this, void 0, void 0, function* () {
523
- const promises = [];
524
- const ids = [];
525
- newData.map((item) => {
526
- promises.push((0, api_1.updateDataBySchema)({
527
- model,
528
- modelObjectId: item.id,
529
- serverEndPoint,
530
- data: item,
531
- schema,
532
- }));
533
- ids.push(item.id);
534
- });
535
- const results = yield Promise.all(promises);
536
- setSelectionModel([]);
537
- setSelectionModelIds([]);
538
- const updatedData = dataGrid.data.map((item) => {
539
- const index = ids.indexOf(item.id);
540
- return index === -1 ? item : newData[index];
541
- });
542
- if (onDataChange) {
543
- onDataChange(updatedData);
544
- }
545
- setDataGrid({
546
- data: updatedData,
547
- });
548
- setSnackBar({
549
- open: true,
550
- severity: 'success',
551
- msg: 'Alterações salvas com sucesso',
552
- });
553
- return results.map((result, index) => {
554
- return {
555
- id: ids[index],
556
- success: 'isAxiosError' in result,
557
- };
558
- });
88
+ }, [apiRef, dataGrid.data]);
89
+ const { optionsAC, updateOptionsAC } = (0, useOptionsAC_1.useOptionsAC)({
90
+ columns,
91
+ schema,
92
+ optionsACExternal,
559
93
  });
560
- const bulkDeleteData = (ids) => __awaiter(this, void 0, void 0, function* () {
561
- const promises = [];
562
- ids.map((id) => {
563
- promises.push((0, api_1.deleteData)(model, serverEndPoint, id));
564
- });
565
- setDataGridLoading(true);
566
- const results = yield Promise.all(promises);
567
- setSelectionModel([]);
568
- setSelectionModelIds([]);
569
- const newData = dataGrid.data.filter(({ id }) => !ids.includes(id));
570
- if (onDataChange) {
571
- onDataChange(newData);
572
- }
573
- setDataGrid({
574
- data: newData,
575
- });
576
- setDataGridLoading(false);
577
- setSnackBar({
578
- open: true,
579
- severity: 'success',
580
- msg: 'Itens apagados com sucesso',
581
- });
582
- return results.map((result, index) => {
583
- return {
584
- id: ids[index],
585
- success: result === true,
586
- };
587
- });
94
+ const { handleAddItem, bulkUpdateData, bulkDeleteData, bulkCreateData } = (0, useDataGridActions_1.useDataGridActions)({
95
+ apiRef,
96
+ dataGrid,
97
+ setDataGrid,
98
+ setSnackBar,
99
+ emptyItem,
100
+ defaultValues,
101
+ model,
102
+ schema,
103
+ setSelectionModel,
104
+ setSelectionModelIds,
105
+ setDataGridLoading,
106
+ indexField,
107
+ handleStartEditing,
108
+ isRowEditing,
588
109
  });
589
- const bulkCreateData = (ids) => __awaiter(this, void 0, void 0, function* () {
590
- handleAddItems(ids.length);
591
- setSelectionModel([]);
592
- setSelectionModelIds([]);
593
- setSnackBar({
594
- open: true,
595
- severity: 'success',
596
- msg: 'Linhas adicionadas com sucesso',
597
- });
110
+ const { preparedColumns, setPreparedColumns } = (0, usePreparedColumns_1.usePreparedColumns)({
111
+ schema,
112
+ columns,
113
+ isEditable,
114
+ actions,
115
+ customActions,
116
+ LinkComponent,
117
+ indexFieldBasePath,
118
+ indexFieldViewBasePath,
119
+ stateToLink,
120
+ validationErrors,
121
+ optionsAC,
122
+ onEditModel,
123
+ customFieldFormLayouts,
124
+ setDialog,
125
+ indexField,
126
+ addExistingModel,
127
+ indexFieldMinWidth,
128
+ minWidth,
129
+ customColumnOperations,
130
+ customLinkDestination,
598
131
  });
599
- (0, react_1.useEffect)(() => {
600
- updateOptionsAC().then(() => {
601
- initColumns();
602
- });
603
- // eslint-disable-next-line react-hooks/exhaustive-deps
604
- }, [rowModesModel, columns]);
605
- const processRowUpdate = (editedRow) => __awaiter(this, void 0, void 0, function* () {
606
- if (!preparedColumns || !yupValidationSchema) {
607
- return false;
608
- }
609
- setDataGridLoading(true);
610
- const indexCol = preparedColumns.find((col) => col.field === indexField);
611
- processingRow.current = editedRow.id;
612
- yield yupValidationSchema.validate(editedRow);
613
- const onlyAddExisting = indexField &&
614
- (0, utils_1.isTmpId)(editedRow.id) &&
615
- editedRow[indexField] &&
616
- !(0, utils_1.isTmpId)(editedRow[indexField].id) &&
617
- (!indexCol || !indexCol.valueFormatter);
618
- const createNewItem = indexField &&
619
- (0, utils_1.isTmpId)(editedRow.id) &&
620
- editedRow[indexField] &&
621
- (0, utils_1.isTmpId)(editedRow[indexField].id);
622
- if (onlyAddExisting) {
623
- const row = {};
624
- row.id_to_add = editedRow[indexField].id;
625
- for (const [key, value] of Object.entries(editedRow[indexField])) {
626
- if (key === 'id') {
627
- row[key] = editedRow.id;
628
- continue;
629
- }
630
- row[key] = value;
631
- }
632
- editedRow = Object.assign({}, row);
633
- }
634
- if (createNewItem && editedRow[indexField]) {
635
- if (editedRow[indexField].inputValue) {
636
- editedRow[indexField] = editedRow[indexField].inputValue;
637
- }
638
- if (addExistingModel) {
639
- editedRow[indexField] = editedRow[indexField].label;
132
+ const { processRowUpdate } = (0, useProcessRowUpdate_1.useProcessRowUpdate)({
133
+ preparedColumns,
134
+ indexField,
135
+ schema,
136
+ model,
137
+ yupValidationSchema,
138
+ extraValidators,
139
+ onEditModel,
140
+ onProcessRow,
141
+ onDataChange,
142
+ updateOptionsAC,
143
+ dataGrid,
144
+ setDataGrid,
145
+ setDataGridLoading,
146
+ setValidationErrors,
147
+ processingRow,
148
+ modelParent,
149
+ modelParentId,
150
+ addExistingModel,
151
+ handleStopEditing,
152
+ });
153
+ const InternalToolbar = (0, react_1.useCallback)((_props) => (react_1.default.createElement(CustomToolbar_1.CustomToolbar, { preparedColumns: preparedColumns || [], setPreparedColumns: setPreparedColumns, selectionModel: selectionModel, onSelectActions: onSelectActions, bulkUpdateData: bulkUpdateData, bulkDeleteData: bulkDeleteData, bulkCreateData: bulkCreateData, hideColumnsButton: hideColumnsButton, hideFilterButton: hideFilterButton, hideDensityButton: hideDensityButton, hideExportButton: hideExportButton, hideQuickFilterBar: hideQuickFilterBar })), [
154
+ preparedColumns,
155
+ selectionModel,
156
+ onSelectActions,
157
+ bulkUpdateData,
158
+ bulkDeleteData,
159
+ bulkCreateData,
160
+ hideColumnsButton,
161
+ hideFilterButton,
162
+ hideDensityButton,
163
+ hideExportButton,
164
+ hideQuickFilterBar,
165
+ ]);
166
+ const actionColumn = (0, react_1.useMemo)(() => ({
167
+ field: 'actions',
168
+ type: 'actions',
169
+ headerName: '',
170
+ width: 100,
171
+ getActions: (params) => {
172
+ const { id } = params;
173
+ if (isRowEditing === id) {
174
+ return [
175
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: "save", icon: react_1.default.createElement(Check_1.default, null), label: "Salvar", onClick: () => handleSaveRow(id), color: "success" }),
176
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: "cancel", icon: react_1.default.createElement(Close_1.default, null), label: "Cancelar", onClick: () => {
177
+ handleCancelRow(id);
178
+ }, color: "inherit" }),
179
+ ];
640
180
  }
641
- }
642
- if (modelParent && modelParentId && onEditRelatedModelSave) {
643
- const response = yield onEditRelatedModelSave({
644
- model: modelParent,
645
- id: modelParentId,
646
- relatedModel: model,
647
- relatedModelId: editedRow.id,
648
- newRow: editedRow,
649
- schema,
650
- onlyAddExisting,
651
- });
652
- if (response !== false && (onlyAddExisting || createNewItem || !onlyAddExisting)) {
653
- updateOptionsAC();
654
- const data = [...dataGrid.data];
655
- const newRow = 'data' in response && 'schema' in response ? response.data : response;
656
- for (const i in data) {
657
- if (data[i].id === editedRow.id) {
658
- data[i] = newRow;
659
- // This is for cases where users want to do custom operations after saving the row,
660
- // like for example make calculations among columns.
661
- if (onProcessRow) {
662
- onProcessRow(data[i]);
181
+ return [
182
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: "edit", icon: react_1.default.createElement(Edit_1.default, null), label: "Editar", onClick: () => {
183
+ const visibleColumns = apiRef.current.getAllColumns();
184
+ const firstEditableCol = visibleColumns.find((col) => col.editable && col.field !== 'actions');
185
+ const fieldToFocus = firstEditableCol === null || firstEditableCol === void 0 ? void 0 : firstEditableCol.field;
186
+ apiRef.current.startRowEditMode({ id, fieldToFocus });
187
+ handleStartEditing(id);
188
+ }, color: "inherit" }),
189
+ react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: "delete", icon: react_1.default.createElement(Delete_1.default, null), label: "Apagar", onClick: () => {
190
+ if ((0, utils_1.isTmpId)(id)) {
191
+ const newData = dataGrid.data.filter(({ id: rowId }) => id !== rowId);
192
+ setDataGrid({ data: newData });
193
+ return;
663
194
  }
664
- // Reflect the changes to the outside, for example for global calculations over all data
665
- if (onDataChange) {
666
- onDataChange(data);
667
- }
668
- setDataGrid({ data });
669
- break;
670
- }
671
- }
672
- setDataGridLoading(false);
673
- return newRow;
674
- }
675
- setDataGridLoading(false);
676
- return false;
677
- }
678
- const response = yield onEditModelDataGridSave({
679
- model,
680
- id: editedRow.id,
681
- newRow: editedRow,
682
- schema,
683
- });
684
- setDataGridLoading(false);
685
- if (response !== false) {
686
- updateOptionsAC();
687
- const data = [...dataGrid.data];
688
- const newRow = response;
689
- for (const i in data) {
690
- if (data[i].id === editedRow.id) {
691
- data[i] = newRow;
692
- // This is for cases where users want to do custom operations after saving the row,
693
- // like for example make calculations among columns.
694
- if (onProcessRow) {
695
- onProcessRow(data[i]);
696
- }
697
- // Reflect the changes to the outside, for example for global calculations over all data
698
- if (onDataChange) {
699
- onDataChange(data);
700
- }
701
- setDataGrid({ data });
702
- break;
703
- }
704
- }
705
- return newRow;
706
- }
707
- return false;
708
- });
709
- const customPaddings = isAutoHeight
710
- ? {
711
- '&.MuiDataGrid-root--densityCompact .MuiDataGrid-cell': {
712
- py: '8px',
713
- },
714
- '&.MuiDataGrid-root--densityStandard .MuiDataGrid-cell': {
715
- py: '15px',
716
- },
717
- '&.MuiDataGrid-root--densityComfortable .MuiDataGrid-cell': {
718
- py: '22px',
719
- },
720
- }
721
- : undefined;
195
+ handleDeleteClick(id);
196
+ }, color: "error" }),
197
+ ];
198
+ },
199
+ }), [apiRef, handleDeleteClick, isRowEditing, dataGrid.data]);
200
+ const InternalFooter = (0, react_1.useCallback)(() => (react_1.default.createElement(FooterToolbar_1.FooterToolbar, { isEditable: isEditable, handleAddItem: handleAddItem, isRowEditing: isRowEditing, handleSaveRow: handleSaveRow, handleCancelRow: handleCancelRow })), [isEditable, handleAddItem, isRowEditing, handleSaveRow, handleCancelRow]);
722
201
  const checkboxSelection = hasBulkSelect ? true : undefined;
723
202
  const disableRowSelectionOnClick = hasBulkSelect ? true : undefined;
724
- return (react_1.default.createElement(Box_1.default, { className: `dataGrid_${name}`, sx: { height: '100%' } }, preparedColumns === null ? (react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.loadingBox },
725
- react_1.default.createElement(CircularProgress_1.default, null))) : (react_1.default.createElement(x_data_grid_1.DataGrid, { rows: dataGrid.data, columns: preparedColumns, autoHeight: tableAutoHeight, onStateChange: (state) => {
726
- if (setVisibleRows) {
727
- const newVisibleRows = Object.entries(state.filter.visibleRowsLookup)
728
- .filter((entry) => {
729
- return entry[1] === true;
730
- })
731
- .map((entry) => {
732
- return entry[0];
733
- });
734
- const newVisibleRowsJSON = JSON.stringify(newVisibleRows);
735
- if (newVisibleRowsJSON !== visibleRows.current) {
736
- setVisibleRows(newVisibleRows);
737
- visibleRows.current = newVisibleRowsJSON;
738
- }
203
+ const sx = Object.assign(Object.assign({}, sxProp), (isAutoHeight || tableAutoHeight
204
+ ? {
205
+ '&.MuiDataGrid-root--densityCompact .MuiDataGrid-cell': { py: '8px' },
206
+ '&.MuiDataGrid-root--densityStandard .MuiDataGrid-cell': { py: '15px' },
207
+ '&.MuiDataGrid-root--densityComfortable .MuiDataGrid-cell': { py: '22px' },
208
+ }
209
+ : {}));
210
+ return (react_1.default.createElement(Box_1.default, { className: `dataGrid_${name}`, sx: Object.assign({ height: '100%', width: '100%', maxWidth: '100%', display: 'grid' }, sxProp) }, preparedColumns === null ? (react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.loadingBox },
211
+ react_1.default.createElement(CircularProgress_1.default, null))) : (react_1.default.createElement(x_data_grid_1.DataGrid, { apiRef: apiRef, rows: dataGrid.data, columns: isEditable ? [actionColumn, ...(preparedColumns || [])] : preparedColumns || [], getCellClassName: ({ id, cellMode, field }) => {
212
+ if (cellMode !== 'edit') {
213
+ return '';
739
214
  }
740
- }, editMode: "row", loading: dataGridLoading || loading, hideFooterPagination: hideFooterPagination, getRowHeight: () => {
741
- if (isAutoHeight) {
215
+ const rowError = validationErrors[id];
216
+ return rowError && rowError[field] ? 'cell--error' : '';
217
+ }, editMode: "row", loading: dataGridLoading || loading, hideFooterPagination: hideFooterPagination, getRowHeight: ({ id }) => {
218
+ if (isRowEditing === id || isAutoHeight || tableAutoHeight) {
742
219
  return 'auto';
743
220
  }
744
221
  return null;
745
- }, isCellEditable: (params) => {
746
- var _a;
747
- const isRowInEditMode = ((_a = rowModesModel === null || rowModesModel === void 0 ? void 0 : rowModesModel[params.row.id]) === null || _a === void 0 ? void 0 : _a.mode) === x_data_grid_1.GridRowModes.Edit;
748
- const isPermanentRow = !(0, utils_1.isTmpId)(params.row.id);
749
- const isIndexField = params.field === indexField;
750
- const indexColumn = preparedColumns.find((col) => col.field === indexField);
222
+ }, isCellEditable: ({ row, field }) => {
223
+ // const isRowEditing = apiRef.current.getRowMode(row.id) === 'edit';
224
+ const isPermanentRow = !(0, utils_1.isTmpId)(row.id);
225
+ const isIndexField = field === indexField;
226
+ const indexColumn = preparedColumns === null || preparedColumns === void 0 ? void 0 : preparedColumns.find((col) => col.field === indexField);
751
227
  const hasValueFormatter = (indexColumn === null || indexColumn === void 0 ? void 0 : indexColumn.valueFormatter) !== undefined;
752
- const isIndexFieldEditable = !optionsAC.current || !(indexField in optionsAC.current) || hasValueFormatter;
753
- return (isRowInEditMode &&
754
- (isPermanentRow || ((0, utils_1.isTmpId)(params.row.id) && (isIndexField || isIndexFieldEditable))));
755
- }, checkboxSelection: checkboxSelection, onSelectionModelChange: (newSelectionModel) => {
228
+ const isIndexFieldEditable = !(indexField in optionsAC) || hasValueFormatter;
229
+ return (
230
+ // isRowEditing &&
231
+ isPermanentRow || ((0, utils_1.isTmpId)(row.id) && (isIndexField || isIndexFieldEditable)));
232
+ }, checkboxSelection: checkboxSelection, onRowSelectionModelChange: (newSelectionModel) => {
756
233
  const selectedData = dataGrid.data.filter((item) => newSelectionModel.includes(item.id));
757
234
  setSelectionModel(selectedData);
758
- setSelectionModelIds(newSelectionModel);
759
- }, selectionModel: selectionModelIds, disableSelectionOnClick: disableRowSelectionOnClick, rowModesModel: rowModesModel, onRowEditStart: (params, event) => {
760
- event.defaultMuiPrevented = true;
235
+ setSelectionModelIds([...newSelectionModel]);
236
+ }, rowSelectionModel: selectionModelIds, disableRowSelectionOnClick: disableRowSelectionOnClick, onRowEditStart: (params) => {
237
+ console.log({ onRowEditStart: params.reason, id: params.id, isRowEditing });
238
+ if (isRowEditing) {
239
+ handleSaveRow(isRowEditing);
240
+ }
241
+ handleStartEditing(params.id);
761
242
  }, onRowEditStop: (params, event) => {
762
- event.defaultMuiPrevented = true;
243
+ console.log({ onRowEditStop: params.reason });
244
+ if (params.reason === 'rowFocusOut') {
245
+ const isInsideGrid = !('target' in event);
246
+ if (!isInsideGrid) {
247
+ event.defaultMuiPrevented = true;
248
+ }
249
+ return;
250
+ }
251
+ const fieldSchema = params.field ? schema[params.field] : undefined;
252
+ if (params.reason === 'enterKeyDown' &&
253
+ ['date', 'datetime', 'nested object', 'field', 'choice', 'list'].includes((fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.type) || '')) {
254
+ event.defaultMuiPrevented = true;
255
+ return;
256
+ }
257
+ // Escape key prevents saving:
258
+ if (params.reason === 'escapeKeyDown') {
259
+ handleCancelRow(params.id);
260
+ }
763
261
  }, processRowUpdate: processRowUpdate, onProcessRowUpdateError: (e) => {
764
262
  setDataGridLoading(false);
765
- if (processingRow.current) {
766
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [processingRow.current]: {
767
- mode: x_data_grid_1.GridRowModes.Edit,
768
- } }));
263
+ if (e.message === 'CANCEL_TMP_ROW') {
264
+ return;
265
+ }
266
+ // if (processingRow.current) {
267
+ // apiRef.current.startRowEditMode({ id: processingRow.current });
268
+ // }
269
+ let msg = 'Ocorreu um erro desconhecido ao salvar.';
270
+ if (e.message === 'Validation Error') {
271
+ msg = 'Não foi possível salvar os dados. Confira os erros nos campos.';
272
+ }
273
+ else if (e.message) {
274
+ msg = e.message;
769
275
  }
770
- const msg = `Erro em "${e.path}": ${e.errors}`;
771
276
  setSnackBar({
772
277
  open: true,
773
278
  severity: 'error',
774
279
  msg,
775
280
  });
776
281
  console.log(e);
777
- }, components: {
778
- Toolbar: hideToolbarComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : CustomToolbar_1.CustomToolbar,
779
- Footer: hideFooterComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : FooterToolbar_1.FooterToolbar,
780
- }, componentsProps: {
282
+ }, slots: {
283
+ toolbar: hideToolbarComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : InternalToolbar,
284
+ footer: hideFooterComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : InternalFooter,
285
+ }, slotProps: {
781
286
  toolbar: {
782
- preparedColumns,
783
- setPreparedColumns,
784
287
  showQuickFilter: true,
785
288
  quickFilterProps: { debounceMs: 500 },
786
- // getRowsToExport: () => {
787
- // return [];
788
- // },
789
- selectionModel,
790
- onSelectActions,
791
- bulkUpdateData,
792
- bulkDeleteData,
793
- bulkCreateData,
794
- hideColumnsButton,
795
- hideFilterButton,
796
- hideDensityButton,
797
- hideExportButton,
798
- hideQuickFilterBar,
799
- },
800
- footer: {
801
- isEditable,
802
- handleAddItem: () => {
803
- handleAddItems();
804
- },
805
289
  },
806
290
  filterPanel: {
807
291
  sx: {
@@ -810,26 +294,39 @@ function DataGridDesktop({ schema, dataGrid, setDataGrid, rowCount = 0, columns,
810
294
  },
811
295
  },
812
296
  },
813
- }, experimentalFeatures: { newEditingApi: isEditable }, sx: customPaddings, paginationMode: paginationModel ? 'server' : 'client', onPageChange: (newPage) => {
297
+ },
298
+ // sx={sx}
299
+ sx: Object.assign(Object.assign({}, sx), { width: '100%', minWidth: 0 }), paginationMode: paginationModel ? 'server' : 'client', paginationModel: paginationModel
300
+ ? { page: paginationModel.page, pageSize: paginationModel.pageSize }
301
+ : undefined, onPaginationModelChange: (newModel) => {
814
302
  if (setPaginationModel && paginationModel) {
815
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { page: newPage }));
303
+ setPaginationModel(Object.assign(Object.assign({}, paginationModel), { page: newModel.page, pageSize: newModel.pageSize }));
816
304
  }
817
- }, onPageSizeChange: (newPageSize) => {
305
+ }, initialState: {
306
+ columns: { columnVisibilityModel },
307
+ pagination: !paginationModel ? { paginationModel: { pageSize: 100 } } : undefined,
308
+ }, rowCount: paginationModel && typeof rowCount !== 'undefined' ? rowCount : undefined, pageSizeOptions: paginationModel ? [paginationModel.pageSize] : [5, 10, 25, 50, 100], filterMode: paginationModel ? 'server' : 'client', onFilterModelChange: (newFilter) => {
818
309
  if (setPaginationModel && paginationModel) {
819
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { pageSize: newPageSize }));
310
+ setPaginationModel(Object.assign(Object.assign({}, paginationModel), { filter: newFilter }));
820
311
  }
821
- }, rowCount: paginationModel && typeof rowCount !== 'undefined' ? rowCount : undefined, pageSize: paginationModel ? paginationModel.pageSize : 100, rowsPerPageOptions: paginationModel ? [paginationModel.pageSize] : [5, 10, 25, 50, 100], filterMode: paginationModel ? 'server' : 'client', onFilterModelChange: paginationModel
822
- ? (newFilter) => {
823
- if (setPaginationModel && paginationModel) {
824
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { filter: newFilter }));
825
- }
312
+ }, sortingMode: paginationModel ? 'server' : 'client', onSortModelChange: (newSorting) => {
313
+ if (setPaginationModel && paginationModel) {
314
+ setPaginationModel(Object.assign(Object.assign({}, paginationModel), { sort: newSorting }));
826
315
  }
827
- : undefined, sortingMode: paginationModel ? 'server' : 'client', onSortModelChange: paginationModel
828
- ? (newSorting) => {
829
- if (setPaginationModel && paginationModel) {
830
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { sort: newSorting }));
831
- }
316
+ }, onStateChange: (state) => {
317
+ if (setVisibleRows) {
318
+ const visibleRows = (0, x_data_grid_1.gridFilteredSortedRowIdsSelector)(state, apiRef.current.instanceId);
319
+ setVisibleRows(visibleRows);
832
320
  }
833
- : undefined }))));
321
+ } }))));
834
322
  }
835
- exports.default = react_1.default.memo(DataGridDesktop, utils_1.shouldMemoUpdate);
323
+ // const shouldMemoUpdate = (prevProps: DataGridDesktopProps, nextProps: DataGridDesktopProps) => {
324
+ // return (
325
+ // prevProps.dataGrid === nextProps.dataGrid &&
326
+ // prevProps.loading === nextProps.loading &&
327
+ // prevProps.schema === nextProps.schema &&
328
+ // prevProps.columns === nextProps.columns
329
+ // );
330
+ // };
331
+ // export default React.memo(DataGridDesktop, shouldMemoUpdate);
332
+ exports.default = DataGridDesktop;