drf-react-by-schema 0.3.0 → 0.3.1

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 (83) hide show
  1. package/dist/api.d.ts +84 -0
  2. package/dist/api.js +613 -0
  3. package/dist/components/DataGridBySchemaEditable/ConfirmDialog.d.ts +8 -0
  4. package/dist/components/DataGridBySchemaEditable/ConfirmDialog.js +21 -0
  5. package/dist/components/DataGridBySchemaEditable/CustomToolbar.d.ts +16 -0
  6. package/dist/components/DataGridBySchemaEditable/CustomToolbar.js +77 -0
  7. package/dist/components/DataGridBySchemaEditable/FooterToolbar.d.ts +16 -0
  8. package/dist/components/DataGridBySchemaEditable/FooterToolbar.js +41 -0
  9. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.d.ts +8 -0
  10. package/dist/components/DataGridBySchemaEditable/GridDecimalInput.js +32 -0
  11. package/dist/components/DataGridBySchemaEditable/GridPatternInput.d.ts +8 -0
  12. package/dist/components/DataGridBySchemaEditable/GridPatternInput.js +30 -0
  13. package/dist/components/DataGridBySchemaEditable/InputInterval.d.ts +3 -0
  14. package/dist/components/DataGridBySchemaEditable/InputInterval.js +105 -0
  15. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.d.ts +33 -0
  16. package/dist/components/DataGridBySchemaEditable/SelectEditInputCell.js +140 -0
  17. package/dist/components/DataGridBySchemaEditable/utils.d.ts +15 -0
  18. package/{src/components/DataGridBySchemaEditable/utils.ts → dist/components/DataGridBySchemaEditable/utils.js} +32 -50
  19. package/dist/components/DataGridBySchemaEditable.d.ts +34 -0
  20. package/dist/components/DataGridBySchemaEditable.js +549 -0
  21. package/dist/components/DataTotals.d.ts +14 -0
  22. package/dist/components/DataTotals.js +23 -0
  23. package/dist/components/DialogActions.d.ts +10 -0
  24. package/dist/components/DialogActions.js +17 -0
  25. package/dist/components/DialogJSONSchemaForm.d.ts +12 -0
  26. package/dist/components/DialogJSONSchemaForm.js +20 -0
  27. package/dist/components/FormButtons.d.ts +14 -0
  28. package/dist/components/FormButtons.js +39 -0
  29. package/dist/components/GenericModelList.d.ts +19 -0
  30. package/dist/components/GenericModelList.js +113 -0
  31. package/dist/components/GenericRelatedModelList.d.ts +25 -0
  32. package/dist/components/GenericRelatedModelList.js +111 -0
  33. package/dist/components/TextFieldBySchema.js +39 -0
  34. package/dist/context/APIWrapper.d.ts +12 -0
  35. package/dist/context/APIWrapper.js +341 -0
  36. package/{src/context/APIWrapperContext.tsx → dist/context/APIWrapperContext.d.ts} +22 -31
  37. package/dist/context/APIWrapperContext.js +15 -0
  38. package/{src/context/DRFReactBySchemaContext.tsx → dist/context/DRFReactBySchemaContext.d.ts} +4 -17
  39. package/dist/context/DRFReactBySchemaContext.js +19 -0
  40. package/dist/context/DRFReactBySchemaProvider.d.ts +13 -0
  41. package/dist/context/DRFReactBySchemaProvider.js +53 -0
  42. package/dist/context/Form.d.ts +11 -0
  43. package/dist/context/Form.js +82 -0
  44. package/dist/context/Overlays.d.ts +4 -0
  45. package/dist/context/Overlays.js +87 -0
  46. package/dist/index.d.ts +11 -0
  47. package/{src/styles/index.ts → dist/styles/index.d.ts} +0 -1
  48. package/dist/styles/index.js +28 -0
  49. package/dist/styles/layout.d.ts +107 -0
  50. package/dist/styles/layout.js +56 -0
  51. package/dist/styles/theme.d.ts +21 -0
  52. package/dist/styles/theme.js +139 -0
  53. package/dist/utils.d.ts +75 -0
  54. package/dist/utils.js +268 -0
  55. package/package.json +11 -2
  56. package/.eslintrc.js +0 -14
  57. package/.gitlab-ci.yml +0 -14
  58. package/src/api.ts +0 -727
  59. package/src/components/DataGridBySchemaEditable/ConfirmDialog.tsx +0 -41
  60. package/src/components/DataGridBySchemaEditable/CustomToolbar.tsx +0 -93
  61. package/src/components/DataGridBySchemaEditable/FooterToolbar.tsx +0 -77
  62. package/src/components/DataGridBySchemaEditable/GridDecimalInput.tsx +0 -41
  63. package/src/components/DataGridBySchemaEditable/GridPatternInput.tsx +0 -37
  64. package/src/components/DataGridBySchemaEditable/InputInterval.tsx +0 -194
  65. package/src/components/DataGridBySchemaEditable/SelectEditInputCell.tsx +0 -154
  66. package/src/components/DataGridBySchemaEditable.md +0 -50
  67. package/src/components/DataGridBySchemaEditable.tsx +0 -758
  68. package/src/components/DataTotals.tsx +0 -57
  69. package/src/components/DialogActions.tsx +0 -33
  70. package/src/components/DialogJSONSchemaForm.tsx +0 -40
  71. package/src/components/GenericModelList.tsx +0 -165
  72. package/src/components/GenericRelatedModelList.tsx +0 -168
  73. package/src/context/APIWrapper.tsx +0 -447
  74. package/src/context/DRFReactBySchemaProvider.md +0 -57
  75. package/src/context/DRFReactBySchemaProvider.tsx +0 -72
  76. package/src/context/Overlays.tsx +0 -94
  77. package/src/index.ts +0 -77
  78. package/src/styles/layout.ts +0 -104
  79. package/src/styles/theme.ts +0 -190
  80. package/src/utils.ts +0 -327
  81. package/styleguide.config.js +0 -13
  82. package/tsconfig.json +0 -104
  83. package/webpack.config.js +0 -24
