drf-react-by-schema 0.5.3 → 0.6.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.
@@ -46,18 +46,15 @@ const styles_1 = require("../styles");
46
46
  const api_1 = require("../api");
47
47
  const DRFReactBySchemaContext_1 = require("../context/DRFReactBySchemaContext");
48
48
  const APIWrapperContext_1 = require("../context/APIWrapperContext");
49
- const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, indexFieldBasePath, indexField, customColumnOperations, customLinkDestination, sumRows, isAutoHeight = true, model, forceReload = false, LinkComponent = null, hasHeader = false, }) => {
49
+ const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, indexFieldBasePath, indexField, customColumnOperations, customLinkDestination, sumRows, isAutoHeight = true, model, forceReload = false, LinkComponent = null, hasHeader = false, paginationMode = 'client', }) => {
50
50
  const context = react_1.default.useContext(DRFReactBySchemaContext_1.DRFReactBySchemaContext);
51
51
  const apiContext = react_1.default.useContext(APIWrapperContext_1.APIWrapperContext);
52
- if (!context.serverEndPoint || !apiContext) {
53
- console.error('Error: There is no endpoint defined in DRFReactBySchemaProvider!');
54
- return (react_1.default.createElement(react_1.default.Fragment, null));
55
- }
56
52
  const { serverEndPoint, isInBatches, firstBatchLength } = context;
57
53
  const { handleLoading } = apiContext;
58
54
  const [data, setData] = (0, react_1.useState)(false);
59
55
  const [visibleRows, setVisibleRows] = (0, react_1.useState)([]);
60
56
  const [hideFooterPagination, setHideFooterPagination] = (0, react_1.useState)(false);
57
+ const [paginationModel, setPaginationModel] = (0, react_1.useState)(paginationMode === 'server' ? { page: 0, pageSize: 2 } : undefined);
61
58
  const finalCustomColumnOperations = (column) => {
62
59
  if (minWidthFields) {
63
60
  if (Object.prototype.hasOwnProperty.call(minWidthFields, column.field)) {
@@ -70,33 +67,51 @@ const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, ind
70
67
  return column;
71
68
  };
72
69
  const loadObjectList = () => __awaiter(void 0, void 0, void 0, function* () {
73
- const loadParams = {
74
- model,
75
- serverEndPoint,
76
- columnFields,
77
- hiddenFields,
78
- isInBatches
79
- };
80
70
  handleLoading(true);
81
- const loadedData = yield (0, api_1.getGenericModelList)(loadParams);
82
- if (loadedData && typeof loadedData !== 'boolean') {
83
- setData(loadedData);
84
- handleLoading(false);
85
- if (isInBatches && loadedData.data.length === firstBatchLength) {
86
- setHideFooterPagination(true);
87
- (0, api_1.getGenericModelList)(Object.assign(Object.assign({}, loadParams), { loadedSchema: loadedData.schema, loadedModelOptions: loadedData.modelOptions })).then(lastBatchData => {
88
- if (lastBatchData && typeof lastBatchData !== 'boolean') {
89
- setData(Object.assign(Object.assign({}, loadedData), { data: [
90
- ...loadedData.data,
91
- ...lastBatchData.data
92
- ] }));
71
+ switch (paginationMode) {
72
+ case 'client':
73
+ const loadParams = {
74
+ model,
75
+ serverEndPoint,
76
+ columnFields,
77
+ hiddenFields,
78
+ isInBatches,
79
+ };
80
+ const loadedData = yield (0, api_1.getGenericModelList)(loadParams);
81
+ if (loadedData && typeof loadedData !== 'boolean') {
82
+ setData(loadedData);
83
+ handleLoading(false);
84
+ if (isInBatches && loadedData.data.length === firstBatchLength) {
85
+ setHideFooterPagination(true);
86
+ (0, api_1.getGenericModelList)(Object.assign(Object.assign({}, loadParams), { loadedSchema: loadedData.schema, loadedModelOptions: loadedData.modelOptions })).then((lastBatchData) => {
87
+ if (lastBatchData && typeof lastBatchData !== 'boolean') {
88
+ setData(Object.assign(Object.assign({}, loadedData), { data: [...loadedData.data, ...lastBatchData.data] }));
89
+ }
90
+ setHideFooterPagination(false);
91
+ });
93
92
  }
94
- setHideFooterPagination(false);
95
- });
96
- }
97
- return;
93
+ return;
94
+ }
95
+ console.log('error retrieving data!');
96
+ return;
97
+ case 'server':
98
+ const loadPaginatedParams = {
99
+ model,
100
+ serverEndPoint,
101
+ columnFields,
102
+ hiddenFields,
103
+ page: paginationModel ? paginationModel.page : 0,
104
+ filter: paginationModel ? paginationModel.filter : undefined,
105
+ };
106
+ const paginatedData = yield (0, api_1.getGenericModelList)(loadPaginatedParams);
107
+ if (paginatedData && typeof paginatedData !== 'boolean') {
108
+ setData(paginatedData);
109
+ handleLoading(false);
110
+ return;
111
+ }
112
+ console.log('error retrieving data!');
113
+ return;
98
114
  }
99
- console.log('error retrieving data!');
100
115
  });
101
116
  if (forceReload) {
102
117
  loadObjectList();
@@ -104,19 +119,29 @@ const GenericModelList = ({ columnFields, hiddenFields = [], minWidthFields, ind
104
119
  (0, react_1.useEffect)(() => {
105
120
  loadObjectList();
106
121
  }, [model]);
107
- return (react_1.default.createElement(react_1.default.Fragment, null, typeof data !== 'boolean' && data.columns &&
108
- react_1.default.createElement(react_1.default.Fragment, null,
109
- hasHeader &&
110
- react_1.default.createElement(Box_1.default, { sx: Object.assign(Object.assign({}, styles_1.Layout.flexRowGrow), { mb: 2 }) },
111
- react_1.default.createElement(Typography_1.default, { variant: "h5" }, data.modelOptions.verbose_name_plural || data.modelOptions.name),
112
- LinkComponent &&
113
- react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.flexRow },
114
- react_1.default.createElement(LinkComponent, { to: `novo` },
115
- react_1.default.createElement(Button_1.default, { variant: "contained", size: "medium", sx: { alignSelf: 'stretch' }, startIcon: react_1.default.createElement(AddCircleOutline_1.default, null) }, "Adicionar")))),
116
- react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.dataGridWithTabs },
117
- react_1.default.createElement(DataGridBySchemaEditable_1.default, { data: data.data, columns: data.columns, schema: data.schema || {}, model: model, indexField: indexField, indexFieldBasePath: indexFieldBasePath, isEditable: false, isAutoHeight: isAutoHeight, hideFooterPagination: hideFooterPagination, customColumnOperations: finalCustomColumnOperations, customLinkDestination: customLinkDestination, setVisibleRows: setVisibleRows, onDataChange: newData => {
118
- setData(Object.assign(Object.assign({}, data), { data: newData }));
119
- }, LinkComponent: LinkComponent })),
120
- react_1.default.createElement(DataTotals_1.default, { data: data.data, sumRows: sumRows, visibleRows: visibleRows }))));
122
+ (0, react_1.useEffect)(() => {
123
+ if (paginationMode === 'server') {
124
+ loadObjectList();
125
+ }
126
+ }, [paginationModel]);
127
+ if (!context.serverEndPoint || !apiContext) {
128
+ console.error('Error: There is no endpoint defined in DRFReactBySchemaProvider!');
129
+ return react_1.default.createElement(react_1.default.Fragment, null);
130
+ }
131
+ return (react_1.default.createElement(react_1.default.Fragment, null, typeof data !== 'boolean' && data.columns && (react_1.default.createElement(react_1.default.Fragment, null,
132
+ hasHeader && (react_1.default.createElement(Box_1.default, { sx: Object.assign(Object.assign({}, styles_1.Layout.flexRowGrow), { mb: 2 }) },
133
+ react_1.default.createElement(Typography_1.default, { variant: "h5" }, data.modelOptions.verbose_name_plural || data.modelOptions.name),
134
+ LinkComponent && (react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.flexRow },
135
+ react_1.default.createElement(LinkComponent, { to: `novo` },
136
+ react_1.default.createElement(Button_1.default, { variant: "contained", size: "medium", sx: { alignSelf: 'stretch' }, startIcon: react_1.default.createElement(AddCircleOutline_1.default, null) }, "Adicionar")))))),
137
+ react_1.default.createElement(Box_1.default, { sx: styles_1.Layout.dataGridWithTabs },
138
+ react_1.default.createElement(DataGridBySchemaEditable_1.default, { data: data.data, columns: data.columns, schema: data.schema || {}, model: model, indexField: indexField, indexFieldBasePath: indexFieldBasePath, isEditable: false, isAutoHeight: isAutoHeight, hideFooterPagination: hideFooterPagination, customColumnOperations: finalCustomColumnOperations, customLinkDestination: customLinkDestination, setVisibleRows: setVisibleRows, onDataChange: (newData) => {
139
+ setData(Object.assign(Object.assign({}, data), { data: newData }));
140
+ }, LinkComponent: LinkComponent, paginationModel: paginationMode === 'server' ? paginationModel : undefined, setPaginationModel: paginationMode === 'server' ? setPaginationModel : undefined, rowCount: paginationMode === 'client'
141
+ ? undefined
142
+ : typeof data.rowCount !== undefined
143
+ ? data.rowCount
144
+ : 0 })),
145
+ react_1.default.createElement(DataTotals_1.default, { data: data.data, sumRows: sumRows, visibleRows: visibleRows })))));
121
146
  };
122
147
  exports.default = GenericModelList;
@@ -62,7 +62,7 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
62
62
  return (react_1.default.createElement(react_1.default.Fragment, null, children));
63
63
  }
