@bomjan133/react-crud-ui 1.2.6 → 1.2.7
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/README.md +4284 -23
- package/dist/components/book-viewer/EpubViewer.d.ts +8 -0
- package/dist/components/book-viewer/PdfViewer.d.ts +9 -0
- package/dist/components/book-viewer/constants.d.ts +23 -0
- package/dist/components/book-viewer/hooks.d.ts +6 -0
- package/dist/components/book-viewer/index.d.ts +16 -0
- package/dist/components/book-viewer/ui.d.ts +16 -0
- package/dist/components/book-viewer/utils.d.ts +12 -0
- package/dist/components/crud/CrudDetail.d.ts +86 -0
- package/dist/components/crud/CrudForm.d.ts +33 -0
- package/dist/components/crud/CrudList.d.ts +105 -0
- package/dist/components/crud/DataTable.d.ts +64 -0
- package/dist/components/crud/EmptyState.d.ts +54 -0
- package/dist/components/crud/Loading.d.ts +32 -0
- package/dist/components/crud/Modal.d.ts +75 -0
- package/dist/components/crud/Pagination.d.ts +18 -0
- package/dist/components/crud/ServerErrorPage.d.ts +7 -0
- package/dist/components/layouts/AuthLayout.d.ts +32 -0
- package/dist/components/layouts/BreadcrumbContext.d.ts +4 -0
- package/dist/components/layouts/DashboardLayout.d.ts +41 -0
- package/dist/components/layouts/DetailView.d.ts +58 -0
- package/dist/components/layouts/Header.d.ts +13 -0
- package/dist/components/layouts/HeaderSlotContext.d.ts +4 -0
- package/dist/components/layouts/LoginPage.d.ts +50 -0
- package/dist/components/layouts/Sidebar.d.ts +38 -0
- package/dist/components/layouts/SidebarContext.d.ts +18 -0
- package/dist/components/layouts/index.d.ts +8 -0
- package/dist/components/toast/ToastContainer.d.ts +4 -0
- package/dist/components/toast/useUI.d.ts +33 -0
- package/dist/components/ui/CopyableField.d.ts +12 -0
- package/dist/components/ui/DownloadableButton.d.ts +15 -0
- package/dist/components/ui/alert-dialog.d.ts +26 -0
- package/dist/components/ui/alert.d.ts +8 -0
- package/dist/components/ui/avatar.d.ts +4 -0
- package/dist/components/ui/badge.d.ts +8 -0
- package/dist/components/ui/button.d.ts +6 -0
- package/dist/components/ui/calendar.d.ts +16 -0
- package/dist/components/ui/card.d.ts +7 -0
- package/dist/components/ui/checkbox.d.ts +2 -0
- package/dist/components/ui/collapsible.d.ts +3 -0
- package/dist/components/ui/date-picker.d.ts +2 -0
- package/dist/components/ui/date-range-picker.d.ts +2 -0
- package/dist/components/ui/dialog.d.ts +25 -0
- package/dist/components/ui/dropdown-menu.d.ts +23 -0
- package/dist/components/ui/form-fields.d.ts +19 -0
- package/dist/components/ui/input-group.d.ts +28 -0
- package/dist/components/ui/input.d.ts +2 -0
- package/dist/components/ui/label.d.ts +2 -0
- package/dist/components/ui/popover.d.ts +5 -0
- package/dist/components/ui/q-tabs.d.ts +18 -0
- package/dist/components/ui/rich-text-editor.d.ts +2 -0
- package/dist/components/ui/scroll-area.d.ts +3 -0
- package/dist/components/ui/search-select.d.ts +6 -0
- package/dist/components/ui/select.d.ts +12 -0
- package/dist/components/ui/separator.d.ts +2 -0
- package/dist/components/ui/skeleton.d.ts +4 -0
- package/dist/components/ui/switch.d.ts +2 -0
- package/dist/components/ui/table.d.ts +9 -0
- package/dist/components/ui/tabs.d.ts +6 -0
- package/dist/components/ui/textarea.d.ts +2 -0
- package/dist/components/ui/tiptap-editor.d.ts +2 -0
- package/dist/components/ui/tooltip.d.ts +6 -0
- package/dist/index.d.ts +42 -0
- package/dist/lib/utils.d.ts +61 -0
- package/dist/store/createCrudStore.d.ts +11 -0
- package/dist/store/useUIStore.d.ts +5 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,17 +16,4290 @@ A comprehensive React CRUD and UI component library with Zustand store integrati
|
|
|
16
16
|
|
|
17
17
|
## Documentation
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
- [Getting Started](
|
|
22
|
-
- [UI Components](
|
|
23
|
-
- [CRUD Components](
|
|
24
|
-
- [Form Components](
|
|
25
|
-
- [Layout Components](
|
|
26
|
-
- [Store Factory](
|
|
27
|
-
- [Book Viewer](
|
|
28
|
-
- [Toast Notifications](
|
|
29
|
-
- [Utilities](
|
|
19
|
+
The full component/API reference ships inside the package (`node_modules/@bomjan133/react-crud-ui/docs/`) and is also inlined below as collapsible sections, so you can read it directly on this page (npmjs.com or GitLab) without leaving it.
|
|
20
|
+
|
|
21
|
+
- [Getting Started](#getting-started) - Installation and setup
|
|
22
|
+
- [UI Components](#ui-components) - Button, Card, Badge, Input, Select, etc.
|
|
23
|
+
- [CRUD Components](#crud-components) - DataTable, CrudList, CrudForm, CrudDetail
|
|
24
|
+
- [Form Components](#form-components) - QInput, QTextarea, QSelect, QSwitch
|
|
25
|
+
- [Layout Components](#layout-components) - AuthLayout, LoginPage, DashboardLayout
|
|
26
|
+
- [Store Factory](#store-factory) - createCrudStore and store patterns
|
|
27
|
+
- [Book Viewer](#book-viewer) - BookViewer, EpubViewer, PdfViewer for EPUB/PDF flipbooks
|
|
28
|
+
- [Toast Notifications](#toast-notifications) - useToast, ToastContainer
|
|
29
|
+
- [Utilities](#utilities) - formatCurrency, formatDate, debounce, slugify, and more
|
|
30
|
+
|
|
31
|
+
<a id="getting-started"></a>
|
|
32
|
+
<details>
|
|
33
|
+
<summary><strong>1. Getting Started</strong></summary>
|
|
34
|
+
|
|
35
|
+
A comprehensive React CRUD and UI component library with Zustand store integration.
|
|
36
|
+
|
|
37
|
+
## Table of Contents
|
|
38
|
+
1. [Installation](#installation)
|
|
39
|
+
2. [Quick Setup](#quick-setup)
|
|
40
|
+
3. [Project Structure](#project-structure)
|
|
41
|
+
4. [Creating Your First CRUD Module](#creating-your-first-crud-module)
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm install @bomjan133/react-crud-ui
|
|
49
|
+
# or
|
|
50
|
+
yarn add @bomjan133/react-crud-ui
|
|
51
|
+
# or
|
|
52
|
+
pnpm add @bomjan133/react-crud-ui
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Peer Dependencies
|
|
56
|
+
|
|
57
|
+
Make sure you have these peer dependencies installed:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
npm install react react-dom react-router-dom zustand axios
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Quick Setup
|
|
66
|
+
|
|
67
|
+
### 1. Import Styles
|
|
68
|
+
|
|
69
|
+
Add the styles to your main entry file (e.g., `main.jsx` or `App.jsx`):
|
|
70
|
+
|
|
71
|
+
```jsx
|
|
72
|
+
import '@bomjan133/react-crud-ui/styles.css'
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 2. Configure Tailwind v4 (Optional)
|
|
76
|
+
|
|
77
|
+
If you're using Tailwind CSS v4 in your project:
|
|
78
|
+
|
|
79
|
+
**index.css:**
|
|
80
|
+
```css
|
|
81
|
+
@import "tailwindcss";
|
|
82
|
+
|
|
83
|
+
@theme {
|
|
84
|
+
/* Light theme - Clean white/gray palette */
|
|
85
|
+
--color-background: #ffffff;
|
|
86
|
+
--color-foreground: #09090b;
|
|
87
|
+
--color-card: #ffffff;
|
|
88
|
+
--color-card-foreground: #09090b;
|
|
89
|
+
--color-popover: #ffffff;
|
|
90
|
+
--color-popover-foreground: #09090b;
|
|
91
|
+
--color-primary: #000000;
|
|
92
|
+
--color-primary-foreground: #fef2f2;
|
|
93
|
+
--color-secondary: #f4f4f5;
|
|
94
|
+
--color-secondary-foreground: #18181b;
|
|
95
|
+
--color-muted: #f4f4f5;
|
|
96
|
+
--color-muted-foreground: #71717a;
|
|
97
|
+
--color-accent: #f4f4f5;
|
|
98
|
+
--color-accent-foreground: #18181b;
|
|
99
|
+
--color-destructive: #ef4444;
|
|
100
|
+
--color-destructive-foreground: #fafafa;
|
|
101
|
+
--color-border: #e4e4e7;
|
|
102
|
+
--color-input: #e4e4e7;
|
|
103
|
+
--color-ring: #000000;
|
|
104
|
+
|
|
105
|
+
/* Sidebar specific */
|
|
106
|
+
--color-sidebar: #fafafa;
|
|
107
|
+
--color-sidebar-foreground: #3f3f46;
|
|
108
|
+
--color-sidebar-primary: #000000;
|
|
109
|
+
--color-sidebar-primary-foreground: #fafafa;
|
|
110
|
+
--color-sidebar-accent: #f4f4f5;
|
|
111
|
+
--color-sidebar-accent-foreground: #18181b;
|
|
112
|
+
--color-sidebar-border: #e5e7eb;
|
|
113
|
+
|
|
114
|
+
/* Border radius */
|
|
115
|
+
--radius-sm: 0.25rem;
|
|
116
|
+
--radius-md: 0.375rem;
|
|
117
|
+
--radius-lg: 0.5rem;
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 3. Set up API Client
|
|
122
|
+
|
|
123
|
+
Create an axios client for API calls:
|
|
124
|
+
|
|
125
|
+
**src/lib/apiClient.js:**
|
|
126
|
+
```js
|
|
127
|
+
import axios from 'axios';
|
|
128
|
+
|
|
129
|
+
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api/v1';
|
|
130
|
+
|
|
131
|
+
const apiClient = axios.create({
|
|
132
|
+
baseURL: API_BASE_URL,
|
|
133
|
+
headers: { 'Content-Type': 'application/json' },
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Add auth token to requests
|
|
137
|
+
apiClient.interceptors.request.use((config) => {
|
|
138
|
+
const token = localStorage.getItem('auth_token');
|
|
139
|
+
if (token) {
|
|
140
|
+
config.headers.Authorization = `Bearer ${token}`;
|
|
141
|
+
}
|
|
142
|
+
return config;
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// Handle auth errors
|
|
146
|
+
apiClient.interceptors.response.use(
|
|
147
|
+
(response) => response,
|
|
148
|
+
(error) => {
|
|
149
|
+
if (error.response?.status === 401) {
|
|
150
|
+
localStorage.removeItem('auth_token');
|
|
151
|
+
window.location.href = '/login';
|
|
152
|
+
}
|
|
153
|
+
return Promise.reject({
|
|
154
|
+
message: error.response?.data?.error || error.message,
|
|
155
|
+
status: error.response?.status,
|
|
156
|
+
data: error.response?.data,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
export default apiClient;
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Project Structure
|
|
167
|
+
|
|
168
|
+
Recommended project structure when using this package:
|
|
169
|
+
|
|
170
|
+
```
|
|
171
|
+
src/
|
|
172
|
+
├── App.jsx # Main app component
|
|
173
|
+
├── main.jsx # Entry point
|
|
174
|
+
├── index.css # Global styles (Tailwind)
|
|
175
|
+
│
|
|
176
|
+
├── pages/ # Page components (by module)
|
|
177
|
+
│ ├── auth/
|
|
178
|
+
│ │ └── LoginPage.jsx
|
|
179
|
+
│ ├── dashboard/
|
|
180
|
+
│ │ └── DashboardPage.jsx
|
|
181
|
+
│ ├── users/
|
|
182
|
+
│ │ ├── UserListPage.jsx
|
|
183
|
+
│ │ ├── UserFormPage.jsx
|
|
184
|
+
│ │ └── UserDetailPage.jsx
|
|
185
|
+
│ └── products/
|
|
186
|
+
│ ├── ProductListPage.jsx
|
|
187
|
+
│ ├── ProductFormPage.jsx
|
|
188
|
+
│ └── ProductDetailPage.jsx
|
|
189
|
+
│
|
|
190
|
+
├── routes/
|
|
191
|
+
│ ├── index.jsx # Main router
|
|
192
|
+
│ ├── guards.jsx # Protected/Public route guards
|
|
193
|
+
│ └── modules/
|
|
194
|
+
│ ├── userRoutes.js
|
|
195
|
+
│ └── productRoutes.js
|
|
196
|
+
│
|
|
197
|
+
├── stores/
|
|
198
|
+
│ ├── createCrudStore.js # Import from package or customize
|
|
199
|
+
│ ├── useAuthStore.js # Auth state
|
|
200
|
+
│ ├── useUIStore.js # UI state (toasts, modals, sidebar)
|
|
201
|
+
│ ├── useUserStore.js
|
|
202
|
+
│ └── useProductStore.js
|
|
203
|
+
│
|
|
204
|
+
├── components/
|
|
205
|
+
│ └── layouts/
|
|
206
|
+
│ ├── MainLayout.jsx # Uses DashboardLayout from package
|
|
207
|
+
│ └── AuthLayout.jsx # Uses AuthLayout from package
|
|
208
|
+
│
|
|
209
|
+
├── hooks/
|
|
210
|
+
│ └── useUI.js # Toast, modal, sidebar hooks
|
|
211
|
+
│
|
|
212
|
+
└── lib/
|
|
213
|
+
├── apiClient.js # Axios instance
|
|
214
|
+
└── utils.js # Utility functions
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
## Creating Your First CRUD Module
|
|
220
|
+
|
|
221
|
+
### Method 1: Using the CLI (Recommended)
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
npx @bomjan133/react-crud-ui generate product
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
This creates:
|
|
228
|
+
- `src/pages/products/ProductListPage.jsx`
|
|
229
|
+
- `src/pages/products/ProductFormPage.jsx`
|
|
230
|
+
- `src/pages/products/ProductDetailPage.jsx`
|
|
231
|
+
- `src/routes/modules/productRoutes.js`
|
|
232
|
+
- `src/stores/useProductStore.js`
|
|
233
|
+
|
|
234
|
+
### Method 2: Manual Setup
|
|
235
|
+
|
|
236
|
+
**1. Create the Store:**
|
|
237
|
+
|
|
238
|
+
```js
|
|
239
|
+
// src/stores/useProductStore.js
|
|
240
|
+
import { createCrudStore } from '@bomjan133/react-crud-ui';
|
|
241
|
+
|
|
242
|
+
const defaultFormValues = {
|
|
243
|
+
name: '',
|
|
244
|
+
description: '',
|
|
245
|
+
price: 0,
|
|
246
|
+
is_active: true,
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const useProductStore = createCrudStore('product', '/products/', defaultFormValues);
|
|
250
|
+
|
|
251
|
+
export default useProductStore;
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
**2. Create the List Page:**
|
|
255
|
+
|
|
256
|
+
```jsx
|
|
257
|
+
// src/pages/products/ProductListPage.jsx
|
|
258
|
+
import { CrudList, Badge } from '@bomjan133/react-crud-ui';
|
|
259
|
+
import useProductStore from '@/stores/useProductStore';
|
|
260
|
+
|
|
261
|
+
const columns = [
|
|
262
|
+
{ key: 'name', label: 'Name', sortable: true },
|
|
263
|
+
{ key: 'price', label: 'Price', render: (v) => `$${v}` },
|
|
264
|
+
{
|
|
265
|
+
key: 'is_active',
|
|
266
|
+
label: 'Status',
|
|
267
|
+
render: (v) => <Badge variant={v ? 'success' : 'secondary'}>{v ? 'Active' : 'Inactive'}</Badge>,
|
|
268
|
+
},
|
|
269
|
+
];
|
|
270
|
+
|
|
271
|
+
export default function ProductListPage() {
|
|
272
|
+
const store = useProductStore();
|
|
273
|
+
|
|
274
|
+
return (
|
|
275
|
+
<CrudList
|
|
276
|
+
title="Products"
|
|
277
|
+
description="Manage products"
|
|
278
|
+
createPath="/products/create"
|
|
279
|
+
editPath="/products"
|
|
280
|
+
store={store}
|
|
281
|
+
columns={columns}
|
|
282
|
+
searchPlaceholder="Search products..."
|
|
283
|
+
getDeleteItemName={(item) => item?.name}
|
|
284
|
+
/>
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
**3. Create the Form Page:**
|
|
290
|
+
|
|
291
|
+
```jsx
|
|
292
|
+
// src/pages/products/ProductFormPage.jsx
|
|
293
|
+
import { Box } from 'lucide-react';
|
|
294
|
+
import { CrudForm, QInput, QTextarea, QSwitch } from '@bomjan133/react-crud-ui';
|
|
295
|
+
import useProductStore from '@/stores/useProductStore';
|
|
296
|
+
|
|
297
|
+
export default function ProductFormPage() {
|
|
298
|
+
const { form, setFormField } = useProductStore();
|
|
299
|
+
|
|
300
|
+
return (
|
|
301
|
+
<CrudForm
|
|
302
|
+
title="Product"
|
|
303
|
+
description="Enter product information"
|
|
304
|
+
icon={Box}
|
|
305
|
+
listPath="/products"
|
|
306
|
+
useStore={useProductStore}
|
|
307
|
+
>
|
|
308
|
+
<QInput
|
|
309
|
+
name="name"
|
|
310
|
+
label="Name"
|
|
311
|
+
value={form.values.name || ''}
|
|
312
|
+
onChange={(val) => setFormField('name', val)}
|
|
313
|
+
error={form.errors.name}
|
|
314
|
+
placeholder="Enter name"
|
|
315
|
+
required
|
|
316
|
+
/>
|
|
317
|
+
<QTextarea
|
|
318
|
+
name="description"
|
|
319
|
+
label="Description"
|
|
320
|
+
value={form.values.description || ''}
|
|
321
|
+
onChange={(val) => setFormField('description', val)}
|
|
322
|
+
rows={4}
|
|
323
|
+
/>
|
|
324
|
+
<QInput
|
|
325
|
+
name="price"
|
|
326
|
+
label="Price"
|
|
327
|
+
type="number"
|
|
328
|
+
value={form.values.price || 0}
|
|
329
|
+
onChange={(val) => setFormField('price', parseFloat(val))}
|
|
330
|
+
/>
|
|
331
|
+
<QSwitch
|
|
332
|
+
label="Active"
|
|
333
|
+
checked={form.values.is_active ?? true}
|
|
334
|
+
onChange={(val) => setFormField('is_active', val)}
|
|
335
|
+
/>
|
|
336
|
+
</CrudForm>
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
**4. Create Routes:**
|
|
342
|
+
|
|
343
|
+
```jsx
|
|
344
|
+
// src/routes/modules/productRoutes.js
|
|
345
|
+
import ProductListPage from '@/pages/products/ProductListPage';
|
|
346
|
+
import ProductFormPage from '@/pages/products/ProductFormPage';
|
|
347
|
+
|
|
348
|
+
const productRoutes = [
|
|
349
|
+
{ path: '/products', element: <ProductListPage /> },
|
|
350
|
+
{ path: '/products/create', element: <ProductFormPage /> },
|
|
351
|
+
{ path: '/products/:id/edit', element: <ProductFormPage /> },
|
|
352
|
+
];
|
|
353
|
+
|
|
354
|
+
export default productRoutes;
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
---
|
|
358
|
+
|
|
359
|
+
## Next Steps
|
|
360
|
+
|
|
361
|
+
- [UI Components Guide](#ui-components) - Learn about all available UI components
|
|
362
|
+
- [CRUD Components Guide](#crud-components) - Deep dive into CRUD components
|
|
363
|
+
- [Form Components Guide](#form-components) - Form fields and validation
|
|
364
|
+
- [Layout Components Guide](#layout-components) - Dashboard and Auth layouts
|
|
365
|
+
- [Store Factory Guide](#store-factory) - Creating and customizing stores
|
|
366
|
+
|
|
367
|
+
</details>
|
|
368
|
+
|
|
369
|
+
<a id="ui-components"></a>
|
|
370
|
+
<details>
|
|
371
|
+
<summary><strong>2. UI Components Guide</strong></summary>
|
|
372
|
+
|
|
373
|
+
Complete reference for all UI components included in @bomjan133/react-crud-ui.
|
|
374
|
+
|
|
375
|
+
## Table of Contents
|
|
376
|
+
1. [Button](#button)
|
|
377
|
+
2. [Card](#card)
|
|
378
|
+
3. [Badge](#badge)
|
|
379
|
+
4. [Input & Label](#input--label)
|
|
380
|
+
5. [Select](#select)
|
|
381
|
+
6. [Checkbox & Switch](#checkbox--switch)
|
|
382
|
+
7. [Dialog](#dialog)
|
|
383
|
+
8. [Dropdown Menu](#dropdown-menu)
|
|
384
|
+
9. [Tabs](#tabs)
|
|
385
|
+
10. [Table](#table)
|
|
386
|
+
11. [Avatar](#avatar)
|
|
387
|
+
12. [Tooltip](#tooltip)
|
|
388
|
+
13. [Date Picker](#date-picker)
|
|
389
|
+
14. [Rich Text Editor](#rich-text-editor)
|
|
390
|
+
15. [Separator](#separator)
|
|
391
|
+
16. [Skeleton](#skeleton)
|
|
392
|
+
16. [Alert](#alert)
|
|
393
|
+
|
|
394
|
+
---
|
|
395
|
+
|
|
396
|
+
## Button
|
|
397
|
+
|
|
398
|
+
```jsx
|
|
399
|
+
import { Button, buttonVariants } from '@bomjan133/react-crud-ui';
|
|
400
|
+
|
|
401
|
+
// Variants
|
|
402
|
+
<Button>Default</Button>
|
|
403
|
+
<Button variant="secondary">Secondary</Button>
|
|
404
|
+
<Button variant="destructive">Destructive</Button>
|
|
405
|
+
<Button variant="outline">Outline</Button>
|
|
406
|
+
<Button variant="ghost">Ghost</Button>
|
|
407
|
+
<Button variant="link">Link</Button>
|
|
408
|
+
<Button variant="success">Success</Button>
|
|
409
|
+
|
|
410
|
+
// Sizes
|
|
411
|
+
<Button size="sm">Small</Button>
|
|
412
|
+
<Button size="default">Default</Button>
|
|
413
|
+
<Button size="lg">Large</Button>
|
|
414
|
+
<Button size="icon"><Icon /></Button>
|
|
415
|
+
|
|
416
|
+
// With icon
|
|
417
|
+
<Button>
|
|
418
|
+
<Plus className="h-4 w-4 mr-2" />
|
|
419
|
+
Add Item
|
|
420
|
+
</Button>
|
|
421
|
+
|
|
422
|
+
// Loading state
|
|
423
|
+
<Button disabled>
|
|
424
|
+
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
425
|
+
Loading...
|
|
426
|
+
</Button>
|
|
427
|
+
|
|
428
|
+
// As link using buttonVariants
|
|
429
|
+
<a href="/path" className={buttonVariants({ variant: "outline" })}>
|
|
430
|
+
Link Button
|
|
431
|
+
</a>
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
---
|
|
435
|
+
|
|
436
|
+
## Card
|
|
437
|
+
|
|
438
|
+
```jsx
|
|
439
|
+
import {
|
|
440
|
+
Card,
|
|
441
|
+
CardHeader,
|
|
442
|
+
CardTitle,
|
|
443
|
+
CardDescription,
|
|
444
|
+
CardContent,
|
|
445
|
+
CardFooter
|
|
446
|
+
} from '@bomjan133/react-crud-ui';
|
|
447
|
+
|
|
448
|
+
<Card>
|
|
449
|
+
<CardHeader>
|
|
450
|
+
<CardTitle>Card Title</CardTitle>
|
|
451
|
+
<CardDescription>Card description text</CardDescription>
|
|
452
|
+
</CardHeader>
|
|
453
|
+
<CardContent>
|
|
454
|
+
<p>Card content goes here</p>
|
|
455
|
+
</CardContent>
|
|
456
|
+
<CardFooter className="flex justify-end gap-2">
|
|
457
|
+
<Button variant="outline">Cancel</Button>
|
|
458
|
+
<Button>Save</Button>
|
|
459
|
+
</CardFooter>
|
|
460
|
+
</Card>
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
---
|
|
464
|
+
|
|
465
|
+
## Badge
|
|
466
|
+
|
|
467
|
+
```jsx
|
|
468
|
+
import { Badge, badgeVariants } from '@bomjan133/react-crud-ui';
|
|
469
|
+
|
|
470
|
+
// Variants
|
|
471
|
+
<Badge>Default</Badge>
|
|
472
|
+
<Badge variant="secondary">Secondary</Badge>
|
|
473
|
+
<Badge variant="destructive">Destructive</Badge>
|
|
474
|
+
<Badge variant="outline">Outline</Badge>
|
|
475
|
+
<Badge variant="success">Success</Badge>
|
|
476
|
+
<Badge variant="warning">Warning</Badge>
|
|
477
|
+
<Badge variant="info">Info</Badge>
|
|
478
|
+
|
|
479
|
+
// Status badges pattern
|
|
480
|
+
const StatusBadge = ({ status }) => {
|
|
481
|
+
const variants = {
|
|
482
|
+
active: 'success',
|
|
483
|
+
pending: 'warning',
|
|
484
|
+
inactive: 'secondary',
|
|
485
|
+
error: 'destructive',
|
|
486
|
+
};
|
|
487
|
+
return <Badge variant={variants[status]}>{status}</Badge>;
|
|
488
|
+
};
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
---
|
|
492
|
+
|
|
493
|
+
## Input & Label
|
|
494
|
+
|
|
495
|
+
```jsx
|
|
496
|
+
import { Input } from '@bomjan133/react-crud-ui';
|
|
497
|
+
import { Label } from '@bomjan133/react-crud-ui';
|
|
498
|
+
|
|
499
|
+
// Basic input
|
|
500
|
+
<div className="space-y-2">
|
|
501
|
+
<Label htmlFor="email">Email</Label>
|
|
502
|
+
<Input
|
|
503
|
+
id="email"
|
|
504
|
+
type="email"
|
|
505
|
+
placeholder="Enter email"
|
|
506
|
+
value={value}
|
|
507
|
+
onChange={(e) => setValue(e.target.value)}
|
|
508
|
+
/>
|
|
509
|
+
</div>
|
|
510
|
+
|
|
511
|
+
// With error
|
|
512
|
+
<div className="space-y-2">
|
|
513
|
+
<Label htmlFor="name">Name</Label>
|
|
514
|
+
<Input
|
|
515
|
+
id="name"
|
|
516
|
+
className="border-destructive"
|
|
517
|
+
value={value}
|
|
518
|
+
onChange={(e) => setValue(e.target.value)}
|
|
519
|
+
/>
|
|
520
|
+
<p className="text-sm text-destructive">Name is required</p>
|
|
521
|
+
</div>
|
|
522
|
+
|
|
523
|
+
// Disabled
|
|
524
|
+
<Input disabled placeholder="Disabled input" />
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
---
|
|
528
|
+
|
|
529
|
+
## Select
|
|
530
|
+
|
|
531
|
+
```jsx
|
|
532
|
+
import {
|
|
533
|
+
Select,
|
|
534
|
+
SelectGroup,
|
|
535
|
+
SelectValue,
|
|
536
|
+
SelectTrigger,
|
|
537
|
+
SelectContent,
|
|
538
|
+
SelectLabel,
|
|
539
|
+
SelectItem,
|
|
540
|
+
SelectSeparator,
|
|
541
|
+
} from '@bomjan133/react-crud-ui';
|
|
542
|
+
|
|
543
|
+
// Basic select
|
|
544
|
+
<Select value={value} onValueChange={setValue}>
|
|
545
|
+
<SelectTrigger className="w-[200px]">
|
|
546
|
+
<SelectValue placeholder="Select option" />
|
|
547
|
+
</SelectTrigger>
|
|
548
|
+
<SelectContent>
|
|
549
|
+
<SelectItem value="option1">Option 1</SelectItem>
|
|
550
|
+
<SelectItem value="option2">Option 2</SelectItem>
|
|
551
|
+
<SelectItem value="option3">Option 3</SelectItem>
|
|
552
|
+
</SelectContent>
|
|
553
|
+
</Select>
|
|
554
|
+
|
|
555
|
+
// With groups
|
|
556
|
+
<Select>
|
|
557
|
+
<SelectTrigger>
|
|
558
|
+
<SelectValue placeholder="Select fruit" />
|
|
559
|
+
</SelectTrigger>
|
|
560
|
+
<SelectContent>
|
|
561
|
+
<SelectGroup>
|
|
562
|
+
<SelectLabel>Fruits</SelectLabel>
|
|
563
|
+
<SelectItem value="apple">Apple</SelectItem>
|
|
564
|
+
<SelectItem value="banana">Banana</SelectItem>
|
|
565
|
+
</SelectGroup>
|
|
566
|
+
<SelectSeparator />
|
|
567
|
+
<SelectGroup>
|
|
568
|
+
<SelectLabel>Vegetables</SelectLabel>
|
|
569
|
+
<SelectItem value="carrot">Carrot</SelectItem>
|
|
570
|
+
<SelectItem value="potato">Potato</SelectItem>
|
|
571
|
+
</SelectGroup>
|
|
572
|
+
</SelectContent>
|
|
573
|
+
</Select>
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
---
|
|
577
|
+
|
|
578
|
+
## Checkbox & Switch
|
|
579
|
+
|
|
580
|
+
```jsx
|
|
581
|
+
import { Checkbox } from '@bomjan133/react-crud-ui';
|
|
582
|
+
import { Switch } from '@bomjan133/react-crud-ui';
|
|
583
|
+
import { Label } from '@bomjan133/react-crud-ui';
|
|
584
|
+
|
|
585
|
+
// Checkbox
|
|
586
|
+
<div className="flex items-center space-x-2">
|
|
587
|
+
<Checkbox
|
|
588
|
+
id="terms"
|
|
589
|
+
checked={checked}
|
|
590
|
+
onCheckedChange={setChecked}
|
|
591
|
+
/>
|
|
592
|
+
<Label htmlFor="terms">Accept terms and conditions</Label>
|
|
593
|
+
</div>
|
|
594
|
+
|
|
595
|
+
// Switch
|
|
596
|
+
<div className="flex items-center space-x-2">
|
|
597
|
+
<Switch
|
|
598
|
+
id="active"
|
|
599
|
+
checked={active}
|
|
600
|
+
onCheckedChange={setActive}
|
|
601
|
+
/>
|
|
602
|
+
<Label htmlFor="active">Active</Label>
|
|
603
|
+
</div>
|
|
604
|
+
|
|
605
|
+
// Switch with description
|
|
606
|
+
<div className="flex items-center justify-between rounded-lg border p-4">
|
|
607
|
+
<div className="space-y-0.5">
|
|
608
|
+
<Label>Marketing emails</Label>
|
|
609
|
+
<p className="text-sm text-muted-foreground">
|
|
610
|
+
Receive emails about new products
|
|
611
|
+
</p>
|
|
612
|
+
</div>
|
|
613
|
+
<Switch checked={marketing} onCheckedChange={setMarketing} />
|
|
614
|
+
</div>
|
|
615
|
+
```
|
|
616
|
+
|
|
617
|
+
---
|
|
618
|
+
|
|
619
|
+
## Dialog
|
|
620
|
+
|
|
621
|
+
```jsx
|
|
622
|
+
import {
|
|
623
|
+
Dialog,
|
|
624
|
+
DialogTrigger,
|
|
625
|
+
DialogContent,
|
|
626
|
+
DialogHeader,
|
|
627
|
+
DialogTitle,
|
|
628
|
+
DialogDescription,
|
|
629
|
+
DialogFooter,
|
|
630
|
+
DialogClose,
|
|
631
|
+
} from '@bomjan133/react-crud-ui';
|
|
632
|
+
|
|
633
|
+
<Dialog open={open} onOpenChange={setOpen}>
|
|
634
|
+
<DialogTrigger asChild>
|
|
635
|
+
<Button>Open Dialog</Button>
|
|
636
|
+
</DialogTrigger>
|
|
637
|
+
<DialogContent>
|
|
638
|
+
<DialogHeader>
|
|
639
|
+
<DialogTitle>Dialog Title</DialogTitle>
|
|
640
|
+
<DialogDescription>
|
|
641
|
+
This is the dialog description.
|
|
642
|
+
</DialogDescription>
|
|
643
|
+
</DialogHeader>
|
|
644
|
+
<div className="py-4">
|
|
645
|
+
{/* Dialog content */}
|
|
646
|
+
</div>
|
|
647
|
+
<DialogFooter>
|
|
648
|
+
<DialogClose asChild>
|
|
649
|
+
<Button variant="outline">Cancel</Button>
|
|
650
|
+
</DialogClose>
|
|
651
|
+
<Button onClick={handleSubmit}>Save</Button>
|
|
652
|
+
</DialogFooter>
|
|
653
|
+
</DialogContent>
|
|
654
|
+
</Dialog>
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
---
|
|
658
|
+
|
|
659
|
+
## Dropdown Menu
|
|
660
|
+
|
|
661
|
+
```jsx
|
|
662
|
+
import {
|
|
663
|
+
DropdownMenu,
|
|
664
|
+
DropdownMenuTrigger,
|
|
665
|
+
DropdownMenuContent,
|
|
666
|
+
DropdownMenuItem,
|
|
667
|
+
DropdownMenuLabel,
|
|
668
|
+
DropdownMenuSeparator,
|
|
669
|
+
DropdownMenuCheckboxItem,
|
|
670
|
+
DropdownMenuRadioGroup,
|
|
671
|
+
DropdownMenuRadioItem,
|
|
672
|
+
DropdownMenuSub,
|
|
673
|
+
DropdownMenuSubTrigger,
|
|
674
|
+
DropdownMenuSubContent,
|
|
675
|
+
} from '@bomjan133/react-crud-ui';
|
|
676
|
+
|
|
677
|
+
<DropdownMenu>
|
|
678
|
+
<DropdownMenuTrigger asChild>
|
|
679
|
+
<Button variant="ghost" size="icon">
|
|
680
|
+
<MoreHorizontal className="h-4 w-4" />
|
|
681
|
+
</Button>
|
|
682
|
+
</DropdownMenuTrigger>
|
|
683
|
+
<DropdownMenuContent align="end">
|
|
684
|
+
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
|
685
|
+
<DropdownMenuSeparator />
|
|
686
|
+
<DropdownMenuItem onClick={() => handleEdit(item)}>
|
|
687
|
+
<Edit className="h-4 w-4 mr-2" />
|
|
688
|
+
Edit
|
|
689
|
+
</DropdownMenuItem>
|
|
690
|
+
<DropdownMenuItem onClick={() => handleView(item)}>
|
|
691
|
+
<Eye className="h-4 w-4 mr-2" />
|
|
692
|
+
View
|
|
693
|
+
</DropdownMenuItem>
|
|
694
|
+
<DropdownMenuSeparator />
|
|
695
|
+
<DropdownMenuItem
|
|
696
|
+
onClick={() => handleDelete(item)}
|
|
697
|
+
className="text-destructive"
|
|
698
|
+
>
|
|
699
|
+
<Trash className="h-4 w-4 mr-2" />
|
|
700
|
+
Delete
|
|
701
|
+
</DropdownMenuItem>
|
|
702
|
+
</DropdownMenuContent>
|
|
703
|
+
</DropdownMenu>
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
---
|
|
707
|
+
|
|
708
|
+
## Tabs
|
|
709
|
+
|
|
710
|
+
```jsx
|
|
711
|
+
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@bomjan133/react-crud-ui';
|
|
712
|
+
import { QTabs } from '@bomjan133/react-crud-ui';
|
|
713
|
+
|
|
714
|
+
// Basic Tabs
|
|
715
|
+
<Tabs defaultValue="tab1">
|
|
716
|
+
<TabsList>
|
|
717
|
+
<TabsTrigger value="tab1">Tab 1</TabsTrigger>
|
|
718
|
+
<TabsTrigger value="tab2">Tab 2</TabsTrigger>
|
|
719
|
+
<TabsTrigger value="tab3">Tab 3</TabsTrigger>
|
|
720
|
+
</TabsList>
|
|
721
|
+
<TabsContent value="tab1">Content 1</TabsContent>
|
|
722
|
+
<TabsContent value="tab2">Content 2</TabsContent>
|
|
723
|
+
<TabsContent value="tab3">Content 3</TabsContent>
|
|
724
|
+
</Tabs>
|
|
725
|
+
|
|
726
|
+
// QTabs - Quick tabs with config
|
|
727
|
+
const tabs = [
|
|
728
|
+
{ value: 'overview', label: 'Overview', content: <Overview /> },
|
|
729
|
+
{ value: 'analytics', label: 'Analytics', content: <Analytics /> },
|
|
730
|
+
{ value: 'settings', label: 'Settings', content: <Settings /> },
|
|
731
|
+
];
|
|
732
|
+
|
|
733
|
+
<QTabs tabs={tabs} defaultValue="overview" />
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
---
|
|
737
|
+
|
|
738
|
+
## Table
|
|
739
|
+
|
|
740
|
+
```jsx
|
|
741
|
+
import {
|
|
742
|
+
Table,
|
|
743
|
+
TableHeader,
|
|
744
|
+
TableBody,
|
|
745
|
+
TableFooter,
|
|
746
|
+
TableHead,
|
|
747
|
+
TableRow,
|
|
748
|
+
TableCell,
|
|
749
|
+
TableCaption,
|
|
750
|
+
} from '@bomjan133/react-crud-ui';
|
|
751
|
+
|
|
752
|
+
<Table>
|
|
753
|
+
<TableCaption>A list of recent invoices.</TableCaption>
|
|
754
|
+
<TableHeader>
|
|
755
|
+
<TableRow>
|
|
756
|
+
<TableHead>Invoice</TableHead>
|
|
757
|
+
<TableHead>Status</TableHead>
|
|
758
|
+
<TableHead>Method</TableHead>
|
|
759
|
+
<TableHead className="text-right">Amount</TableHead>
|
|
760
|
+
</TableRow>
|
|
761
|
+
</TableHeader>
|
|
762
|
+
<TableBody>
|
|
763
|
+
{invoices.map((invoice) => (
|
|
764
|
+
<TableRow key={invoice.id}>
|
|
765
|
+
<TableCell className="font-medium">{invoice.id}</TableCell>
|
|
766
|
+
<TableCell>{invoice.status}</TableCell>
|
|
767
|
+
<TableCell>{invoice.method}</TableCell>
|
|
768
|
+
<TableCell className="text-right">{invoice.amount}</TableCell>
|
|
769
|
+
</TableRow>
|
|
770
|
+
))}
|
|
771
|
+
</TableBody>
|
|
772
|
+
<TableFooter>
|
|
773
|
+
<TableRow>
|
|
774
|
+
<TableCell colSpan={3}>Total</TableCell>
|
|
775
|
+
<TableCell className="text-right">$2,500.00</TableCell>
|
|
776
|
+
</TableRow>
|
|
777
|
+
</TableFooter>
|
|
778
|
+
</Table>
|
|
779
|
+
```
|
|
780
|
+
|
|
781
|
+
---
|
|
782
|
+
|
|
783
|
+
## Avatar
|
|
784
|
+
|
|
785
|
+
```jsx
|
|
786
|
+
import { Avatar, AvatarImage, AvatarFallback } from '@bomjan133/react-crud-ui';
|
|
787
|
+
|
|
788
|
+
<Avatar>
|
|
789
|
+
<AvatarImage src="/avatar.jpg" alt="User" />
|
|
790
|
+
<AvatarFallback>JD</AvatarFallback>
|
|
791
|
+
</Avatar>
|
|
792
|
+
|
|
793
|
+
// With size
|
|
794
|
+
<Avatar className="h-16 w-16">
|
|
795
|
+
<AvatarImage src="/avatar.jpg" alt="User" />
|
|
796
|
+
<AvatarFallback className="text-lg">JD</AvatarFallback>
|
|
797
|
+
</Avatar>
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
---
|
|
801
|
+
|
|
802
|
+
## Tooltip
|
|
803
|
+
|
|
804
|
+
```jsx
|
|
805
|
+
import {
|
|
806
|
+
Tooltip,
|
|
807
|
+
TooltipTrigger,
|
|
808
|
+
TooltipContent,
|
|
809
|
+
TooltipProvider
|
|
810
|
+
} from '@bomjan133/react-crud-ui';
|
|
811
|
+
|
|
812
|
+
// Wrap your app with TooltipProvider
|
|
813
|
+
<TooltipProvider>
|
|
814
|
+
<App />
|
|
815
|
+
</TooltipProvider>
|
|
816
|
+
|
|
817
|
+
// Usage
|
|
818
|
+
<Tooltip>
|
|
819
|
+
<TooltipTrigger asChild>
|
|
820
|
+
<Button variant="ghost" size="icon">
|
|
821
|
+
<Info className="h-4 w-4" />
|
|
822
|
+
</Button>
|
|
823
|
+
</TooltipTrigger>
|
|
824
|
+
<TooltipContent>
|
|
825
|
+
<p>This is helpful information</p>
|
|
826
|
+
</TooltipContent>
|
|
827
|
+
</Tooltip>
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
---
|
|
831
|
+
|
|
832
|
+
## Date Picker
|
|
833
|
+
|
|
834
|
+
```jsx
|
|
835
|
+
import { DatePicker, DateRangePicker } from '@bomjan133/react-crud-ui';
|
|
836
|
+
|
|
837
|
+
// Single date picker
|
|
838
|
+
const [date, setDate] = useState();
|
|
839
|
+
<DatePicker
|
|
840
|
+
date={date}
|
|
841
|
+
onDateChange={setDate}
|
|
842
|
+
placeholder="Pick a date"
|
|
843
|
+
/>
|
|
844
|
+
|
|
845
|
+
// Date range picker
|
|
846
|
+
const [dateRange, setDateRange] = useState();
|
|
847
|
+
<DateRangePicker
|
|
848
|
+
dateRange={dateRange}
|
|
849
|
+
onDateRangeChange={setDateRange}
|
|
850
|
+
placeholder="Pick a date range"
|
|
851
|
+
/>
|
|
852
|
+
```
|
|
853
|
+
|
|
854
|
+
---
|
|
855
|
+
|
|
856
|
+
## Rich Text Editor
|
|
857
|
+
|
|
858
|
+
```jsx
|
|
859
|
+
import { RichTextEditor } from '@bomjan133/react-crud-ui';
|
|
860
|
+
|
|
861
|
+
const [content, setContent] = useState('');
|
|
862
|
+
|
|
863
|
+
<RichTextEditor
|
|
864
|
+
value={content}
|
|
865
|
+
onChange={setContent}
|
|
866
|
+
placeholder="Start writing..."
|
|
867
|
+
height="300px"
|
|
868
|
+
/>
|
|
869
|
+
```
|
|
870
|
+
|
|
871
|
+
---
|
|
872
|
+
|
|
873
|
+
## Separator
|
|
874
|
+
|
|
875
|
+
```jsx
|
|
876
|
+
import { Separator } from '@bomjan133/react-crud-ui';
|
|
877
|
+
|
|
878
|
+
// Horizontal
|
|
879
|
+
<div>
|
|
880
|
+
<h2>Section 1</h2>
|
|
881
|
+
<Separator className="my-4" />
|
|
882
|
+
<h2>Section 2</h2>
|
|
883
|
+
</div>
|
|
884
|
+
|
|
885
|
+
// Vertical
|
|
886
|
+
<div className="flex h-5 items-center space-x-4">
|
|
887
|
+
<span>Item 1</span>
|
|
888
|
+
<Separator orientation="vertical" />
|
|
889
|
+
<span>Item 2</span>
|
|
890
|
+
<Separator orientation="vertical" />
|
|
891
|
+
<span>Item 3</span>
|
|
892
|
+
</div>
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
---
|
|
896
|
+
|
|
897
|
+
## Skeleton
|
|
898
|
+
|
|
899
|
+
```jsx
|
|
900
|
+
import { Skeleton } from '@bomjan133/react-crud-ui';
|
|
901
|
+
|
|
902
|
+
// Basic skeleton
|
|
903
|
+
<Skeleton className="h-4 w-[250px]" />
|
|
904
|
+
|
|
905
|
+
// Card skeleton
|
|
906
|
+
<div className="flex items-center space-x-4">
|
|
907
|
+
<Skeleton className="h-12 w-12 rounded-full" />
|
|
908
|
+
<div className="space-y-2">
|
|
909
|
+
<Skeleton className="h-4 w-[250px]" />
|
|
910
|
+
<Skeleton className="h-4 w-[200px]" />
|
|
911
|
+
</div>
|
|
912
|
+
</div>
|
|
913
|
+
|
|
914
|
+
// Table skeleton
|
|
915
|
+
<div className="space-y-2">
|
|
916
|
+
{[1, 2, 3, 4, 5].map((i) => (
|
|
917
|
+
<Skeleton key={i} className="h-10 w-full" />
|
|
918
|
+
))}
|
|
919
|
+
</div>
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
---
|
|
923
|
+
|
|
924
|
+
## Alert
|
|
925
|
+
|
|
926
|
+
```jsx
|
|
927
|
+
import {
|
|
928
|
+
Alert,
|
|
929
|
+
AlertTitle,
|
|
930
|
+
AlertDescription,
|
|
931
|
+
AlertWithIcon,
|
|
932
|
+
alertVariants
|
|
933
|
+
} from '@bomjan133/react-crud-ui';
|
|
934
|
+
|
|
935
|
+
// Basic alert
|
|
936
|
+
<Alert>
|
|
937
|
+
<AlertTitle>Heads up!</AlertTitle>
|
|
938
|
+
<AlertDescription>
|
|
939
|
+
You can add components to your app using the cli.
|
|
940
|
+
</AlertDescription>
|
|
941
|
+
</Alert>
|
|
942
|
+
|
|
943
|
+
// Destructive alert
|
|
944
|
+
<Alert variant="destructive">
|
|
945
|
+
<AlertTitle>Error</AlertTitle>
|
|
946
|
+
<AlertDescription>
|
|
947
|
+
Your session has expired. Please log in again.
|
|
948
|
+
</AlertDescription>
|
|
949
|
+
</Alert>
|
|
950
|
+
|
|
951
|
+
// With icon
|
|
952
|
+
<AlertWithIcon type="success" title="Success" message="Changes saved successfully" />
|
|
953
|
+
<AlertWithIcon type="error" title="Error" message="Something went wrong" />
|
|
954
|
+
<AlertWithIcon type="warning" title="Warning" message="This action cannot be undone" />
|
|
955
|
+
<AlertWithIcon type="info" title="Info" message="New features available" />
|
|
956
|
+
```
|
|
957
|
+
|
|
958
|
+
</details>
|
|
959
|
+
|
|
960
|
+
<a id="crud-components"></a>
|
|
961
|
+
<details>
|
|
962
|
+
<summary><strong>3. CRUD Components Guide</strong></summary>
|
|
963
|
+
|
|
964
|
+
Complete reference for CRUD components in @bomjan133/react-crud-ui.
|
|
965
|
+
|
|
966
|
+
## Table of Contents
|
|
967
|
+
1. [DataTable](#datatable)
|
|
968
|
+
2. [CrudList](#crudlist)
|
|
969
|
+
3. [CrudForm](#crudform)
|
|
970
|
+
4. [CrudDetail](#cruddetail)
|
|
971
|
+
5. [Pagination](#pagination)
|
|
972
|
+
6. [Loading Components](#loading-components)
|
|
973
|
+
7. [Empty States](#empty-states)
|
|
974
|
+
8. [Modal Components](#modal-components)
|
|
975
|
+
|
|
976
|
+
---
|
|
977
|
+
|
|
978
|
+
## DataTable
|
|
979
|
+
|
|
980
|
+
A data table with sorting, pagination, search, row selection, clickable "link" columns, and a per-row dropdown actions menu.
|
|
981
|
+
|
|
982
|
+
### Props
|
|
983
|
+
|
|
984
|
+
| Prop | Type | Default | Description |
|
|
985
|
+
|------|------|---------|--------------|
|
|
986
|
+
| `data` | `array` | `[]` | Rows to display (current page only — this component does not paginate client-side). |
|
|
987
|
+
| `columns` | `array` | `[]` | Column definitions. See Column Definition below. |
|
|
988
|
+
| `loading` | `boolean` | `false` | Shows a full-width `Loading` row instead of the data rows. |
|
|
989
|
+
| `error` | `any` | `null` | Accepted but currently unused — nothing in the component reads or renders this value. |
|
|
990
|
+
| `pagination` | `boolean` | `null` | Only meaningful when set to `false`, which hides the pagination footer entirely. Any other value (including the default `null`) shows it. Pagination is otherwise driven by the flat props below — it is **not** an object with `{ page, totalPages, total }`. |
|
|
991
|
+
| `currentPage` | `number` | `1` | Current page (1-indexed). Used to compute serial numbers and passed through to the internal `Pagination` component. |
|
|
992
|
+
| `pageSize` | `number` | `15` | Items per page. Used to compute serial numbers and passed to `Pagination`. |
|
|
993
|
+
| `totalItems` | `number` | `0` | Total item count, passed to `Pagination`. |
|
|
994
|
+
| `totalPages` | `number` | `1` | Total page count, passed to `Pagination`. |
|
|
995
|
+
| `onPageChange` | `function` | - | Passed to `Pagination`; called with the new page. |
|
|
996
|
+
| `onPageSizeChange` | `function` | - | Passed to `Pagination`; called when the page size changes. |
|
|
997
|
+
| `sortable` | `boolean` | `true` | Global switch for sorting. A column must also set `sortable: true` to become sortable. |
|
|
998
|
+
| `sortColumn` | `string` | `null` | The field currently sorted on (compared against each column's `sortKey`/`accessor`/`key`). |
|
|
999
|
+
| `sortDirection` | `'asc' \| 'desc' \| null` | `null` | Current sort direction. |
|
|
1000
|
+
| `onSort` | `function` | - | Called as `onSort(field, direction)` when a sortable header is clicked. Clicking cycles asc → desc → none; on the third click it's called as `onSort(null, null)`. |
|
|
1001
|
+
| `openInNewTab` | `boolean` | `false` | When a column renders as a link (via `onViewLink`), opens it in a new tab (`target="_blank"`) instead of the same tab. |
|
|
1002
|
+
| `searchable` | `boolean` | `true` | Shows/hides the search input in the toolbar. |
|
|
1003
|
+
| `searchValue` | `string` | `''` | **Initial value only** — seeds the component's internal search state on mount. The input is managed internally after that; changing this prop later does not reset the input. |
|
|
1004
|
+
| `onSearchChange` | `function` | - | Called with the search string, debounced 300ms after the user stops typing (fixed delay, not configurable). |
|
|
1005
|
+
| `searchPlaceholder` | `string` | `'Search...'` | Placeholder text for the search input. |
|
|
1006
|
+
| `filters` | `node` | - | Extra filter control(s) rendered next to the search box. Accepts a single element or an array/fragment of elements; each is wrapped in a `w-[200px]` container. |
|
|
1007
|
+
| `toolbarActions` | `node` | - | Content rendered on the right side of the toolbar (e.g. an "Add" button). |
|
|
1008
|
+
| `selectable` | `boolean` | `false` | Shows a checkbox column for row selection. |
|
|
1009
|
+
| `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). |
|
|
1010
|
+
| `onSelectionChange` | `function` | - | Called with the new array of selected row keys, on both row and select-all/clear actions. |
|
|
1011
|
+
| `actions` | `array` | `[]` | Row-level dropdown menu actions. There is no `onEdit`/`onDelete`/`onView`/`showActions` prop on `DataTable` itself — a single `actions` array drives the whole menu. See Actions Column below. |
|
|
1012
|
+
| `onRowClick` | `function` | - | Called with the row object when a row is clicked (ignored if the click originates from the checkbox or actions cells, which stop propagation). |
|
|
1013
|
+
| `striped` | `boolean` | `false` | Applies a light background to odd rows. |
|
|
1014
|
+
| `hover` | `boolean` | `true` | Gates two visual behaviors: shows a pointer cursor on rows when `onRowClick` is set, and (when `onRowClick` is *not* set) highlights selected rows with a tinted background. It does not add a generic hover background by itself. |
|
|
1015
|
+
| `compact` | `boolean` | `false` | Reduces cell vertical padding. |
|
|
1016
|
+
| `className` | `string` | - | Class for the outer wrapping `<div>`. |
|
|
1017
|
+
| `emptyTitle` | `string` | `'No data found'` | Empty-state title. |
|
|
1018
|
+
| `emptyDescription` | `string` | `'There are no items to display.'` | Empty-state description text. |
|
|
1019
|
+
| `emptyAction` | `string` | - | Label for an optional empty-state action button. |
|
|
1020
|
+
| `onEmptyAction` | `function` | - | Handler for the empty-state action button. |
|
|
1021
|
+
| `getRowKey` | `function` | `(row) => row.id \|\| row._id` | Derives a unique key per row; used for React keys and selection tracking. |
|
|
1022
|
+
| `showSerialNumber` | `boolean` | `true` | Shows a leading row-number column. |
|
|
1023
|
+
| `serialNumberHeader` | `string` | `'SN'` | Header label for the serial number column. |
|
|
1024
|
+
| `onViewClick` | `function` | - | If set, "clickable" columns (see `clickableColumns`) render their value as a button; clicking it calls `onViewClick(row)`. |
|
|
1025
|
+
| `onViewLink` | `function` | - | If set, "clickable" columns render their value as an `<a>`; called as `onViewLink(row)` to compute the `href`. Takes precedence over `onViewClick`. |
|
|
1026
|
+
| `onBeforeNavigate` | `function` | - | Only used when `onViewLink` is set and `openInNewTab` is `false`. If provided, clicking the link is intercepted (`preventDefault`/`stopPropagation`) and `onBeforeNavigate(href)` is called instead of navigating. |
|
|
1027
|
+
| `clickableColumns` | `array` | `[]` | List of column `accessor`/`key` strings that should render as links/buttons. Pass `['*']` to make every column clickable. If left empty, only columns whose accessor/key is `"name"` or `"title"` are clickable by default. |
|
|
1028
|
+
| `enableTextClamping` | `boolean` | `true` | Truncates long string cell values (30+ characters) with an ellipsis and shows the full text in a tooltip on hover. |
|
|
1029
|
+
| `defaultMaxLines` | `number` | `1` | Default number of lines before clamping; overridable per-column via `column.maxLines`. |
|
|
1030
|
+
| `tableClassName` | `string` | - | Class passed to the root `<Table>`. |
|
|
1031
|
+
| `tableHeaderClassName` | `string` | - | Class passed to `<TableHeader>`. |
|
|
1032
|
+
| `tableBodyClassName` | `string` | - | Class passed to `<TableBody>`. |
|
|
1033
|
+
| `tableRowClassName` | `string` | - | Class merged onto every data/status `<TableRow>`. |
|
|
1034
|
+
| `tableHeadClassName` | `string` | - | Class merged onto every `<TableHead>` cell (selection, SN, data, and actions headers). |
|
|
1035
|
+
| `tableCellClassName` | `string` | - | Class merged onto every `<TableCell>` (selection, SN, data, actions, and loading/empty cells). |
|
|
1036
|
+
| `headerRowClassName` | `string` | - | Class merged onto the header `<TableRow>`. |
|
|
1037
|
+
| `statusRowClassName` | `string` | - | Class merged onto the loading/empty-state `<TableRow>`. |
|
|
1038
|
+
| `paginationClassName` | `string` | - | Class passed to the `Pagination` component. |
|
|
1039
|
+
|
|
1040
|
+
> **Not implemented:** `onEdit`, `onDelete`, `onView`, `showActions`, and `emptyMessage` do not exist on `DataTable` — they were fabricated in an earlier version of this doc. Use `actions` (below) and `emptyTitle`/`emptyDescription` instead.
|
|
1041
|
+
|
|
1042
|
+
### Column Definition
|
|
1043
|
+
|
|
1044
|
+
```js
|
|
1045
|
+
const columns = [
|
|
1046
|
+
{
|
|
1047
|
+
// Value extraction — accessor wins over key
|
|
1048
|
+
accessor: 'name', // string, OR a function: (row) => value
|
|
1049
|
+
key: 'name', // fallback for accessor; also used as React key/sort field if accessor is absent
|
|
1050
|
+
|
|
1051
|
+
// Header text — header wins over label
|
|
1052
|
+
header: 'Name',
|
|
1053
|
+
label: 'Name', // fallback if header is not set
|
|
1054
|
+
|
|
1055
|
+
sortable: true, // enables sorting for this column (requires top-level sortable !== false)
|
|
1056
|
+
sortKey: 'name', // optional override of the field name used for sort comparisons/onSort
|
|
1057
|
+
|
|
1058
|
+
render: (value, row, index) => (
|
|
1059
|
+
<span className="font-medium">{value}</span>
|
|
1060
|
+
), // custom cell renderer, highest precedence
|
|
1061
|
+
format: (value, row) => value, // used only if render is not provided
|
|
1062
|
+
|
|
1063
|
+
width: 200, // inline style: width
|
|
1064
|
+
minWidth: 120, // inline style: minWidth
|
|
1065
|
+
maxWidth: 300, // inline style: maxWidth (cells default to '300px' if unset)
|
|
1066
|
+
|
|
1067
|
+
headerClassName: '', // extra className on the <TableHead>
|
|
1068
|
+
cellClassName: '', // extra className on the <TableCell>
|
|
1069
|
+
|
|
1070
|
+
disableClamping: false, // opt this column out of enableTextClamping
|
|
1071
|
+
maxLines: 1, // per-column override of defaultMaxLines
|
|
1072
|
+
},
|
|
1073
|
+
];
|
|
1074
|
+
```
|
|
1075
|
+
|
|
1076
|
+
> A column-level `className` field does not exist — the real per-column style hooks are `headerClassName` and `cellClassName`.
|
|
1077
|
+
|
|
1078
|
+
### Actions Column
|
|
1079
|
+
|
|
1080
|
+
Passing a non-empty `actions` array is what causes the Actions column (header cell + per-row dropdown trigger) to render — there is no separate `showActions` toggle.
|
|
1081
|
+
|
|
1082
|
+
```js
|
|
1083
|
+
const actions = [
|
|
1084
|
+
{
|
|
1085
|
+
label: 'Edit',
|
|
1086
|
+
icon: PencilIcon, // optional component, rendered at 16px with right margin
|
|
1087
|
+
onClick: (row) => handleEdit(row),
|
|
1088
|
+
disabled: false, // optional
|
|
1089
|
+
},
|
|
1090
|
+
{
|
|
1091
|
+
label: 'Delete',
|
|
1092
|
+
icon: TrashIcon,
|
|
1093
|
+
variant: 'destructive', // only 'destructive' has special styling (red text)
|
|
1094
|
+
onClick: (row) => handleDelete(row),
|
|
1095
|
+
hidden: (row) => row.locked, // boolean, or a function(row) => boolean
|
|
1096
|
+
},
|
|
1097
|
+
];
|
|
1098
|
+
```
|
|
1099
|
+
|
|
1100
|
+
- Items render in a `DropdownMenu` opened by an icon-only ghost button, in the same order as the `actions` array.
|
|
1101
|
+
- Per row, an action is filtered out of the menu if `hidden` is `true`, or if `hidden` is a function returning `true` for that row.
|
|
1102
|
+
- `disabled` maps directly to the underlying menu item's disabled state.
|
|
1103
|
+
- Clicking a row's actions cell does not trigger `onRowClick` (click propagation is stopped).
|
|
1104
|
+
|
|
1105
|
+
### Usage
|
|
1106
|
+
|
|
1107
|
+
```jsx
|
|
1108
|
+
import { DataTable } from '@bomjan133/react-crud-ui';
|
|
1109
|
+
import { PencilIcon, TrashIcon } from 'lucide-react';
|
|
1110
|
+
|
|
1111
|
+
<DataTable
|
|
1112
|
+
data={users}
|
|
1113
|
+
columns={[
|
|
1114
|
+
{ key: 'name', label: 'Name', sortable: true },
|
|
1115
|
+
{ key: 'email', label: 'Email' },
|
|
1116
|
+
{
|
|
1117
|
+
key: 'status',
|
|
1118
|
+
label: 'Status',
|
|
1119
|
+
render: (value) => <Badge>{value}</Badge>,
|
|
1120
|
+
},
|
|
1121
|
+
]}
|
|
1122
|
+
loading={isLoading}
|
|
1123
|
+
searchValue={search}
|
|
1124
|
+
onSearchChange={setSearch}
|
|
1125
|
+
currentPage={page}
|
|
1126
|
+
pageSize={15}
|
|
1127
|
+
totalItems={total}
|
|
1128
|
+
totalPages={Math.ceil(total / 15)}
|
|
1129
|
+
onPageChange={setPage}
|
|
1130
|
+
sortColumn={sortColumn}
|
|
1131
|
+
sortDirection={sortDirection}
|
|
1132
|
+
onSort={(field, direction) => {
|
|
1133
|
+
setSortColumn(field);
|
|
1134
|
+
setSortDirection(direction);
|
|
1135
|
+
}}
|
|
1136
|
+
actions={[
|
|
1137
|
+
{ label: 'Edit', icon: PencilIcon, onClick: (row) => openEdit(row) },
|
|
1138
|
+
{
|
|
1139
|
+
label: 'Delete',
|
|
1140
|
+
icon: TrashIcon,
|
|
1141
|
+
variant: 'destructive',
|
|
1142
|
+
onClick: (row) => openDelete(row),
|
|
1143
|
+
},
|
|
1144
|
+
]}
|
|
1145
|
+
emptyTitle="No users found"
|
|
1146
|
+
emptyDescription="Try adjusting your search or add a new user."
|
|
1147
|
+
/>
|
|
1148
|
+
|
|
1149
|
+
// Selectable rows with a clickable "name" column linking to a detail page
|
|
1150
|
+
<DataTable
|
|
1151
|
+
data={orders}
|
|
1152
|
+
columns={[{ key: 'name', label: 'Order' }, { key: 'amount', label: 'Amount' }]}
|
|
1153
|
+
selectable
|
|
1154
|
+
selectedRows={selectedIds}
|
|
1155
|
+
onSelectionChange={setSelectedIds}
|
|
1156
|
+
onViewLink={(row) => `/orders/${row.id}`}
|
|
1157
|
+
clickableColumns={['name']}
|
|
1158
|
+
getRowKey={(row) => row.id}
|
|
1159
|
+
/>
|
|
1160
|
+
```
|
|
1161
|
+
|
|
1162
|
+
---
|
|
1163
|
+
|
|
1164
|
+
## CrudList
|
|
1165
|
+
|
|
1166
|
+
A complete list view component that combines `DataTable` with a header, toolbar (search/create/refresh/export/bulk actions), pagination, row actions (view/edit/delete + custom), and a delete-confirmation modal. It can source its data either from a store object or from direct props — each store capability (`items`, `loading`, `error`, `pagination`, `fetchList`, `delete`, `setPage`, `setPageSize`, `setFilters`, sorting) is read independently via optional chaining and falls back to the matching direct prop if the store doesn't provide it.
|
|
1167
|
+
|
|
1168
|
+
### Store integration (preferred)
|
|
1169
|
+
|
|
1170
|
+
| Prop | Type | Default | Description |
|
|
1171
|
+
|------|------|---------|--------------|
|
|
1172
|
+
| `store` | `object` | - | A store instance (e.g. a Zustand store). Recognized shape: `store.items` (array), `store.loading` (bool), `store.error`, `store.pagination` (`{ page, pageSize, total, totalPages }`), `store.fetchList()`, `store.delete(id)`, `store.setPage(page)`, `store.setPageSize(size)`, `store.setFilters({ search })`, `store.sortColumn`, `store.sortDirection`, `store.setSort(column, direction)`. None of these are required — missing pieces fall back to the direct props below. |
|
|
1173
|
+
|
|
1174
|
+
> **Note if you're using this package's own [`createCrudStore`](#store-factory):** its pagination fields are flat (`page`/`pageSize`/`totalItems`/`totalPages`), not a nested `pagination` object. Since `CrudList` specifically reads `store.pagination`, a plain `createCrudStore` instance won't provide it and pagination will appear stuck — bridge it yourself, e.g. `store={{ ...store, pagination: { page: store.page, pageSize: store.pageSize, total: store.totalItems, totalPages: store.totalPages } }}`. See [Store Factory → Compatibility](#compatibility-with-crudlist--crudform--cruddetail) for the full compatibility matrix (this also applies to `CrudDetail`'s `currentItem` vs. `item`, and `CrudForm`'s store mode).
|
|
1175
|
+
|
|
1176
|
+
### Direct data props (used if store not provided)
|
|
1177
|
+
|
|
1178
|
+
| Prop | Type | Default | Description |
|
|
1179
|
+
|------|------|---------|--------------|
|
|
1180
|
+
| `data` | `array` | - | Row data. Used when `store?.items` is nullish. |
|
|
1181
|
+
| `loading` | `boolean` | `false` | Loading state, used when `store?.loading` is nullish. |
|
|
1182
|
+
| `error` | `any` | `null` | Error state, used when `store?.error` is nullish. |
|
|
1183
|
+
| `skipInitialFetch` | `boolean` | `false` | When a store is provided, skips the automatic call to `store.fetchList()` on mount. |
|
|
1184
|
+
|
|
1185
|
+
### Columns configuration
|
|
1186
|
+
|
|
1187
|
+
| Prop | Type | Default | Description |
|
|
1188
|
+
|------|------|---------|--------------|
|
|
1189
|
+
| `columns` | `array` | `[]` | Column definitions, forwarded to the internal `DataTable` — see [DataTable's Column Definition](#column-definition) for the full field list (`accessor`/`key`, `header`/`label`, `sortable`, `sortKey`, `render`, `format`, width fields, `headerClassName`/`cellClassName`, clamping options). |
|
|
1190
|
+
|
|
1191
|
+
### Pagination (direct-prop mode)
|
|
1192
|
+
|
|
1193
|
+
| Prop | Type | Default | Description |
|
|
1194
|
+
|------|------|---------|--------------|
|
|
1195
|
+
| `currentPage` | `number` | `1` | Current page, used when no `store.pagination` value is available. |
|
|
1196
|
+
| `pageSize` | `number` | `15` | Page size fallback. |
|
|
1197
|
+
| `totalItems` | `number` | `0` | Total item count fallback. |
|
|
1198
|
+
| `totalPages` | `number` | `1` | Total page count fallback. |
|
|
1199
|
+
| `onPageChange` | `function(page)` | - | Called when the store has no `setPage` method. |
|
|
1200
|
+
| `onPageSizeChange` | `function(size)` | - | Called when the store has no `setPageSize` method. |
|
|
1201
|
+
|
|
1202
|
+
> There is no `showPagination` prop. `CrudList` never passes a `pagination` prop through to `DataTable`, and `DataTable` renders its pagination footer whenever there is data — so pagination is always shown once you have data.
|
|
1203
|
+
|
|
1204
|
+
### Sorting
|
|
1205
|
+
|
|
1206
|
+
| Prop | Type | Default | Description |
|
|
1207
|
+
|------|------|---------|--------------|
|
|
1208
|
+
| `sortColumn` | `string` | - | Current sort column, used when the store doesn't expose `sortColumn`. |
|
|
1209
|
+
| `sortDirection` | `'asc' \| 'desc' \| null` | - | Current sort direction fallback. |
|
|
1210
|
+
| `onSort` | `function(column, direction)` | - | Called on sort-header click when no `store` is present. When a `store` **is** present, sort clicks instead call `store.setSort(column, direction)` followed by `store.fetchList()`, regardless of whether `onSort` is also passed. |
|
|
1211
|
+
|
|
1212
|
+
### Search
|
|
1213
|
+
|
|
1214
|
+
| Prop | Type | Default | Description |
|
|
1215
|
+
|------|------|---------|--------------|
|
|
1216
|
+
| `searchValue` | `string` | `""` | Controlled search text, used only when the store has no `setFilters` method. |
|
|
1217
|
+
| `onSearchChange` | `function(value)` | - | Called on search input change when the store has no `setFilters` method. |
|
|
1218
|
+
| `searchPlaceholder` | `string` | `"Search..."` | Placeholder text for the search input. |
|
|
1219
|
+
| `searchable` | `boolean` | `true` | Whether the search input (and debounced store search) is enabled. This is the real prop for what an earlier version of this doc called `showSearch`, which does not exist. |
|
|
1220
|
+
| `openInNewTab` | `boolean` | `false` | When true, clickable-column/view links open via `window.open(..., "_blank")` instead of SPA navigation, and scroll-position save/restore is skipped. |
|
|
1221
|
+
|
|
1222
|
+
When a store with `setFilters` is present, typing in the search box updates internal state, and after a 300ms debounce calls `store.setFilters({ search })`, resets to page 1, then calls `store.fetchList()`.
|
|
1223
|
+
|
|
1224
|
+
### Selection
|
|
1225
|
+
|
|
1226
|
+
| Prop | Type | Default | Description |
|
|
1227
|
+
|------|------|---------|--------------|
|
|
1228
|
+
| `selectable` | `boolean` | `false` | Enables row checkboxes and the "select all" header checkbox. |
|
|
1229
|
+
| `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). Controlled — the component does not manage this internally. |
|
|
1230
|
+
| `onSelectionChange` | `function(newSelectedRowKeys: array)` | - | Called with the full updated array whenever a row or "select all" checkbox changes. |
|
|
1231
|
+
|
|
1232
|
+
### CRUD Actions (direct-prop mode, used if paths not provided)
|
|
1233
|
+
|
|
1234
|
+
| Prop | Type | Default | Description |
|
|
1235
|
+
|------|------|---------|--------------|
|
|
1236
|
+
| `onCreate` | `function()` | - | Called by the Create button when `createPath` is not set. |
|
|
1237
|
+
| `onView` | `function(row)` | - | Called by the row "View" action when `detailPath` is not set. |
|
|
1238
|
+
| `onEdit` | `function(row)` | - | Called by the row "Edit" action when `editPath` is not set. |
|
|
1239
|
+
| `onDelete` | `function(row): Promise` | - | Called on delete confirmation when the store has no `delete` method. Awaited; success shows a toast, thrown errors show an error toast. |
|
|
1240
|
+
| `onRefresh` | `function()` | - | Called by the Refresh button when the store has no `fetchList` method. |
|
|
1241
|
+
| `onExport` | `function() \| React element` | - | If a valid React element, it is rendered as-is in the toolbar. If a function, a default "Export" button is rendered that calls it on click. |
|
|
1242
|
+
|
|
1243
|
+
### Table & button styling overrides
|
|
1244
|
+
|
|
1245
|
+
Purely presentational, forwarded straight through to `DataTable`/toolbar buttons:
|
|
1246
|
+
|
|
1247
|
+
| Prop | Type | Description |
|
|
1248
|
+
|------|------|-------------|
|
|
1249
|
+
| `tableClassName` | `string` | Class on the `<Table>` element. |
|
|
1250
|
+
| `tableHeaderClassName` | `string` | Class on `<TableHeader>`. |
|
|
1251
|
+
| `tableBodyClassName` | `string` | Class on `<TableBody>`. |
|
|
1252
|
+
| `tableRowClassName` | `string` | Class on each `<TableRow>` (data + status rows). |
|
|
1253
|
+
| `tableHeadClassName` | `string` | Class on each `<TableHead>` cell. |
|
|
1254
|
+
| `tableCellClassName` | `string` | Class on each `<TableCell>`. |
|
|
1255
|
+
| `headerRowClassName` | `string` | Class on the header `<TableRow>`. |
|
|
1256
|
+
| `statusRowClassName` | `string` | Class on the loading/empty status row. |
|
|
1257
|
+
| `paginationClassName` | `string` | Class passed to the `Pagination` component. |
|
|
1258
|
+
| `createButtonClassName` | `string` | Class on the Create button. |
|
|
1259
|
+
| `refreshButtonClassName` | `string` | Class on the Refresh button. |
|
|
1260
|
+
| `exportButtonClassName` | `string` | Class on the default Export button. |
|
|
1261
|
+
| `bulkActionButtonClassName` | `string` | Class applied to every bulk-action button. |
|
|
1262
|
+
|
|
1263
|
+
### Navigation paths
|
|
1264
|
+
|
|
1265
|
+
| Prop | Type | Default | Description |
|
|
1266
|
+
|------|------|---------|--------------|
|
|
1267
|
+
| `createPath` | `string` | - | If set, the Create button navigates here (via `react-router`'s `navigate`) instead of calling `onCreate`. Used as-is — no suffix appended. |
|
|
1268
|
+
| `detailPath` | `string` | - | If set, the row "View" action and clickable-name columns navigate to `` `${detailPath}/${getRowKey(row)}` `` instead of calling `onView`. |
|
|
1269
|
+
| `editPath` | `string` | - | If set, the row "Edit" action navigates to `` `${editPath}/${getRowKey(row)}/edit` `` instead of calling `onEdit`. |
|
|
1270
|
+
|
|
1271
|
+
> **Correction:** there is no `viewPath` prop — the real prop is `detailPath`. An earlier version of this doc used `viewPath`, which has no effect.
|
|
1272
|
+
|
|
1273
|
+
### Breadcrumb helper
|
|
1274
|
+
|
|
1275
|
+
| Prop | Type | Default | Description |
|
|
1276
|
+
|------|------|---------|--------------|
|
|
1277
|
+
| `getBreadcrumbName` | `function(row)` | - | Returns a display name passed as `location.state.breadcrumbName` when navigating to the detail page. |
|
|
1278
|
+
| `customBreadcrumbPaths` | `object` | - | Static breadcrumb path map passed as `location.state.customBreadcrumbPaths` on create/view/edit navigation, unless `getCustomBreadcrumbPath` is given. |
|
|
1279
|
+
| `getCustomBreadcrumbPath` | `function(row)` | - | Per-row/per-action function that computes breadcrumb paths, overriding `customBreadcrumbPaths` when provided. |
|
|
1280
|
+
| `getParentPath` | `function(row)` | - | Returns a parent path string; used to build `{ [firstPathSegment]: parentPath }` (passed as `location.state.parentPath`) when neither `customBreadcrumbPaths` nor `getCustomBreadcrumbPath` produced a result. |
|
|
1281
|
+
| `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state object passed to create/view/edit navigations. |
|
|
1282
|
+
|
|
1283
|
+
### Custom actions
|
|
1284
|
+
|
|
1285
|
+
| Prop | Type | Default | Description |
|
|
1286
|
+
|------|------|---------|--------------|
|
|
1287
|
+
| `additionalActions` | `array` | `[]` | Extra per-row dropdown actions, inserted between the built-in Edit and Delete actions. Each item: `{ label, icon?: Component, onClick(row), variant?: 'destructive', disabled?: boolean, hidden?: boolean \| (row) => boolean }`. |
|
|
1288
|
+
| `bulkActions` | `array` | `[]` | Toolbar buttons shown only when `selectable` is true and at least one row is selected. Each item: `{ label, icon?: Component, variant?: string (default "outline"), onClick(selectedRowKeys), disabled?: boolean, className?: string }`. |
|
|
1289
|
+
|
|
1290
|
+
### Labels
|
|
1291
|
+
|
|
1292
|
+
| Prop | Type | Default | Description |
|
|
1293
|
+
|------|------|---------|--------------|
|
|
1294
|
+
| `title` | `string` | - | Card title text. Also used verbatim in the delete-success toast: `` `${title} Deleted successfully` `` (note: uses `title`, not `itemName`). |
|
|
1295
|
+
| `description` | `string` | - | Card description text. |
|
|
1296
|
+
| `createLabel` | `string` | `"Create"` | Create button label. |
|
|
1297
|
+
| `refreshLabel` | `string` | `"Refresh"` | Refresh button label. |
|
|
1298
|
+
| `exportLabel` | `string` | `"Export"` | Default Export button label. |
|
|
1299
|
+
| `viewLabel` | `string` | `"View"` | Row "View" action label. |
|
|
1300
|
+
| `editLabel` | `string` | `"Edit"` | Row "Edit" action label. |
|
|
1301
|
+
| `deleteLabel` | `string` | `"Delete"` | Row "Delete" action label. |
|
|
1302
|
+
| `itemName` | `string` | `"item"` | Used in the default delete-confirmation title/description and the empty-state text (`` `No ${itemName}s found` ``, `` `Create your first ${itemName} to get started.` ``). |
|
|
1303
|
+
|
|
1304
|
+
### Row key
|
|
1305
|
+
|
|
1306
|
+
| Prop | Type | Default | Description |
|
|
1307
|
+
|------|------|---------|--------------|
|
|
1308
|
+
| `getRowKey` | `function(row)` | `(row) => row.uuid \|\| row.id \|\| row._id` | Derives a unique key/id for each row; used for selection, navigation URLs, delete calls, and React keys. |
|
|
1309
|
+
|
|
1310
|
+
### Appearance
|
|
1311
|
+
|
|
1312
|
+
| Prop | Type | Default | Description |
|
|
1313
|
+
|------|------|---------|--------------|
|
|
1314
|
+
| `showHeader` | `boolean` | `true` | Whether to wrap content in a `Card` with a header (title/description/toolbar). If false (or no title/description), content renders in a plain `<div>`. |
|
|
1315
|
+
| `showToolbar` | `boolean` | `true` | Whether to render the toolbar (header actions, bulk actions, export, refresh, create) — independent of `showHeader`. |
|
|
1316
|
+
| `compact` | `boolean` | `false` | Passed to `DataTable` to tighten row padding. |
|
|
1317
|
+
| `className` | `string` | - | Class on the outer `Card`/`div` wrapper. |
|
|
1318
|
+
| `filters` | `node` | - | Custom filter control(s) rendered in the `DataTable` toolbar next to the search box. |
|
|
1319
|
+
| `headerActions` | `node` | - | Arbitrary content rendered at the start of the toolbar, before bulk actions/export/refresh/create. **This is the real "custom header actions" slot** — `children` is not read anywhere in `CrudList` and has no effect. |
|
|
1320
|
+
| `showEditButton` | `boolean` | `true` | Hides the built-in row "Edit" action when `false`, even if `editPath`/`onEdit` is set. |
|
|
1321
|
+
| `showDeleteButton` | `boolean` | `true` | Hides the built-in row "Delete" action when `false`, even if delete is otherwise available. |
|
|
1322
|
+
| `clickableColumns` | `array` | `[]` | Accessor keys that should render as clickable links/buttons to the detail view. Pass `["*"]` for all columns. Forwarded to `DataTable`. |
|
|
1323
|
+
|
|
1324
|
+
> **Correction:** `icon` (a title icon) and `children` (custom header actions) do not exist on `CrudList` — both were fabricated in an earlier version of this doc. Use `headerActions` for custom toolbar content.
|
|
1325
|
+
|
|
1326
|
+
### Delete confirmation
|
|
1327
|
+
|
|
1328
|
+
| Prop | Type | Default | Description |
|
|
1329
|
+
|------|------|---------|--------------|
|
|
1330
|
+
| `deleteConfirmTitle` | `string` | - | Overrides the delete modal's title (default: `` `Delete ${itemName}` ``). |
|
|
1331
|
+
| `deleteConfirmDescription` | `string` | - | Overrides the modal's description (default asks to confirm deleting the resolved item name). |
|
|
1332
|
+
| `getDeleteItemName` | `function(item)` | - | Returns the display name for the item being deleted (HTML-stripped and truncated to 80 chars internally); falls back to `item.name \|\| item.title \|\| itemName`. |
|
|
1333
|
+
|
|
1334
|
+
> There is no `onDeleteSuccess` callback — delete success always shows a hardcoded toast using `title` (see Labels above).
|
|
1335
|
+
|
|
1336
|
+
### Usage
|
|
1337
|
+
|
|
1338
|
+
**Basic (store-based):**
|
|
1339
|
+
|
|
1340
|
+
```jsx
|
|
1341
|
+
import { CrudList } from '@bomjan133/react-crud-ui';
|
|
1342
|
+
import { useUserStore } from './stores/useUserStore';
|
|
1343
|
+
|
|
1344
|
+
const columns = [
|
|
1345
|
+
{ accessor: 'name', header: 'Name', sortable: true },
|
|
1346
|
+
{ accessor: 'email', header: 'Email' },
|
|
1347
|
+
{
|
|
1348
|
+
accessor: 'createdAt',
|
|
1349
|
+
header: 'Created',
|
|
1350
|
+
format: (value) => new Date(value).toLocaleDateString(),
|
|
1351
|
+
},
|
|
1352
|
+
];
|
|
1353
|
+
|
|
1354
|
+
function UsersPage() {
|
|
1355
|
+
const store = useUserStore();
|
|
1356
|
+
|
|
1357
|
+
return (
|
|
1358
|
+
<CrudList
|
|
1359
|
+
store={store}
|
|
1360
|
+
title="Users"
|
|
1361
|
+
description="Manage your organization's users"
|
|
1362
|
+
columns={columns}
|
|
1363
|
+
createPath="/users/create"
|
|
1364
|
+
detailPath="/users"
|
|
1365
|
+
editPath="/users"
|
|
1366
|
+
itemName="user"
|
|
1367
|
+
getRowKey={(row) => row.id}
|
|
1368
|
+
/>
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
```
|
|
1372
|
+
|
|
1373
|
+
**Selection + bulk actions (direct data props):**
|
|
1374
|
+
|
|
1375
|
+
```jsx
|
|
1376
|
+
import { useState } from 'react';
|
|
1377
|
+
import { CrudList } from '@bomjan133/react-crud-ui';
|
|
1378
|
+
import { Archive, Trash2 } from 'lucide-react';
|
|
1379
|
+
|
|
1380
|
+
const columns = [
|
|
1381
|
+
{ accessor: 'name', header: 'Name', sortable: true },
|
|
1382
|
+
{ accessor: 'status', header: 'Status' },
|
|
1383
|
+
];
|
|
1384
|
+
|
|
1385
|
+
function InvoicesPage({ invoices, isLoading }) {
|
|
1386
|
+
const [selectedRows, setSelectedRows] = useState([]);
|
|
1387
|
+
|
|
1388
|
+
const bulkActions = [
|
|
1389
|
+
{ label: 'Archive', icon: Archive, onClick: (rowKeys) => archiveInvoices(rowKeys) },
|
|
1390
|
+
{ label: 'Delete', icon: Trash2, variant: 'destructive', onClick: (rowKeys) => deleteInvoices(rowKeys) },
|
|
1391
|
+
];
|
|
1392
|
+
|
|
1393
|
+
return (
|
|
1394
|
+
<CrudList
|
|
1395
|
+
data={invoices}
|
|
1396
|
+
loading={isLoading}
|
|
1397
|
+
columns={columns}
|
|
1398
|
+
title="Invoices"
|
|
1399
|
+
itemName="invoice"
|
|
1400
|
+
selectable
|
|
1401
|
+
selectedRows={selectedRows}
|
|
1402
|
+
onSelectionChange={setSelectedRows}
|
|
1403
|
+
bulkActions={bulkActions}
|
|
1404
|
+
onCreate={() => openCreateModal()}
|
|
1405
|
+
onView={(row) => openDetailModal(row)}
|
|
1406
|
+
onEdit={(row) => openEditModal(row)}
|
|
1407
|
+
onDelete={async (row) => deleteInvoice(row.id)}
|
|
1408
|
+
getRowKey={(row) => row.id}
|
|
1409
|
+
/>
|
|
1410
|
+
);
|
|
1411
|
+
}
|
|
1412
|
+
```
|
|
1413
|
+
|
|
1414
|
+
---
|
|
1415
|
+
|
|
1416
|
+
## CrudForm
|
|
1417
|
+
|
|
1418
|
+
A form component for create/edit operations. **It is dual-mode** — which mode renders is decided by a single runtime check: `useStore && children` (both truthy).
|
|
1419
|
+
|
|
1420
|
+
- **Store mode** (`useStore` **and** `children` both supplied): renders `children` verbatim inside a `<form>`, does its own lightweight "required" validation by inspecting each child's `name`/`required`/`label` props, and calls `store.create`/`store.update`. `fields`, `onSubmit`, `initialData`, `defaultValues`, `validationSchema`, and `columns` are all ignored in this mode.
|
|
1421
|
+
- **Fields mode** (anything else — including `useStore` *without* `children`, or `children` *without* `useStore`): a self-contained `react-hook-form` + optional Zod form driven by the `fields` array and `onSubmit`. `useStore`, `children`, `onBeforeSubmit`, `onAfterCreate`, and `getBreadcrumbName` are all ignored in this mode — `children` isn't even rendered.
|
|
1422
|
+
|
|
1423
|
+
`CrudForm` unconditionally calls `useNavigate()`/`useParams()` (react-router) and `useBreadcrumb()`, so it must be rendered under a router and a `BreadcrumbProvider` regardless of which mode you use.
|
|
1424
|
+
|
|
1425
|
+
> ⚠️ **Store-shape warning:** `CrudForm`'s store mode expects a store exposing `form.values`, `form.isSubmitting`, `create(data)`, `update(id, data)`, `resetForm()`, `setFormErrors(errorsObj)`, and one of `fetchAndPopulateForm(id)` / `fetchById(id)` / `fetchOne(id)`. **The `createCrudStore`/`createStore` factory shipped in this same package does not produce this shape** — it exposes `item`, `fetchOne`, `create`, `update`, `loading`, `submitting`, `error`, with no `form`, `resetForm`, `setFormErrors`, or `fetchAndPopulateForm`. If you're using `createCrudStore`, use **fields mode** instead (`fields` + `onSubmit`), or hand-write a store matching store mode's expected shape.
|
|
1426
|
+
|
|
1427
|
+
### Props
|
|
1428
|
+
|
|
1429
|
+
| Prop | Type | Default | Description |
|
|
1430
|
+
|------|------|---------|--------------|
|
|
1431
|
+
| `useStore` | `function` | - | Zustand store hook. Combined with `children` to trigger store mode. See store-shape warning above. |
|
|
1432
|
+
| `children` | `node` | - | Store mode only. Rendered as-is inside `<form>` — `CrudForm` does **not** clone children or inject `value`/`onChange`. Each field is a fully generic controlled component; you must wire `value`/`onChange` to the store yourself. `CrudForm` only recursively reads each descendant's `name`, `required`, and `label` props to run its own "is empty" required-field check — unrelated to `validationSchema`/Zod. If passed without `useStore` (or vice versa), it is silently dropped and fields mode renders instead. |
|
|
1433
|
+
| `fields` | `array` | `[]` | Fields mode only. Array of field descriptors: `{ name, type, label, placeholder, description, required, disabled, options, className, hidden, colSpan, render, ...rest }`. `type` is one of `text \| email \| password \| number \| url \| tel \| textarea \| select \| search-select \| switch \| section \| custom` (unknown/omitted types fall back to a text `QInput`). `hidden` may be a boolean or `(allValues) => boolean`. `colSpan` is `1 \| 2 \| 3 \| 4 \| 'full'`. `type: 'section'` renders a divider using its own `title`/`description`/`icon`. `type: 'custom'` calls `field.render({ form, field, error, value })`. |
|
|
1434
|
+
| `defaultValues` | `object` | `{}` | Fields mode only. Initial `react-hook-form` values, used when `initialData` is not provided. |
|
|
1435
|
+
| `validationSchema` | Zod schema | - | Fields mode only. Passed to `zodResolver` for `react-hook-form` validation. No effect in store mode. |
|
|
1436
|
+
| `initialData` | `object` | `null` | Fields mode only. When present, seeds and re-syncs the form (`reset()`) — the fields-mode equivalent of "edit" data. Store mode instead fetches edit data itself via `fetchById`/`fetchAndPopulateForm`. |
|
|
1437
|
+
| `onSubmit` | `function(data)` | - | Fields mode only. Called with the `react-hook-form`-validated data. Thrown errors are caught and shown via a toast; there is **no** built-in success toast in fields mode (unlike store mode) — handle success yourself. |
|
|
1438
|
+
| `onCancel` | `function` | - | Store mode: called by the Cancel button (after `resetForm()`); if omitted, Cancel falls back to the back-navigation handler. Fields mode: the Cancel button is **only rendered if `onCancel` is truthy**, and clicking it calls `onCancel` directly with no fallback. |
|
|
1439
|
+
| `onBack` | `function` | - | Store mode: the back-arrow button (when `showBack` is true) always calls a `handleBack()` that uses `onBack` if given, else `navigate(listPath)`, else `navigate(-1)`. Fields mode: the back-arrow button is **only rendered if `showBack && onBack` are both truthy**, and calls `onBack` directly (no `listPath`/`navigate(-1)` fallback). |
|
|
1440
|
+
| `onBeforeSubmit` | `function(values) => values` | - | Store mode only. Called synchronously (not awaited) with the current `store.form.values` right before submit. **Its return value directly replaces the values passed to `create`/`update`** — there is no "return `false` to cancel" behavior; it must always return an object. |
|
|
1441
|
+
| `onAfterCreate` | `function(result, navigate)` | - | Store mode only, and only fires after `create` (never `update`), and only if `create()` resolved with a truthy result. If omitted (or the result is falsy), falls back to the back-navigation handler. No equivalent hook exists for the update/edit path. |
|
|
1442
|
+
| `title` | `string` | - | Store mode: form title, auto-prefixed as `` `Edit ${title}` `` or `` `Create ${title}` `` depending on edit-mode detection (see below), and used in the auto success toast (`"{title} created/updated successfully"`, default `"Item"` if omitted). Fields mode: rendered as-is (no Edit/Create prefix), and only shown at all if `showHeader` and (`title` or `description` or `showBack`) are truthy. |
|
|
1443
|
+
| `description` | `string` | - | Subtitle shown under the title, both modes. |
|
|
1444
|
+
| `submitLabel` | `string` | `"Save"` | Submit button text, both modes. Shows a spinner + "Saving..." while submitting. |
|
|
1445
|
+
| `cancelLabel` | `string` | `"Cancel"` | Cancel button text, both modes (subject to the `onCancel` visibility rule above). |
|
|
1446
|
+
| `columns` | `1 \| 2 \| 3 \| 4` | `1` | Fields mode only. Grid column count for laying out `fields`. No effect in store mode. |
|
|
1447
|
+
| `showHeader` | `boolean` | `true` | Fields mode only. Gates whether the Card+header wrapper is used (vs. a plain `<div>`). No effect in store mode (its header is unconditional). |
|
|
1448
|
+
| `showFooter` | `boolean` | `true` | Shows/hides the Cancel/Submit button row, both modes. |
|
|
1449
|
+
| `showBack` | `boolean` | `true` | Shows the back-arrow icon button. See the asymmetric per-mode behavior under `onBack`. |
|
|
1450
|
+
| `showCard` | `boolean` | `true` | **Only honored in store mode** (wraps output in `Card` vs. a plain `<div>`). In fields mode, Card-vs-div is decided solely by `showHeader && (title \|\| description \|\| showBack)` — this prop is read but never checked there. |
|
|
1451
|
+
| `listPath` | `string` | - | Fallback destination for `handleBack()` when no `onBack` is given, in both modes. |
|
|
1452
|
+
| `icon` | `component` | - | **Only rendered in store mode when `showCard` is `false`.** Not used in the Card-wrapped store header, and not used anywhere in fields mode. |
|
|
1453
|
+
| `className` | `string` | - | Applied to the outer `Card`/`div` wrapper, both modes. |
|
|
1454
|
+
| `getBreadcrumbName` | `function(values)` | - | Store mode only, active only while editing (`uuid` route param present). Called with `store.form.values` once they look populated; its return value is registered via `useBreadcrumb().setBreadcrumbName(uuid, name)` and cleared on unmount. Requires an ancestor `BreadcrumbProvider`. |
|
|
1455
|
+
| `loading` | `boolean` | `false` | OR'd with the store's own `loading` (store mode). Disables fields and combines with `submitting` to disable Submit. |
|
|
1456
|
+
| `submitting` | `boolean` | `false` | OR'd with the store's own `form.isSubmitting` (store mode). Disables Cancel/Submit and swaps Submit's label/icon for a spinner + "Saving...". |
|
|
1457
|
+
|
|
1458
|
+
> **Not implemented / dead props:** there is no `onSuccess` callback — store mode's success message is a hardcoded toast (`"{title} created/updated successfully"`); the closest customization hook is `onAfterCreate` (create only). `backLabel` is destructured but never rendered anywhere — it has no effect.
|
|
1459
|
+
|
|
1460
|
+
**Edit-mode detection**: create-vs-edit is determined solely by `Boolean(useParams().uuid)` — `CrudForm` must be rendered on a route with a literal `:uuid` param (not `:id`, and not an `id` prop). This flag drives the title prefix, whether `fetchById`/`fetchAndPopulateForm`/`fetchOne` runs, and whether submit calls `store.update(uuid, values)` vs `store.create(values)`. Fields mode ignores this entirely — there, "edit" is just whatever `initialData` you pass in.
|
|
1461
|
+
|
|
1462
|
+
### Usage
|
|
1463
|
+
|
|
1464
|
+
**Store mode** (requires a hand-written store matching the shape described in the warning above), rendered on routes like `/users/new` and `/users/:uuid/edit`:
|
|
1465
|
+
|
|
1466
|
+
```jsx
|
|
1467
|
+
import { CrudForm, QInput } from '@bomjan133/react-crud-ui';
|
|
1468
|
+
|
|
1469
|
+
function UserForm() {
|
|
1470
|
+
return (
|
|
1471
|
+
<CrudForm
|
|
1472
|
+
title="User"
|
|
1473
|
+
useStore={useUserFormStore}
|
|
1474
|
+
listPath="/users"
|
|
1475
|
+
getBreadcrumbName={(values) => values.name}
|
|
1476
|
+
onBeforeSubmit={(values) => ({ ...values, email: values.email.trim().toLowerCase() })}
|
|
1477
|
+
onAfterCreate={(result, navigate) => navigate(`/users/${result.uuid}/edit`)}
|
|
1478
|
+
>
|
|
1479
|
+
<QInput
|
|
1480
|
+
name="name"
|
|
1481
|
+
label="Name"
|
|
1482
|
+
required
|
|
1483
|
+
value={useUserFormStore((s) => s.form.values.name) ?? ''}
|
|
1484
|
+
onChange={(val) => useUserFormStore.getState().setFormValue('name', val)}
|
|
1485
|
+
/>
|
|
1486
|
+
<QInput
|
|
1487
|
+
name="email"
|
|
1488
|
+
label="Email"
|
|
1489
|
+
required
|
|
1490
|
+
value={useUserFormStore((s) => s.form.values.email) ?? ''}
|
|
1491
|
+
onChange={(val) => useUserFormStore.getState().setFormValue('email', val)}
|
|
1492
|
+
/>
|
|
1493
|
+
</CrudForm>
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
```
|
|
1497
|
+
|
|
1498
|
+
**Fields mode** (self-contained `react-hook-form`, no store, no router param required — pass `initialData` for edit, omit it for create):
|
|
1499
|
+
|
|
1500
|
+
```jsx
|
|
1501
|
+
import { CrudForm } from '@bomjan133/react-crud-ui';
|
|
1502
|
+
|
|
1503
|
+
<CrudForm
|
|
1504
|
+
title="User"
|
|
1505
|
+
description="Basic account details"
|
|
1506
|
+
fields={[
|
|
1507
|
+
{ name: 'email', type: 'email', label: 'Email', required: true },
|
|
1508
|
+
{
|
|
1509
|
+
name: 'role',
|
|
1510
|
+
type: 'select',
|
|
1511
|
+
label: 'Role',
|
|
1512
|
+
options: [
|
|
1513
|
+
{ value: 'admin', label: 'Admin' },
|
|
1514
|
+
{ value: 'member', label: 'Member' },
|
|
1515
|
+
],
|
|
1516
|
+
},
|
|
1517
|
+
]}
|
|
1518
|
+
initialData={editingUser} // omit for create mode
|
|
1519
|
+
columns={2}
|
|
1520
|
+
onSubmit={async (data) => {
|
|
1521
|
+
await api.saveUser(data);
|
|
1522
|
+
toast.success('Saved');
|
|
1523
|
+
}}
|
|
1524
|
+
onCancel={() => navigate('/users')}
|
|
1525
|
+
onBack={() => navigate('/users')}
|
|
1526
|
+
/>
|
|
1527
|
+
```
|
|
1528
|
+
|
|
1529
|
+
---
|
|
1530
|
+
|
|
1531
|
+
## CrudDetail
|
|
1532
|
+
|
|
1533
|
+
A detail-view component for a single record. It supports two distinct rendering modes, and can source its data either from a Zustand-style store hook (`useStore`) or directly via a `data` prop.
|
|
1534
|
+
|
|
1535
|
+
**Mode selection is automatic and based on `children`:**
|
|
1536
|
+
- **Store + render-prop mode** — used only when *both* `useStore` is passed **and** `children` is a function. Renders whatever `children(data)` returns inside a plain header + content wrapper (no Card).
|
|
1537
|
+
- **Fields-based mode** — used in every other case (no `useStore`, or `useStore` without a function `children`, or `children` that isn't a function). Renders a `Card` with a field grid built from the `fields` array. **`children` is completely ignored in this mode.**
|
|
1538
|
+
|
|
1539
|
+
`useStore` can also be used purely for fetching/deleting without triggering render-prop mode, as long as `children` isn't a function — data then comes from the store and renders via `fields`.
|
|
1540
|
+
|
|
1541
|
+
> ⚠️ **`children` is a render-prop function, not a plain node**, and only takes effect when `useStore` is *also* set. Passing `children` without `useStore` (or a non-function `children`) is silently dropped in favor of fields-based rendering — it will not throw, it just won't render what you passed.
|
|
1542
|
+
|
|
1543
|
+
### How the record id and fetch are resolved
|
|
1544
|
+
|
|
1545
|
+
- The id comes from the React Router route param named by `paramName` (default `"uuid"`), read via `useParams()` — your route must contain a `:uuid` (or whatever `paramName` is) segment. **There is no `id` prop.**
|
|
1546
|
+
- On mount and whenever that id changes, if `useStore` was given and the store exposes `fetchById` (or, as a fallback, `fetchOne`), the component calls `fetchById(id)`.
|
|
1547
|
+
- Delete calls the store's `delete(id)` method (or your own `onDelete` callback) and then navigates back on success.
|
|
1548
|
+
|
|
1549
|
+
### Loading / error / not-found states
|
|
1550
|
+
|
|
1551
|
+
- **Loading**: shown when `loading` (prop) or the store's `loading` is true. Renders `Loading {itemName}...`. There is no prop to swap in a custom loading component.
|
|
1552
|
+
- **Error**: shown when `error` (prop) or the store's `error` is truthy. Renders the internal `ServerErrorPage` (parses Axios/fetch/plain-`Error` shapes, with a Retry button that re-calls `fetchById`, and a Back button). No prop supplies a custom error component; only `backLabel` affects its text.
|
|
1553
|
+
- **Not found** (`!data` after loading, no error): renders "No {itemName} found" with a Back button.
|
|
1554
|
+
|
|
1555
|
+
### Props
|
|
1556
|
+
|
|
1557
|
+
| Prop | Type | Default | Description |
|
|
1558
|
+
|------|------|---------|--------------|
|
|
1559
|
+
| `useStore` | `function` | - | Zustand-style hook, called as `useStore()`. Component reads `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), and `delete` off the returned store. |
|
|
1560
|
+
| `children` | `function` | - | Render prop `(data) => ReactNode`. Only used when `useStore` is also set; otherwise ignored. |
|
|
1561
|
+
| `data` | `object` | `null` | Direct data mode: record to display (`propData \|\| storeData`), used in place of / alongside the store's `currentItem`. |
|
|
1562
|
+
| `paramName` | `string` | `"uuid"` | Name of the route param (via `useParams()`) used as the record id. |
|
|
1563
|
+
| `loading` | `boolean` | `false` | External loading flag, OR'd with the store's own `loading`. |
|
|
1564
|
+
| `error` | `any` | `null` | External error value, OR'd with the store's own `error`. |
|
|
1565
|
+
| `fields` | `array` | `[]` | Field definitions for fields-based mode. Each item: `{ name, accessor, label, type, icon, hidden, colSpan, format, render, variant, statusColors, trueLabel, falseLabel, getItemLabel, currency, linkText, imageClassName }`. Supported `type`s: `badge`, `status`, `boolean`, `date`, `datetime`, `currency`, `number`, `list`, `link`, `email`, `phone`, `image`, `html` (plus default/plain rendering). |
|
|
1566
|
+
| `onBack` | `function` | - | Custom back handler. If omitted, falls back to navigating to `listPath`, or `navigate(-1)` if no `listPath`. |
|
|
1567
|
+
| `onEdit` | `function(data)` | - | Custom edit handler. If omitted, falls back to navigating to `` `${editPath}/${id}/edit` `` (only if `editPath` and the route id are present). |
|
|
1568
|
+
| `onDelete` | `function(data)` | - | Custom delete handler (awaited). If omitted, falls back to the store's `delete(id)`, then navigates back on success. |
|
|
1569
|
+
| `listPath` | `string` | - | Path the Back button navigates to when `onBack` isn't provided. |
|
|
1570
|
+
| `editPath` | `string` | - | Base path used to build the default edit destination (`${editPath}/{id}/edit`) when `onEdit` isn't provided. |
|
|
1571
|
+
| `title` | `string` | - | Card title text. **Only rendered in fields-based mode**; ignored in store+children mode (whose header title comes from `getBreadcrumbName(data)` instead). |
|
|
1572
|
+
| `description` | `string` | - | Description text shown under the title in both modes. |
|
|
1573
|
+
| `editLabel` | `string` | `"Edit"` | Label for the Edit item in the actions dropdown. |
|
|
1574
|
+
| `deleteLabel` | `string` | `"Delete"` | Label for the Delete item in the actions dropdown. |
|
|
1575
|
+
| `backLabel` | `string` | `"Back"` | Label for Back buttons. |
|
|
1576
|
+
| `itemName` | `string` | `"item"` | Generic noun used in loading/empty text and as a fallback for the delete-confirmation item name. |
|
|
1577
|
+
| `getItemName` | `function(data)` | - | Returns a display name for the record, used (HTML-stripped, truncated to 80 chars) in the delete confirmation dialog. Falls back to `data.name`, then `data.title`, then `itemName`. |
|
|
1578
|
+
| `showBackButton` | `boolean` | `true` | Whether to show the Back button. Also auto-hidden when the page was opened as a new tab (`window.history.length <= 1`), regardless of this prop. |
|
|
1579
|
+
| `additionalActions` | `array` | `[]` | Extra items in the actions dropdown: `[{ label, icon, onClick(data), variant, separator }]`. `variant: "destructive"` applies destructive styling; `separator: true` inserts a divider before that item. |
|
|
1580
|
+
| `getBreadcrumbName` | `function(data)` | - | Returns a name registered with the breadcrumb context (via `useBreadcrumb()`, requires a `BreadcrumbProvider`) keyed by the route id. Also used as the store+children mode's header title. |
|
|
1581
|
+
| `customBreadcrumbPaths` | `object` | - | Static breadcrumb path overrides passed through `navigate(..., { state })` when navigating to edit. |
|
|
1582
|
+
| `getCustomBreadcrumbPath` | `function(data)` | - | Dynamic version of `customBreadcrumbPaths`; takes precedence when provided. |
|
|
1583
|
+
| `getParentPath` | `function(data)` | - | Returns a parent path used to build breadcrumb path overrides for edit navigation, when neither of the above apply. |
|
|
1584
|
+
| `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state passed when navigating to edit. |
|
|
1585
|
+
| `showEditButton` | `boolean` | `true` | Whether the Edit action appears in the dropdown (also requires `onEdit` or `editPath` to be set). |
|
|
1586
|
+
| `showDeleteButton` | `boolean` | `true` | Whether the Delete action appears in the dropdown (also requires `onDelete` or the store's `delete` to be available). |
|
|
1587
|
+
| `showHeader` | `boolean` | `true` | Whether to render the header/title row (and its actions dropdown) at all. |
|
|
1588
|
+
| `showMeta` | `boolean` | `true` | Fields-based mode only: whether to show the Created/Updated/ID meta row below the fields grid (only shown if the record actually has those fields). |
|
|
1589
|
+
| `columns` | `1 \| 2 \| 3` | `2` | Number of grid columns for the fields grid (fields-based mode). |
|
|
1590
|
+
| `className` | `string` | - | Root wrapper class (store+children mode) or `Card` class (fields-based mode). |
|
|
1591
|
+
| `cardHeaderClassName` | `string` | - | Applied to `CardHeader` (fields-based mode). |
|
|
1592
|
+
| `headerClassName` | `string` | - | Applied to the header's inner flex container (store+children mode only). |
|
|
1593
|
+
| `titleClassName` | `string` | - | Applied to `CardTitle` (fields-based mode only). |
|
|
1594
|
+
| `descriptionClassName` | `string` | - | Applied to `CardDescription` (fields-based mode only). |
|
|
1595
|
+
| `fieldsGridClassName` | `string` | - | Applied to the fields grid container. |
|
|
1596
|
+
| `fieldItemClassName` | `string` | - | Applied to each individual field's wrapper. |
|
|
1597
|
+
| `fieldLabelClassName` | `string` | - | Applied to each field's label element. |
|
|
1598
|
+
| `fieldValueClassName` | `string` | - | Applied to each field's value element. |
|
|
1599
|
+
| `metaClassName` | `string` | - | Applied to the Created/Updated/ID meta row container. |
|
|
1600
|
+
| `metaItemClassName` | `string` | - | Applied to each item within the meta row. |
|
|
1601
|
+
| `backButtonClassName` | `string` | - | Applied to the Back icon button (store+children mode header). |
|
|
1602
|
+
| `actionsDropdownItemClassName` | `string` | - | Applied to the Edit item inside the actions dropdown only (not Delete or additional-action items). |
|
|
1603
|
+
| `loadingStateClassName` | `string` | - | Applied to the loading `Card` in store+children mode only; no effect in fields-based mode. |
|
|
1604
|
+
|
|
1605
|
+
> **Not implemented / dead props:** `showCard`, `icon`, `cardContentClassName`, and `emptyStateClassName` are all accepted but not referenced anywhere else in the component — they currently have no effect. `errorStateClassName` is likewise a no-op in practice (the reachable error-render path never applies it). `actionsDropdownClassName` is also accepted, but rather than styling the actions dropdown, it's applied to the Back button in fields-based mode's header — this is a naming/wiring bug in the component, documented here as-observed rather than as-intended.
|
|
1606
|
+
|
|
1607
|
+
### Usage
|
|
1608
|
+
|
|
1609
|
+
**Store-driven, custom render (render-prop `children`):**
|
|
1610
|
+
|
|
1611
|
+
```jsx
|
|
1612
|
+
<CrudDetail
|
|
1613
|
+
useStore={useUserStore}
|
|
1614
|
+
listPath="/users"
|
|
1615
|
+
editPath="/users"
|
|
1616
|
+
getBreadcrumbName={(user) => user.name}
|
|
1617
|
+
additionalActions={[
|
|
1618
|
+
{ label: 'Reset Password', onClick: (user) => resetPassword(user.uuid) },
|
|
1619
|
+
]}
|
|
1620
|
+
>
|
|
1621
|
+
{(user) => (
|
|
1622
|
+
<Card>
|
|
1623
|
+
<CardContent className="py-6">
|
|
1624
|
+
<p>{user.email}</p>
|
|
1625
|
+
</CardContent>
|
|
1626
|
+
</Card>
|
|
1627
|
+
)}
|
|
1628
|
+
</CrudDetail>
|
|
1629
|
+
```
|
|
1630
|
+
|
|
1631
|
+
Requires a route like `/users/:uuid` (or pass `paramName="id"` for `/users/:id`).
|
|
1632
|
+
|
|
1633
|
+
**Direct data + fields array (no store):**
|
|
1634
|
+
|
|
1635
|
+
```jsx
|
|
1636
|
+
<CrudDetail
|
|
1637
|
+
title="User"
|
|
1638
|
+
data={user}
|
|
1639
|
+
fields={[
|
|
1640
|
+
{ name: 'email', label: 'Email', type: 'email' },
|
|
1641
|
+
{ name: 'status', label: 'Status', type: 'status' },
|
|
1642
|
+
{ name: 'created_at', label: 'Joined', type: 'date' },
|
|
1643
|
+
]}
|
|
1644
|
+
onBack={() => navigate('/users')}
|
|
1645
|
+
onEdit={(u) => navigate(`/users/${u.uuid}/edit`)}
|
|
1646
|
+
onDelete={(u) => deleteUser(u.uuid)}
|
|
1647
|
+
/>
|
|
1648
|
+
```
|
|
1649
|
+
|
|
1650
|
+
---
|
|
1651
|
+
|
|
1652
|
+
## Pagination
|
|
1653
|
+
|
|
1654
|
+
### Props
|
|
1655
|
+
|
|
1656
|
+
| Prop | Type | Default | Description |
|
|
1657
|
+
|------|------|---------|--------------|
|
|
1658
|
+
| `currentPage` | `number` | `1` | The active page (1-indexed). |
|
|
1659
|
+
| `totalPages` | `number` | `1` | Total number of pages. Controls whether Next/Last buttons are enabled and how page numbers are rendered. |
|
|
1660
|
+
| `totalItems` | `number` | `0` | Total item count across all pages, used only to compute the "Showing X to Y of Z results" text. |
|
|
1661
|
+
| `pageSize` | `number` | `15` | Current page size; also drives the value shown in the rows-per-page select. |
|
|
1662
|
+
| `pageSizeOptions` | `number[]` | `[15, 20, 50, 100]` | Options rendered in the rows-per-page dropdown. |
|
|
1663
|
+
| `onPageChange` | `function(page)` | - | Called with the target page number when First/Prev/page-number/Next/Last is clicked. |
|
|
1664
|
+
| `onPageSizeChange` | `function(size)` | - | Called with the new numeric page size when the rows-per-page select changes. |
|
|
1665
|
+
| `showPageSizeSelector` | `boolean` | `true` | Show/hide the "Rows per page" selector. |
|
|
1666
|
+
| `showInfo` | `boolean` | `true` | Show/hide the "Showing X to Y of Z results" text (also requires `totalItems > 0`). |
|
|
1667
|
+
| `className` | `string` | - | Extra classes merged onto the root container. |
|
|
1668
|
+
|
|
1669
|
+
Not a Radix wrapper — a plain `div` composed from this library's own `Button` and `Select`. No extra props pass through.
|
|
1670
|
+
|
|
1671
|
+
### Usage
|
|
1672
|
+
|
|
1673
|
+
```jsx
|
|
1674
|
+
import { Pagination } from '@bomjan133/react-crud-ui';
|
|
1675
|
+
|
|
1676
|
+
<Pagination
|
|
1677
|
+
currentPage={pagination.page}
|
|
1678
|
+
totalPages={pagination.totalPages}
|
|
1679
|
+
totalItems={pagination.totalItems}
|
|
1680
|
+
pageSize={pagination.pageSize}
|
|
1681
|
+
pageSizeOptions={[15, 20, 50, 100]}
|
|
1682
|
+
onPageChange={(page) => setPage(page)}
|
|
1683
|
+
onPageSizeChange={(size) => setPageSize(size)}
|
|
1684
|
+
/>
|
|
1685
|
+
```
|
|
1686
|
+
|
|
1687
|
+
---
|
|
1688
|
+
|
|
1689
|
+
## Loading Components
|
|
1690
|
+
|
|
1691
|
+
### `Loading`
|
|
1692
|
+
|
|
1693
|
+
| Prop | Type | Default | Description |
|
|
1694
|
+
|------|------|---------|--------------|
|
|
1695
|
+
| `variant` | `'spinner' \| 'dots' \| 'pulse' \| 'skeleton'` | `'spinner'` | Visual style. Any unrecognized value falls back to the spinner. |
|
|
1696
|
+
| `size` | `'sm' \| 'default' \| 'lg' \| 'xl'` | `'default'` | Size of the spinner/dots/pulse indicator (there is no `'md'` value). Has no effect on the `skeleton` variant. |
|
|
1697
|
+
| `text` | `string` | - | Optional caption below the loader. |
|
|
1698
|
+
| `fullScreen` | `boolean` | `false` | Adds `fixed inset-0 z-50` to cover the viewport. |
|
|
1699
|
+
| `overlay` | `boolean` | `false` | Adds a translucent blurred background. |
|
|
1700
|
+
| `className` | `string` | - | Extra classes merged onto the root container. |
|
|
1701
|
+
|
|
1702
|
+
### `LoadingOverlay`
|
|
1703
|
+
|
|
1704
|
+
| Prop | Type | Default | Description |
|
|
1705
|
+
|------|------|---------|--------------|
|
|
1706
|
+
| `loading` | `boolean` | `false` | When true, renders an absolutely-positioned, blurred overlay on top of `children`. **The prop is `loading`, not `visible`.** |
|
|
1707
|
+
| `children` | `node` | - | The content the overlay layers on top of (always rendered underneath). |
|
|
1708
|
+
| `text` | `string` | - | Passed straight through to the internal `<Loading text={text} />` shown while `loading` is true. |
|
|
1709
|
+
| `className` | `string` | - | Extra classes on the root wrapper. |
|
|
1710
|
+
|
|
1711
|
+
There is no `size`/`variant` control — the internal loader is always the default spinner at default size.
|
|
1712
|
+
|
|
1713
|
+
### `LoadingButton`
|
|
1714
|
+
|
|
1715
|
+
| Prop | Type | Default | Description |
|
|
1716
|
+
|------|------|---------|--------------|
|
|
1717
|
+
| `loading` | `boolean` | `false` | When true, disables the button and swaps its content for a spinner + `loadingText`. |
|
|
1718
|
+
| `loadingText` | `string` | `'Loading...'` | Text shown next to the spinner while `loading` is true. |
|
|
1719
|
+
| `children` | `node` | - | Normal button content, shown when not loading. |
|
|
1720
|
+
| `disabled` | `boolean` | - | Manually disable the button; internally OR'd with `loading`. |
|
|
1721
|
+
| `className` | `string` | - | Extra classes passed to the underlying `Button`. |
|
|
1722
|
+
| `...props` | - | - | Anything else (`onClick`, `variant`, `size`, `type`, etc.) spreads onto the underlying `Button`. |
|
|
1723
|
+
|
|
1724
|
+
`LoadingButton` is a `forwardRef` component — a `ref` attaches to the underlying `Button`/native `<button>`.
|
|
1725
|
+
|
|
1726
|
+
### Usage
|
|
1727
|
+
|
|
1728
|
+
```jsx
|
|
1729
|
+
import { Loading, LoadingOverlay, LoadingButton } from '@bomjan133/react-crud-ui';
|
|
1730
|
+
|
|
1731
|
+
<Loading />
|
|
1732
|
+
<Loading size="sm" />
|
|
1733
|
+
<Loading variant="dots" size="lg" text="Loading data..." />
|
|
1734
|
+
<Loading variant="skeleton" />
|
|
1735
|
+
<Loading fullScreen overlay text="Please wait..." />
|
|
1736
|
+
|
|
1737
|
+
<LoadingOverlay loading={isLoading} text="Refreshing...">
|
|
1738
|
+
<ProductTable data={products} />
|
|
1739
|
+
</LoadingOverlay>
|
|
1740
|
+
|
|
1741
|
+
<LoadingButton loading={isSubmitting} loadingText="Saving..." onClick={handleSubmit}>
|
|
1742
|
+
Save Changes
|
|
1743
|
+
</LoadingButton>
|
|
1744
|
+
```
|
|
1745
|
+
|
|
1746
|
+
---
|
|
1747
|
+
|
|
1748
|
+
## Empty States
|
|
1749
|
+
|
|
1750
|
+
### `EmptyState`
|
|
1751
|
+
|
|
1752
|
+
| Prop | Type | Default | Description |
|
|
1753
|
+
|------|------|---------|--------------|
|
|
1754
|
+
| `icon` | `component` | `FileQuestion` | Icon rendered inside the circular badge. |
|
|
1755
|
+
| `title` | `string` | `'No data found'` | Heading text. |
|
|
1756
|
+
| `description` | `string` | `'There are no items to display.'` | Body text. |
|
|
1757
|
+
| `actionLabel` | `string` | `'Take Action'` | Label for the built-in action button, shown when `actionLabel`/`onAction` is truthy (see note below). |
|
|
1758
|
+
| `onAction` | `function()` | - | Click handler wired to the built-in action button. |
|
|
1759
|
+
| `variant` | `'default' \| 'search' \| 'empty' \| 'error'` | `'default'` | Selects a fallback icon/title/description, but the fallback only applies when `icon`/`title`/`description` are explicitly `null` — since all three already have their own default values, `variant` alone changes nothing visually in normal use. |
|
|
1760
|
+
| `className` | `string` | - | Extra classes on the root container. |
|
|
1761
|
+
| `children` | `node` | - | Rendered between the description and the action button — use this for custom action content. |
|
|
1762
|
+
|
|
1763
|
+
> **`action` is not a rendering slot.** It exists in the source but is only checked for truthiness (to help decide whether to show the built-in button) — its content is never actually rendered. Passing `action={<Button>...</Button>}` does **not** render that button. Use `actionLabel` + `onAction` for the built-in button, or `children` for fully custom content.
|
|
1764
|
+
|
|
1765
|
+
### `SearchEmptyState`
|
|
1766
|
+
|
|
1767
|
+
| Prop | Type | Default | Description |
|
|
1768
|
+
|------|------|---------|--------------|
|
|
1769
|
+
| `searchTerm` | `string` | - | Interpolated into the title as `` No results for "${searchTerm}" ``. |
|
|
1770
|
+
| `onClear` | `function()` | - | If provided, renders an outline "Clear Search" button (via `children`, not the built-in action button). |
|
|
1771
|
+
| `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
|
|
1772
|
+
|
|
1773
|
+
Internally renders `<EmptyState variant="search" ... />` but always leaves `icon` unset, so — per the `variant` note above — it actually displays the default `FileQuestion` icon, not a search icon.
|
|
1774
|
+
|
|
1775
|
+
### `CreateEmptyState`
|
|
1776
|
+
|
|
1777
|
+
| Prop | Type | Default | Description |
|
|
1778
|
+
|------|------|---------|--------------|
|
|
1779
|
+
| `itemName` | `string` | `'item'` | Builds the title (`` No ${itemName}s yet ``), description (`` Create your first ${itemName} to get started. ``), and action label (`` Create ${itemName} ``). |
|
|
1780
|
+
| `onCreate` | `function()` | - | Click handler for the built-in "Create ___" button. |
|
|
1781
|
+
| `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
|
|
1782
|
+
|
|
1783
|
+
> There is no `title`, `description`, `createPath`, or `createLabel` prop — these were fabricated in an earlier version of this doc. Text is always auto-generated from `itemName`; there's no route/navigation concept baked in.
|
|
1784
|
+
|
|
1785
|
+
### `ErrorState`
|
|
1786
|
+
|
|
1787
|
+
| Prop | Type | Default | Description |
|
|
1788
|
+
|------|------|---------|--------------|
|
|
1789
|
+
| `error` | `Error \| { message?: string }` | - | If `error?.message` exists it's used as the description; otherwise falls back to `'Something went wrong. Please try again.'`. Title is always hardcoded to `'Error loading data'`. |
|
|
1790
|
+
| `onRetry` | `function()` | - | Click handler for the built-in "Try Again" button. |
|
|
1791
|
+
| `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
|
|
1792
|
+
|
|
1793
|
+
> There is no `title` or `description` string prop — pass an `error` object instead.
|
|
1794
|
+
|
|
1795
|
+
None of the Empty State components are Radix-based, and none spread extra props through.
|
|
1796
|
+
|
|
1797
|
+
### Usage
|
|
1798
|
+
|
|
1799
|
+
```jsx
|
|
1800
|
+
import { EmptyState, SearchEmptyState, CreateEmptyState, ErrorState } from '@bomjan133/react-crud-ui';
|
|
1801
|
+
|
|
1802
|
+
<EmptyState
|
|
1803
|
+
icon={Box}
|
|
1804
|
+
title="No Products"
|
|
1805
|
+
description="You haven't added any products yet."
|
|
1806
|
+
actionLabel="Create Product"
|
|
1807
|
+
onAction={() => navigate('/products/create')}
|
|
1808
|
+
/>
|
|
1809
|
+
|
|
1810
|
+
<SearchEmptyState searchTerm={search} onClear={() => setSearch('')} />
|
|
1811
|
+
|
|
1812
|
+
<CreateEmptyState itemName="product" onCreate={() => navigate('/products/create')} />
|
|
1813
|
+
|
|
1814
|
+
<ErrorState error={fetchError} onRetry={() => fetchList()} />
|
|
1815
|
+
```
|
|
1816
|
+
|
|
1817
|
+
---
|
|
1818
|
+
|
|
1819
|
+
## Modal Components
|
|
1820
|
+
|
|
1821
|
+
All four components are built on Radix Dialog (`@radix-ui/react-dialog`). Only `Modal` forwards extra props, and it forwards them to the Radix `Dialog` **root** (e.g. `modal`, `defaultOpen`) — not to `DialogContent`, so Content-level Radix props like `onInteractOutside` can't be passed through any of these.
|
|
1822
|
+
|
|
1823
|
+
> **Naming correction:** none of these components use `isOpen` — the control prop is `open`, paired with `onOpenChange`. Only `Modal` additionally accepts an `onClose` convenience callback; `ConfirmModal` has `onCancel` instead; `DeleteConfirmModal` and `FormModal` have neither and rely solely on `onOpenChange`.
|
|
1824
|
+
|
|
1825
|
+
### `Modal`
|
|
1826
|
+
|
|
1827
|
+
| Prop | Type | Default | Description |
|
|
1828
|
+
|------|------|---------|--------------|
|
|
1829
|
+
| `open` | `boolean` | - | Controls dialog visibility. |
|
|
1830
|
+
| `onOpenChange` | `function(open)` | - | Standard Radix open-state change handler. |
|
|
1831
|
+
| `onClose` | `function()` | - | Extra convenience callback fired whenever `onOpenChange` transitions to `false`. |
|
|
1832
|
+
| `title` | `string` | - | Rendered in the dialog header (only if `title` or `description` is truthy). Clamped to 3 lines. |
|
|
1833
|
+
| `description` | `string` | - | Rendered under the title. Clamped to 3 lines. |
|
|
1834
|
+
| `children` | `node` | - | Main dialog body content. |
|
|
1835
|
+
| `footer` | `node` | - | Rendered in the dialog footer if provided. |
|
|
1836
|
+
| `size` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | `'default'` | Maps to `max-w-sm` / `max-w-lg` / `max-w-2xl` / `max-w-4xl` / `max-w-[95vw]` respectively. |
|
|
1837
|
+
| `className` | `string` | - | Extra classes merged onto the dialog content (combined with the `size` class). |
|
|
1838
|
+
| `...props` | - | - | Spread onto the Radix `Dialog` root (e.g. `modal`, `defaultOpen`). |
|
|
1839
|
+
|
|
1840
|
+
> `showClose` is accepted but has **no effect** — it's never read in the render logic. The close (×) button always shows regardless of this prop's value.
|
|
1841
|
+
|
|
1842
|
+
### `ConfirmModal`
|
|
1843
|
+
|
|
1844
|
+
| Prop | Type | Default | Description |
|
|
1845
|
+
|------|------|---------|--------------|
|
|
1846
|
+
| `open` | `boolean` | - | Dialog visibility. |
|
|
1847
|
+
| `onOpenChange` | `function(open)` | - | Passed straight through to `Modal`. |
|
|
1848
|
+
| `onConfirm` | `function()` | - | Called (and awaited) when the confirm button is clicked. |
|
|
1849
|
+
| `onCancel` | `function()` | - | Called when Cancel is clicked, in addition to automatically calling `onOpenChange?.(false)`. |
|
|
1850
|
+
| `title` | `string` | `'Are you sure?'` | |
|
|
1851
|
+
| `description` | `string` | `'This action cannot be undone.'` | |
|
|
1852
|
+
| `confirmText` | `string` | `'Confirm'` | Confirm button label (shows `'Loading...'` while `loading`). |
|
|
1853
|
+
| `cancelText` | `string` | `'Cancel'` | Cancel button label. |
|
|
1854
|
+
| `variant` | `'default' \| 'destructive'` | `'default'` | Only `'destructive'` is specially handled (styles the confirm button as destructive). |
|
|
1855
|
+
| `loading` | `boolean` | `false` | Disables both buttons; confirm button shows `'Loading...'`. |
|
|
1856
|
+
| `className` | `string` | - | Forwarded to the internal `Modal`. |
|
|
1857
|
+
|
|
1858
|
+
`ConfirmModal` doesn't accept `children`, and its internal `Modal` always uses `size="default"` — there's no way to resize it.
|
|
1859
|
+
|
|
1860
|
+
### `DeleteConfirmModal`
|
|
1861
|
+
|
|
1862
|
+
| Prop | Type | Default | Description |
|
|
1863
|
+
|------|------|---------|--------------|
|
|
1864
|
+
| `open` | `boolean` | - | Dialog visibility. |
|
|
1865
|
+
| `onOpenChange` | `function(open)` | - | Forwarded to `ConfirmModal`. |
|
|
1866
|
+
| `onConfirm` | `function()` | - | Delete handler. |
|
|
1867
|
+
| `title` | `string` | `` `Delete ${itemName}?` `` | Overridable. |
|
|
1868
|
+
| `description` | `string` | `` `Are you sure you want to delete this ${itemName}? This action cannot be undone.` `` | Overridable. |
|
|
1869
|
+
| `itemName` | `string` | `'item'` | Interpolated into the default title/description. |
|
|
1870
|
+
| `loading` | `boolean` | `false` | Passed through to `ConfirmModal`. |
|
|
1871
|
+
|
|
1872
|
+
Internally always passes `confirmText="Delete"` and `variant="destructive"` (not overridable). There is **no** `className` prop and no `cancelText` override.
|
|
1873
|
+
|
|
1874
|
+
### `FormModal`
|
|
1875
|
+
|
|
1876
|
+
| Prop | Type | Default | Description |
|
|
1877
|
+
|------|------|---------|--------------|
|
|
1878
|
+
| `open` | `boolean` | - | Dialog visibility. |
|
|
1879
|
+
| `onOpenChange` | `function(open)` | - | Forwarded to `Modal`; also called directly with `false` when Cancel is clicked (there is no separate `onCancel` prop here). |
|
|
1880
|
+
| `onSubmit` | `function()` | - | Called (and awaited) on form submit — the body is wrapped in a real `<form onSubmit>`, so pressing Enter or clicking submit both trigger it. |
|
|
1881
|
+
| `title` | `string` | - | Forwarded to `Modal`. |
|
|
1882
|
+
| `description` | `string` | - | Forwarded to `Modal`. |
|
|
1883
|
+
| `children` | `node` | - | Form fields, rendered inside the `<form>`. |
|
|
1884
|
+
| `submitText` | `string` | `'Save'` | Submit button label (shows `'Saving...'` while `loading`). |
|
|
1885
|
+
| `cancelText` | `string` | `'Cancel'` | Cancel button label. |
|
|
1886
|
+
| `loading` | `boolean` | `false` | Disables both buttons and swaps the submit label to `'Saving...'`. |
|
|
1887
|
+
| `size` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | `'default'` | Forwarded to the internal `Modal`. |
|
|
1888
|
+
| `className` | `string` | - | Forwarded to the internal `Modal`. |
|
|
1889
|
+
|
|
1890
|
+
### Usage
|
|
1891
|
+
|
|
1892
|
+
```jsx
|
|
1893
|
+
import { Modal, ConfirmModal, DeleteConfirmModal, FormModal } from '@bomjan133/react-crud-ui';
|
|
1894
|
+
|
|
1895
|
+
<Modal
|
|
1896
|
+
open={isOpen}
|
|
1897
|
+
onOpenChange={setIsOpen}
|
|
1898
|
+
title="Modal Title"
|
|
1899
|
+
description="Modal description"
|
|
1900
|
+
size="lg"
|
|
1901
|
+
>
|
|
1902
|
+
<p>Modal body content</p>
|
|
1903
|
+
</Modal>
|
|
1904
|
+
|
|
1905
|
+
<ConfirmModal
|
|
1906
|
+
open={isConfirmOpen}
|
|
1907
|
+
onOpenChange={setIsConfirmOpen}
|
|
1908
|
+
onConfirm={handleConfirm}
|
|
1909
|
+
title="Confirm Action"
|
|
1910
|
+
description="Do you want to proceed?"
|
|
1911
|
+
confirmText="Yes, Continue"
|
|
1912
|
+
variant="default"
|
|
1913
|
+
loading={isConfirming}
|
|
1914
|
+
/>
|
|
1915
|
+
|
|
1916
|
+
<DeleteConfirmModal
|
|
1917
|
+
open={isDeleteOpen}
|
|
1918
|
+
onOpenChange={setIsDeleteOpen}
|
|
1919
|
+
onConfirm={handleDelete}
|
|
1920
|
+
itemName={selectedItem?.name ?? 'item'}
|
|
1921
|
+
loading={isDeleting}
|
|
1922
|
+
/>
|
|
1923
|
+
|
|
1924
|
+
<FormModal
|
|
1925
|
+
open={isFormOpen}
|
|
1926
|
+
onOpenChange={setIsFormOpen}
|
|
1927
|
+
onSubmit={handleSubmit}
|
|
1928
|
+
title="Edit Item"
|
|
1929
|
+
description="Update the item details below."
|
|
1930
|
+
loading={isSubmitting}
|
|
1931
|
+
size="lg"
|
|
1932
|
+
>
|
|
1933
|
+
<input name="name" defaultValue={item.name} />
|
|
1934
|
+
</FormModal>
|
|
1935
|
+
```
|
|
1936
|
+
|
|
1937
|
+
</details>
|
|
1938
|
+
|
|
1939
|
+
<a id="form-components"></a>
|
|
1940
|
+
<details>
|
|
1941
|
+
<summary><strong>4. Form Components Guide</strong></summary>
|
|
1942
|
+
|
|
1943
|
+
Complete reference for form field components in @bomjan133/react-crud-ui.
|
|
1944
|
+
|
|
1945
|
+
## Table of Contents
|
|
1946
|
+
1. [FormField](#formfield)
|
|
1947
|
+
2. [QInput](#qinput)
|
|
1948
|
+
3. [QTextarea](#qtextarea)
|
|
1949
|
+
4. [QSelect](#qselect)
|
|
1950
|
+
5. [QSearchSelect](#qsearchselect)
|
|
1951
|
+
6. [QSwitch](#qswitch)
|
|
1952
|
+
7. [QCheckbox](#qcheckbox)
|
|
1953
|
+
8. [QForm](#qform)
|
|
1954
|
+
9. [QDatePicker](#qdatepicker)
|
|
1955
|
+
10. [QDateRangePicker](#qdaterangepicker)
|
|
1956
|
+
11. [QRichTextEditor](#qrichtexteditor)
|
|
1957
|
+
12. [Form Validation](#form-validation)
|
|
1958
|
+
|
|
1959
|
+
All `Q*` components (except `QInput`) are thin wrappers around [`FormField`](#formfield) plus a Radix/native primitive — they share the `label`/`description`/`error`/`required` props documented once below.
|
|
1960
|
+
|
|
1961
|
+
Every `Q*` component also accepts a `helpText` prop as an alias for `description` — pass whichever name reads better at the call site. If both are passed, `description` wins.
|
|
1962
|
+
|
|
1963
|
+
---
|
|
1964
|
+
|
|
1965
|
+
## FormField
|
|
1966
|
+
|
|
1967
|
+
The base wrapper every `Q*` component (other than `QInput`, which lays itself out manually) renders through. Use it directly if you're wrapping a custom input that isn't covered by the `Q*` components.
|
|
1968
|
+
|
|
1969
|
+
### Props
|
|
1970
|
+
|
|
1971
|
+
| Prop | Type | Default | Description |
|
|
1972
|
+
|------|------|---------|-------------|
|
|
1973
|
+
| `label` | `string` | - | Label text |
|
|
1974
|
+
| `description` | `string` | - | Helper text shown below the field (hidden while `error` is set) |
|
|
1975
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
1976
|
+
| `error` | `string` | - | Error message; when set, also adds destructive-color styling to the first child input |
|
|
1977
|
+
| `required` | `boolean` | `false` | Shows a red `*` next to the label |
|
|
1978
|
+
| `children` | `node` | - | The input element(s) to wrap. The **first** child automatically receives `id`, `aria-invalid`, and error border styling |
|
|
1979
|
+
| `className` | `string` | - | Classes on the outer wrapper `div` |
|
|
1980
|
+
| `labelClassName` | `string` | - | Classes on the `Label` |
|
|
1981
|
+
| `descriptionClassName` | `string` | - | Classes on the description text |
|
|
1982
|
+
| `errorClassName` | `string` | - | Classes on the error text |
|
|
1983
|
+
|
|
1984
|
+
### Usage
|
|
1985
|
+
|
|
1986
|
+
```jsx
|
|
1987
|
+
import { FormField } from '@bomjan133/react-crud-ui';
|
|
1988
|
+
|
|
1989
|
+
<FormField label="Custom Field" description="Some helper text" error={errors.custom} required>
|
|
1990
|
+
<MyCustomInput value={value} onChange={setValue} />
|
|
1991
|
+
</FormField>
|
|
1992
|
+
```
|
|
1993
|
+
|
|
1994
|
+
---
|
|
1995
|
+
|
|
1996
|
+
## QInput
|
|
1997
|
+
|
|
1998
|
+
Text/number input with label and error handling. Unlike the other `Q*` components, `QInput` does **not** use `FormField` — it has its own layout, and in `type="number"` mode it renders a full increment/decrement spinner instead of a plain `<input>`.
|
|
1999
|
+
|
|
2000
|
+
### Props
|
|
2001
|
+
|
|
2002
|
+
| Prop | Type | Default | Description |
|
|
2003
|
+
|------|------|---------|-------------|
|
|
2004
|
+
| `label` | `string` | - | Label text |
|
|
2005
|
+
| `description` | `string` | - | Helper text shown below the input (hidden while `error` is set) |
|
|
2006
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2007
|
+
| `error` | `string` | - | Error message shown below the input |
|
|
2008
|
+
| `required` | `boolean` | `false` | Adds a red `*` next to the label |
|
|
2009
|
+
| `type` | `string` | - | Input type (`text`, `email`, `password`, `number`, etc.) — `'number'` switches to spinner mode |
|
|
2010
|
+
| `value` | `string \| number` | - | Input value |
|
|
2011
|
+
| `onChange` | `function` | - | Change handler. By default called with just the new value: `(value) => void`. Set `emitValue={false}` to instead receive the raw event: `(e) => void` |
|
|
2012
|
+
| `emitValue` | `boolean` | `true` | Whether `onChange` receives the value directly vs. the raw event |
|
|
2013
|
+
| `disabled` | `boolean` | `false` | Disable the input |
|
|
2014
|
+
| `className` | `string` | - | Classes on the outer wrapper |
|
|
2015
|
+
| `inputClassName` | `string` | - | Classes on the `<input>` itself |
|
|
2016
|
+
| `containerClassName` | `string` | - | Classes on the input's relative-position container (number mode) |
|
|
2017
|
+
| `buttonClassName` | `string` | - | Classes on the +/- spinner buttons (number mode only) |
|
|
2018
|
+
| `labelClassName` / `descriptionClassName` / `errorClassName` | `string` | - | Classes for those respective parts |
|
|
2019
|
+
| `icon` | `ReactNode` | - | Icon rendered inside the input (non-`number` mode only). When set, the input is wrapped in an `InputGroup` so the icon sits flush against the border |
|
|
2020
|
+
| `iconPosition` | `'prefix' \| 'postfix'` | `'prefix'` | Where `icon` is placed — `'prefix'` renders it before the text, `'postfix'` renders it after |
|
|
2021
|
+
| `...props` | - | - | Anything else (`name`, `placeholder`, `readOnly`, `onBlur`, etc.) passes through to the underlying `<input>` |
|
|
2022
|
+
|
|
2023
|
+
> **Not implemented:** `icon`/`iconPosition` have no effect in `type="number"` mode, since that mode renders its own increment/decrement spinner layout instead.
|
|
2024
|
+
|
|
2025
|
+
### Number mode props
|
|
2026
|
+
|
|
2027
|
+
Only apply when `type="number"`:
|
|
2028
|
+
|
|
2029
|
+
| Prop | Type | Default | Description |
|
|
2030
|
+
|------|------|---------|-------------|
|
|
2031
|
+
| `min` | `number` | `-Infinity` | Minimum value; also disables the decrement button at the floor |
|
|
2032
|
+
| `max` | `number` | `Infinity` | Maximum value; also disables the increment button at the ceiling |
|
|
2033
|
+
| `step` | `number` | `1` | Amount added/subtracted per spinner click |
|
|
2034
|
+
| `allowNegative` | `boolean` | `false` | Allow negative values/typing a leading `-` |
|
|
2035
|
+
| `width` | `string` | `'w-36'` | Tailwind width class applied to the numeric `<input>` between the spinner buttons |
|
|
2036
|
+
|
|
2037
|
+
`onChange` in number mode always emits a `number` (not a string), including on blur, where partial/empty input is normalized to `0` (or `min`, if `min > 0`).
|
|
2038
|
+
|
|
2039
|
+
### Usage
|
|
2040
|
+
|
|
2041
|
+
```jsx
|
|
2042
|
+
import { QInput } from '@bomjan133/react-crud-ui';
|
|
2043
|
+
|
|
2044
|
+
// Basic text input
|
|
2045
|
+
<QInput
|
|
2046
|
+
name="name"
|
|
2047
|
+
label="Full Name"
|
|
2048
|
+
value={form.name}
|
|
2049
|
+
onChange={(val) => setField('name', val)}
|
|
2050
|
+
placeholder="Enter your name"
|
|
2051
|
+
required
|
|
2052
|
+
/>
|
|
2053
|
+
|
|
2054
|
+
// With error
|
|
2055
|
+
<QInput
|
|
2056
|
+
name="email"
|
|
2057
|
+
label="Email"
|
|
2058
|
+
type="email"
|
|
2059
|
+
value={form.email}
|
|
2060
|
+
onChange={(val) => setField('email', val)}
|
|
2061
|
+
error={errors.email}
|
|
2062
|
+
placeholder="Enter email address"
|
|
2063
|
+
/>
|
|
2064
|
+
|
|
2065
|
+
// Number input with spinner, bounds, and step
|
|
2066
|
+
<QInput
|
|
2067
|
+
name="quantity"
|
|
2068
|
+
label="Quantity"
|
|
2069
|
+
type="number"
|
|
2070
|
+
value={form.quantity}
|
|
2071
|
+
onChange={(val) => setField('quantity', val)}
|
|
2072
|
+
min={1}
|
|
2073
|
+
max={100}
|
|
2074
|
+
step={1}
|
|
2075
|
+
/>
|
|
2076
|
+
|
|
2077
|
+
// Number input allowing negative values
|
|
2078
|
+
<QInput
|
|
2079
|
+
name="adjustment"
|
|
2080
|
+
label="Stock Adjustment"
|
|
2081
|
+
type="number"
|
|
2082
|
+
value={form.adjustment}
|
|
2083
|
+
onChange={(val) => setField('adjustment', val)}
|
|
2084
|
+
allowNegative
|
|
2085
|
+
/>
|
|
2086
|
+
|
|
2087
|
+
// Receive the raw event instead of the value
|
|
2088
|
+
<QInput
|
|
2089
|
+
name="search"
|
|
2090
|
+
label="Search"
|
|
2091
|
+
value={form.search}
|
|
2092
|
+
onChange={(e) => handleRawEvent(e)}
|
|
2093
|
+
emitValue={false}
|
|
2094
|
+
/>
|
|
2095
|
+
|
|
2096
|
+
// With a prefix icon
|
|
2097
|
+
<QInput
|
|
2098
|
+
name="search"
|
|
2099
|
+
label="Search"
|
|
2100
|
+
value={form.search}
|
|
2101
|
+
onChange={(val) => setField('search', val)}
|
|
2102
|
+
icon={<SearchIcon />}
|
|
2103
|
+
iconPosition="prefix"
|
|
2104
|
+
placeholder="Search..."
|
|
2105
|
+
/>
|
|
2106
|
+
|
|
2107
|
+
// With a postfix icon
|
|
2108
|
+
<QInput
|
|
2109
|
+
name="email"
|
|
2110
|
+
label="Email"
|
|
2111
|
+
type="email"
|
|
2112
|
+
value={form.email}
|
|
2113
|
+
onChange={(val) => setField('email', val)}
|
|
2114
|
+
icon={<MailIcon />}
|
|
2115
|
+
iconPosition="postfix"
|
|
2116
|
+
/>
|
|
2117
|
+
```
|
|
2118
|
+
|
|
2119
|
+
---
|
|
2120
|
+
|
|
2121
|
+
## QTextarea
|
|
2122
|
+
|
|
2123
|
+
Multi-line text input, wrapped in [`FormField`](#formfield).
|
|
2124
|
+
|
|
2125
|
+
### Props
|
|
2126
|
+
|
|
2127
|
+
| Prop | Type | Default | Description |
|
|
2128
|
+
|------|------|---------|-------------|
|
|
2129
|
+
| `label` | `string` | - | Label text |
|
|
2130
|
+
| `description` | `string` | - | Helper text |
|
|
2131
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2132
|
+
| `error` | `string` | - | Error message |
|
|
2133
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2134
|
+
| `value` | `string` | - | Input value |
|
|
2135
|
+
| `onChange` | `function` | - | Change handler — `(value) => void` by default, `(e) => void` if `emitValue={false}` |
|
|
2136
|
+
| `emitValue` | `boolean` | `true` | Whether `onChange` receives the value directly vs. the raw event |
|
|
2137
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2138
|
+
| `textareaClassName` | `string` | - | Classes on the `<textarea>` itself |
|
|
2139
|
+
| `...props` | - | - | Anything else (`rows`, `placeholder`, `disabled`, `maxLength`, etc.) passes through to the underlying `<textarea>` as native HTML attributes |
|
|
2140
|
+
|
|
2141
|
+
|
|
2142
|
+
### Usage
|
|
2143
|
+
|
|
2144
|
+
```jsx
|
|
2145
|
+
import { QTextarea } from '@bomjan133/react-crud-ui';
|
|
2146
|
+
|
|
2147
|
+
// Basic textarea
|
|
2148
|
+
<QTextarea
|
|
2149
|
+
name="description"
|
|
2150
|
+
label="Description"
|
|
2151
|
+
value={form.description}
|
|
2152
|
+
onChange={(val) => setField('description', val)}
|
|
2153
|
+
placeholder="Enter description"
|
|
2154
|
+
rows={4}
|
|
2155
|
+
/>
|
|
2156
|
+
|
|
2157
|
+
// With a manual character count
|
|
2158
|
+
<QTextarea
|
|
2159
|
+
name="bio"
|
|
2160
|
+
label="Bio"
|
|
2161
|
+
value={form.bio}
|
|
2162
|
+
onChange={(val) => setField('bio', val)}
|
|
2163
|
+
maxLength={500}
|
|
2164
|
+
placeholder="Tell us about yourself..."
|
|
2165
|
+
description={`${form.bio?.length ?? 0}/500`}
|
|
2166
|
+
/>
|
|
2167
|
+
```
|
|
2168
|
+
|
|
2169
|
+
---
|
|
2170
|
+
|
|
2171
|
+
## QSelect
|
|
2172
|
+
|
|
2173
|
+
Dropdown select (built on the Radix `Select` primitive) for choosing a single value from a static list, wrapped in [`FormField`](#formfield).
|
|
2174
|
+
|
|
2175
|
+
### Props
|
|
2176
|
+
|
|
2177
|
+
| Prop | Type | Default | Description |
|
|
2178
|
+
|------|------|---------|-------------|
|
|
2179
|
+
| `label` | `string` | - | Label text |
|
|
2180
|
+
| `description` | `string` | - | Helper text |
|
|
2181
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2182
|
+
| `error` | `string` | - | Error message |
|
|
2183
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2184
|
+
| `options` | `array` | `[]` | Array of options (objects or primitives) |
|
|
2185
|
+
| `value` | `any` | - | Selected value (compared as a string internally) |
|
|
2186
|
+
| `onChange` | `function` | - | Value change handler — `(value: string) => void` |
|
|
2187
|
+
| `optionLabel` | `string \| function` | - | Key name, or `(option) => label`, for display text. Falls back to `option.label ?? option.name ?? String(option)` |
|
|
2188
|
+
| `optionValue` | `string \| function` | - | Key name, or `(option) => value`, for the option's value. Falls back to `option.value ?? option.id ?? option` |
|
|
2189
|
+
| `getOptionLabel` | `function` | - | Alternative to `optionLabel` — takes precedence if both are given |
|
|
2190
|
+
| `getOptionValue` | `function` | - | Alternative to `optionValue` — takes precedence if both are given |
|
|
2191
|
+
| `placeholder` | `string` | `'Select...'` | Placeholder text |
|
|
2192
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2193
|
+
| `selectTriggerClassName` | `string` | - | Classes on the trigger button |
|
|
2194
|
+
| `selectContentClassName` | `string` | - | Classes on the dropdown content panel |
|
|
2195
|
+
| `selectItemClassName` | `string` | - | Classes on each option item |
|
|
2196
|
+
| `...props` | - | - | Anything else (`disabled`, etc.) passes through to the underlying Radix `Select` |
|
|
2197
|
+
|
|
2198
|
+
|
|
2199
|
+
### Usage
|
|
2200
|
+
|
|
2201
|
+
```jsx
|
|
2202
|
+
import { QSelect } from '@bomjan133/react-crud-ui';
|
|
2203
|
+
|
|
2204
|
+
// With simple options
|
|
2205
|
+
const statusOptions = [
|
|
2206
|
+
{ value: 'active', label: 'Active' },
|
|
2207
|
+
{ value: 'inactive', label: 'Inactive' },
|
|
2208
|
+
{ value: 'pending', label: 'Pending' },
|
|
2209
|
+
];
|
|
2210
|
+
|
|
2211
|
+
<QSelect
|
|
2212
|
+
name="status"
|
|
2213
|
+
label="Status"
|
|
2214
|
+
value={form.status}
|
|
2215
|
+
onChange={(val) => setField('status', val)}
|
|
2216
|
+
options={statusOptions}
|
|
2217
|
+
placeholder="Select status"
|
|
2218
|
+
/>
|
|
2219
|
+
|
|
2220
|
+
// With object options and a custom key
|
|
2221
|
+
const categories = [
|
|
2222
|
+
{ id: 1, name: 'Electronics' },
|
|
2223
|
+
{ id: 2, name: 'Clothing' },
|
|
2224
|
+
{ id: 3, name: 'Books' },
|
|
2225
|
+
];
|
|
2226
|
+
|
|
2227
|
+
<QSelect
|
|
2228
|
+
name="category_id"
|
|
2229
|
+
label="Category"
|
|
2230
|
+
value={form.category_id}
|
|
2231
|
+
onChange={(val) => setField('category_id', val)}
|
|
2232
|
+
options={categories}
|
|
2233
|
+
optionLabel="name"
|
|
2234
|
+
optionValue="id"
|
|
2235
|
+
placeholder="Select category"
|
|
2236
|
+
/>
|
|
2237
|
+
|
|
2238
|
+
// With function-based getters
|
|
2239
|
+
<QSelect
|
|
2240
|
+
name="user_id"
|
|
2241
|
+
label="Assigned To"
|
|
2242
|
+
value={form.user_id}
|
|
2243
|
+
onChange={(val) => setField('user_id', val)}
|
|
2244
|
+
options={users}
|
|
2245
|
+
getOptionLabel={(u) => `${u.firstName} ${u.lastName}`}
|
|
2246
|
+
getOptionValue={(u) => u.id}
|
|
2247
|
+
error={errors.user_id}
|
|
2248
|
+
required
|
|
2249
|
+
/>
|
|
2250
|
+
```
|
|
2251
|
+
|
|
2252
|
+
---
|
|
2253
|
+
|
|
2254
|
+
## QSearchSelect
|
|
2255
|
+
|
|
2256
|
+
Searchable select with client-side filtering, async search, multi-select, and infinite-scroll pagination — built on the custom `SearchSelect` primitive, wrapped in [`FormField`](#formfield).
|
|
2257
|
+
|
|
2258
|
+
### Props
|
|
2259
|
+
|
|
2260
|
+
| Prop | Type | Default | Description |
|
|
2261
|
+
|------|------|---------|-------------|
|
|
2262
|
+
| `label` | `string` | - | Label text |
|
|
2263
|
+
| `description` | `string` | - | Helper text |
|
|
2264
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2265
|
+
| `error` | `string` | - | Error message |
|
|
2266
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2267
|
+
| `value` | `any` | - | Selected value — a single value normally, an array when `multiple` |
|
|
2268
|
+
| `onChange` | `function` | - | Change handler. Single mode: `(value) => void`. Multi mode: `(values: array) => void` |
|
|
2269
|
+
| `options` | `array` | `[]` | Array of options (objects or primitives) |
|
|
2270
|
+
| `optionLabel` / `optionValue` | `string \| function` | - | Same resolution rules as [`QSelect`](#qselect) |
|
|
2271
|
+
| `getOptionLabel` / `getOptionValue` | `function` | - | Same as `QSelect` — take precedence over `optionLabel`/`optionValue` |
|
|
2272
|
+
| `onSearch` | `function` | - | Debounced (300ms) search handler — `(query: string) => void`. Use this to trigger an async fetch and update `options` |
|
|
2273
|
+
| `multiple` | `boolean` | `false` | Allow multiple selections; `onChange`/`value` become arrays |
|
|
2274
|
+
| `onLoadMore` | `function` | - | `() => Promise` — called when the dropdown list is scrolled near the bottom, for infinite-scroll pagination |
|
|
2275
|
+
| `hasMore` | `boolean` | `false` | Whether more pages are available (controls whether `onLoadMore` can fire again) |
|
|
2276
|
+
| `loadingMore` | `boolean` | `false` | Shows a loading row at the bottom of the list while a `onLoadMore` page is in flight |
|
|
2277
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2278
|
+
| `searchSelectClassName` | `string` | - | Classes on the `SearchSelect` root |
|
|
2279
|
+
| `searchSelectTriggerClassName` | `string` | - | Classes on the trigger button |
|
|
2280
|
+
| `...props` | - | - | Anything else (`loading`, `disabled`, `renderOption`, `renderValue`, `filterOption`, `noOptionsMessage`, `loadingMessage`, etc.) passes through to the underlying `SearchSelect` |
|
|
2281
|
+
|
|
2282
|
+
> **Selection survives search filtering:** `QSearchSelect` internally caches every full option object it has ever seen (by value), so a previously-selected item keeps displaying its label even if it later scrolls out of the current (filtered or paginated) `options` list.
|
|
2283
|
+
|
|
2284
|
+
### Usage
|
|
2285
|
+
|
|
2286
|
+
```jsx
|
|
2287
|
+
import { QSearchSelect } from '@bomjan133/react-crud-ui';
|
|
2288
|
+
import { searchUsers } from '@/api';
|
|
2289
|
+
|
|
2290
|
+
// Async search select
|
|
2291
|
+
const [users, setUsers] = useState([]);
|
|
2292
|
+
const [loading, setLoading] = useState(false);
|
|
2293
|
+
|
|
2294
|
+
const handleUserSearch = async (query) => {
|
|
2295
|
+
setLoading(true);
|
|
2296
|
+
try {
|
|
2297
|
+
setUsers(await searchUsers(query));
|
|
2298
|
+
} finally {
|
|
2299
|
+
setLoading(false);
|
|
2300
|
+
}
|
|
2301
|
+
};
|
|
2302
|
+
|
|
2303
|
+
<QSearchSelect
|
|
2304
|
+
name="user_id"
|
|
2305
|
+
label="Assign User"
|
|
2306
|
+
value={form.user_id}
|
|
2307
|
+
onChange={(val) => setField('user_id', val)}
|
|
2308
|
+
options={users}
|
|
2309
|
+
optionLabel="name"
|
|
2310
|
+
optionValue="id"
|
|
2311
|
+
onSearch={handleUserSearch}
|
|
2312
|
+
loading={loading}
|
|
2313
|
+
placeholder="Search users..."
|
|
2314
|
+
/>
|
|
2315
|
+
|
|
2316
|
+
// Multiple selection
|
|
2317
|
+
<QSearchSelect
|
|
2318
|
+
name="tags"
|
|
2319
|
+
label="Tags"
|
|
2320
|
+
value={form.tags}
|
|
2321
|
+
onChange={(val) => setField('tags', val)}
|
|
2322
|
+
options={tags}
|
|
2323
|
+
optionLabel="name"
|
|
2324
|
+
optionValue="id"
|
|
2325
|
+
multiple
|
|
2326
|
+
placeholder="Select tags..."
|
|
2327
|
+
/>
|
|
2328
|
+
|
|
2329
|
+
// Infinite scroll pagination
|
|
2330
|
+
const [items, setItems] = useState([]);
|
|
2331
|
+
const [page, setPage] = useState(1);
|
|
2332
|
+
const [hasMore, setHasMore] = useState(true);
|
|
2333
|
+
const [loadingMore, setLoadingMore] = useState(false);
|
|
2334
|
+
|
|
2335
|
+
const loadMore = async () => {
|
|
2336
|
+
const next = page + 1;
|
|
2337
|
+
const results = await fetchItems({ page: next });
|
|
2338
|
+
setItems((prev) => [...prev, ...results.data]);
|
|
2339
|
+
setHasMore(results.hasMore);
|
|
2340
|
+
setPage(next);
|
|
2341
|
+
};
|
|
2342
|
+
|
|
2343
|
+
<QSearchSelect
|
|
2344
|
+
name="item_id"
|
|
2345
|
+
label="Item"
|
|
2346
|
+
value={form.item_id}
|
|
2347
|
+
onChange={(val) => setField('item_id', val)}
|
|
2348
|
+
options={items}
|
|
2349
|
+
onLoadMore={loadMore}
|
|
2350
|
+
hasMore={hasMore}
|
|
2351
|
+
loadingMore={loadingMore}
|
|
2352
|
+
/>
|
|
2353
|
+
```
|
|
2354
|
+
|
|
2355
|
+
---
|
|
2356
|
+
|
|
2357
|
+
## QSwitch
|
|
2358
|
+
|
|
2359
|
+
Toggle switch for boolean values, built on the Radix `Switch` primitive.
|
|
2360
|
+
|
|
2361
|
+
### Props
|
|
2362
|
+
|
|
2363
|
+
| Prop | Type | Default | Description |
|
|
2364
|
+
|------|------|---------|-------------|
|
|
2365
|
+
| `label` | `string` | - | Label text |
|
|
2366
|
+
| `description` | `string` | - | Helper text below the label |
|
|
2367
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2368
|
+
| `error` | `string` | - | Error message |
|
|
2369
|
+
| `checked` | `boolean` | `false` | Switch state |
|
|
2370
|
+
| `onChange` | `function` | - | State change handler — `(checked: boolean) => void` |
|
|
2371
|
+
| `onCheckedChange` | `function` | - | Alternative handler name (Radix convention); both fire if both are passed |
|
|
2372
|
+
| `className` | `string` | - | Classes on the outer flex container |
|
|
2373
|
+
| `switchClassName` | `string` | - | Classes on the switch root |
|
|
2374
|
+
| `switchThumbClassName` | `string` | - | Classes on the switch thumb |
|
|
2375
|
+
| `...props` | - | - | Anything else (`disabled`, etc.) passes through to the underlying `Switch` |
|
|
2376
|
+
|
|
2377
|
+
### Usage
|
|
2378
|
+
|
|
2379
|
+
```jsx
|
|
2380
|
+
import { QSwitch } from '@bomjan133/react-crud-ui';
|
|
2381
|
+
|
|
2382
|
+
<QSwitch
|
|
2383
|
+
label="Active"
|
|
2384
|
+
checked={form.is_active}
|
|
2385
|
+
onChange={(val) => setField('is_active', val)}
|
|
2386
|
+
/>
|
|
2387
|
+
|
|
2388
|
+
<QSwitch
|
|
2389
|
+
label="Email Notifications"
|
|
2390
|
+
description="Receive email notifications for new orders"
|
|
2391
|
+
checked={form.email_notifications}
|
|
2392
|
+
onChange={(val) => setField('email_notifications', val)}
|
|
2393
|
+
disabled={!form.email_verified}
|
|
2394
|
+
/>
|
|
2395
|
+
```
|
|
2396
|
+
|
|
2397
|
+
---
|
|
2398
|
+
|
|
2399
|
+
## QCheckbox
|
|
2400
|
+
|
|
2401
|
+
Checkbox with label, built on the Radix `Checkbox` primitive.
|
|
2402
|
+
|
|
2403
|
+
### Props
|
|
2404
|
+
|
|
2405
|
+
| Prop | Type | Default | Description |
|
|
2406
|
+
|------|------|---------|-------------|
|
|
2407
|
+
| `label` | `string` | - | Label text |
|
|
2408
|
+
| `description` | `string` | - | Helper text below the label |
|
|
2409
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2410
|
+
| `error` | `string` | - | Error message |
|
|
2411
|
+
| `checked` | `boolean` | `false` | Checkbox state |
|
|
2412
|
+
| `onCheckedChange` | `function` | - | State change handler — `(checked: boolean) => void` |
|
|
2413
|
+
| `className` | `string` | - | Classes on the outer flex container |
|
|
2414
|
+
| `checkboxClassName` | `string` | - | Classes on the checkbox itself |
|
|
2415
|
+
| `...props` | - | - | Anything else (`disabled`, etc.) passes through to the underlying `Checkbox` |
|
|
2416
|
+
|
|
2417
|
+
> **Use `onCheckedChange`, not `onChange`:** `QCheckbox` only wires up `onCheckedChange` (matching the underlying Radix `Checkbox` API) — passing `onChange` instead is silently ignored. There is also no built-in `indeterminate` prop.
|
|
2418
|
+
|
|
2419
|
+
### Usage
|
|
2420
|
+
|
|
2421
|
+
```jsx
|
|
2422
|
+
import { QCheckbox } from '@bomjan133/react-crud-ui';
|
|
2423
|
+
|
|
2424
|
+
<QCheckbox
|
|
2425
|
+
label="I agree to the terms and conditions"
|
|
2426
|
+
checked={form.agree}
|
|
2427
|
+
onCheckedChange={(val) => setField('agree', val)}
|
|
2428
|
+
/>
|
|
2429
|
+
|
|
2430
|
+
// Checkbox group
|
|
2431
|
+
const permissions = ['read', 'write', 'delete', 'admin'];
|
|
2432
|
+
|
|
2433
|
+
<div className="space-y-2">
|
|
2434
|
+
<label className="text-sm font-medium">Permissions</label>
|
|
2435
|
+
{permissions.map((perm) => (
|
|
2436
|
+
<QCheckbox
|
|
2437
|
+
key={perm}
|
|
2438
|
+
label={perm.charAt(0).toUpperCase() + perm.slice(1)}
|
|
2439
|
+
checked={form.permissions?.includes(perm)}
|
|
2440
|
+
onCheckedChange={(checked) => {
|
|
2441
|
+
const newPerms = checked
|
|
2442
|
+
? [...(form.permissions || []), perm]
|
|
2443
|
+
: form.permissions?.filter((p) => p !== perm);
|
|
2444
|
+
setField('permissions', newPerms);
|
|
2445
|
+
}}
|
|
2446
|
+
/>
|
|
2447
|
+
))}
|
|
2448
|
+
</div>
|
|
2449
|
+
```
|
|
2450
|
+
|
|
2451
|
+
---
|
|
2452
|
+
|
|
2453
|
+
## QForm
|
|
2454
|
+
|
|
2455
|
+
Thin `<form>` wrapper that calls `preventDefault()` for you before invoking `onSubmit`.
|
|
2456
|
+
|
|
2457
|
+
### Props
|
|
2458
|
+
|
|
2459
|
+
| Prop | Type | Default | Description |
|
|
2460
|
+
|------|------|---------|-------------|
|
|
2461
|
+
| `onSubmit` | `function` | - | Called with the (already `preventDefault`-ed) submit event: `(e) => void` |
|
|
2462
|
+
| `className` | `string` | - | Classes on the `<form>` (defaults include `space-y-4`) |
|
|
2463
|
+
| `children` | `node` | - | Form fields |
|
|
2464
|
+
| `...props` | - | - | Anything else passes through to the native `<form>` element |
|
|
2465
|
+
|
|
2466
|
+
### Usage
|
|
2467
|
+
|
|
2468
|
+
```jsx
|
|
2469
|
+
import { QForm, QInput } from '@bomjan133/react-crud-ui';
|
|
2470
|
+
|
|
2471
|
+
<QForm onSubmit={() => handleSave(form)}>
|
|
2472
|
+
<QInput name="name" label="Name" value={form.name} onChange={(v) => setField('name', v)} />
|
|
2473
|
+
<button type="submit">Save</button>
|
|
2474
|
+
</QForm>
|
|
2475
|
+
```
|
|
2476
|
+
|
|
2477
|
+
---
|
|
2478
|
+
|
|
2479
|
+
## QDatePicker
|
|
2480
|
+
|
|
2481
|
+
Single date picker combining a typeable `yyyy-MM-dd` text field with a calendar popover, wrapped in [`FormField`](#formfield).
|
|
2482
|
+
|
|
2483
|
+
### Props
|
|
2484
|
+
|
|
2485
|
+
| Prop | Type | Default | Description |
|
|
2486
|
+
|------|------|---------|-------------|
|
|
2487
|
+
| `label` | `string` | - | Label text |
|
|
2488
|
+
| `description` | `string` | - | Helper text |
|
|
2489
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2490
|
+
| `error` | `string` | - | Error message |
|
|
2491
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2492
|
+
| `value` | `Date \| string` | - | Selected date. Accepts a `Date`, a `yyyy-MM-dd` string, or an ISO string |
|
|
2493
|
+
| `onChange` | `function` | - | Change handler — `(value: string | undefined) => void`. See output format below |
|
|
2494
|
+
| `placeholder` | `string` | `'Pick a date'` | Placeholder shown when empty |
|
|
2495
|
+
| `clearable` | `boolean` | `true` | Show a clear (`×`) button once a date is selected |
|
|
2496
|
+
| `sendUTC` | `boolean` | `false` | Changes the `onChange` output format — see below |
|
|
2497
|
+
| `minDate` / `maxDate` | `Date \| string` | - | Disables calendar days outside this range and rejects typed dates outside it (shows an inline error under the field) |
|
|
2498
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2499
|
+
| `...props` | - | - | Anything else passes through to the underlying trigger button |
|
|
2500
|
+
|
|
2501
|
+
### Output format
|
|
2502
|
+
|
|
2503
|
+
`onChange` is always called with a **string**, never a `Date` object:
|
|
2504
|
+
- `sendUTC={false}` (default): `'yyyy-MM-dd'`, e.g. `'2026-07-12'`
|
|
2505
|
+
- `sendUTC={true}`: a full UTC ISO string, e.g. `'2026-07-12T00:00:00.000Z'`
|
|
2506
|
+
|
|
2507
|
+
There is no `format` prop — the input/output format is fixed as above; only the *displayed* calendar month/labels use `date-fns` formatting internally.
|
|
2508
|
+
|
|
2509
|
+
### Usage
|
|
2510
|
+
|
|
2511
|
+
```jsx
|
|
2512
|
+
import { QDatePicker } from '@bomjan133/react-crud-ui';
|
|
2513
|
+
|
|
2514
|
+
<QDatePicker
|
|
2515
|
+
name="date"
|
|
2516
|
+
label="Event Date"
|
|
2517
|
+
value={form.date}
|
|
2518
|
+
onChange={(val) => setField('date', val)}
|
|
2519
|
+
/>
|
|
2520
|
+
|
|
2521
|
+
// With min/max bounds
|
|
2522
|
+
<QDatePicker
|
|
2523
|
+
name="start_date"
|
|
2524
|
+
label="Start Date"
|
|
2525
|
+
value={form.start_date}
|
|
2526
|
+
onChange={(val) => setField('start_date', val)}
|
|
2527
|
+
minDate={new Date()}
|
|
2528
|
+
maxDate={new Date(2027, 11, 31)}
|
|
2529
|
+
/>
|
|
2530
|
+
|
|
2531
|
+
// Send full UTC timestamps instead of yyyy-MM-dd
|
|
2532
|
+
<QDatePicker
|
|
2533
|
+
name="published_at"
|
|
2534
|
+
label="Publish Date"
|
|
2535
|
+
value={form.published_at}
|
|
2536
|
+
onChange={(val) => setField('published_at', val)}
|
|
2537
|
+
sendUTC
|
|
2538
|
+
/>
|
|
2539
|
+
```
|
|
2540
|
+
|
|
2541
|
+
---
|
|
2542
|
+
|
|
2543
|
+
## QDateRangePicker
|
|
2544
|
+
|
|
2545
|
+
Date range picker with quick presets (last 7 days, this month, etc.) and a click-twice range selection in the calendar, wrapped in [`FormField`](#formfield).
|
|
2546
|
+
|
|
2547
|
+
### Props
|
|
2548
|
+
|
|
2549
|
+
| Prop | Type | Default | Description |
|
|
2550
|
+
|------|------|---------|-------------|
|
|
2551
|
+
| `label` | `string` | - | Label text |
|
|
2552
|
+
| `description` | `string` | - | Helper text |
|
|
2553
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2554
|
+
| `error` | `string` | - | Error message |
|
|
2555
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2556
|
+
| `value` | `{ from, to }` | - | Selected range |
|
|
2557
|
+
| `onChange` | `function` | - | Change handler — `({ from, to }) => void`. See output format below |
|
|
2558
|
+
| `placeholder` | `string` | `'Pick a date range'` | Placeholder shown when empty |
|
|
2559
|
+
| `clearable` | `boolean` | `true` | Show a clear button once a range is selected |
|
|
2560
|
+
| `sendUTC` | `boolean` | `false` | Changes the `onChange` output format — see below |
|
|
2561
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2562
|
+
| `datePickerTriggerClassName` | `string` | - | Classes on the trigger button |
|
|
2563
|
+
| `...props` | - | - | Anything else passes through to the underlying trigger button |
|
|
2564
|
+
|
|
2565
|
+
### Output format
|
|
2566
|
+
|
|
2567
|
+
The selection only commits when the user clicks **Apply** in the popover (picking two calendar days stages the range first). `onChange` then receives:
|
|
2568
|
+
- `sendUTC={false}` (default): `{ from: 'yyyy-MM-dd', to: 'yyyy-MM-dd' }`
|
|
2569
|
+
- `sendUTC={true}`: `{ from: ISOString, to: ISOString }`
|
|
2570
|
+
|
|
2571
|
+
> There is no `minDate`/`maxDate` support on `QDateRangePicker` (unlike `QDatePicker`) — all days are selectable.
|
|
2572
|
+
|
|
2573
|
+
### Usage
|
|
2574
|
+
|
|
2575
|
+
```jsx
|
|
2576
|
+
import { QDateRangePicker } from '@bomjan133/react-crud-ui';
|
|
2577
|
+
|
|
2578
|
+
<QDateRangePicker
|
|
2579
|
+
name="date_range"
|
|
2580
|
+
label="Date Range"
|
|
2581
|
+
value={form.date_range}
|
|
2582
|
+
onChange={(val) => setField('date_range', val)}
|
|
2583
|
+
/>
|
|
2584
|
+
```
|
|
2585
|
+
|
|
2586
|
+
---
|
|
2587
|
+
|
|
2588
|
+
## QRichTextEditor
|
|
2589
|
+
|
|
2590
|
+
Rich text editor (built on [`suneditor-react`](https://github.com/mkhstar/suneditor-react)) with a full formatting toolbar, wrapped in [`FormField`](#formfield).
|
|
2591
|
+
|
|
2592
|
+
### Props
|
|
2593
|
+
|
|
2594
|
+
| Prop | Type | Default | Description |
|
|
2595
|
+
|------|------|---------|-------------|
|
|
2596
|
+
| `label` | `string` | - | Label text |
|
|
2597
|
+
| `description` | `string` | - | Helper text |
|
|
2598
|
+
| `helpText` | `string` | - | Alias for `description` — used if `description` isn't passed |
|
|
2599
|
+
| `error` | `string` | - | Error message |
|
|
2600
|
+
| `required` | `boolean` | `false` | Mark as required |
|
|
2601
|
+
| `value` | `string` | `''` | HTML content |
|
|
2602
|
+
| `onChange` | `function` | - | Content change handler — `(html: string) => void` |
|
|
2603
|
+
| `placeholder` | `string` | `'Start writing...'` | Placeholder text |
|
|
2604
|
+
| `height` | `string` | `'200px'` | Editor height |
|
|
2605
|
+
| `className` | `string` | - | Classes on the `FormField` wrapper |
|
|
2606
|
+
| `editorClassName` | `string` | - | Classes on the editor container |
|
|
2607
|
+
| `editorToolbarClassName` | `string` | - | Classes on the toolbar |
|
|
2608
|
+
| `...props` | - | - | Anything else passes through to `SunEditorReact` |
|
|
2609
|
+
|
|
2610
|
+
### Usage
|
|
2611
|
+
|
|
2612
|
+
```jsx
|
|
2613
|
+
import { QRichTextEditor } from '@bomjan133/react-crud-ui';
|
|
2614
|
+
|
|
2615
|
+
<QRichTextEditor
|
|
2616
|
+
name="content"
|
|
2617
|
+
label="Content"
|
|
2618
|
+
value={form.content}
|
|
2619
|
+
onChange={(val) => setField('content', val)}
|
|
2620
|
+
placeholder="Start writing your content..."
|
|
2621
|
+
height="300px"
|
|
2622
|
+
/>
|
|
2623
|
+
```
|
|
2624
|
+
|
|
2625
|
+
### Toolbar Features
|
|
2626
|
+
|
|
2627
|
+
The editor includes a comprehensive toolbar with the following features:
|
|
2628
|
+
|
|
2629
|
+
- **Text Formatting**: Bold, italic, underline, strike, subscript, superscript
|
|
2630
|
+
- **Font**: Font family, size, color, background color
|
|
2631
|
+
- **Paragraph**: Headings, blockquotes, alignment, line height
|
|
2632
|
+
- **Lists**: Ordered and unordered lists
|
|
2633
|
+
- **Links**: Insert and edit links
|
|
2634
|
+
- **Media**: Images, videos, audio files
|
|
2635
|
+
- **Tables**: Create and edit tables
|
|
2636
|
+
- **Code**: Code view, full screen mode
|
|
2637
|
+
- **Templates**: Predefined templates
|
|
2638
|
+
- **Undo/Redo**: History management
|
|
2639
|
+
|
|
2640
|
+
---
|
|
2641
|
+
|
|
2642
|
+
## Form Validation
|
|
2643
|
+
|
|
2644
|
+
### Client-Side Validation
|
|
2645
|
+
|
|
2646
|
+
Use the `onBeforeSubmit` prop to validate before submission:
|
|
2647
|
+
|
|
2648
|
+
```jsx
|
|
2649
|
+
<CrudForm
|
|
2650
|
+
onBeforeSubmit={(data) => {
|
|
2651
|
+
const errors = {};
|
|
2652
|
+
|
|
2653
|
+
if (!data.name?.trim()) {
|
|
2654
|
+
errors.name = 'Name is required';
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
if (!data.email?.trim()) {
|
|
2658
|
+
errors.email = 'Email is required';
|
|
2659
|
+
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
|
|
2660
|
+
errors.email = 'Invalid email format';
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
if (Object.keys(errors).length > 0) {
|
|
2664
|
+
// Set errors in store
|
|
2665
|
+
setFormErrors(errors);
|
|
2666
|
+
return false; // Prevent submission
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
return data; // Return transformed data
|
|
2670
|
+
}}
|
|
2671
|
+
>
|
|
2672
|
+
{/* Form fields */}
|
|
2673
|
+
</CrudForm>
|
|
2674
|
+
```
|
|
2675
|
+
|
|
2676
|
+
### Server-Side Validation
|
|
2677
|
+
|
|
2678
|
+
Handle API validation errors:
|
|
2679
|
+
|
|
2680
|
+
```jsx
|
|
2681
|
+
// In your store
|
|
2682
|
+
create: async (data) => {
|
|
2683
|
+
try {
|
|
2684
|
+
const response = await api.post('/items', data);
|
|
2685
|
+
return response.data;
|
|
2686
|
+
} catch (error) {
|
|
2687
|
+
if (error.response?.status === 422) {
|
|
2688
|
+
// Validation errors
|
|
2689
|
+
const errors = error.response.data.errors;
|
|
2690
|
+
set({ form: { ...get().form, errors } });
|
|
2691
|
+
}
|
|
2692
|
+
throw error;
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
```
|
|
2696
|
+
|
|
2697
|
+
### Form State Management
|
|
2698
|
+
|
|
2699
|
+
The store provides form state management:
|
|
2700
|
+
|
|
2701
|
+
```jsx
|
|
2702
|
+
const store = useStore();
|
|
2703
|
+
|
|
2704
|
+
// Access form state
|
|
2705
|
+
const { values, errors, loading } = store.form;
|
|
2706
|
+
|
|
2707
|
+
// Set field value
|
|
2708
|
+
store.setFormField('name', 'New Value');
|
|
2709
|
+
|
|
2710
|
+
// Set multiple fields
|
|
2711
|
+
store.setFormFields({ name: 'John', email: 'john@example.com' });
|
|
2712
|
+
|
|
2713
|
+
// Set errors
|
|
2714
|
+
store.setFormErrors({ name: 'Required' });
|
|
2715
|
+
|
|
2716
|
+
// Reset form
|
|
2717
|
+
store.resetForm();
|
|
2718
|
+
```
|
|
2719
|
+
|
|
2720
|
+
</details>
|
|
2721
|
+
|
|
2722
|
+
<a id="layout-components"></a>
|
|
2723
|
+
<details>
|
|
2724
|
+
<summary><strong>5. Layout Components Guide</strong></summary>
|
|
2725
|
+
|
|
2726
|
+
Complete reference for layout components in @bomjan133/react-crud-ui.
|
|
2727
|
+
|
|
2728
|
+
## Table of Contents
|
|
2729
|
+
1. [AuthLayout](#authlayout)
|
|
2730
|
+
2. [LoginPage](#loginpage)
|
|
2731
|
+
3. [DashboardLayout](#dashboardlayout)
|
|
2732
|
+
4. [SidebarProvider](#sidebarprovider)
|
|
2733
|
+
|
|
2734
|
+
---
|
|
2735
|
+
|
|
2736
|
+
## AuthLayout
|
|
2737
|
+
|
|
2738
|
+
A centered layout for authentication pages (login, register, forgot password).
|
|
2739
|
+
|
|
2740
|
+
### Props
|
|
2741
|
+
|
|
2742
|
+
| Prop | Type | Default | Description |
|
|
2743
|
+
|------|------|---------|-------------|
|
|
2744
|
+
| `children` | `node` | - | Content to render |
|
|
2745
|
+
| `className` | `string` | - | Additional CSS classes |
|
|
2746
|
+
|
|
2747
|
+
### Usage
|
|
2748
|
+
|
|
2749
|
+
```jsx
|
|
2750
|
+
import { AuthLayout } from '@bomjan133/react-crud-ui';
|
|
2751
|
+
|
|
2752
|
+
function LoginPage() {
|
|
2753
|
+
return (
|
|
2754
|
+
<AuthLayout>
|
|
2755
|
+
<div className="w-full max-w-md space-y-6 p-8 bg-white rounded-lg shadow">
|
|
2756
|
+
<h1 className="text-2xl font-bold text-center">Login</h1>
|
|
2757
|
+
{/* Login form */}
|
|
2758
|
+
</div>
|
|
2759
|
+
</AuthLayout>
|
|
2760
|
+
);
|
|
2761
|
+
}
|
|
2762
|
+
```
|
|
2763
|
+
|
|
2764
|
+
### Styling
|
|
2765
|
+
|
|
2766
|
+
The AuthLayout provides:
|
|
2767
|
+
- Full viewport height centered container
|
|
2768
|
+
- Gradient background
|
|
2769
|
+
- Responsive padding
|
|
2770
|
+
- Dark mode support
|
|
2771
|
+
|
|
2772
|
+
---
|
|
2773
|
+
|
|
2774
|
+
## LoginPage
|
|
2775
|
+
|
|
2776
|
+
A complete, styled login page component.
|
|
2777
|
+
|
|
2778
|
+
### Props
|
|
2779
|
+
|
|
2780
|
+
| Prop | Type | Default | Description |
|
|
2781
|
+
|------|------|---------|-------------|
|
|
2782
|
+
| `onSubmit` | `function` | - | Form submit handler `({ email, password }) => Promise` |
|
|
2783
|
+
| `loading` | `boolean` | `false` | Show loading state |
|
|
2784
|
+
| `error` | `string` | - | Error message to display |
|
|
2785
|
+
| `title` | `string` | `'Login'` | Page title |
|
|
2786
|
+
| `description` | `string` | `'Enter your credentials'` | Page description |
|
|
2787
|
+
| `logo` | `node` | - | Logo component |
|
|
2788
|
+
| `brandName` | `string` | - | Brand name text |
|
|
2789
|
+
| `showForgotPassword` | `boolean` | `true` | Show forgot password link |
|
|
2790
|
+
| `forgotPasswordPath` | `string` | `'/forgot-password'` | Forgot password URL |
|
|
2791
|
+
| `showRegister` | `boolean` | `true` | Show register link |
|
|
2792
|
+
| `registerPath` | `string` | `'/register'` | Register URL |
|
|
2793
|
+
| `registerText` | `string` | `"Don't have an account?"` | Register prompt text |
|
|
2794
|
+
|
|
2795
|
+
### Usage
|
|
2796
|
+
|
|
2797
|
+
```jsx
|
|
2798
|
+
import { LoginPage } from '@bomjan133/react-crud-ui';
|
|
2799
|
+
import { useNavigate } from 'react-router-dom';
|
|
2800
|
+
import { useAuthStore } from '@/stores/useAuthStore';
|
|
2801
|
+
import Logo from '@/assets/logo.svg';
|
|
2802
|
+
|
|
2803
|
+
function Login() {
|
|
2804
|
+
const navigate = useNavigate();
|
|
2805
|
+
const { login, loading, error } = useAuthStore();
|
|
2806
|
+
|
|
2807
|
+
const handleSubmit = async ({ email, password }) => {
|
|
2808
|
+
const success = await login(email, password);
|
|
2809
|
+
if (success) {
|
|
2810
|
+
navigate('/dashboard');
|
|
2811
|
+
}
|
|
2812
|
+
};
|
|
2813
|
+
|
|
2814
|
+
return (
|
|
2815
|
+
<LoginPage
|
|
2816
|
+
onSubmit={handleSubmit}
|
|
2817
|
+
loading={loading}
|
|
2818
|
+
error={error}
|
|
2819
|
+
title="Welcome Back"
|
|
2820
|
+
description="Sign in to your account"
|
|
2821
|
+
logo={<img src={Logo} alt="Logo" className="h-12 w-auto" />}
|
|
2822
|
+
brandName="My App"
|
|
2823
|
+
showForgotPassword
|
|
2824
|
+
forgotPasswordPath="/forgot-password"
|
|
2825
|
+
showRegister
|
|
2826
|
+
registerPath="/register"
|
|
2827
|
+
/>
|
|
2828
|
+
);
|
|
2829
|
+
}
|
|
2830
|
+
```
|
|
2831
|
+
|
|
2832
|
+
---
|
|
2833
|
+
|
|
2834
|
+
## DashboardLayout
|
|
2835
|
+
|
|
2836
|
+
A complete admin dashboard layout with sidebar and header.
|
|
2837
|
+
|
|
2838
|
+
### Props
|
|
2839
|
+
|
|
2840
|
+
| Prop | Type | Default | Description |
|
|
2841
|
+
|------|------|---------|-------------|
|
|
2842
|
+
| `sidebarProps` | `object` | - | Sidebar configuration |
|
|
2843
|
+
| `headerProps` | `object` | - | Header configuration |
|
|
2844
|
+
| `children` | `node` | - | Page content |
|
|
2845
|
+
|
|
2846
|
+
### Sidebar Props
|
|
2847
|
+
|
|
2848
|
+
| Prop | Type | Description |
|
|
2849
|
+
|------|------|-------------|
|
|
2850
|
+
| `items` | `array` | Navigation items |
|
|
2851
|
+
| `brandName` | `string` | Brand name in sidebar |
|
|
2852
|
+
| `brandLogo` | `node` | Brand logo component |
|
|
2853
|
+
| `user` | `object` | Current user `{ name, email, avatar }` |
|
|
2854
|
+
| `onLogout` | `function` | Logout handler |
|
|
2855
|
+
|
|
2856
|
+
### Header Props
|
|
2857
|
+
|
|
2858
|
+
| Prop | Type | Description |
|
|
2859
|
+
|------|------|-------------|
|
|
2860
|
+
| `pathNames` | `object` | URL to title mapping for breadcrumbs |
|
|
2861
|
+
| `title` | `string` | Static page title (overrides pathNames) |
|
|
2862
|
+
|
|
2863
|
+
### Navigation Item Structure
|
|
2864
|
+
|
|
2865
|
+
```ts
|
|
2866
|
+
interface NavItem {
|
|
2867
|
+
name: string; // Display name
|
|
2868
|
+
path: string; // Route path
|
|
2869
|
+
icon: Component; // Lucide icon component
|
|
2870
|
+
children?: NavItem[]; // Submenu items (optional)
|
|
2871
|
+
badge?: string; // Badge text (optional)
|
|
2872
|
+
badgeVariant?: string; // Badge variant (optional)
|
|
2873
|
+
}
|
|
2874
|
+
```
|
|
2875
|
+
|
|
2876
|
+
### Usage
|
|
2877
|
+
|
|
2878
|
+
```jsx
|
|
2879
|
+
import { DashboardLayout } from '@bomjan133/react-crud-ui';
|
|
2880
|
+
import { Outlet, useNavigate } from 'react-router-dom';
|
|
2881
|
+
import {
|
|
2882
|
+
LayoutDashboard,
|
|
2883
|
+
Users,
|
|
2884
|
+
Settings,
|
|
2885
|
+
Package,
|
|
2886
|
+
ShoppingCart,
|
|
2887
|
+
BarChart,
|
|
2888
|
+
} from 'lucide-react';
|
|
2889
|
+
import { useAuthStore } from '@/stores/useAuthStore';
|
|
2890
|
+
|
|
2891
|
+
const sidebarItems = [
|
|
2892
|
+
{
|
|
2893
|
+
name: 'Dashboard',
|
|
2894
|
+
path: '/dashboard',
|
|
2895
|
+
icon: LayoutDashboard,
|
|
2896
|
+
},
|
|
2897
|
+
{
|
|
2898
|
+
name: 'Products',
|
|
2899
|
+
path: '/products',
|
|
2900
|
+
icon: Package,
|
|
2901
|
+
},
|
|
2902
|
+
{
|
|
2903
|
+
name: 'Orders',
|
|
2904
|
+
path: '/orders',
|
|
2905
|
+
icon: ShoppingCart,
|
|
2906
|
+
badge: '12',
|
|
2907
|
+
badgeVariant: 'destructive',
|
|
2908
|
+
},
|
|
2909
|
+
{
|
|
2910
|
+
name: 'Users',
|
|
2911
|
+
path: '/users',
|
|
2912
|
+
icon: Users,
|
|
2913
|
+
children: [
|
|
2914
|
+
{ name: 'All Users', path: '/users', icon: Users },
|
|
2915
|
+
{ name: 'Roles', path: '/users/roles', icon: Settings },
|
|
2916
|
+
],
|
|
2917
|
+
},
|
|
2918
|
+
{
|
|
2919
|
+
name: 'Analytics',
|
|
2920
|
+
path: '/analytics',
|
|
2921
|
+
icon: BarChart,
|
|
2922
|
+
},
|
|
2923
|
+
{
|
|
2924
|
+
name: 'Settings',
|
|
2925
|
+
path: '/settings',
|
|
2926
|
+
icon: Settings,
|
|
2927
|
+
},
|
|
2928
|
+
];
|
|
2929
|
+
|
|
2930
|
+
const pathNames = {
|
|
2931
|
+
'/dashboard': 'Dashboard',
|
|
2932
|
+
'/products': 'Products',
|
|
2933
|
+
'/products/create': 'Create Product',
|
|
2934
|
+
'/products/:id': 'Product Details',
|
|
2935
|
+
'/products/:id/edit': 'Edit Product',
|
|
2936
|
+
'/users': 'Users',
|
|
2937
|
+
'/users/roles': 'Roles',
|
|
2938
|
+
'/settings': 'Settings',
|
|
2939
|
+
};
|
|
2940
|
+
|
|
2941
|
+
export default function MainLayout() {
|
|
2942
|
+
const navigate = useNavigate();
|
|
2943
|
+
const { user, logout } = useAuthStore();
|
|
2944
|
+
|
|
2945
|
+
const handleLogout = async () => {
|
|
2946
|
+
await logout();
|
|
2947
|
+
navigate('/login');
|
|
2948
|
+
};
|
|
2949
|
+
|
|
2950
|
+
return (
|
|
2951
|
+
<DashboardLayout
|
|
2952
|
+
sidebarProps={{
|
|
2953
|
+
items: sidebarItems,
|
|
2954
|
+
brandName: 'My Admin',
|
|
2955
|
+
user: {
|
|
2956
|
+
name: user?.name,
|
|
2957
|
+
email: user?.email,
|
|
2958
|
+
avatar: user?.avatar,
|
|
2959
|
+
},
|
|
2960
|
+
onLogout: handleLogout,
|
|
2961
|
+
}}
|
|
2962
|
+
headerProps={{
|
|
2963
|
+
pathNames: pathNames,
|
|
2964
|
+
}}
|
|
2965
|
+
>
|
|
2966
|
+
<Outlet />
|
|
2967
|
+
</DashboardLayout>
|
|
2968
|
+
);
|
|
2969
|
+
}
|
|
2970
|
+
```
|
|
2971
|
+
|
|
2972
|
+
### Route Configuration
|
|
2973
|
+
|
|
2974
|
+
```jsx
|
|
2975
|
+
// routes.jsx
|
|
2976
|
+
import { Route, Routes } from 'react-router-dom';
|
|
2977
|
+
import MainLayout from '@/layouts/MainLayout';
|
|
2978
|
+
import Dashboard from '@/pages/Dashboard';
|
|
2979
|
+
import ProductList from '@/pages/products/ProductList';
|
|
2980
|
+
import ProductForm from '@/pages/products/ProductForm';
|
|
2981
|
+
import ProductDetail from '@/pages/products/ProductDetail';
|
|
2982
|
+
|
|
2983
|
+
function AppRoutes() {
|
|
2984
|
+
return (
|
|
2985
|
+
<Routes>
|
|
2986
|
+
{/* Public routes */}
|
|
2987
|
+
<Route path="/login" element={<LoginPage />} />
|
|
2988
|
+
|
|
2989
|
+
{/* Protected routes with dashboard layout */}
|
|
2990
|
+
<Route element={<MainLayout />}>
|
|
2991
|
+
<Route path="/dashboard" element={<Dashboard />} />
|
|
2992
|
+
<Route path="/products" element={<ProductList />} />
|
|
2993
|
+
<Route path="/products/create" element={<ProductForm />} />
|
|
2994
|
+
<Route path="/products/:id" element={<ProductDetail />} />
|
|
2995
|
+
<Route path="/products/:id/edit" element={<ProductForm />} />
|
|
2996
|
+
</Route>
|
|
2997
|
+
</Routes>
|
|
2998
|
+
);
|
|
2999
|
+
}
|
|
3000
|
+
```
|
|
3001
|
+
|
|
3002
|
+
---
|
|
3003
|
+
|
|
3004
|
+
## SidebarProvider
|
|
3005
|
+
|
|
3006
|
+
Context provider for sidebar state management (collapse/expand).
|
|
3007
|
+
|
|
3008
|
+
### Usage
|
|
3009
|
+
|
|
3010
|
+
The `DashboardLayout` automatically includes the `SidebarProvider`. If you need to access sidebar state outside the layout:
|
|
3011
|
+
|
|
3012
|
+
```jsx
|
|
3013
|
+
import { useSidebarContext } from '@bomjan133/react-crud-ui';
|
|
3014
|
+
|
|
3015
|
+
function SomeComponent() {
|
|
3016
|
+
const { isCollapsed, toggleCollapse } = useSidebarContext();
|
|
3017
|
+
|
|
3018
|
+
return (
|
|
3019
|
+
<button onClick={toggleCollapse}>
|
|
3020
|
+
{isCollapsed ? 'Expand' : 'Collapse'} Sidebar
|
|
3021
|
+
</button>
|
|
3022
|
+
);
|
|
3023
|
+
}
|
|
3024
|
+
```
|
|
3025
|
+
|
|
3026
|
+
### Context Values
|
|
3027
|
+
|
|
3028
|
+
| Value | Type | Description |
|
|
3029
|
+
|-------|------|-------------|
|
|
3030
|
+
| `isOpen` | `boolean` | Whether sidebar is open (mobile) |
|
|
3031
|
+
| `isCollapsed` | `boolean` | Whether sidebar is collapsed (desktop) |
|
|
3032
|
+
| `setOpen` | `function` | Set open state directly |
|
|
3033
|
+
| `setCollapsed` | `function` | Set collapsed state directly |
|
|
3034
|
+
| `toggle` | `function` | Toggle open state |
|
|
3035
|
+
| `toggleCollapse` | `function` | Toggle collapsed state |
|
|
3036
|
+
|
|
3037
|
+
---
|
|
3038
|
+
|
|
3039
|
+
## Full Example: App Setup
|
|
3040
|
+
|
|
3041
|
+
```jsx
|
|
3042
|
+
// src/App.jsx
|
|
3043
|
+
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
|
3044
|
+
import MainLayout from '@/layouts/MainLayout';
|
|
3045
|
+
import Login from '@/pages/Login';
|
|
3046
|
+
import Dashboard from '@/pages/Dashboard';
|
|
3047
|
+
import ProductListPage from '@/pages/products/ProductListPage';
|
|
3048
|
+
import ProductFormPage from '@/pages/products/ProductFormPage';
|
|
3049
|
+
import ProductDetailPage from '@/pages/products/ProductDetailPage';
|
|
3050
|
+
|
|
3051
|
+
function App() {
|
|
3052
|
+
return (
|
|
3053
|
+
<BrowserRouter>
|
|
3054
|
+
<Routes>
|
|
3055
|
+
{/* Redirect root to dashboard */}
|
|
3056
|
+
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
|
3057
|
+
|
|
3058
|
+
{/* Auth routes */}
|
|
3059
|
+
<Route path="/login" element={<Login />} />
|
|
3060
|
+
|
|
3061
|
+
{/* Dashboard routes */}
|
|
3062
|
+
<Route element={<MainLayout />}>
|
|
3063
|
+
<Route path="/dashboard" element={<Dashboard />} />
|
|
3064
|
+
<Route path="/products" element={<ProductListPage />} />
|
|
3065
|
+
<Route path="/products/create" element={<ProductFormPage />} />
|
|
3066
|
+
<Route path="/products/:id" element={<ProductDetailPage />} />
|
|
3067
|
+
<Route path="/products/:id/edit" element={<ProductFormPage />} />
|
|
3068
|
+
</Route>
|
|
3069
|
+
|
|
3070
|
+
{/* 404 */}
|
|
3071
|
+
<Route path="*" element={<Navigate to="/dashboard" replace />} />
|
|
3072
|
+
</Routes>
|
|
3073
|
+
</BrowserRouter>
|
|
3074
|
+
);
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
export default App;
|
|
3078
|
+
```
|
|
3079
|
+
|
|
3080
|
+
```jsx
|
|
3081
|
+
// src/layouts/MainLayout.jsx
|
|
3082
|
+
import { DashboardLayout } from '@bomjan133/react-crud-ui';
|
|
3083
|
+
import { Outlet, useNavigate } from 'react-router-dom';
|
|
3084
|
+
import { LayoutDashboard, Package, Settings } from 'lucide-react';
|
|
3085
|
+
import { useAuthStore } from '@/stores/useAuthStore';
|
|
3086
|
+
|
|
3087
|
+
const sidebarItems = [
|
|
3088
|
+
{ name: 'Dashboard', path: '/dashboard', icon: LayoutDashboard },
|
|
3089
|
+
{ name: 'Products', path: '/products', icon: Package },
|
|
3090
|
+
{ name: 'Settings', path: '/settings', icon: Settings },
|
|
3091
|
+
];
|
|
3092
|
+
|
|
3093
|
+
const pathNames = {
|
|
3094
|
+
'/dashboard': 'Dashboard',
|
|
3095
|
+
'/products': 'Products',
|
|
3096
|
+
'/products/create': 'Create Product',
|
|
3097
|
+
'/products/:id': 'Product Details',
|
|
3098
|
+
'/products/:id/edit': 'Edit Product',
|
|
3099
|
+
'/settings': 'Settings',
|
|
3100
|
+
};
|
|
3101
|
+
|
|
3102
|
+
export default function MainLayout() {
|
|
3103
|
+
const navigate = useNavigate();
|
|
3104
|
+
const { user, logout } = useAuthStore();
|
|
3105
|
+
|
|
3106
|
+
const handleLogout = async () => {
|
|
3107
|
+
await logout();
|
|
3108
|
+
navigate('/login');
|
|
3109
|
+
};
|
|
3110
|
+
|
|
3111
|
+
return (
|
|
3112
|
+
<DashboardLayout
|
|
3113
|
+
sidebarProps={{
|
|
3114
|
+
items: sidebarItems,
|
|
3115
|
+
brandName: 'Admin Panel',
|
|
3116
|
+
user: { name: user?.name, email: user?.email },
|
|
3117
|
+
onLogout: handleLogout,
|
|
3118
|
+
}}
|
|
3119
|
+
headerProps={{ pathNames }}
|
|
3120
|
+
>
|
|
3121
|
+
<Outlet />
|
|
3122
|
+
</DashboardLayout>
|
|
3123
|
+
);
|
|
3124
|
+
}
|
|
3125
|
+
```
|
|
3126
|
+
|
|
3127
|
+
</details>
|
|
3128
|
+
|
|
3129
|
+
<a id="store-factory"></a>
|
|
3130
|
+
<details>
|
|
3131
|
+
<summary><strong>6. Store Factory Guide</strong></summary>
|
|
3132
|
+
|
|
3133
|
+
Complete reference for `createCrudStore` (and `createStore`) in @bomjan133/react-crud-ui.
|
|
3134
|
+
|
|
3135
|
+
## Table of Contents
|
|
3136
|
+
1. [Overview](#overview)
|
|
3137
|
+
2. [Basic Usage](#basic-usage)
|
|
3138
|
+
3. [`createStore` is currently broken under ESM](#createstore-is-currently-broken-under-esm)
|
|
3139
|
+
4. [Store Options](#store-options)
|
|
3140
|
+
5. [Store State](#store-state)
|
|
3141
|
+
6. [Store Actions](#store-actions)
|
|
3142
|
+
7. [API Request/Response Conventions](#api-requestresponse-conventions)
|
|
3143
|
+
8. [Extending with `extraActions`](#extending-with-extraactions)
|
|
3144
|
+
9. [Compatibility with `CrudList` / `CrudForm` / `CrudDetail`](#compatibility-with-crudlist--crudform--cruddetail)
|
|
3145
|
+
10. [Best Practices](#best-practices)
|
|
3146
|
+
|
|
3147
|
+
Everything below was verified by reading `src/store/createCrudStore.js` in full and running it directly against zustand 5 in Node — not inferred from the function names alone.
|
|
3148
|
+
|
|
3149
|
+
---
|
|
3150
|
+
|
|
3151
|
+
## Overview
|
|
3152
|
+
|
|
3153
|
+
`createCrudStore(options)` is a factory that builds a Zustand **state creator** for a single resource, wired to an Axios-compatible `apiClient`. It gives you:
|
|
3154
|
+
|
|
3155
|
+
- Flat list state (`items`, `page`, `pageSize`, `totalItems`, `totalPages`, `search`, `filters`, `sortColumn`, `sortDirection`, `selectedIds`)
|
|
3156
|
+
- A single-item slot (`item`) for detail/edit views
|
|
3157
|
+
- `loading` (list operations) and `submitting` (item operations) flags, plus `error`
|
|
3158
|
+
- CRUD methods: `fetchList`, `fetchOne`, `create`, `update`, `delete`, `bulkDelete`, `replace`
|
|
3159
|
+
- An `extraActions` escape hatch for anything custom
|
|
3160
|
+
|
|
3161
|
+
**It does not manage form state.** There is no `form.values`/`form.errors`, no `resetForm`/`setFormField`/`initForm` — none of that exists in this factory. If you need form state, either manage it yourself (`useState`/`react-hook-form`) or use `CrudForm`'s **fields mode** (`fields` + `onSubmit`), which is self-contained and doesn't need any of this. See [Compatibility](#compatibility-with-crudlist--crudform--cruddetail) below.
|
|
3162
|
+
|
|
3163
|
+
---
|
|
3164
|
+
|
|
3165
|
+
## Basic Usage
|
|
3166
|
+
|
|
3167
|
+
`createCrudStore(options)` does **not** return a ready-to-use hook by itself — it returns a Zustand *state creator function* that still needs zustand's own `create` passed into it. The correct pattern is:
|
|
3168
|
+
|
|
3169
|
+
```js
|
|
3170
|
+
// stores/useProductStore.js
|
|
3171
|
+
import { create } from 'zustand';
|
|
3172
|
+
import { createCrudStore } from '@bomjan133/react-crud-ui';
|
|
3173
|
+
import apiClient from '@/lib/api'; // an Axios instance
|
|
3174
|
+
|
|
3175
|
+
const useProductStore = createCrudStore({
|
|
3176
|
+
name: 'products',
|
|
3177
|
+
apiClient,
|
|
3178
|
+
endpoint: '/products',
|
|
3179
|
+
})(create); // <-- note the trailing (create) call
|
|
3180
|
+
|
|
3181
|
+
export default useProductStore;
|
|
3182
|
+
```
|
|
3183
|
+
|
|
3184
|
+
Use it like any Zustand store:
|
|
3185
|
+
|
|
3186
|
+
```jsx
|
|
3187
|
+
import useProductStore from '@/stores/useProductStore';
|
|
3188
|
+
|
|
3189
|
+
function ProductList() {
|
|
3190
|
+
const { items, loading, fetchList } = useProductStore();
|
|
3191
|
+
|
|
3192
|
+
useEffect(() => {
|
|
3193
|
+
fetchList();
|
|
3194
|
+
}, []);
|
|
3195
|
+
|
|
3196
|
+
return (
|
|
3197
|
+
<div>
|
|
3198
|
+
{items.map((product) => (
|
|
3199
|
+
<div key={product.id}>{product.name}</div>
|
|
3200
|
+
))}
|
|
3201
|
+
</div>
|
|
3202
|
+
);
|
|
3203
|
+
}
|
|
3204
|
+
```
|
|
3205
|
+
|
|
3206
|
+
---
|
|
3207
|
+
|
|
3208
|
+
## `createStore` is currently broken under ESM
|
|
3209
|
+
|
|
3210
|
+
The package also exports a `createStore(options)` "convenience wrapper" that's meant to skip the `(create)` call:
|
|
3211
|
+
|
|
3212
|
+
```js
|
|
3213
|
+
export const createStore = (options) => {
|
|
3214
|
+
const { create } = require("zustand");
|
|
3215
|
+
return create(createCrudStore(options));
|
|
3216
|
+
};
|
|
3217
|
+
```
|
|
3218
|
+
|
|
3219
|
+
**This throws `ReferenceError: require is not defined` when you `import` the package (ESM)** — verified directly: calling `createStore({...})` after `import { createStore } from '@bomjan133/react-crud-ui'` fails immediately, because `require` doesn't exist in an ES module/browser bundle, and the published `dist/index.js` (ESM build) ships this `require("zustand")` call completely un-transformed. It only works if you consume the package's CommonJS build (`require('@bomjan133/react-crud-ui')`) directly, since `require` is a real function there.
|
|
3220
|
+
|
|
3221
|
+
**Until this is fixed upstream, don't use `createStore`. Use `createCrudStore(options)(create)` instead** (shown above) — it has no dependency on `require` and works identically in both ESM and CJS.
|
|
3222
|
+
|
|
3223
|
+
---
|
|
3224
|
+
|
|
3225
|
+
## Store Options
|
|
3226
|
+
|
|
3227
|
+
| Option | Type | Required | Default | Description |
|
|
3228
|
+
|--------|------|----------|---------|-------------|
|
|
3229
|
+
| `apiClient` | Axios instance (or compatible: needs `.get`/`.post`/`.patch`/`.put`/`.delete`) | **Yes** | - | Throws `"createCrudStore: apiClient is required"` if omitted. Not called `api` — see correction below. |
|
|
3230
|
+
| `endpoint` | `string` | **Yes** | - | Throws `"createCrudStore: endpoint is required"` if omitted. Requests are built as `` `${endpoint}` ``, `` `${endpoint}/` `` (create), and `` `${endpoint}/${id}/` `` (fetchOne/update/delete/replace) — the trailing slashes are hardcoded, matching a Django REST Framework-style API. If your backend doesn't use trailing slashes, use `transformRequest`/a custom `apiClient` interceptor to compensate, or don't rely on this factory's endpoint building. |
|
|
3231
|
+
| `name` | `string` | No | `"crud"` | Accepted but only used as a label — **not currently used for anything visible** (e.g. no Zustand devtools naming is wired up in this factory). |
|
|
3232
|
+
| `transformResponse` | `(item) => item` | No | identity | Applied to each item in `fetchList` results and to the single item in `fetchOne`/`create`/`update`/`replace`. **Not called `transformItem`.** |
|
|
3233
|
+
| `transformRequest` | `(data) => data` | No | identity | Applied to the payload before `create`/`update`/`replace` POST/PATCH/PUT calls. |
|
|
3234
|
+
| `initialState` | `object` | No | `{}` | Merged into the store's initial state, after the built-in defaults — use this to add custom fields (it does **not** support a nested `filters: {...}` shorthand differently from any other key; it's a plain shallow merge). |
|
|
3235
|
+
| `extraActions` | `object` | No | `{}` | Merged into the store, after all built-in actions — see [Extending](#extending-with-extraactions). **Not called `extend`, and not a function** — it's a plain object of actions (though you can build that object using `set`/`get` closures yourself before passing it in). |
|
|
3236
|
+
| `idField` | `string` | No | `"id"` | Field name used to match items in `update`/`delete`/`bulkDelete`/`replace` (e.g. `item[idField] === id`). Set this to `"uuid"` if your API uses UUIDs under that key. |
|
|
3237
|
+
| `listKey` | `string` | No | `"results"` | Key read from the list response body for the array of items — see [API conventions](#api-requestresponse-conventions). |
|
|
3238
|
+
| `countKey` | `string` | No | `"count"` | Key read from the list response body for the total item count. |
|
|
3239
|
+
|
|
3240
|
+
> **Corrections vs. an earlier version of this doc:** the real required client option is `apiClient`, not `api`. There is no `transformItem`/`transformList`/`onFetchSuccess`/`onFetchError`/`onCreateSuccess`/`onUpdateSuccess`/`onDeleteSuccess`/`endpoints` (per-action endpoint overrides) option — none of these exist in the source. The only response-shaping hooks are `transformResponse`, `transformRequest`, `listKey`, and `countKey`.
|
|
3241
|
+
|
|
3242
|
+
---
|
|
3243
|
+
|
|
3244
|
+
## Store State
|
|
3245
|
+
|
|
3246
|
+
All of this is flat top-level state — there is no nested `pagination`/`form`/`current` object.
|
|
3247
|
+
|
|
3248
|
+
| Field | Type | Initial value | Description |
|
|
3249
|
+
|-------|------|----------------|-------------|
|
|
3250
|
+
| `items` | `array` | `[]` | Current page of list results. |
|
|
3251
|
+
| `item` | `object \| null` | `null` | Currently-loaded single record (populated by `fetchOne`, kept in sync by `update`/`delete`/`replace`). |
|
|
3252
|
+
| `loading` | `boolean` | `false` | True while `fetchList` or `fetchOne` is in flight. |
|
|
3253
|
+
| `submitting` | `boolean` | `false` | True while `create`/`update`/`delete`/`bulkDelete`/`replace` is in flight. |
|
|
3254
|
+
| `error` | `{ message, original, fieldErrors? } \| null` | `null` | Set by any failed request; cleared at the start of the next request, or via `clearError()`. `fieldErrors` (the raw `error.response.data`) is only attached by `create`/`update`/`replace`. |
|
|
3255
|
+
| `page` | `number` | `1` | Current page. |
|
|
3256
|
+
| `pageSize` | `number` | `15` | Items per page, sent as the `page_size` query param. |
|
|
3257
|
+
| `totalItems` | `number` | `0` | Set from the last `fetchList` response. |
|
|
3258
|
+
| `totalPages` | `number` | `0` | Computed as `Math.ceil(totalItems / pageSize)` after each `fetchList`. |
|
|
3259
|
+
| `sortColumn` | `string \| null` | `null` | Set via `setSort`. |
|
|
3260
|
+
| `sortDirection` | `string \| null` | `null` | Set via `setSort`; `"desc"` is sent as a `-` prefix on the `ordering` query param, anything else is sent unprefixed. |
|
|
3261
|
+
| `search` | `string` | `""` | Set via `setSearch`; sent as the `search` query param. |
|
|
3262
|
+
| `filters` | `object` | `{}` | Set (replaced wholesale, not merged) via `setFilters`; each key is spread directly into the query params. |
|
|
3263
|
+
| `selectedIds` | `array` | `[]` | Set via `setSelectedIds`/`clearSelection`; also auto-pruned by `delete`/`bulkDelete`. |
|
|
3264
|
+
|
|
3265
|
+
> **There is no `pagination` object, no `current`/`itemLoading`/`itemError`, and no `form` state.** An earlier version of this doc described a `{ page, totalPages, total, perPage }` pagination object and a full form sub-state (`values`/`errors`/`isDirty`) — none of that exists in `createCrudStore`.
|
|
3266
|
+
|
|
3267
|
+
---
|
|
3268
|
+
|
|
3269
|
+
## Store Actions
|
|
3270
|
+
|
|
3271
|
+
### List actions
|
|
3272
|
+
|
|
3273
|
+
```js
|
|
3274
|
+
const {
|
|
3275
|
+
fetchList, // async (params = {}) => { items, totalItems, totalPages }
|
|
3276
|
+
setPage, // (page) => void
|
|
3277
|
+
setPageSize, // (pageSize) => void — also resets page to 1
|
|
3278
|
+
setSearch, // (search) => void — also resets page to 1
|
|
3279
|
+
setFilters, // (filters) => void — REPLACES filters wholesale, also resets page to 1
|
|
3280
|
+
setSort, // (sortColumn, sortDirection) => void
|
|
3281
|
+
clearError, // () => void
|
|
3282
|
+
reset, // () => void — resets items/item/loading/submitting/error/page/search/filters/selectedIds/sort
|
|
3283
|
+
} = useProductStore();
|
|
3284
|
+
|
|
3285
|
+
await fetchList(); // uses current page/pageSize/search/filters/sort
|
|
3286
|
+
await fetchList({ page: 2 }); // merges extra params into the request (does not update store state)
|
|
3287
|
+
setFilters({ status: 'active' }); // replaces the whole filters object — see caveat below
|
|
3288
|
+
```
|
|
3289
|
+
|
|
3290
|
+
> **`setFilters` replaces, it does not merge.** Calling `setFilters({ status: 'active' })` and later `setFilters({ category: 1 })` leaves `filters` as `{ category: 1 }` — the earlier `status` key is gone. If you need multiple independent filters, merge them yourself: `setFilters({ ...filters, category: 1 })`. There is no `clearFilters()` action — call `setFilters({})` instead.
|
|
3291
|
+
|
|
3292
|
+
### Selection actions
|
|
3293
|
+
|
|
3294
|
+
```js
|
|
3295
|
+
const { selectedIds, setSelectedIds, clearSelection } = useProductStore();
|
|
3296
|
+
|
|
3297
|
+
setSelectedIds([1, 2, 3]);
|
|
3298
|
+
clearSelection();
|
|
3299
|
+
```
|
|
3300
|
+
|
|
3301
|
+
### Item actions
|
|
3302
|
+
|
|
3303
|
+
```js
|
|
3304
|
+
const { fetchOne } = useProductStore();
|
|
3305
|
+
|
|
3306
|
+
const product = await fetchOne(productId);
|
|
3307
|
+
console.log(product.name);
|
|
3308
|
+
```
|
|
3309
|
+
|
|
3310
|
+
> There is no `fetchById` alias, and no `setCurrent`/`clearCurrent` — `item` is only ever set by `fetchOne` (and kept in sync by `update`/`delete`/`replace` when the ids match).
|
|
3311
|
+
|
|
3312
|
+
### CRUD actions
|
|
3313
|
+
|
|
3314
|
+
```js
|
|
3315
|
+
const { create, update, delete: remove, bulkDelete, replace } = useProductStore();
|
|
3316
|
+
|
|
3317
|
+
const newProduct = await create({ name: 'New Product', price: 99.99 });
|
|
3318
|
+
const updated = await update(productId, { name: 'Updated Name' });
|
|
3319
|
+
await remove(productId); // the real action is named `delete` — alias it on destructure since `delete` is reserved in some contexts
|
|
3320
|
+
await bulkDelete([1, 2, 3]); // deletes one-by-one via Promise.all, then updates items/totalItems/selectedIds
|
|
3321
|
+
const replaced = await replace(productId, fullPayload); // PUT, full replace
|
|
3322
|
+
```
|
|
3323
|
+
|
|
3324
|
+
> **The delete method is named `delete`, not `remove`.** Since `delete` is a reserved word in object literal *shorthand* contexts in some older tooling, destructure it with a rename if needed: `const { delete: remove } = useProductStore();`. There is no separate `remove` action.
|
|
3325
|
+
|
|
3326
|
+
All of `create`/`update`/`delete`/`bulkDelete`/`replace` guard against concurrent calls (they no-op while `submitting` is already `true`, except `bulkDelete` which doesn't check `submitting` at all), and all reject (throw) on failure after populating `error`.
|
|
3327
|
+
|
|
3328
|
+
---
|
|
3329
|
+
|
|
3330
|
+
## API Request/Response Conventions
|
|
3331
|
+
|
|
3332
|
+
### `fetchList` request
|
|
3333
|
+
|
|
3334
|
+
```
|
|
3335
|
+
GET {endpoint}?page=1&page_size=15&search=foo&ordering=-created_at&<...filters>
|
|
3336
|
+
```
|
|
3337
|
+
|
|
3338
|
+
- `page`/`page_size` always sent.
|
|
3339
|
+
- `search` only sent if non-empty.
|
|
3340
|
+
- `ordering` only sent if `sortColumn` is set; `sortDirection === 'desc'` prefixes it with `-`.
|
|
3341
|
+
- Every key in `filters` is spread in directly, then any explicit `params` passed to `fetchList(params)` are spread in last (so they win over store state for that one call, without persisting it back to the store).
|
|
3342
|
+
- Keys with `undefined` or `''` values are stripped before the request is sent.
|
|
3343
|
+
|
|
3344
|
+
### `fetchList` response
|
|
3345
|
+
|
|
3346
|
+
Reads, in order of preference:
|
|
3347
|
+
```js
|
|
3348
|
+
const items = data[listKey] || data.data || (Array.isArray(data) ? data : []);
|
|
3349
|
+
const totalItems = data[countKey] || data.total || items.length;
|
|
3350
|
+
```
|
|
3351
|
+
With the defaults (`listKey: "results"`, `countKey: "count"`), that means:
|
|
3352
|
+
|
|
3353
|
+
```json
|
|
3354
|
+
{ "results": [ ... ], "count": 42 }
|
|
3355
|
+
```
|
|
3356
|
+
|
|
3357
|
+
is read out of the box. A response shaped like `{ "data": [...], "meta": { "total": 42 } }` requires either passing `listKey`/`countKey` (they only look at top-level keys, not nested `meta.total`) or handling reshaping yourself via a response interceptor on `apiClient`, since there is no `transformList` hook.
|
|
3358
|
+
|
|
3359
|
+
### Single-item requests
|
|
3360
|
+
|
|
3361
|
+
- `fetchOne(id)` → `GET {endpoint}/{id}/`, result passed through `transformResponse`.
|
|
3362
|
+
- `create(data)` → `POST {endpoint}/`, payload passed through `transformRequest` first, result through `transformResponse`.
|
|
3363
|
+
- `update(id, data)` → `PATCH {endpoint}/{id}/`.
|
|
3364
|
+
- `replace(id, data)` → `PUT {endpoint}/{id}/` (full replace).
|
|
3365
|
+
- `delete(id)` / `bulkDelete(ids)` → `DELETE {endpoint}/{id}/` (one request per id for `bulkDelete`, run concurrently via `Promise.all`).
|
|
3366
|
+
|
|
3367
|
+
### Error shape
|
|
3368
|
+
|
|
3369
|
+
Every action sets `error` to:
|
|
3370
|
+
```js
|
|
3371
|
+
{ message: string, original: Error, fieldErrors?: object }
|
|
3372
|
+
```
|
|
3373
|
+
`message` is resolved from `error.response?.data?.message`, then `.detail`, then `error.message`, then a hardcoded fallback string. `fieldErrors` (the raw `error.response?.data`) is only attached for `create`/`update`/`replace` — useful for mapping server-side validation errors back onto form fields yourself.
|
|
3374
|
+
|
|
3375
|
+
---
|
|
3376
|
+
|
|
3377
|
+
## Extending with `extraActions`
|
|
3378
|
+
|
|
3379
|
+
`extraActions` is a plain object merged onto the store after all built-in state/actions — build it with closures over `set`/`get` yourself if it needs to read/write store state:
|
|
3380
|
+
|
|
3381
|
+
```js
|
|
3382
|
+
import { create } from 'zustand';
|
|
3383
|
+
import { createCrudStore } from '@bomjan133/react-crud-ui';
|
|
3384
|
+
import apiClient from '@/lib/api';
|
|
3385
|
+
|
|
3386
|
+
const useProductStoreCreator = (set, get) => ({
|
|
3387
|
+
archive: async (id) => {
|
|
3388
|
+
await apiClient.post(`/products/${id}/archive`);
|
|
3389
|
+
await get().fetchList();
|
|
3390
|
+
},
|
|
3391
|
+
duplicate: async (id) => {
|
|
3392
|
+
const { data } = await apiClient.post(`/products/${id}/duplicate`);
|
|
3393
|
+
await get().fetchList();
|
|
3394
|
+
return data;
|
|
3395
|
+
},
|
|
3396
|
+
});
|
|
3397
|
+
|
|
3398
|
+
// createCrudStore itself doesn't give you set/get ahead of time, so build
|
|
3399
|
+
// extraActions inline using zustand's create, or pass simple stateless helpers:
|
|
3400
|
+
const useProductStore = createCrudStore({
|
|
3401
|
+
apiClient,
|
|
3402
|
+
endpoint: '/products',
|
|
3403
|
+
initialState: { viewMode: 'grid' },
|
|
3404
|
+
extraActions: {
|
|
3405
|
+
// Actions defined here only close over module-level values (like apiClient),
|
|
3406
|
+
// not `set`/`get` — for state-aware extras, patch the store after creation instead:
|
|
3407
|
+
},
|
|
3408
|
+
})(create);
|
|
3409
|
+
|
|
3410
|
+
// State-aware extension pattern (recommended): wrap the created hook.
|
|
3411
|
+
useProductStore.setState((state) => ({
|
|
3412
|
+
setViewMode: (mode) => useProductStore.setState({ viewMode: mode }),
|
|
3413
|
+
archive: async (id) => {
|
|
3414
|
+
await apiClient.post(`/products/${id}/archive`);
|
|
3415
|
+
await useProductStore.getState().fetchList();
|
|
3416
|
+
},
|
|
3417
|
+
}));
|
|
3418
|
+
```
|
|
3419
|
+
|
|
3420
|
+
> An earlier version of this doc showed an `extend: (set, get, store) => ({...})` function option — **that option does not exist**. `extraActions` is a plain object, so any action inside it that needs `set`/`get` must either close over the resulting hook itself (as shown above) or be added via `useProductStore.setState(...)` after creation.
|
|
3421
|
+
|
|
3422
|
+
---
|
|
3423
|
+
|
|
3424
|
+
## Compatibility with `CrudList` / `CrudForm` / `CrudDetail`
|
|
3425
|
+
|
|
3426
|
+
A store built with `createCrudStore` is **not** a drop-in for every `Q*`/`Crud*` component's `store`/`useStore` prop — each one expects a different shape:
|
|
3427
|
+
|
|
3428
|
+
| Component | What it needs from the store | Compatible with `createCrudStore`? |
|
|
3429
|
+
|---|---|---|
|
|
3430
|
+
| `CrudList` (`store` prop) | `items`, `loading`, `error`, `fetchList`, `delete`, `setPage`, `setPageSize`, `setFilters`, `sortColumn`/`sortDirection`/`setSort`, **and a nested `store.pagination` object** (`{ page, pageSize, total, totalPages }`) | **Partially.** `createCrudStore` gives you everything except `pagination` as a nested object — its pagination fields are flat (`page`/`pageSize`/`totalItems`/`totalPages`). Since `CrudList` reads `store?.pagination` directly, it won't find one and will silently fall back to `currentPage`/`pageSize`/`totalItems`/`totalPages` **props** (default `1`/`15`/`0`/`1`) instead of the store's real values — i.e. pagination will look stuck at page 1 unless you bridge it, e.g. `store={{ ...store, pagination: { page: store.page, pageSize: store.pageSize, total: store.totalItems, totalPages: store.totalPages } }}`. |
|
|
3431
|
+
| `CrudDetail` (`useStore` prop) | `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), `delete` | **Partially.** `createCrudStore` has `fetchOne` (used as the fallback) and `delete`, `loading`, `error` — but its single-item field is named `item`, not `currentItem`. `CrudDetail` reads `currentItem` specifically, so you'll need to bridge it too: `useStore={() => { const s = useProductStore(); return { ...s, currentItem: s.item }; }}`. |
|
|
3432
|
+
| `CrudForm` (`useStore` + `children` store mode) | `form.values`, `form.isSubmitting`, `create`, `update`, `resetForm`, `setFormErrors`, `fetchAndPopulateForm`/`fetchById`/`fetchOne` | **No.** `createCrudStore` has no `form` state, no `resetForm`, no `setFormErrors`, and no `fetchAndPopulateForm`. Use `CrudForm`'s **fields mode** (`fields` array + `onSubmit`) with a `createCrudStore`-based store instead — call `create`/`update` yourself from `onSubmit`. |
|
|
3433
|
+
|
|
3434
|
+
Given these gaps, treat `createCrudStore` as a solid base for **list fetching, item fetching, and CRUD mutations**, and either bridge the shape differences above or manage form/pagination-object state yourself alongside it.
|
|
3435
|
+
|
|
3436
|
+
---
|
|
3437
|
+
|
|
3438
|
+
## Best Practices
|
|
3439
|
+
|
|
3440
|
+
### 1. One store per resource
|
|
3441
|
+
|
|
3442
|
+
```js
|
|
3443
|
+
const useProductStore = createCrudStore({ apiClient, endpoint: '/products' })(create);
|
|
3444
|
+
const useOrderStore = createCrudStore({ apiClient, endpoint: '/orders' })(create);
|
|
3445
|
+
```
|
|
3446
|
+
|
|
3447
|
+
### 2. Centralized API instance
|
|
3448
|
+
|
|
3449
|
+
```js
|
|
3450
|
+
// lib/api.js
|
|
3451
|
+
import axios from 'axios';
|
|
3452
|
+
|
|
3453
|
+
const apiClient = axios.create({
|
|
3454
|
+
baseURL: import.meta.env.VITE_API_URL,
|
|
3455
|
+
headers: { 'Content-Type': 'application/json' },
|
|
3456
|
+
});
|
|
3457
|
+
|
|
3458
|
+
apiClient.interceptors.request.use((config) => {
|
|
3459
|
+
const token = localStorage.getItem('token');
|
|
3460
|
+
if (token) config.headers.Authorization = `Bearer ${token}`;
|
|
3461
|
+
return config;
|
|
3462
|
+
});
|
|
3463
|
+
|
|
3464
|
+
export default apiClient;
|
|
3465
|
+
```
|
|
3466
|
+
|
|
3467
|
+
### 3. Handle loading/error/empty states
|
|
3468
|
+
|
|
3469
|
+
```jsx
|
|
3470
|
+
function ProductList() {
|
|
3471
|
+
const { items, loading, error, fetchList } = useProductStore();
|
|
3472
|
+
|
|
3473
|
+
useEffect(() => {
|
|
3474
|
+
fetchList();
|
|
3475
|
+
}, []);
|
|
3476
|
+
|
|
3477
|
+
if (loading) return <Loading />;
|
|
3478
|
+
if (error) return <ErrorState error={error} onRetry={fetchList} />;
|
|
3479
|
+
if (items.length === 0) return <EmptyState />;
|
|
3480
|
+
|
|
3481
|
+
return <DataTable data={items} columns={columns} />;
|
|
3482
|
+
}
|
|
3483
|
+
```
|
|
3484
|
+
|
|
3485
|
+
### 4. Form pattern (since the store has no form state)
|
|
3486
|
+
|
|
3487
|
+
Manage form state locally (or with `react-hook-form`, or `CrudForm`'s fields mode) and call the store's `create`/`update`/`fetchOne` directly:
|
|
3488
|
+
|
|
3489
|
+
```jsx
|
|
3490
|
+
function ProductForm({ productId }) {
|
|
3491
|
+
const { fetchOne, create, update, submitting } = useProductStore();
|
|
3492
|
+
const [values, setValues] = useState({ name: '', price: '' });
|
|
3493
|
+
const isEditing = Boolean(productId);
|
|
3494
|
+
|
|
3495
|
+
useEffect(() => {
|
|
3496
|
+
if (isEditing) {
|
|
3497
|
+
fetchOne(productId).then((item) => setValues(item));
|
|
3498
|
+
}
|
|
3499
|
+
}, [productId]);
|
|
3500
|
+
|
|
3501
|
+
const handleSubmit = async (e) => {
|
|
3502
|
+
e.preventDefault();
|
|
3503
|
+
if (isEditing) {
|
|
3504
|
+
await update(productId, values);
|
|
3505
|
+
} else {
|
|
3506
|
+
await create(values);
|
|
3507
|
+
}
|
|
3508
|
+
};
|
|
3509
|
+
|
|
3510
|
+
return (
|
|
3511
|
+
<form onSubmit={handleSubmit}>
|
|
3512
|
+
{/* fields bound to values/setValues */}
|
|
3513
|
+
<button disabled={submitting}>{submitting ? 'Saving...' : 'Save'}</button>
|
|
3514
|
+
</form>
|
|
3515
|
+
);
|
|
3516
|
+
}
|
|
3517
|
+
```
|
|
3518
|
+
|
|
3519
|
+
### 5. Filtering pattern (remember `setFilters` replaces, not merges)
|
|
3520
|
+
|
|
3521
|
+
```jsx
|
|
3522
|
+
function ProductFilters() {
|
|
3523
|
+
const { filters, setFilters, fetchList } = useProductStore();
|
|
3524
|
+
|
|
3525
|
+
const handleFilterChange = (key, value) => {
|
|
3526
|
+
setFilters({ ...filters, [key]: value }); // merge yourself
|
|
3527
|
+
};
|
|
3528
|
+
|
|
3529
|
+
useEffect(() => {
|
|
3530
|
+
fetchList();
|
|
3531
|
+
}, [filters]);
|
|
3532
|
+
|
|
3533
|
+
return (
|
|
3534
|
+
<div className="flex gap-4">
|
|
3535
|
+
<QSelect
|
|
3536
|
+
label="Category"
|
|
3537
|
+
value={filters.category}
|
|
3538
|
+
onChange={(val) => handleFilterChange('category', val)}
|
|
3539
|
+
options={categories}
|
|
3540
|
+
/>
|
|
3541
|
+
<QSelect
|
|
3542
|
+
label="Status"
|
|
3543
|
+
value={filters.status}
|
|
3544
|
+
onChange={(val) => handleFilterChange('status', val)}
|
|
3545
|
+
options={statusOptions}
|
|
3546
|
+
/>
|
|
3547
|
+
</div>
|
|
3548
|
+
);
|
|
3549
|
+
}
|
|
3550
|
+
```
|
|
3551
|
+
|
|
3552
|
+
### 6. Bulk selection + bulk delete
|
|
3553
|
+
|
|
3554
|
+
```jsx
|
|
3555
|
+
function ProductList() {
|
|
3556
|
+
const { items, selectedIds, setSelectedIds, clearSelection, bulkDelete } = useProductStore();
|
|
3557
|
+
|
|
3558
|
+
const toggleSelection = (id) => {
|
|
3559
|
+
setSelectedIds(
|
|
3560
|
+
selectedIds.includes(id) ? selectedIds.filter((i) => i !== id) : [...selectedIds, id],
|
|
3561
|
+
);
|
|
3562
|
+
};
|
|
3563
|
+
|
|
3564
|
+
return (
|
|
3565
|
+
<div>
|
|
3566
|
+
<div className="flex gap-2 mb-4">
|
|
3567
|
+
<Button onClick={() => setSelectedIds(items.map((i) => i.id))}>Select All</Button>
|
|
3568
|
+
<Button onClick={clearSelection}>Clear Selection</Button>
|
|
3569
|
+
{selectedIds.length > 0 && (
|
|
3570
|
+
<Button variant="destructive" onClick={() => bulkDelete(selectedIds)}>
|
|
3571
|
+
Delete Selected ({selectedIds.length})
|
|
3572
|
+
</Button>
|
|
3573
|
+
)}
|
|
3574
|
+
</div>
|
|
3575
|
+
{items.map((item) => (
|
|
3576
|
+
<ProductCard
|
|
3577
|
+
key={item.id}
|
|
3578
|
+
item={item}
|
|
3579
|
+
selected={selectedIds.includes(item.id)}
|
|
3580
|
+
onSelect={() => toggleSelection(item.id)}
|
|
3581
|
+
/>
|
|
3582
|
+
))}
|
|
3583
|
+
</div>
|
|
3584
|
+
);
|
|
3585
|
+
}
|
|
3586
|
+
```
|
|
3587
|
+
|
|
3588
|
+
</details>
|
|
3589
|
+
|
|
3590
|
+
<a id="book-viewer"></a>
|
|
3591
|
+
<details>
|
|
3592
|
+
<summary><strong>7. Book Viewer Guide</strong></summary>
|
|
3593
|
+
|
|
3594
|
+
A self-contained flipbook component for rendering **EPUB** and **PDF** files with a realistic page-flip animation, built on [`react-pageflip`](https://github.com/Nodlik/react-pageflip).
|
|
3595
|
+
|
|
3596
|
+
## Table of Contents
|
|
3597
|
+
1. [Installation](#installation-1)
|
|
3598
|
+
2. [Exports](#exports)
|
|
3599
|
+
3. [BookViewer (recommended)](#bookviewer-recommended)
|
|
3600
|
+
4. [EpubViewer (direct use)](#epubviewer-direct-use)
|
|
3601
|
+
5. [PdfViewer (direct use)](#pdfviewer-direct-use)
|
|
3602
|
+
6. [useBookDimensions](#usebookdimensionscontainerref)
|
|
3603
|
+
7. [Keyboard Navigation](#keyboard-navigation)
|
|
3604
|
+
8. [Container Setup](#container-setup)
|
|
3605
|
+
9. [Troubleshooting](#troubleshooting)
|
|
3606
|
+
|
|
3607
|
+
---
|
|
3608
|
+
|
|
3609
|
+
## Installation
|
|
3610
|
+
|
|
3611
|
+
Install the package along with its required runtime dependencies:
|
|
3612
|
+
|
|
3613
|
+
```bash
|
|
3614
|
+
npm install @bomjan133/react-crud-ui
|
|
3615
|
+
npm install react-pageflip epubjs html2canvas
|
|
3616
|
+
```
|
|
3617
|
+
|
|
3618
|
+
### Dependency notes
|
|
3619
|
+
|
|
3620
|
+
| Package | Why needed |
|
|
3621
|
+
|-----------------|---------------------------------------------------------------------|
|
|
3622
|
+
| `react-pageflip`| Flipbook animation — statically imported by both viewers |
|
|
3623
|
+
| `epubjs` | EPUB parsing and rendering — dynamically imported at runtime |
|
|
3624
|
+
| `html2canvas` | Screenshots EPUB iframe pages — dynamically imported at runtime |
|
|
3625
|
+
| `pdfjs-dist` | **Not required.** PDF.js 4.0.379 is loaded from `cdnjs.cloudflare.com` at runtime automatically |
|
|
3626
|
+
|
|
3627
|
+
> **Internet access required for PDFs:** The PDF viewer fetches pdf.js from `cdnjs.cloudflare.com` at runtime. EPUB rendering works fully offline once `epubjs` and `html2canvas` are installed.
|
|
3628
|
+
|
|
3629
|
+
---
|
|
3630
|
+
|
|
3631
|
+
## Exports
|
|
3632
|
+
|
|
3633
|
+
```js
|
|
3634
|
+
import BookViewer, { EpubViewer, PdfViewer, useBookDimensions } from "@bomjan133/react-crud-ui";
|
|
3635
|
+
```
|
|
3636
|
+
|
|
3637
|
+
| Export | Kind | Description |
|
|
3638
|
+
|---------------------|-----------|-------------------------------------------------------------------|
|
|
3639
|
+
| `BookViewer` | `default` | Recommended entry point — handles fetching + auto type-detect |
|
|
3640
|
+
| `EpubViewer` | named | Renders a pre-loaded EPUB blob URL as a flipbook |
|
|
3641
|
+
| `PdfViewer` | named | Renders a pre-loaded PDF blob URL as a flipbook (lazy render) |
|
|
3642
|
+
| `useBookDimensions` | named | Hook — computes responsive `pageWidth`/`pageHeight` from a ref |
|
|
3643
|
+
|
|
3644
|
+
---
|
|
3645
|
+
|
|
3646
|
+
## `BookViewer` (recommended)
|
|
3647
|
+
|
|
3648
|
+
Handles the full lifecycle: fetch → blob URL → type detection → delegates to `EpubViewer` or `PdfViewer`. This is the component most consumers should use.
|
|
3649
|
+
|
|
3650
|
+
### Props
|
|
3651
|
+
|
|
3652
|
+
| Prop | Type | Default | Description |
|
|
3653
|
+
|------------------|--------------------------------------------------|--------------|---------------------------------------------------------------|
|
|
3654
|
+
| `src` | `string` | — | URL to fetch the file from |
|
|
3655
|
+
| `file` | `File \| Blob` | — | File or Blob — skips fetching entirely |
|
|
3656
|
+
| `blobUrl` | `string` | — | Pre-resolved `blob:` URL — skips fetching entirely |
|
|
3657
|
+
| `type` | `'epub' \| 'pdf'` | auto-detect | Force file type (default: inferred from URL extension or mimeType) |
|
|
3658
|
+
| `mimeType` | `string` | — | Hint for type detection (`'application/pdf'`, `'application/epub+zip'`) |
|
|
3659
|
+
| `title` | `string` | `'Untitled'` | Displayed in the toolbar |
|
|
3660
|
+
| `canDownload` | `boolean` | `false` | Show a download button in the toolbar |
|
|
3661
|
+
| `downloadUrl` | `string` | — | `href` for the download button |
|
|
3662
|
+
| `totalPagesHint` | `number` | — | **PDF only** — pre-known page count. When provided, shows the correct page count immediately without waiting for the PDF to load |
|
|
3663
|
+
| `onFetch` | `async (src: string) => ArrayBuffer \| Blob` | — | Custom fetcher — use your own API client here (e.g. axios with auth headers) |
|
|
3664
|
+
| `fetchOptions` | `RequestInit` | — | Options passed to native `fetch()` when no `onFetch` is provided |
|
|
3665
|
+
|
|
3666
|
+
### Type auto-detection
|
|
3667
|
+
|
|
3668
|
+
Type is inferred in this order:
|
|
3669
|
+
1. `type` prop (if given)
|
|
3670
|
+
2. `mimeType` prop (`application/pdf` → `'pdf'`, `application/epub+zip` → `'epub'`)
|
|
3671
|
+
3. URL extension (`.pdf` → `'pdf'`, `.epub` → `'epub'`)
|
|
3672
|
+
4. Falls back to `'epub'` if nothing matches
|
|
3673
|
+
|
|
3674
|
+
### Examples
|
|
3675
|
+
|
|
3676
|
+
#### Load from a URL
|
|
3677
|
+
```jsx
|
|
3678
|
+
import BookViewer from "@bomjan133/react-crud-ui";
|
|
3679
|
+
|
|
3680
|
+
export default function Page() {
|
|
3681
|
+
return (
|
|
3682
|
+
<div style={{ height: "100vh" }}>
|
|
3683
|
+
<BookViewer
|
|
3684
|
+
src="https://example.com/my-book.epub"
|
|
3685
|
+
title="My Book"
|
|
3686
|
+
canDownload
|
|
3687
|
+
downloadUrl="https://example.com/my-book.epub"
|
|
3688
|
+
/>
|
|
3689
|
+
</div>
|
|
3690
|
+
);
|
|
3691
|
+
}
|
|
3692
|
+
```
|
|
3693
|
+
|
|
3694
|
+
#### Load a PDF with your API client (e.g. axios)
|
|
3695
|
+
```jsx
|
|
3696
|
+
import BookViewer from "@bomjan133/react-crud-ui";
|
|
3697
|
+
import api from "./api"; // your axios instance
|
|
3698
|
+
|
|
3699
|
+
export default function ReportViewer() {
|
|
3700
|
+
const handleFetch = async (src) => {
|
|
3701
|
+
const res = await api.get(src, { responseType: "arraybuffer" });
|
|
3702
|
+
return res.data; // ArrayBuffer — BookViewer wraps it in a Blob internally
|
|
3703
|
+
};
|
|
3704
|
+
|
|
3705
|
+
return (
|
|
3706
|
+
<BookViewer
|
|
3707
|
+
src="/api/documents/42/download"
|
|
3708
|
+
type="pdf"
|
|
3709
|
+
title="Annual Report 2024"
|
|
3710
|
+
onFetch={handleFetch}
|
|
3711
|
+
canDownload
|
|
3712
|
+
downloadUrl="/api/documents/42/download"
|
|
3713
|
+
/>
|
|
3714
|
+
);
|
|
3715
|
+
}
|
|
3716
|
+
```
|
|
3717
|
+
|
|
3718
|
+
#### Load from a `<input type="file">` upload
|
|
3719
|
+
```jsx
|
|
3720
|
+
import { useState } from "react";
|
|
3721
|
+
import BookViewer from "@bomjan133/react-crud-ui";
|
|
3722
|
+
|
|
3723
|
+
export default function LocalFileViewer() {
|
|
3724
|
+
const [file, setFile] = useState(null);
|
|
3725
|
+
|
|
3726
|
+
return (
|
|
3727
|
+
<div style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
|
|
3728
|
+
<input
|
|
3729
|
+
type="file"
|
|
3730
|
+
accept=".epub,.pdf"
|
|
3731
|
+
onChange={(e) => setFile(e.target.files[0] ?? null)}
|
|
3732
|
+
style={{ margin: 16 }}
|
|
3733
|
+
/>
|
|
3734
|
+
{file && (
|
|
3735
|
+
<div style={{ flex: 1 }}>
|
|
3736
|
+
<BookViewer file={file} title={file.name} />
|
|
3737
|
+
</div>
|
|
3738
|
+
)}
|
|
3739
|
+
</div>
|
|
3740
|
+
);
|
|
3741
|
+
}
|
|
3742
|
+
```
|
|
3743
|
+
|
|
3744
|
+
#### PDF with known page count (faster display)
|
|
3745
|
+
```jsx
|
|
3746
|
+
<BookViewer
|
|
3747
|
+
src="/files/report.pdf"
|
|
3748
|
+
type="pdf"
|
|
3749
|
+
totalPagesHint={48}
|
|
3750
|
+
title="Q4 Report"
|
|
3751
|
+
canDownload
|
|
3752
|
+
downloadUrl="/files/report.pdf"
|
|
3753
|
+
/>
|
|
3754
|
+
```
|
|
3755
|
+
|
|
3756
|
+
#### Pass custom fetch headers (e.g. JWT auth)
|
|
3757
|
+
```jsx
|
|
3758
|
+
<BookViewer
|
|
3759
|
+
src="/secure/book.epub"
|
|
3760
|
+
type="epub"
|
|
3761
|
+
title="Protected Book"
|
|
3762
|
+
fetchOptions={{
|
|
3763
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
3764
|
+
credentials: "include",
|
|
3765
|
+
}}
|
|
3766
|
+
/>
|
|
3767
|
+
```
|
|
3768
|
+
|
|
3769
|
+
---
|
|
3770
|
+
|
|
3771
|
+
## `EpubViewer` (direct use)
|
|
3772
|
+
|
|
3773
|
+
Use this when you have already resolved the blob URL yourself. It handles EPUB parsing, page scanning, and progressive screenshot capture internally.
|
|
3774
|
+
|
|
3775
|
+
### Props
|
|
3776
|
+
|
|
3777
|
+
| Prop | Type | Required | Description |
|
|
3778
|
+
|---------------|-----------|----------|---------------------------------------------------------------|
|
|
3779
|
+
| `blobUrl` | `string` | yes | `blob:` URL pointing to the EPUB file |
|
|
3780
|
+
| `pageWidth` | `number` | yes | Width of a single page in pixels (use `useBookDimensions`) |
|
|
3781
|
+
| `pageHeight` | `number` | yes | Height of a single page in pixels (use `useBookDimensions`) |
|
|
3782
|
+
| `title` | `string` | no | Displayed in the toolbar |
|
|
3783
|
+
| `canDownload` | `boolean` | no | Show download button in toolbar |
|
|
3784
|
+
| `downloadUrl` | `string` | no | `href` for the download button |
|
|
3785
|
+
|
|
3786
|
+
### How EPUB rendering works (two-phase)
|
|
3787
|
+
|
|
3788
|
+
**Phase 1 — Pre-scan (fast):** Each spine item is rendered into a hidden off-screen `<div>` using `epubjs`. The component measures the `scrollHeight` of the rendered iframe to calculate how many viewport-sized pages each section produces. A hard cap of **3,000 pages** is enforced.
|
|
3789
|
+
|
|
3790
|
+
**Phase 2 — Background capture:** After the flipbook mounts with placeholder slots, `html2canvas` screenshots each page progressively. A progress bar in the toolbar tracks completion (`0–100%`). Pages render in place as they complete — you can read from page 1 while later pages are still loading.
|
|
3791
|
+
|
|
3792
|
+
### Example
|
|
3793
|
+
|
|
3794
|
+
```jsx
|
|
3795
|
+
import { useRef } from "react";
|
|
3796
|
+
import { EpubViewer, useBookDimensions } from "@bomjan133/react-crud-ui";
|
|
3797
|
+
|
|
3798
|
+
export default function MyEpubReader({ epubBlobUrl }) {
|
|
3799
|
+
const containerRef = useRef(null);
|
|
3800
|
+
const { pageWidth, pageHeight } = useBookDimensions(containerRef);
|
|
3801
|
+
|
|
3802
|
+
return (
|
|
3803
|
+
<div ref={containerRef} style={{ width: "100%", height: "100vh" }}>
|
|
3804
|
+
{pageWidth > 0 && (
|
|
3805
|
+
<EpubViewer
|
|
3806
|
+
blobUrl={epubBlobUrl}
|
|
3807
|
+
pageWidth={pageWidth}
|
|
3808
|
+
pageHeight={pageHeight}
|
|
3809
|
+
title="My EPUB Book"
|
|
3810
|
+
/>
|
|
3811
|
+
)}
|
|
3812
|
+
</div>
|
|
3813
|
+
);
|
|
3814
|
+
}
|
|
3815
|
+
```
|
|
3816
|
+
|
|
3817
|
+
---
|
|
3818
|
+
|
|
3819
|
+
## `PdfViewer` (direct use)
|
|
3820
|
+
|
|
3821
|
+
Use this when you have already resolved the blob URL yourself. PDF pages are **lazily rendered** — only pages within ±2 pages of the current visible spread are rendered at any time.
|
|
3822
|
+
|
|
3823
|
+
### Props
|
|
3824
|
+
|
|
3825
|
+
| Prop | Type | Required | Description |
|
|
3826
|
+
|------------------|-----------|----------|---------------------------------------------------------------|
|
|
3827
|
+
| `blobUrl` | `string` | yes | `blob:` URL pointing to the PDF file |
|
|
3828
|
+
| `pageWidth` | `number` | yes | Width of a single page in pixels (use `useBookDimensions`) |
|
|
3829
|
+
| `pageHeight` | `number` | yes | Height of a single page in pixels (use `useBookDimensions`) |
|
|
3830
|
+
| `title` | `string` | no | Displayed in the toolbar |
|
|
3831
|
+
| `canDownload` | `boolean` | no | Show download button in toolbar |
|
|
3832
|
+
| `downloadUrl` | `string` | no | `href` for the download button |
|
|
3833
|
+
| `totalPagesHint` | `number` | no | Pre-known page count — shows total immediately without waiting for PDF load |
|
|
3834
|
+
|
|
3835
|
+
### How PDF rendering works
|
|
3836
|
+
|
|
3837
|
+
- PDF.js `4.0.379` is loaded **dynamically from CDN** (`cdnjs.cloudflare.com`) on first use — no `pdfjs-dist` npm package needed.
|
|
3838
|
+
- Pages are rendered to a `<canvas>` and converted to JPEG (quality `0.92`) data URLs.
|
|
3839
|
+
- A **lazy window of ±2 pages** around the current spread is maintained — when you flip, the next pages render ahead automatically.
|
|
3840
|
+
- Pages already rendered are cached in state for the lifetime of the component.
|
|
3841
|
+
|
|
3842
|
+
### Example
|
|
3843
|
+
|
|
3844
|
+
```jsx
|
|
3845
|
+
import { useRef } from "react";
|
|
3846
|
+
import { PdfViewer, useBookDimensions } from "@bomjan133/react-crud-ui";
|
|
3847
|
+
|
|
3848
|
+
export default function MyPdfReader({ pdfBlobUrl }) {
|
|
3849
|
+
const containerRef = useRef(null);
|
|
3850
|
+
const { pageWidth, pageHeight } = useBookDimensions(containerRef);
|
|
3851
|
+
|
|
3852
|
+
return (
|
|
3853
|
+
<div ref={containerRef} style={{ width: "100%", height: "100vh" }}>
|
|
3854
|
+
{pageWidth > 0 && (
|
|
3855
|
+
<PdfViewer
|
|
3856
|
+
blobUrl={pdfBlobUrl}
|
|
3857
|
+
pageWidth={pageWidth}
|
|
3858
|
+
pageHeight={pageHeight}
|
|
3859
|
+
title="My PDF"
|
|
3860
|
+
totalPagesHint={20}
|
|
3861
|
+
/>
|
|
3862
|
+
)}
|
|
3863
|
+
</div>
|
|
3864
|
+
);
|
|
3865
|
+
}
|
|
3866
|
+
```
|
|
3867
|
+
|
|
3868
|
+
---
|
|
3869
|
+
|
|
3870
|
+
## `useBookDimensions(containerRef)`
|
|
3871
|
+
|
|
3872
|
+
Observes a container element with `ResizeObserver` and computes page dimensions that fit the available viewport height while preserving an A4-like aspect ratio (`1:1.414`). Re-calculates on both container resize and window resize.
|
|
3873
|
+
|
|
3874
|
+
### Returns
|
|
3875
|
+
|
|
3876
|
+
| Field | Type | Description |
|
|
3877
|
+
|------------------|----------|-------------------------------------------------------------|
|
|
3878
|
+
| `containerWidth` | `number` | Current measured width of the container in pixels |
|
|
3879
|
+
| `spreadWidth` | `number` | Total width for a two-page spread (`pageWidth * 2`) |
|
|
3880
|
+
| `pageWidth` | `number` | Width of a single page in pixels |
|
|
3881
|
+
| `pageHeight` | `number` | Height of a single page in pixels |
|
|
3882
|
+
|
|
3883
|
+
> All values start at `0`. Guard against rendering before the first measurement: `{pageWidth > 0 && <EpubViewer ... />}`.
|
|
3884
|
+
|
|
3885
|
+
### Dimension logic
|
|
3886
|
+
|
|
3887
|
+
- Maximum page height is capped at `720px` or the available viewport height, whichever is smaller.
|
|
3888
|
+
- Navigation buttons (`40px` each) are subtracted from the container width before computing `pageWidth`.
|
|
3889
|
+
- Minimum page size is `150×200px`.
|
|
3890
|
+
|
|
3891
|
+
### Example
|
|
3892
|
+
|
|
3893
|
+
```jsx
|
|
3894
|
+
import { useRef } from "react";
|
|
3895
|
+
import { useBookDimensions } from "@bomjan133/react-crud-ui";
|
|
3896
|
+
|
|
3897
|
+
function DimensionDebug() {
|
|
3898
|
+
const ref = useRef(null);
|
|
3899
|
+
const { pageWidth, pageHeight, spreadWidth } = useBookDimensions(ref);
|
|
3900
|
+
|
|
3901
|
+
return (
|
|
3902
|
+
<div ref={ref} style={{ width: "100%" }}>
|
|
3903
|
+
<p>Spread: {spreadWidth}px — Each page: {pageWidth} × {pageHeight}px</p>
|
|
3904
|
+
</div>
|
|
3905
|
+
);
|
|
3906
|
+
}
|
|
3907
|
+
```
|
|
3908
|
+
|
|
3909
|
+
---
|
|
3910
|
+
|
|
3911
|
+
## Keyboard Navigation
|
|
3912
|
+
|
|
3913
|
+
Both viewers attach global `keydown` listeners while mounted:
|
|
3914
|
+
|
|
3915
|
+
| Key | Action |
|
|
3916
|
+
|---------------|---------------------------|
|
|
3917
|
+
| `→ ArrowRight`| Flip to next two pages |
|
|
3918
|
+
| `← ArrowLeft` | Flip to previous two pages|
|
|
3919
|
+
|
|
3920
|
+
Mouse click on page corners and touch swipe (distance threshold: `30px`) also trigger page flips.
|
|
3921
|
+
|
|
3922
|
+
---
|
|
3923
|
+
|
|
3924
|
+
## Container setup
|
|
3925
|
+
|
|
3926
|
+
The component needs a container with a defined width. Height drives the dimension calculation via `window.innerHeight`. A full-screen layout works best:
|
|
3927
|
+
|
|
3928
|
+
```jsx
|
|
3929
|
+
// Full page
|
|
3930
|
+
<div style={{ height: "100vh" }}>
|
|
3931
|
+
<BookViewer src="..." title="..." />
|
|
3932
|
+
</div>
|
|
3933
|
+
|
|
3934
|
+
// Inside a fixed-height panel
|
|
3935
|
+
<div style={{ width: "100%", height: 700 }}>
|
|
3936
|
+
<BookViewer src="..." title="..." />
|
|
3937
|
+
</div>
|
|
3938
|
+
```
|
|
3939
|
+
|
|
3940
|
+
> If the container has `height: 0` or `width: 0`, the viewer will not render (dimensions are `0` until the first ResizeObserver measurement).
|
|
3941
|
+
|
|
3942
|
+
---
|
|
3943
|
+
|
|
3944
|
+
## Troubleshooting
|
|
3945
|
+
|
|
3946
|
+
| Symptom | Likely cause | Fix |
|
|
3947
|
+
|---|---|---|
|
|
3948
|
+
| Blank/lined pages in EPUB | `html2canvas` failed to capture the iframe | Check browser console; usually caused by cross-origin iframe content |
|
|
3949
|
+
| "No readable sections found" | EPUB spine is empty | Verify the EPUB file is valid (`epubcheck`) |
|
|
3950
|
+
| "Failed to render EPUB pages" | `epubjs` threw during render | Check console; file may be malformed or DRM-protected |
|
|
3951
|
+
| PDF shows spinner forever | CDN blocked or offline | Check network tab for `cdnjs.cloudflare.com` requests; ensure internet access |
|
|
3952
|
+
| "Failed to load PDF" | PDF.js CDN request failed or the blob URL is invalid | Verify the blob URL is still alive and CDN is reachable |
|
|
3953
|
+
| Viewer is 0px tall / not visible | Container has no width or height | Wrap in a `div` with explicit dimensions |
|
|
3954
|
+
| `pageWidth` is `0` on first render | `useBookDimensions` hasn't measured yet | Guard with `{pageWidth > 0 && <EpubViewer />}` |
|
|
3955
|
+
| Pages out of order in EPUB | Long EPUB with many spine items | Expected during Phase 2 capture; pages fill in as captured |
|
|
3956
|
+
| EPUB stops at 3,000 pages | `MAX_PAGES` hard cap | By design — very long books are capped to prevent memory exhaustion |
|
|
3957
|
+
|
|
3958
|
+
</details>
|
|
3959
|
+
|
|
3960
|
+
<a id="toast-notifications"></a>
|
|
3961
|
+
<details>
|
|
3962
|
+
<summary><strong>8. Toast Notifications Guide</strong></summary>
|
|
3963
|
+
|
|
3964
|
+
Complete reference for the toast notification system in @bomjan133/react-crud-ui.
|
|
3965
|
+
|
|
3966
|
+
## Table of Contents
|
|
3967
|
+
1. [Setup](#setup)
|
|
3968
|
+
2. [useToast](#usetoast)
|
|
3969
|
+
3. [ToastContainer](#toastcontainer)
|
|
3970
|
+
4. [Toast Options](#toast-options)
|
|
3971
|
+
5. [Validation Error Example](#validation-error-example)
|
|
3972
|
+
|
|
3973
|
+
---
|
|
3974
|
+
|
|
3975
|
+
## Setup
|
|
3976
|
+
|
|
3977
|
+
Toasts are backed by an internal Zustand store, so no provider is required — just mount `ToastContainer` once near the root of your app and call `useToast()` from anywhere.
|
|
3978
|
+
|
|
3979
|
+
```jsx
|
|
3980
|
+
// src/App.jsx
|
|
3981
|
+
import { ToastContainer } from '@bomjan133/react-crud-ui';
|
|
3982
|
+
|
|
3983
|
+
function App() {
|
|
3984
|
+
return (
|
|
3985
|
+
<>
|
|
3986
|
+
{/* ...routes/layout... */}
|
|
3987
|
+
<ToastContainer />
|
|
3988
|
+
</>
|
|
3989
|
+
);
|
|
3990
|
+
}
|
|
3991
|
+
```
|
|
3992
|
+
|
|
3993
|
+
`ToastContainer` renders fixed to the bottom-right of the viewport (`bottom-4 right-4`) and stacks toasts vertically.
|
|
3994
|
+
|
|
3995
|
+
---
|
|
3996
|
+
|
|
3997
|
+
## `useToast`
|
|
3998
|
+
|
|
3999
|
+
```jsx
|
|
4000
|
+
import { useToast } from '@bomjan133/react-crud-ui';
|
|
4001
|
+
|
|
4002
|
+
function ProductForm() {
|
|
4003
|
+
const { success, error, warning, info, toast, dismiss, clearAll } = useToast();
|
|
4004
|
+
|
|
4005
|
+
const handleCreate = async () => {
|
|
4006
|
+
try {
|
|
4007
|
+
await createProduct();
|
|
4008
|
+
success('Product created successfully!');
|
|
4009
|
+
} catch (err) {
|
|
4010
|
+
error('Failed to create product', { title: 'Error' });
|
|
4011
|
+
}
|
|
4012
|
+
};
|
|
4013
|
+
|
|
4014
|
+
return <button onClick={handleCreate}>Create</button>;
|
|
4015
|
+
}
|
|
4016
|
+
```
|
|
4017
|
+
|
|
4018
|
+
### Returned API
|
|
4019
|
+
|
|
4020
|
+
| Method | Signature | Description |
|
|
4021
|
+
|--------|-----------|--------------|
|
|
4022
|
+
| `toast` | `(options) => id` | Add a toast with a fully custom `options` object (see below) |
|
|
4023
|
+
| `success` | `(message, options?) => id` | Shortcut for `toast({ type: 'success', message, ...options })` |
|
|
4024
|
+
| `error` | `(message, options?) => id` | Shortcut for `toast({ type: 'error', message, ...options })` |
|
|
4025
|
+
| `warning` | `(message, options?) => id` | Shortcut for `toast({ type: 'warning', message, ...options })` |
|
|
4026
|
+
| `info` | `(message, options?) => id` | Shortcut for `toast({ type: 'info', message, ...options })` |
|
|
4027
|
+
| `dismiss` | `(id) => void` | Remove a specific toast before its auto-dismiss timer fires |
|
|
4028
|
+
| `clearAll` | `() => void` | Remove every active toast |
|
|
4029
|
+
| `toasts` | `array` | Current list of active toast objects (used internally by `ToastContainer`) |
|
|
4030
|
+
|
|
4031
|
+
---
|
|
4032
|
+
|
|
4033
|
+
## `ToastContainer`
|
|
4034
|
+
|
|
4035
|
+
Renders every active toast. Mount it once, typically at the top level of your app (it has no props).
|
|
4036
|
+
|
|
4037
|
+
- Icon and color are derived automatically from `type` (`success`, `error`, `warning`, `info` — defaults to `info` for unknown types).
|
|
4038
|
+
- Clicking the `×` button calls `dismiss(id)`.
|
|
4039
|
+
- Toasts animate in from the right (`slide-in-from-right-full`).
|
|
4040
|
+
|
|
4041
|
+
```jsx
|
|
4042
|
+
import { ToastContainer } from '@bomjan133/react-crud-ui';
|
|
4043
|
+
|
|
4044
|
+
<ToastContainer />
|
|
4045
|
+
```
|
|
4046
|
+
|
|
4047
|
+
---
|
|
4048
|
+
|
|
4049
|
+
## Toast Options
|
|
4050
|
+
|
|
4051
|
+
Options accepted by `toast(options)` (and merged in by `success`/`error`/`warning`/`info`):
|
|
4052
|
+
|
|
4053
|
+
| Option | Type | Default | Description |
|
|
4054
|
+
|--------|------|---------|--------------|
|
|
4055
|
+
| `type` | `'success' \| 'error' \| 'warning' \| 'info'` | `'info'` | Determines icon and color |
|
|
4056
|
+
| `message` | `string` | — | Main toast text |
|
|
4057
|
+
| `title` | `string` | — | Optional bold heading shown above the message |
|
|
4058
|
+
| `details` | `object` | — | Field-level messages, e.g. API validation errors — see below |
|
|
4059
|
+
| `duration` | `number` (ms) | `5000` | Auto-dismiss delay. Pass `0` to disable auto-dismiss (toast stays until manually dismissed) |
|
|
4060
|
+
|
|
4061
|
+
### Example: with title
|
|
4062
|
+
|
|
4063
|
+
```jsx
|
|
4064
|
+
success('Your changes have been saved.', { title: 'Saved' });
|
|
4065
|
+
```
|
|
4066
|
+
|
|
4067
|
+
### Example: persistent toast
|
|
4068
|
+
|
|
4069
|
+
```jsx
|
|
4070
|
+
info('Upload in progress — this may take a few minutes.', { duration: 0 });
|
|
4071
|
+
// later, once done:
|
|
4072
|
+
dismiss(id);
|
|
4073
|
+
```
|
|
4074
|
+
|
|
4075
|
+
---
|
|
4076
|
+
|
|
4077
|
+
## Validation Error Example
|
|
4078
|
+
|
|
4079
|
+
`details` renders as a bulleted list of field-level messages below the main text — useful for surfacing API validation errors (each value can be a string or an array of strings):
|
|
4080
|
+
|
|
4081
|
+
```jsx
|
|
4082
|
+
try {
|
|
4083
|
+
await api.post('/products', data);
|
|
4084
|
+
} catch (err) {
|
|
4085
|
+
error('Please fix the errors below', {
|
|
4086
|
+
title: 'Validation failed',
|
|
4087
|
+
details: err.response?.data?.errors,
|
|
4088
|
+
// e.g. { name: ['Name is required'], price: 'Price must be positive' }
|
|
4089
|
+
});
|
|
4090
|
+
}
|
|
4091
|
+
```
|
|
4092
|
+
|
|
4093
|
+
</details>
|
|
4094
|
+
|
|
4095
|
+
<a id="utilities"></a>
|
|
4096
|
+
<details>
|
|
4097
|
+
<summary><strong>9. Utility Functions Guide</strong></summary>
|
|
4098
|
+
|
|
4099
|
+
Complete reference for the standalone utility functions in @bomjan133/react-crud-ui. All of these are pure functions with no dependency on any store or component — import only what you need.
|
|
4100
|
+
|
|
4101
|
+
```jsx
|
|
4102
|
+
import {
|
|
4103
|
+
cn,
|
|
4104
|
+
formatCurrency,
|
|
4105
|
+
formatDate,
|
|
4106
|
+
formatDateTime,
|
|
4107
|
+
formatRelativeTime,
|
|
4108
|
+
TimeStampFormat,
|
|
4109
|
+
truncate,
|
|
4110
|
+
capitalize,
|
|
4111
|
+
slugify,
|
|
4112
|
+
debounce,
|
|
4113
|
+
generateId,
|
|
4114
|
+
deepClone,
|
|
4115
|
+
isEmpty,
|
|
4116
|
+
getInitials,
|
|
4117
|
+
parseQueryString,
|
|
4118
|
+
buildQueryString,
|
|
4119
|
+
} from '@bomjan133/react-crud-ui';
|
|
4120
|
+
```
|
|
4121
|
+
|
|
4122
|
+
## Table of Contents
|
|
4123
|
+
1. [cn](#cnclassvalue)
|
|
4124
|
+
2. [Formatting](#formatting)
|
|
4125
|
+
3. [String helpers](#string-helpers)
|
|
4126
|
+
4. [Misc helpers](#misc-helpers)
|
|
4127
|
+
5. [Query string helpers](#query-string-helpers)
|
|
4128
|
+
|
|
4129
|
+
---
|
|
4130
|
+
|
|
4131
|
+
## `cn(...classValue)`
|
|
4132
|
+
|
|
4133
|
+
Merges Tailwind class names with [`clsx`](https://github.com/lukeed/clsx) + [`tailwind-merge`](https://github.com/dcastil/tailwind-merge), so conflicting utility classes (e.g. `p-2` vs `p-4`) resolve correctly instead of both being applied.
|
|
4134
|
+
|
|
4135
|
+
```jsx
|
|
4136
|
+
cn('px-2 py-1', isActive && 'bg-blue-500', className);
|
|
4137
|
+
```
|
|
4138
|
+
|
|
4139
|
+
Used internally by nearly every component in this library to accept a `className` override prop.
|
|
4140
|
+
|
|
4141
|
+
---
|
|
4142
|
+
|
|
4143
|
+
## Formatting
|
|
4144
|
+
|
|
4145
|
+
### `formatCurrency(amount, currency = 'NPR')`
|
|
4146
|
+
|
|
4147
|
+
Formats a number as currency using `Intl.NumberFormat('en-NP', ...)`.
|
|
4148
|
+
|
|
4149
|
+
```jsx
|
|
4150
|
+
formatCurrency(1500); // "NPR 1,500.00"
|
|
4151
|
+
formatCurrency(99.5, 'USD'); // "$99.50"
|
|
4152
|
+
```
|
|
4153
|
+
|
|
4154
|
+
### `formatDate(date, options = {})`
|
|
4155
|
+
|
|
4156
|
+
Formats a date as `Month Day, Year` (locale `en-US`) by default. `options` is merged into and overrides the `Intl.DateTimeFormat` options.
|
|
4157
|
+
|
|
4158
|
+
```jsx
|
|
4159
|
+
formatDate('2026-07-12'); // "July 12, 2026"
|
|
4160
|
+
formatDate('2026-07-12', { month: 'short' }); // "Jul 12, 2026"
|
|
4161
|
+
```
|
|
4162
|
+
|
|
4163
|
+
### `formatDateTime(date)`
|
|
4164
|
+
|
|
4165
|
+
Formats a date + time as `Mon Day, Year, HH:MM` (locale `en-US`, 2-digit hour/minute).
|
|
4166
|
+
|
|
4167
|
+
```jsx
|
|
4168
|
+
formatDateTime('2026-07-12T14:30:00'); // "Jul 12, 2026, 02:30 PM"
|
|
4169
|
+
```
|
|
4170
|
+
|
|
4171
|
+
### `TimeStampFormat(date)`
|
|
4172
|
+
|
|
4173
|
+
Formats a date as `YYYY-MM-DD HH:MM:SS` (24-hour, zero-padded). Returns `'-'` for a falsy input — handy for rendering optional timestamp fields in a table without a null check at the call site.
|
|
4174
|
+
|
|
4175
|
+
```jsx
|
|
4176
|
+
TimeStampFormat('2026-07-12T09:05:03'); // "2026-07-12 09:05:03"
|
|
4177
|
+
TimeStampFormat(null); // "-"
|
|
4178
|
+
```
|
|
4179
|
+
|
|
4180
|
+
### `formatRelativeTime(date)`
|
|
4181
|
+
|
|
4182
|
+
Formats a date relative to now (`"just now"`, `"5 minutes ago"`, `"3 hours ago"`, `"2 days ago"`). Falls back to `formatDate` once the difference exceeds a week.
|
|
4183
|
+
|
|
4184
|
+
```jsx
|
|
4185
|
+
formatRelativeTime(new Date(Date.now() - 5 * 60 * 1000)); // "5 minutes ago"
|
|
4186
|
+
```
|
|
4187
|
+
|
|
4188
|
+
---
|
|
4189
|
+
|
|
4190
|
+
## String helpers
|
|
4191
|
+
|
|
4192
|
+
### `truncate(str, length = 100)`
|
|
4193
|
+
|
|
4194
|
+
Truncates a string to `length` characters, appending `...` if it was cut. Returns `''` for a falsy input.
|
|
4195
|
+
|
|
4196
|
+
```jsx
|
|
4197
|
+
truncate('A very long product description...', 20); // "A very long product ..."
|
|
4198
|
+
```
|
|
4199
|
+
|
|
4200
|
+
### `capitalize(str)`
|
|
4201
|
+
|
|
4202
|
+
Uppercases the first character only. Returns `''` for a falsy input.
|
|
4203
|
+
|
|
4204
|
+
```jsx
|
|
4205
|
+
capitalize('hello world'); // "Hello world"
|
|
4206
|
+
```
|
|
4207
|
+
|
|
4208
|
+
### `slugify(str)`
|
|
4209
|
+
|
|
4210
|
+
Converts a string to a URL-safe slug: lowercases, trims, strips non-word characters, and collapses whitespace/underscores/dashes into single hyphens.
|
|
4211
|
+
|
|
4212
|
+
```jsx
|
|
4213
|
+
slugify(' Hello, World! '); // "hello-world"
|
|
4214
|
+
```
|
|
4215
|
+
|
|
4216
|
+
### `getInitials(name)`
|
|
4217
|
+
|
|
4218
|
+
Returns up to 2 uppercase initials from a space-separated name. Returns `''` for a falsy input.
|
|
4219
|
+
|
|
4220
|
+
```jsx
|
|
4221
|
+
getInitials('Sujan Bomjan'); // "SB"
|
|
4222
|
+
```
|
|
4223
|
+
|
|
4224
|
+
---
|
|
4225
|
+
|
|
4226
|
+
## Misc helpers
|
|
4227
|
+
|
|
4228
|
+
### `debounce(func, wait = 300)`
|
|
4229
|
+
|
|
4230
|
+
Returns a debounced version of `func` that only runs after `wait` ms of inactivity. Commonly used for search inputs.
|
|
4231
|
+
|
|
4232
|
+
```jsx
|
|
4233
|
+
const handleSearch = debounce((value) => {
|
|
4234
|
+
setSearchQuery(value);
|
|
4235
|
+
}, 300);
|
|
4236
|
+
|
|
4237
|
+
<input onChange={(e) => handleSearch(e.target.value)} />
|
|
4238
|
+
```
|
|
4239
|
+
|
|
4240
|
+
### `generateId()`
|
|
4241
|
+
|
|
4242
|
+
Returns a short random alphanumeric string (`Math.random().toString(36)`, 7 characters). Suitable for client-only keys (e.g. list item `key`s before a real ID exists) — **not** cryptographically secure and not guaranteed unique across a large dataset.
|
|
4243
|
+
|
|
4244
|
+
```jsx
|
|
4245
|
+
generateId(); // e.g. "f3k2p9a"
|
|
4246
|
+
```
|
|
4247
|
+
|
|
4248
|
+
### `deepClone(obj)`
|
|
4249
|
+
|
|
4250
|
+
Deep-clones a plain JSON-serializable object via `JSON.parse(JSON.stringify(obj))`. Does not preserve `Date`, `Map`, `Set`, `undefined` values, or functions — only use on plain data objects.
|
|
4251
|
+
|
|
4252
|
+
```jsx
|
|
4253
|
+
const copy = deepClone(originalFormValues);
|
|
4254
|
+
```
|
|
4255
|
+
|
|
4256
|
+
### `isEmpty(obj)`
|
|
4257
|
+
|
|
4258
|
+
Returns `true` for `null`/`undefined`, an empty array, or an object with no own keys; `false` otherwise (including for empty strings and `0`, which are returned as-is by the fallback).
|
|
4259
|
+
|
|
4260
|
+
```jsx
|
|
4261
|
+
isEmpty(null); // true
|
|
4262
|
+
isEmpty([]); // true
|
|
4263
|
+
isEmpty({}); // true
|
|
4264
|
+
isEmpty({ a: 1 }); // false
|
|
4265
|
+
```
|
|
4266
|
+
|
|
4267
|
+
---
|
|
4268
|
+
|
|
4269
|
+
## Query string helpers
|
|
4270
|
+
|
|
4271
|
+
### `parseQueryString(queryString)`
|
|
4272
|
+
|
|
4273
|
+
Parses a query string (with or without a leading `?`) into a plain object via `URLSearchParams`.
|
|
4274
|
+
|
|
4275
|
+
```jsx
|
|
4276
|
+
parseQueryString('?page=2&search=shoes'); // { page: '2', search: 'shoes' }
|
|
4277
|
+
```
|
|
4278
|
+
|
|
4279
|
+
### `buildQueryString(params)`
|
|
4280
|
+
|
|
4281
|
+
Builds a query string from an object, skipping keys whose value is `null`, `undefined`, or `''`.
|
|
4282
|
+
|
|
4283
|
+
```jsx
|
|
4284
|
+
buildQueryString({ page: 2, search: 'shoes', category: '' });
|
|
4285
|
+
// "page=2&search=shoes"
|
|
4286
|
+
```
|
|
4287
|
+
|
|
4288
|
+
Pairing the two is a common pattern for syncing table filters with the URL:
|
|
4289
|
+
|
|
4290
|
+
```jsx
|
|
4291
|
+
import { useSearchParams } from 'react-router-dom';
|
|
4292
|
+
import { buildQueryString, parseQueryString } from '@bomjan133/react-crud-ui';
|
|
4293
|
+
|
|
4294
|
+
const [searchParams, setSearchParams] = useSearchParams();
|
|
4295
|
+
const filters = parseQueryString(searchParams.toString());
|
|
4296
|
+
|
|
4297
|
+
const applyFilters = (next) => {
|
|
4298
|
+
setSearchParams(buildQueryString({ ...filters, ...next }));
|
|
4299
|
+
};
|
|
4300
|
+
```
|
|
4301
|
+
|
|
4302
|
+
</details>
|
|
30
4303
|
|
|
31
4304
|
## Installation
|
|
32
4305
|
|
|
@@ -95,10 +4368,8 @@ module.exports = {
|
|
|
95
4368
|
|
|
96
4369
|
### UI Components
|
|
97
4370
|
|
|
98
|
-
```jsx
|
|
99
4371
|
```jsx
|
|
100
4372
|
import { Button, Card, CardHeader, CardTitle, CardContent, Badge } from '@bomjan133/react-crud-ui'
|
|
101
|
-
```
|
|
102
4373
|
|
|
103
4374
|
function MyComponent() {
|
|
104
4375
|
return (
|
|
@@ -117,10 +4388,8 @@ function MyComponent() {
|
|
|
117
4388
|
|
|
118
4389
|
### Form Components
|
|
119
4390
|
|
|
120
|
-
```jsx
|
|
121
4391
|
```jsx
|
|
122
4392
|
import { QInput, QSelect, QSwitch, QForm } from '@bomjan133/react-crud-ui'
|
|
123
|
-
```
|
|
124
4393
|
|
|
125
4394
|
function MyForm() {
|
|
126
4395
|
const handleSubmit = (e) => {
|
|
@@ -156,10 +4425,8 @@ function MyForm() {
|
|
|
156
4425
|
|
|
157
4426
|
### DataTable
|
|
158
4427
|
|
|
159
|
-
```jsx
|
|
160
4428
|
```jsx
|
|
161
4429
|
import { DataTable } from '@bomjan133/react-crud-ui'
|
|
162
|
-
```
|
|
163
4430
|
|
|
164
4431
|
const columns = [
|
|
165
4432
|
{ header: 'Name', accessor: 'name', sortable: true },
|
|
@@ -195,10 +4462,8 @@ function UserTable() {
|
|
|
195
4462
|
|
|
196
4463
|
### CrudList
|
|
197
4464
|
|
|
198
|
-
```jsx
|
|
199
4465
|
```jsx
|
|
200
4466
|
import { CrudList } from '@bomjan133/react-crud-ui'
|
|
201
|
-
```
|
|
202
4467
|
|
|
203
4468
|
function ProductList() {
|
|
204
4469
|
const columns = [
|
|
@@ -223,10 +4488,8 @@ function ProductList() {
|
|
|
223
4488
|
|
|
224
4489
|
### CrudForm
|
|
225
4490
|
|
|
226
|
-
```jsx
|
|
227
4491
|
```jsx
|
|
228
4492
|
import { CrudForm } from '@bomjan133/react-crud-ui'
|
|
229
|
-
```
|
|
230
4493
|
import { z } from 'zod'
|
|
231
4494
|
|
|
232
4495
|
const schema = z.object({
|
|
@@ -260,9 +4523,7 @@ function ProductForm() {
|
|
|
260
4523
|
|
|
261
4524
|
```jsx
|
|
262
4525
|
import { create } from 'zustand'
|
|
263
|
-
```jsx
|
|
264
4526
|
import { createCrudStore } from '@bomjan133/react-crud-ui'
|
|
265
|
-
```
|
|
266
4527
|
import { apiClient } from './api'
|
|
267
4528
|
|
|
268
4529
|
// Create a product store
|