@bomjan133/react-crud-ui 1.2.5 → 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.
Files changed (78) hide show
  1. package/README.md +4630 -369
  2. package/bin/cli.js +387 -387
  3. package/dist/components/book-viewer/EpubViewer.d.ts +8 -0
  4. package/dist/components/book-viewer/PdfViewer.d.ts +9 -0
  5. package/dist/components/book-viewer/constants.d.ts +23 -0
  6. package/dist/components/book-viewer/hooks.d.ts +6 -0
  7. package/dist/components/book-viewer/index.d.ts +16 -0
  8. package/dist/components/book-viewer/ui.d.ts +16 -0
  9. package/dist/components/book-viewer/utils.d.ts +12 -0
  10. package/dist/components/crud/CrudDetail.d.ts +86 -0
  11. package/dist/components/crud/CrudForm.d.ts +33 -0
  12. package/dist/components/crud/CrudList.d.ts +105 -0
  13. package/dist/components/crud/DataTable.d.ts +64 -0
  14. package/dist/components/crud/EmptyState.d.ts +54 -0
  15. package/dist/components/crud/Loading.d.ts +32 -0
  16. package/dist/components/crud/Modal.d.ts +75 -0
  17. package/dist/components/crud/Pagination.d.ts +18 -0
  18. package/dist/components/crud/ServerErrorPage.d.ts +7 -0
  19. package/dist/components/layouts/AuthLayout.d.ts +32 -0
  20. package/dist/components/layouts/BreadcrumbContext.d.ts +4 -0
  21. package/dist/components/layouts/DashboardLayout.d.ts +41 -0
  22. package/dist/components/layouts/DetailView.d.ts +58 -0
  23. package/dist/components/layouts/Header.d.ts +13 -0
  24. package/dist/components/layouts/HeaderSlotContext.d.ts +4 -0
  25. package/dist/components/layouts/LoginPage.d.ts +50 -0
  26. package/dist/components/layouts/Sidebar.d.ts +38 -0
  27. package/dist/components/layouts/SidebarContext.d.ts +18 -0
  28. package/dist/components/layouts/index.d.ts +8 -0
  29. package/dist/components/toast/ToastContainer.d.ts +4 -0
  30. package/dist/components/toast/useUI.d.ts +33 -0
  31. package/dist/components/ui/CopyableField.d.ts +12 -0
  32. package/dist/components/ui/DownloadableButton.d.ts +15 -0
  33. package/dist/components/ui/alert-dialog.d.ts +26 -0
  34. package/dist/components/ui/alert.d.ts +8 -0
  35. package/dist/components/ui/avatar.d.ts +4 -0
  36. package/dist/components/ui/badge.d.ts +8 -0
  37. package/dist/components/ui/button.d.ts +6 -0
  38. package/dist/components/ui/calendar.d.ts +16 -0
  39. package/dist/components/ui/card.d.ts +7 -0
  40. package/dist/components/ui/checkbox.d.ts +2 -0
  41. package/dist/components/ui/collapsible.d.ts +3 -0
  42. package/dist/components/ui/date-picker.d.ts +2 -0
  43. package/dist/components/ui/date-range-picker.d.ts +2 -0
  44. package/dist/components/ui/dialog.d.ts +25 -0
  45. package/dist/components/ui/dropdown-menu.d.ts +23 -0
  46. package/dist/components/ui/form-fields.d.ts +19 -0
  47. package/dist/components/ui/input-group.d.ts +28 -0
  48. package/dist/components/ui/input.d.ts +2 -0
  49. package/dist/components/ui/label.d.ts +2 -0
  50. package/dist/components/ui/popover.d.ts +5 -0
  51. package/dist/components/ui/q-tabs.d.ts +18 -0
  52. package/dist/components/ui/rich-text-editor.d.ts +2 -0
  53. package/dist/components/ui/scroll-area.d.ts +3 -0
  54. package/dist/components/ui/search-select.d.ts +6 -0
  55. package/dist/components/ui/select.d.ts +12 -0
  56. package/dist/components/ui/separator.d.ts +2 -0
  57. package/dist/components/ui/skeleton.d.ts +4 -0
  58. package/dist/components/ui/switch.d.ts +2 -0
  59. package/dist/components/ui/table.d.ts +9 -0
  60. package/dist/components/ui/tabs.d.ts +6 -0
  61. package/dist/components/ui/textarea.d.ts +2 -0
  62. package/dist/components/ui/tiptap-editor.d.ts +2 -0
  63. package/dist/components/ui/tooltip.d.ts +6 -0
  64. package/dist/index.d.ts +42 -0
  65. package/dist/lib/utils.d.ts +61 -0
  66. package/dist/store/createCrudStore.d.ts +11 -0
  67. package/dist/store/useUIStore.d.ts +5 -0
  68. package/docs/1_GETTING_STARTED.md +333 -333
  69. package/docs/2_UI_COMPONENTS.md +586 -586
  70. package/docs/3_CRUD_COMPONENTS.md +974 -974
  71. package/docs/4_FORM_COMPONENTS.md +778 -778
  72. package/docs/5_LAYOUT_COMPONENTS.md +402 -402
  73. package/docs/6_STORE_FACTORY.md +456 -456
  74. package/docs/7_BOOK_VIEWER.md +365 -365
  75. package/docs/8_TOAST_NOTIFICATIONS.md +130 -130
  76. package/docs/9_UTILITIES.md +204 -204
  77. package/docs/README.md +83 -83
  78. package/package.json +1 -1
