@osmandvc/react-upload-control 0.3.2 → 1.0.1

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 (60) hide show
  1. package/README.md +190 -262
  2. package/dist/index.d.ts +1 -6
  3. package/dist/index.js +1 -2
  4. package/dist/providers/UploadedFilesManager.d.ts +2 -2
  5. package/dist/providers/UploadedFilesProvider.d.ts +0 -1
  6. package/dist/providers/index.d.ts +2 -2
  7. package/dist/types.d.ts +10 -11
  8. package/package.json +25 -32
  9. package/dist/FileUploadContainer.d.ts +0 -9
  10. package/dist/FileUploadControl.d.ts +0 -5
  11. package/dist/actions/FileDeleteAllButton.d.ts +0 -1
  12. package/dist/actions/FileItemActions.d.ts +0 -7
  13. package/dist/actions/FileUploadAllButton.d.ts +0 -1
  14. package/dist/actions/index.d.ts +0 -3
  15. package/dist/components/camera/custom-react-webcam.d.ts +0 -58
  16. package/dist/components/camera/frames/index.d.ts +0 -1
  17. package/dist/components/camera/index.d.ts +0 -1
  18. package/dist/components/camera/use-webcam.d.ts +0 -34
  19. package/dist/components/file-drop/FileDropArea.d.ts +0 -2
  20. package/dist/components/file-drop/FileDropLarge.d.ts +0 -6
  21. package/dist/components/file-drop/FileDropSmall.d.ts +0 -6
  22. package/dist/components/file-list/FileList.d.ts +0 -2
  23. package/dist/components/file-list/FileListActions.d.ts +0 -1
  24. package/dist/components/file-list/FileListContainer.d.ts +0 -6
  25. package/dist/components/file-list/FileListItem.d.ts +0 -3
  26. package/dist/components/index.d.ts +0 -6
  27. package/dist/hooks/index.d.ts +0 -2
  28. package/dist/hooks/use-mobile-detect.d.ts +0 -9
  29. package/dist/hooks/use-state-machine.d.ts +0 -21
  30. package/dist/index.js.LICENSE.txt +0 -33
  31. package/dist/loaders/FileLoaderActions.d.ts +0 -2
  32. package/dist/loaders/FileLoaderCamera.d.ts +0 -2
  33. package/dist/loaders/FileLoaderFileSystem.d.ts +0 -2
  34. package/dist/loaders/index.d.ts +0 -3
  35. package/dist/ui/button/Button.d.ts +0 -18
  36. package/dist/ui/button/index.d.ts +0 -1
  37. package/dist/ui/card/Card.d.ts +0 -8
  38. package/dist/ui/card/index.d.ts +0 -1
  39. package/dist/ui/dialog/Dialog.d.ts +0 -19
  40. package/dist/ui/dialog/index.d.ts +0 -1
  41. package/dist/ui/icons/index.d.ts +0 -1
  42. package/dist/ui/image-zoom/index.d.ts +0 -3
  43. package/dist/ui/progress/Progress.d.ts +0 -4
  44. package/dist/ui/progress/index.d.ts +0 -1
  45. package/dist/ui/select/Select.d.ts +0 -13
  46. package/dist/ui/select/index.d.ts +0 -1
  47. package/dist/ui/seperator/Seperator.d.ts +0 -4
  48. package/dist/ui/seperator/index.d.ts +0 -1
  49. package/dist/ui/tooltip/Tooltip.d.ts +0 -7
  50. package/dist/ui/tooltip/index.d.ts +0 -1
  51. package/dist/utils/api-mocker.d.ts +0 -2
  52. package/dist/utils/cn.d.ts +0 -2
  53. package/dist/utils/date/index.d.ts +0 -1
  54. package/dist/utils/file-types.d.ts +0 -36
  55. package/dist/utils/image-processing/blob-to-base64.d.ts +0 -1
  56. package/dist/utils/image-processing/canvas-utils.d.ts +0 -7
  57. package/dist/utils/image-processing/index.d.ts +0 -3
  58. package/dist/utils/image-processing/load-image.d.ts +0 -3
  59. package/dist/utils/index.d.ts +0 -5
  60. package/dist/utils/is-filedrop-error.d.ts +0 -2
