@dakataa/crud-react 1.0.0 → 1.0.2

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 (84) hide show
  1. package/dist/crud-react.css +5 -0
  2. package/dist/crud-react.js +14467 -0
  3. package/dist/denied-CgoMpaA7.js +27 -0
  4. package/dist/info-D-NzIEYs.js +144 -0
  5. package/dist/main.d.ts +19 -0
  6. package/dist/success-Bu_BJcf1.js +27 -0
  7. package/dist/warning-B1nr7TsB.js +27 -0
  8. package/package.json +14 -4
  9. package/.env +0 -3
  10. package/babel-plugin-macros.config.js +0 -5
  11. package/index.html +0 -12
  12. package/public/favicon.ico +0 -0
  13. package/public/logo192.png +0 -0
  14. package/public/logo512.png +0 -0
  15. package/public/manifest.json +0 -25
  16. package/public/robots.txt +0 -3
  17. package/src/Crud.tsx +0 -29
  18. package/src/CrudContext.tsx +0 -21
  19. package/src/CrudLoader.tsx +0 -27
  20. package/src/assets/images/alert/denied.json +0 -1
  21. package/src/assets/images/alert/info.json +0 -1
  22. package/src/assets/images/alert/success.json +0 -1
  23. package/src/assets/images/alert/warning.json +0 -1
  24. package/src/assets/style/alert.scss +0 -97
  25. package/src/component/Animation.tsx +0 -50
  26. package/src/component/BaseButton.tsx +0 -26
  27. package/src/component/Button.tsx +0 -15
  28. package/src/component/Dropdown.tsx +0 -55
  29. package/src/component/EmptyView.tsx +0 -5
  30. package/src/component/Link.tsx +0 -11
  31. package/src/component/Modal.tsx +0 -174
  32. package/src/component/ModifyForm.tsx +0 -139
  33. package/src/component/TemplateBlock.tsx +0 -21
  34. package/src/component/TemplateExtend.tsx +0 -17
  35. package/src/component/TemplateParentBlock.tsx +0 -7
  36. package/src/component/Translation.tsx +0 -7
  37. package/src/component/ViewLoader.tsx +0 -33
  38. package/src/component/crud/DynamicView.tsx +0 -42
  39. package/src/component/crud/FormView.tsx +0 -29
  40. package/src/component/crud/GridTableView.tsx +0 -205
  41. package/src/component/crud/PaginatorView.tsx +0 -80
  42. package/src/component/error/ErrorBoundary.tsx +0 -78
  43. package/src/component/error/Exception.tsx +0 -17
  44. package/src/component/error/HttpException.tsx +0 -24
  45. package/src/component/form/Choice.tsx +0 -119
  46. package/src/component/form/Form.tsx +0 -233
  47. package/src/component/form/FormAlert.tsx +0 -19
  48. package/src/component/form/FormFieldError.tsx +0 -16
  49. package/src/component/form/FormGroup.tsx +0 -53
  50. package/src/component/form/FormWidget.tsx +0 -34
  51. package/src/component/form/Input.tsx +0 -63
  52. package/src/component/form/constraint/Contraint.tsx +0 -8
  53. package/src/component/form/constraint/NotBlank.tsx +0 -20
  54. package/src/component/hooks/GetData.tsx +0 -137
  55. package/src/context/ActionContext.tsx +0 -99
  56. package/src/context/AlertContext.tsx +0 -181
  57. package/src/context/ModalContext.tsx +0 -56
  58. package/src/context/SessionContext.tsx +0 -97
  59. package/src/helper/ObjectUtils.tsx +0 -36
  60. package/src/helper/RouterUtils.tsx +0 -24
  61. package/src/helper/StingUtils.tsx +0 -25
  62. package/src/index.tsx +0 -23
  63. package/src/layout/default/Base.tsx +0 -15
  64. package/src/layout/default/Error.tsx +0 -27
  65. package/src/layout/default/Main.tsx +0 -64
  66. package/src/layout/default/component/Navigation.tsx +0 -197
  67. package/src/page/List.tsx +0 -268
  68. package/src/page/Modify.tsx +0 -156
  69. package/src/react-app-env.d.ts +0 -2
  70. package/src/setupTests.ts +0 -5
  71. package/src/type/ActionType.tsx +0 -10
  72. package/src/type/ColumnType.tsx +0 -18
  73. package/src/type/ExceptionType.tsx +0 -7
  74. package/src/type/FormType.tsx +0 -6
  75. package/src/type/FormViewType.tsx +0 -37
  76. package/src/type/ListMetaType.tsx +0 -7
  77. package/src/type/ListType.tsx +0 -20
  78. package/src/type/ModifyType.tsx +0 -10
  79. package/src/type/RedirectType.tsx +0 -6
  80. package/src/type/RouteType.tsx +0 -5
  81. package/tsconfig.app.json +0 -46
  82. package/tsconfig.json +0 -11
  83. package/tsconfig.node.json +0 -15
  84. package/vite.config.ts +0 -33
@@ -1,233 +0,0 @@
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
- });
@@ -1,19 +0,0 @@
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
- }
@@ -1,16 +0,0 @@
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
- }
@@ -1,53 +0,0 @@
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
- }
@@ -1,34 +0,0 @@
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;
@@ -1,63 +0,0 @@
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;
@@ -1,8 +0,0 @@
1
- export interface Constraint {
2
- message: string | null;
3
- options: any;
4
-
5
- isValid(value: any): boolean;
6
-
7
- getMessage(): string;
8
- }
@@ -1,20 +0,0 @@
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
- }
@@ -1,137 +0,0 @@
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};
@@ -1,99 +0,0 @@
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
- }