gbs-add-block 0.0.8 → 0.0.10

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/index.js CHANGED
@@ -17,6 +17,7 @@ const COMPONENTS = [
17
17
  "Modal",
18
18
  "Spinner",
19
19
  "Toast",
20
+ "Uploader"
20
21
  ];
21
22
  const SOURCE_PATH = path.join(__dirname, "source", "components");
22
23
  const DEST_PATH = path.join(process.cwd(), "src", "component-lib");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gbs-add-block",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "React Component Library",
5
5
  "files": [
6
6
  "index.js",
@@ -17,13 +17,16 @@ export const Input = ({
17
17
  OTPLength = 4,
18
18
  OTPClass = "w-8 h-10 m-1 border border-gray-600 rounded-lg text-center",
19
19
  onOTPValueChange,
20
+ error = undefined,
20
21
  ...props
21
22
  }: InputProps) => {
22
23
  const [otpValues, setOtpValues] = useState(new Array(OTPLength).fill(""));
23
24
  const [showPassword, setShowPassword] = useState(false);
24
25
  const inputRefs = useRef<any>([]);
25
26
 
26
- const defaultClass = "bg-gray-100 p-2 rounded-lg";
27
+ const defaultClass = `bg-gray-100 p-2 rounded-lg ${
28
+ error ? "border border-red-600" : ""
29
+ }`;
27
30
 
28
31
  // This will update the OTP Field Value
29
32
  const updateOtpValue = (index: number, e: any) => {
@@ -60,7 +63,7 @@ export const Input = ({
60
63
  return (
61
64
  <div>
62
65
  {!OTPField ? (
63
- <div className="text-input-container w-60 relative">
66
+ <div className="text-input-container w-full relative">
64
67
  <input
65
68
  className={twMerge(defaultClass, "w-full focus:outline-blue-400")}
66
69
  {...props}
@@ -80,6 +83,7 @@ export const Input = ({
80
83
  />
81
84
  </button>
82
85
  )}
86
+ <div className="text-xs text-red-500">{error && error}</div>
83
87
  </div>
84
88
  ) : (
85
89
  <div className="otp-container">
@@ -94,7 +98,7 @@ export const Input = ({
94
98
  value={otpValues[index]}
95
99
  onChange={(e) => updateOtpValue(index, e)}
96
100
  onKeyDown={(e) => handleKeydown(index, e)}
97
- ref={(ref) => (inputRefs.current[index] = ref)}
101
+ // ref={(ref) => (inputRefs.current[index] = ref)}
98
102
  className={OTPClass}
99
103
  />
100
104
  ))}
@@ -33,6 +33,7 @@ const Select = forwardRef<any, SelectProps>((props, ref) => {
33
33
  showSearch = true,
34
34
  onSelect,
35
35
  selectedItem: initialSelectedItem,
36
+ error = undefined,
36
37
  } = props;
37
38
 
38
39
  const [showPopover, setShowPopover] = useState(false);
@@ -145,11 +146,14 @@ const Select = forwardRef<any, SelectProps>((props, ref) => {
145
146
  }));
146
147
 
147
148
  return (
148
- <div className="relative" ref={selectRef}>
149
- <div className="w-[200px] relative">
149
+ <div className="relative w-full" ref={selectRef}>
150
+ <div className="w-full relative">
150
151
  <button
151
- className="flex items-center border px-4 py-2 w-[200px] justify-between rounded-lg font-medium text-sm dark:bg-black dark:border-white dark:text-white"
152
+ className={`flex items-center ${
153
+ error ? "border border-red-600" : "border"
154
+ } px-4 py-2 w-full justify-between rounded-lg font-medium text-sm dark:bg-black dark:border-white dark:text-white`}
152
155
  onClick={togglePopover}
156
+ type="button"
153
157
  >
154
158
  {selectedDisplay || placeholder}
155
159
  <Icon
@@ -168,10 +172,11 @@ const Select = forwardRef<any, SelectProps>((props, ref) => {
168
172
  />
169
173
  </button>
170
174
  )}
175
+ <p className="text-xs text-red-500">{error && error}</p>
171
176
  </div>
172
177
 
173
178
  {showPopover && (
174
- <div className="w-[200px] absolute overflow-y-auto border px-2 rounded-lg mt-[1px] scrollbar bg-white z-50 scrollbar h-auto dark:bg-black dark:text-white">
179
+ <div className="w-full absolute overflow-y-auto border px-2 rounded-lg mt-[1px] scrollbar bg-white z-50 scrollbar h-auto dark:bg-black dark:text-white">
175
180
  {showSearch && (
176
181
  <div className="flex p-2 gap-1 items-center sticky top-0 bg-white border-b dark:bg-black">
177
182
  <Icon
@@ -17,10 +17,16 @@ export const FileUploader = ({
17
17
  onChange,
18
18
  startsUpload = false,
19
19
  selectedFiles = [],
20
+ accept,
21
+ fileCount,
22
+ disabled = false,
23
+ inputFileSize, // Max file size in MB
20
24
  }: any) => {
21
25
  const [files, setFiles] = useState<any[]>([]);
22
26
  const [previewUrls, setPreviewUrls] = useState<{ [key: string]: string }>({});
23
27
  const [isDragging, setIsDragging] = useState(false);
28
+ const [fileCountError, setFileCountError] = useState(false);
29
+ const [fileSizeErrors, setFileSizeErrors] = useState<string[]>([]); // Array for file size errors
24
30
  const fileInputRef = useRef<any>(null);
25
31
  const dropZoneRef = useRef<any>(null);
26
32
 
@@ -33,33 +39,54 @@ export const FileUploader = ({
33
39
 
34
40
  // Adds files to file array
35
41
  const handleFileChange = (newFiles: File[]) => {
36
- let updatedFiles: File[];
37
- if (multiple) {
38
- updatedFiles = [...files, ...newFiles];
42
+ let updatedFiles: File[] = multiple
43
+ ? [...files, ...newFiles]
44
+ : [newFiles[0]];
45
+
46
+ // Ensure the total number of files doesn't exceed the fileCount limit
47
+ if (updatedFiles.length > fileCount) {
48
+ setFileCountError(true);
49
+ updatedFiles = updatedFiles.slice(0, fileCount); // Limit the number of files to fileCount
39
50
  } else {
40
- updatedFiles = [newFiles[0]];
41
- }
42
- setFiles(updatedFiles);
43
-
44
- // Clear previous preview URLs if not multiple
45
- if (!multiple) {
46
- setPreviewUrls({});
51
+ setFileCountError(false);
47
52
  }
48
53
 
49
- newFiles.forEach((file) => {
50
- if (showImagePreview && file.type.startsWith("image/")) {
51
- const reader = new FileReader();
52
- reader.onload = () => {
53
- setPreviewUrls((prev) => ({
54
- ...prev,
55
- [file.name]: reader.result as string,
56
- }));
57
- };
58
- reader.readAsDataURL(file);
54
+ // File size validation
55
+ const validFiles: File[] = [];
56
+ const newErrors: string[] = [];
57
+
58
+ updatedFiles.forEach((file) => {
59
+ const fileSizeInMB = file.size / 1024 / 1024; // Convert bytes to MB
60
+ if (inputFileSize && fileSizeInMB > inputFileSize) {
61
+ newErrors.push(
62
+ `File ${file.name} exceeds the size limit of ${inputFileSize} MB`
63
+ );
64
+ } else {
65
+ validFiles.push(file);
59
66
  }
60
67
  });
61
68
 
62
- if (onChange) onChange(updatedFiles);
69
+ // Update state with valid files and set errors for oversized files
70
+ if (validFiles.length > 0) {
71
+ setFiles(validFiles);
72
+ setPreviewUrls({});
73
+ validFiles.forEach((file) => {
74
+ if (showImagePreview && file.type.startsWith("image/")) {
75
+ const reader = new FileReader();
76
+ reader.onload = () => {
77
+ setPreviewUrls((prev) => ({
78
+ ...prev,
79
+ [file.name]: reader.result as string,
80
+ }));
81
+ };
82
+ reader.readAsDataURL(file);
83
+ }
84
+ });
85
+ if (onChange) onChange(validFiles);
86
+ }
87
+
88
+ // Set file size errors
89
+ setFileSizeErrors(newErrors);
63
90
  };
64
91
 
65
92
  // Removes the file from file array
@@ -74,7 +101,7 @@ export const FileUploader = ({
74
101
  if (onChange) onChange(updatedFiles);
75
102
  };
76
103
 
77
- // *** Code to handle Drag and drop functionalities Starts here
104
+ // Drag and drop handling
78
105
  const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
79
106
  e.preventDefault();
80
107
  e.stopPropagation();
@@ -100,7 +127,6 @@ export const FileUploader = ({
100
127
  const droppedFiles = Array.from(e.dataTransfer.files);
101
128
  handleFileChange(multiple ? droppedFiles : [droppedFiles[0]]);
102
129
  };
103
- // Code to handle Drag and drop functionalities Ends here ***
104
130
 
105
131
  return (
106
132
  <div className="w-full max-w-md mx-auto">
@@ -130,6 +156,17 @@ export const FileUploader = ({
130
156
  ? "Supports multiple file uploads"
131
157
  : "Single file upload only"}
132
158
  </p>
159
+
160
+ {/* Display file size errors */}
161
+ {fileSizeErrors.length > 0 && (
162
+ <div className="mt-2 space-y-1">
163
+ {fileSizeErrors.map((error, index) => (
164
+ <span key={index} className="text-xs text-red-500">
165
+ {error}
166
+ </span>
167
+ ))}
168
+ </div>
169
+ )}
133
170
  </div>
134
171
  <input
135
172
  type="file"
@@ -137,8 +174,17 @@ export const FileUploader = ({
137
174
  className="hidden"
138
175
  onChange={(e) => handleFileChange(Array.from(e.target.files || []))}
139
176
  multiple={multiple}
177
+ accept={accept}
178
+ disabled={disabled}
140
179
  />
141
180
 
181
+ {/* Display file count error */}
182
+ {fileCountError && (
183
+ <span className="text-xs text-red-500">
184
+ Maximum file count is set to {fileCount}
185
+ </span>
186
+ )}
187
+
142
188
  {startsUpload && <AestheticProcessingAnimationWithStyles />}
143
189
 
144
190
  {files.length > 0 && (
@@ -0,0 +1,66 @@
1
+ function processFiles(files: File[], chunkSize: number) {
2
+ const finalFiles: { file: Blob; originalFile: File }[] = [];
3
+
4
+ files.forEach((file) => {
5
+ if (file.size > chunkSize) {
6
+ let offset = 0;
7
+ while (offset < file.size) {
8
+ const chunk = file.slice(offset, offset + chunkSize);
9
+ finalFiles.push({ file: chunk, originalFile: file });
10
+ offset += chunkSize;
11
+ }
12
+ } else {
13
+ finalFiles.push({ file, originalFile: file });
14
+ }
15
+ });
16
+
17
+ return finalFiles;
18
+ }
19
+
20
+ // Converts large files to chunks to send over network and sends
21
+ export async function sendFiles(
22
+ files: File[],
23
+ chunkSize: number,
24
+ apiUrl = "http://localhost:8080/upload"
25
+ ) {
26
+ const processedFiles = processFiles(files, chunkSize);
27
+ const totalChunks = processedFiles.length;
28
+
29
+ for (let i = 0; i < processedFiles.length; i++) {
30
+ const { file, originalFile } = processedFiles[i];
31
+ const formData = new FormData();
32
+ formData.append("file", file, originalFile.name);
33
+ formData.append("originalname", originalFile.name);
34
+
35
+ if (file.size > chunkSize) {
36
+ formData.append("chunkIndex", i.toString());
37
+ formData.append("totalChunks", totalChunks.toString());
38
+ } else {
39
+ formData.append("chunkIndex", "0");
40
+ formData.append("totalChunks", "1");
41
+ }
42
+
43
+ try {
44
+ const response = await fetch(apiUrl, {
45
+ method: "POST",
46
+ body: formData,
47
+ });
48
+
49
+ if (!response.ok) {
50
+ throw new Error(`HTTP error! status: ${response.status}`);
51
+ }
52
+
53
+ const data = await response.json();
54
+
55
+ if (data.documentId) {
56
+ console.log(
57
+ `File uploaded successfully. Document ID: ${data.documentId}`
58
+ );
59
+ } else {
60
+ console.log(`Chunk ${i + 1}/${totalChunks} uploaded`);
61
+ }
62
+ } catch (error) {
63
+ console.error("Error uploading file chunk:", error);
64
+ }
65
+ }
66
+ }