@@ -1,974 +1,974 @@
1
- # CRUD Components Guide
2
-
3
- Complete reference for CRUD components in @sujanbomjan/react-crud-ui.
4
-
5
- ## Table of Contents
6
- 1. [DataTable](#datatable)
7
- 2. [CrudList](#crudlist)
8
- 3. [CrudForm](#crudform)
9
- 4. [CrudDetail](#cruddetail)
10
- 5. [Pagination](#pagination)
11
- 6. [Loading Components](#loading-components)
12
- 7. [Empty States](#empty-states)
13
- 8. [Modal Components](#modal-components)
14
-
15
- ---
16
-
17
- ## DataTable
18
-
19
- A data table with sorting, pagination, search, row selection, clickable "link" columns, and a per-row dropdown actions menu.
20
-
21
- ### Props
22
-
23
- | Prop | Type | Default | Description |
24
- |------|------|---------|--------------|
25
- | `data` | `array` | `[]` | Rows to display (current page only — this component does not paginate client-side). |
26
- | `columns` | `array` | `[]` | Column definitions. See Column Definition below. |
27
- | `loading` | `boolean` | `false` | Shows a full-width `Loading` row instead of the data rows. |
28
- | `error` | `any` | `null` | Accepted but currently unused — nothing in the component reads or renders this value. |
29
- | `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 }`. |
30
- | `currentPage` | `number` | `1` | Current page (1-indexed). Used to compute serial numbers and passed through to the internal `Pagination` component. |
31
- | `pageSize` | `number` | `15` | Items per page. Used to compute serial numbers and passed to `Pagination`. |
32
- | `totalItems` | `number` | `0` | Total item count, passed to `Pagination`. |
33
- | `totalPages` | `number` | `1` | Total page count, passed to `Pagination`. |
34
- | `onPageChange` | `function` | - | Passed to `Pagination`; called with the new page. |
35
- | `onPageSizeChange` | `function` | - | Passed to `Pagination`; called when the page size changes. |
36
- | `sortable` | `boolean` | `true` | Global switch for sorting. A column must also set `sortable: true` to become sortable. |
37
- | `sortColumn` | `string` | `null` | The field currently sorted on (compared against each column's `sortKey`/`accessor`/`key`). |
38
- | `sortDirection` | `'asc' \| 'desc' \| null` | `null` | Current sort direction. |
39
- | `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)`. |
40
- | `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. |
41
- | `searchable` | `boolean` | `true` | Shows/hides the search input in the toolbar. |
42
- | `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. |
43
- | `onSearchChange` | `function` | - | Called with the search string, debounced 300ms after the user stops typing (fixed delay, not configurable). |
44
- | `searchPlaceholder` | `string` | `'Search...'` | Placeholder text for the search input. |
45
- | `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. |
46
- | `toolbarActions` | `node` | - | Content rendered on the right side of the toolbar (e.g. an "Add" button). |
47
- | `selectable` | `boolean` | `false` | Shows a checkbox column for row selection. |
48
- | `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). |
49
- | `onSelectionChange` | `function` | - | Called with the new array of selected row keys, on both row and select-all/clear actions. |
50
- | `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. |
51
- | `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). |
52
- | `striped` | `boolean` | `false` | Applies a light background to odd rows. |
53
- | `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. |
54
- | `compact` | `boolean` | `false` | Reduces cell vertical padding. |
55
- | `className` | `string` | - | Class for the outer wrapping `<div>`. |
56
- | `emptyTitle` | `string` | `'No data found'` | Empty-state title. |
57
- | `emptyDescription` | `string` | `'There are no items to display.'` | Empty-state description text. |
58
- | `emptyAction` | `string` | - | Label for an optional empty-state action button. |
59
- | `onEmptyAction` | `function` | - | Handler for the empty-state action button. |
60
- | `getRowKey` | `function` | `(row) => row.id \|\| row._id` | Derives a unique key per row; used for React keys and selection tracking. |
61
- | `showSerialNumber` | `boolean` | `true` | Shows a leading row-number column. |
62
- | `serialNumberHeader` | `string` | `'SN'` | Header label for the serial number column. |
63
- | `onViewClick` | `function` | - | If set, "clickable" columns (see `clickableColumns`) render their value as a button; clicking it calls `onViewClick(row)`. |
64
- | `onViewLink` | `function` | - | If set, "clickable" columns render their value as an `<a>`; called as `onViewLink(row)` to compute the `href`. Takes precedence over `onViewClick`. |
65
- | `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. |
66
- | `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. |
67
- | `enableTextClamping` | `boolean` | `true` | Truncates long string cell values (30+ characters) with an ellipsis and shows the full text in a tooltip on hover. |
68
- | `defaultMaxLines` | `number` | `1` | Default number of lines before clamping; overridable per-column via `column.maxLines`. |
69
- | `tableClassName` | `string` | - | Class passed to the root `<Table>`. |
70
- | `tableHeaderClassName` | `string` | - | Class passed to `<TableHeader>`. |
71
- | `tableBodyClassName` | `string` | - | Class passed to `<TableBody>`. |
72
- | `tableRowClassName` | `string` | - | Class merged onto every data/status `<TableRow>`. |
73
- | `tableHeadClassName` | `string` | - | Class merged onto every `<TableHead>` cell (selection, SN, data, and actions headers). |
74
- | `tableCellClassName` | `string` | - | Class merged onto every `<TableCell>` (selection, SN, data, actions, and loading/empty cells). |
75
- | `headerRowClassName` | `string` | - | Class merged onto the header `<TableRow>`. |
76
- | `statusRowClassName` | `string` | - | Class merged onto the loading/empty-state `<TableRow>`. |
77
- | `paginationClassName` | `string` | - | Class passed to the `Pagination` component. |
78
-
79
- > **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.
80
-
81
- ### Column Definition
82
-
83
- ```js
84
- const columns = [
85
- {
86
- // Value extraction — accessor wins over key
87
- accessor: 'name', // string, OR a function: (row) => value
88
- key: 'name', // fallback for accessor; also used as React key/sort field if accessor is absent
89
-
90
- // Header text — header wins over label
91
- header: 'Name',
92
- label: 'Name', // fallback if header is not set
93
-
94
- sortable: true, // enables sorting for this column (requires top-level sortable !== false)
95
- sortKey: 'name', // optional override of the field name used for sort comparisons/onSort
96
-
97
- render: (value, row, index) => (
98
- <span className="font-medium">{value}</span>
99
- ), // custom cell renderer, highest precedence
100
- format: (value, row) => value, // used only if render is not provided
101
-
102
- width: 200, // inline style: width
103
- minWidth: 120, // inline style: minWidth
104
- maxWidth: 300, // inline style: maxWidth (cells default to '300px' if unset)
105
-
106
- headerClassName: '', // extra className on the <TableHead>
107
- cellClassName: '', // extra className on the <TableCell>
108
-
109
- disableClamping: false, // opt this column out of enableTextClamping
110
- maxLines: 1, // per-column override of defaultMaxLines
111
- },
112
- ];
113
- ```
114
-
115
- > A column-level `className` field does not exist — the real per-column style hooks are `headerClassName` and `cellClassName`.
116
-
117
- ### Actions Column
118
-
119
- 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.
120
-
121
- ```js
122
- const actions = [
123
- {
124
- label: 'Edit',
125
- icon: PencilIcon, // optional component, rendered at 16px with right margin
126
- onClick: (row) => handleEdit(row),
127
- disabled: false, // optional
128
- },
129
- {
130
- label: 'Delete',
131
- icon: TrashIcon,
132
- variant: 'destructive', // only 'destructive' has special styling (red text)
133
- onClick: (row) => handleDelete(row),
134
- hidden: (row) => row.locked, // boolean, or a function(row) => boolean
135
- },
136
- ];
137
- ```
138
-
139
- - Items render in a `DropdownMenu` opened by an icon-only ghost button, in the same order as the `actions` array.
140
- - 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.
141
- - `disabled` maps directly to the underlying menu item's disabled state.
142
- - Clicking a row's actions cell does not trigger `onRowClick` (click propagation is stopped).
143
-
144
- ### Usage
145
-
146
- ```jsx
147
- import { DataTable } from '@sujanbomjan/react-crud-ui';
148
- import { PencilIcon, TrashIcon } from 'lucide-react';
149
-
150
- <DataTable
151
- data={users}
152
- columns={[
153
- { key: 'name', label: 'Name', sortable: true },
154
- { key: 'email', label: 'Email' },
155
- {
156
- key: 'status',
157
- label: 'Status',
158
- render: (value) => <Badge>{value}</Badge>,
159
- },
160
- ]}
161
- loading={isLoading}
162
- searchValue={search}
163
- onSearchChange={setSearch}
164
- currentPage={page}
165
- pageSize={15}
166
- totalItems={total}
167
- totalPages={Math.ceil(total / 15)}
168
- onPageChange={setPage}
169
- sortColumn={sortColumn}
170
- sortDirection={sortDirection}
171
- onSort={(field, direction) => {
172
- setSortColumn(field);
173
- setSortDirection(direction);
174
- }}
175
- actions={[
176
- { label: 'Edit', icon: PencilIcon, onClick: (row) => openEdit(row) },
177
- {
178
- label: 'Delete',
179
- icon: TrashIcon,
180
- variant: 'destructive',
181
- onClick: (row) => openDelete(row),
182
- },
183
- ]}
184
- emptyTitle="No users found"
185
- emptyDescription="Try adjusting your search or add a new user."
186
- />
187
-
188
- // Selectable rows with a clickable "name" column linking to a detail page
189
- <DataTable
190
- data={orders}
191
- columns={[{ key: 'name', label: 'Order' }, { key: 'amount', label: 'Amount' }]}
192
- selectable
193
- selectedRows={selectedIds}
194
- onSelectionChange={setSelectedIds}
195
- onViewLink={(row) => `/orders/${row.id}`}
196
- clickableColumns={['name']}
197
- getRowKey={(row) => row.id}
198
- />
199
- ```
200
-
201
- ---
202
-
203
- ## CrudList
204
-
205
- 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.
206
-
207
- ### Store integration (preferred)
208
-
209
- | Prop | Type | Default | Description |
210
- |------|------|---------|--------------|
211
- | `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. |
212
-
213
- > **Note if you're using this package's own [`createCrudStore`](./6_STORE_FACTORY.md):** 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](./6_STORE_FACTORY.md#compatibility-with-crudlist--crudform--cruddetail) for the full compatibility matrix (this also applies to `CrudDetail`'s `currentItem` vs. `item`, and `CrudForm`'s store mode).
214
-
215
- ### Direct data props (used if store not provided)
216
-
217
- | Prop | Type | Default | Description |
218
- |------|------|---------|--------------|
219
- | `data` | `array` | - | Row data. Used when `store?.items` is nullish. |
220
- | `loading` | `boolean` | `false` | Loading state, used when `store?.loading` is nullish. |
221
- | `error` | `any` | `null` | Error state, used when `store?.error` is nullish. |
222
- | `skipInitialFetch` | `boolean` | `false` | When a store is provided, skips the automatic call to `store.fetchList()` on mount. |
223
-
224
- ### Columns configuration
225
-
226
- | Prop | Type | Default | Description |
227
- |------|------|---------|--------------|
228
- | `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). |
229
-
230
- ### Pagination (direct-prop mode)
231
-
232
- | Prop | Type | Default | Description |
233
- |------|------|---------|--------------|
234
- | `currentPage` | `number` | `1` | Current page, used when no `store.pagination` value is available. |
235
- | `pageSize` | `number` | `15` | Page size fallback. |
236
- | `totalItems` | `number` | `0` | Total item count fallback. |
237
- | `totalPages` | `number` | `1` | Total page count fallback. |
238
- | `onPageChange` | `function(page)` | - | Called when the store has no `setPage` method. |
239
- | `onPageSizeChange` | `function(size)` | - | Called when the store has no `setPageSize` method. |
240
-
241
- > 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.
242
-
243
- ### Sorting
244
-
245
- | Prop | Type | Default | Description |
246
- |------|------|---------|--------------|
247
- | `sortColumn` | `string` | - | Current sort column, used when the store doesn't expose `sortColumn`. |
248
- | `sortDirection` | `'asc' \| 'desc' \| null` | - | Current sort direction fallback. |
249
- | `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. |
250
-
251
- ### Search
252
-
253
- | Prop | Type | Default | Description |
254
- |------|------|---------|--------------|
255
- | `searchValue` | `string` | `""` | Controlled search text, used only when the store has no `setFilters` method. |
256
- | `onSearchChange` | `function(value)` | - | Called on search input change when the store has no `setFilters` method. |
257
- | `searchPlaceholder` | `string` | `"Search..."` | Placeholder text for the search input. |
258
- | `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. |
259
- | `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. |
260
-
261
- 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()`.
262
-
263
- ### Selection
264
-
265
- | Prop | Type | Default | Description |
266
- |------|------|---------|--------------|
267
- | `selectable` | `boolean` | `false` | Enables row checkboxes and the "select all" header checkbox. |
268
- | `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). Controlled — the component does not manage this internally. |
269
- | `onSelectionChange` | `function(newSelectedRowKeys: array)` | - | Called with the full updated array whenever a row or "select all" checkbox changes. |
270
-
271
- ### CRUD Actions (direct-prop mode, used if paths not provided)
272
-
273
- | Prop | Type | Default | Description |
274
- |------|------|---------|--------------|
275
- | `onCreate` | `function()` | - | Called by the Create button when `createPath` is not set. |
276
- | `onView` | `function(row)` | - | Called by the row "View" action when `detailPath` is not set. |
277
- | `onEdit` | `function(row)` | - | Called by the row "Edit" action when `editPath` is not set. |
278
- | `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. |
279
- | `onRefresh` | `function()` | - | Called by the Refresh button when the store has no `fetchList` method. |
280
- | `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. |
281
-
282
- ### Table & button styling overrides
283
-
284
- Purely presentational, forwarded straight through to `DataTable`/toolbar buttons:
285
-
286
- | Prop | Type | Description |
287
- |------|------|-------------|
288
- | `tableClassName` | `string` | Class on the `<Table>` element. |
289
- | `tableHeaderClassName` | `string` | Class on `<TableHeader>`. |
290
- | `tableBodyClassName` | `string` | Class on `<TableBody>`. |
291
- | `tableRowClassName` | `string` | Class on each `<TableRow>` (data + status rows). |
292
- | `tableHeadClassName` | `string` | Class on each `<TableHead>` cell. |
293
- | `tableCellClassName` | `string` | Class on each `<TableCell>`. |
294
- | `headerRowClassName` | `string` | Class on the header `<TableRow>`. |
295
- | `statusRowClassName` | `string` | Class on the loading/empty status row. |
296
- | `paginationClassName` | `string` | Class passed to the `Pagination` component. |
297
- | `createButtonClassName` | `string` | Class on the Create button. |
298
- | `refreshButtonClassName` | `string` | Class on the Refresh button. |
299
- | `exportButtonClassName` | `string` | Class on the default Export button. |
300
- | `bulkActionButtonClassName` | `string` | Class applied to every bulk-action button. |
301
-
302
- ### Navigation paths
303
-
304
- | Prop | Type | Default | Description |
305
- |------|------|---------|--------------|
306
- | `createPath` | `string` | - | If set, the Create button navigates here (via `react-router`'s `navigate`) instead of calling `onCreate`. Used as-is — no suffix appended. |
307
- | `detailPath` | `string` | - | If set, the row "View" action and clickable-name columns navigate to `` `${detailPath}/${getRowKey(row)}` `` instead of calling `onView`. |
308
- | `editPath` | `string` | - | If set, the row "Edit" action navigates to `` `${editPath}/${getRowKey(row)}/edit` `` instead of calling `onEdit`. |
309
-
310
- > **Correction:** there is no `viewPath` prop — the real prop is `detailPath`. An earlier version of this doc used `viewPath`, which has no effect.
311
-
312
- ### Breadcrumb helper
313
-
314
- | Prop | Type | Default | Description |
315
- |------|------|---------|--------------|
316
- | `getBreadcrumbName` | `function(row)` | - | Returns a display name passed as `location.state.breadcrumbName` when navigating to the detail page. |
317
- | `customBreadcrumbPaths` | `object` | - | Static breadcrumb path map passed as `location.state.customBreadcrumbPaths` on create/view/edit navigation, unless `getCustomBreadcrumbPath` is given. |
318
- | `getCustomBreadcrumbPath` | `function(row)` | - | Per-row/per-action function that computes breadcrumb paths, overriding `customBreadcrumbPaths` when provided. |
319
- | `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. |
320
- | `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state object passed to create/view/edit navigations. |
321
-
322
- ### Custom actions
323
-
324
- | Prop | Type | Default | Description |
325
- |------|------|---------|--------------|
326
- | `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 }`. |
327
- | `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 }`. |
328
-
329
- ### Labels
330
-
331
- | Prop | Type | Default | Description |
332
- |------|------|---------|--------------|
333
- | `title` | `string` | - | Card title text. Also used verbatim in the delete-success toast: `` `${title} Deleted successfully` `` (note: uses `title`, not `itemName`). |
334
- | `description` | `string` | - | Card description text. |
335
- | `createLabel` | `string` | `"Create"` | Create button label. |
336
- | `refreshLabel` | `string` | `"Refresh"` | Refresh button label. |
337
- | `exportLabel` | `string` | `"Export"` | Default Export button label. |
338
- | `viewLabel` | `string` | `"View"` | Row "View" action label. |
339
- | `editLabel` | `string` | `"Edit"` | Row "Edit" action label. |
340
- | `deleteLabel` | `string` | `"Delete"` | Row "Delete" action label. |
341
- | `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.` ``). |
342
-
343
- ### Row key
344
-
345
- | Prop | Type | Default | Description |
346
- |------|------|---------|--------------|
347
- | `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. |
348
-
349
- ### Appearance
350
-
351
- | Prop | Type | Default | Description |
352
- |------|------|---------|--------------|
353
- | `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>`. |
354
- | `showToolbar` | `boolean` | `true` | Whether to render the toolbar (header actions, bulk actions, export, refresh, create) — independent of `showHeader`. |
355
- | `compact` | `boolean` | `false` | Passed to `DataTable` to tighten row padding. |
356
- | `className` | `string` | - | Class on the outer `Card`/`div` wrapper. |
357
- | `filters` | `node` | - | Custom filter control(s) rendered in the `DataTable` toolbar next to the search box. |
358
- | `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. |
359
- | `showEditButton` | `boolean` | `true` | Hides the built-in row "Edit" action when `false`, even if `editPath`/`onEdit` is set. |
360
- | `showDeleteButton` | `boolean` | `true` | Hides the built-in row "Delete" action when `false`, even if delete is otherwise available. |
361
- | `clickableColumns` | `array` | `[]` | Accessor keys that should render as clickable links/buttons to the detail view. Pass `["*"]` for all columns. Forwarded to `DataTable`. |
362
-
363
- > **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.
364
-
365
- ### Delete confirmation
366
-
367
- | Prop | Type | Default | Description |
368
- |------|------|---------|--------------|
369
- | `deleteConfirmTitle` | `string` | - | Overrides the delete modal's title (default: `` `Delete ${itemName}` ``). |
370
- | `deleteConfirmDescription` | `string` | - | Overrides the modal's description (default asks to confirm deleting the resolved item name). |
371
- | `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`. |
372
-
373
- > There is no `onDeleteSuccess` callback — delete success always shows a hardcoded toast using `title` (see Labels above).
374
-
375
- ### Usage
376
-
377
- **Basic (store-based):**
378
-
379
- ```jsx
380
- import { CrudList } from '@sujanbomjan/react-crud-ui';
381
- import { useUserStore } from './stores/useUserStore';
382
-
383
- const columns = [
384
- { accessor: 'name', header: 'Name', sortable: true },
385
- { accessor: 'email', header: 'Email' },
386
- {
387
- accessor: 'createdAt',
388
- header: 'Created',
389
- format: (value) => new Date(value).toLocaleDateString(),
390
- },
391
- ];
392
-
393
- function UsersPage() {
394
- const store = useUserStore();
395
-
396
- return (
397
- <CrudList
398
- store={store}
399
- title="Users"
400
- description="Manage your organization's users"
401
- columns={columns}
402
- createPath="/users/create"
403
- detailPath="/users"
404
- editPath="/users"
405
- itemName="user"
406
- getRowKey={(row) => row.id}
407
- />
408
- );
409
- }
410
- ```
411
-
412
- **Selection + bulk actions (direct data props):**
413
-
414
- ```jsx
415
- import { useState } from 'react';
416
- import { CrudList } from '@sujanbomjan/react-crud-ui';
417
- import { Archive, Trash2 } from 'lucide-react';
418
-
419
- const columns = [
420
- { accessor: 'name', header: 'Name', sortable: true },
421
- { accessor: 'status', header: 'Status' },
422
- ];
423
-
424
- function InvoicesPage({ invoices, isLoading }) {
425
- const [selectedRows, setSelectedRows] = useState([]);
426
-
427
- const bulkActions = [
428
- { label: 'Archive', icon: Archive, onClick: (rowKeys) => archiveInvoices(rowKeys) },
429
- { label: 'Delete', icon: Trash2, variant: 'destructive', onClick: (rowKeys) => deleteInvoices(rowKeys) },
430
- ];
431
-
432
- return (
433
- <CrudList
434
- data={invoices}
435
- loading={isLoading}
436
- columns={columns}
437
- title="Invoices"
438
- itemName="invoice"
439
- selectable
440
- selectedRows={selectedRows}
441
- onSelectionChange={setSelectedRows}
442
- bulkActions={bulkActions}
443
- onCreate={() => openCreateModal()}
444
- onView={(row) => openDetailModal(row)}
445
- onEdit={(row) => openEditModal(row)}
446
- onDelete={async (row) => deleteInvoice(row.id)}
447
- getRowKey={(row) => row.id}
448
- />
449
- );
450
- }
451
- ```
452
-
453
- ---
454
-
455
- ## CrudForm
456
-
457
- 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).
458
-
459
- - **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.
460
- - **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.
461
-
462
- `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.
463
-
464
- > ⚠️ **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.
465
-
466
- ### Props
467
-
468
- | Prop | Type | Default | Description |
469
- |------|------|---------|--------------|
470
- | `useStore` | `function` | - | Zustand store hook. Combined with `children` to trigger store mode. See store-shape warning above. |
471
- | `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. |
472
- | `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 })`. |
473
- | `defaultValues` | `object` | `{}` | Fields mode only. Initial `react-hook-form` values, used when `initialData` is not provided. |
474
- | `validationSchema` | Zod schema | - | Fields mode only. Passed to `zodResolver` for `react-hook-form` validation. No effect in store mode. |
475
- | `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`. |
476
- | `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. |
477
- | `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. |
478
- | `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). |
479
- | `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. |
480
- | `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. |
481
- | `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. |
482
- | `description` | `string` | - | Subtitle shown under the title, both modes. |
483
- | `submitLabel` | `string` | `"Save"` | Submit button text, both modes. Shows a spinner + "Saving..." while submitting. |
484
- | `cancelLabel` | `string` | `"Cancel"` | Cancel button text, both modes (subject to the `onCancel` visibility rule above). |
485
- | `columns` | `1 \| 2 \| 3 \| 4` | `1` | Fields mode only. Grid column count for laying out `fields`. No effect in store mode. |
486
- | `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). |
487
- | `showFooter` | `boolean` | `true` | Shows/hides the Cancel/Submit button row, both modes. |
488
- | `showBack` | `boolean` | `true` | Shows the back-arrow icon button. See the asymmetric per-mode behavior under `onBack`. |
489
- | `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. |
490
- | `listPath` | `string` | - | Fallback destination for `handleBack()` when no `onBack` is given, in both modes. |
491
- | `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. |
492
- | `className` | `string` | - | Applied to the outer `Card`/`div` wrapper, both modes. |
493
- | `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`. |
494
- | `loading` | `boolean` | `false` | OR'd with the store's own `loading` (store mode). Disables fields and combines with `submitting` to disable Submit. |
495
- | `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...". |
496
-
497
- > **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.
498
-
499
- **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.
500
-
501
- ### Usage
502
-
503
- **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`:
504
-
505
- ```jsx
506
- import { CrudForm, QInput } from '@sujanbomjan/react-crud-ui';
507
-
508
- function UserForm() {
509
- return (
510
- <CrudForm
511
- title="User"
512
- useStore={useUserFormStore}
513
- listPath="/users"
514
- getBreadcrumbName={(values) => values.name}
515
- onBeforeSubmit={(values) => ({ ...values, email: values.email.trim().toLowerCase() })}
516
- onAfterCreate={(result, navigate) => navigate(`/users/${result.uuid}/edit`)}
517
- >
518
- <QInput
519
- name="name"
520
- label="Name"
521
- required
522
- value={useUserFormStore((s) => s.form.values.name) ?? ''}
523
- onChange={(val) => useUserFormStore.getState().setFormValue('name', val)}
524
- />
525
- <QInput
526
- name="email"
527
- label="Email"
528
- required
529
- value={useUserFormStore((s) => s.form.values.email) ?? ''}
530
- onChange={(val) => useUserFormStore.getState().setFormValue('email', val)}
531
- />
532
- </CrudForm>
533
- );
534
- }
535
- ```
536
-
537
- **Fields mode** (self-contained `react-hook-form`, no store, no router param required — pass `initialData` for edit, omit it for create):
538
-
539
- ```jsx
540
- import { CrudForm } from '@sujanbomjan/react-crud-ui';
541
-
542
- <CrudForm
543
- title="User"
544
- description="Basic account details"
545
- fields={[
546
- { name: 'email', type: 'email', label: 'Email', required: true },
547
- {
548
- name: 'role',
549
- type: 'select',
550
- label: 'Role',
551
- options: [
552
- { value: 'admin', label: 'Admin' },
553
- { value: 'member', label: 'Member' },
554
- ],
555
- },
556
- ]}
557
- initialData={editingUser} // omit for create mode
558
- columns={2}
559
- onSubmit={async (data) => {
560
- await api.saveUser(data);
561
- toast.success('Saved');
562
- }}
563
- onCancel={() => navigate('/users')}
564
- onBack={() => navigate('/users')}
565
- />
566
- ```
567
-
568
- ---
569
-
570
- ## CrudDetail
571
-
572
- 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.
573
-
574
- **Mode selection is automatic and based on `children`:**
575
- - **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).
576
- - **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.**
577
-
578
- `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`.
579
-
580
- > ⚠️ **`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.
581
-
582
- ### How the record id and fetch are resolved
583
-
584
- - 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.**
585
- - 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)`.
586
- - Delete calls the store's `delete(id)` method (or your own `onDelete` callback) and then navigates back on success.
587
-
588
- ### Loading / error / not-found states
589
-
590
- - **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.
591
- - **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.
592
- - **Not found** (`!data` after loading, no error): renders "No {itemName} found" with a Back button.
593
-
594
- ### Props
595
-
596
- | Prop | Type | Default | Description |
597
- |------|------|---------|--------------|
598
- | `useStore` | `function` | - | Zustand-style hook, called as `useStore()`. Component reads `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), and `delete` off the returned store. |
599
- | `children` | `function` | - | Render prop `(data) => ReactNode`. Only used when `useStore` is also set; otherwise ignored. |
600
- | `data` | `object` | `null` | Direct data mode: record to display (`propData \|\| storeData`), used in place of / alongside the store's `currentItem`. |
601
- | `paramName` | `string` | `"uuid"` | Name of the route param (via `useParams()`) used as the record id. |
602
- | `loading` | `boolean` | `false` | External loading flag, OR'd with the store's own `loading`. |
603
- | `error` | `any` | `null` | External error value, OR'd with the store's own `error`. |
604
- | `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). |
605
- | `onBack` | `function` | - | Custom back handler. If omitted, falls back to navigating to `listPath`, or `navigate(-1)` if no `listPath`. |
606
- | `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). |
607
- | `onDelete` | `function(data)` | - | Custom delete handler (awaited). If omitted, falls back to the store's `delete(id)`, then navigates back on success. |
608
- | `listPath` | `string` | - | Path the Back button navigates to when `onBack` isn't provided. |
609
- | `editPath` | `string` | - | Base path used to build the default edit destination (`${editPath}/{id}/edit`) when `onEdit` isn't provided. |
610
- | `title` | `string` | - | Card title text. **Only rendered in fields-based mode**; ignored in store+children mode (whose header title comes from `getBreadcrumbName(data)` instead). |
611
- | `description` | `string` | - | Description text shown under the title in both modes. |
612
- | `editLabel` | `string` | `"Edit"` | Label for the Edit item in the actions dropdown. |
613
- | `deleteLabel` | `string` | `"Delete"` | Label for the Delete item in the actions dropdown. |
614
- | `backLabel` | `string` | `"Back"` | Label for Back buttons. |
615
- | `itemName` | `string` | `"item"` | Generic noun used in loading/empty text and as a fallback for the delete-confirmation item name. |
616
- | `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`. |
617
- | `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. |
618
- | `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. |
619
- | `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. |
620
- | `customBreadcrumbPaths` | `object` | - | Static breadcrumb path overrides passed through `navigate(..., { state })` when navigating to edit. |
621
- | `getCustomBreadcrumbPath` | `function(data)` | - | Dynamic version of `customBreadcrumbPaths`; takes precedence when provided. |
622
- | `getParentPath` | `function(data)` | - | Returns a parent path used to build breadcrumb path overrides for edit navigation, when neither of the above apply. |
623
- | `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state passed when navigating to edit. |
624
- | `showEditButton` | `boolean` | `true` | Whether the Edit action appears in the dropdown (also requires `onEdit` or `editPath` to be set). |
625
- | `showDeleteButton` | `boolean` | `true` | Whether the Delete action appears in the dropdown (also requires `onDelete` or the store's `delete` to be available). |
626
- | `showHeader` | `boolean` | `true` | Whether to render the header/title row (and its actions dropdown) at all. |
627
- | `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). |
628
- | `columns` | `1 \| 2 \| 3` | `2` | Number of grid columns for the fields grid (fields-based mode). |
629
- | `className` | `string` | - | Root wrapper class (store+children mode) or `Card` class (fields-based mode). |
630
- | `cardHeaderClassName` | `string` | - | Applied to `CardHeader` (fields-based mode). |
631
- | `headerClassName` | `string` | - | Applied to the header's inner flex container (store+children mode only). |
632
- | `titleClassName` | `string` | - | Applied to `CardTitle` (fields-based mode only). |
633
- | `descriptionClassName` | `string` | - | Applied to `CardDescription` (fields-based mode only). |
634
- | `fieldsGridClassName` | `string` | - | Applied to the fields grid container. |
635
- | `fieldItemClassName` | `string` | - | Applied to each individual field's wrapper. |
636
- | `fieldLabelClassName` | `string` | - | Applied to each field's label element. |
637
- | `fieldValueClassName` | `string` | - | Applied to each field's value element. |
638
- | `metaClassName` | `string` | - | Applied to the Created/Updated/ID meta row container. |
639
- | `metaItemClassName` | `string` | - | Applied to each item within the meta row. |
640
- | `backButtonClassName` | `string` | - | Applied to the Back icon button (store+children mode header). |
641
- | `actionsDropdownItemClassName` | `string` | - | Applied to the Edit item inside the actions dropdown only (not Delete or additional-action items). |
642
- | `loadingStateClassName` | `string` | - | Applied to the loading `Card` in store+children mode only; no effect in fields-based mode. |
643
-
644
- > **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.
645
-
646
- ### Usage
647
-
648
- **Store-driven, custom render (render-prop `children`):**
649
-
650
- ```jsx
651
- <CrudDetail
652
- useStore={useUserStore}
653
- listPath="/users"
654
- editPath="/users"
655
- getBreadcrumbName={(user) => user.name}
656
- additionalActions={[
657
- { label: 'Reset Password', onClick: (user) => resetPassword(user.uuid) },
658
- ]}
659
- >
660
- {(user) => (
661
- <Card>
662
- <CardContent className="py-6">
663
- <p>{user.email}</p>
664
- </CardContent>
665
- </Card>
666
- )}
667
- </CrudDetail>
668
- ```
669
-
670
- Requires a route like `/users/:uuid` (or pass `paramName="id"` for `/users/:id`).
671
-
672
- **Direct data + fields array (no store):**
673
-
674
- ```jsx
675
- <CrudDetail
676
- title="User"
677
- data={user}
678
- fields={[
679
- { name: 'email', label: 'Email', type: 'email' },
680
- { name: 'status', label: 'Status', type: 'status' },
681
- { name: 'created_at', label: 'Joined', type: 'date' },
682
- ]}
683
- onBack={() => navigate('/users')}
684
- onEdit={(u) => navigate(`/users/${u.uuid}/edit`)}
685
- onDelete={(u) => deleteUser(u.uuid)}
686
- />
687
- ```
688
-
689
- ---
690
-
691
- ## Pagination
692
-
693
- ### Props
694
-
695
- | Prop | Type | Default | Description |
696
- |------|------|---------|--------------|
697
- | `currentPage` | `number` | `1` | The active page (1-indexed). |
698
- | `totalPages` | `number` | `1` | Total number of pages. Controls whether Next/Last buttons are enabled and how page numbers are rendered. |
699
- | `totalItems` | `number` | `0` | Total item count across all pages, used only to compute the "Showing X to Y of Z results" text. |
700
- | `pageSize` | `number` | `15` | Current page size; also drives the value shown in the rows-per-page select. |
701
- | `pageSizeOptions` | `number[]` | `[15, 20, 50, 100]` | Options rendered in the rows-per-page dropdown. |
702
- | `onPageChange` | `function(page)` | - | Called with the target page number when First/Prev/page-number/Next/Last is clicked. |
703
- | `onPageSizeChange` | `function(size)` | - | Called with the new numeric page size when the rows-per-page select changes. |
704
- | `showPageSizeSelector` | `boolean` | `true` | Show/hide the "Rows per page" selector. |
705
- | `showInfo` | `boolean` | `true` | Show/hide the "Showing X to Y of Z results" text (also requires `totalItems > 0`). |
706
- | `className` | `string` | - | Extra classes merged onto the root container. |
707
-
708
- Not a Radix wrapper — a plain `div` composed from this library's own `Button` and `Select`. No extra props pass through.
709
-
710
- ### Usage
711
-
712
- ```jsx
713
- import { Pagination } from '@sujanbomjan/react-crud-ui';
714
-
715
- <Pagination
716
- currentPage={pagination.page}
717
- totalPages={pagination.totalPages}
718
- totalItems={pagination.totalItems}
719
- pageSize={pagination.pageSize}
720
- pageSizeOptions={[15, 20, 50, 100]}
721
- onPageChange={(page) => setPage(page)}
722
- onPageSizeChange={(size) => setPageSize(size)}
723
- />
724
- ```
725
-
726
- ---
727
-
728
- ## Loading Components
729
-
730
- ### `Loading`
731
-
732
- | Prop | Type | Default | Description |
733
- |------|------|---------|--------------|
734
- | `variant` | `'spinner' \| 'dots' \| 'pulse' \| 'skeleton'` | `'spinner'` | Visual style. Any unrecognized value falls back to the spinner. |
735
- | `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. |
736
- | `text` | `string` | - | Optional caption below the loader. |
737
- | `fullScreen` | `boolean` | `false` | Adds `fixed inset-0 z-50` to cover the viewport. |
738
- | `overlay` | `boolean` | `false` | Adds a translucent blurred background. |
739
- | `className` | `string` | - | Extra classes merged onto the root container. |
740
-
741
- ### `LoadingOverlay`
742
-
743
- | Prop | Type | Default | Description |
744
- |------|------|---------|--------------|
745
- | `loading` | `boolean` | `false` | When true, renders an absolutely-positioned, blurred overlay on top of `children`. **The prop is `loading`, not `visible`.** |
746
- | `children` | `node` | - | The content the overlay layers on top of (always rendered underneath). |
747
- | `text` | `string` | - | Passed straight through to the internal `<Loading text={text} />` shown while `loading` is true. |
748
- | `className` | `string` | - | Extra classes on the root wrapper. |
749
-
750
- There is no `size`/`variant` control — the internal loader is always the default spinner at default size.
751
-
752
- ### `LoadingButton`
753
-
754
- | Prop | Type | Default | Description |
755
- |------|------|---------|--------------|
756
- | `loading` | `boolean` | `false` | When true, disables the button and swaps its content for a spinner + `loadingText`. |
757
- | `loadingText` | `string` | `'Loading...'` | Text shown next to the spinner while `loading` is true. |
758
- | `children` | `node` | - | Normal button content, shown when not loading. |
759
- | `disabled` | `boolean` | - | Manually disable the button; internally OR'd with `loading`. |
760
- | `className` | `string` | - | Extra classes passed to the underlying `Button`. |
761
- | `...props` | - | - | Anything else (`onClick`, `variant`, `size`, `type`, etc.) spreads onto the underlying `Button`. |
762
-
763
- `LoadingButton` is a `forwardRef` component — a `ref` attaches to the underlying `Button`/native `<button>`.
764
-
765
- ### Usage
766
-
767
- ```jsx
768
- import { Loading, LoadingOverlay, LoadingButton } from '@sujanbomjan/react-crud-ui';
769
-
770
- <Loading />
771
- <Loading size="sm" />
772
- <Loading variant="dots" size="lg" text="Loading data..." />
773
- <Loading variant="skeleton" />
774
- <Loading fullScreen overlay text="Please wait..." />
775
-
776
- <LoadingOverlay loading={isLoading} text="Refreshing...">
777
- <ProductTable data={products} />
778
- </LoadingOverlay>
779
-
780
- <LoadingButton loading={isSubmitting} loadingText="Saving..." onClick={handleSubmit}>
781
- Save Changes
782
- </LoadingButton>
783
- ```
784
-
785
- ---
786
-
787
- ## Empty States
788
-
789
- ### `EmptyState`
790
-
791
- | Prop | Type | Default | Description |
792
- |------|------|---------|--------------|
793
- | `icon` | `component` | `FileQuestion` | Icon rendered inside the circular badge. |
794
- | `title` | `string` | `'No data found'` | Heading text. |
795
- | `description` | `string` | `'There are no items to display.'` | Body text. |
796
- | `actionLabel` | `string` | `'Take Action'` | Label for the built-in action button, shown when `actionLabel`/`onAction` is truthy (see note below). |
797
- | `onAction` | `function()` | - | Click handler wired to the built-in action button. |
798
- | `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. |
799
- | `className` | `string` | - | Extra classes on the root container. |
800
- | `children` | `node` | - | Rendered between the description and the action button — use this for custom action content. |
801
-
802
- > **`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.
803
-
804
- ### `SearchEmptyState`
805
-
806
- | Prop | Type | Default | Description |
807
- |------|------|---------|--------------|
808
- | `searchTerm` | `string` | - | Interpolated into the title as `` No results for "${searchTerm}" ``. |
809
- | `onClear` | `function()` | - | If provided, renders an outline "Clear Search" button (via `children`, not the built-in action button). |
810
- | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
811
-
812
- 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.
813
-
814
- ### `CreateEmptyState`
815
-
816
- | Prop | Type | Default | Description |
817
- |------|------|---------|--------------|
818
- | `itemName` | `string` | `'item'` | Builds the title (`` No ${itemName}s yet ``), description (`` Create your first ${itemName} to get started. ``), and action label (`` Create ${itemName} ``). |
819
- | `onCreate` | `function()` | - | Click handler for the built-in "Create ___" button. |
820
- | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
821
-
822
- > 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.
823
-
824
- ### `ErrorState`
825
-
826
- | Prop | Type | Default | Description |
827
- |------|------|---------|--------------|
828
- | `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'`. |
829
- | `onRetry` | `function()` | - | Click handler for the built-in "Try Again" button. |
830
- | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
831
-
832
- > There is no `title` or `description` string prop — pass an `error` object instead.
833
-
834
- None of the Empty State components are Radix-based, and none spread extra props through.
835
-
836
- ### Usage
837
-
838
- ```jsx
839
- import { EmptyState, SearchEmptyState, CreateEmptyState, ErrorState } from '@sujanbomjan/react-crud-ui';
840
-
841
- <EmptyState
842
- icon={Box}
843
- title="No Products"
844
- description="You haven't added any products yet."
845
- actionLabel="Create Product"
846
- onAction={() => navigate('/products/create')}
847
- />
848
-
849
- <SearchEmptyState searchTerm={search} onClear={() => setSearch('')} />
850
-
851
- <CreateEmptyState itemName="product" onCreate={() => navigate('/products/create')} />
852
-
853
- <ErrorState error={fetchError} onRetry={() => fetchList()} />
854
- ```
855
-
856
- ---
857
-
858
- ## Modal Components
859
-
860
- 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.
861
-
862
- > **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`.
863
-
864
- ### `Modal`
865
-
866
- | Prop | Type | Default | Description |
867
- |------|------|---------|--------------|
868
- | `open` | `boolean` | - | Controls dialog visibility. |
869
- | `onOpenChange` | `function(open)` | - | Standard Radix open-state change handler. |
870
- | `onClose` | `function()` | - | Extra convenience callback fired whenever `onOpenChange` transitions to `false`. |
871
- | `title` | `string` | - | Rendered in the dialog header (only if `title` or `description` is truthy). Clamped to 3 lines. |
872
- | `description` | `string` | - | Rendered under the title. Clamped to 3 lines. |
873
- | `children` | `node` | - | Main dialog body content. |
874
- | `footer` | `node` | - | Rendered in the dialog footer if provided. |
875
- | `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. |
876
- | `className` | `string` | - | Extra classes merged onto the dialog content (combined with the `size` class). |
877
- | `...props` | - | - | Spread onto the Radix `Dialog` root (e.g. `modal`, `defaultOpen`). |
878
-
879
- > `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.
880
-
881
- ### `ConfirmModal`
882
-
883
- | Prop | Type | Default | Description |
884
- |------|------|---------|--------------|
885
- | `open` | `boolean` | - | Dialog visibility. |
886
- | `onOpenChange` | `function(open)` | - | Passed straight through to `Modal`. |
887
- | `onConfirm` | `function()` | - | Called (and awaited) when the confirm button is clicked. |
888
- | `onCancel` | `function()` | - | Called when Cancel is clicked, in addition to automatically calling `onOpenChange?.(false)`. |
889
- | `title` | `string` | `'Are you sure?'` | |
890
- | `description` | `string` | `'This action cannot be undone.'` | |
891
- | `confirmText` | `string` | `'Confirm'` | Confirm button label (shows `'Loading...'` while `loading`). |
892
- | `cancelText` | `string` | `'Cancel'` | Cancel button label. |
893
- | `variant` | `'default' \| 'destructive'` | `'default'` | Only `'destructive'` is specially handled (styles the confirm button as destructive). |
894
- | `loading` | `boolean` | `false` | Disables both buttons; confirm button shows `'Loading...'`. |
895
- | `className` | `string` | - | Forwarded to the internal `Modal`. |
896
-
897
- `ConfirmModal` doesn't accept `children`, and its internal `Modal` always uses `size="default"` — there's no way to resize it.
898
-
899
- ### `DeleteConfirmModal`
900
-
901
- | Prop | Type | Default | Description |
902
- |------|------|---------|--------------|
903
- | `open` | `boolean` | - | Dialog visibility. |
904
- | `onOpenChange` | `function(open)` | - | Forwarded to `ConfirmModal`. |
905
- | `onConfirm` | `function()` | - | Delete handler. |
906
- | `title` | `string` | `` `Delete ${itemName}?` `` | Overridable. |
907
- | `description` | `string` | `` `Are you sure you want to delete this ${itemName}? This action cannot be undone.` `` | Overridable. |
908
- | `itemName` | `string` | `'item'` | Interpolated into the default title/description. |
909
- | `loading` | `boolean` | `false` | Passed through to `ConfirmModal`. |
910
-
911
- Internally always passes `confirmText="Delete"` and `variant="destructive"` (not overridable). There is **no** `className` prop and no `cancelText` override.
912
-
913
- ### `FormModal`
914
-
915
- | Prop | Type | Default | Description |
916
- |------|------|---------|--------------|
917
- | `open` | `boolean` | - | Dialog visibility. |
918
- | `onOpenChange` | `function(open)` | - | Forwarded to `Modal`; also called directly with `false` when Cancel is clicked (there is no separate `onCancel` prop here). |
919
- | `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. |
920
- | `title` | `string` | - | Forwarded to `Modal`. |
921
- | `description` | `string` | - | Forwarded to `Modal`. |
922
- | `children` | `node` | - | Form fields, rendered inside the `<form>`. |
923
- | `submitText` | `string` | `'Save'` | Submit button label (shows `'Saving...'` while `loading`). |
924
- | `cancelText` | `string` | `'Cancel'` | Cancel button label. |
925
- | `loading` | `boolean` | `false` | Disables both buttons and swaps the submit label to `'Saving...'`. |
926
- | `size` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | `'default'` | Forwarded to the internal `Modal`. |
927
- | `className` | `string` | - | Forwarded to the internal `Modal`. |
928
-
929
- ### Usage
930
-
931
- ```jsx
932
- import { Modal, ConfirmModal, DeleteConfirmModal, FormModal } from '@sujanbomjan/react-crud-ui';
933
-
934
- <Modal
935
- open={isOpen}
936
- onOpenChange={setIsOpen}
937
- title="Modal Title"
938
- description="Modal description"
939
- size="lg"
940
- >
941
- <p>Modal body content</p>
942
- </Modal>
943
-
944
- <ConfirmModal
945
- open={isConfirmOpen}
946
- onOpenChange={setIsConfirmOpen}
947
- onConfirm={handleConfirm}
948
- title="Confirm Action"
949
- description="Do you want to proceed?"
950
- confirmText="Yes, Continue"
951
- variant="default"
952
- loading={isConfirming}
953
- />
954
-
955
- <DeleteConfirmModal
956
- open={isDeleteOpen}
957
- onOpenChange={setIsDeleteOpen}
958
- onConfirm={handleDelete}
959
- itemName={selectedItem?.name ?? 'item'}
960
- loading={isDeleting}
961
- />
962
-
963
- <FormModal
964
- open={isFormOpen}
965
- onOpenChange={setIsFormOpen}
966
- onSubmit={handleSubmit}
967
- title="Edit Item"
968
- description="Update the item details below."
969
- loading={isSubmitting}
970
- size="lg"
971
- >
972
- <input name="name" defaultValue={item.name} />
973
- </FormModal>
974
- ```
1
+ # CRUD Components Guide
2
+
3
+ Complete reference for CRUD components in @bomjan133/react-crud-ui.
4
+
5
+ ## Table of Contents
6
+ 1. [DataTable](#datatable)
7
+ 2. [CrudList](#crudlist)
8
+ 3. [CrudForm](#crudform)
9
+ 4. [CrudDetail](#cruddetail)
10
+ 5. [Pagination](#pagination)
11
+ 6. [Loading Components](#loading-components)
12
+ 7. [Empty States](#empty-states)
13
+ 8. [Modal Components](#modal-components)
14
+
15
+ ---
16
+
17
+ ## DataTable
18
+
19
+ A data table with sorting, pagination, search, row selection, clickable "link" columns, and a per-row dropdown actions menu.
20
+
21
+ ### Props
22
+
23
+ | Prop | Type | Default | Description |
24
+ |------|------|---------|--------------|
25
+ | `data` | `array` | `[]` | Rows to display (current page only — this component does not paginate client-side). |
26
+ | `columns` | `array` | `[]` | Column definitions. See Column Definition below. |
27
+ | `loading` | `boolean` | `false` | Shows a full-width `Loading` row instead of the data rows. |
28
+ | `error` | `any` | `null` | Accepted but currently unused — nothing in the component reads or renders this value. |
29
+ | `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 }`. |
30
+ | `currentPage` | `number` | `1` | Current page (1-indexed). Used to compute serial numbers and passed through to the internal `Pagination` component. |
31
+ | `pageSize` | `number` | `15` | Items per page. Used to compute serial numbers and passed to `Pagination`. |
32
+ | `totalItems` | `number` | `0` | Total item count, passed to `Pagination`. |
33
+ | `totalPages` | `number` | `1` | Total page count, passed to `Pagination`. |
34
+ | `onPageChange` | `function` | - | Passed to `Pagination`; called with the new page. |
35
+ | `onPageSizeChange` | `function` | - | Passed to `Pagination`; called when the page size changes. |
36
+ | `sortable` | `boolean` | `true` | Global switch for sorting. A column must also set `sortable: true` to become sortable. |
37
+ | `sortColumn` | `string` | `null` | The field currently sorted on (compared against each column's `sortKey`/`accessor`/`key`). |
38
+ | `sortDirection` | `'asc' \| 'desc' \| null` | `null` | Current sort direction. |
39
+ | `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)`. |
40
+ | `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. |
41
+ | `searchable` | `boolean` | `true` | Shows/hides the search input in the toolbar. |
42
+ | `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. |
43
+ | `onSearchChange` | `function` | - | Called with the search string, debounced 300ms after the user stops typing (fixed delay, not configurable). |
44
+ | `searchPlaceholder` | `string` | `'Search...'` | Placeholder text for the search input. |
45
+ | `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. |
46
+ | `toolbarActions` | `node` | - | Content rendered on the right side of the toolbar (e.g. an "Add" button). |
47
+ | `selectable` | `boolean` | `false` | Shows a checkbox column for row selection. |
48
+ | `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). |
49
+ | `onSelectionChange` | `function` | - | Called with the new array of selected row keys, on both row and select-all/clear actions. |
50
+ | `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. |
51
+ | `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). |
52
+ | `striped` | `boolean` | `false` | Applies a light background to odd rows. |
53
+ | `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. |
54
+ | `compact` | `boolean` | `false` | Reduces cell vertical padding. |
55
+ | `className` | `string` | - | Class for the outer wrapping `<div>`. |
56
+ | `emptyTitle` | `string` | `'No data found'` | Empty-state title. |
57
+ | `emptyDescription` | `string` | `'There are no items to display.'` | Empty-state description text. |
58
+ | `emptyAction` | `string` | - | Label for an optional empty-state action button. |
59
+ | `onEmptyAction` | `function` | - | Handler for the empty-state action button. |
60
+ | `getRowKey` | `function` | `(row) => row.id \|\| row._id` | Derives a unique key per row; used for React keys and selection tracking. |
61
+ | `showSerialNumber` | `boolean` | `true` | Shows a leading row-number column. |
62
+ | `serialNumberHeader` | `string` | `'SN'` | Header label for the serial number column. |
63
+ | `onViewClick` | `function` | - | If set, "clickable" columns (see `clickableColumns`) render their value as a button; clicking it calls `onViewClick(row)`. |
64
+ | `onViewLink` | `function` | - | If set, "clickable" columns render their value as an `<a>`; called as `onViewLink(row)` to compute the `href`. Takes precedence over `onViewClick`. |
65
+ | `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. |
66
+ | `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. |
67
+ | `enableTextClamping` | `boolean` | `true` | Truncates long string cell values (30+ characters) with an ellipsis and shows the full text in a tooltip on hover. |
68
+ | `defaultMaxLines` | `number` | `1` | Default number of lines before clamping; overridable per-column via `column.maxLines`. |
69
+ | `tableClassName` | `string` | - | Class passed to the root `<Table>`. |
70
+ | `tableHeaderClassName` | `string` | - | Class passed to `<TableHeader>`. |
71
+ | `tableBodyClassName` | `string` | - | Class passed to `<TableBody>`. |
72
+ | `tableRowClassName` | `string` | - | Class merged onto every data/status `<TableRow>`. |
73
+ | `tableHeadClassName` | `string` | - | Class merged onto every `<TableHead>` cell (selection, SN, data, and actions headers). |
74
+ | `tableCellClassName` | `string` | - | Class merged onto every `<TableCell>` (selection, SN, data, actions, and loading/empty cells). |
75
+ | `headerRowClassName` | `string` | - | Class merged onto the header `<TableRow>`. |
76
+ | `statusRowClassName` | `string` | - | Class merged onto the loading/empty-state `<TableRow>`. |
77
+ | `paginationClassName` | `string` | - | Class passed to the `Pagination` component. |
78
+
79
+ > **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.
80
+
81
+ ### Column Definition
82
+
83
+ ```js
84
+ const columns = [
85
+ {
86
+ // Value extraction — accessor wins over key
87
+ accessor: 'name', // string, OR a function: (row) => value
88
+ key: 'name', // fallback for accessor; also used as React key/sort field if accessor is absent
89
+
90
+ // Header text — header wins over label
91
+ header: 'Name',
92
+ label: 'Name', // fallback if header is not set
93
+
94
+ sortable: true, // enables sorting for this column (requires top-level sortable !== false)
95
+ sortKey: 'name', // optional override of the field name used for sort comparisons/onSort
96
+
97
+ render: (value, row, index) => (
98
+ <span className="font-medium">{value}</span>
99
+ ), // custom cell renderer, highest precedence
100
+ format: (value, row) => value, // used only if render is not provided
101
+
102
+ width: 200, // inline style: width
103
+ minWidth: 120, // inline style: minWidth
104
+ maxWidth: 300, // inline style: maxWidth (cells default to '300px' if unset)
105
+
106
+ headerClassName: '', // extra className on the <TableHead>
107
+ cellClassName: '', // extra className on the <TableCell>
108
+
109
+ disableClamping: false, // opt this column out of enableTextClamping
110
+ maxLines: 1, // per-column override of defaultMaxLines
111
+ },
112
+ ];
113
+ ```
114
+
115
+ > A column-level `className` field does not exist — the real per-column style hooks are `headerClassName` and `cellClassName`.
116
+
117
+ ### Actions Column
118
+
119
+ 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.
120
+
121
+ ```js
122
+ const actions = [
123
+ {
124
+ label: 'Edit',
125
+ icon: PencilIcon, // optional component, rendered at 16px with right margin
126
+ onClick: (row) => handleEdit(row),
127
+ disabled: false, // optional
128
+ },
129
+ {
130
+ label: 'Delete',
131
+ icon: TrashIcon,
132
+ variant: 'destructive', // only 'destructive' has special styling (red text)
133
+ onClick: (row) => handleDelete(row),
134
+ hidden: (row) => row.locked, // boolean, or a function(row) => boolean
135
+ },
136
+ ];
137
+ ```
138
+
139
+ - Items render in a `DropdownMenu` opened by an icon-only ghost button, in the same order as the `actions` array.
140
+ - 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.
141
+ - `disabled` maps directly to the underlying menu item's disabled state.
142
+ - Clicking a row's actions cell does not trigger `onRowClick` (click propagation is stopped).
143
+
144
+ ### Usage
145
+
146
+ ```jsx
147
+ import { DataTable } from '@bomjan133/react-crud-ui';
148
+ import { PencilIcon, TrashIcon } from 'lucide-react';
149
+
150
+ <DataTable
151
+ data={users}
152
+ columns={[
153
+ { key: 'name', label: 'Name', sortable: true },
154
+ { key: 'email', label: 'Email' },
155
+ {
156
+ key: 'status',
157
+ label: 'Status',
158
+ render: (value) => <Badge>{value}</Badge>,
159
+ },
160
+ ]}
161
+ loading={isLoading}
162
+ searchValue={search}
163
+ onSearchChange={setSearch}
164
+ currentPage={page}
165
+ pageSize={15}
166
+ totalItems={total}
167
+ totalPages={Math.ceil(total / 15)}
168
+ onPageChange={setPage}
169
+ sortColumn={sortColumn}
170
+ sortDirection={sortDirection}
171
+ onSort={(field, direction) => {
172
+ setSortColumn(field);
173
+ setSortDirection(direction);
174
+ }}
175
+ actions={[
176
+ { label: 'Edit', icon: PencilIcon, onClick: (row) => openEdit(row) },
177
+ {
178
+ label: 'Delete',
179
+ icon: TrashIcon,
180
+ variant: 'destructive',
181
+ onClick: (row) => openDelete(row),
182
+ },
183
+ ]}
184
+ emptyTitle="No users found"
185
+ emptyDescription="Try adjusting your search or add a new user."
186
+ />
187
+
188
+ // Selectable rows with a clickable "name" column linking to a detail page
189
+ <DataTable
190
+ data={orders}
191
+ columns={[{ key: 'name', label: 'Order' }, { key: 'amount', label: 'Amount' }]}
192
+ selectable
193
+ selectedRows={selectedIds}
194
+ onSelectionChange={setSelectedIds}
195
+ onViewLink={(row) => `/orders/${row.id}`}
196
+ clickableColumns={['name']}
197
+ getRowKey={(row) => row.id}
198
+ />
199
+ ```
200
+
201
+ ---
202
+
203
+ ## CrudList
204
+
205
+ 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.
206
+
207
+ ### Store integration (preferred)
208
+
209
+ | Prop | Type | Default | Description |
210
+ |------|------|---------|--------------|
211
+ | `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. |
212
+
213
+ > **Note if you're using this package's own [`createCrudStore`](./6_STORE_FACTORY.md):** 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](./6_STORE_FACTORY.md#compatibility-with-crudlist--crudform--cruddetail) for the full compatibility matrix (this also applies to `CrudDetail`'s `currentItem` vs. `item`, and `CrudForm`'s store mode).
214
+
215
+ ### Direct data props (used if store not provided)
216
+
217
+ | Prop | Type | Default | Description |
218
+ |------|------|---------|--------------|
219
+ | `data` | `array` | - | Row data. Used when `store?.items` is nullish. |
220
+ | `loading` | `boolean` | `false` | Loading state, used when `store?.loading` is nullish. |
221
+ | `error` | `any` | `null` | Error state, used when `store?.error` is nullish. |
222
+ | `skipInitialFetch` | `boolean` | `false` | When a store is provided, skips the automatic call to `store.fetchList()` on mount. |
223
+
224
+ ### Columns configuration
225
+
226
+ | Prop | Type | Default | Description |
227
+ |------|------|---------|--------------|
228
+ | `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). |
229
+
230
+ ### Pagination (direct-prop mode)
231
+
232
+ | Prop | Type | Default | Description |
233
+ |------|------|---------|--------------|
234
+ | `currentPage` | `number` | `1` | Current page, used when no `store.pagination` value is available. |
235
+ | `pageSize` | `number` | `15` | Page size fallback. |
236
+ | `totalItems` | `number` | `0` | Total item count fallback. |
237
+ | `totalPages` | `number` | `1` | Total page count fallback. |
238
+ | `onPageChange` | `function(page)` | - | Called when the store has no `setPage` method. |
239
+ | `onPageSizeChange` | `function(size)` | - | Called when the store has no `setPageSize` method. |
240
+
241
+ > 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.
242
+
243
+ ### Sorting
244
+
245
+ | Prop | Type | Default | Description |
246
+ |------|------|---------|--------------|
247
+ | `sortColumn` | `string` | - | Current sort column, used when the store doesn't expose `sortColumn`. |
248
+ | `sortDirection` | `'asc' \| 'desc' \| null` | - | Current sort direction fallback. |
249
+ | `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. |
250
+
251
+ ### Search
252
+
253
+ | Prop | Type | Default | Description |
254
+ |------|------|---------|--------------|
255
+ | `searchValue` | `string` | `""` | Controlled search text, used only when the store has no `setFilters` method. |
256
+ | `onSearchChange` | `function(value)` | - | Called on search input change when the store has no `setFilters` method. |
257
+ | `searchPlaceholder` | `string` | `"Search..."` | Placeholder text for the search input. |
258
+ | `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. |
259
+ | `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. |
260
+
261
+ 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()`.
262
+
263
+ ### Selection
264
+
265
+ | Prop | Type | Default | Description |
266
+ |------|------|---------|--------------|
267
+ | `selectable` | `boolean` | `false` | Enables row checkboxes and the "select all" header checkbox. |
268
+ | `selectedRows` | `array` | `[]` | Array of currently-selected row keys (as returned by `getRowKey`). Controlled — the component does not manage this internally. |
269
+ | `onSelectionChange` | `function(newSelectedRowKeys: array)` | - | Called with the full updated array whenever a row or "select all" checkbox changes. |
270
+
271
+ ### CRUD Actions (direct-prop mode, used if paths not provided)
272
+
273
+ | Prop | Type | Default | Description |
274
+ |------|------|---------|--------------|
275
+ | `onCreate` | `function()` | - | Called by the Create button when `createPath` is not set. |
276
+ | `onView` | `function(row)` | - | Called by the row "View" action when `detailPath` is not set. |
277
+ | `onEdit` | `function(row)` | - | Called by the row "Edit" action when `editPath` is not set. |
278
+ | `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. |
279
+ | `onRefresh` | `function()` | - | Called by the Refresh button when the store has no `fetchList` method. |
280
+ | `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. |
281
+
282
+ ### Table & button styling overrides
283
+
284
+ Purely presentational, forwarded straight through to `DataTable`/toolbar buttons:
285
+
286
+ | Prop | Type | Description |
287
+ |------|------|-------------|
288
+ | `tableClassName` | `string` | Class on the `<Table>` element. |
289
+ | `tableHeaderClassName` | `string` | Class on `<TableHeader>`. |
290
+ | `tableBodyClassName` | `string` | Class on `<TableBody>`. |
291
+ | `tableRowClassName` | `string` | Class on each `<TableRow>` (data + status rows). |
292
+ | `tableHeadClassName` | `string` | Class on each `<TableHead>` cell. |
293
+ | `tableCellClassName` | `string` | Class on each `<TableCell>`. |
294
+ | `headerRowClassName` | `string` | Class on the header `<TableRow>`. |
295
+ | `statusRowClassName` | `string` | Class on the loading/empty status row. |
296
+ | `paginationClassName` | `string` | Class passed to the `Pagination` component. |
297
+ | `createButtonClassName` | `string` | Class on the Create button. |
298
+ | `refreshButtonClassName` | `string` | Class on the Refresh button. |
299
+ | `exportButtonClassName` | `string` | Class on the default Export button. |
300
+ | `bulkActionButtonClassName` | `string` | Class applied to every bulk-action button. |
301
+
302
+ ### Navigation paths
303
+
304
+ | Prop | Type | Default | Description |
305
+ |------|------|---------|--------------|
306
+ | `createPath` | `string` | - | If set, the Create button navigates here (via `react-router`'s `navigate`) instead of calling `onCreate`. Used as-is — no suffix appended. |
307
+ | `detailPath` | `string` | - | If set, the row "View" action and clickable-name columns navigate to `` `${detailPath}/${getRowKey(row)}` `` instead of calling `onView`. |
308
+ | `editPath` | `string` | - | If set, the row "Edit" action navigates to `` `${editPath}/${getRowKey(row)}/edit` `` instead of calling `onEdit`. |
309
+
310
+ > **Correction:** there is no `viewPath` prop — the real prop is `detailPath`. An earlier version of this doc used `viewPath`, which has no effect.
311
+
312
+ ### Breadcrumb helper
313
+
314
+ | Prop | Type | Default | Description |
315
+ |------|------|---------|--------------|
316
+ | `getBreadcrumbName` | `function(row)` | - | Returns a display name passed as `location.state.breadcrumbName` when navigating to the detail page. |
317
+ | `customBreadcrumbPaths` | `object` | - | Static breadcrumb path map passed as `location.state.customBreadcrumbPaths` on create/view/edit navigation, unless `getCustomBreadcrumbPath` is given. |
318
+ | `getCustomBreadcrumbPath` | `function(row)` | - | Per-row/per-action function that computes breadcrumb paths, overriding `customBreadcrumbPaths` when provided. |
319
+ | `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. |
320
+ | `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state object passed to create/view/edit navigations. |
321
+
322
+ ### Custom actions
323
+
324
+ | Prop | Type | Default | Description |
325
+ |------|------|---------|--------------|
326
+ | `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 }`. |
327
+ | `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 }`. |
328
+
329
+ ### Labels
330
+
331
+ | Prop | Type | Default | Description |
332
+ |------|------|---------|--------------|
333
+ | `title` | `string` | - | Card title text. Also used verbatim in the delete-success toast: `` `${title} Deleted successfully` `` (note: uses `title`, not `itemName`). |
334
+ | `description` | `string` | - | Card description text. |
335
+ | `createLabel` | `string` | `"Create"` | Create button label. |
336
+ | `refreshLabel` | `string` | `"Refresh"` | Refresh button label. |
337
+ | `exportLabel` | `string` | `"Export"` | Default Export button label. |
338
+ | `viewLabel` | `string` | `"View"` | Row "View" action label. |
339
+ | `editLabel` | `string` | `"Edit"` | Row "Edit" action label. |
340
+ | `deleteLabel` | `string` | `"Delete"` | Row "Delete" action label. |
341
+ | `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.` ``). |
342
+
343
+ ### Row key
344
+
345
+ | Prop | Type | Default | Description |
346
+ |------|------|---------|--------------|
347
+ | `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. |
348
+
349
+ ### Appearance
350
+
351
+ | Prop | Type | Default | Description |
352
+ |------|------|---------|--------------|
353
+ | `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>`. |
354
+ | `showToolbar` | `boolean` | `true` | Whether to render the toolbar (header actions, bulk actions, export, refresh, create) — independent of `showHeader`. |
355
+ | `compact` | `boolean` | `false` | Passed to `DataTable` to tighten row padding. |
356
+ | `className` | `string` | - | Class on the outer `Card`/`div` wrapper. |
357
+ | `filters` | `node` | - | Custom filter control(s) rendered in the `DataTable` toolbar next to the search box. |
358
+ | `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. |
359
+ | `showEditButton` | `boolean` | `true` | Hides the built-in row "Edit" action when `false`, even if `editPath`/`onEdit` is set. |
360
+ | `showDeleteButton` | `boolean` | `true` | Hides the built-in row "Delete" action when `false`, even if delete is otherwise available. |
361
+ | `clickableColumns` | `array` | `[]` | Accessor keys that should render as clickable links/buttons to the detail view. Pass `["*"]` for all columns. Forwarded to `DataTable`. |
362
+
363
+ > **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.
364
+
365
+ ### Delete confirmation
366
+
367
+ | Prop | Type | Default | Description |
368
+ |------|------|---------|--------------|
369
+ | `deleteConfirmTitle` | `string` | - | Overrides the delete modal's title (default: `` `Delete ${itemName}` ``). |
370
+ | `deleteConfirmDescription` | `string` | - | Overrides the modal's description (default asks to confirm deleting the resolved item name). |
371
+ | `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`. |
372
+
373
+ > There is no `onDeleteSuccess` callback — delete success always shows a hardcoded toast using `title` (see Labels above).
374
+
375
+ ### Usage
376
+
377
+ **Basic (store-based):**
378
+
379
+ ```jsx
380
+ import { CrudList } from '@bomjan133/react-crud-ui';
381
+ import { useUserStore } from './stores/useUserStore';
382
+
383
+ const columns = [
384
+ { accessor: 'name', header: 'Name', sortable: true },
385
+ { accessor: 'email', header: 'Email' },
386
+ {
387
+ accessor: 'createdAt',
388
+ header: 'Created',
389
+ format: (value) => new Date(value).toLocaleDateString(),
390
+ },
391
+ ];
392
+
393
+ function UsersPage() {
394
+ const store = useUserStore();
395
+
396
+ return (
397
+ <CrudList
398
+ store={store}
399
+ title="Users"
400
+ description="Manage your organization's users"
401
+ columns={columns}
402
+ createPath="/users/create"
403
+ detailPath="/users"
404
+ editPath="/users"
405
+ itemName="user"
406
+ getRowKey={(row) => row.id}
407
+ />
408
+ );
409
+ }
410
+ ```
411
+
412
+ **Selection + bulk actions (direct data props):**
413
+
414
+ ```jsx
415
+ import { useState } from 'react';
416
+ import { CrudList } from '@bomjan133/react-crud-ui';
417
+ import { Archive, Trash2 } from 'lucide-react';
418
+
419
+ const columns = [
420
+ { accessor: 'name', header: 'Name', sortable: true },
421
+ { accessor: 'status', header: 'Status' },
422
+ ];
423
+
424
+ function InvoicesPage({ invoices, isLoading }) {
425
+ const [selectedRows, setSelectedRows] = useState([]);
426
+
427
+ const bulkActions = [
428
+ { label: 'Archive', icon: Archive, onClick: (rowKeys) => archiveInvoices(rowKeys) },
429
+ { label: 'Delete', icon: Trash2, variant: 'destructive', onClick: (rowKeys) => deleteInvoices(rowKeys) },
430
+ ];
431
+
432
+ return (
433
+ <CrudList
434
+ data={invoices}
435
+ loading={isLoading}
436
+ columns={columns}
437
+ title="Invoices"
438
+ itemName="invoice"
439
+ selectable
440
+ selectedRows={selectedRows}
441
+ onSelectionChange={setSelectedRows}
442
+ bulkActions={bulkActions}
443
+ onCreate={() => openCreateModal()}
444
+ onView={(row) => openDetailModal(row)}
445
+ onEdit={(row) => openEditModal(row)}
446
+ onDelete={async (row) => deleteInvoice(row.id)}
447
+ getRowKey={(row) => row.id}
448
+ />
449
+ );
450
+ }
451
+ ```
452
+
453
+ ---
454
+
455
+ ## CrudForm
456
+
457
+ 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).
458
+
459
+ - **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.
460
+ - **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.
461
+
462
+ `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.
463
+
464
+ > ⚠️ **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.
465
+
466
+ ### Props
467
+
468
+ | Prop | Type | Default | Description |
469
+ |------|------|---------|--------------|
470
+ | `useStore` | `function` | - | Zustand store hook. Combined with `children` to trigger store mode. See store-shape warning above. |
471
+ | `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. |
472
+ | `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 })`. |
473
+ | `defaultValues` | `object` | `{}` | Fields mode only. Initial `react-hook-form` values, used when `initialData` is not provided. |
474
+ | `validationSchema` | Zod schema | - | Fields mode only. Passed to `zodResolver` for `react-hook-form` validation. No effect in store mode. |
475
+ | `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`. |
476
+ | `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. |
477
+ | `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. |
478
+ | `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). |
479
+ | `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. |
480
+ | `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. |
481
+ | `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. |
482
+ | `description` | `string` | - | Subtitle shown under the title, both modes. |
483
+ | `submitLabel` | `string` | `"Save"` | Submit button text, both modes. Shows a spinner + "Saving..." while submitting. |
484
+ | `cancelLabel` | `string` | `"Cancel"` | Cancel button text, both modes (subject to the `onCancel` visibility rule above). |
485
+ | `columns` | `1 \| 2 \| 3 \| 4` | `1` | Fields mode only. Grid column count for laying out `fields`. No effect in store mode. |
486
+ | `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). |
487
+ | `showFooter` | `boolean` | `true` | Shows/hides the Cancel/Submit button row, both modes. |
488
+ | `showBack` | `boolean` | `true` | Shows the back-arrow icon button. See the asymmetric per-mode behavior under `onBack`. |
489
+ | `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. |
490
+ | `listPath` | `string` | - | Fallback destination for `handleBack()` when no `onBack` is given, in both modes. |
491
+ | `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. |
492
+ | `className` | `string` | - | Applied to the outer `Card`/`div` wrapper, both modes. |
493
+ | `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`. |
494
+ | `loading` | `boolean` | `false` | OR'd with the store's own `loading` (store mode). Disables fields and combines with `submitting` to disable Submit. |
495
+ | `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...". |
496
+
497
+ > **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.
498
+
499
+ **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.
500
+
501
+ ### Usage
502
+
503
+ **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`:
504
+
505
+ ```jsx
506
+ import { CrudForm, QInput } from '@bomjan133/react-crud-ui';
507
+
508
+ function UserForm() {
509
+ return (
510
+ <CrudForm
511
+ title="User"
512
+ useStore={useUserFormStore}
513
+ listPath="/users"
514
+ getBreadcrumbName={(values) => values.name}
515
+ onBeforeSubmit={(values) => ({ ...values, email: values.email.trim().toLowerCase() })}
516
+ onAfterCreate={(result, navigate) => navigate(`/users/${result.uuid}/edit`)}
517
+ >
518
+ <QInput
519
+ name="name"
520
+ label="Name"
521
+ required
522
+ value={useUserFormStore((s) => s.form.values.name) ?? ''}
523
+ onChange={(val) => useUserFormStore.getState().setFormValue('name', val)}
524
+ />
525
+ <QInput
526
+ name="email"
527
+ label="Email"
528
+ required
529
+ value={useUserFormStore((s) => s.form.values.email) ?? ''}
530
+ onChange={(val) => useUserFormStore.getState().setFormValue('email', val)}
531
+ />
532
+ </CrudForm>
533
+ );
534
+ }
535
+ ```
536
+
537
+ **Fields mode** (self-contained `react-hook-form`, no store, no router param required — pass `initialData` for edit, omit it for create):
538
+
539
+ ```jsx
540
+ import { CrudForm } from '@bomjan133/react-crud-ui';
541
+
542
+ <CrudForm
543
+ title="User"
544
+ description="Basic account details"
545
+ fields={[
546
+ { name: 'email', type: 'email', label: 'Email', required: true },
547
+ {
548
+ name: 'role',
549
+ type: 'select',
550
+ label: 'Role',
551
+ options: [
552
+ { value: 'admin', label: 'Admin' },
553
+ { value: 'member', label: 'Member' },
554
+ ],
555
+ },
556
+ ]}
557
+ initialData={editingUser} // omit for create mode
558
+ columns={2}
559
+ onSubmit={async (data) => {
560
+ await api.saveUser(data);
561
+ toast.success('Saved');
562
+ }}
563
+ onCancel={() => navigate('/users')}
564
+ onBack={() => navigate('/users')}
565
+ />
566
+ ```
567
+
568
+ ---
569
+
570
+ ## CrudDetail
571
+
572
+ 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.
573
+
574
+ **Mode selection is automatic and based on `children`:**
575
+ - **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).
576
+ - **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.**
577
+
578
+ `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`.
579
+
580
+ > ⚠️ **`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.
581
+
582
+ ### How the record id and fetch are resolved
583
+
584
+ - 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.**
585
+ - 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)`.
586
+ - Delete calls the store's `delete(id)` method (or your own `onDelete` callback) and then navigates back on success.
587
+
588
+ ### Loading / error / not-found states
589
+
590
+ - **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.
591
+ - **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.
592
+ - **Not found** (`!data` after loading, no error): renders "No {itemName} found" with a Back button.
593
+
594
+ ### Props
595
+
596
+ | Prop | Type | Default | Description |
597
+ |------|------|---------|--------------|
598
+ | `useStore` | `function` | - | Zustand-style hook, called as `useStore()`. Component reads `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), and `delete` off the returned store. |
599
+ | `children` | `function` | - | Render prop `(data) => ReactNode`. Only used when `useStore` is also set; otherwise ignored. |
600
+ | `data` | `object` | `null` | Direct data mode: record to display (`propData \|\| storeData`), used in place of / alongside the store's `currentItem`. |
601
+ | `paramName` | `string` | `"uuid"` | Name of the route param (via `useParams()`) used as the record id. |
602
+ | `loading` | `boolean` | `false` | External loading flag, OR'd with the store's own `loading`. |
603
+ | `error` | `any` | `null` | External error value, OR'd with the store's own `error`. |
604
+ | `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). |
605
+ | `onBack` | `function` | - | Custom back handler. If omitted, falls back to navigating to `listPath`, or `navigate(-1)` if no `listPath`. |
606
+ | `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). |
607
+ | `onDelete` | `function(data)` | - | Custom delete handler (awaited). If omitted, falls back to the store's `delete(id)`, then navigates back on success. |
608
+ | `listPath` | `string` | - | Path the Back button navigates to when `onBack` isn't provided. |
609
+ | `editPath` | `string` | - | Base path used to build the default edit destination (`${editPath}/{id}/edit`) when `onEdit` isn't provided. |
610
+ | `title` | `string` | - | Card title text. **Only rendered in fields-based mode**; ignored in store+children mode (whose header title comes from `getBreadcrumbName(data)` instead). |
611
+ | `description` | `string` | - | Description text shown under the title in both modes. |
612
+ | `editLabel` | `string` | `"Edit"` | Label for the Edit item in the actions dropdown. |
613
+ | `deleteLabel` | `string` | `"Delete"` | Label for the Delete item in the actions dropdown. |
614
+ | `backLabel` | `string` | `"Back"` | Label for Back buttons. |
615
+ | `itemName` | `string` | `"item"` | Generic noun used in loading/empty text and as a fallback for the delete-confirmation item name. |
616
+ | `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`. |
617
+ | `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. |
618
+ | `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. |
619
+ | `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. |
620
+ | `customBreadcrumbPaths` | `object` | - | Static breadcrumb path overrides passed through `navigate(..., { state })` when navigating to edit. |
621
+ | `getCustomBreadcrumbPath` | `function(data)` | - | Dynamic version of `customBreadcrumbPaths`; takes precedence when provided. |
622
+ | `getParentPath` | `function(data)` | - | Returns a parent path used to build breadcrumb path overrides for edit navigation, when neither of the above apply. |
623
+ | `preserveLocationState` | `boolean` | `false` | If true, spreads the current `location.state` into the state passed when navigating to edit. |
624
+ | `showEditButton` | `boolean` | `true` | Whether the Edit action appears in the dropdown (also requires `onEdit` or `editPath` to be set). |
625
+ | `showDeleteButton` | `boolean` | `true` | Whether the Delete action appears in the dropdown (also requires `onDelete` or the store's `delete` to be available). |
626
+ | `showHeader` | `boolean` | `true` | Whether to render the header/title row (and its actions dropdown) at all. |
627
+ | `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). |
628
+ | `columns` | `1 \| 2 \| 3` | `2` | Number of grid columns for the fields grid (fields-based mode). |
629
+ | `className` | `string` | - | Root wrapper class (store+children mode) or `Card` class (fields-based mode). |
630
+ | `cardHeaderClassName` | `string` | - | Applied to `CardHeader` (fields-based mode). |
631
+ | `headerClassName` | `string` | - | Applied to the header's inner flex container (store+children mode only). |
632
+ | `titleClassName` | `string` | - | Applied to `CardTitle` (fields-based mode only). |
633
+ | `descriptionClassName` | `string` | - | Applied to `CardDescription` (fields-based mode only). |
634
+ | `fieldsGridClassName` | `string` | - | Applied to the fields grid container. |
635
+ | `fieldItemClassName` | `string` | - | Applied to each individual field's wrapper. |
636
+ | `fieldLabelClassName` | `string` | - | Applied to each field's label element. |
637
+ | `fieldValueClassName` | `string` | - | Applied to each field's value element. |
638
+ | `metaClassName` | `string` | - | Applied to the Created/Updated/ID meta row container. |
639
+ | `metaItemClassName` | `string` | - | Applied to each item within the meta row. |
640
+ | `backButtonClassName` | `string` | - | Applied to the Back icon button (store+children mode header). |
641
+ | `actionsDropdownItemClassName` | `string` | - | Applied to the Edit item inside the actions dropdown only (not Delete or additional-action items). |
642
+ | `loadingStateClassName` | `string` | - | Applied to the loading `Card` in store+children mode only; no effect in fields-based mode. |
643
+
644
+ > **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.
645
+
646
+ ### Usage
647
+
648
+ **Store-driven, custom render (render-prop `children`):**
649
+
650
+ ```jsx
651
+ <CrudDetail
652
+ useStore={useUserStore}
653
+ listPath="/users"
654
+ editPath="/users"
655
+ getBreadcrumbName={(user) => user.name}
656
+ additionalActions={[
657
+ { label: 'Reset Password', onClick: (user) => resetPassword(user.uuid) },
658
+ ]}
659
+ >
660
+ {(user) => (
661
+ <Card>
662
+ <CardContent className="py-6">
663
+ <p>{user.email}</p>
664
+ </CardContent>
665
+ </Card>
666
+ )}
667
+ </CrudDetail>
668
+ ```
669
+
670
+ Requires a route like `/users/:uuid` (or pass `paramName="id"` for `/users/:id`).
671
+
672
+ **Direct data + fields array (no store):**
673
+
674
+ ```jsx
675
+ <CrudDetail
676
+ title="User"
677
+ data={user}
678
+ fields={[
679
+ { name: 'email', label: 'Email', type: 'email' },
680
+ { name: 'status', label: 'Status', type: 'status' },
681
+ { name: 'created_at', label: 'Joined', type: 'date' },
682
+ ]}
683
+ onBack={() => navigate('/users')}
684
+ onEdit={(u) => navigate(`/users/${u.uuid}/edit`)}
685
+ onDelete={(u) => deleteUser(u.uuid)}
686
+ />
687
+ ```
688
+
689
+ ---
690
+
691
+ ## Pagination
692
+
693
+ ### Props
694
+
695
+ | Prop | Type | Default | Description |
696
+ |------|------|---------|--------------|
697
+ | `currentPage` | `number` | `1` | The active page (1-indexed). |
698
+ | `totalPages` | `number` | `1` | Total number of pages. Controls whether Next/Last buttons are enabled and how page numbers are rendered. |
699
+ | `totalItems` | `number` | `0` | Total item count across all pages, used only to compute the "Showing X to Y of Z results" text. |
700
+ | `pageSize` | `number` | `15` | Current page size; also drives the value shown in the rows-per-page select. |
701
+ | `pageSizeOptions` | `number[]` | `[15, 20, 50, 100]` | Options rendered in the rows-per-page dropdown. |
702
+ | `onPageChange` | `function(page)` | - | Called with the target page number when First/Prev/page-number/Next/Last is clicked. |
703
+ | `onPageSizeChange` | `function(size)` | - | Called with the new numeric page size when the rows-per-page select changes. |
704
+ | `showPageSizeSelector` | `boolean` | `true` | Show/hide the "Rows per page" selector. |
705
+ | `showInfo` | `boolean` | `true` | Show/hide the "Showing X to Y of Z results" text (also requires `totalItems > 0`). |
706
+ | `className` | `string` | - | Extra classes merged onto the root container. |
707
+
708
+ Not a Radix wrapper — a plain `div` composed from this library's own `Button` and `Select`. No extra props pass through.
709
+
710
+ ### Usage
711
+
712
+ ```jsx
713
+ import { Pagination } from '@bomjan133/react-crud-ui';
714
+
715
+ <Pagination
716
+ currentPage={pagination.page}
717
+ totalPages={pagination.totalPages}
718
+ totalItems={pagination.totalItems}
719
+ pageSize={pagination.pageSize}
720
+ pageSizeOptions={[15, 20, 50, 100]}
721
+ onPageChange={(page) => setPage(page)}
722
+ onPageSizeChange={(size) => setPageSize(size)}
723
+ />
724
+ ```
725
+
726
+ ---
727
+
728
+ ## Loading Components
729
+
730
+ ### `Loading`
731
+
732
+ | Prop | Type | Default | Description |
733
+ |------|------|---------|--------------|
734
+ | `variant` | `'spinner' \| 'dots' \| 'pulse' \| 'skeleton'` | `'spinner'` | Visual style. Any unrecognized value falls back to the spinner. |
735
+ | `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. |
736
+ | `text` | `string` | - | Optional caption below the loader. |
737
+ | `fullScreen` | `boolean` | `false` | Adds `fixed inset-0 z-50` to cover the viewport. |
738
+ | `overlay` | `boolean` | `false` | Adds a translucent blurred background. |
739
+ | `className` | `string` | - | Extra classes merged onto the root container. |
740
+
741
+ ### `LoadingOverlay`
742
+
743
+ | Prop | Type | Default | Description |
744
+ |------|------|---------|--------------|
745
+ | `loading` | `boolean` | `false` | When true, renders an absolutely-positioned, blurred overlay on top of `children`. **The prop is `loading`, not `visible`.** |
746
+ | `children` | `node` | - | The content the overlay layers on top of (always rendered underneath). |
747
+ | `text` | `string` | - | Passed straight through to the internal `<Loading text={text} />` shown while `loading` is true. |
748
+ | `className` | `string` | - | Extra classes on the root wrapper. |
749
+
750
+ There is no `size`/`variant` control — the internal loader is always the default spinner at default size.
751
+
752
+ ### `LoadingButton`
753
+
754
+ | Prop | Type | Default | Description |
755
+ |------|------|---------|--------------|
756
+ | `loading` | `boolean` | `false` | When true, disables the button and swaps its content for a spinner + `loadingText`. |
757
+ | `loadingText` | `string` | `'Loading...'` | Text shown next to the spinner while `loading` is true. |
758
+ | `children` | `node` | - | Normal button content, shown when not loading. |
759
+ | `disabled` | `boolean` | - | Manually disable the button; internally OR'd with `loading`. |
760
+ | `className` | `string` | - | Extra classes passed to the underlying `Button`. |
761
+ | `...props` | - | - | Anything else (`onClick`, `variant`, `size`, `type`, etc.) spreads onto the underlying `Button`. |
762
+
763
+ `LoadingButton` is a `forwardRef` component — a `ref` attaches to the underlying `Button`/native `<button>`.
764
+
765
+ ### Usage
766
+
767
+ ```jsx
768
+ import { Loading, LoadingOverlay, LoadingButton } from '@bomjan133/react-crud-ui';
769
+
770
+ <Loading />
771
+ <Loading size="sm" />
772
+ <Loading variant="dots" size="lg" text="Loading data..." />
773
+ <Loading variant="skeleton" />
774
+ <Loading fullScreen overlay text="Please wait..." />
775
+
776
+ <LoadingOverlay loading={isLoading} text="Refreshing...">
777
+ <ProductTable data={products} />
778
+ </LoadingOverlay>
779
+
780
+ <LoadingButton loading={isSubmitting} loadingText="Saving..." onClick={handleSubmit}>
781
+ Save Changes
782
+ </LoadingButton>
783
+ ```
784
+
785
+ ---
786
+
787
+ ## Empty States
788
+
789
+ ### `EmptyState`
790
+
791
+ | Prop | Type | Default | Description |
792
+ |------|------|---------|--------------|
793
+ | `icon` | `component` | `FileQuestion` | Icon rendered inside the circular badge. |
794
+ | `title` | `string` | `'No data found'` | Heading text. |
795
+ | `description` | `string` | `'There are no items to display.'` | Body text. |
796
+ | `actionLabel` | `string` | `'Take Action'` | Label for the built-in action button, shown when `actionLabel`/`onAction` is truthy (see note below). |
797
+ | `onAction` | `function()` | - | Click handler wired to the built-in action button. |
798
+ | `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. |
799
+ | `className` | `string` | - | Extra classes on the root container. |
800
+ | `children` | `node` | - | Rendered between the description and the action button — use this for custom action content. |
801
+
802
+ > **`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.
803
+
804
+ ### `SearchEmptyState`
805
+
806
+ | Prop | Type | Default | Description |
807
+ |------|------|---------|--------------|
808
+ | `searchTerm` | `string` | - | Interpolated into the title as `` No results for "${searchTerm}" ``. |
809
+ | `onClear` | `function()` | - | If provided, renders an outline "Clear Search" button (via `children`, not the built-in action button). |
810
+ | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
811
+
812
+ 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.
813
+
814
+ ### `CreateEmptyState`
815
+
816
+ | Prop | Type | Default | Description |
817
+ |------|------|---------|--------------|
818
+ | `itemName` | `string` | `'item'` | Builds the title (`` No ${itemName}s yet ``), description (`` Create your first ${itemName} to get started. ``), and action label (`` Create ${itemName} ``). |
819
+ | `onCreate` | `function()` | - | Click handler for the built-in "Create ___" button. |
820
+ | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
821
+
822
+ > 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.
823
+
824
+ ### `ErrorState`
825
+
826
+ | Prop | Type | Default | Description |
827
+ |------|------|---------|--------------|
828
+ | `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'`. |
829
+ | `onRetry` | `function()` | - | Click handler for the built-in "Try Again" button. |
830
+ | `className` | `string` | - | Extra classes forwarded to the underlying `EmptyState`. |
831
+
832
+ > There is no `title` or `description` string prop — pass an `error` object instead.
833
+
834
+ None of the Empty State components are Radix-based, and none spread extra props through.
835
+
836
+ ### Usage
837
+
838
+ ```jsx
839
+ import { EmptyState, SearchEmptyState, CreateEmptyState, ErrorState } from '@bomjan133/react-crud-ui';
840
+
841
+ <EmptyState
842
+ icon={Box}
843
+ title="No Products"
844
+ description="You haven't added any products yet."
845
+ actionLabel="Create Product"
846
+ onAction={() => navigate('/products/create')}
847
+ />
848
+
849
+ <SearchEmptyState searchTerm={search} onClear={() => setSearch('')} />
850
+
851
+ <CreateEmptyState itemName="product" onCreate={() => navigate('/products/create')} />
852
+
853
+ <ErrorState error={fetchError} onRetry={() => fetchList()} />
854
+ ```
855
+
856
+ ---
857
+
858
+ ## Modal Components
859
+
860
+ 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.
861
+
862
+ > **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`.
863
+
864
+ ### `Modal`
865
+
866
+ | Prop | Type | Default | Description |
867
+ |------|------|---------|--------------|
868
+ | `open` | `boolean` | - | Controls dialog visibility. |
869
+ | `onOpenChange` | `function(open)` | - | Standard Radix open-state change handler. |
870
+ | `onClose` | `function()` | - | Extra convenience callback fired whenever `onOpenChange` transitions to `false`. |
871
+ | `title` | `string` | - | Rendered in the dialog header (only if `title` or `description` is truthy). Clamped to 3 lines. |
872
+ | `description` | `string` | - | Rendered under the title. Clamped to 3 lines. |
873
+ | `children` | `node` | - | Main dialog body content. |
874
+ | `footer` | `node` | - | Rendered in the dialog footer if provided. |
875
+ | `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. |
876
+ | `className` | `string` | - | Extra classes merged onto the dialog content (combined with the `size` class). |
877
+ | `...props` | - | - | Spread onto the Radix `Dialog` root (e.g. `modal`, `defaultOpen`). |
878
+
879
+ > `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.
880
+
881
+ ### `ConfirmModal`
882
+
883
+ | Prop | Type | Default | Description |
884
+ |------|------|---------|--------------|
885
+ | `open` | `boolean` | - | Dialog visibility. |
886
+ | `onOpenChange` | `function(open)` | - | Passed straight through to `Modal`. |
887
+ | `onConfirm` | `function()` | - | Called (and awaited) when the confirm button is clicked. |
888
+ | `onCancel` | `function()` | - | Called when Cancel is clicked, in addition to automatically calling `onOpenChange?.(false)`. |
889
+ | `title` | `string` | `'Are you sure?'` | |
890
+ | `description` | `string` | `'This action cannot be undone.'` | |
891
+ | `confirmText` | `string` | `'Confirm'` | Confirm button label (shows `'Loading...'` while `loading`). |
892
+ | `cancelText` | `string` | `'Cancel'` | Cancel button label. |
893
+ | `variant` | `'default' \| 'destructive'` | `'default'` | Only `'destructive'` is specially handled (styles the confirm button as destructive). |
894
+ | `loading` | `boolean` | `false` | Disables both buttons; confirm button shows `'Loading...'`. |
895
+ | `className` | `string` | - | Forwarded to the internal `Modal`. |
896
+
897
+ `ConfirmModal` doesn't accept `children`, and its internal `Modal` always uses `size="default"` — there's no way to resize it.
898
+
899
+ ### `DeleteConfirmModal`
900
+
901
+ | Prop | Type | Default | Description |
902
+ |------|------|---------|--------------|
903
+ | `open` | `boolean` | - | Dialog visibility. |
904
+ | `onOpenChange` | `function(open)` | - | Forwarded to `ConfirmModal`. |
905
+ | `onConfirm` | `function()` | - | Delete handler. |
906
+ | `title` | `string` | `` `Delete ${itemName}?` `` | Overridable. |
907
+ | `description` | `string` | `` `Are you sure you want to delete this ${itemName}? This action cannot be undone.` `` | Overridable. |
908
+ | `itemName` | `string` | `'item'` | Interpolated into the default title/description. |
909
+ | `loading` | `boolean` | `false` | Passed through to `ConfirmModal`. |
910
+
911
+ Internally always passes `confirmText="Delete"` and `variant="destructive"` (not overridable). There is **no** `className` prop and no `cancelText` override.
912
+
913
+ ### `FormModal`
914
+
915
+ | Prop | Type | Default | Description |
916
+ |------|------|---------|--------------|
917
+ | `open` | `boolean` | - | Dialog visibility. |
918
+ | `onOpenChange` | `function(open)` | - | Forwarded to `Modal`; also called directly with `false` when Cancel is clicked (there is no separate `onCancel` prop here). |
919
+ | `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. |
920
+ | `title` | `string` | - | Forwarded to `Modal`. |
921
+ | `description` | `string` | - | Forwarded to `Modal`. |
922
+ | `children` | `node` | - | Form fields, rendered inside the `<form>`. |
923
+ | `submitText` | `string` | `'Save'` | Submit button label (shows `'Saving...'` while `loading`). |
924
+ | `cancelText` | `string` | `'Cancel'` | Cancel button label. |
925
+ | `loading` | `boolean` | `false` | Disables both buttons and swaps the submit label to `'Saving...'`. |
926
+ | `size` | `'sm' \| 'default' \| 'lg' \| 'xl' \| 'full'` | `'default'` | Forwarded to the internal `Modal`. |
927
+ | `className` | `string` | - | Forwarded to the internal `Modal`. |
928
+
929
+ ### Usage
930
+
931
+ ```jsx
932
+ import { Modal, ConfirmModal, DeleteConfirmModal, FormModal } from '@bomjan133/react-crud-ui';
933
+
934
+ <Modal
935
+ open={isOpen}
936
+ onOpenChange={setIsOpen}
937
+ title="Modal Title"
938
+ description="Modal description"
939
+ size="lg"
940
+ >
941
+ <p>Modal body content</p>
942
+ </Modal>
943
+
944
+ <ConfirmModal
945
+ open={isConfirmOpen}
946
+ onOpenChange={setIsConfirmOpen}
947
+ onConfirm={handleConfirm}
948
+ title="Confirm Action"
949
+ description="Do you want to proceed?"
950
+ confirmText="Yes, Continue"
951
+ variant="default"
952
+ loading={isConfirming}
953
+ />
954
+
955
+ <DeleteConfirmModal
956
+ open={isDeleteOpen}
957
+ onOpenChange={setIsDeleteOpen}
958
+ onConfirm={handleDelete}
959
+ itemName={selectedItem?.name ?? 'item'}
960
+ loading={isDeleting}
961
+ />
962
+
963
+ <FormModal
964
+ open={isFormOpen}
965
+ onOpenChange={setIsFormOpen}
966
+ onSubmit={handleSubmit}
967
+ title="Edit Item"
968
+ description="Update the item details below."
969
+ loading={isSubmitting}
970
+ size="lg"
971
+ >
972
+ <input name="name" defaultValue={item.name} />
973
+ </FormModal>
974
+ ```