drf-react-by-schema 0.19.9 → 0.19.10

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.
@@ -32,49 +32,22 @@ 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
- const x_data_grid_1 = require("@mui/x-data-grid");
51
40
  const Box_1 = __importDefault(require("@mui/material/Box"));
52
- const CircularProgress_1 = __importDefault(require("@mui/material/CircularProgress"));
53
- const Edit_1 = __importDefault(require("@mui/icons-material/Edit"));
54
- const Bolt_1 = __importDefault(require("@mui/icons-material/Bolt"));
55
- const Visibility_1 = __importDefault(require("@mui/icons-material/Visibility"));
56
- const Clear_1 = __importDefault(require("@mui/icons-material/Clear"));
57
- const Check_1 = __importDefault(require("@mui/icons-material/Check"));
58
- const Undo_1 = __importDefault(require("@mui/icons-material/Undo"));
59
41
  const Snackbar_1 = __importDefault(require("@mui/material/Snackbar"));
60
42
  const Alert_1 = __importDefault(require("@mui/material/Alert"));
61
- const string_mask_1 = __importDefault(require("string-mask"));
62
- const styles_1 = require("../styles");
63
- const api_1 = require("../api");
43
+ const material_1 = require("@mui/material");
64
44
  const utils_1 = require("../utils");
65
- const DRFReactBySchemaContext_1 = require("../context/DRFReactBySchemaContext");
66
- const utils_2 = require("./DataGridBySchemaEditable/utils");
67
- const CustomToolbar_1 = require("./DataGridBySchemaEditable/CustomToolbar");
68
- const SelectEditInputCell_1 = require("./DataGridBySchemaEditable/SelectEditInputCell");
69
- const GridDateInput_1 = require("./DataGridBySchemaEditable/GridDateInput");
70
- const GridDecimalInput_1 = require("./DataGridBySchemaEditable/GridDecimalInput");
71
- const GridPatternInput_1 = require("./DataGridBySchemaEditable/GridPatternInput");
72
- const BooleanInputCell_1 = require("./DataGridBySchemaEditable/BooleanInputCell");
73
- const FooterToolbar_1 = require("./DataGridBySchemaEditable/FooterToolbar");
74
45
  const ConfirmDialog_1 = require("./DataGridBySchemaEditable/ConfirmDialog");
75
46
  const APIWrapperContext_1 = require("../context/APIWrapperContext");
