@dakataa/crud-react 1.0.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.
- package/.env +3 -0
- package/README.md +58 -0
- package/babel-plugin-macros.config.js +5 -0
- package/index.html +12 -0
- package/package.json +74 -0
- package/public/favicon.ico +0 -0
- package/public/logo192.png +0 -0
- package/public/logo512.png +0 -0
- package/public/manifest.json +25 -0
- package/public/robots.txt +3 -0
- package/src/Crud.tsx +29 -0
- package/src/CrudContext.tsx +21 -0
- package/src/CrudLoader.tsx +27 -0
- package/src/assets/images/alert/denied.json +1 -0
- package/src/assets/images/alert/info.json +1 -0
- package/src/assets/images/alert/success.json +1 -0
- package/src/assets/images/alert/warning.json +1 -0
- package/src/assets/style/alert.scss +97 -0
- package/src/component/Animation.tsx +50 -0
- package/src/component/BaseButton.tsx +26 -0
- package/src/component/Button.tsx +15 -0
- package/src/component/Dropdown.tsx +55 -0
- package/src/component/EmptyView.tsx +5 -0
- package/src/component/Link.tsx +11 -0
- package/src/component/Modal.tsx +174 -0
- package/src/component/ModifyForm.tsx +139 -0
- package/src/component/TemplateBlock.tsx +21 -0
- package/src/component/TemplateExtend.tsx +17 -0
- package/src/component/TemplateParentBlock.tsx +7 -0
- package/src/component/Translation.tsx +7 -0
- package/src/component/ViewLoader.tsx +33 -0
- package/src/component/crud/DynamicView.tsx +42 -0
- package/src/component/crud/FormView.tsx +29 -0
- package/src/component/crud/GridTableView.tsx +205 -0
- package/src/component/crud/PaginatorView.tsx +80 -0
- package/src/component/error/ErrorBoundary.tsx +78 -0
- package/src/component/error/Exception.tsx +17 -0
- package/src/component/error/HttpException.tsx +24 -0
- package/src/component/form/Choice.tsx +119 -0
- package/src/component/form/Form.tsx +233 -0
- package/src/component/form/FormAlert.tsx +19 -0
- package/src/component/form/FormFieldError.tsx +16 -0
- package/src/component/form/FormGroup.tsx +53 -0
- package/src/component/form/FormWidget.tsx +34 -0
- package/src/component/form/Input.tsx +63 -0
- package/src/component/form/constraint/Contraint.tsx +8 -0
- package/src/component/form/constraint/NotBlank.tsx +20 -0
- package/src/component/hooks/GetData.tsx +137 -0
- package/src/context/ActionContext.tsx +99 -0
- package/src/context/AlertContext.tsx +181 -0
- package/src/context/ModalContext.tsx +56 -0
- package/src/context/SessionContext.tsx +97 -0
- package/src/helper/ObjectUtils.tsx +36 -0
- package/src/helper/RouterUtils.tsx +24 -0
- package/src/helper/StingUtils.tsx +25 -0
- package/src/index.tsx +23 -0
- package/src/layout/default/Base.tsx +15 -0
- package/src/layout/default/Error.tsx +27 -0
- package/src/layout/default/Main.tsx +64 -0
- package/src/layout/default/component/Navigation.tsx +197 -0
- package/src/page/List.tsx +268 -0
- package/src/page/Modify.tsx +156 -0
- package/src/react-app-env.d.ts +2 -0
- package/src/setupTests.ts +5 -0
- package/src/type/ActionType.tsx +10 -0
- package/src/type/ColumnType.tsx +18 -0
- package/src/type/ExceptionType.tsx +7 -0
- package/src/type/FormType.tsx +6 -0
- package/src/type/FormViewType.tsx +37 -0
- package/src/type/ListMetaType.tsx +7 -0
- package/src/type/ListType.tsx +20 -0
- package/src/type/ModifyType.tsx +10 -0
- package/src/type/RedirectType.tsx +6 -0
- package/src/type/RouteType.tsx +5 -0
- package/tsconfig.app.json +46 -0
- package/tsconfig.json +11 -0
- package/tsconfig.node.json +15 -0
- package/vite.config.ts +33 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import React, {ForwardedRef, forwardRef, useEffect, useImperativeHandle, useReducer, useRef} from "react";
|
|
2
|
+
import {Constraint} from "@src/component/form/constraint/Contraint";
|
|
3
|
+
|
|
4
|
+
export type FormError = {
|
|
5
|
+
message: string;
|
|
6
|
+
messageParameters?: { [key: string]: string };
|
|
7
|
+
messageTemplate?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const FormContext: any = React.createContext<any>(null);
|
|
11
|
+
|
|
12
|
+
export function useForm(): any {
|
|
13
|
+
const context = React.useContext(FormContext);
|
|
14
|
+
if (!context) {
|
|
15
|
+
throw new Error("useForm must be used in Form");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return context;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type FormStatePayload = {
|
|
22
|
+
action: string;
|
|
23
|
+
payload: any;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type FormState = {
|
|
27
|
+
response?: any;
|
|
28
|
+
constraints?: any;
|
|
29
|
+
errors?: { [key: string]: FormError[] };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type FormProps = {
|
|
33
|
+
children?: any,
|
|
34
|
+
onComplete?: Function,
|
|
35
|
+
onError?: Function,
|
|
36
|
+
onSubmit?: Function,
|
|
37
|
+
onBeforeSubmit?: Function,
|
|
38
|
+
onReset?: Function,
|
|
39
|
+
action?: string,
|
|
40
|
+
method?: 'GET' | 'POST',
|
|
41
|
+
className?: string,
|
|
42
|
+
data?: FormData,
|
|
43
|
+
id?: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type FormRef = {
|
|
47
|
+
getFormData: () => FormData,
|
|
48
|
+
setFormData: (data: FormData) => void,
|
|
49
|
+
setErrors: Function,
|
|
50
|
+
reset: Function,
|
|
51
|
+
submit: Function
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const nameToId = (name: string, index: number | null = null) => (
|
|
55
|
+
name
|
|
56
|
+
.replace(/[\[\]]/gi, '_')
|
|
57
|
+
.replace(/_+/gi, '_')
|
|
58
|
+
.replace(/([a-zA-Z])(?=[A-Z])/g, '$1_')
|
|
59
|
+
+ (index ?? '')
|
|
60
|
+
).toLowerCase();
|
|
61
|
+
|
|
62
|
+
export const Form = forwardRef(({
|
|
63
|
+
id,
|
|
64
|
+
children,
|
|
65
|
+
data,
|
|
66
|
+
onError,
|
|
67
|
+
onBeforeSubmit,
|
|
68
|
+
onSubmit: onSubmitCallback,
|
|
69
|
+
onReset: onResetCallback,
|
|
70
|
+
...props
|
|
71
|
+
}: FormProps, ref: ForwardedRef<FormRef>) => {
|
|
72
|
+
const formElementRef = useRef<HTMLFormElement | null>(null);
|
|
73
|
+
const initialState: FormState = {
|
|
74
|
+
response: null,
|
|
75
|
+
constraints: {},
|
|
76
|
+
errors: {}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const handler: FormRef = {
|
|
80
|
+
getFormData: () => new FormData(formElementRef.current || undefined),
|
|
81
|
+
setFormData: (data: FormData) => {
|
|
82
|
+
[...formElementRef.current?.elements || []].forEach((inputEl: any) => {
|
|
83
|
+
const value: any = data.get(inputEl.name);
|
|
84
|
+
|
|
85
|
+
switch (inputEl.tagName.toLowerCase()) {
|
|
86
|
+
case 'select': {
|
|
87
|
+
if(inputEl.multiple) {
|
|
88
|
+
[...(inputEl as HTMLSelectElement).options].forEach((element: HTMLOptionElement) => {
|
|
89
|
+
element.selected = data.getAll(inputEl.name).includes(element.value);
|
|
90
|
+
})
|
|
91
|
+
} else {
|
|
92
|
+
inputEl.value = value;
|
|
93
|
+
}
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
default: {
|
|
97
|
+
switch (inputEl.type) {
|
|
98
|
+
case 'checkbox':
|
|
99
|
+
inputEl.checked = !!value;
|
|
100
|
+
break;
|
|
101
|
+
default:
|
|
102
|
+
inputEl.value = value;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
setErrors: (errors: { [key: string]: FormError[] }) => {
|
|
111
|
+
const [, dispatch] = context;
|
|
112
|
+
dispatch({action: 'errors', payload: errors});
|
|
113
|
+
},
|
|
114
|
+
reset: () => {
|
|
115
|
+
formElementRef.current?.reset();
|
|
116
|
+
},
|
|
117
|
+
submit: () => formElementRef.current?.requestSubmit()
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
useImperativeHandle(ref, (): FormRef => handler);
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
const handleFormResetEvent = () => {
|
|
123
|
+
onResetCallback && onResetCallback()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const formElement = formElementRef?.current;
|
|
127
|
+
formElement?.addEventListener('reset', handleFormResetEvent);
|
|
128
|
+
return () => {
|
|
129
|
+
formElement?.removeEventListener('reset', handleFormResetEvent);
|
|
130
|
+
}
|
|
131
|
+
}, []);
|
|
132
|
+
|
|
133
|
+
const validateField = (name: string, constraints: Constraint[]) => {
|
|
134
|
+
const formData = handler.getFormData();
|
|
135
|
+
for (const constraint of constraints) {
|
|
136
|
+
if (!constraint.isValid(formData.get(name) || null)) {
|
|
137
|
+
return {valid: false, message: constraint.getMessage()};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return {valid: true, message: null};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const context = useReducer((state: FormState, command: FormStatePayload): FormState => {
|
|
145
|
+
const {action, payload} = command;
|
|
146
|
+
switch (action) {
|
|
147
|
+
case 'constraints': {
|
|
148
|
+
const {name, constraints} = payload;
|
|
149
|
+
return {
|
|
150
|
+
...state,
|
|
151
|
+
constraints: {
|
|
152
|
+
...(state.constraints || {}),
|
|
153
|
+
[name]: constraints
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
case 'validate': {
|
|
158
|
+
const {valid, message} = validateField(payload, state.constraints[payload] || []);
|
|
159
|
+
const errors = state.errors || {};
|
|
160
|
+
const formName = payload as string;
|
|
161
|
+
if (valid) {
|
|
162
|
+
delete errors[formName];
|
|
163
|
+
} else {
|
|
164
|
+
errors[formName] = [...(errors[formName] || []), {message: message || 'Error'}];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (!Object.keys(errors).length) {
|
|
168
|
+
return state;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
...state,
|
|
173
|
+
errors
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
case 'response': {
|
|
177
|
+
return {
|
|
178
|
+
...state,
|
|
179
|
+
response: payload
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
case 'errors': {
|
|
183
|
+
return {
|
|
184
|
+
...state,
|
|
185
|
+
errors: payload || []
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
case 'error': {
|
|
189
|
+
const errors = {...state.errors, ...payload};
|
|
190
|
+
return {
|
|
191
|
+
...state,
|
|
192
|
+
errors: errors
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return state;
|
|
198
|
+
}, initialState as FormState);
|
|
199
|
+
const onSubmit = (e: any) => {
|
|
200
|
+
e.preventDefault();
|
|
201
|
+
const [form, dispatch] = context;
|
|
202
|
+
let errors: any = {};
|
|
203
|
+
for (const [name, constraints] of Object.entries<[any, Constraint[]]>(form.constraints)) {
|
|
204
|
+
const {valid, message} = validateField(name, constraints);
|
|
205
|
+
if (!valid) {
|
|
206
|
+
errors[name] = [message];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (Object.values(errors).length) {
|
|
211
|
+
dispatch({action: 'errors', payload: errors});
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const formData = new FormData(formElementRef?.current || undefined);
|
|
216
|
+
|
|
217
|
+
onBeforeSubmit && onBeforeSubmit(formData);
|
|
218
|
+
|
|
219
|
+
if (onSubmitCallback) {
|
|
220
|
+
onSubmitCallback(formData)
|
|
221
|
+
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// formElementRef?.current?.submit();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return (
|
|
229
|
+
<FormContext.Provider value={[context, ref, formElementRef]}>
|
|
230
|
+
<form id={id} ref={formElementRef} onSubmit={onSubmit} {...props}>{children}</form>
|
|
231
|
+
</FormContext.Provider>
|
|
232
|
+
)
|
|
233
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import {FormError, useForm} from "@src/component/form/Form";
|
|
3
|
+
|
|
4
|
+
export const FormAlert = ({name = 'global'}: { name: string; }) => {
|
|
5
|
+
const [[form]] = useForm();
|
|
6
|
+
const errorMessages = form?.errors[name] || [];
|
|
7
|
+
|
|
8
|
+
return (
|
|
9
|
+
<>
|
|
10
|
+
{
|
|
11
|
+
errorMessages.length > 0 && (
|
|
12
|
+
<div className={"alert alert-danger"}>
|
|
13
|
+
{errorMessages.map((m: FormError) => m.message).join(' ')}
|
|
14
|
+
</div>
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
</>
|
|
18
|
+
)
|
|
19
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {FormError, useForm} from "@src/component/form/Form";
|
|
2
|
+
import React from "react";
|
|
3
|
+
|
|
4
|
+
export const FormFieldError = ({name, className}: { name: string, className?: string }) => {
|
|
5
|
+
const [[form]] = useForm();
|
|
6
|
+
const errorMessages = form?.errors[name] || [];
|
|
7
|
+
|
|
8
|
+
if (!errorMessages.length)
|
|
9
|
+
return <></>;
|
|
10
|
+
|
|
11
|
+
return (
|
|
12
|
+
<div className={className}>
|
|
13
|
+
{errorMessages.map((error: FormError, i: number) => <span key={i}>{error.message}</span>)}
|
|
14
|
+
</div>
|
|
15
|
+
)
|
|
16
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {FormFieldError} from "@src/component/form/FormFieldError";
|
|
2
|
+
import {FormViewType} from "@src/type/FormViewType";
|
|
3
|
+
import {titlize} from "@src/helper/StingUtils";
|
|
4
|
+
import React from "react";
|
|
5
|
+
|
|
6
|
+
export type FormGroupProps = {
|
|
7
|
+
view: FormViewType
|
|
8
|
+
};
|
|
9
|
+
export const FormGroup = ({
|
|
10
|
+
view,
|
|
11
|
+
children,
|
|
12
|
+
className
|
|
13
|
+
}: FormGroupProps & {
|
|
14
|
+
className: string,
|
|
15
|
+
children: React.JSX.Element
|
|
16
|
+
}): React.JSX.Element => {
|
|
17
|
+
const nameToId = (name: string, index: number | null = null) => (name.replace(/[\[\]]/gi, '_').replace(/_+/gi, '_') + (index && index));
|
|
18
|
+
const label = view.label || titlize(view.name);
|
|
19
|
+
const isCheckbox = ['checkbox', 'radio'].includes(view.type || 'input');
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
<div
|
|
23
|
+
className={[...(className?.split(' ') || []), 'mb-3', (isCheckbox && 'form-check')].filter(v => v).join(' ')}
|
|
24
|
+
{...(view.attr && (view.attr instanceof Function ? view.attr() : view.attr))}
|
|
25
|
+
>
|
|
26
|
+
{!isCheckbox && (
|
|
27
|
+
<label
|
|
28
|
+
className={"form-label"}
|
|
29
|
+
{...(view.label_attr && (view.label_attr instanceof Function ? view.label_attr() : view.label_attr))}>
|
|
30
|
+
{label}
|
|
31
|
+
</label>
|
|
32
|
+
)}
|
|
33
|
+
{children}
|
|
34
|
+
{isCheckbox && (
|
|
35
|
+
<label
|
|
36
|
+
className={"form-check-label"}
|
|
37
|
+
htmlFor={view.id || nameToId(view.full_name)}
|
|
38
|
+
{...(view.label_attr && (view.label_attr instanceof Function ? view.label_attr() : view.label_attr))}>
|
|
39
|
+
{label}
|
|
40
|
+
</label>
|
|
41
|
+
)}
|
|
42
|
+
<FormFieldError name={view.full_name} className={"invalid-feedback"}/>
|
|
43
|
+
{view.help && (
|
|
44
|
+
<div
|
|
45
|
+
className={'form-help'}
|
|
46
|
+
{...(view.help_attr && (view.help_attr instanceof Function ? view.help_attr() : view.help_attr))}
|
|
47
|
+
>
|
|
48
|
+
{view.help}
|
|
49
|
+
</div>
|
|
50
|
+
)}
|
|
51
|
+
</div>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import Choice from "@src/component/form/Choice";
|
|
2
|
+
import {FormGroup, FormGroupProps} from "@src/component/form/FormGroup";
|
|
3
|
+
import React from "react";
|
|
4
|
+
import {FormViewType} from "@src/type/FormViewType";
|
|
5
|
+
import Input from "@src/component/form/Input.tsx";
|
|
6
|
+
|
|
7
|
+
const FormWidget = ({
|
|
8
|
+
view
|
|
9
|
+
}: {
|
|
10
|
+
view: FormViewType,
|
|
11
|
+
} & FormGroupProps):
|
|
12
|
+
React.JSX.Element => {
|
|
13
|
+
|
|
14
|
+
const elements = () => {
|
|
15
|
+
switch (view.type) {
|
|
16
|
+
case 'entity':
|
|
17
|
+
case 'choice':
|
|
18
|
+
case 'collection':
|
|
19
|
+
case 'enum': {
|
|
20
|
+
return <Choice view={view}/>
|
|
21
|
+
}
|
|
22
|
+
default:
|
|
23
|
+
return <Input view={view}/>
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return (
|
|
28
|
+
<FormGroup className={"mb-3"} view={view}>
|
|
29
|
+
{elements()}
|
|
30
|
+
</FormGroup>
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export default FormWidget;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import React, {ChangeEvent, KeyboardEvent, useEffect, useRef} from "react";
|
|
2
|
+
import {nameToId, useForm} from "./Form";
|
|
3
|
+
import {Constraint} from "./constraint/Contraint";
|
|
4
|
+
import {FormViewType} from "@src/type/FormViewType";
|
|
5
|
+
|
|
6
|
+
export type FormFieldProps = {
|
|
7
|
+
view: FormViewType;
|
|
8
|
+
className?: string;
|
|
9
|
+
constraints?: Constraint[],
|
|
10
|
+
onChange?: Function
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type InputProps = {} & FormFieldProps;
|
|
14
|
+
|
|
15
|
+
const Input = ({
|
|
16
|
+
view,
|
|
17
|
+
constraints,
|
|
18
|
+
className,
|
|
19
|
+
onChange,
|
|
20
|
+
}: InputProps):
|
|
21
|
+
React.JSX.Element => {
|
|
22
|
+
|
|
23
|
+
const [[formState, dispatch]] = useForm();
|
|
24
|
+
const fieldRef = useRef<HTMLInputElement | null>(null);
|
|
25
|
+
const errorMessages = formState?.errors[view.full_name] || [];
|
|
26
|
+
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
dispatch({
|
|
29
|
+
action: 'constraints',
|
|
30
|
+
payload: {
|
|
31
|
+
name: view.full_name,
|
|
32
|
+
constraints: constraints || []
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}, [])
|
|
36
|
+
|
|
37
|
+
const validate = (value: any) => {
|
|
38
|
+
dispatch({action: 'validate', payload: view.full_name});
|
|
39
|
+
onChange && onChange(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const isCheckbox = ['checkbox', 'radio'].includes(view.type);
|
|
43
|
+
const defaultFieldClassName = isCheckbox ? 'form-check-input' : 'form-control';
|
|
44
|
+
const key = btoa(encodeURIComponent(view.full_name + JSON.stringify(view.data)));
|
|
45
|
+
return <>
|
|
46
|
+
<input
|
|
47
|
+
ref={fieldRef}
|
|
48
|
+
id={view.id || nameToId(view.full_name)}
|
|
49
|
+
key={key}
|
|
50
|
+
name={view.full_name}
|
|
51
|
+
type={view.type}
|
|
52
|
+
defaultValue={view.data}
|
|
53
|
+
aria-invalid={!errorMessages.length}
|
|
54
|
+
onKeyUp={(e: KeyboardEvent<HTMLInputElement>) => validate({value: (e.target as HTMLInputElement).value})}
|
|
55
|
+
onChange={(e: ChangeEvent<HTMLInputElement>) => validate({value: e.target.value})}
|
|
56
|
+
className={[defaultFieldClassName, ...(errorMessages.length ? ['is-invalid'] : [])].join(' ')}
|
|
57
|
+
defaultChecked={view?.checked}
|
|
58
|
+
{...(view.attr && (view.attr instanceof Function ? view.attr() : view.attr))}
|
|
59
|
+
/>
|
|
60
|
+
</>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export default Input;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {Constraint} from "./Contraint";
|
|
2
|
+
|
|
3
|
+
export class NotBlank implements Constraint {
|
|
4
|
+
defaultMessage = 'Value cannot be blank.'
|
|
5
|
+
|
|
6
|
+
message: string | null = null;
|
|
7
|
+
options: { message?: string };
|
|
8
|
+
|
|
9
|
+
constructor(options: Object) {
|
|
10
|
+
this.options = options;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
isValid(value: any) {
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
getMessage() {
|
|
18
|
+
return this.options.message || this.defaultMessage;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import React, {ReactNode, use, useEffect, useRef, useState} from "react";
|
|
2
|
+
import {ListType} from "@src/type/ListType.tsx";
|
|
3
|
+
import Requester, {convertObjectToURLSearchParams} from "@dakataa/requester";
|
|
4
|
+
import {ModifyType} from "@src/type/ModifyType.tsx";
|
|
5
|
+
import {UseActions} from "@src/context/ActionContext.tsx";
|
|
6
|
+
import {generateRoute} from "@src/helper/RouterUtils.tsx";
|
|
7
|
+
import {ActionType} from "@src/type/ActionType.tsx";
|
|
8
|
+
import HttpException from "@src/component/error/HttpException.tsx";
|
|
9
|
+
import {ExceptionType} from "@src/type/ExceptionType.tsx";
|
|
10
|
+
|
|
11
|
+
const GetDataContext = React.createContext<GetDataType | null>(null);
|
|
12
|
+
|
|
13
|
+
export type GetDataType = {
|
|
14
|
+
results: any;
|
|
15
|
+
setParameters: (v: { [key: string]: string } | null) => void;
|
|
16
|
+
setQueryParameters: (v: URLSearchParams | { [key: string]: string }) => void;
|
|
17
|
+
refresh: () => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type GetDataProps = {
|
|
21
|
+
entityAction: ActionType,
|
|
22
|
+
initParameters?: { [key: string]: any };
|
|
23
|
+
initQueryParameters?: URLSearchParams | { [key: string]: any }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function UseDataProvider(): GetDataType | null {
|
|
27
|
+
return React.useContext<GetDataType | null>(GetDataContext);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const GetData = ({entityAction, initParameters, initQueryParameters}: GetDataProps): GetDataType => {
|
|
31
|
+
const {getAction} = UseActions();
|
|
32
|
+
entityAction = getAction(entityAction.entity, entityAction.name, entityAction.namespace) || entityAction;
|
|
33
|
+
|
|
34
|
+
const [results, setResults] = useState<ListType | ModifyType | null>();
|
|
35
|
+
const [parameters, setParameters] = useState<{ [key: string]: string } | null>(initParameters || null);
|
|
36
|
+
const [queryParameters, setQueryParameters] = useState<URLSearchParams>(new URLSearchParams(initQueryParameters || {}));
|
|
37
|
+
const lastKey = useRef<string | null>(null);
|
|
38
|
+
const key = btoa(encodeURIComponent([entityAction.entity, entityAction.name, entityAction.namespace, ...Object.entries(parameters || {}).map(([key, value]) => key + '-' + value), (queryParameters instanceof URLSearchParams ? queryParameters : convertObjectToURLSearchParams(queryParameters)).toString()].filter(v => v).join('.')));
|
|
39
|
+
const cache = useRef<{ [key: string]: string }>({});
|
|
40
|
+
const [refresh, setRefresh] = useState(1);
|
|
41
|
+
|
|
42
|
+
const setCache = (results: any) => {
|
|
43
|
+
// cache.current[key] = btoa(encodeURIComponent(JSON.stringify(results)));
|
|
44
|
+
sessionStorage.setItem(key, btoa(encodeURIComponent(JSON.stringify(results))))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// const getCache = () => {
|
|
48
|
+
// return null;
|
|
49
|
+
// const cachedData = sessionStorage.getItem(key);
|
|
50
|
+
// // let cachedData = cache.current[key] ?? null;
|
|
51
|
+
//
|
|
52
|
+
// if(cachedData) {
|
|
53
|
+
// try {
|
|
54
|
+
// return JSON.parse(decodeURIComponent(atob(cachedData)));
|
|
55
|
+
// } catch (e) {
|
|
56
|
+
// console.log('error', e);
|
|
57
|
+
// }
|
|
58
|
+
// }
|
|
59
|
+
//
|
|
60
|
+
// return null;
|
|
61
|
+
// }
|
|
62
|
+
|
|
63
|
+
// useEffect(() => {
|
|
64
|
+
// if (!results) {
|
|
65
|
+
// return;
|
|
66
|
+
// }
|
|
67
|
+
//
|
|
68
|
+
// setCache(results);
|
|
69
|
+
// }, [JSON.stringify(results)]);
|
|
70
|
+
|
|
71
|
+
useEffect(() => {
|
|
72
|
+
/*if(lastKey.current === key) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
lastKey.current = key;
|
|
77
|
+
|
|
78
|
+
let cachedData = getCache();
|
|
79
|
+
if(cachedData) {
|
|
80
|
+
try {
|
|
81
|
+
setResults(cachedData);
|
|
82
|
+
return;
|
|
83
|
+
} catch (e) {
|
|
84
|
+
console.log('error', e);
|
|
85
|
+
}
|
|
86
|
+
}*/
|
|
87
|
+
|
|
88
|
+
if (!entityAction) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
(new Requester())
|
|
93
|
+
.get(generateRoute(entityAction.route, parameters ?? null), queryParameters)
|
|
94
|
+
.then((response) => {
|
|
95
|
+
return response.getData().then(v => {
|
|
96
|
+
switch (response.status) {
|
|
97
|
+
case 201:
|
|
98
|
+
case 200: {
|
|
99
|
+
setResults(v);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
default: {
|
|
103
|
+
const exception = (v as ExceptionType);
|
|
104
|
+
throw new HttpException(exception.status, exception.detail, exception.trace);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}, [JSON.stringify(parameters), queryParameters.toString(), refresh]);
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
results,
|
|
113
|
+
setParameters,
|
|
114
|
+
setQueryParameters: (value: URLSearchParams | { [key: string]: any }) => {
|
|
115
|
+
setQueryParameters(new URLSearchParams(value));
|
|
116
|
+
},
|
|
117
|
+
refresh: () => {
|
|
118
|
+
setRefresh(refresh + 1);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const DataProvider = ({entityAction, initParameters, initQueryParameters, suspense, children}: GetDataProps & {
|
|
124
|
+
children: ReactNode,
|
|
125
|
+
suspense?: ReactNode
|
|
126
|
+
}) => {
|
|
127
|
+
|
|
128
|
+
const data = GetData({entityAction, initParameters, initQueryParameters});
|
|
129
|
+
|
|
130
|
+
return (
|
|
131
|
+
<GetDataContext.Provider value={data}>
|
|
132
|
+
{suspense && !data.results ? suspense : children}
|
|
133
|
+
</GetDataContext.Provider>
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export {DataProvider, GetData as default};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import React, {PropsWithChildren, useEffect, useState} from "react";
|
|
2
|
+
import {ActionType} from "@src/type/ActionType.tsx";
|
|
3
|
+
import Requester from "@dakataa/requester";
|
|
4
|
+
import {matchPath} from "react-router-dom";
|
|
5
|
+
import {crudToReactPathPattern} from "@src/helper/RouterUtils.tsx";
|
|
6
|
+
import {OnClickAction} from "@src/component/crud/GridTableView.tsx";
|
|
7
|
+
import HttpException from "@src/component/error/HttpException.tsx";
|
|
8
|
+
|
|
9
|
+
const STORAGE_KEY = 'actions';
|
|
10
|
+
const ActionContext = React.createContext<ActionType[] | null>(null);
|
|
11
|
+
|
|
12
|
+
export function UseActions() {
|
|
13
|
+
const context = React.useContext<ActionType[] | null>(ActionContext);
|
|
14
|
+
|
|
15
|
+
const getAction = (entity: string, name: string, namespace?: string): ActionType | undefined => {
|
|
16
|
+
return context?.filter(a => a.entity === entity && a.name === name && (namespace === undefined || a.namespace === namespace)).shift();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const getActionByPath = (path: string): ActionType | undefined => {
|
|
20
|
+
return context?.find((a) => a.route?.path && matchPath(crudToReactPathPattern(a.route.path), path));
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const getOnClickActionByPath = (path: string): Promise<OnClickAction> => {
|
|
24
|
+
const getOnClickAction = () => {
|
|
25
|
+
const action = getActionByPath(path);
|
|
26
|
+
|
|
27
|
+
if(!action)
|
|
28
|
+
throw new HttpException(404, 'Page not found.');
|
|
29
|
+
|
|
30
|
+
const match = matchPath(crudToReactPathPattern(action.route?.path || ''), path)
|
|
31
|
+
return {
|
|
32
|
+
action,
|
|
33
|
+
parameters: match?.params
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return new Promise<OnClickAction>((resolve, reject) => {
|
|
38
|
+
let retries = 0;
|
|
39
|
+
const timeout = () => {
|
|
40
|
+
if(retries > 10) {
|
|
41
|
+
throw new HttpException(500, 'Cannot load routes');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if(context) {
|
|
45
|
+
return resolve(getOnClickAction());
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
setTimeout(timeout, 200);
|
|
49
|
+
retries++;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
timeout();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
getAction,
|
|
59
|
+
getActionByPath,
|
|
60
|
+
getOnClickActionByPath
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function ActionProvider(props: PropsWithChildren) {
|
|
65
|
+
let initActions: ActionType[] | null = null;
|
|
66
|
+
try {
|
|
67
|
+
const data = sessionStorage.getItem(STORAGE_KEY);
|
|
68
|
+
initActions = JSON.parse(atob(data || '')) as ActionType[];
|
|
69
|
+
} catch (e) {
|
|
70
|
+
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const [actions, setActions] = useState<ActionType[] | null>(initActions);
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
if (initActions)
|
|
76
|
+
return;
|
|
77
|
+
|
|
78
|
+
(new Requester()).get('/_crud/actions', {}).then((response) => {
|
|
79
|
+
if (response.status !== 200) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
response.getData().then((data) => {
|
|
84
|
+
sessionStorage.setItem(STORAGE_KEY, btoa(JSON.stringify(data)));
|
|
85
|
+
setActions(data);
|
|
86
|
+
});
|
|
87
|
+
}).catch((e) => {
|
|
88
|
+
console.log('error', e);
|
|
89
|
+
}).finally(() => {
|
|
90
|
+
|
|
91
|
+
});
|
|
92
|
+
}, []);
|
|
93
|
+
|
|
94
|
+
return (
|
|
95
|
+
<ActionContext.Provider value={actions}>
|
|
96
|
+
{props.children}
|
|
97
|
+
</ActionContext.Provider>
|
|
98
|
+
);
|
|
99
|
+
}
|