package/README.md CHANGED
@@ -1,12 +1,10 @@
1
- # React Upload Control
1
+ # React Upload Control Core
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@osmandvc/react-upload-control.svg)](https://www.npmjs.com/package/@osmandvc/react-upload-control)
4
4
  [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
6
 
7
- A modern, flexible file upload control for React applications.
8
-
9
- React Upload Control is a free, lightweight and open-source file uploader library designed for modern React applications. This library is crafted to provide a high-quality developer experience (DX), making it easy to use for simple file uploads while offering extensive customization options for advanced use cases.
7
+ The core package of React Upload Control, providing the essential hooks and providers for file upload management in React applications. This package is part of the React Upload Control ecosystem, designed to be lightweight and tree-shakable.
10
8
 
11
9
  ## Demo
12
10
 
@@ -17,91 +15,64 @@ Check out our interactive demo cases here:
17
15
 
18
16
  Born from real-world needs in a production environment, React Upload Control addresses common limitations found in existing file upload solutions. While there are many file upload libraries available, we found that most of them fell short in crucial areas:
19
17
 
20
- - 🔄 **No Drag-to-Reorder:** Most solutions lack built-in file ordering capabilities, a crucial feature for many applications
21
18
  - 📚 **Documentation Gaps:** Many libraries either have excessive boilerplate, insufficient documentation or lacking DX
22
19
  - 🔧 **Maintenance Issues:** Several options are outdated or no longer actively maintained
23
- - 🎨 **Poor UI/UX:** Many unstyled options result in subpar user interfaces
24
20
  - 🔒 **Vendor Lock-in:** Some solutions tie you to specific cloud services or platforms
25
21
  - 📦 **Bloated Dependencies:** Often file uploaders come bundled within larger UI libraries, increasing your bundle size
26
22
 
27
- React Upload Control was created to solve these problems, offering a standalone, modern file uploader that's both powerful and flexible. Whether you need a simple file upload control or a feature-rich solution with file processing capabilities, you can customize it to your specific needs without compromising on quality or developer experience.
23
+ React Upload Control was created to solve these problems, offering a powerful and flexible core that you can build upon. Whether you need a simple file upload implementation or want to build a feature-rich solution, you can customize it to your specific needs without compromising on quality or developer experience.
28
24
 
29
- ## Features summary 🔥
25
+ ## Features 🔥
30
26
 
31
27
  - 🚀 **Modern Stack:** Built with React 18+ and TypeScript for type-safe development
32
- - 📁 **Drag & Drop:** Intuitive file uploading with visual feedback and validation
33
- - 📋 **File Management:** Drag-to-reorder capability for organizing user uploads
34
- - 🔄 **File Processing:** Optional pre/post-processing capabilities with [@osmandvc/react-upload-control-processors](https://www.npmjs.com/package/@osmandvc/react-upload-control-processors) or custom integrations
35
- - 📷 **Camera Integration:** Camera integration for capturing photos directly
36
- - 💻 **Developer Experience:** Simple API with comprehensive TypeScript support and documentation
37
- - 🌐 **Internationalization:** Built-in i18n support for multiple languages (currently English and German)
38
- - 🎨 **Beautiful UI:** Modern, responsive design powered by Tailwind CSS
39
- - 📱 **Mobile Ready:** Optimized experience across all device sizes
28
+ - 🎯 **Core Functionality:** Provides the essential hooks and providers for file upload management
29
+ - 🌳 **Tree Shakable:** Only import what you need, keeping your bundle size minimal
30
+ - ⚛️ **State Management:** Built-in state machine for handling upload lifecycle
31
+ - 🔄 **File Ordering:** Built-in file ordering system with programmatic reordering capabilities
40
32
  - ⚡ **Async Processing:** Handle file uploads asynchronously with progress updates
41
- - 🔍 **File Preview:** Built-in preview support for images
33
+ - 💻 **Developer Experience:** Simple API with comprehensive TypeScript support
42
34
  - ⚙️ **Unopinionated:** You decide how and where files are uploaded, no vendor lock-in
43
35
  - 🔓 **Open Source:** Free to use and modify under the MIT license
36
+ - 📦 **Lightweight:** Zero dependencies (except for optional toaster notifications)
44
37
 
45
38
  ## Installation
46
39
 
47
- To install React Upload Control, use npm or yarn:
48
-
49
40
  ```bash
50
41
  npm install @osmandvc/react-upload-control
42
+
43
+ # Optional: Install sonner if you want built-in toast notifications
44
+ npm install sonner
51
45
  ```
52
46
 
53
- or
47
+ ## Pre-built Components
54
48
 
55
- ```bash
56
- yarn add @osmandvc/react-upload-control
57
- ```
49
+ Looking for a complete UI solution? Check out [@osmandvc/react-upload-control-components](https://www.npmjs.com/package/@osmandvc/react-upload-control-components), our official UI components package that provides:
50
+
51
+ - Drag & Drop upload zone
52
+ - File list with reordering capabilities
53
+ - Progress indicators
54
+ - Camera integration
55
+ - And more!
58
56
 
59
- ## Getting Started
57
+ While this is currently the only pre-built component package, we welcome community-built components and plan to integrate more solutions in the future. The core package's flexible architecture makes it easy to build custom UI components on top of it.
60
58
 
61
- This section will guide you through the process of setting up everything you need to get started. The library is built around the concept of providers and the React Context API, which means you need to wrap your application in a `UploadedFilesProvider` provider. If you want to use the default use case of a list of files and a drop area, you can do this by wrapping your `FileUploadControl` component in the provider. An minimal example of this can be seen below:
59
+ ## Basic Usage
62
60
 
63
61
  ```tsx
64
- import React, { PropsWithChildren } from "react";
65
62
  import {
66
- FileUploadControl,
67
63
  UploadedFilesProvider,
68
- UploadedFile,
69
- UploadFileResult,
70
- } from "react-upload-control";
71
-
72
- function MyFileUploadParent(props: PropsWithChildren) {
73
- // Your custom delete and upload handlers (more about them later)...
74
- // function handleDelete(files: UploadedFile[]) {...}
75
- // function handleUpload(files: UploadedFile[], onProgressChange: (...) => void) {...}
64
+ useUploadFilesProvider,
65
+ } from "@osmandvc/react-upload-control";
76
66
 
77
- function handleFinish(files: UploadedFile[]) {
78
- console.log(files);
79
- }
67
+ function MyUploadComponent() {
68
+ const uploadProvider = useUploadFilesProvider();
69
+ const { files, addFiles, uploadAllFiles } = uploadProvider;
80
70
 
81
- return (
82
- <UploadedFilesProvider
83
- handlers={{ onUpload: handleUpload, onFinish: handleFinish }}
84
- config={{
85
- mimeTypes: ["image/png", "image/jpeg"],
86
- disableSorting: false, // Disable drag-to-reorder functionality
87
- }}
88
- >
89
- <FileUploadControl />
90
- </UploadedFilesProvider>
91
- );
71
+ return <div>{/* Build your own UI components */}</div>;
92
72
  }
93
73
  ```
94
74
 
95
- ## Upload Handler Guide
96
-
97
- The upload handler is a crucial part of the library that gives you complete control over how files are processed and uploaded.
98
-
99
- The upload handler receives two parameters:
100
-
101
- 1. `files`: An array of `UploadedFile` objects to be uploaded
102
- 2. `onProgressChange`: A callback function to update the upload progress
103
-
104
- Here are two examples of implementing an upload handler:
75
+ ## Upload Handler Examples
105
76
 
106
77
  ### Example 1: Simple Batch Upload
107
78
 
@@ -122,9 +93,9 @@ async function handleUpload(
122
93
 
123
94
  // Create form data with all files
124
95
  const formData = new FormData();
125
- files.forEach((file, index) => {
96
+ files.forEach((file) => {
126
97
  if (file.file) {
127
- formData.append(`files`, file.file);
98
+ formData.append("files", file.file);
128
99
  }
129
100
  });
130
101
 
@@ -138,9 +109,7 @@ async function handleUpload(
138
109
  throw new Error("Upload failed");
139
110
  }
140
111
 
141
- // Example API response with processed file data
142
112
  const result = await response.json();
143
- // { success: true, files: [{ id: "...", url: "..." }] }
144
113
 
145
114
  // Set progress to 100% for all files after successful upload
146
115
  files.forEach((file) => {
@@ -157,13 +126,12 @@ async function handleUpload(
157
126
  },
158
127
  }));
159
128
  } catch (error) {
160
- // Set error state for all files
129
+ // Handle errors
161
130
  const errorResult = {
162
131
  text: error.message || "Upload failed",
163
132
  code: "BATCH_UPLOAD_ERROR",
164
133
  };
165
134
 
166
- // Return error results for all files
167
135
  return files.map((file) => ({
168
136
  fileId: file.id,
169
137
  success: false,
@@ -171,34 +139,12 @@ async function handleUpload(
171
139
  }));
172
140
  }
173
141
  }
174
-
175
- // Usage with the UploadedFilesProvider
176
- function MyFileUpload() {
177
- return (
178
- <UploadedFilesProvider
179
- handlers={{
180
- onUpload: handleUpload,
181
- onFinish: (files) => {
182
- // All files are uploaded successfully at this point
183
- const urls = files.map((f) => f.metadata.url);
184
- console.log("Uploaded file URLs:", urls);
185
- },
186
- }}
187
- config={{
188
- mimeTypes: ["image/jpeg", "image/png", "application/pdf"],
189
- maxFileSizeMb: 10,
190
- }}
191
- >
192
- <FileUploadControl />
193
- </UploadedFilesProvider>
194
- );
195
- }
196
142
  ```
197
143
 
198
- ### Example 2: Real-World AWS S3 Example
144
+ ### Example 2: AWS S3 Upload
199
145
 
200
146
  ```tsx
201
- import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
147
+ import { S3Client } from "@aws-sdk/client-s3";
202
148
  import { Upload } from "@aws-sdk/lib-storage";
203
149
 
204
150
  async function handleS3Upload(
@@ -209,7 +155,6 @@ async function handleS3Upload(
209
155
  error?: { text: string; code: string }
210
156
  ) => void
211
157
  ): Promise<UploadFileResult[]> {
212
- // Initialize the S3 client
213
158
  const s3Client = new S3Client({
214
159
  region: "your-region",
215
160
  credentials: {
@@ -223,10 +168,7 @@ async function handleS3Upload(
223
168
  try {
224
169
  if (!file.file) throw new Error("No file provided");
225
170
 
226
- // Generate a unique key for the file
227
171
  const key = `uploads/${Date.now()}-${file.name}`;
228
-
229
- // Create the upload
230
172
  const upload = new Upload({
231
173
  client: s3Client,
232
174
  params: {
@@ -234,9 +176,6 @@ async function handleS3Upload(
234
176
  Key: key,
235
177
  Body: file.file,
236
178
  ContentType: file.file.type,
237
- // Optional: Set additional parameters
238
- // ACL: 'public-read',
239
- // Metadata: { /* your metadata */ }
240
179
  },
241
180
  });
242
181
 
@@ -248,10 +187,8 @@ async function handleS3Upload(
248
187
  onProgressChange(file.id, percentage);
249
188
  });
250
189
 
251
- // Perform the upload
252
190
  await upload.done();
253
191
 
254
- // Return success result with the S3 URL
255
192
  return {
256
193
  fileId: file.id,
257
194
  success: true,
@@ -260,7 +197,6 @@ async function handleS3Upload(
260
197
  },
261
198
  };
262
199
  } catch (error) {
263
- console.error("S3 upload error:", error);
264
200
  return {
265
201
  fileId: file.id,
266
202
  success: false,
@@ -273,226 +209,218 @@ async function handleS3Upload(
273
209
  })
274
210
  );
275
211
  }
276
-
277
- // Usage with the UploadedFilesProvider
278
- function MyFileUpload() {
279
- return (
280
- <UploadedFilesProvider
281
- handlers={{
282
- onUpload: handleS3Upload,
283
- onFinish: (files) => {
284
- // All files are successfully uploaded at this point
285
- const urls = files.map((f) => f.metadata.url);
286
- console.log("Uploaded file URLs:", urls);
287
- },
288
- }}
289
- config={{
290
- mimeTypes: ["image/jpeg", "image/png", "application/pdf"],
291
- maxFileSizeMb: 10,
292
- }}
293
- >
294
- <FileUploadControl />
295
- </UploadedFilesProvider>
296
- );
297
- }
298
212
  ```
299
213
 
300
- ### Understanding UploadFileResult
214
+ ## State Management
301
215
 
302
- The upload handler must return an array of `UploadFileResult` objects - one for each uploaded file. Here's the structure:
216
+ The core package includes a built-in state machine that handles different upload states automatically. The `useUploadFilesProvider` hook gives you access to these states through the `smStatus` property and helper methods `smStatusIs` and `smStatusIsnt`.
303
217
 
304
- ```typescript
305
- type UploadFileResult = {
306
- // The ID of the file that was uploaded (must match the original file.id)
307
- fileId: string;
218
+ ### Upload States
308
219
 
309
- // Whether the upload was successful
310
- success: boolean;
220
+ The state machine handles the following states:
311
221
 
312
- // Optional error information if success is false
313
- error?: {
314
- text: string; // Human-readable error message
315
- code: string; // Error code for programmatic handling
316
- };
222
+ - **IDLE**: Initial state and after successful operations
223
+ - **PROCESSING**: During file transformations, uploads, or deletions
224
+ - **ERROR**: When an upload operation fails
225
+ - **RETRY**: When retrying after an error
226
+ - **FINISHED**: After successful upload completion (if resetOnFinish is false)
317
227
 
318
- // Optional metadata to attach to the file
319
- metadata?: {
320
- [key: string]: any; // Any additional data you want to store with the file
321
- };
322
- };
323
- ```
228
+ ### State Transitions
324
229
 
325
- Example of a successful upload result:
230
+ States change automatically based on different operations:
326
231
 
327
- ```typescript
328
- {
329
- fileId: "file123",
330
- success: true,
331
- metadata: {
332
- url: "https://example.com/uploads/file123.jpg",
333
- uploadedAt: "2025-01-02T12:00:00Z",
334
- size: 1024000
335
- }
336
- }
337
- ```
232
+ 1. **Adding Files**:
338
233
 
339
- Example of a failed upload result:
234
+ - IDLE PROCESSING (during file transformation)
235
+ - PROCESSING → IDLE (after files are added)
236
+ - PROCESSING → ERROR (if error occurs)
340
237
 
341
- ```typescript
342
- {
343
- fileId: "file456",
344
- success: false,
345
- error: {
346
- text: "File size exceeds server limit",
347
- code: "SIZE_LIMIT_EXCEEDED"
348
- }
349
- }
350
- ```
238
+ 2. **Uploading Files**:
239
+
240
+ - IDLE/ERROR → PROCESSING (during upload)
241
+ - PROCESSING → IDLE (all uploads successful)
242
+ - PROCESSING → ERROR (if any upload fails)
243
+ - ERROR RETRY (when retrying upload)
244
+ - IDLE → FINISHED (after successful upload if resetOnFinish is false)
351
245
 
352
- ## onDelete Handler
246
+ 3. **Deleting Files**:
247
+ - IDLE → PROCESSING (during deletion)
248
+ - PROCESSING → IDLE (after deletion)
353
249
 
354
- The `onDelete` handler is designed to be non-blocking and does not include progress tracking. This is intentional for better UX - since it's primarily used for cleanup when resetting a control with already finished uploads. Users should be able to reset the control immediately without waiting for deletion to complete or being blocked by deletion errors.
250
+ ### File States
251
+
252
+ Individual files also have their own states through the `uploadStatus` property:
355
253
 
356
254
  ```typescript
357
- interface Props {
358
- onDelete?: (files: UploadedFile[]) => void | Promise<void>;
255
+ interface UploadStatus {
256
+ stage: "IDLE" | "UPLOADING" | "FINISHED" | "FAILED";
257
+ progress: number;
258
+ error?: {
259
+ text: string;
260
+ code: string;
261
+ };
359
262
  }
360
263
  ```
361
264
 
362
- > Note: Unlike `onUpload`, the `onDelete` handler won't show progress or block the UI. This ensures users can quickly reset or clear their upload state without delays.
265
+ The hook manages these states automatically during:
363
266
 
364
- ## Core Components
267
+ - File validation
268
+ - Pre-processing
269
+ - Upload progress
270
+ - Upload completion/failure
365
271
 
366
- ### FileUploadControl
367
-
368
- The default component that provides the file upload interface with a FileList and FileDropArea.
272
+ ### Usage Example
369
273
 
370
274
  ```tsx
371
- <FileUploadControl
372
- size="auto" // 'auto' | 'sm' | 'lg'
373
- disableCamera={false} // Disable camera integration
374
- disableFileSystem={false} // Disable file system uploads
375
- />
275
+ function MyUploadComponent() {
276
+ const { smStatus, smStatusIs, files, uploadAllFiles } =
277
+ useUploadFilesProvider();
278
+
279
+ return (
280
+ <div>
281
+ {smStatusIs("ERROR") && <div>Upload failed! Please try again.</div>}
282
+ {smStatusIs("PROCESSING") && <div>Processing...</div>}
283
+ {smStatusIs("FINISHED") && <div>Upload complete!</div>}
284
+
285
+ <button onClick={uploadAllFiles} disabled={smStatusIs("PROCESSING")}>
286
+ {smStatusIs("ERROR") ? "Retry Upload" : "Upload Files"}
287
+ </button>
288
+ </div>
289
+ );
290
+ }
376
291
  ```
377
292
 
378
- ### UploadedFilesProvider
293
+ ## Error Handling
379
294
 
380
- The provider component that manages the upload state and configuration.
295
+ The package provides two ways to handle errors:
381
296
 
382
- ```tsx
383
- <UploadedFilesProvider
384
- config={{
385
- mimeTypes: ["image/jpeg", "image/png"], // Allowed file types
386
- maxFileSizeMb: 10, // Maximum file size in MB
387
- multiple: true, // Allow multiple file uploads
388
- maxFiles: 5, // Maximum number of files
389
- locale: "en", // Locale for i18n
390
- resetOnFinish: false, // Reset state after finish
391
- disableSorting: false, // Disable drag-to-reorder functionality
392
- }}
393
- handlers={{
394
- onUpload: handleUpload, // Upload handler function
395
- onDelete: handleDelete, // Delete handler function
396
- onFinish: handleFinish, // Finish handler function
397
- }}
398
- />
399
- ```
297
+ 1. **Built-in Toast Notifications:** If you have `sonner` installed, the package will automatically show toast notifications for validation errors.
298
+ 2. **Custom Error Handler:** Provide your own `onAddFileError` handler in the provider props for custom error handling.
400
299
 
401
300
  ## API Reference
402
301
 
403
302
  ### UploadedFilesProvider Props
404
303
 
405
- | Prop | Type | Default | Description |
406
- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------------------------------------------- |
407
- | config | { mimeTypes: string[], maxFileSizeMb: number, multiple: boolean, maxFiles: number, locale: string, resetOnFinish: boolean, disableSorting: boolean } | required | Configuration object |
408
- | handlers | { onUpload: (files: UploadedFile[]) => Promise<UploadFileResult[]>, onDelete: (files: UploadedFile[]) => Promise<UploadFileResult[]>, onFinish: (files: UploadedFile[]) => void } | required | Handlers object |
409
- | children | React.ReactNode | required | Child components to render |
410
- | initFiles | UploadedFile[] | undefined | Initial files to populate the uploader with |
411
- | locale | string | 'en' | Locale for internationalization |
412
-
413
- ### FileUploadControl Props
304
+ | Prop | Type | Description |
305
+ | -------- | ------------------ | ----------------------------------- |
306
+ | config | `FileUploadConfig` | Configuration for file uploads |
307
+ | handlers | `UploadHandlers` | Upload and error handling functions |
308
+ | children | `ReactNode` | Child components |
414
309
 
415
- | Prop | Type | Default | Description |
416
- | ----------------- | ---------------------- | --------- | --------------------------- |
417
- | size | 'auto' \| 'sm' \| 'lg' | 'auto' | Component size variant |
418
- | disableCamera | boolean | false | Disable camera integration |
419
- | disableFileSystem | boolean | false | Disable file system uploads |
420
- | className | string | undefined | Additional CSS classes |
310
+ ### Config Options
421
311
 
422
- ## File Processing
312
+ ```typescript
313
+ interface FileUploadConfig {
314
+ mimeTypes: string[]; // Allowed file types
315
+ maxFileSizeMb: number; // Maximum file size in MB
316
+ multiple?: boolean; // Allow multiple file uploads
317
+ maxFiles?: number; // Maximum number of files
318
+ resetOnFinish?: boolean; // Reset state after finish
319
+ disableSorting?: boolean; // Disable reordering
320
+ }
321
+ ```
423
322
 
424
- React Upload Control supports file processing through the optional [@osmandvc/react-upload-control-processors](https://www.npmjs.com/package/@osmandvc/react-upload-control-processors) package. This enables you to process files before or after upload, with built-in support for PDF manipulation and extensible architecture for custom processors.
323
+ ### Handler Types
425
324
 
426
- ```bash
427
- npm install @osmandvc/react-upload-control-processors
325
+ ```typescript
326
+ interface UploadHandlers {
327
+ onUpload: (
328
+ files: UploadedFile[],
329
+ onProgressChange: OnProgressCallback
330
+ ) => Promise<UploadFileResult[]> | UploadFileResult[];
331
+ onDelete?: (files: UploadedFile[]) => Promise<void> | void;
332
+ onFinish?: (files: UploadedFile[]) => void;
333
+ onAddFileError?: (error: FileDropError | unknown) => void;
334
+ }
428
335
  ```
429
336
 
430
- ### Example: PDF to JPEG Conversion
337
+ Example usage of progress callback:
431
338
 
432
- ```tsx
339
+ ```typescript
433
340
  import {
434
- FileUploadControl,
435
- UploadedFile,
436
- UploadedFilesProvider,
437
- UploadFileResult,
341
+ OnProgressCallback,
342
+ UploadProgressError,
438
343
  } from "@osmandvc/react-upload-control";
439
- import { processPdfToJpeg } from "@osmandvc/react-upload-control-processors";
440
344
 
441
- function FileUploadTest() {
345
+ function MyUploadComponent() {
442
346
  return (
443
- <div className="max-w-lg">
444
- <UploadedFilesProvider
445
- config={{
446
- mimeTypes: ["image/png", "image/jpeg", "application/pdf"],
447
- disableSorting: true,
448
- }}
449
- handlers={{
450
- onUpload: handleUpload,
451
- onFinish: handleFinish,
452
- preProcessFiles: {
453
- "application/pdf": processPdfToJpeg,
454
- },
455
- }}
456
- >
457
- <FileUploadControl />
458
- </UploadedFilesProvider>
459
- </div>
347
+ <UploadedFilesProvider
348
+ config={{
349
+ mimeTypes: ["image/jpeg", "image/png"],
350
+ maxFileSizeMb: 10,
351
+ }}
352
+ handlers={{
353
+ onUpload: async (files, onProgressChange) => {
354
+ try {
355
+ for (const file of files) {
356
+ // Update progress as the upload proceeds
357
+ onProgressChange(file.id, 30);
358
+
359
+ // ... upload logic ...
360
+
361
+ // Upload complete
362
+ onProgressChange(file.id, 100);
363
+ }
364
+ return files.map((file) => ({
365
+ fileId: file.id,
366
+ success: true,
367
+ }));
368
+ } catch (error) {
369
+ // Handle error case
370
+ onProgressChange(file.id, 0, {
371
+ text: "Upload failed",
372
+ code: "UPLOAD_ERROR",
373
+ });
374
+ return [
375
+ {
376
+ fileId: file.id,
377
+ success: false,
378
+ error: { text: "Upload failed", code: "UPLOAD_ERROR" },
379
+ },
380
+ ];
381
+ }
382
+ },
383
+ }}
384
+ >
385
+ <YourConsumingComponent />
386
+ </UploadedFilesProvider>
460
387
  );
461
388
  }
462
389
  ```
463
390
 
464
- You can see a demo of this in action [here](https://675c9582166050575d7b72e2-bzirycxazq.chromatic.com/?path=/story/examples-upload-control-with-pdf-pre-processing--default).
391
+ ## Hook Return Values
465
392
 
466
- ## Creating Custom Upload Sources and Destinations
393
+ The `useUploadFilesProvider` hook returns an object with the following properties:
467
394
 
468
- The `useUploadFilesProvider` hook allows you to create your own file sources (like drop areas) and file destinations (like file lists) with ease. The provider handles all the complex validation and state management for you.
395
+ ### File Management
469
396
 
470
- The provider abstracts away:
397
+ - `files`: Array of currently uploaded files
398
+ - `addFiles`: Function to add new files to the upload queue
399
+ - `removeFile`: Function to remove a specific file from the queue
400
+ - `updateFile`: Function to update properties of a specific file
401
+ - `uploadAllFiles`: Function to start uploading all files in the queue
402
+ - `deleteFile`: Function to delete a specific uploaded file
403
+ - `deleteAllFiles`: Function to delete all uploaded files
404
+ - `getFile`: Function to retrieve a specific file by its ID
405
+ - `setFiles`: Function to directly set the files array
406
+ - `resetControl`: Function to reset the upload control to its initial state
407
+ - `moveFile`: Function to change the order of a file. Takes a fileId and direction (-1 for up, 1 for down)
471
408
 
472
- - File validation (size, type, count)
473
- - Progress tracking
474
- - File state management
475
- - Error handling
476
- - Upload coordination
409
+ ### Status Management
477
410
 
478
- > 🔍 **Coming Soon**: Detailed documentation on creating custom upload components, handling file preprocessing, and implementing advanced validation logic.
411
+ - `smStatus`: Current status of the state machine
412
+ - `smStatusIs`: Function to check if the current status matches a specific status
413
+ - `smStatusIsnt`: Function to check if the current status does not match a specific status
479
414
 
480
- ## Customization
415
+ ### Validation
481
416
 
482
- React Upload Control is highly customizable. You can tailor it to meet your specific needs by adjusting its configuration and using its extensive API. <i> Detailed documentation coming soon. </i>
417
+ - `getValidationInfo`: Function to get validation information for files
418
+ - `disableSorting`: Property to disable file sorting functionality
483
419
 
484
420
  ## Contributing
485
421
 
486
422
  We welcome contributions from the community. Feel free to open issues or submit pull requests on our [GitHub repository](https://github.com/osmandvc/react-upload-control).
487
423
 
488
- Please note that while React Upload Control is in an early state and has been battle-tested, bugs may still appear. We would appreciate it if you report any issues you encounter so they can be fixed as soon as possible. Contributions to improve the library are **very welcome**.
489
-
490
- Because the library is in its early stages, **we are open to suggestions and feedback. If you have any ideas for new features or enhancements, please don't hesitate to share them with us.**
491
-
492
424
  ## License
493
425
 
494
- This project is licensed under the MIT License.
495
-
496
- ---
497
-
498
- MIT © Osman Deveci
426
+ MIT © [osmandvc](https://github.com/osmandvc)
package/dist/index.d.ts CHANGED
@@ -1,7 +1,2 @@
1
- import "./styles/tailwind.css";
2
- import "react-medium-image-zoom/dist/styles.css";
3
- export { FileUploadContainer } from "./FileUploadContainer";
4
- export { FileUploadControl } from "./FileUploadControl";
5
- export { UploadedFilesProvider } from "./providers";
6
- export { isFileDropError } from "./utils";
1
+ export { UploadedFilesProvider, useUploadFilesProvider } from "./providers";
7
2
  export * from "./types";