76
- const DataGridBySchemaEditable = (0, react_1.forwardRef)(({ schema, data, 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, defaultValues = {}, hideFooterPagination = false, setVisibleRows, paginationModel = undefined, setPaginationModel = undefined, hideFooterComponent, hideToolbarComponent, tableAutoHeight, actions = ['editInline', 'remove'], customActions, hideColumnsButton, hideFilterButton, hideDensityButton, hideExportButton, hideQuickFilterBar, optionsAC: optionsACExternal, extraValidators, }, _) => {
77
- const { serverEndPoint } = (0, DRFReactBySchemaContext_1.useDRFReactBySchema)();
47
+ const DataGridDesktop_1 = __importDefault(require("./DataGridBySchemaEditable/DataGridDesktop"));
48
+ const DataGridMobile_1 = __importDefault(require("./DataGridBySchemaEditable/DataGridMobile"));
49
+ const theme_1 = __importDefault(require("../styles/theme"));
50
+ const DataGridBySchemaEditable = (0, react_1.forwardRef)(({ schema, data, 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, defaultValues = {}, hideFooterPagination = false, setVisibleRows, paginationModel = undefined, setPaginationModel = undefined, hideFooterComponent, hideToolbarComponent, tableAutoHeight, actions = ['editInline', 'remove'], customActions, hideColumnsButton, hideFilterButton, hideDensityButton, hideExportButton, hideQuickFilterBar, optionsAC, extraValidators, MobileListRenderItem, }, _) => {
78
51
  const apiContext = (0, APIWrapperContext_1.useAPIWrapper)();
79
52
  const initialSnackBar = {
80
53
  open: false,
@@ -85,461 +58,14 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)(({ schema, data, rowCou
85
58
  const [dataGrid, setDataGrid] = (0, react_1.useState)({
86
59
  data: [],
87
60
  });
88
- const [preparedColumns, setPreparedColumns] = (0, react_1.useState)(null);
89
- const [dataGridLoading, setDataGridLoading] = (0, react_1.useState)(false);
90
- const [rowModesModel, setRowModesModel] = (0, react_1.useState)();
91
61
  const [confirmDialogOpen, setConfirmDialogOpen] = (0, react_1.useState)(false);
92
- const [selectionModel, setSelectionModel] = (0, react_1.useState)([]);
93
- const [selectionModelIds, setSelectionModelIds] = (0, react_1.useState)([]);
94
- const optionsAC = (0, react_1.useRef)(null);
95
- const emptyItem = (0, react_1.useRef)({});
62
+ const [emptyItem, setEmptyItem] = (0, react_1.useState)({});
96
63
  const yupValidationSchema = (0, react_1.useRef)(null);
97
- const processingRow = (0, react_1.useRef)(null);
98
64
  const idToRemove = (0, react_1.useRef)(null);
99
- const visibleRows = (0, react_1.useRef)('');
100
- if (!onEditModel) {
101
- onEditModel = apiContext.onEditModel;
102
- }
103
- const updateOptionsAC = () => __awaiter(void 0, void 0, void 0, function* () {
104
- optionsAC.current = {};
105
- for (const col of columns) {
106
- if (optionsACExternal && col.field in optionsACExternal) {
107
- optionsAC.current[col.field] = optionsACExternal[col.field];
108
- continue;
109
- }
110
- if (!schema[col.field]) {
111
- continue;
112
- }
113
- if (['field', 'nested object'].includes(schema[col.field].type) &&
114
- !(col.field in optionsAC.current)) {
115
- const options = yield (0, api_1.getAutoComplete)({
116
- model: col.field,
117
- serverEndPoint,
118
- });
119
- if (options) {
120
- optionsAC.current[col.field] = options;
121
- continue;
122
- }
123
- console.log(`Couldn't load autocomplete options from '${col.field}'`);
124
- continue;
125
- }
126
- if (schema[col.field].type === 'choice' && !(col.field in optionsAC.current)) {
127
- optionsAC.current[col.field] = schema[col.field].choices;
128
- continue;
129
- }
130
- if (col.field === indexField && addExistingModel && !optionsAC.current[col.field]) {
131
- const options = yield (0, api_1.getAutoComplete)({
132
- model: addExistingModel,
133
- serverEndPoint,
134
- });
135
- if (options) {
136
- optionsAC.current[col.field] = options;
137
- continue;
138
- }
139
- if (!(col.field in optionsAC.current)) {
140
- delete optionsAC.current[col.field];
141
- }
142
- }
143
- }
144
- });
145
- const initColumns = () => __awaiter(void 0, void 0, void 0, function* () {
146
- const actionCols = [];
147
- if (isEditable) {
148
- const handleSaveClick = (id) => () => {
149
- if (id) {
150
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View } }));
151
- }
152
- };
153
- const handleCancelClick = (id) => () => {
154
- if (id) {
155
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.View, ignoreModifications: true } }));
156
- }
157
- setDataGrid((currentDataGrid) => {
158
- const editedRow = currentDataGrid.data.find((row) => row.id === id);
159
- if (editedRow && editedRow.isNew) {
160
- return Object.assign(Object.assign({}, currentDataGrid), { data: currentDataGrid.data.filter((row) => row.id !== id) });
161
- }
162
- return currentDataGrid;
163
- });
164
- };
165
- const handleEditInlineClick = (id) => () => {
166
- if (id) {
167
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [id]: { mode: x_data_grid_1.GridRowModes.Edit } }));
168
- }
169
- };
170
- actionCols.push({
171
- field: 'actions',
172
- headerName: '',
173
- type: 'actions',
174
- getActions: ({ id }) => {
175
- var _a;
176
- if (!id) {
177
- return [];
178
- }
179
- 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;
180
- if (isInEditMode) {
181
- return [
182
- 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: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined }),
183
- 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: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined }),
184
- ];
185
- }
186
- const actionItems = [];
187
- actions.forEach((action) => {
188
- switch (action) {
189
- case 'editInline':
190
- actionItems.push(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: "Edit inline", onClick: handleEditInlineClick(id), color: "inherit", showInMenu: false, placeholder: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined }));
191
- break;
192
- case 'remove':
193
- actionItems.push(react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { key: `remove_${id}`, icon: react_1.default.createElement(Clear_1.default, null), label: "Delete", onClick: handleDeleteClick(id), color: "error", showInMenu: false, placeholder: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined }));
194
- break;
195
- case 'edit':
196
- if (!LinkComponent) {
197
- console.log('you must pass LinkComponent prop to navigate externally');
198
- break;
199
- }
200
- actionItems.push(react_1.default.createElement(LinkComponent, { key: `edit_${id}`, to: `${indexFieldBasePath}${id}`, state: stateToLink },
201
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { icon: react_1.default.createElement(Edit_1.default, null), label: "Edit", color: "inherit", showInMenu: false, placeholder: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined })));
202
- break;
203
- case 'view':
204
- if (!LinkComponent) {
205
- console.log('you must pass LinkComponent prop to navigate externally');
206
- break;
207
- }
208
- if (!indexFieldViewBasePath) {
209
- console.log('For view action to work, you must supply indexFieldViewBasePath prop!');
210
- break;
211
- }
212
- actionItems.push(react_1.default.createElement(LinkComponent, { key: `view_${id}`, to: `${indexFieldViewBasePath}${id}`, state: stateToLink },
213
- react_1.default.createElement(x_data_grid_1.GridActionsCellItem, { icon: react_1.default.createElement(Visibility_1.default, null), label: "View", color: "inherit", showInMenu: false, placeholder: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined })));
214
- break;
215
- }
216
- });
217
- // React.ReactElement<any, string | React.JSXElementConstructor<any>>
218
- // React.ReactElement<any, string | React.JSXElementConstructor<any>>
219
- if (customActions) {
220
- customActions.forEach((customAction) => {
221
- actionItems.push(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: "", onResize: () => undefined, onResizeCapture: () => undefined, onPointerEnterCapture: () => undefined, onPointerLeaveCapture: () => undefined }));
222
- });
223
- }
224
- return actionItems;
225
- },
226
- });
227
- }
228
- const cols = [...actionCols, ...columns];
229
- const colsPromises = cols.map((col) => __awaiter(void 0, void 0, void 0, function* () {
230
- if (!schema[col.field]) {
231
- return col;
232
- }
233
- const isIndexField = indexField !== '' && col.field === indexField;
234
- let column = col;
235
- if (isIndexField) {
236
- col.isIndexField = true;
237
- }
238
- column.editable =
239
- isEditable &&
240
- !col.disabled &&
241
- (!schema[col.field].read_only ||
242
- ['field', 'nested object'].includes(schema[col.field].type));
243
- if (['field', 'nested object'].includes(schema[col.field].type)) {
244
- column.creatable =
245
- 'related_editable' in schema[col.field]
246
- ? schema[col.field].related_editable
247
- : column.creatable;
248
- }
249
- switch (schema[col.field].type) {
250
- case 'date':
251
- column.type = 'date';
252
- const dateFormat = (0, utils_1.buildDateFormatBySchema)(schema[col.field].date_views);
253
- column.valueFormatter = (params) => params.value ? (0, dayjs_1.default)(params.value).format(dateFormat) : '';
254
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
255
- type: 'date',
256
- });
257
- if (isEditable && !col.disabled) {
258
- column.renderEditCell = (params) => (react_1.default.createElement(GridDateInput_1.GridDateInput, Object.assign({}, params, { column: column, dateViews: schema[col.field].date_views })));
259
- break;
260
- }
261
- break;
262
- case 'datetime':
263
- column.type = 'dateTime';
264
- column.minWidth = 180;
265
- column.valueFormatter = (params) => params.value ? (0, dayjs_1.default)(params.value).format('DD/MM/YYYY HH:mm') : '';
266
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
267
- type: 'date',
268
- });
269
- break;
270
- case 'nested object':
271
- column.minWidth = 150;
272
- if (isEditable && !col.disabled) {
273
- column.valueFormatter = (params) => {
274
- return !params.value ? '' : params.value.label;
275
- };
276
- // column.filterable = false;
277
- column.sortComparator = (v1, v2, param1, param2) => {
278
- return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.label, v2.label, param1, param2);
279
- };
280
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, options: optionsAC.current && col.field in optionsAC.current
281
- ? optionsAC.current[col.field]
282
- : [], isIndexField: isIndexField, onEditModel: onEditModel, fieldsLayout: customFieldFormLayouts && col.field in customFieldFormLayouts
283
- ? customFieldFormLayouts[col.field]
284
- : undefined, setDialog: apiContext.setDialog })));
285
- break;
286
- }
287
- column.valueGetter = (params) => {
288
- return !params.value ? '' : params.value.label;
289
- };
290
- break;
291
- case 'field':
292
- column.orderable = false;
293
- if (isEditable && !col.disabled) {
294
- column.minWidth = 300;
295
- column.valueFormatter = (params) => {
296
- return !params.value || !Array.isArray(params.value)
297
- ? ''
298
- : params.value.map((val) => val.label).join(', ');
299
- };
300
- column.filterable = false;
301
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, options: optionsAC.current && col.field in optionsAC.current
302
- ? optionsAC.current[col.field]
303
- : [], isIndexField: isIndexField, multiple: schema[col.field].many || false, setDialog: apiContext.setDialog })));
304
- break;
305
- }
306
- column.valueGetter = (params) => {
307
- return !params.value || !Array.isArray(params.value)
308
- ? ''
309
- : params.value.map((val) => val.label).join(', ');
310
- };
311
- break;
312
- case 'choice':
313
- if (isEditable && !col.disabled) {
314
- column.minWidth = 150;
315
- column.valueFormatter = (params) => {
316
- return !params.value ? '' : params.value.display_name;
317
- };
318
- column.filterable = false;
319
- column.sortComparator = (v1, v2, param1, param2) => {
320
- return (0, x_data_grid_1.gridStringOrNumberComparator)(v1.display_name, v2.display_name, param1, param2);
321
- };
322
- column.renderEditCell = (params) => (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, options: optionsAC.current && col.field in optionsAC.current
323
- ? optionsAC.current[col.field]
324
- : [], isIndexField: isIndexField, setDialog: apiContext.setDialog })));
325
- break;
326
- }
327
- column.valueGetter = (params) => {
328
- return !params.value ? '' : params.value.display_name;
329
- };
330
- break;
331
- case 'boolean':
332
- if (isEditable && !col.disabled) {
333
- column.valueFormatter = (params) => {
334
- return params.value ? 'Sim' : 'Não';
335
- };
336
- column.renderEditCell = (params) => react_1.default.createElement(BooleanInputCell_1.BooleanInputCell, Object.assign({}, params, { column: column }));
337
- break;
338
- }
339
- column.valueGetter = (params) => {
340
- return params.value ? 'Sim' : 'Não';
341
- };
342
- break;
343
- case 'decimal':
344
- case 'float':
345
- const decimalScale = schema[col.field].decimal_places || 2;
346
- const prefix = schema[col.field].prefix || '';
347
- const suffix = schema[col.field].suffix || '';
348
- const isCurrency = schema[col.field].is_currency;
349
- column.type = 'number';
350
- column.valueFormatter = (params) => {
351
- return !params.value
352
- ? ''
353
- : parseFloat(params.value).toLocaleString('pt-BR', {
354
- minimumFractionDigits: decimalScale,
355
- maximumFractionDigits: decimalScale,
356
- });
357
- };
358
- if (isEditable && !col.disabled) {
359
- column.renderEditCell = (params) => (react_1.default.createElement(GridDecimalInput_1.GridDecimalInput, Object.assign({}, params, { decimalPlaces: decimalScale, isCurrency: isCurrency, prefix: prefix, suffix: suffix, column: column })));
360
- }
361
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
362
- type: 'float',
363
- });
364
- break;
365
- case 'number':
366
- case 'integer':
367
- column.type = 'number';
368
- column.filterOperators = (0, utils_2.quantityOnlyOperators)({
369
- type: 'number',
370
- });
371
- break;
372
- }
373
- if (indexFieldMinWidth && !column.minWidth) {
374
- column.minWidth = col.field === indexField ? indexFieldMinWidth : minWidth;
375
- }
376
- if (indexField) {
377
- if (col.field === indexField) {
378
- column.flex = 1;
379
- column.renderCell = (params) => {
380
- if (LinkComponent && customLinkDestination && !actions.includes('edit')) {
381
- return (react_1.default.createElement(LinkComponent, { to: `${customLinkDestination(params)}`, state: stateToLink }, params.formattedValue));
382
- }
383
- if (!LinkComponent ||
384
- !indexFieldBasePath ||
385
- actions.includes('edit') ||
386
- (['field', 'nested object'].includes(schema[col.field].type) &&
387
- (!params.row[col.field] || !params.row[col.field].id))) {
388
- return react_1.default.createElement(react_1.default.Fragment, null, params.formattedValue);
389
- }
390
- const targetId = ['field', 'nested object'].includes(schema[col.field].type)
391
- ? params.row[col.field].id.toString()
392
- : params.row.id.toString();
393
- return (react_1.default.createElement(LinkComponent, { to: `${indexFieldBasePath}${targetId}`, state: stateToLink }, params.formattedValue));
394
- };
395
- if (isEditable &&
396
- !col.disabled &&
397
- optionsAC.current &&
398
- col.field in optionsAC.current &&
399
- addExistingModel) {
400
- column.renderEditCell = (params) => {
401
- if (!(0, utils_1.isTmpId)(params.id)) {
402
- return react_1.default.createElement(x_data_grid_1.GridEditInputCell, Object.assign({}, params));
403
- }
404
- return (react_1.default.createElement(SelectEditInputCell_1.SelectEditInputCell, Object.assign({}, params, { column: column, type: schema[col.field].type, options: optionsAC.current && col.field in optionsAC.current
405
- ? optionsAC.current[col.field]
406
- : [], isIndexField: true, setDialog: apiContext.setDialog })));
407
- };
408
- }
409
- }
410
- }
411
- // format numbers:
412
- if (column.patternFormat) {
413
- column.valueFormatter = (params) => {
414
- if (!params.value || typeof params.value !== 'string') {
415
- return params.value;
416
- }
417
- const formattedValue = new string_mask_1.default(column.patternFormat, {}).apply(params.value);
418
- return formattedValue;
419
- };
420
- if (isEditable && !col.disabled) {
421
- column.renderEditCell = (params) => (react_1.default.createElement(GridPatternInput_1.GridPatternInput, Object.assign({}, params, { patternFormat: column.patternFormat })));
422
- }
423
- }
424
- // Custom column operations:
425
- if (customColumnOperations) {
426
- column = yield customColumnOperations(column);
427
- }
428
- // Finally!
429
- return column;
430
- }));
431
- const finalCols = yield Promise.all(colsPromises);
432
- setPreparedColumns(finalCols);
433
- });
434
- const handleAddItems = (numberOfRows = 1) => {
435
- const newRows = [];
436
- for (let i = 0; i < numberOfRows; i++) {
437
- const id = (0, utils_1.getTmpId)();
438
- newRows.push(Object.assign(Object.assign({}, emptyItem.current), { id }));
439
- }
440
- const newData = tableAutoHeight
441
- ? [...dataGrid.data, ...newRows]
442
- : [...newRows, ...dataGrid.data];
443
- setDataGrid({
444
- data: newData,
445
- });
446
- setRowModesModel((oldModel) => {
447
- const newModel = Object.assign({}, oldModel);
448
- newRows.map((newRow) => {
449
- newModel[newRow.id] = { mode: x_data_grid_1.GridRowModes.Edit, fieldToFocus: indexField };
450
- });
451
- return newModel;
452
- });
453
- if (!tableAutoHeight) {
454
- // Ugly hack to scroll to top, since scroll to cell is only available in Pro
455
- const el = document.querySelector(`.dataGrid_${name} .MuiDataGrid-virtualScroller`);
456
- if (el) {
457
- el.scrollTop = 0;
458
- setTimeout(() => {
459
- el.scrollTop = 0;
460
- }, 10);
461
- }
462
- }
463
- };
464
- const bulkUpdateData = (newData) => __awaiter(void 0, void 0, void 0, function* () {
465
- const promises = [];
466
- const ids = [];
467
- newData.map((item) => {
468
- promises.push((0, api_1.updateDataBySchema)({
469
- model,
470
- modelObjectId: item.id,
471
- serverEndPoint,
472
- data: item,
473
- schema,
474
- }));
475
- ids.push(item.id);
476
- });
477
- const results = yield Promise.all(promises);
478
- setSelectionModel([]);
479
- setSelectionModelIds([]);
480
- setDataGrid((currentData) => {
481
- const updatedData = currentData.data.map((item) => {
482
- const index = ids.indexOf(item.id);
483
- return index === -1 ? item : newData[index];
484
- });
485
- return {
486
- data: updatedData,
487
- };
488
- });
489
- setSnackBar({
490
- open: true,
491
- severity: 'success',
492
- msg: 'Alterações salvas com sucesso',
493
- });
494
- return results.map((result, index) => {
495
- return {
496
- id: ids[index],
497
- success: 'isAxiosError' in result,
498
- };
499
- });
500
- });
501
- const bulkDeleteData = (ids) => __awaiter(void 0, void 0, void 0, function* () {
502
- const promises = [];
503
- ids.map((id) => {
504
- promises.push((0, api_1.deleteData)(model, serverEndPoint, id));
505
- });
506
- setDataGridLoading(true);
507
- const results = yield Promise.all(promises);
508
- setSelectionModel([]);
509
- setSelectionModelIds([]);
510
- setDataGrid({
511
- data: data.filter((item) => !ids.includes(item.id)),
512
- });
513
- setDataGridLoading(false);
514
- setSnackBar({
515
- open: true,
516
- severity: 'success',
517
- msg: 'Itens apagados com sucesso',
518
- });
519
- return results.map((result, index) => {
520
- return {
521
- id: ids[index],
522
- success: result === true,
523
- };
524
- });
525
- });
526
- const bulkCreateData = (ids) => __awaiter(void 0, void 0, void 0, function* () {
527
- handleAddItems(ids.length);
528
- setSelectionModel([]);
529
- setSelectionModelIds([]);
530
- setSnackBar({
531
- open: true,
532
- severity: 'success',
533
- msg: 'Linhas adicionadas com sucesso',
534
- });
535
- });
65
+ const isMobile = (0, material_1.useMediaQuery)(theme_1.default.breakpoints.down('md'));
536
66
  const handleConfirmDialogClose = () => {
537
67
  setConfirmDialogOpen(false);
538
68
  };
