@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.
Files changed (78) hide show
  1. package/.env +3 -0
  2. package/README.md +58 -0
  3. package/babel-plugin-macros.config.js +5 -0
  4. package/index.html +12 -0
  5. package/package.json +74 -0
  6. package/public/favicon.ico +0 -0
  7. package/public/logo192.png +0 -0
  8. package/public/logo512.png +0 -0
  9. package/public/manifest.json +25 -0
  10. package/public/robots.txt +3 -0
  11. package/src/Crud.tsx +29 -0
  12. package/src/CrudContext.tsx +21 -0
  13. package/src/CrudLoader.tsx +27 -0
  14. package/src/assets/images/alert/denied.json +1 -0
  15. package/src/assets/images/alert/info.json +1 -0
  16. package/src/assets/images/alert/success.json +1 -0
  17. package/src/assets/images/alert/warning.json +1 -0
  18. package/src/assets/style/alert.scss +97 -0
  19. package/src/component/Animation.tsx +50 -0
  20. package/src/component/BaseButton.tsx +26 -0
  21. package/src/component/Button.tsx +15 -0
  22. package/src/component/Dropdown.tsx +55 -0
  23. package/src/component/EmptyView.tsx +5 -0
  24. package/src/component/Link.tsx +11 -0
  25. package/src/component/Modal.tsx +174 -0
  26. package/src/component/ModifyForm.tsx +139 -0
  27. package/src/component/TemplateBlock.tsx +21 -0
  28. package/src/component/TemplateExtend.tsx +17 -0
  29. package/src/component/TemplateParentBlock.tsx +7 -0
  30. package/src/component/Translation.tsx +7 -0
  31. package/src/component/ViewLoader.tsx +33 -0
  32. package/src/component/crud/DynamicView.tsx +42 -0
  33. package/src/component/crud/FormView.tsx +29 -0
  34. package/src/component/crud/GridTableView.tsx +205 -0
  35. package/src/component/crud/PaginatorView.tsx +80 -0
  36. package/src/component/error/ErrorBoundary.tsx +78 -0
  37. package/src/component/error/Exception.tsx +17 -0
  38. package/src/component/error/HttpException.tsx +24 -0
  39. package/src/component/form/Choice.tsx +119 -0
  40. package/src/component/form/Form.tsx +233 -0
  41. package/src/component/form/FormAlert.tsx +19 -0
  42. package/src/component/form/FormFieldError.tsx +16 -0
  43. package/src/component/form/FormGroup.tsx +53 -0
  44. package/src/component/form/FormWidget.tsx +34 -0
  45. package/src/component/form/Input.tsx +63 -0
  46. package/src/component/form/constraint/Contraint.tsx +8 -0
  47. package/src/component/form/constraint/NotBlank.tsx +20 -0
  48. package/src/component/hooks/GetData.tsx +137 -0
  49. package/src/context/ActionContext.tsx +99 -0
  50. package/src/context/AlertContext.tsx +181 -0
  51. package/src/context/ModalContext.tsx +56 -0
  52. package/src/context/SessionContext.tsx +97 -0
  53. package/src/helper/ObjectUtils.tsx +36 -0
  54. package/src/helper/RouterUtils.tsx +24 -0
  55. package/src/helper/StingUtils.tsx +25 -0
  56. package/src/index.tsx +23 -0
  57. package/src/layout/default/Base.tsx +15 -0
  58. package/src/layout/default/Error.tsx +27 -0
  59. package/src/layout/default/Main.tsx +64 -0
  60. package/src/layout/default/component/Navigation.tsx +197 -0
  61. package/src/page/List.tsx +268 -0
  62. package/src/page/Modify.tsx +156 -0
  63. package/src/react-app-env.d.ts +2 -0
  64. package/src/setupTests.ts +5 -0
  65. package/src/type/ActionType.tsx +10 -0
  66. package/src/type/ColumnType.tsx +18 -0
  67. package/src/type/ExceptionType.tsx +7 -0
  68. package/src/type/FormType.tsx +6 -0
  69. package/src/type/FormViewType.tsx +37 -0
  70. package/src/type/ListMetaType.tsx +7 -0
  71. package/src/type/ListType.tsx +20 -0
  72. package/src/type/ModifyType.tsx +10 -0
  73. package/src/type/RedirectType.tsx +6 -0
  74. package/src/type/RouteType.tsx +5 -0
  75. package/tsconfig.app.json +46 -0
  76. package/tsconfig.json +11 -0
  77. package/tsconfig.node.json +15 -0
  78. package/vite.config.ts +33 -0
