@bomjan133/react-crud-ui 1.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +369 -0
- package/bin/cli.js +387 -0
- package/dist/html2canvas.esm-BA_v9SIU.cjs +23 -0
- package/dist/html2canvas.esm-BA_v9SIU.cjs.map +1 -0
- package/dist/html2canvas.esm-d2sM-0Wm.js +4871 -0
- package/dist/html2canvas.esm-d2sM-0Wm.js.map +1 -0
- package/dist/index-CYnVj6pv.js +15516 -0
- package/dist/index-CYnVj6pv.js.map +1 -0
- package/dist/index-DEnRTqSW.cjs +22 -0
- package/dist/index-DEnRTqSW.cjs.map +1 -0
- package/dist/index-DGN44off.cjs +712 -0
- package/dist/index-DGN44off.cjs.map +1 -0
- package/dist/index-YVvpDXLO.js +49128 -0
- package/dist/index-YVvpDXLO.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +164 -0
- package/dist/index.js.map +1 -0
- package/dist/style.css +1 -0
- package/docs/1_GETTING_STARTED.md +333 -0
- package/docs/2_UI_COMPONENTS.md +586 -0
- package/docs/3_CRUD_COMPONENTS.md +974 -0
- package/docs/4_FORM_COMPONENTS.md +778 -0
- package/docs/5_LAYOUT_COMPONENTS.md +402 -0
- package/docs/6_STORE_FACTORY.md +456 -0
- package/docs/7_BOOK_VIEWER.md +365 -0
- package/docs/8_TOAST_NOTIFICATIONS.md +130 -0
- package/docs/9_UTILITIES.md +204 -0
- package/docs/README.md +83 -0
- package/package.json +109 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
# Book Viewer Guide
|
|
2
|
+
|
|
3
|
+
A self-contained flipbook component for rendering **EPUB** and **PDF** files with a realistic page-flip animation, built on [`react-pageflip`](https://github.com/Nodlik/react-pageflip).
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
1. [Installation](#installation)
|
|
7
|
+
2. [Exports](#exports)
|
|
8
|
+
3. [BookViewer (recommended)](#bookviewer-recommended)
|
|
9
|
+
4. [EpubViewer (direct use)](#epubviewer-direct-use)
|
|
10
|
+
5. [PdfViewer (direct use)](#pdfviewer-direct-use)
|
|
11
|
+
6. [useBookDimensions](#usebookdimensionscontainerref)
|
|
12
|
+
7. [Keyboard Navigation](#keyboard-navigation)
|
|
13
|
+
8. [Container Setup](#container-setup)
|
|
14
|
+
9. [Troubleshooting](#troubleshooting)
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
Install the package along with its required runtime dependencies:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install @sujanbomjan/react-crud-ui
|
|
24
|
+
npm install react-pageflip epubjs html2canvas
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Dependency notes
|
|
28
|
+
|
|
29
|
+
| Package | Why needed |
|
|
30
|
+
|-----------------|-------------------------------------------------------------------|
|
|
31
|
+
| `react-pageflip`| Flipbook animation — statically imported by both viewers |
|
|
32
|
+
| `epubjs` | EPUB parsing and rendering — dynamically imported at runtime |
|
|
33
|
+
| `html2canvas` | Screenshots EPUB iframe pages — dynamically imported at runtime |
|
|
34
|
+
| `pdfjs-dist` | **Not required.** PDF.js 4.0.379 is loaded from `cdnjs.cloudflare.com` at runtime automatically |
|
|
35
|
+
|
|
36
|
+
> **Internet access required for PDFs:** The PDF viewer fetches pdf.js from `cdnjs.cloudflare.com` at runtime. EPUB rendering works fully offline once `epubjs` and `html2canvas` are installed.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Exports
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
import BookViewer, { EpubViewer, PdfViewer, useBookDimensions } from "@sujanbomjan/react-crud-ui";
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Export | Kind | Description |
|
|
47
|
+
|---------------------|-----------|-----------------------------------------------------------------|
|
|
48
|
+
| `BookViewer` | `default` | Recommended entry point — handles fetching + auto type-detect |
|
|
49
|
+
| `EpubViewer` | named | Renders a pre-loaded EPUB blob URL as a flipbook |
|
|
50
|
+
| `PdfViewer` | named | Renders a pre-loaded PDF blob URL as a flipbook (lazy render) |
|
|
51
|
+
| `useBookDimensions` | named | Hook — computes responsive `pageWidth`/`pageHeight` from a ref |
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## `BookViewer` (recommended)
|
|
56
|
+
|
|
57
|
+
Handles the full lifecycle: fetch → blob URL → type detection → delegates to `EpubViewer` or `PdfViewer`. This is the component most consumers should use.
|
|
58
|
+
|
|
59
|
+
### Props
|
|
60
|
+
|
|
61
|
+
| Prop | Type | Default | Description |
|
|
62
|
+
|------------------|--------------------------------------------------|--------------|---------------------------------------------------------------|
|
|
63
|
+
| `src` | `string` | — | URL to fetch the file from |
|
|
64
|
+
| `file` | `File \| Blob` | — | File or Blob — skips fetching entirely |
|
|
65
|
+
| `blobUrl` | `string` | — | Pre-resolved `blob:` URL — skips fetching entirely |
|
|
66
|
+
| `type` | `'epub' \| 'pdf'` | auto-detect | Force file type (default: inferred from URL extension or mimeType) |
|
|
67
|
+
| `mimeType` | `string` | — | Hint for type detection (`'application/pdf'`, `'application/epub+zip'`) |
|
|
68
|
+
| `title` | `string` | `'Untitled'` | Displayed in the toolbar |
|
|
69
|
+
| `canDownload` | `boolean` | `false` | Show a download button in the toolbar |
|
|
70
|
+
| `downloadUrl` | `string` | — | `href` for the download button |
|
|
71
|
+
| `totalPagesHint` | `number` | — | **PDF only** — pre-known page count. When provided, shows the correct page count immediately without waiting for the PDF to load |
|
|
72
|
+
| `onFetch` | `async (src: string) => ArrayBuffer \| Blob` | — | Custom fetcher — use your own API client here (e.g. axios with auth headers) |
|
|
73
|
+
| `fetchOptions` | `RequestInit` | — | Options passed to native `fetch()` when no `onFetch` is provided |
|
|
74
|
+
|
|
75
|
+
### Type auto-detection
|
|
76
|
+
|
|
77
|
+
Type is inferred in this order:
|
|
78
|
+
1. `type` prop (if given)
|
|
79
|
+
2. `mimeType` prop (`application/pdf` → `'pdf'`, `application/epub+zip` → `'epub'`)
|
|
80
|
+
3. URL extension (`.pdf` → `'pdf'`, `.epub` → `'epub'`)
|
|
81
|
+
4. Falls back to `'epub'` if nothing matches
|
|
82
|
+
|
|
83
|
+
### Examples
|
|
84
|
+
|
|
85
|
+
#### Load from a URL
|
|
86
|
+
```jsx
|
|
87
|
+
import BookViewer from "@sujanbomjan/react-crud-ui";
|
|
88
|
+
|
|
89
|
+
export default function Page() {
|
|
90
|
+
return (
|
|
91
|
+
<div style={{ height: "100vh" }}>
|
|
92
|
+
<BookViewer
|
|
93
|
+
src="https://example.com/my-book.epub"
|
|
94
|
+
title="My Book"
|
|
95
|
+
canDownload
|
|
96
|
+
downloadUrl="https://example.com/my-book.epub"
|
|
97
|
+
/>
|
|
98
|
+
</div>
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
#### Load a PDF with your API client (e.g. axios)
|
|
104
|
+
```jsx
|
|
105
|
+
import BookViewer from "@sujanbomjan/react-crud-ui";
|
|
106
|
+
import api from "./api"; // your axios instance
|
|
107
|
+
|
|
108
|
+
export default function ReportViewer() {
|
|
109
|
+
const handleFetch = async (src) => {
|
|
110
|
+
const res = await api.get(src, { responseType: "arraybuffer" });
|
|
111
|
+
return res.data; // ArrayBuffer — BookViewer wraps it in a Blob internally
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return (
|
|
115
|
+
<BookViewer
|
|
116
|
+
src="/api/documents/42/download"
|
|
117
|
+
type="pdf"
|
|
118
|
+
title="Annual Report 2024"
|
|
119
|
+
onFetch={handleFetch}
|
|
120
|
+
canDownload
|
|
121
|
+
downloadUrl="/api/documents/42/download"
|
|
122
|
+
/>
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
#### Load from a `<input type="file">` upload
|
|
128
|
+
```jsx
|
|
129
|
+
import { useState } from "react";
|
|
130
|
+
import BookViewer from "@sujanbomjan/react-crud-ui";
|
|
131
|
+
|
|
132
|
+
export default function LocalFileViewer() {
|
|
133
|
+
const [file, setFile] = useState(null);
|
|
134
|
+
|
|
135
|
+
return (
|
|
136
|
+
<div style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
|
|
137
|
+
<input
|
|
138
|
+
type="file"
|
|
139
|
+
accept=".epub,.pdf"
|
|
140
|
+
onChange={(e) => setFile(e.target.files[0] ?? null)}
|
|
141
|
+
style={{ margin: 16 }}
|
|
142
|
+
/>
|
|
143
|
+
{file && (
|
|
144
|
+
<div style={{ flex: 1 }}>
|
|
145
|
+
<BookViewer file={file} title={file.name} />
|
|
146
|
+
</div>
|
|
147
|
+
)}
|
|
148
|
+
</div>
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### PDF with known page count (faster display)
|
|
154
|
+
```jsx
|
|
155
|
+
<BookViewer
|
|
156
|
+
src="/files/report.pdf"
|
|
157
|
+
type="pdf"
|
|
158
|
+
totalPagesHint={48}
|
|
159
|
+
title="Q4 Report"
|
|
160
|
+
canDownload
|
|
161
|
+
downloadUrl="/files/report.pdf"
|
|
162
|
+
/>
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Pass custom fetch headers (e.g. JWT auth)
|
|
166
|
+
```jsx
|
|
167
|
+
<BookViewer
|
|
168
|
+
src="/secure/book.epub"
|
|
169
|
+
type="epub"
|
|
170
|
+
title="Protected Book"
|
|
171
|
+
fetchOptions={{
|
|
172
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
173
|
+
credentials: "include",
|
|
174
|
+
}}
|
|
175
|
+
/>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## `EpubViewer` (direct use)
|
|
181
|
+
|
|
182
|
+
Use this when you have already resolved the blob URL yourself. It handles EPUB parsing, page scanning, and progressive screenshot capture internally.
|
|
183
|
+
|
|
184
|
+
### Props
|
|
185
|
+
|
|
186
|
+
| Prop | Type | Required | Description |
|
|
187
|
+
|---------------|-----------|----------|---------------------------------------------------------------|
|
|
188
|
+
| `blobUrl` | `string` | yes | `blob:` URL pointing to the EPUB file |
|
|
189
|
+
| `pageWidth` | `number` | yes | Width of a single page in pixels (use `useBookDimensions`) |
|
|
190
|
+
| `pageHeight` | `number` | yes | Height of a single page in pixels (use `useBookDimensions`) |
|
|
191
|
+
| `title` | `string` | no | Displayed in the toolbar |
|
|
192
|
+
| `canDownload` | `boolean` | no | Show download button in toolbar |
|
|
193
|
+
| `downloadUrl` | `string` | no | `href` for the download button |
|
|
194
|
+
|
|
195
|
+
### How EPUB rendering works (two-phase)
|
|
196
|
+
|
|
197
|
+
**Phase 1 — Pre-scan (fast):** Each spine item is rendered into a hidden off-screen `<div>` using `epubjs`. The component measures the `scrollHeight` of the rendered iframe to calculate how many viewport-sized pages each section produces. A hard cap of **3,000 pages** is enforced.
|
|
198
|
+
|
|
199
|
+
**Phase 2 — Background capture:** After the flipbook mounts with placeholder slots, `html2canvas` screenshots each page progressively. A progress bar in the toolbar tracks completion (`0–100%`). Pages render in place as they complete — you can read from page 1 while later pages are still loading.
|
|
200
|
+
|
|
201
|
+
### Example
|
|
202
|
+
|
|
203
|
+
```jsx
|
|
204
|
+
import { useRef } from "react";
|
|
205
|
+
import { EpubViewer, useBookDimensions } from "@sujanbomjan/react-crud-ui";
|
|
206
|
+
|
|
207
|
+
export default function MyEpubReader({ epubBlobUrl }) {
|
|
208
|
+
const containerRef = useRef(null);
|
|
209
|
+
const { pageWidth, pageHeight } = useBookDimensions(containerRef);
|
|
210
|
+
|
|
211
|
+
return (
|
|
212
|
+
<div ref={containerRef} style={{ width: "100%", height: "100vh" }}>
|
|
213
|
+
{pageWidth > 0 && (
|
|
214
|
+
<EpubViewer
|
|
215
|
+
blobUrl={epubBlobUrl}
|
|
216
|
+
pageWidth={pageWidth}
|
|
217
|
+
pageHeight={pageHeight}
|
|
218
|
+
title="My EPUB Book"
|
|
219
|
+
/>
|
|
220
|
+
)}
|
|
221
|
+
</div>
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## `PdfViewer` (direct use)
|
|
229
|
+
|
|
230
|
+
Use this when you have already resolved the blob URL yourself. PDF pages are **lazily rendered** — only pages within ±2 pages of the current visible spread are rendered at any time.
|
|
231
|
+
|
|
232
|
+
### Props
|
|
233
|
+
|
|
234
|
+
| Prop | Type | Required | Description |
|
|
235
|
+
|------------------|-----------|----------|---------------------------------------------------------------|
|
|
236
|
+
| `blobUrl` | `string` | yes | `blob:` URL pointing to the PDF file |
|
|
237
|
+
| `pageWidth` | `number` | yes | Width of a single page in pixels (use `useBookDimensions`) |
|
|
238
|
+
| `pageHeight` | `number` | yes | Height of a single page in pixels (use `useBookDimensions`) |
|
|
239
|
+
| `title` | `string` | no | Displayed in the toolbar |
|
|
240
|
+
| `canDownload` | `boolean` | no | Show download button in toolbar |
|
|
241
|
+
| `downloadUrl` | `string` | no | `href` for the download button |
|
|
242
|
+
| `totalPagesHint` | `number` | no | Pre-known page count — shows total immediately without waiting for PDF load |
|
|
243
|
+
|
|
244
|
+
### How PDF rendering works
|
|
245
|
+
|
|
246
|
+
- PDF.js `4.0.379` is loaded **dynamically from CDN** (`cdnjs.cloudflare.com`) on first use — no `pdfjs-dist` npm package needed.
|
|
247
|
+
- Pages are rendered to a `<canvas>` and converted to JPEG (quality `0.92`) data URLs.
|
|
248
|
+
- A **lazy window of ±2 pages** around the current spread is maintained — when you flip, the next pages render ahead automatically.
|
|
249
|
+
- Pages already rendered are cached in state for the lifetime of the component.
|
|
250
|
+
|
|
251
|
+
### Example
|
|
252
|
+
|
|
253
|
+
```jsx
|
|
254
|
+
import { useRef } from "react";
|
|
255
|
+
import { PdfViewer, useBookDimensions } from "@sujanbomjan/react-crud-ui";
|
|
256
|
+
|
|
257
|
+
export default function MyPdfReader({ pdfBlobUrl }) {
|
|
258
|
+
const containerRef = useRef(null);
|
|
259
|
+
const { pageWidth, pageHeight } = useBookDimensions(containerRef);
|
|
260
|
+
|
|
261
|
+
return (
|
|
262
|
+
<div ref={containerRef} style={{ width: "100%", height: "100vh" }}>
|
|
263
|
+
{pageWidth > 0 && (
|
|
264
|
+
<PdfViewer
|
|
265
|
+
blobUrl={pdfBlobUrl}
|
|
266
|
+
pageWidth={pageWidth}
|
|
267
|
+
pageHeight={pageHeight}
|
|
268
|
+
title="My PDF"
|
|
269
|
+
totalPagesHint={20}
|
|
270
|
+
/>
|
|
271
|
+
)}
|
|
272
|
+
</div>
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
---
|
|
278
|
+
|
|
279
|
+
## `useBookDimensions(containerRef)`
|
|
280
|
+
|
|
281
|
+
Observes a container element with `ResizeObserver` and computes page dimensions that fit the available viewport height while preserving an A4-like aspect ratio (`1:1.414`). Re-calculates on both container resize and window resize.
|
|
282
|
+
|
|
283
|
+
### Returns
|
|
284
|
+
|
|
285
|
+
| Field | Type | Description |
|
|
286
|
+
|------------------|----------|-----------------------------------------------------------|
|
|
287
|
+
| `containerWidth` | `number` | Current measured width of the container in pixels |
|
|
288
|
+
| `spreadWidth` | `number` | Total width for a two-page spread (`pageWidth * 2`) |
|
|
289
|
+
| `pageWidth` | `number` | Width of a single page in pixels |
|
|
290
|
+
| `pageHeight` | `number` | Height of a single page in pixels |
|
|
291
|
+
|
|
292
|
+
> All values start at `0`. Guard against rendering before the first measurement: `{pageWidth > 0 && <EpubViewer ... />}`.
|
|
293
|
+
|
|
294
|
+
### Dimension logic
|
|
295
|
+
|
|
296
|
+
- Maximum page height is capped at `720px` or the available viewport height, whichever is smaller.
|
|
297
|
+
- Navigation buttons (`40px` each) are subtracted from the container width before computing `pageWidth`.
|
|
298
|
+
- Minimum page size is `150×200px`.
|
|
299
|
+
|
|
300
|
+
### Example
|
|
301
|
+
|
|
302
|
+
```jsx
|
|
303
|
+
import { useRef } from "react";
|
|
304
|
+
import { useBookDimensions } from "@sujanbomjan/react-crud-ui";
|
|
305
|
+
|
|
306
|
+
function DimensionDebug() {
|
|
307
|
+
const ref = useRef(null);
|
|
308
|
+
const { pageWidth, pageHeight, spreadWidth } = useBookDimensions(ref);
|
|
309
|
+
|
|
310
|
+
return (
|
|
311
|
+
<div ref={ref} style={{ width: "100%" }}>
|
|
312
|
+
<p>Spread: {spreadWidth}px — Each page: {pageWidth} × {pageHeight}px</p>
|
|
313
|
+
</div>
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
---
|
|
319
|
+
|
|
320
|
+
## Keyboard Navigation
|
|
321
|
+
|
|
322
|
+
Both viewers attach global `keydown` listeners while mounted:
|
|
323
|
+
|
|
324
|
+
| Key | Action |
|
|
325
|
+
|---------------|---------------------------|
|
|
326
|
+
| `→ ArrowRight`| Flip to next two pages |
|
|
327
|
+
| `← ArrowLeft` | Flip to previous two pages|
|
|
328
|
+
|
|
329
|
+
Mouse click on page corners and touch swipe (distance threshold: `30px`) also trigger page flips.
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
## Container setup
|
|
334
|
+
|
|
335
|
+
The component needs a container with a defined width. Height drives the dimension calculation via `window.innerHeight`. A full-screen layout works best:
|
|
336
|
+
|
|
337
|
+
```jsx
|
|
338
|
+
// Full page
|
|
339
|
+
<div style={{ height: "100vh" }}>
|
|
340
|
+
<BookViewer src="..." title="..." />
|
|
341
|
+
</div>
|
|
342
|
+
|
|
343
|
+
// Inside a fixed-height panel
|
|
344
|
+
<div style={{ width: "100%", height: 700 }}>
|
|
345
|
+
<BookViewer src="..." title="..." />
|
|
346
|
+
</div>
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
> If the container has `height: 0` or `width: 0`, the viewer will not render (dimensions are `0` until the first ResizeObserver measurement).
|
|
350
|
+
|
|
351
|
+
---
|
|
352
|
+
|
|
353
|
+
## Troubleshooting
|
|
354
|
+
|
|
355
|
+
| Symptom | Likely cause | Fix |
|
|
356
|
+
|---|---|---|
|
|
357
|
+
| Blank/lined pages in EPUB | `html2canvas` failed to capture the iframe | Check browser console; usually caused by cross-origin iframe content |
|
|
358
|
+
| "No readable sections found" | EPUB spine is empty | Verify the EPUB file is valid (`epubcheck`) |
|
|
359
|
+
| "Failed to render EPUB pages" | `epubjs` threw during render | Check console; file may be malformed or DRM-protected |
|
|
360
|
+
| PDF shows spinner forever | CDN blocked or offline | Check network tab for `cdnjs.cloudflare.com` requests; ensure internet access |
|
|
361
|
+
| "Failed to load PDF" | PDF.js CDN request failed or the blob URL is invalid | Verify the blob URL is still alive and CDN is reachable |
|
|
362
|
+
| Viewer is 0px tall / not visible | Container has no width or height | Wrap in a `div` with explicit dimensions |
|
|
363
|
+
| `pageWidth` is `0` on first render | `useBookDimensions` hasn't measured yet | Guard with `{pageWidth > 0 && <EpubViewer />}` |
|
|
364
|
+
| Pages out of order in EPUB | Long EPUB with many spine items | Expected during Phase 2 capture; pages fill in as captured |
|
|
365
|
+
| EPUB stops at 3,000 pages | `MAX_PAGES` hard cap | By design — very long books are capped to prevent memory exhaustion |
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Toast Notifications Guide
|
|
2
|
+
|
|
3
|
+
Complete reference for the toast notification system in @sujanbomjan/react-crud-ui.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
1. [Setup](#setup)
|
|
7
|
+
2. [useToast](#usetoast)
|
|
8
|
+
3. [ToastContainer](#toastcontainer)
|
|
9
|
+
4. [Toast Options](#toast-options)
|
|
10
|
+
5. [Validation Error Example](#validation-error-example)
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Setup
|
|
15
|
+
|
|
16
|
+
Toasts are backed by an internal Zustand store, so no provider is required — just mount `ToastContainer` once near the root of your app and call `useToast()` from anywhere.
|
|
17
|
+
|
|
18
|
+
```jsx
|
|
19
|
+
// src/App.jsx
|
|
20
|
+
import { ToastContainer } from '@sujanbomjan/react-crud-ui';
|
|
21
|
+
|
|
22
|
+
function App() {
|
|
23
|
+
return (
|
|
24
|
+
<>
|
|
25
|
+
{/* ...routes/layout... */}
|
|
26
|
+
<ToastContainer />
|
|
27
|
+
</>
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`ToastContainer` renders fixed to the bottom-right of the viewport (`bottom-4 right-4`) and stacks toasts vertically.
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## `useToast`
|
|
37
|
+
|
|
38
|
+
```jsx
|
|
39
|
+
import { useToast } from '@sujanbomjan/react-crud-ui';
|
|
40
|
+
|
|
41
|
+
function ProductForm() {
|
|
42
|
+
const { success, error, warning, info, toast, dismiss, clearAll } = useToast();
|
|
43
|
+
|
|
44
|
+
const handleCreate = async () => {
|
|
45
|
+
try {
|
|
46
|
+
await createProduct();
|
|
47
|
+
success('Product created successfully!');
|
|
48
|
+
} catch (err) {
|
|
49
|
+
error('Failed to create product', { title: 'Error' });
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
return <button onClick={handleCreate}>Create</button>;
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Returned API
|
|
58
|
+
|
|
59
|
+
| Method | Signature | Description |
|
|
60
|
+
|--------|-----------|--------------|
|
|
61
|
+
| `toast` | `(options) => id` | Add a toast with a fully custom `options` object (see below) |
|
|
62
|
+
| `success` | `(message, options?) => id` | Shortcut for `toast({ type: 'success', message, ...options })` |
|
|
63
|
+
| `error` | `(message, options?) => id` | Shortcut for `toast({ type: 'error', message, ...options })` |
|
|
64
|
+
| `warning` | `(message, options?) => id` | Shortcut for `toast({ type: 'warning', message, ...options })` |
|
|
65
|
+
| `info` | `(message, options?) => id` | Shortcut for `toast({ type: 'info', message, ...options })` |
|
|
66
|
+
| `dismiss` | `(id) => void` | Remove a specific toast before its auto-dismiss timer fires |
|
|
67
|
+
| `clearAll` | `() => void` | Remove every active toast |
|
|
68
|
+
| `toasts` | `array` | Current list of active toast objects (used internally by `ToastContainer`) |
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## `ToastContainer`
|
|
73
|
+
|
|
74
|
+
Renders every active toast. Mount it once, typically at the top level of your app (it has no props).
|
|
75
|
+
|
|
76
|
+
- Icon and color are derived automatically from `type` (`success`, `error`, `warning`, `info` — defaults to `info` for unknown types).
|
|
77
|
+
- Clicking the `×` button calls `dismiss(id)`.
|
|
78
|
+
- Toasts animate in from the right (`slide-in-from-right-full`).
|
|
79
|
+
|
|
80
|
+
```jsx
|
|
81
|
+
import { ToastContainer } from '@sujanbomjan/react-crud-ui';
|
|
82
|
+
|
|
83
|
+
<ToastContainer />
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Toast Options
|
|
89
|
+
|
|
90
|
+
Options accepted by `toast(options)` (and merged in by `success`/`error`/`warning`/`info`):
|
|
91
|
+
|
|
92
|
+
| Option | Type | Default | Description |
|
|
93
|
+
|--------|------|---------|--------------|
|
|
94
|
+
| `type` | `'success' \| 'error' \| 'warning' \| 'info'` | `'info'` | Determines icon and color |
|
|
95
|
+
| `message` | `string` | — | Main toast text |
|
|
96
|
+
| `title` | `string` | — | Optional bold heading shown above the message |
|
|
97
|
+
| `details` | `object` | — | Field-level messages, e.g. API validation errors — see below |
|
|
98
|
+
| `duration` | `number` (ms) | `5000` | Auto-dismiss delay. Pass `0` to disable auto-dismiss (toast stays until manually dismissed) |
|
|
99
|
+
|
|
100
|
+
### Example: with title
|
|
101
|
+
|
|
102
|
+
```jsx
|
|
103
|
+
success('Your changes have been saved.', { title: 'Saved' });
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Example: persistent toast
|
|
107
|
+
|
|
108
|
+
```jsx
|
|
109
|
+
info('Upload in progress — this may take a few minutes.', { duration: 0 });
|
|
110
|
+
// later, once done:
|
|
111
|
+
dismiss(id);
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Validation Error Example
|
|
117
|
+
|
|
118
|
+
`details` renders as a bulleted list of field-level messages below the main text — useful for surfacing API validation errors (each value can be a string or an array of strings):
|
|
119
|
+
|
|
120
|
+
```jsx
|
|
121
|
+
try {
|
|
122
|
+
await api.post('/products', data);
|
|
123
|
+
} catch (err) {
|
|
124
|
+
error('Please fix the errors below', {
|
|
125
|
+
title: 'Validation failed',
|
|
126
|
+
details: err.response?.data?.errors,
|
|
127
|
+
// e.g. { name: ['Name is required'], price: 'Price must be positive' }
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
```
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# Utility Functions Guide
|
|
2
|
+
|
|
3
|
+
Complete reference for the standalone utility functions in @sujanbomjan/react-crud-ui. All of these are pure functions with no dependency on any store or component — import only what you need.
|
|
4
|
+
|
|
5
|
+
```jsx
|
|
6
|
+
import {
|
|
7
|
+
cn,
|
|
8
|
+
formatCurrency,
|
|
9
|
+
formatDate,
|
|
10
|
+
formatDateTime,
|
|
11
|
+
formatRelativeTime,
|
|
12
|
+
TimeStampFormat,
|
|
13
|
+
truncate,
|
|
14
|
+
capitalize,
|
|
15
|
+
slugify,
|
|
16
|
+
debounce,
|
|
17
|
+
generateId,
|
|
18
|
+
deepClone,
|
|
19
|
+
isEmpty,
|
|
20
|
+
getInitials,
|
|
21
|
+
parseQueryString,
|
|
22
|
+
buildQueryString,
|
|
23
|
+
} from '@sujanbomjan/react-crud-ui';
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Table of Contents
|
|
27
|
+
1. [cn](#cnclassvalue)
|
|
28
|
+
2. [Formatting](#formatting)
|
|
29
|
+
3. [String helpers](#string-helpers)
|
|
30
|
+
4. [Misc helpers](#misc-helpers)
|
|
31
|
+
5. [Query string helpers](#query-string-helpers)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## `cn(...classValue)`
|
|
36
|
+
|
|
37
|
+
Merges Tailwind class names with [`clsx`](https://github.com/lukeed/clsx) + [`tailwind-merge`](https://github.com/dcastil/tailwind-merge), so conflicting utility classes (e.g. `p-2` vs `p-4`) resolve correctly instead of both being applied.
|
|
38
|
+
|
|
39
|
+
```jsx
|
|
40
|
+
cn('px-2 py-1', isActive && 'bg-blue-500', className);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Used internally by nearly every component in this library to accept a `className` override prop.
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Formatting
|
|
48
|
+
|
|
49
|
+
### `formatCurrency(amount, currency = 'NPR')`
|
|
50
|
+
|
|
51
|
+
Formats a number as currency using `Intl.NumberFormat('en-NP', ...)`.
|
|
52
|
+
|
|
53
|
+
```jsx
|
|
54
|
+
formatCurrency(1500); // "NPR 1,500.00"
|
|
55
|
+
formatCurrency(99.5, 'USD'); // "$99.50"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### `formatDate(date, options = {})`
|
|
59
|
+
|
|
60
|
+
Formats a date as `Month Day, Year` (locale `en-US`) by default. `options` is merged into and overrides the `Intl.DateTimeFormat` options.
|
|
61
|
+
|
|
62
|
+
```jsx
|
|
63
|
+
formatDate('2026-07-12'); // "July 12, 2026"
|
|
64
|
+
formatDate('2026-07-12', { month: 'short' }); // "Jul 12, 2026"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### `formatDateTime(date)`
|
|
68
|
+
|
|
69
|
+
Formats a date + time as `Mon Day, Year, HH:MM` (locale `en-US`, 2-digit hour/minute).
|
|
70
|
+
|
|
71
|
+
```jsx
|
|
72
|
+
formatDateTime('2026-07-12T14:30:00'); // "Jul 12, 2026, 02:30 PM"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### `TimeStampFormat(date)`
|
|
76
|
+
|
|
77
|
+
Formats a date as `YYYY-MM-DD HH:MM:SS` (24-hour, zero-padded). Returns `'-'` for a falsy input — handy for rendering optional timestamp fields in a table without a null check at the call site.
|
|
78
|
+
|
|
79
|
+
```jsx
|
|
80
|
+
TimeStampFormat('2026-07-12T09:05:03'); // "2026-07-12 09:05:03"
|
|
81
|
+
TimeStampFormat(null); // "-"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### `formatRelativeTime(date)`
|
|
85
|
+
|
|
86
|
+
Formats a date relative to now (`"just now"`, `"5 minutes ago"`, `"3 hours ago"`, `"2 days ago"`). Falls back to `formatDate` once the difference exceeds a week.
|
|
87
|
+
|
|
88
|
+
```jsx
|
|
89
|
+
formatRelativeTime(new Date(Date.now() - 5 * 60 * 1000)); // "5 minutes ago"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## String helpers
|
|
95
|
+
|
|
96
|
+
### `truncate(str, length = 100)`
|
|
97
|
+
|
|
98
|
+
Truncates a string to `length` characters, appending `...` if it was cut. Returns `''` for a falsy input.
|
|
99
|
+
|
|
100
|
+
```jsx
|
|
101
|
+
truncate('A very long product description...', 20); // "A very long product ..."
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### `capitalize(str)`
|
|
105
|
+
|
|
106
|
+
Uppercases the first character only. Returns `''` for a falsy input.
|
|
107
|
+
|
|
108
|
+
```jsx
|
|
109
|
+
capitalize('hello world'); // "Hello world"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### `slugify(str)`
|
|
113
|
+
|
|
114
|
+
Converts a string to a URL-safe slug: lowercases, trims, strips non-word characters, and collapses whitespace/underscores/dashes into single hyphens.
|
|
115
|
+
|
|
116
|
+
```jsx
|
|
117
|
+
slugify(' Hello, World! '); // "hello-world"
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### `getInitials(name)`
|
|
121
|
+
|
|
122
|
+
Returns up to 2 uppercase initials from a space-separated name. Returns `''` for a falsy input.
|
|
123
|
+
|
|
124
|
+
```jsx
|
|
125
|
+
getInitials('Sujan Bomjan'); // "SB"
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Misc helpers
|
|
131
|
+
|
|
132
|
+
### `debounce(func, wait = 300)`
|
|
133
|
+
|
|
134
|
+
Returns a debounced version of `func` that only runs after `wait` ms of inactivity. Commonly used for search inputs.
|
|
135
|
+
|
|
136
|
+
```jsx
|
|
137
|
+
const handleSearch = debounce((value) => {
|
|
138
|
+
setSearchQuery(value);
|
|
139
|
+
}, 300);
|
|
140
|
+
|
|
141
|
+
<input onChange={(e) => handleSearch(e.target.value)} />
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### `generateId()`
|
|
145
|
+
|
|
146
|
+
Returns a short random alphanumeric string (`Math.random().toString(36)`, 7 characters). Suitable for client-only keys (e.g. list item `key`s before a real ID exists) — **not** cryptographically secure and not guaranteed unique across a large dataset.
|
|
147
|
+
|
|
148
|
+
```jsx
|
|
149
|
+
generateId(); // e.g. "f3k2p9a"
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### `deepClone(obj)`
|
|
153
|
+
|
|
154
|
+
Deep-clones a plain JSON-serializable object via `JSON.parse(JSON.stringify(obj))`. Does not preserve `Date`, `Map`, `Set`, `undefined` values, or functions — only use on plain data objects.
|
|
155
|
+
|
|
156
|
+
```jsx
|
|
157
|
+
const copy = deepClone(originalFormValues);
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### `isEmpty(obj)`
|
|
161
|
+
|
|
162
|
+
Returns `true` for `null`/`undefined`, an empty array, or an object with no own keys; `false` otherwise (including for empty strings and `0`, which are returned as-is by the fallback).
|
|
163
|
+
|
|
164
|
+
```jsx
|
|
165
|
+
isEmpty(null); // true
|
|
166
|
+
isEmpty([]); // true
|
|
167
|
+
isEmpty({}); // true
|
|
168
|
+
isEmpty({ a: 1 }); // false
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## Query string helpers
|
|
174
|
+
|
|
175
|
+
### `parseQueryString(queryString)`
|
|
176
|
+
|
|
177
|
+
Parses a query string (with or without a leading `?`) into a plain object via `URLSearchParams`.
|
|
178
|
+
|
|
179
|
+
```jsx
|
|
180
|
+
parseQueryString('?page=2&search=shoes'); // { page: '2', search: 'shoes' }
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### `buildQueryString(params)`
|
|
184
|
+
|
|
185
|
+
Builds a query string from an object, skipping keys whose value is `null`, `undefined`, or `''`.
|
|
186
|
+
|
|
187
|
+
```jsx
|
|
188
|
+
buildQueryString({ page: 2, search: 'shoes', category: '' });
|
|
189
|
+
// "page=2&search=shoes"
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Pairing the two is a common pattern for syncing table filters with the URL:
|
|
193
|
+
|
|
194
|
+
```jsx
|
|
195
|
+
import { useSearchParams } from 'react-router-dom';
|
|
196
|
+
import { buildQueryString, parseQueryString } from '@sujanbomjan/react-crud-ui';
|
|
197
|
+
|
|
198
|
+
const [searchParams, setSearchParams] = useSearchParams();
|
|
199
|
+
const filters = parseQueryString(searchParams.toString());
|
|
200
|
+
|
|
201
|
+
const applyFilters = (next) => {
|
|
202
|
+
setSearchParams(buildQueryString({ ...filters, ...next }));
|
|
203
|
+
};
|
|
204
|
+
```
|