539
- const handleDeleteClick = (id) => () => {
540
- idToRemove.current = id;
541
- setConfirmDialogOpen(true);
542
- };
543
69
  const handleDeleteSave = () => {
544
70
  if (idToRemove.current === null) {
545
71
  setConfirmDialogOpen(false);
@@ -562,30 +88,36 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)(({ schema, data, rowCou
562
88
  idToRemove.current = null;
563
89
  setConfirmDialogOpen(false);
564
90
  };
91
+ const handleDeleteClick = (id) => () => {
92
+ idToRemove.current = id;
93
+ setConfirmDialogOpen(true);
94
+ };
565
95
  (0, react_1.useEffect)(() => {
566
96
  if (!columns) {
567
97
  setDataGrid({ data: [] });
568
98
  return;
569
99
  }
100
+ const newEmptyItem = {};
570
101
  if (isEditable) {
571
102
  for (const col of columns) {
572
103
  if (schema[col.field].model_default) {
573
- emptyItem.current[col.field] = schema[col.field].model_default;
104
+ newEmptyItem[col.field] = schema[col.field].model_default;
574
105
  continue;
575
106
  }
576
107
  if (col.field in defaultValues) {
577
- emptyItem.current[col.field] = defaultValues[col.field];
108
+ newEmptyItem[col.field] = defaultValues[col.field];
578
109
  continue;
579
110
  }
580
- emptyItem.current[col.field] = schema[col.field] ? (0, utils_1.emptyByType)(schema[col.field]) : null;
111
+ newEmptyItem[col.field] = schema[col.field] ? (0, utils_1.emptyByType)(schema[col.field]) : null;
581
112
  }
113
+ setEmptyItem(newEmptyItem);
582
114
  }
583
115
  const skipFields = [];
584
116
  if (indexField && addExistingModel) {
585
117
  skipFields.push(indexField);
586
118
  }
587
119
  yupValidationSchema.current = (0, utils_1.buildGenericYupValidationSchema)({
588
- data: emptyItem.current,
120
+ data: newEmptyItem,
589
121
  schema,
590
122
  skipFields,
591
123
  extraValidators,
@@ -595,243 +127,8 @@ const DataGridBySchemaEditable = (0, react_1.forwardRef)(({ schema, data, rowCou
595
127
  });
596
128
  // eslint-disable-next-line react-hooks/exhaustive-deps
597
129
  }, [data]);
598
- (0, react_1.useEffect)(() => {
599
- updateOptionsAC().then(() => {
600
- initColumns();
601
- });
602
- // eslint-disable-next-line react-hooks/exhaustive-deps
603
- }, [rowModesModel, JSON.stringify(columns)]);
604
- const processRowUpdate = (editedRow) => __awaiter(void 0, void 0, void 0, function* () {
605
- if (!preparedColumns || !yupValidationSchema.current) {
606
- return false;
607
- }
608
- setDataGridLoading(true);
609
- const indexCol = preparedColumns.find((col) => col.field === indexField);
610
- processingRow.current = editedRow.id;
611
- yield yupValidationSchema.current.validate(editedRow);
612
- const onlyAddExisting = indexField &&
613
- (0, utils_1.isTmpId)(editedRow.id) &&
614
- editedRow[indexField] &&
615
- !(0, utils_1.isTmpId)(editedRow[indexField].id) &&
616
- (!indexCol || !indexCol.valueFormatter);
617
- const createNewItem = indexField &&
618
- (0, utils_1.isTmpId)(editedRow.id) &&
619
- editedRow[indexField] &&
620
- (0, utils_1.isTmpId)(editedRow[indexField].id);
621
- if (onlyAddExisting) {
622
- const row = {};
623
- row.id_to_add = editedRow[indexField].id;
624
- for (const [key, value] of Object.entries(editedRow[indexField])) {
625
- if (key === 'id') {
626
- row[key] = editedRow.id;
627
- continue;
628
- }
629
- row[key] = value;
630
- }
631
- editedRow = Object.assign({}, row);
632
- }
633
- if (createNewItem && editedRow[indexField]) {
634
- if (editedRow[indexField].inputValue) {
635
- editedRow[indexField] = editedRow[indexField].inputValue;
636
- }
637
- if (addExistingModel) {
638
- editedRow[indexField] = editedRow[indexField].label;
639
- }
640
- }
641
- if (modelParent && modelParentId && apiContext) {
642
- const response = yield apiContext.onEditRelatedModelSave({
643
- model: modelParent,
644
- id: modelParentId,
645
- relatedModel: model,
646
- relatedModelId: editedRow.id,
647
- newRow: editedRow,
648
- schema,
649
- onlyAddExisting,
650
- });
651
- if (response !== false && (onlyAddExisting || createNewItem || !onlyAddExisting)) {
652
- updateOptionsAC();
653
- const data = [...dataGrid.data];
654
- const newRow = 'data' in response && 'schema' in response ? response.data : response;
655
- for (const i in data) {
656
- if (data[i].id === editedRow.id) {
657
- data[i] = newRow;
658
- // This is for cases where users want to do custom operations after saving the row,
659
- // like for example make calculations among columns.
660
- if (onProcessRow) {
661
- onProcessRow(data[i]);
662
- }
663
- // Reflect the changes to the outside, for example for global calculations over all data
664
- if (onDataChange) {
665
- onDataChange(data);
666
- }
667
- setDataGrid({ data });
668
- break;
669
- }
670
- }
671
- setDataGridLoading(false);
672
- return newRow;
673
- }
674
- setDataGridLoading(false);
675
- return false;
676
- }
677
- const response = yield apiContext.onEditModelDataGridSave({
678
- model,
679
- id: editedRow.id,
680
- newRow: editedRow,
681
- schema,
682
- });
683
- setDataGridLoading(false);
684
- if (response !== false) {
685
- updateOptionsAC();
686
- const data = [...dataGrid.data];
687
- const newRow = response;
688
- for (const i in data) {
689
- if (data[i].id === editedRow.id) {
690
- data[i] = newRow;
691
- // This is for cases where users want to do custom operations after saving the row,
692
- // like for example make calculations among columns.
693
- if (onProcessRow) {
694
- onProcessRow(data[i]);
695
- }
696
- // Reflect the changes to the outside, for example for global calculations over all data
697
- if (onDataChange) {
698
- onDataChange(data);
699
- }
700
- setDataGrid({ data });
701
- break;
702
- }
703
- }
704
- return newRow;
705
- }
706
- return false;
707
- });
708
- const customPaddings = isAutoHeight
709
- ? {
710
- '&.MuiDataGrid-root--densityCompact .MuiDataGrid-cell': {
711
- py: '8px',
712
- },
713
- '&.MuiDataGrid-root--densityStandard .MuiDataGrid-cell': {
714
- py: '15px',
715
- },
716
- '&.MuiDataGrid-root--densityComfortable .MuiDataGrid-cell': {
717
- py: '22px',
718
- },
719
- }
720
- : undefined;
721
- const checkboxSelection = hasBulkSelect ? true : undefined;
722
- const disableRowSelectionOnClick = hasBulkSelect ? true : undefined;
723
130
  return (react_1.default.createElement(Box_1.default, { className: `dataGrid_${name}`, sx: { height: '100%' } },
724
- 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
- }
739
- }
740
- }, editMode: "row", loading: dataGridLoading || loading, hideFooterPagination: hideFooterPagination, getRowHeight: () => {
741
- if (isAutoHeight) {
742
- return 'auto';
743
- }
744
- 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);
751
- 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 ||
755
- ((0, utils_1.isTmpId)(params.row.id) && (isIndexField || isIndexFieldEditable))));
756
- }, checkboxSelection: checkboxSelection, onSelectionModelChange: (newSelectionModel) => {
757
- const selectedData = dataGrid.data.filter((item) => newSelectionModel.includes(item.id));
758
- setSelectionModel(selectedData);
759
- setSelectionModelIds(newSelectionModel);
760
- }, selectionModel: selectionModelIds, disableSelectionOnClick: disableRowSelectionOnClick, rowModesModel: rowModesModel, onRowEditStart: (params, event) => {
761
- event.defaultMuiPrevented = true;
762
- }, onRowEditStop: (params, event) => {
763
- event.defaultMuiPrevented = true;
764
- }, processRowUpdate: processRowUpdate, onProcessRowUpdateError: (e) => {
765
- setDataGridLoading(false);
766
- if (processingRow.current) {
767
- setRowModesModel(Object.assign(Object.assign({}, rowModesModel), { [processingRow.current]: {
768
- mode: x_data_grid_1.GridRowModes.Edit,
769
- } }));
770
- }
771
- const msg = `Erro em "${e.path}": ${e.errors}`;
772
- setSnackBar({
773
- open: true,
774
- severity: 'error',
775
- msg,
776
- });
777
- console.log(e);
778
- }, components: {
779
- Toolbar: hideToolbarComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : CustomToolbar_1.CustomToolbar,
780
- Footer: hideFooterComponent ? () => react_1.default.createElement(react_1.default.Fragment, null) : FooterToolbar_1.FooterToolbar,
781
- }, componentsProps: {
782
- toolbar: {
783
- preparedColumns,
784
- setPreparedColumns,
785
- showQuickFilter: true,
786
- quickFilterProps: { debounceMs: 500 },
787
- // getRowsToExport: () => {
788
- // return [];
789
- // },
790
- selectionModel,
791
- onSelectActions,
792
- bulkUpdateData,
793
- bulkDeleteData,
794
- bulkCreateData,
795
- hideColumnsButton,
796
- hideFilterButton,
797
- hideDensityButton,
798
- hideExportButton,
799
- hideQuickFilterBar,
800
- },
801
- footer: {
802
- isEditable,
803
- handleAddItem: () => {
804
- handleAddItems();
805
- },
806
- },
807
- filterPanel: {
808
- sx: {
809
- '& .MuiDataGrid-filterFormValueInput': {
810
- width: 300,
811
- },
812
- },
813
- },
814
- }, experimentalFeatures: { newEditingApi: isEditable }, sx: customPaddings, paginationMode: paginationModel ? 'server' : 'client', onPageChange: (newPage) => {
815
- if (setPaginationModel && paginationModel) {
816
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { page: newPage }));
817
- }
818
- }, onPageSizeChange: (newPageSize) => {
819
- if (setPaginationModel && paginationModel) {
820
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { pageSize: newPageSize }));
821
- }
822
- }, 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
823
- ? (newFilter) => {
824
- if (setPaginationModel && paginationModel) {
825
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { filter: newFilter }));
826
- }
827
- }
828
- : undefined, sortingMode: paginationModel ? 'server' : 'client', onSortModelChange: paginationModel
829
- ? (newSorting) => {
830
- if (setPaginationModel && paginationModel) {
831
- setPaginationModel(Object.assign(Object.assign({}, paginationModel), { sort: newSorting }));
832
- }
833
- }
834
- : undefined })),
131
+ isMobile && MobileListRenderItem ? (react_1.default.createElement(DataGridMobile_1.default, { name: name, data: data, schema: schema, columns: columns, customColumnOperations: customColumnOperations, MobileListRenderItem: MobileListRenderItem })) : (react_1.default.createElement(DataGridDesktop_1.default, { schema: schema, dataGrid: dataGrid, setDataGrid: setDataGrid, rowCount: rowCount, columns: columns, model: model, name: name, indexField: indexField, addExistingModel: addExistingModel, indexFieldMinWidth: indexFieldMinWidth, indexFieldBasePath: indexFieldBasePath, indexFieldViewBasePath: indexFieldViewBasePath, stateToLink: stateToLink, minWidth: minWidth, loading: loading, modelParentId: modelParentId, modelParent: modelParent, customColumnOperations: customColumnOperations, customFieldFormLayouts: customFieldFormLayouts, customLinkDestination: customLinkDestination, LinkComponent: LinkComponent, onProcessRow: onProcessRow, onDataChange: onDataChange, onEditModel: onEditModel, isEditable: isEditable, hasBulkSelect: hasBulkSelect, onSelectActions: onSelectActions, isAutoHeight: isAutoHeight, defaultValues: defaultValues, hideFooterPagination: hideFooterPagination, setVisibleRows: setVisibleRows, paginationModel: paginationModel, setPaginationModel: setPaginationModel, hideFooterComponent: hideFooterComponent, hideToolbarComponent: hideToolbarComponent, tableAutoHeight: tableAutoHeight, actions: actions, customActions: customActions, hideColumnsButton: hideColumnsButton, hideFilterButton: hideFilterButton, hideDensityButton: hideDensityButton, hideExportButton: hideExportButton, hideQuickFilterBar: hideQuickFilterBar, optionsAC: optionsAC, extraValidators: extraValidators, emptyItem: emptyItem, handleDeleteClick: handleDeleteClick, setSnackBar: setSnackBar })),
835
132
  react_1.default.createElement(ConfirmDialog_1.ConfirmDialog, { open: confirmDialogOpen, onClose: handleConfirmDialogClose, onConfirm: handleDeleteSave }),
836
133
  react_1.default.createElement(Snackbar_1.default, { open: snackBar.open, autoHideDuration: 5000, onClose: () => {
837
134
  setSnackBar(Object.assign(Object.assign({}, initialSnackBar), { open: false }));