@@ -1,447 +0,0 @@
1
- import React, { useState, useReducer, useEffect, useRef } from 'react';
2
- import {
3
- Id,
4
- Item,
5
- reducer,
6
- SchemaType,
7
- populateValues,
8
- buildGenericYupValidationSchema,
9
- getTmpId,
10
- isTmpId
11
- } from '../utils';
12
-
13
- import DialogJSONSchemaForm from '../components/DialogJSONSchemaForm';
14
- import DialogActions from '../components/DialogActions';
15
- import { DRFReactBySchemaContext, DRFReactBySchemaContextType } from './DRFReactBySchemaContext';
16
- import {
17
- isLoggedIn,
18
- getAutoComplete,
19
- getGenericModel,
20
- updateDataBySchema,
21
- addExistingRelatedModel,
22
- deleteData,
23
- getJSONSchema,
24
- createOrUpdateJSONSchema
25
- } from '../api';
26
- import { AxiosResponse } from 'axios';
27
- import {
28
- APIWrapperContext,
29
- DialogType,
30
- LoadSinglePageDataProps,
31
- OnDeleteRelatedModelType,
32
- OnEditModelType,
33
- OnEditRelatedModelType,
34
- PageFormType,
35
- SnackBarType
36
- } from './APIWrapperContext';
37
-
38
- interface APIWrapperProps {
39
- setLoading: React.Dispatch<React.SetStateAction<boolean>>;
40
- handleLoading: (p: boolean) => void;
41
- setSnackBar: React.Dispatch<React.SetStateAction<SnackBarType>>;
42
- setDialog: React.Dispatch<React.SetStateAction<DialogType>>;
43
- children: React.ReactNode;
44
- };
45
-
46
- function APIWrapper ({
47
- setLoading,
48
- handleLoading,
49
- setSnackBar,
50
- setDialog,
51
- children
52
- }:APIWrapperProps) {
53
- const { serverEndPoint } = DRFReactBySchemaContext
54
- ? React.useContext(DRFReactBySchemaContext) as DRFReactBySchemaContextType
55
- : { serverEndPoint: null };
56
- if (!serverEndPoint) {
57
- return (
58
- <>
59
- {children}
60
- </>
61
- );
62
- }
63
-
64
- const [usuaria, setUsuaria] = useState<Item | null>(null);
65
- const [optionsAC, setOptionsAC] = useReducer(reducer, {});
66
- const initialPageForm:PageFormType = {
67
- id: '',
68
- schema: null,
69
- initialValues: null,
70
- validationSchema: null
71
- };
72
- const [pageForm, setPageForm] = useReducer(reducer, initialPageForm);
73
- const editModel = useRef<Item>({});
74
- const jsonSchemaFormRef = useRef<any>(null);
75
-
76
- useEffect(() => {
77
- setUsuaria(null);
78
- isLoggedIn(serverEndPoint).then(usuaria => {
79
- setUsuaria(usuaria || { erro: 'token inválido' });
80
- });
81
- }, []);
82
-
83
- useEffect(() => {
84
- setPageForm(initialPageForm);
85
- }, []);
86
-
87
- const onTriggerSnackBar = ({ msg, severity = 'info' }:SnackBarType) => {
88
- setSnackBar({
89
- open: true,
90
- msg,
91
- severity
92
- });
93
- };
94
-
95
- const loadSinglePageData = async ({
96
- model,
97
- objId,
98
- objTitleField = 'nome',
99
- optionsACModels,
100
- basePath = '/',
101
- formPath = null,
102
- extraValidators = {}
103
- }: LoadSinglePageDataProps) => {
104
- setLoading(true);
105
- if (objId === 'novo') {
106
- objId = getTmpId();
107
- }
108
-
109
- const object = await getGenericModel({
110
- model,
111
- serverEndPoint,
112
- id: isTmpId(objId) ? null : objId
113
- });
114
-
115
- if (object === false) {
116
- setPageForm({ schema: false, id: '' });
117
- console.log('Houve um erro ao tentar carregar os dados!');
118
- return false;
119
- }
120
-
121
- setLoading(false);
122
-
123
- populateOptionsAC(optionsACModels);
124
-
125
- const values = populateInitialValues({
126
- model,
127
- id: objId,
128
- extraValidators,
129
- ...object
130
- });
131
-
132
- return values;
133
- };
134
-
135
- const onSubmit = async (
136
- model:string,
137
- id:Id,
138
- data:Item,
139
- e:React.SyntheticEvent<HTMLButtonElement, SubmitEvent>
140
- ) => {
141
- setLoading(true);
142
- const response = await updateDataBySchema({
143
- model,
144
- modelObjectId: id,
145
- serverEndPoint,
146
- data,
147
- schema: pageForm.schema
148
- });
149
- setLoading(false);
150
- if (!['number', 'string'].includes(typeof response)) {
151
- onTriggerSnackBar({
152
- msg: 'Houve um problema ao salvar seus dados! Por favor, entre em contato',
153
- severity: 'error'
154
- });
155
- console.log({
156
- msg: 'Error saving model',
157
- errors: response,
158
- data
159
- });
160
- return false;
161
- }
162
-
163
- onTriggerSnackBar({
164
- msg: (id)
165
- ? 'Dados atualizados com sucesso!'
166
- : 'Criado com sucesso!'
167
- });
168
-
169
- return response as Id;
170
- };
171
-
172
- const populateOptionsAC = (optionsACModels:string[]) => {
173
- for (const model of optionsACModels) {
174
- getAutoComplete({ model, serverEndPoint }).then(options => {
175
- setOptionsAC({ [model]: options });
176
- });
177
- }
178
- };
179
-
180
- interface PopulateInitialValuesProps {
181
- model: string;
182
- id: Id;
183
- data: Item;
184
- schema: SchemaType;
185
- extraValidators: Item;
186
- isEditModel?: boolean;
187
- };
188
- const populateInitialValues = ({
189
- model,
190
- id,
191
- isEditModel,
192
- extraValidators,
193
- ...object
194
- }:PopulateInitialValuesProps) => {
195
- const values = populateValues(object);
196
- const yupSchema = buildGenericYupValidationSchema({ ...object, data: values, extraValidators });
197
- setPageForm({
198
- model,
199
- id,
200
- schema: object.schema,
201
- initialValues: values,
202
- validationSchema: yupSchema
203
- });
204
- return values;
205
- };
206
-
207
- const onEditModel = ({
208
- fieldKey,
209
- index,
210
- model,
211
- id,
212
- labelKey,
213
- setValue,
214
- getValues
215
- }: OnEditModelType) => {
216
- setDialog({
217
- open: true,
218
- loading: true
219
- });
220
- getJSONSchema({ model, serverEndPoint, id }).then(data => {
221
- const jsonSchemaSubmit = async (e:React.SyntheticEvent<HTMLElement, SubmitEvent>) => {
222
- jsonSchemaFormRef.current.onSubmit(e);
223
- return true;
224
- };
225
- setDialog({
226
- loading: false,
227
- title: 'Editar',
228
- Body: <DialogJSONSchemaForm
229
- jsonSchemaFormRef = {jsonSchemaFormRef}
230
- schema = {data.serializer.schema}
231
- uiSchema = {data.serializer.uiSchema}
232
- formData = {data.formData}
233
- onSubmit = {onEditModelSave}
234
- />,
235
- Actions: <DialogActions
236
- setDialog = {setDialog}
237
- handleSave = {jsonSchemaSubmit}
238
- />
239
- } as DialogType);
240
- editModel.current = {
241
- fieldKey,
242
- index,
243
- model,
244
- id,
245
- labelKey,
246
- setValue,
247
- getValues
248
- };
249
- });
250
- };
251
-
252
- const onEditModelSave = async ({ formData }:{ formData: Item }) => {
253
- setDialog({ open: false });
254
- setLoading(true);
255
- const {
256
- fieldKey,
257
- index,
258
- model,
259
- id,
260
- labelKey,
261
- setValue,
262
- getValues
263
- } = editModel.current;
264
- const newModelId = await createOrUpdateJSONSchema({
265
- model,
266
- serverEndPoint,
267
- id,
268
- formData
269
- });
270
- if (newModelId.errors) {
271
- console.log(newModelId.errors);
272
- onTriggerSnackBar({
273
- msg: 'Houve um problema ao salvar a alteração! Por favor, entre em contato.',
274
- severity: 'error'
275
- });
276
- return;
277
- }
278
- onTriggerSnackBar({
279
- msg: 'Alterações salvas com sucesso!',
280
- severity: 'info'
281
- });
282
- const targetKey = (fieldKey && index >= 0)
283
- ? `${fieldKey}.${index}.${model}`
284
- : model;
285
- const newValue = {
286
- ...getValues(targetKey),
287
- ...formData,
288
- label: formData[labelKey]
289
- };
290
- setValue(targetKey, newValue);
291
- populateOptionsAC([model]);
292
- setLoading(false);
293
- };
294
-
295
- const onDeleteModel = (model:string, id:Id, onSuccess:()=>void | null) => {
296
- setDialog({
297
- open: true,
298
- loading: false,
299
- title: 'Apagar',
300
- Body: 'Tem certeza de que deseja apagar este item?',
301
- Actions: <DialogActions
302
- setDialog = {setDialog}
303
- handleSave = {(e:React.SyntheticEvent) => {
304
- return onDeleteModelSave(model, id, onSuccess);
305
- }}
306
- btnConfirm = "Sim, apagar"
307
- />
308
- });
309
- };
310
-
311
- const onDeleteModelSave = async (model:string, id:Id, onSuccess:()=>void | null) => {
312
- setDialog({ open: false });
313
- setLoading(true);
314
- const ret = await deleteData(model, serverEndPoint, id);
315
- if (ret !== false) {
316
- onTriggerSnackBar({
317
- msg: 'Apagado com com sucesso!',
318
- severity: 'info'
319
- });
320
- if (onSuccess !== null) {
321
- onSuccess();
322
- }
323
- return true;
324
- }
325
-
326
- setLoading(false);
327
- onTriggerSnackBar({
328
- msg: 'Houve um problema ao remover o item! Por favor, entre em contato.',
329
- severity: 'error'
330
- });
331
- return false;
332
- };
333
-
334
- const onEditRelatedModelSave = async ({
335
- model,
336
- id,
337
- relatedModel,
338
- relatedModelId,
339
- newRow,
340
- schema,
341
- onlyAddExisting
342
- }:OnEditRelatedModelType) => {
343
- const updateUrl = `${model}/${id}/${relatedModel}`;
344
- if (onlyAddExisting) {
345
- const response = await addExistingRelatedModel({
346
- model,
347
- id,
348
- serverEndPoint,
349
- data: {
350
- onlyAddExisting: {
351
- key: relatedModel,
352
- value: newRow.id_to_add
353
- }
354
- }
355
- });
356
- if (Object.prototype.hasOwnProperty.call(response, 'errors')) {
357
- console.log(response);
358
- onTriggerSnackBar({
359
- msg: 'Houve um problema ao salvar a alteração! Por favor, entre em contato.',
360
- severity: 'error'
361
- });
362
- return false;
363
- }
364
- onTriggerSnackBar({
365
- msg: 'Alterações salvas com sucesso!',
366
- severity: 'info'
367
- });
368
- const object = await getGenericModel({
369
- model,
370
- id,
371
- serverEndPoint,
372
- relatedModel,
373
- relatedModelId: newRow.id_to_add
374
- });
375
- return object;
376
- }
377
- // This is important for related data
378
- if (schema[model] && !newRow[model]) {
379
- newRow[model] = id;
380
- }
381
- const response = await updateDataBySchema({
382
- model: relatedModel,
383
- modelObjectId: newRow.id,
384
- serverEndPoint,
385
- data: newRow,
386
- schema,
387
- path: updateUrl
388
- });
389
- if (response && !Object.prototype.hasOwnProperty.call(response, 'errors')) {
390
- onTriggerSnackBar({
391
- msg: 'Alterações salvas com sucesso!',
392
- severity: 'info'
393
- });
394
- return response as Id;
395
- }
396
- onTriggerSnackBar({
397
- msg: 'Não foi possível salvar os dados. Confira os erros.',
398
- severity: 'error'
399
- });
400
- return false;
401
- };
402
-
403
- const onDeleteRelatedModel = async ({
404
- model,
405
- id,
406
- relatedModel,
407
- relatedModelId
408
- }:OnDeleteRelatedModelType) => {
409
- const deleteUrl = `${model}/${id}/${relatedModel}`;
410
- const response = await deleteData(deleteUrl, serverEndPoint, relatedModelId);
411
- if (response) {
412
- onTriggerSnackBar({
413
- msg: 'Alterações salvas com sucesso!',
414
- severity: 'info'
415
- });
416
- return response;
417
- }
418
- onTriggerSnackBar({
419
- msg: 'Houve um problema ao remover o item! Por favor, entre em contato.',
420
- severity: 'error'
421
- });
422
- return false;
423
- };
424
-
425
- return (
426
- <APIWrapperContext.Provider
427
- value = {{
428
- usuaria,
429
- onSubmit,
430
- loadSinglePageData,
431
- handleLoading,
432
- optionsACState: [optionsAC, setOptionsAC],
433
- pageFormState: [pageForm, setPageForm],
434
- onEditModel,
435
- onDeleteModel,
436
- onEditRelatedModelSave,
437
- onDeleteRelatedModel,
438
- onTriggerSnackBar,
439
- setDialog
440
- }}
441
- >
442
- {children}
443
- </APIWrapperContext.Provider>
444
- );
445
- }
446
-
447
- export default React.memo(APIWrapper);
@@ -1,57 +0,0 @@
1
- ```js
2
- /*
3
- import Box from '@mui/material/Box';
4
- import DataGridBySchemaEditable from '../components/DataGridBySchemaEditable';
5
- import { APIWrapperContext } from '../context/APIWrapperContext';
6
-
7
- const data = {
8
- data: [],
9
- columns: [],
10
- schema: {}
11
- };
12
- const model = 'example';
13
- const indexField = null;
14
- const indexFieldBasePath = null;
15
- const isAutoHeight = true;
16
- const hideFooterPagination = false;
17
- const finalCustomColumnOperations = null;
18
- const customLinkDestination = null;
19
- const setVisibleRows = null;
20
- const setData = (newData) => {
21
- return '';
22
- };
23
- const Link = null;
24
- <DRFReactBySchemaProvider
25
- serverEndPoint={{
26
- url: 'https://icv.eita.org.br/api',
27
- apiTokenUrl: 'https://icv.eita.org.br/api-auth/token'
28
- }}
29
- >
30
- <Box sx={{ height: 300px }}>
31
- <DataGridBySchemaEditable
32
- data={data.data}
33
- columns={data.columns}
34
- schema={data.schema}
35
- model={model}
36
- indexField={indexField}
37
- indexFieldBasePath={indexFieldBasePath}
38
- isEditable={false}
39
- isAutoHeight={isAutoHeight}
40
- hideFooterPagination={hideFooterPagination}
41
- customColumnOperations={finalCustomColumnOperations}
42
- customLinkDestination={customLinkDestination}
43
- setVisibleRows={setVisibleRows}
44
- onDataChange={newData => {
45
- const apiContext = React.useContext(APIWrapperContext);
46
- apiContext.handleLoading(false);
47
- setData({
48
- ...data,
49
- data: newData
50
- });
51
- }}
52
- LinkComponent={Link}
53
- />
54
- </Box>
55
- </DRFReactBySchemaProvider>
56
- */
57
- ```
@@ -1,72 +0,0 @@
1
- import React from 'react';
2
- import { ThemeProvider, Theme } from '@mui/material/styles';
3
- import CssBaseline from '@mui/material/CssBaseline';
4
-
5
- import defaultTheme from '../styles/theme';
6
- import Overlays from './Overlays';
7
- import { DRFReactBySchemaContextType, serverEndPointType, DRFReactBySchemaContext } from './DRFReactBySchemaContext';
8
-
9
- interface DRFReactBySchemaProviderProps extends DRFReactBySchemaContextType {
10
- children: React.ReactNode;
11
- }
12
-
13
- /**
14
- *
15
- *
16
- * @param {*} props
17
- * @returns {*}
18
- */
19
- const DRFReactBySchemaProvider = ({
20
- serverEndPoint,
21
- theme,
22
- isInBatches,
23
- firstBatchLength,
24
- children
25
- }: DRFReactBySchemaProviderProps) => {
26
- if (serverEndPoint) {
27
- const defaultKeys = [
28
- 'autocomplete',
29
- 'api',
30
- ['JSONSchema', 'jsonschema'],
31
- ['getToken', ''],
32
- ['refreshToken', 'refresh'],
33
- ['verifyToken', 'verify']
34
- ];
35
- for (const key of defaultKeys) {
36
- const hybridKey = (typeof key === 'string')
37
- ? key as keyof serverEndPointType
38
- : key[0] as keyof serverEndPointType;
39
- const hybridUrl = (typeof key === 'string')
40
- ? key
41
- : key[1];
42
- if (serverEndPoint[hybridKey]) {
43
- continue;
44
- }
45
- serverEndPoint[hybridKey] = `${serverEndPoint.url}/${hybridUrl}`;
46
- }
47
- }
48
-
49
- const mergedTheme = (theme)
50
- ? { ...defaultTheme, ...theme }
51
- : defaultTheme;
52
-
53
- return (
54
- <ThemeProvider theme={mergedTheme}>
55
- <CssBaseline />
56
- <DRFReactBySchemaContext.Provider
57
- value={{
58
- serverEndPoint,
59
- theme,
60
- isInBatches,
61
- firstBatchLength
62
- }}
63
- >
64
- <Overlays
65
- children = {children}
66
- />
67
- </DRFReactBySchemaContext.Provider>
68
- </ThemeProvider>
69
- );
70
- }
71
-
72
- export default DRFReactBySchemaProvider;
@@ -1,94 +0,0 @@
1
- import React, { useState, useReducer } from 'react';
2
- import Backdrop from '@mui/material/Backdrop';
3
- import CircularProgress from '@mui/material/CircularProgress';
4
- import Snackbar from '@mui/material/Snackbar';
5
- import Alert from '@mui/material/Alert';
6
- import Dialog from '@mui/material/Dialog';
7
- import DialogActions from '@mui/material/DialogActions';
8
- import DialogContent from '@mui/material/DialogContent';
9
- import DialogTitle from '@mui/material/DialogTitle';
10
- import Box from '@mui/material/Box';
11
-
12
- import { reducer } from '../utils';
13
- import APIWrapper from './APIWrapper';
14
- import { DialogType, SnackBarType } from './APIWrapperContext';
15
-
16
- export default function Overlays ({ children }: { children:React.ReactNode }) {
17
- const initialSnackBar:SnackBarType = {
18
- open: false,
19
- msg: '',
20
- severity: 'info'
21
- };
22
-
23
- const initialDialog:DialogType = {
24
- open: false,
25
- loading: true,
26
- title: '',
27
- Body: null,
28
- Actions: null
29
- };
30
- const [snackBar, setSnackBar] = useReducer(reducer, initialSnackBar);
31
- const [dialog, setDialog] = useReducer(reducer, initialDialog);
32
- const [loading, setLoading] = useState<boolean>(true);
33
-
34
- // give some time to stop loading when data is retrieved and must render before loading rendering:
35
- const handleLoading = (loadingState:boolean) => {
36
- if (loadingState) {
37
- setLoading(true);
38
- return;
39
- }
40
- setTimeout(() => {
41
- setLoading(false);
42
- }, 300);
43
- };
44
-
45
- const handleDialogClose = () => {
46
- setDialog({
47
- open: false
48
- });
49
- };
50
-
51
- return (
52
- <>
53
- <APIWrapper
54
- setLoading={setLoading}
55
- handleLoading={handleLoading}
56
- setSnackBar={setSnackBar}
57
- setDialog={setDialog}
58
- children={children}
59
- />
60
- <Backdrop
61
- sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
62
- open={loading}
63
- >
64
- <CircularProgress />
65
- </Backdrop>
66
- <Snackbar
67
- open={snackBar.open}
68
- autoHideDuration={3000}
69
- onClose={() => { setSnackBar({ open: false }); }}
70
- anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
71
- >
72
- <Alert severity={snackBar.severity}>
73
- {snackBar.msg}
74
- </Alert>
75
- </Snackbar>
76
- <Dialog open={dialog.open} onClose={handleDialogClose}>
77
- <DialogTitle>
78
- {dialog.loading ? 'Carregando...' : dialog.title}
79
- </DialogTitle>
80
- <DialogContent>
81
- {dialog.loading
82
- ? <Box sx={{ display: 'flex' }}><CircularProgress /></Box>
83
- : <>{dialog.Body}</>
84
- }
85
- </DialogContent>
86
- <DialogActions>
87
- {!dialog.loading &&
88
- <>{dialog.Actions}</>
89
- }
90
- </DialogActions>
91
- </Dialog>
92
- </>
93
- );
94
- }