antd-crud-table 0.0.1 → 0.0.3

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.
@@ -0,0 +1,33 @@
1
+ name: Build and Publish to GH Pages
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+
7
+ jobs:
8
+ build:
9
+
10
+ runs-on: ubuntu-latest
11
+
12
+ strategy:
13
+ matrix:
14
+ node-version: [18.x]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v1
18
+ - name: Use Node.js ${{ matrix.node-version }}
19
+ uses: actions/setup-node@v1
20
+ with:
21
+ node-version: ${{ matrix.node-version }}
22
+ - name: 'Installing build deps'
23
+ run: npm i -g pnpm
24
+ - name: 'Installing deps'
25
+ run: pnpm i
26
+ - name: 'Build'
27
+ run: pnpm build:static
28
+ - name: 'Deploy'
29
+ uses: peaceiris/actions-gh-pages@v4
30
+ with:
31
+ deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }}
32
+ publish_dir: ./dist
33
+ allow_empty_commit: true
@@ -0,0 +1,31 @@
1
+ name: Publish to NPM
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+
11
+ strategy:
12
+ matrix:
13
+ node-version: [18.x]
14
+ registry-url: ['https://registry.npmjs.org']
15
+
16
+ steps:
17
+ - uses: actions/checkout@v2
18
+ - uses: actions/setup-node@v2
19
+ with:
20
+ node-version: ${{ matrix.node-version }}
21
+ registry-url: ${{ matrix.registry-url }}
22
+ - name: 'Installing build deps'
23
+ run: npm i -g pnpm
24
+ - name: 'Installing deps'
25
+ run: pnpm i
26
+ - name: 'Build'
27
+ run: pnpm build:lib
28
+ - name: 'Publish'
29
+ run: pnpm publish --no-git-checks
30
+ env:
31
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Maifee Ul Asad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # antd-crud-table
2
+ Easy CRUD table with AntD (Ant Design)
@@ -0,0 +1,28 @@
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import tseslint from 'typescript-eslint'
6
+
7
+ export default tseslint.config(
8
+ { ignores: ['dist'] },
9
+ {
10
+ extends: [js.configs.recommended, ...tseslint.configs.recommended],
11
+ files: ['**/*.{ts,tsx}'],
12
+ languageOptions: {
13
+ ecmaVersion: 2020,
14
+ globals: globals.browser,
15
+ },
16
+ plugins: {
17
+ 'react-hooks': reactHooks,
18
+ 'react-refresh': reactRefresh,
19
+ },
20
+ rules: {
21
+ ...reactHooks.configs.recommended.rules,
22
+ 'react-refresh/only-export-components': [
23
+ 'warn',
24
+ { allowConstantExport: true },
25
+ ],
26
+ },
27
+ },
28
+ )
@@ -0,0 +1,22 @@
1
+ import { promises as fs } from 'fs';
2
+ import path from 'path';
3
+ import packageJson from '../package.json' assert { type: 'json' };
4
+ import { exit } from 'process';
5
+
6
+ const distPath = path.resolve('dist/lib');
7
+ const packageJsonPath = path.join(distPath, 'package.json');
8
+
9
+ (async () => {
10
+ try {
11
+ // Ensure the dist/lib directory exists
12
+ await fs.mkdir(distPath, { recursive: true });
13
+
14
+ // Write the package.json file to the `dist/lib` directory
15
+ await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');
16
+
17
+ console.log(`package.json has been copied to ${packageJsonPath}`);
18
+ } catch (error) {
19
+ console.error('Error copying package.json:', error);
20
+ exit(1);
21
+ }
22
+ })();
package/index.html ADDED
@@ -0,0 +1,22 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Vite + React + TS</title>
8
+
9
+ <script async src="https://www.googletagmanager.com/gtag/js?id=G-3G1RNC5YLT"></script>
10
+ <script>
11
+ window.dataLayer = window.dataLayer || [];
12
+ function gtag(){dataLayer.push(arguments);}
13
+ gtag('js', new Date());
14
+
15
+ gtag('config', 'G-3G1RNC5YLT');
16
+ </script>
17
+ </head>
18
+ <body>
19
+ <div id="root"></div>
20
+ <script type="module" src="/src/main.tsx"></script>
21
+ </body>
22
+ </html>
@@ -0,0 +1,3 @@
1
+ .row-differentiator {
2
+ background-color: #0000007f;
3
+ }
@@ -0,0 +1,314 @@
1
+ import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
2
+ import type { ActionType, ProColumns } from '@ant-design/pro-components';
3
+ import { ProTable, ProConfigProvider } from '@ant-design/pro-components';
4
+ import { Button, Dropdown, Tag, message, Modal, Form, Input, InputNumber, Select, Switch, DatePicker } from 'antd';
5
+ import { useRef, useState } from 'react';
6
+ import type { SortOrder } from 'antd/es/table/interface';
7
+ import { format, parseISO, formatISO } from 'date-fns';
8
+ import dayjs from 'dayjs';
9
+
10
+ import './CrudTable.css';
11
+
12
+ type DataType = Record<string, any>;
13
+ type FieldType = 'string' | 'number' | 'date' | 'boolean' | 'enum' | 'custom';
14
+
15
+ interface CrudColumn<T extends DataType> extends ProColumns<T> {
16
+ fieldType?: FieldType;
17
+ enumOptions?: Record<string, { text: string;[key: string]: any }>;
18
+ customRender?: (value: any, record: T) => React.ReactNode;
19
+ formConfig?: {
20
+ required?: boolean;
21
+ component?: React.ReactNode;
22
+ transform?: (value: any) => any;
23
+ };
24
+ fieldEditable?: boolean;
25
+ }
26
+
27
+ interface CrudTableConfig<T extends DataType> {
28
+ columns: CrudColumn<T>[];
29
+ service: {
30
+ getList: (params: any) => Promise<{ data: T[]; total: number }>;
31
+ create: (data: Partial<T>) => Promise<T>;
32
+ update: (id: any, data: Partial<T>) => Promise<T>;
33
+ delete: (id: any) => Promise<void>;
34
+ };
35
+ rowKey: keyof T;
36
+ title: string;
37
+ defaultPageSize?: number;
38
+ }
39
+
40
+ const CrudTable = <T extends DataType>(config: CrudTableConfig<T>) => {
41
+ const actionRef = useRef<ActionType>(null);
42
+ const { columns, service, rowKey, title, defaultPageSize = 5 } = config;
43
+ const [modalVisible, setModalVisible] = useState(false);
44
+ const [currentRecord, setCurrentRecord] = useState<Partial<T> | null>(null);
45
+ const [form] = Form.useForm();
46
+
47
+ let enhancedColumns: ProColumns<T>[] = (columns || []).map((col) => {
48
+ const baseColumn: ProColumns<T> = {
49
+ ...col,
50
+ dataIndex: col.dataIndex as string,
51
+ title: col.title,
52
+ };
53
+
54
+ switch (col.fieldType) {
55
+ case 'date':
56
+ return {
57
+ ...baseColumn,
58
+ valueType: 'dateTime',
59
+ render: (_, record) => (
60
+ <span>
61
+ {format(parseISO(record[col.dataIndex as string]), 'yyyy-MM-dd HH:mm')}
62
+ </span>
63
+ ),
64
+ };
65
+ case 'enum':
66
+ return {
67
+ ...baseColumn,
68
+ valueType: 'select',
69
+ valueEnum: col.enumOptions,
70
+ };
71
+ case 'number':
72
+ return {
73
+ ...baseColumn,
74
+ valueType: 'digit',
75
+ };
76
+ case 'boolean':
77
+ return {
78
+ ...baseColumn,
79
+ valueType: 'switch',
80
+ render: (_, record) => (
81
+ <Tag color={record[col.dataIndex as string] ? 'green' : 'red'}>
82
+ {record[col.dataIndex as string] ? 'Yes' : 'No'}
83
+ </Tag>
84
+ ),
85
+ };
86
+ case 'custom':
87
+ return {
88
+ ...baseColumn,
89
+ render: (_, record) => col.customRender?.(record[col.dataIndex as string], record),
90
+ };
91
+ default:
92
+ return baseColumn;
93
+ }
94
+ });
95
+ enhancedColumns.push({
96
+ title: 'Actions',
97
+ valueType: 'option',
98
+ render: (_, record: T) => [
99
+ <Button key="edit" type="primary" onClick={() => openModal(record)}>
100
+ Edit
101
+ </Button>,
102
+ <Button key="delete" type="primary" danger onClick={async () => {
103
+ await service.delete(record[rowKey]);
104
+ actionRef.current?.reload();
105
+ }}>
106
+ Delete
107
+ </Button>,
108
+ ],
109
+ });
110
+
111
+ const handleRequest = async (
112
+ params: Record<string, any>,
113
+ sort: Record<string, SortOrder>,
114
+ filter: Record<string, any>,
115
+ ) => {
116
+ try {
117
+ const query = {
118
+ ...params,
119
+ sortBy: Object.keys(sort)[0],
120
+ sortOrder: Object.values(sort)[0],
121
+ ...filter,
122
+ };
123
+ const { data, total } = await service.getList(query);
124
+ return { data, success: true, total };
125
+ } catch (error) {
126
+ message.error('Failed to fetch data');
127
+ return { data: [], success: false, total: 0 };
128
+ }
129
+ };
130
+
131
+ const openModal = (record?: Partial<T>) => {
132
+ setCurrentRecord(record || null);
133
+ if (record) {
134
+ const values = { ...record };
135
+ columns.forEach((col) => {
136
+ const field = col.dataIndex as string;
137
+ if (col.fieldType === 'date' && values[field]) {
138
+ // @ts-ignore
139
+ values[field] = dayjs(values[field]);
140
+ }
141
+ });
142
+ form.setFieldsValue(values);
143
+ } else {
144
+ form.resetFields();
145
+ }
146
+ setModalVisible(true);
147
+ };
148
+
149
+ const handleOk = async () => {
150
+ try {
151
+ const values = await form.validateFields();
152
+ const transformedValues = { ...values };
153
+
154
+ // Handle any transformations like date formatting
155
+ columns.forEach((col) => {
156
+ const field = col.dataIndex as string;
157
+ if (col.fieldType === 'date' && values[field]) {
158
+ transformedValues[field] = formatISO(values[field]);
159
+ }
160
+ if (col.formConfig?.transform) {
161
+ transformedValues[field] = col.formConfig.transform(values[field]);
162
+ }
163
+ });
164
+
165
+ if (currentRecord && currentRecord[rowKey]) {
166
+ await service.update(currentRecord[rowKey], transformedValues);
167
+ message.success('Updated successfully');
168
+ } else {
169
+ await service.create(transformedValues);
170
+ message.success('Created successfully');
171
+ }
172
+
173
+ setModalVisible(false);
174
+ actionRef.current?.reload();
175
+ } catch (error) {
176
+ console.error(error);
177
+ message.error('Submit failed');
178
+ }
179
+ };
180
+
181
+ const handleCancel = () => {
182
+ setModalVisible(false);
183
+ };
184
+
185
+ return (
186
+ <ProConfigProvider needDeps>
187
+ <ProTable<T>
188
+ headerTitle={title}
189
+ rowKey={rowKey as string}
190
+ // row classname to gray and white
191
+ rowClassName={(_, index) => (index % 2 === 0 && 'row-differentiator' || '')}
192
+ actionRef={actionRef}
193
+ columns={enhancedColumns}
194
+ request={handleRequest}
195
+ search={{ labelWidth: 'auto' }}
196
+ pagination={{ pageSize: defaultPageSize }}
197
+ toolBarRender={() => [
198
+ <Button
199
+ key="add"
200
+ type="primary"
201
+ icon={<PlusOutlined />}
202
+ onClick={() => openModal()}
203
+ >
204
+ New
205
+ </Button>,
206
+ <Dropdown
207
+ key="menu"
208
+ menu={{
209
+ items: [
210
+ { key: 'export', label: 'Export' },
211
+ { key: 'refresh', label: 'Refresh', onClick: () => actionRef.current?.reload() },
212
+ ],
213
+ }}
214
+ >
215
+ <Button>
216
+ <EllipsisOutlined />
217
+ </Button>
218
+ </Dropdown>,
219
+ ]}
220
+ options={{
221
+ setting: { listsHeight: 400 },
222
+ reload: () => actionRef.current?.reload(),
223
+ }}
224
+ dateFormatter="string"
225
+ />
226
+
227
+ <Modal
228
+ forceRender
229
+ title={currentRecord ? 'Edit Item' : 'Create Item'}
230
+ open={modalVisible}
231
+ onOk={handleOk}
232
+ onCancel={handleCancel}
233
+ destroyOnClose
234
+ >
235
+ <Form form={form} layout="vertical">
236
+ {columns.map((col) => {
237
+ if (!col.dataIndex) return null;
238
+ const name = col.dataIndex as string;
239
+ const label = col.title as string;
240
+ const fieldDisabled = !(col.fieldEditable ?? true);
241
+
242
+ switch (col.fieldType) {
243
+ case 'string':
244
+ return (
245
+ <Form.Item
246
+ key={name}
247
+ name={name}
248
+ label={label}
249
+ rules={[{ required: col.formConfig?.required, message: `${label} is required` }]}
250
+ >
251
+ <Input disabled={fieldDisabled} />
252
+ </Form.Item>
253
+ );
254
+ case 'number':
255
+ return (
256
+ <Form.Item
257
+ key={name}
258
+ name={name}
259
+ label={label}
260
+ rules={[{ required: col.formConfig?.required, message: `${label} is required` }]}
261
+ >
262
+ <InputNumber style={{ width: '100%' }} disabled={fieldDisabled} />
263
+ </Form.Item>
264
+ );
265
+ case 'date':
266
+ return (
267
+ <Form.Item
268
+ key={name}
269
+ name={name}
270
+ label={label}
271
+ rules={[{ required: col.formConfig?.required, message: `${label} is required` }]}
272
+ >
273
+ <DatePicker style={{ width: '100%' }} showTime disabled={fieldDisabled} />
274
+ </Form.Item>
275
+ );
276
+ case 'boolean':
277
+ return (
278
+ <Form.Item
279
+ key={name}
280
+ name={name}
281
+ label={label}
282
+ valuePropName="checked"
283
+ >
284
+ <Switch disabled={fieldDisabled} />
285
+ </Form.Item>
286
+ );
287
+ case 'enum':
288
+ return (
289
+ <Form.Item
290
+ key={name}
291
+ name={name}
292
+ label={label}
293
+ rules={[{ required: col.formConfig?.required, message: `${label} is required` }]}
294
+ >
295
+ <Select
296
+ disabled={fieldDisabled}
297
+ options={Object.entries(col.enumOptions || {}).map(([value, option]) => ({
298
+ label: option.text,
299
+ value,
300
+ }))} />
301
+ </Form.Item>
302
+ );
303
+ default:
304
+ return null;
305
+ }
306
+ })}
307
+ </Form>
308
+ </Modal>
309
+ </ProConfigProvider>
310
+ );
311
+ };
312
+
313
+ export default CrudTable;
314
+ export type { CrudTableConfig, CrudColumn, DataType };
@@ -0,0 +1,27 @@
1
+ import { Suspense, lazy } from 'react';
2
+ import type { CrudTableConfig, DataType } from './CrudTable';
3
+
4
+ const CrudTable = lazy(() => import('./CrudTable'));
5
+
6
+ const CrudTableLazy = <T extends DataType>(props: CrudTableConfig<T>) => {
7
+ const { columns, service, rowKey, title, defaultPageSize = 5 } = props;
8
+ return (
9
+ <Suspense
10
+ fallback={
11
+ <div style={{ textAlign: 'center', padding: '2rem' }}>
12
+ Loading curd table w antd
13
+ </div>
14
+ }
15
+ >
16
+ <CrudTable
17
+ columns={columns as any}
18
+ service={service as any}
19
+ rowKey={rowKey as string}
20
+ title={title}
21
+ defaultPageSize={defaultPageSize}
22
+ />
23
+ </Suspense>
24
+ );
25
+ };
26
+
27
+ export default CrudTableLazy;
package/lib/main.ts ADDED
@@ -0,0 +1,5 @@
1
+ import CrudTable from "./CrudTable/CrudTable";
2
+ import CrudTableLazy from "./CrudTable/CrudTableLazy";
3
+
4
+ export { CrudTable, CrudTableLazy };
5
+ export type { CrudTableConfig, CrudColumn, DataType } from "./CrudTable/CrudTable";
package/package.json CHANGED
@@ -1,16 +1,9 @@
1
1
  {
2
2
  "name": "antd-crud-table",
3
3
  "private": false,
4
- "version": "0.0.1",
4
+ "version": "0.0.3",
5
5
  "type": "module",
6
6
  "homepage": ".",
7
- "scripts": {
8
- "dev": "vite",
9
- "build:static": "tsc -b && vite build",
10
- "build:lib": "tsc --p ./tsconfig.build.json && vite build --config vite.config.lib.ts",
11
- "lint": "eslint .",
12
- "preview": "vite preview"
13
- },
14
7
  "devDependencies": {
15
8
  "@ant-design/icons": "^6.0.0",
16
9
  "@ant-design/pro-components": "^2.8.7",
@@ -40,5 +33,12 @@
40
33
  "dayjs": "^1.11.13",
41
34
  "react": "^19.0.0",
42
35
  "react-dom": "^19.0.0"
36
+ },
37
+ "scripts": {
38
+ "dev": "vite",
39
+ "build:static": "tsc -b && vite build",
40
+ "build:lib": "tsc --p ./tsconfig.build.json && vite build --config vite.config.lib.ts && node helper/post-build.js",
41
+ "lint": "eslint .",
42
+ "preview": "vite preview"
43
43
  }
44
- }
44
+ }
package/src/App.css ADDED
@@ -0,0 +1,42 @@
1
+ #root {
2
+ max-width: 1280px;
3
+ margin: 0 auto;
4
+ padding: 2rem;
5
+ text-align: center;
6
+ }
7
+
8
+ .logo {
9
+ height: 6em;
10
+ padding: 1.5em;
11
+ will-change: filter;
12
+ transition: filter 300ms;
13
+ }
14
+ .logo:hover {
15
+ filter: drop-shadow(0 0 2em #646cffaa);
16
+ }
17
+ .logo.react:hover {
18
+ filter: drop-shadow(0 0 2em #61dafbaa);
19
+ }
20
+
21
+ @keyframes logo-spin {
22
+ from {
23
+ transform: rotate(0deg);
24
+ }
25
+ to {
26
+ transform: rotate(360deg);
27
+ }
28
+ }
29
+
30
+ @media (prefers-reduced-motion: no-preference) {
31
+ a:nth-of-type(2) .logo {
32
+ animation: logo-spin infinite 20s linear;
33
+ }
34
+ }
35
+
36
+ .card {
37
+ padding: 2em;
38
+ }
39
+
40
+ .read-the-docs {
41
+ color: #888;
42
+ }