@@ -0,0 +1,174 @@
1
+ import TemplateBlock from "@src/component/TemplateBlock.tsx";
2
+ import React, {forwardRef, KeyboardEvent, ReactNode, useEffect, useImperativeHandle, useRef, useState} from "react";
3
+ import {createPortal} from "react-dom";
4
+
5
+ export type ModalType = {
6
+ children?: ReactNode,
7
+ open?: boolean,
8
+ onClose?: () => void,
9
+ backdrop?: boolean,
10
+ animation?: Animation | string,
11
+ keyboard?: boolean,
12
+ size?: 'sm' | 'lg' | 'xl' | 'auto',
13
+ className?: string,
14
+ };
15
+
16
+ export type ModalRefType = {
17
+ toggle: () => void;
18
+ open: () => void;
19
+ close: () => Promise<void>;
20
+ isOpen: () => boolean;
21
+ };
22
+
23
+ export enum Animation {
24
+ fade = 'fade'
25
+ }
26
+
27
+ const Modal = forwardRef(({
28
+ children,
29
+ open = false,
30
+ animation = Animation.fade,
31
+ backdrop = true,
32
+ keyboard = true,
33
+ size,
34
+ onClose,
35
+ className,
36
+ }: ModalType, ref) => {
37
+ const [isOpen, setIsOpen] = useState<boolean>(open);
38
+
39
+ useImperativeHandle(ref, () => ({
40
+ toggle: () => setIsOpen(!isOpen),
41
+ open: () => setIsOpen(true),
42
+ close: () => startClosing(),
43
+ isOpen: () => isOpen,
44
+ }));
45
+
46
+ useEffect(() => {
47
+ setIsOpen(open);
48
+ }, [open]);
49
+
50
+ const closeOnKeyboard = (ev: any & KeyboardEvent<Window>): any => {
51
+ if (!keyboard) {
52
+ return;
53
+ }
54
+
55
+ switch (ev.key) {
56
+ case 'Escape': {
57
+ startClosing();
58
+ break;
59
+ }
60
+ }
61
+ };
62
+
63
+ useEffect(() => {
64
+ if (!isOpen) {
65
+ return;
66
+ }
67
+
68
+ const onAnimationStart = () => {
69
+ modalRef.current?.addEventListener('animationend', onAnimationEnd);
70
+ };
71
+
72
+ const onAnimationEnd = () => {
73
+ modalRef.current?.classList.remove(animation);
74
+ modalRef.current?.removeEventListener('animationstart', onAnimationStart)
75
+ modalRef.current?.removeEventListener('animationend', onAnimationEnd);
76
+ };
77
+
78
+ setTimeout(() => {
79
+ modalRef.current?.classList.add(...['d-block', 'show']);
80
+ modalBackdropRef?.current?.classList.add('show');
81
+ }, animation ? 100 : 0);
82
+
83
+ document.addEventListener('keydown', closeOnKeyboard);
84
+ modalRef.current?.addEventListener('animationstart', onAnimationStart);
85
+
86
+ return () => {
87
+ document.removeEventListener('keydown', closeOnKeyboard)
88
+ modalRef.current?.removeEventListener('animationstart', onAnimationStart)
89
+ modalRef.current?.removeEventListener('animationend', onAnimationEnd)
90
+ }
91
+ }, [isOpen]);
92
+
93
+ const modalRef = useRef<HTMLDivElement | null>(null);
94
+ const modalBackdropRef = useRef<HTMLDivElement | null>(null);
95
+
96
+ const endClosing = () => {
97
+ setIsOpen(false);
98
+ onClose && onClose();
99
+ }
100
+ const startClosing = (): Promise<void> => {
101
+ return new Promise((resolve: Function, reject: Function) => {
102
+ if (!isOpen) {
103
+ return resolve();
104
+ }
105
+
106
+ const closeAndResolve = () => {
107
+ modalRef?.current?.classList.remove(...['show', 'd-block']);
108
+ resolve();
109
+ endClosing();
110
+ };
111
+
112
+
113
+ if (animation) {
114
+ const closeTimeout = setTimeout(() => {
115
+ closeAndResolve();
116
+ }, animation ? 50 : 0);
117
+
118
+ modalRef.current?.addEventListener('animationstart', () => {
119
+ console.log('timeout');
120
+ clearTimeout(closeTimeout);
121
+ modalRef.current?.removeEventListener('animationend', closeAndResolve);
122
+ modalRef.current?.addEventListener('animationend', closeAndResolve);
123
+ });
124
+
125
+ modalRef.current?.classList.add(...[animation, 'close']);
126
+ } else {
127
+ closeAndResolve();
128
+ }
129
+ })
130
+
131
+ }
132
+
133
+ return isOpen && createPortal((
134
+ <>
135
+ <div ref={modalRef}
136
+ className={["modal", (size && "modal-" + size), animation && animation, className].filter(v => v).join(' ')}>
137
+ <div className="modal-dialog modal-dialog-centered" role="document">
138
+ <div className="modal-content">
139
+ <TemplateBlock name={"header"} content={children} data={null}>
140
+ <div className="modal-header">
141
+ <h5 className="modal-title" id="exampleModalLabel">
142
+ <TemplateBlock name={"title"} content={children} data={null}>
143
+ Title
144
+ </TemplateBlock>
145
+ </h5>
146
+ <button onClick={startClosing} type="button" className="btn-close" aria-label="Close"/>
147
+ </div>
148
+ </TemplateBlock>
149
+ <div className="modal-body">
150
+ <TemplateBlock name={"content"} content={children} data={null}>
151
+ {children}
152
+ </TemplateBlock>
153
+ </div>
154
+ <TemplateBlock name={"footer"} content={children} data={null}>
155
+ <div className="modal-footer">
156
+ <TemplateBlock name={"actions"} content={children} data={null}>
157
+ <button onClick={startClosing} type="button" className="btn btn-secondary">
158
+ Close
159
+ </button>
160
+ </TemplateBlock>
161
+ </div>
162
+ </TemplateBlock>
163
+ </div>
164
+ </div>
165
+ </div>
166
+ {backdrop && (
167
+ <div ref={modalBackdropRef}
168
+ className={["modal-backdrop", "fade", ...(animation && ['show'])].filter(v => v).join(' ')}></div>
169
+ )}
170
+ </>
171
+ ), document.body);
172
+ });
173
+
174
+ export default Modal;
@@ -0,0 +1,139 @@
1
+ import {Form, FormRef} from "@src/component/form/Form.tsx";
2
+ import FormView from "@src/component/crud/FormView.tsx";
3
+ import React, {forwardRef, ReactNode, useEffect, useImperativeHandle, useRef, useState} from "react";
4
+ import {ModifyType} from "@src/type/ModifyType.tsx";
5
+ import {generateRoute} from "@src/helper/RouterUtils.tsx";
6
+ import {FormViewType} from "@src/type/FormViewType.tsx";
7
+ import {useNavigate} from "react-router-dom";
8
+ import Requester, {RequestBodyType} from "@dakataa/requester";
9
+ import {ActionType} from "@src/type/ActionType.tsx";
10
+ import TemplateBlock from "@src/component/TemplateBlock.tsx";
11
+ import Button from "@src/component/Button.tsx";
12
+ import {UseDataProvider} from "@src/component/hooks/GetData.tsx";
13
+ import {FormFieldError} from "@src/component/form/FormFieldError.tsx";
14
+ import {default as T} from "@src/component/Translation.tsx";
15
+ import {ExceptionType} from "@src/type/ExceptionType.tsx";
16
+
17
+ export type ModifyFormRefType = {
18
+ getData: () => ModifyType | null;
19
+ getFormRef: () => FormRef | null
20
+ };
21
+
22
+ const ModifyForm = forwardRef(({name, data: initData, action, parameters, onSuccess, onError, onLoad, children, embedded = false}: {
23
+ name?: string,
24
+ data?: ModifyType;
25
+ action: ActionType;
26
+ parameters?: { [key: string]: any };
27
+ onSuccess?: (data: any) => void;
28
+ onError?: (data: ExceptionType) => void;
29
+ onLoad?: () => void;
30
+ children?: ReactNode;
31
+ embedded?: boolean;
32
+ }, ref) => {
33
+ const [preload, setPreloader] = useState(false);
34
+ const navigate = useNavigate();
35
+ const actionURL = generateRoute(action.route, (parameters || {}));
36
+ const formRef = useRef<FormRef | null>(null);
37
+ const dataProvider = UseDataProvider();
38
+ const [data, setData] = useState<ModifyType | undefined>();
39
+
40
+ useImperativeHandle(ref, () => ({
41
+ getData: (): ModifyType | undefined => data,
42
+ getFormRef: (): FormRef | null => formRef.current
43
+ }));
44
+
45
+ const getFormErrors = (view: FormViewType): { [key: string]: any } => {
46
+ let result: { [key: string]: any } = {
47
+ ...(view.errors?.length ? {[view.full_name]: view.errors} : {})
48
+ }
49
+
50
+ for (let [, child] of Object.entries(view?.children || [])) {
51
+ if (child.children && Object.values(child.children).length) {
52
+ result = {...result, ...getFormErrors(child)};
53
+ } else if (child.errors?.length) {
54
+ result[child.full_name] = child.errors;
55
+ }
56
+ }
57
+
58
+ return result;
59
+ };
60
+
61
+ const onSubmit = (formData: FormData) => {
62
+ setPreloader(true);
63
+
64
+ (new Requester()).post(actionURL, formData, RequestBodyType.FormData).then(response => {
65
+ return response.getData().then((data) => {
66
+ if (![200, 201, 400].includes(response.status)) {
67
+ return Promise.reject(data);
68
+ }
69
+
70
+ return data;
71
+ })
72
+
73
+ }).then(data => {
74
+ setData(data);
75
+
76
+ const errors = getFormErrors(data.form.modify.view);
77
+ if (Object.entries(errors).length) {
78
+ formRef.current?.setErrors(errors);
79
+ return;
80
+ }
81
+
82
+ if (onSuccess) {
83
+ onSuccess(data);
84
+ }
85
+
86
+ if (data.redirect && !embedded) {
87
+ navigate(generateRoute(data.redirect.route, {...(parameters || {}), ...data.redirect.parameters}));
88
+ }
89
+ }).catch((error: ExceptionType) => {
90
+ if (onError) {
91
+ onError(error);
92
+ }
93
+ }).finally(() => {
94
+ setPreloader(false);
95
+ });
96
+ }
97
+
98
+ useEffect(() => {
99
+ if (onLoad) {
100
+ onLoad();
101
+ }
102
+ }, []);
103
+
104
+ initData = (dataProvider?.results as ModifyType) ?? initData;
105
+ useEffect(() => {
106
+ setData(initData);
107
+ }, [JSON.stringify(initData)])
108
+
109
+ return data && (
110
+ <>
111
+ {Object.keys(data?.messages || {}).map((messageType, index) => (
112
+ <div key={"alert-" + messageType} className={['alert', 'alert-' + messageType].join(' ')}>
113
+ {(data?.messages[messageType] || ['Item was saved successful.']).join(' ')}
114
+ </div>
115
+ ))}
116
+
117
+ <Form id={data?.form?.modify?.view?.id} ref={formRef} action={actionURL} method={"POST"} onSubmit={onSubmit}>
118
+ {
119
+ data?.form?.modify?.view !== undefined && (
120
+ <>
121
+ <FormView
122
+ name={name}
123
+ namespace={action.namespace}
124
+ key={data.form.modify.view.id}
125
+ view={data.form.modify.view}
126
+ />
127
+ <FormFieldError name={data.form.modify.view.full_name} className={"alert alert-danger"}/>
128
+ </>
129
+ )
130
+ }
131
+ <TemplateBlock name={"actions"} content={children} data={{formRef}}>
132
+ <Button type={"submit"} className={"btn btn-primary"}><T>Save</T></Button>
133
+ </TemplateBlock>
134
+ </Form>
135
+ </>
136
+ )
137
+ });
138
+
139
+ export default ModifyForm;
@@ -0,0 +1,21 @@
1
+ import React, {memo} from "react";
2
+ import TemplateExtend from "@src/component/TemplateExtend.tsx";
3
+
4
+ const TemplateBlock = memo(({name, content, children, data}: {
5
+ name: string,
6
+ content: any,
7
+ children?: any,
8
+ data: any
9
+ }) => {
10
+ const templateElement = React.Children.toArray(content).find(x => React.isValidElement(x) && x.type === TemplateExtend && x.props.name === name);
11
+ let contentElement = null;
12
+ if (templateElement && React.isValidElement(templateElement)) {
13
+ contentElement = React.cloneElement(templateElement as any, {parent: children, data: data});
14
+ }
15
+
16
+ const restChildren = React.Children.toArray(children).filter(e => React.isValidElement(e) && e.type !== TemplateExtend);
17
+
18
+ return <>{contentElement || (restChildren.length ? restChildren : children)}</>
19
+ })
20
+
21
+ export default TemplateBlock;
@@ -0,0 +1,17 @@
1
+ import React, {memo} from "react";
2
+ import TemplateParentBlock from "@src/component/TemplateParentBlock.tsx";
3
+ import TemplateBlock from "@src/component/TemplateBlock.tsx";
4
+
5
+ const TemplateExtend = memo(({name, children, data, parent, render}: { name: string, children?: any, parent?: any, data?: any, render?: (...args: any) => void }) => {
6
+ children = React.Children.toArray((render ? render(data, parent) : children) || []).map(x => {
7
+ if(React.isValidElement(x) && x.type === TemplateParentBlock) {
8
+ x = React.cloneElement(x as any, { children: parent }) ;
9
+ }
10
+
11
+ return x;
12
+ });
13
+
14
+ return <>{children}</>
15
+ })
16
+
17
+ export default TemplateExtend;
@@ -0,0 +1,7 @@
1
+ import React, {ReactNode} from "react";
2
+
3
+ const TemplateParentBlock = ({children}: { children?: ReactNode | undefined }) => {
4
+ return <>{children}</>
5
+ };
6
+
7
+ export default TemplateParentBlock;
@@ -0,0 +1,7 @@
1
+ import {memo} from "react";
2
+
3
+ const Translation = memo(({children}: {children?: string}) => {
4
+ return <>{children}</>
5
+ })
6
+
7
+ export default Translation;
@@ -0,0 +1,33 @@
1
+ import Modify from "@src/page/Modify";
2
+ import EmptyView from "@src/component/EmptyView";
3
+ import List from "@src/page/List";
4
+ import React from "react";
5
+ import DynamicView from "@src/component/crud/DynamicView.tsx";
6
+ import HttpException from "@src/component/error/HttpException.tsx";
7
+
8
+ const DefaultViewComponent = ({view, props}: {
9
+ view: string,
10
+ props?: { [key: string]: any }
11
+ }) => {
12
+ const defaultComponents: { [key: string]: any } = {
13
+ add: Modify,
14
+ edit: Modify,
15
+ list: List
16
+ }
17
+
18
+ if(defaultComponents[view] === undefined)
19
+ throw new HttpException(500, 'View not found');
20
+
21
+ return React.createElement(defaultComponents[view] || EmptyView, props);
22
+ }
23
+
24
+ const ViewLoader = ({view, namespace, props}: { view: string; namespace: string; props?: { [key: string]: any } }): any => {
25
+
26
+ return (
27
+ <DynamicView namespace={namespace} view={view} key={namespace + view} props={props}>
28
+ <DefaultViewComponent view={view} props={props}/>
29
+ </DynamicView>
30
+ );
31
+ }
32
+
33
+ export {ViewLoader as default, DefaultViewComponent};
@@ -0,0 +1,42 @@
1
+ import React, {memo, ReactNode, useEffect, useRef, useState} from "react";
2
+ import {capitalize} from "@src/helper/StingUtils.tsx";
3
+
4
+ const EmptyView = ({children}: { children?: ReactNode }) => {
5
+ return <>{children}</>
6
+ }
7
+
8
+ const DynamicView = memo(({namespace, view, prefix, children, props, data}: {
9
+ namespace?: string,
10
+ view: string,
11
+ prefix?: string,
12
+ children?: ReactNode,
13
+ data?: any
14
+ props?: any
15
+ }) => {
16
+
17
+ view = view.split(/[._]/).map((v) => capitalize(v)).join('');
18
+ const files = import.meta.glob('@crud/**');
19
+ const templateFilePath = ['crud', namespace, prefix, view].filter(v => v).join('/') + '.tsx';
20
+ const [key, importMethod] = Object.entries(files).filter(([path, importMethod]) => path.endsWith(templateFilePath)).shift() || [];
21
+ const [update, setUpdate] = useState(1);
22
+ const LoadedView = useRef<any>(EmptyView);
23
+
24
+ useEffect(() => {
25
+ if (importMethod === undefined) {
26
+ return () => {};
27
+ }
28
+
29
+ importMethod().then((module: any) => {
30
+ LoadedView.current = module.default;
31
+ setUpdate(update + 1);
32
+ });
33
+ }, []);
34
+
35
+ return (
36
+ <LoadedView.current {...props} view={view} controller={namespace} viewName={view} data={data} parent={children}>
37
+ {(!importMethod || LoadedView.current !== EmptyView) && children}
38
+ </LoadedView.current>
39
+ );
40
+ });
41
+
42
+ export default DynamicView;
@@ -0,0 +1,29 @@
1
+ import {FormViewType} from "@src/type/FormViewType";
2
+ import FormWidget from "@src/component/form/FormWidget";
3
+ import React, {memo} from "react";
4
+ import DynamicView from "@src/component/crud/DynamicView.tsx";
5
+
6
+ export const FormView = memo(({view, namespace, name}: { view: FormViewType, namespace?: string, name?: string }) => {
7
+ return (
8
+ view && <DynamicView
9
+ namespace={namespace}
10
+ key={view.id}
11
+ view={name || view.name || 'form'}
12
+ prefix={"modify/form"}
13
+ data={view}
14
+ >
15
+ {
16
+ Object.keys(view.children || []).length ?
17
+ Object.values(view.children || []).map((child) => {
18
+ return (
19
+ <FormView namespace={namespace} key={child.id} view={child}/>
20
+ )
21
+ })
22
+ :
23
+ <FormWidget key={view.id} view={view}/>
24
+ }
25
+ </DynamicView>
26
+ );
27
+ });
28
+
29
+ export default FormView;