64
64
  const [usuaria, setUsuaria] = (0, react_1.useState)(null);
65
- const [optionsAC, setOptionsAC] = (0, react_1.useReducer)(utils_1.reducer, {});
65
+ const [optionsAC, setOptionsAC] = (0, react_1.useReducer)(utils_1.reducer, null);
66
66
  const initialPageForm = {
67
67
  id: '',
68
68
  schema: null,
@@ -91,7 +91,7 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
91
91
  severity
92
92
  });
93
93
  };
94
- const loadSinglePageData = ({ model, objId, optionsACModels, defaults = {}, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
94
+ const loadSinglePageData = ({ model, objId, optionsACModels = null, defaults = {}, extraValidators = {} }) => __awaiter(this, void 0, void 0, function* () {
95
95
  setLoading(true);
96
96
  if (!objId || objId === 'novo') {
97
97
  objId = (0, utils_1.getTmpId)();
@@ -107,7 +107,9 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
107
107
  return false;
108
108
  }
109
109
  setLoading(false);
110
- populateOptionsAC(optionsACModels);
110
+ if (optionsACModels) {
111
+ populateOptionsAC(optionsACModels);
112
+ }
111
113
  for (const [field, value] of Object.entries(defaults)) {
112
114
  if (!object.data[field]) {
113
115
  object.data[field] = value;
@@ -117,6 +119,10 @@ function APIWrapper({ setLoading, handleLoading, setSnackBar, setDialog, childre
117
119
  return values;
118
120
  });
119
121
  const onSubmit = (model, id, data) => __awaiter(this, void 0, void 0, function* () {
122
+ if (!pageForm) {
123
+ console.log('there must be a pageForm!');
124
+ return false;
125
+ }
120
126
  setLoading(true);
121
127
  const response = yield (0, api_1.updateDataBySchema)({
122
128
  model,
@@ -6,7 +6,7 @@ export interface LoadSinglePageDataProps {
6
6
  model: string;
7
7
  objId?: Id;
8
8
  objTitleField?: string;
9
- optionsACModels: string[];
9
+ optionsACModels: string[] | null;
10
10
  defaults?: Item;
11
11
  basePath?: string;
12
12
  formPath?: string | null;
@@ -62,12 +62,8 @@ export interface APIWrapperContextType {
62
62
  onSubmit: DRFReactBySchemaSubmitHandler;
63
63
  loadSinglePageData: (p: LoadSinglePageDataProps) => Promise<boolean | FieldValues>;
64
64
  handleLoading: (p: boolean) => void;
65
- optionsACState: [{
66
- [x: string]: any;
67
- }, React.Dispatch<OptionsACType>];
68
- pageFormState: [{
69
- [x: string]: any;
70
- }, React.Dispatch<PageFormType>];
65
+ optionsACState: [OptionsACType | null, React.Dispatch<OptionsACType>];
66
+ pageFormState: [Record<string, any> | null, React.Dispatch<PageFormType>];
71
67
  onEditModel: (p: OnEditModelType) => void;
72
68
  onDeleteModel: (model: string, id: Id, onSuccess?: (e: React.BaseSyntheticEvent) => any) => void;
73
69
  onEditRelatedModelSave: (p: OnEditRelatedModelType) => Promise<boolean | Id | ItemSchemaColumnsType>;
package/dist/utils.d.ts CHANGED
@@ -1,6 +1,17 @@
1
- import { GridActionsColDef, GridColDef } from '@mui/x-data-grid';
1
+ import { GridActionsColDef, GridColDef, GridFilterModel } from '@mui/x-data-grid';
2
2
  export type Id = string | number;
3
3
  export type Item = Record<string, any>;
4
+ export type PaginatedResult = {
5
+ count: number;
6
+ next: number;
7
+ previous: number;
8
+ results: Item[];
9
+ };
10
+ export interface PaginationModel {
11
+ page: number;
12
+ pageSize: number;
13
+ filter?: GridFilterModel;
14
+ }
4
15
  export type SchemaType = Record<string, Field>;
5
16
  export type modelOptionsType = Record<string, string>;
6
17
  export interface Choice {
@@ -24,7 +35,9 @@ export interface Field {
24
35
  prefix?: string;
25
36
  suffix?: string;
26
37
  creatable?: boolean;
38
+ related_editable?: boolean;
27
39
  validators_regex?: Item[];
40
+ many?: boolean;
28
41
  }
29
42
  interface GridBySchemaColDef extends GridColDef {
30
43
  isIndexField?: boolean;
@@ -41,6 +54,7 @@ interface GridActionsBySchemaColDef extends GridActionsColDef {
41
54
  export type GridEnrichedBySchemaColDef = GridBySchemaColDef | GridActionsBySchemaColDef;
42
55
  export interface DataSchemaColumnsType {
43
56
  data: Item[];
57
+ rowCount?: number;
44
58
  schema: SchemaType;
45
59
  modelOptions: modelOptionsType;
46
60
  columns?: GridEnrichedBySchemaColDef[];
@@ -76,9 +90,7 @@ export declare const errorProps: ({ type, errors, fieldKey, fieldKeyProp, index
76
90
  };
77
91
  export declare const getTmpId: () => string;
78
92
  export declare const isTmpId: (id: string | number | undefined | null) => boolean;
79
- export declare const reducer: (state: Record<string, any>, newState: Record<string, any>) => {
80
- [x: string]: any;
81
- };
93
+ export declare const reducer: (state: Record<string, any> | null, newState: Record<string, any>) => Record<string, any> | null;
82
94
  export declare const getPatternFormat: (type: string) => string;
83
95
  export type AddParametersToEnd<TFunction extends (...args: any) => any, TParameters extends [...args: any]> = (...args: [...Parameters<TFunction>, ...TParameters]) => ReturnType<TFunction>;
84
96
  export {};
package/dist/utils.js CHANGED
@@ -217,7 +217,7 @@ const buildGenericYupValidationSchema = ({ data, schema, many = false, skipField
217
217
  return val.toString().length <= maxDigits;
218
218
  });
219
219
  }
220
- if (field.validators_regex) {
220
+ if (!field.read_only && field.validators_regex) {
221
221
  for (const validator of field.validators_regex) {
222
222
  yupValidator[key] = yupValidator[key].matches(validator.regex, validator.message);
223
223
  }
@@ -256,6 +256,12 @@ const isTmpId = (id) => {
256
256
  };
257
257
  exports.isTmpId = isTmpId;
258
258
  const reducer = (state, newState) => {
259
+ if (newState === null) {
260
+ return null;
261
+ }
262
+ if (state === null) {
263
+ return newState;
264
+ }
259
265
  return Object.assign(Object.assign({}, state), newState);
260
266
  };
261
267
  exports.reducer = reducer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drf-react-by-schema",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "description": "Components and Tools for building a React App having Django Rest Framework (DRF) as server",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -45,10 +45,11 @@
45
45
  "@typescript-eslint/parser": "^5.47.0",
46
46
  "eslint": "^8.30.0",
47
47
  "eslint-config-prettier": "^8.5.0",
48
- "eslint-plugin-prettier": "^4.2.1",
48
+ "eslint-plugin-prettier": "^5.0.0",
49
49
  "eslint-plugin-react-hooks": "^4.6.0",
50
50
  "eslint-plugin-tsdoc": "^0.2.17",
51
51
  "install-peers-cli": "^2.2.0",
52
+ "prettier": "^3.0.0",
52
53
  "react-docgen-typescript": "^2.2.2",
53
54
  "react-styleguidist": "^13.0.0",
54
55
  "semver": "^7.5.1",