@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,205 @@
1
+ import {ListType} from "@src/type/ListType";
2
+ import {Link} from "react-router-dom";
3
+ import {ColumnType} from "@src/type/ColumnType";
4
+ import React, {forwardRef, ReactElement, useRef, useState} from "react";
5
+ import {ActionType} from "@src/type/ActionType";
6
+ import {generateRoute} from "@src/helper/RouterUtils.tsx";
7
+ import DynamicView from "@src/component/crud/DynamicView.tsx";
8
+ import Dropdown, {DropdownButton, DropdownContent} from "@src/component/Dropdown.tsx";
9
+
10
+ type GridViewHeaderColumnAttributes = {
11
+ className?: string
12
+ };
13
+
14
+ export type OnClickAction = {
15
+ action: ActionType,
16
+ parameters?: { [key: string]: any }
17
+ };
18
+
19
+ type GridTableViewType = {
20
+ data?: ListType | null,
21
+ columns?: ColumnType[],
22
+ options?: {
23
+ columns: ColumnType[]
24
+ },
25
+ headerOptions?: {
26
+ columns: {
27
+ [key: string]: {
28
+ view: ReactElement | ((column: ColumnType) => ReactElement);
29
+ attr?: GridViewHeaderColumnAttributes | ((column: ColumnType) => GridViewHeaderColumnAttributes)
30
+ }
31
+ }
32
+ },
33
+ onClick?: (props: OnClickAction, event: React.MouseEvent) => void,
34
+ onBatchClick?: (method: string, ids: any, data: FormData) => void,
35
+ routeParams?: {[key: string]: any},
36
+ namespace?: string
37
+ };
38
+
39
+ const GridTableView = forwardRef(({data, columns, options, onClick, onBatchClick, routeParams, namespace}: GridTableViewType, ref) => {
40
+ columns = (columns || data?.entity?.columns || []).filter(c => c.group !== false);
41
+
42
+ const [, updateState] = useState<any>();
43
+ const primaryColumn = data?.entity?.primaryColumn;
44
+ const actions = Object.values(data?.action || []);
45
+ const objectActions = actions.filter(a => a.object);
46
+ const columnsTotal = columns.length + (actions.length ? 1 : 0);
47
+ const currentIds: number[] = (data?.entity.data.items || []).map(row => (row[primaryColumn?.field || ''] || 0));
48
+ const batchSelectedIds = useRef<number[]>([]);
49
+ const batchIsSelectedAll = !!currentIds.length && currentIds.reduce<boolean>((result: boolean, id) => result && batchSelectedIds.current.includes(id), true);
50
+ const batchActions = data?.form?.batch.view.children?.method?.choices;
51
+ const hasBatchActions = !!batchActions?.length && primaryColumn;
52
+
53
+ const batchToggleItem = (id: number, add: boolean = false) => {
54
+ if (add) {
55
+ batchSelectedIds.current.push(id);
56
+ } else {
57
+ batchSelectedIds.current = batchSelectedIds.current.filter(v => v !== id);
58
+ }
59
+ updateState({});
60
+ };
61
+
62
+ const batchToggleAll = (selectAll: boolean = false) => {
63
+ batchSelectedIds.current = (selectAll ? batchSelectedIds.current.concat(currentIds) : batchSelectedIds.current.filter((id) => !currentIds.includes(id))).filter((v, i, self) => self.indexOf(v) === i)
64
+ updateState({});
65
+ };
66
+
67
+ const batchHandle = (method: string) => {
68
+ if(!onBatchClick) {
69
+ return;
70
+ }
71
+
72
+ const batchFormView = data?.form.batch.view;
73
+ if(!hasBatchActions) {
74
+ return;
75
+ }
76
+
77
+ if(!batchSelectedIds.current?.length) {
78
+ return;
79
+ }
80
+
81
+ const formData = new FormData()
82
+ batchSelectedIds.current.forEach((value) => {
83
+ formData.append(`${batchFormView?.children?.ids.full_name}[]`, value.toString());
84
+ })
85
+ formData.append(batchFormView?.children?.method.full_name || 'method', method)
86
+
87
+ onBatchClick(method, batchSelectedIds.current, formData);
88
+ }
89
+
90
+ return (
91
+ <>
92
+ {hasBatchActions && (
93
+ <div className={"btn-group btn-group-sm mb-2"}>
94
+ <label className={"btn btn-light"}>
95
+ <input
96
+ checked={batchIsSelectedAll}
97
+ onChange={(e) => batchToggleAll(e.target.checked)}
98
+ type={"checkbox"}/>
99
+ </label>
100
+ <Dropdown className={"btn-group btn-group-sm"}>
101
+ <DropdownButton disabled={!batchSelectedIds.current.length} className={"btn-light"}></DropdownButton>
102
+ <DropdownContent>
103
+ {(data.form.batch.view.children?.method.choices?.map((choice) => {
104
+ const value = choice.value instanceof Function ? choice.value() : choice.value;
105
+ return (<Link key={value} to={"#"} onClick={() => batchHandle(value)} className={"dropdown-item"}>{(choice.label instanceof Function ? choice.label() : choice.label)}</Link>
106
+ )}))}
107
+ </DropdownContent>
108
+ </Dropdown>
109
+ </div>
110
+ )}
111
+
112
+ <table className="table table-striped table-hover table-bordered">
113
+ <thead>
114
+ <tr>
115
+ {columns.map((column, index) => (
116
+ <th key={index}>
117
+ <DynamicView namespace={data?.entity.name || 'unknown'} data={column} prefix={"list"} view={column.field + '.label'}>{column.label}</DynamicView>
118
+ {column.sortable && data?.sort[column.field] !== undefined && (
119
+ <Link
120
+ onClick={(event) => onClick && onClick({
121
+ action: {
122
+ name: 'sort',
123
+ object: false,
124
+ namespace: namespace,
125
+ entity: data?.entity.name
126
+ },
127
+ parameters: {[column.field]: data?.sort[column.field] ? (data?.sort[column.field] === 'ASC' ? 'DESC' : '') : 'ASC'}
128
+ }, event)}
129
+ className={"btn"}
130
+ to={"#"}
131
+ >
132
+ {data.sort[column.field] ? (data.sort[column.field] === 'ASC' ? '\u21D1' : '\u21D3') : '\u21C5'}
133
+ </Link>
134
+ )}
135
+ </th>
136
+ ))}
137
+ {primaryColumn && objectActions.length > 0 && (
138
+ <th className="text-end">Actions</th>
139
+ )}
140
+ </tr>
141
+ </thead>
142
+ <tbody>
143
+ {data && (!!data.entity.data.items.length ? data.entity.data.items.map((row, rowIndex) => (
144
+ <tr key={rowIndex}>
145
+ {columns?.map((column, columnIndex) => (
146
+ <td key={columnIndex}>
147
+ {columnIndex === 0 && hasBatchActions &&
148
+ (
149
+ <input
150
+ checked={batchSelectedIds.current.includes(row[primaryColumn?.field])}
151
+ className={"me-2"} type="checkbox"
152
+ name={data.form.batch.view.full_name}
153
+ value={row[primaryColumn?.field]}
154
+ onChange={(e) => batchToggleItem(row[primaryColumn?.field], e.target.checked)}
155
+ />
156
+ )
157
+ }
158
+ <DynamicView namespace={namespace || 'unknown'} data={row} prefix={"list"} view={column.field}>
159
+ {row[column.field] !== undefined && (
160
+ row[column.field] instanceof Object ? (row[column.field] instanceof Array ? row[column.field].join(', ') : JSON.stringify(row[column.field])): row[column.field]?.toString()
161
+ )}
162
+ </DynamicView>
163
+ </td>
164
+ )
165
+ )}
166
+ {primaryColumn && objectActions.length > 0 && (
167
+ <td className={"text-end text-nowrap"}>
168
+ {objectActions.map((action, index) => (
169
+ <Link
170
+ key={index}
171
+ onClick={(event) => onClick && onClick({
172
+ action: action,
173
+ parameters: {
174
+ ...(routeParams || {}),
175
+ id: row[primaryColumn?.field]
176
+ }
177
+ }, event)}
178
+ className={['btn', 'btn-sm', 'mb-1', 'ms-1', (action.route?.methods ?? []).includes('DELETE') ? 'btn-outline-danger' : 'btn-outline-secondary'].join(' ')}
179
+ to={generateRoute(action.route, {
180
+ ...(routeParams || {}),
181
+ id: row[primaryColumn.field]
182
+ })}
183
+ >
184
+ {action.title}
185
+ </Link>
186
+ ))}
187
+ </td>
188
+ )}
189
+ </tr>
190
+ )
191
+ ) : (
192
+ <tr>
193
+ <td colSpan={columnsTotal}>
194
+ Not results found.
195
+ </td>
196
+ </tr>
197
+ )
198
+ )}
199
+ </tbody>
200
+ </table>
201
+ </>
202
+ );
203
+ });
204
+
205
+ export default GridTableView;
@@ -0,0 +1,80 @@
1
+ import {Link, useSearchParams} from "react-router-dom";
2
+ import {ListMetaType} from "@src/type/ListMetaType";
3
+ import {RouteType} from "@src/type/RouteType";
4
+
5
+ const PageItem = ({route, page, active = false, title, children}: {
6
+ route?: RouteType,
7
+ page: number | string,
8
+ active?: boolean,
9
+ title?: string,
10
+ children?: any
11
+ }) => {
12
+ const url = new URL(document.location.href);
13
+ url.searchParams.set('page', page.toString());
14
+
15
+ return (
16
+ <li className={`page-item ${active ? 'active' : ''}`}>
17
+ <Link
18
+ to={url.toString()}
19
+ className="page-link"
20
+ title={title}>
21
+ {children || page}
22
+ </Link>
23
+ </li>
24
+ )
25
+ }
26
+
27
+ const Paginator = ({meta}: { meta: ListMetaType, route?: RouteType }) => {
28
+ const firstPage = 1;
29
+ const lastPage = meta.totalPages;
30
+ const page = meta.page || firstPage;
31
+ const link = meta.links;
32
+ const hasPagination = !!meta.totalPages;
33
+
34
+ return (
35
+ <div className="d-flex flex-column justiry-content-center">
36
+ <small className="mb-2">
37
+ {meta.totalResults} Results
38
+ {hasPagination && (<> - Page {page} of {meta.totalPages}</>)}
39
+ </small>
40
+ {hasPagination &&
41
+ <nav aria-label="Page navigation" className="m-auto text-center d-inline">
42
+ <ul className="pagination pagination-sm">
43
+ {page > firstPage && (
44
+ <PageItem page={page - 1} title="Go to First Page">
45
+ {'\u00ab'}
46
+ </PageItem>
47
+ )}
48
+ {meta.links[0] !== firstPage && (
49
+ <>
50
+ <PageItem key={1} page={1} active={firstPage === page}>{firstPage}</PageItem>
51
+ <div className={"page-item"}>
52
+ <a className="page-link">...</a>
53
+ </div>
54
+ </>
55
+ )}
56
+ {(link || []).map((p, i) => (
57
+ <PageItem key={i} page={p} active={p === page}/>
58
+ ))}
59
+ {[...meta.links].reverse()[0] !== lastPage && (
60
+ <>
61
+ <div className={"page-item"}>
62
+ <a className="page-link">...</a>
63
+ </div>
64
+ <PageItem key={lastPage} page={lastPage}
65
+ active={lastPage === page}>{lastPage}</PageItem>
66
+ </>
67
+ )}
68
+ {page < lastPage && (
69
+ <PageItem page={meta.totalPages} title="Go to Last Page">
70
+ {'\u00bb'}
71
+ </PageItem>
72
+ )}
73
+ </ul>
74
+ </nav>
75
+ }
76
+ </div>
77
+ )
78
+ }
79
+
80
+ export default Paginator;
@@ -0,0 +1,78 @@
1
+ import * as React from 'react';
2
+ import Exception from "@src/component/error/Exception.tsx";
3
+ import HttpException from "@src/component/error/HttpException.tsx";
4
+
5
+ type ErrorBoundaryProps = {
6
+ fallback: React.ReactElement;
7
+ children: any
8
+ }
9
+
10
+ type ErrorBoundaryState = {
11
+ hasError: boolean;
12
+ error: Error | Exception | null
13
+ }
14
+
15
+ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
16
+ constructor(props: ErrorBoundaryProps) {
17
+ super(props);
18
+ this.state = {
19
+ hasError: false,
20
+ error: null
21
+ };
22
+ }
23
+
24
+ private promiseRejectionHandler = (e: PromiseRejectionEvent) => {
25
+ if(!(e.reason instanceof Exception)) {
26
+ return;
27
+ }
28
+
29
+ this.setState({
30
+ ...this.state,
31
+ hasError: true,
32
+ error: e.reason
33
+ })
34
+ };
35
+
36
+ componentDidMount() {
37
+ window.addEventListener('unhandledrejection', this.promiseRejectionHandler);
38
+ }
39
+
40
+ componentWillUnmount() {
41
+ window.removeEventListener('unhandledrejection', this.promiseRejectionHandler);
42
+ }
43
+
44
+ static getDerivedStateFromError(error: any) {
45
+ // Update state so the next render will show the fallback UI.
46
+ if(error instanceof Error) {
47
+ error = new HttpException(0, error.message)
48
+ }
49
+
50
+ return {
51
+ hasError: true,
52
+ error: error
53
+ };
54
+ }
55
+
56
+ componentDidCatch(error: any, info: any) {
57
+ // Todo: Log error
58
+
59
+ // console.log('error', error);
60
+
61
+ }
62
+
63
+ render() {
64
+ if (this.state.hasError) {
65
+ // You can render any custom fallback UI
66
+ return React.cloneElement<any>(
67
+ this.props.fallback, {
68
+ error: this.state.error
69
+ }
70
+ );
71
+ }
72
+
73
+ return this.props.children;
74
+ }
75
+ }
76
+
77
+
78
+ export default ErrorBoundary;
@@ -0,0 +1,17 @@
1
+ import {ExceptionTraceType} from "@src/component/error/HttpException.tsx";
2
+
3
+ class Exception {
4
+ code: number;
5
+
6
+ detail: string;
7
+
8
+ trace?: ExceptionTraceType[];
9
+
10
+ constructor(code: number = 0, detail: string, trace?: ExceptionTraceType[]) {
11
+ this.code = code;
12
+ this.detail = detail;
13
+ this.trace = trace;
14
+ }
15
+ }
16
+
17
+ export default Exception;
@@ -0,0 +1,24 @@
1
+ import Exception from "@src/component/error/Exception.tsx";
2
+
3
+ export type ExceptionTraceType = {
4
+ type: string;
5
+ file: string;
6
+ class: string;
7
+ args: string[];
8
+ function: string;
9
+ line: number;
10
+ namespace: string;
11
+ short_class: string;
12
+ };
13
+
14
+ class HttpException extends Exception {
15
+
16
+ status: number = 400;
17
+
18
+ constructor(status: number, detail: string, trace?: ExceptionTraceType[]) {
19
+ super(0, detail, trace);
20
+ this.status = status;
21
+ }
22
+ }
23
+
24
+ export default HttpException;
@@ -0,0 +1,119 @@
1
+ import React, {createRef, useEffect, useRef} from "react";
2
+ import {nameToId, useForm} from "./Form";
3
+ import {FormFieldProps} from "@src/component/form/Input";
4
+ import {ChoiceType, FormViewType} from "@src/type/FormViewType";
5
+
6
+ export type ChoiceProps = {
7
+ view: FormViewType,
8
+ choiceValueTransform?: Function,
9
+ choiceLabelTransform?: Function
10
+ } & FormFieldProps;
11
+
12
+ const Choice = ({
13
+ view,
14
+ constraints,
15
+ className,
16
+ onChange,
17
+ choiceValueTransform,
18
+ choiceLabelTransform,
19
+ ...props
20
+ }: ChoiceProps):
21
+ React.JSX.Element => {
22
+ constraints = constraints || [];
23
+
24
+ const [[formState, dispatch], formRef] = useForm();
25
+ const fieldRef = useRef<HTMLSelectElement | HTMLInputElement | null>(null);
26
+ const errorMessages = formState?.errors[view.full_name] || [];
27
+ const isInvalid = !!errorMessages.length;
28
+ const key = btoa(encodeURIComponent(view.full_name + JSON.stringify(view.data)));
29
+
30
+ useEffect(() => {
31
+ dispatch({
32
+ action: 'constraints',
33
+ payload: {
34
+ name: view.full_name,
35
+ constraints: constraints
36
+ }
37
+ });
38
+ }, [])
39
+
40
+ const validate = (value: any) => {
41
+ dispatch({action: 'validate', payload: view.full_name});
42
+ onChange && onChange(value);
43
+ }
44
+
45
+ if (view?.expanded) {
46
+ return <>
47
+ {Object.values(view.choices || []).map((choice: ChoiceType, choiceIndex: number) => {
48
+ const elementId = nameToId(view.full_name, choiceIndex);
49
+ const choiceValue = choiceValueTransform ? choiceValueTransform(choice) : choice.value;
50
+ const choiceLabel = choiceLabelTransform ? choiceLabelTransform(choice) : choice.label || choiceValue;
51
+ const attributes = {
52
+ id: elementId,
53
+ ...(view?.choice_attr && (view?.choice_attr instanceof Function ? view?.choice_attr(choice) : view?.choice_attr))
54
+ }
55
+ return <div
56
+ key={choiceIndex}
57
+ className={"form-check"}
58
+ >
59
+ <input
60
+ key={key}
61
+ ref={fieldRef}
62
+ defaultValue={choiceValue}
63
+ type={view?.multiple ? 'checkbox' : 'radio'}
64
+ defaultChecked={view?.data?.includes(choiceValue)}
65
+ name={view?.full_name + '[]'}
66
+ id={elementId}
67
+ className={"form-check-input"}
68
+ {...attributes}
69
+ onChange={(e) => {
70
+ return validate({
71
+ value: (view?.multiple ? formRef?.current?.getFormData().getAll(view?.full_name) : formRef?.current?.getFormData().get(view?.full_name)) || e.target.value,
72
+ targetValue: e.target.value,
73
+ checked: e.target.checked
74
+ })
75
+ }}
76
+ />
77
+ <label
78
+ htmlFor={attributes.id}
79
+ className={"form-check-label"}
80
+ >
81
+ {choiceLabel}
82
+ </label>
83
+ </div>
84
+ }
85
+ )}
86
+ </>
87
+ } else {
88
+ return (
89
+ <>
90
+ <select
91
+ ref={fieldRef}
92
+ key={key}
93
+ name={view.full_name}
94
+ multiple={view.multiple}
95
+ aria-invalid={isInvalid}
96
+ onChange={(e) => validate({
97
+ value: (view.multiple ? formRef?.current?.getFormData().getAll(view.full_name) : formRef?.current?.getFormData().get(view.full_name)) || e.target.value
98
+ })}
99
+ className={[...((className || '').split(' ') || []), 'form-control', ...(isInvalid ? ['is-invalid'] : [])].join(' ')}
100
+ {...(view.attr && (view.attr instanceof Function ? view.attr() : view.attr))}
101
+ defaultValue={view.data}
102
+ >
103
+ {view.placeholder && <option value={''}>{view.placeholder}</option>}
104
+ {Object.values(view.choices || []).map((choice: any, index: number) =>
105
+ <option
106
+ key={index}
107
+ value={choice.value || choice.label}
108
+ {...(view.choice_attr && (view.choice_attr instanceof Function ? view.choice_attr(choice) : view.choice_attr))}
109
+ >
110
+ {choice.label}
111
+ </option>
112
+ )}
113
+ </select>
114
+ </>
115
+ )
116
+ }
117
+ }
118
+
119
+ export default Choice;