@howells/stow-react 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Stow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # @howells/stow-react
2
+
3
+ React components for [Stow](https://stow.sh) file storage.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @howells/stow-react
9
+ # or
10
+ pnpm add @howells/stow-react
11
+ # or
12
+ yarn add @howells/stow-react
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```tsx
18
+ import { UploadDropzone } from "@howells/stow-react";
19
+
20
+ function MyComponent() {
21
+ return (
22
+ <UploadDropzone
23
+ endpoint="/api/upload"
24
+ onUploadComplete={(files) => {
25
+ console.log("Uploaded:", files);
26
+ }}
27
+ onUploadError={(error) => {
28
+ console.error("Error:", error.message);
29
+ }}
30
+ />
31
+ );
32
+ }
33
+ ```
34
+
35
+ ## Components
36
+
37
+ ### `<UploadDropzone>`
38
+
39
+ A drag-and-drop file upload zone with built-in progress tracking.
40
+
41
+ ```tsx
42
+ <UploadDropzone
43
+ // Required
44
+ endpoint="/api/upload"
45
+
46
+ // Callbacks
47
+ onUploadComplete={(files) => console.log(files)}
48
+ onUploadError={(error) => console.error(error)}
49
+ onUploadProgress={(progress) => console.log(progress.percent)}
50
+ onUploadBegin={(files) => console.log("Starting upload...")}
51
+
52
+ // File restrictions
53
+ accept="image/*" // Accepted file types
54
+ maxSize={10 * 1024 * 1024} // Max 10MB
55
+ maxFiles={5} // Max 5 files
56
+ multiple={true} // Allow multiple files
57
+
58
+ // Appearance
59
+ className="my-dropzone"
60
+ disabled={false}
61
+
62
+ // Optional route for organizing files
63
+ route="avatars"
64
+ />
65
+ ```
66
+
67
+ ## Props
68
+
69
+ | Prop | Type | Default | Description |
70
+ |------|------|---------|-------------|
71
+ | `endpoint` | `string` | required | Your server upload endpoint |
72
+ | `route` | `string` | - | Optional route for organizing files |
73
+ | `onUploadComplete` | `(files: UploadedFile[]) => void` | - | Called when all files uploaded |
74
+ | `onUploadError` | `(error: Error) => void` | - | Called on upload error |
75
+ | `onUploadProgress` | `(progress: UploadProgress) => void` | - | Called with progress updates |
76
+ | `onUploadBegin` | `(files: File[]) => void` | - | Called when upload starts |
77
+ | `accept` | `string` | - | Accepted file types (e.g., "image/*") |
78
+ | `maxSize` | `number` | - | Maximum file size in bytes |
79
+ | `maxFiles` | `number` | `10` | Maximum number of files |
80
+ | `multiple` | `boolean` | `true` | Allow multiple file selection |
81
+ | `className` | `string` | - | Custom CSS class |
82
+ | `disabled` | `boolean` | `false` | Disable the dropzone |
83
+
84
+ ## Types
85
+
86
+ ```typescript
87
+ type UploadedFile = {
88
+ key: string;
89
+ url: string | null;
90
+ name: string;
91
+ size: number;
92
+ type: string;
93
+ };
94
+
95
+ type UploadProgress = {
96
+ file: File;
97
+ loaded: number;
98
+ total: number;
99
+ percent: number;
100
+ };
101
+ ```
102
+
103
+ ## Styling
104
+
105
+ The component uses inline styles by default. Override with your own CSS:
106
+
107
+ ```tsx
108
+ <UploadDropzone
109
+ endpoint="/api/upload"
110
+ className="custom-dropzone"
111
+ />
112
+ ```
113
+
114
+ ```css
115
+ .custom-dropzone {
116
+ border: 2px dashed #3b82f6;
117
+ border-radius: 12px;
118
+ padding: 3rem;
119
+ background: #f8fafc;
120
+ }
121
+ ```
122
+
123
+ ## Server Setup
124
+
125
+ This component requires a server endpoint. Use `@howells/stow-next` for easy setup:
126
+
127
+ ```typescript
128
+ // app/api/upload/route.ts
129
+ import { createUploadHandler } from "@howells/stow-next";
130
+ import { StowServer } from "@howells/stow-server";
131
+
132
+ const stow = new StowServer(process.env.STOW_API_KEY!);
133
+
134
+ export const POST = createUploadHandler({
135
+ stow,
136
+ maxSize: 10 * 1024 * 1024,
137
+ allowedTypes: ["image/*"],
138
+ });
139
+ ```
140
+
141
+ ## License
142
+
143
+ MIT
@@ -0,0 +1,70 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+
3
+ interface UploadedFile {
4
+ key: string;
5
+ name: string;
6
+ size: number;
7
+ type: string;
8
+ url: string | null;
9
+ }
10
+ interface UploadProgress {
11
+ file: File;
12
+ loaded: number;
13
+ percent: number;
14
+ total: number;
15
+ }
16
+ interface UploadDropzoneProps {
17
+ /**
18
+ * Accepted file types (e.g., "image/*" or ".pdf,.doc")
19
+ */
20
+ accept?: string;
21
+ /**
22
+ * Custom class name for the dropzone container
23
+ */
24
+ className?: string;
25
+ /**
26
+ * Whether the dropzone is disabled
27
+ */
28
+ disabled?: boolean;
29
+ /**
30
+ * Your server endpoint that handles uploads.
31
+ * This endpoint should use @howells/stow-server internally.
32
+ */
33
+ endpoint: string;
34
+ /**
35
+ * Maximum number of files
36
+ */
37
+ maxFiles?: number;
38
+ /**
39
+ * Maximum file size in bytes
40
+ */
41
+ maxSize?: number;
42
+ /**
43
+ * Whether to allow multiple file selection
44
+ */
45
+ multiple?: boolean;
46
+ /**
47
+ * Callback when upload starts
48
+ */
49
+ onUploadBegin?: (files: File[]) => void;
50
+ /**
51
+ * Callback when all files have been uploaded successfully
52
+ */
53
+ onUploadComplete?: (files: UploadedFile[]) => void;
54
+ /**
55
+ * Callback when an upload error occurs
56
+ */
57
+ onUploadError?: (error: Error) => void;
58
+ /**
59
+ * Callback for upload progress updates
60
+ */
61
+ onUploadProgress?: (progress: UploadProgress) => void;
62
+ /**
63
+ * Optional route identifier for organizing files
64
+ */
65
+ route?: string;
66
+ }
67
+
68
+ declare function UploadDropzone({ endpoint, route, onUploadComplete, onUploadError, onUploadProgress, onUploadBegin, accept, maxSize, maxFiles, multiple, className, disabled, }: UploadDropzoneProps): react_jsx_runtime.JSX.Element;
69
+
70
+ export { UploadDropzone, type UploadDropzoneProps, type UploadProgress, type UploadedFile };
@@ -0,0 +1,70 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+
3
+ interface UploadedFile {
4
+ key: string;
5
+ name: string;
6
+ size: number;
7
+ type: string;
8
+ url: string | null;
9
+ }
10
+ interface UploadProgress {
11
+ file: File;
12
+ loaded: number;
13
+ percent: number;
14
+ total: number;
15
+ }
16
+ interface UploadDropzoneProps {
17
+ /**
18
+ * Accepted file types (e.g., "image/*" or ".pdf,.doc")
19
+ */
20
+ accept?: string;
21
+ /**
22
+ * Custom class name for the dropzone container
23
+ */
24
+ className?: string;
25
+ /**
26
+ * Whether the dropzone is disabled
27
+ */
28
+ disabled?: boolean;
29
+ /**
30
+ * Your server endpoint that handles uploads.
31
+ * This endpoint should use @howells/stow-server internally.
32
+ */
33
+ endpoint: string;
34
+ /**
35
+ * Maximum number of files
36
+ */
37
+ maxFiles?: number;
38
+ /**
39
+ * Maximum file size in bytes
40
+ */
41
+ maxSize?: number;
42
+ /**
43
+ * Whether to allow multiple file selection
44
+ */
45
+ multiple?: boolean;
46
+ /**
47
+ * Callback when upload starts
48
+ */
49
+ onUploadBegin?: (files: File[]) => void;
50
+ /**
51
+ * Callback when all files have been uploaded successfully
52
+ */
53
+ onUploadComplete?: (files: UploadedFile[]) => void;
54
+ /**
55
+ * Callback when an upload error occurs
56
+ */
57
+ onUploadError?: (error: Error) => void;
58
+ /**
59
+ * Callback for upload progress updates
60
+ */
61
+ onUploadProgress?: (progress: UploadProgress) => void;
62
+ /**
63
+ * Optional route identifier for organizing files
64
+ */
65
+ route?: string;
66
+ }
67
+
68
+ declare function UploadDropzone({ endpoint, route, onUploadComplete, onUploadError, onUploadProgress, onUploadBegin, accept, maxSize, maxFiles, multiple, className, disabled, }: UploadDropzoneProps): react_jsx_runtime.JSX.Element;
69
+
70
+ export { UploadDropzone, type UploadDropzoneProps, type UploadProgress, type UploadedFile };
package/dist/index.js ADDED
@@ -0,0 +1,444 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.tsx
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ UploadDropzone: () => UploadDropzone
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ var import_stow_client = require("@howells/stow-client");
28
+ var import_react = require("react");
29
+
30
+ // src/icons.tsx
31
+ var import_jsx_runtime = require("react/jsx-runtime");
32
+ function UploadIcon() {
33
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
34
+ "svg",
35
+ {
36
+ "aria-hidden": "true",
37
+ fill: "none",
38
+ height: "40",
39
+ stroke: "#6b7280",
40
+ strokeLinecap: "round",
41
+ strokeLinejoin: "round",
42
+ strokeWidth: "2",
43
+ viewBox: "0 0 24 24",
44
+ width: "40",
45
+ children: [
46
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }),
47
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("polyline", { points: "17 8 12 3 7 8" }),
48
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "12", y1: "3", y2: "15" })
49
+ ]
50
+ }
51
+ );
52
+ }
53
+ function UploadingIcon() {
54
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
55
+ "svg",
56
+ {
57
+ "aria-hidden": "true",
58
+ fill: "none",
59
+ height: "40",
60
+ stroke: "#3b82f6",
61
+ strokeLinecap: "round",
62
+ strokeLinejoin: "round",
63
+ strokeWidth: "2",
64
+ style: { animation: "spin 1s linear infinite" },
65
+ viewBox: "0 0 24 24",
66
+ width: "40",
67
+ children: [
68
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }),
69
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: "@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }" })
70
+ ]
71
+ }
72
+ );
73
+ }
74
+ function CheckIcon() {
75
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
76
+ "svg",
77
+ {
78
+ "aria-hidden": "true",
79
+ fill: "none",
80
+ height: "40",
81
+ stroke: "#16a34a",
82
+ strokeLinecap: "round",
83
+ strokeLinejoin: "round",
84
+ strokeWidth: "2",
85
+ viewBox: "0 0 24 24",
86
+ width: "40",
87
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("polyline", { points: "20 6 9 17 4 12" })
88
+ }
89
+ );
90
+ }
91
+ function ErrorIcon() {
92
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
93
+ "svg",
94
+ {
95
+ "aria-hidden": "true",
96
+ fill: "none",
97
+ height: "40",
98
+ stroke: "#dc2626",
99
+ strokeLinecap: "round",
100
+ strokeLinejoin: "round",
101
+ strokeWidth: "2",
102
+ viewBox: "0 0 24 24",
103
+ width: "40",
104
+ children: [
105
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
106
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "15", x2: "9", y1: "9", y2: "15" }),
107
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "9", x2: "15", y1: "9", y2: "15" })
108
+ ]
109
+ }
110
+ );
111
+ }
112
+ function ProgressBar({ progress }) {
113
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
114
+ "div",
115
+ {
116
+ style: {
117
+ width: "100%",
118
+ maxWidth: "200px",
119
+ height: "8px",
120
+ backgroundColor: "#e5e7eb",
121
+ borderRadius: "4px",
122
+ marginTop: "1rem",
123
+ overflow: "hidden"
124
+ },
125
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
126
+ "div",
127
+ {
128
+ style: {
129
+ width: `${progress}%`,
130
+ height: "100%",
131
+ backgroundColor: "#3b82f6",
132
+ borderRadius: "4px",
133
+ transition: "width 0.2s ease"
134
+ }
135
+ }
136
+ )
137
+ }
138
+ );
139
+ }
140
+
141
+ // src/index.tsx
142
+ var import_jsx_runtime2 = require("react/jsx-runtime");
143
+ function getBorderColor(state) {
144
+ if (state === "dragging") {
145
+ return "#3b82f6";
146
+ }
147
+ if (state === "error") {
148
+ return "#ef4444";
149
+ }
150
+ if (state === "complete") {
151
+ return "#22c55e";
152
+ }
153
+ return "#d1d5db";
154
+ }
155
+ function getBackgroundColor(state) {
156
+ if (state === "dragging") {
157
+ return "#eff6ff";
158
+ }
159
+ if (state === "error") {
160
+ return "#fef2f2";
161
+ }
162
+ if (state === "complete") {
163
+ return "#f0fdf4";
164
+ }
165
+ return "#f9fafb";
166
+ }
167
+ function UploadDropzone({
168
+ endpoint,
169
+ route,
170
+ onUploadComplete,
171
+ onUploadError,
172
+ onUploadProgress,
173
+ onUploadBegin,
174
+ accept,
175
+ maxSize,
176
+ maxFiles = 10,
177
+ multiple = true,
178
+ className = "",
179
+ disabled = false
180
+ }) {
181
+ const [state, setState] = (0, import_react.useState)("idle");
182
+ const [progress, setProgress] = (0, import_react.useState)(0);
183
+ const [errorMessage, setErrorMessage] = (0, import_react.useState)(null);
184
+ const inputRef = (0, import_react.useRef)(null);
185
+ const uploadFiles = (0, import_react.useCallback)(
186
+ async (files) => {
187
+ if (disabled) {
188
+ return;
189
+ }
190
+ if (files.length > maxFiles) {
191
+ const error = new Error(`Maximum ${maxFiles} files allowed`);
192
+ setErrorMessage(error.message);
193
+ setState("error");
194
+ onUploadError?.(error);
195
+ return;
196
+ }
197
+ if (maxSize) {
198
+ const oversizedFile = files.find((f) => f.size > maxSize);
199
+ if (oversizedFile) {
200
+ const error = new Error(
201
+ `File "${oversizedFile.name}" exceeds maximum size of ${formatBytes(maxSize)}`
202
+ );
203
+ setErrorMessage(error.message);
204
+ setState("error");
205
+ onUploadError?.(error);
206
+ return;
207
+ }
208
+ }
209
+ setState("uploading");
210
+ setProgress(0);
211
+ setErrorMessage(null);
212
+ onUploadBegin?.(files);
213
+ const results = [];
214
+ let totalLoaded = 0;
215
+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);
216
+ try {
217
+ for (const file of files) {
218
+ const result = await uploadSingleFile(
219
+ file,
220
+ endpoint,
221
+ route,
222
+ (loaded) => {
223
+ const fileProgress = totalLoaded + loaded;
224
+ const percent = Math.round(fileProgress / totalSize * 100);
225
+ setProgress(percent);
226
+ onUploadProgress?.({
227
+ file,
228
+ loaded,
229
+ total: file.size,
230
+ percent: Math.round(loaded / file.size * 100)
231
+ });
232
+ }
233
+ );
234
+ totalLoaded += file.size;
235
+ results.push({
236
+ key: result.key,
237
+ url: result.url,
238
+ name: file.name,
239
+ size: file.size,
240
+ type: file.type
241
+ });
242
+ }
243
+ setState("complete");
244
+ onUploadComplete?.(results);
245
+ setTimeout(() => {
246
+ setState("idle");
247
+ setProgress(0);
248
+ }, 2e3);
249
+ } catch (error) {
250
+ const err = error instanceof Error ? error : new Error("Upload failed");
251
+ setErrorMessage(err.message);
252
+ setState("error");
253
+ onUploadError?.(err);
254
+ }
255
+ },
256
+ [
257
+ endpoint,
258
+ route,
259
+ maxFiles,
260
+ maxSize,
261
+ disabled,
262
+ onUploadBegin,
263
+ onUploadComplete,
264
+ onUploadError,
265
+ onUploadProgress
266
+ ]
267
+ );
268
+ const handleDragOver = (0, import_react.useCallback)(
269
+ (e) => {
270
+ e.preventDefault();
271
+ e.stopPropagation();
272
+ if (!disabled) {
273
+ setState("dragging");
274
+ }
275
+ },
276
+ [disabled]
277
+ );
278
+ const handleDragLeave = (0, import_react.useCallback)((e) => {
279
+ e.preventDefault();
280
+ e.stopPropagation();
281
+ setState("idle");
282
+ }, []);
283
+ const handleDrop = (0, import_react.useCallback)(
284
+ (e) => {
285
+ e.preventDefault();
286
+ e.stopPropagation();
287
+ if (disabled) {
288
+ return;
289
+ }
290
+ const droppedFiles = Array.from(e.dataTransfer.files);
291
+ if (droppedFiles.length > 0) {
292
+ uploadFiles(multiple ? droppedFiles : [droppedFiles[0]]);
293
+ } else {
294
+ setState("idle");
295
+ }
296
+ },
297
+ [disabled, multiple, uploadFiles]
298
+ );
299
+ const handleFileChange = (0, import_react.useCallback)(
300
+ (e) => {
301
+ const selectedFiles = e.target.files;
302
+ if (selectedFiles && selectedFiles.length > 0) {
303
+ uploadFiles(Array.from(selectedFiles));
304
+ }
305
+ if (inputRef.current) {
306
+ inputRef.current.value = "";
307
+ }
308
+ },
309
+ [uploadFiles]
310
+ );
311
+ const handleClick = (0, import_react.useCallback)(() => {
312
+ if (!disabled && state !== "uploading") {
313
+ inputRef.current?.click();
314
+ }
315
+ }, [disabled, state]);
316
+ const baseStyles = {
317
+ display: "flex",
318
+ flexDirection: "column",
319
+ alignItems: "center",
320
+ justifyContent: "center",
321
+ padding: "2rem",
322
+ border: "2px dashed",
323
+ borderRadius: "0.5rem",
324
+ cursor: disabled || state === "uploading" ? "not-allowed" : "pointer",
325
+ transition: "all 0.2s ease",
326
+ minHeight: "200px",
327
+ opacity: disabled ? 0.5 : 1,
328
+ borderColor: getBorderColor(state),
329
+ backgroundColor: getBackgroundColor(state)
330
+ };
331
+ return (
332
+ // biome-ignore lint/a11y/useSemanticElements: div is used for dropzone drag-and-drop behavior
333
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
334
+ "div",
335
+ {
336
+ className,
337
+ onClick: handleClick,
338
+ onDragLeave: handleDragLeave,
339
+ onDragOver: handleDragOver,
340
+ onDrop: handleDrop,
341
+ onKeyDown: (e) => {
342
+ if (e.key === "Enter" || e.key === " ") {
343
+ handleClick();
344
+ }
345
+ },
346
+ role: "button",
347
+ style: baseStyles,
348
+ tabIndex: 0,
349
+ children: [
350
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
351
+ "input",
352
+ {
353
+ accept,
354
+ disabled,
355
+ multiple,
356
+ onChange: handleFileChange,
357
+ ref: inputRef,
358
+ style: { display: "none" },
359
+ type: "file"
360
+ }
361
+ ),
362
+ state === "uploading" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
363
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(UploadingIcon, {}),
364
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { style: { marginTop: "0.5rem", color: "#6b7280" }, children: [
365
+ "Uploading... ",
366
+ progress,
367
+ "%"
368
+ ] }),
369
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ProgressBar, { progress })
370
+ ] }),
371
+ state === "complete" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
372
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(CheckIcon, {}),
373
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: { marginTop: "0.5rem", color: "#16a34a" }, children: "Upload complete!" })
374
+ ] }),
375
+ state === "error" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
376
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorIcon, {}),
377
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: { marginTop: "0.5rem", color: "#dc2626" }, children: errorMessage }),
378
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
379
+ "p",
380
+ {
381
+ style: {
382
+ marginTop: "0.25rem",
383
+ fontSize: "0.875rem",
384
+ color: "#6b7280"
385
+ },
386
+ children: "Click to try again"
387
+ }
388
+ )
389
+ ] }),
390
+ (state === "idle" || state === "dragging") && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
391
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(UploadIcon, {}),
392
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { style: { marginTop: "0.5rem", color: "#374151" }, children: state === "dragging" ? "Drop files here" : "Drag & drop files here" }),
393
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
394
+ "p",
395
+ {
396
+ style: {
397
+ marginTop: "0.25rem",
398
+ fontSize: "0.875rem",
399
+ color: "#6b7280"
400
+ },
401
+ children: "or click to browse"
402
+ }
403
+ ),
404
+ maxSize && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
405
+ "p",
406
+ {
407
+ style: {
408
+ marginTop: "0.5rem",
409
+ fontSize: "0.75rem",
410
+ color: "#9ca3af"
411
+ },
412
+ children: [
413
+ "Max file size: ",
414
+ formatBytes(maxSize)
415
+ ]
416
+ }
417
+ )
418
+ ] })
419
+ ]
420
+ }
421
+ )
422
+ );
423
+ }
424
+ async function uploadSingleFile(file, endpoint, route, onProgress) {
425
+ const client = new import_stow_client.StowClient({ endpoint });
426
+ const result = await client.uploadFile(file, {
427
+ route,
428
+ onProgress: onProgress ? (p) => onProgress(p.loaded) : void 0
429
+ });
430
+ return { key: result.key, url: result.url };
431
+ }
432
+ function formatBytes(bytes) {
433
+ if (bytes === 0) {
434
+ return "0 Bytes";
435
+ }
436
+ const k = 1024;
437
+ const sizes = ["Bytes", "KB", "MB", "GB"];
438
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
439
+ return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
440
+ }
441
+ // Annotate the CommonJS export names for ESM import in node:
442
+ 0 && (module.exports = {
443
+ UploadDropzone
444
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,424 @@
1
+ "use client";
2
+
3
+ // src/index.tsx
4
+ import { StowClient } from "@howells/stow-client";
5
+ import {
6
+ useCallback,
7
+ useRef,
8
+ useState
9
+ } from "react";
10
+
11
+ // src/icons.tsx
12
+ import { jsx, jsxs } from "react/jsx-runtime";
13
+ function UploadIcon() {
14
+ return /* @__PURE__ */ jsxs(
15
+ "svg",
16
+ {
17
+ "aria-hidden": "true",
18
+ fill: "none",
19
+ height: "40",
20
+ stroke: "#6b7280",
21
+ strokeLinecap: "round",
22
+ strokeLinejoin: "round",
23
+ strokeWidth: "2",
24
+ viewBox: "0 0 24 24",
25
+ width: "40",
26
+ children: [
27
+ /* @__PURE__ */ jsx("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }),
28
+ /* @__PURE__ */ jsx("polyline", { points: "17 8 12 3 7 8" }),
29
+ /* @__PURE__ */ jsx("line", { x1: "12", x2: "12", y1: "3", y2: "15" })
30
+ ]
31
+ }
32
+ );
33
+ }
34
+ function UploadingIcon() {
35
+ return /* @__PURE__ */ jsxs(
36
+ "svg",
37
+ {
38
+ "aria-hidden": "true",
39
+ fill: "none",
40
+ height: "40",
41
+ stroke: "#3b82f6",
42
+ strokeLinecap: "round",
43
+ strokeLinejoin: "round",
44
+ strokeWidth: "2",
45
+ style: { animation: "spin 1s linear infinite" },
46
+ viewBox: "0 0 24 24",
47
+ width: "40",
48
+ children: [
49
+ /* @__PURE__ */ jsx("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }),
50
+ /* @__PURE__ */ jsx("style", { children: "@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }" })
51
+ ]
52
+ }
53
+ );
54
+ }
55
+ function CheckIcon() {
56
+ return /* @__PURE__ */ jsx(
57
+ "svg",
58
+ {
59
+ "aria-hidden": "true",
60
+ fill: "none",
61
+ height: "40",
62
+ stroke: "#16a34a",
63
+ strokeLinecap: "round",
64
+ strokeLinejoin: "round",
65
+ strokeWidth: "2",
66
+ viewBox: "0 0 24 24",
67
+ width: "40",
68
+ children: /* @__PURE__ */ jsx("polyline", { points: "20 6 9 17 4 12" })
69
+ }
70
+ );
71
+ }
72
+ function ErrorIcon() {
73
+ return /* @__PURE__ */ jsxs(
74
+ "svg",
75
+ {
76
+ "aria-hidden": "true",
77
+ fill: "none",
78
+ height: "40",
79
+ stroke: "#dc2626",
80
+ strokeLinecap: "round",
81
+ strokeLinejoin: "round",
82
+ strokeWidth: "2",
83
+ viewBox: "0 0 24 24",
84
+ width: "40",
85
+ children: [
86
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
87
+ /* @__PURE__ */ jsx("line", { x1: "15", x2: "9", y1: "9", y2: "15" }),
88
+ /* @__PURE__ */ jsx("line", { x1: "9", x2: "15", y1: "9", y2: "15" })
89
+ ]
90
+ }
91
+ );
92
+ }
93
+ function ProgressBar({ progress }) {
94
+ return /* @__PURE__ */ jsx(
95
+ "div",
96
+ {
97
+ style: {
98
+ width: "100%",
99
+ maxWidth: "200px",
100
+ height: "8px",
101
+ backgroundColor: "#e5e7eb",
102
+ borderRadius: "4px",
103
+ marginTop: "1rem",
104
+ overflow: "hidden"
105
+ },
106
+ children: /* @__PURE__ */ jsx(
107
+ "div",
108
+ {
109
+ style: {
110
+ width: `${progress}%`,
111
+ height: "100%",
112
+ backgroundColor: "#3b82f6",
113
+ borderRadius: "4px",
114
+ transition: "width 0.2s ease"
115
+ }
116
+ }
117
+ )
118
+ }
119
+ );
120
+ }
121
+
122
+ // src/index.tsx
123
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
124
+ function getBorderColor(state) {
125
+ if (state === "dragging") {
126
+ return "#3b82f6";
127
+ }
128
+ if (state === "error") {
129
+ return "#ef4444";
130
+ }
131
+ if (state === "complete") {
132
+ return "#22c55e";
133
+ }
134
+ return "#d1d5db";
135
+ }
136
+ function getBackgroundColor(state) {
137
+ if (state === "dragging") {
138
+ return "#eff6ff";
139
+ }
140
+ if (state === "error") {
141
+ return "#fef2f2";
142
+ }
143
+ if (state === "complete") {
144
+ return "#f0fdf4";
145
+ }
146
+ return "#f9fafb";
147
+ }
148
+ function UploadDropzone({
149
+ endpoint,
150
+ route,
151
+ onUploadComplete,
152
+ onUploadError,
153
+ onUploadProgress,
154
+ onUploadBegin,
155
+ accept,
156
+ maxSize,
157
+ maxFiles = 10,
158
+ multiple = true,
159
+ className = "",
160
+ disabled = false
161
+ }) {
162
+ const [state, setState] = useState("idle");
163
+ const [progress, setProgress] = useState(0);
164
+ const [errorMessage, setErrorMessage] = useState(null);
165
+ const inputRef = useRef(null);
166
+ const uploadFiles = useCallback(
167
+ async (files) => {
168
+ if (disabled) {
169
+ return;
170
+ }
171
+ if (files.length > maxFiles) {
172
+ const error = new Error(`Maximum ${maxFiles} files allowed`);
173
+ setErrorMessage(error.message);
174
+ setState("error");
175
+ onUploadError?.(error);
176
+ return;
177
+ }
178
+ if (maxSize) {
179
+ const oversizedFile = files.find((f) => f.size > maxSize);
180
+ if (oversizedFile) {
181
+ const error = new Error(
182
+ `File "${oversizedFile.name}" exceeds maximum size of ${formatBytes(maxSize)}`
183
+ );
184
+ setErrorMessage(error.message);
185
+ setState("error");
186
+ onUploadError?.(error);
187
+ return;
188
+ }
189
+ }
190
+ setState("uploading");
191
+ setProgress(0);
192
+ setErrorMessage(null);
193
+ onUploadBegin?.(files);
194
+ const results = [];
195
+ let totalLoaded = 0;
196
+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);
197
+ try {
198
+ for (const file of files) {
199
+ const result = await uploadSingleFile(
200
+ file,
201
+ endpoint,
202
+ route,
203
+ (loaded) => {
204
+ const fileProgress = totalLoaded + loaded;
205
+ const percent = Math.round(fileProgress / totalSize * 100);
206
+ setProgress(percent);
207
+ onUploadProgress?.({
208
+ file,
209
+ loaded,
210
+ total: file.size,
211
+ percent: Math.round(loaded / file.size * 100)
212
+ });
213
+ }
214
+ );
215
+ totalLoaded += file.size;
216
+ results.push({
217
+ key: result.key,
218
+ url: result.url,
219
+ name: file.name,
220
+ size: file.size,
221
+ type: file.type
222
+ });
223
+ }
224
+ setState("complete");
225
+ onUploadComplete?.(results);
226
+ setTimeout(() => {
227
+ setState("idle");
228
+ setProgress(0);
229
+ }, 2e3);
230
+ } catch (error) {
231
+ const err = error instanceof Error ? error : new Error("Upload failed");
232
+ setErrorMessage(err.message);
233
+ setState("error");
234
+ onUploadError?.(err);
235
+ }
236
+ },
237
+ [
238
+ endpoint,
239
+ route,
240
+ maxFiles,
241
+ maxSize,
242
+ disabled,
243
+ onUploadBegin,
244
+ onUploadComplete,
245
+ onUploadError,
246
+ onUploadProgress
247
+ ]
248
+ );
249
+ const handleDragOver = useCallback(
250
+ (e) => {
251
+ e.preventDefault();
252
+ e.stopPropagation();
253
+ if (!disabled) {
254
+ setState("dragging");
255
+ }
256
+ },
257
+ [disabled]
258
+ );
259
+ const handleDragLeave = useCallback((e) => {
260
+ e.preventDefault();
261
+ e.stopPropagation();
262
+ setState("idle");
263
+ }, []);
264
+ const handleDrop = useCallback(
265
+ (e) => {
266
+ e.preventDefault();
267
+ e.stopPropagation();
268
+ if (disabled) {
269
+ return;
270
+ }
271
+ const droppedFiles = Array.from(e.dataTransfer.files);
272
+ if (droppedFiles.length > 0) {
273
+ uploadFiles(multiple ? droppedFiles : [droppedFiles[0]]);
274
+ } else {
275
+ setState("idle");
276
+ }
277
+ },
278
+ [disabled, multiple, uploadFiles]
279
+ );
280
+ const handleFileChange = useCallback(
281
+ (e) => {
282
+ const selectedFiles = e.target.files;
283
+ if (selectedFiles && selectedFiles.length > 0) {
284
+ uploadFiles(Array.from(selectedFiles));
285
+ }
286
+ if (inputRef.current) {
287
+ inputRef.current.value = "";
288
+ }
289
+ },
290
+ [uploadFiles]
291
+ );
292
+ const handleClick = useCallback(() => {
293
+ if (!disabled && state !== "uploading") {
294
+ inputRef.current?.click();
295
+ }
296
+ }, [disabled, state]);
297
+ const baseStyles = {
298
+ display: "flex",
299
+ flexDirection: "column",
300
+ alignItems: "center",
301
+ justifyContent: "center",
302
+ padding: "2rem",
303
+ border: "2px dashed",
304
+ borderRadius: "0.5rem",
305
+ cursor: disabled || state === "uploading" ? "not-allowed" : "pointer",
306
+ transition: "all 0.2s ease",
307
+ minHeight: "200px",
308
+ opacity: disabled ? 0.5 : 1,
309
+ borderColor: getBorderColor(state),
310
+ backgroundColor: getBackgroundColor(state)
311
+ };
312
+ return (
313
+ // biome-ignore lint/a11y/useSemanticElements: div is used for dropzone drag-and-drop behavior
314
+ /* @__PURE__ */ jsxs2(
315
+ "div",
316
+ {
317
+ className,
318
+ onClick: handleClick,
319
+ onDragLeave: handleDragLeave,
320
+ onDragOver: handleDragOver,
321
+ onDrop: handleDrop,
322
+ onKeyDown: (e) => {
323
+ if (e.key === "Enter" || e.key === " ") {
324
+ handleClick();
325
+ }
326
+ },
327
+ role: "button",
328
+ style: baseStyles,
329
+ tabIndex: 0,
330
+ children: [
331
+ /* @__PURE__ */ jsx2(
332
+ "input",
333
+ {
334
+ accept,
335
+ disabled,
336
+ multiple,
337
+ onChange: handleFileChange,
338
+ ref: inputRef,
339
+ style: { display: "none" },
340
+ type: "file"
341
+ }
342
+ ),
343
+ state === "uploading" && /* @__PURE__ */ jsxs2(Fragment, { children: [
344
+ /* @__PURE__ */ jsx2(UploadingIcon, {}),
345
+ /* @__PURE__ */ jsxs2("p", { style: { marginTop: "0.5rem", color: "#6b7280" }, children: [
346
+ "Uploading... ",
347
+ progress,
348
+ "%"
349
+ ] }),
350
+ /* @__PURE__ */ jsx2(ProgressBar, { progress })
351
+ ] }),
352
+ state === "complete" && /* @__PURE__ */ jsxs2(Fragment, { children: [
353
+ /* @__PURE__ */ jsx2(CheckIcon, {}),
354
+ /* @__PURE__ */ jsx2("p", { style: { marginTop: "0.5rem", color: "#16a34a" }, children: "Upload complete!" })
355
+ ] }),
356
+ state === "error" && /* @__PURE__ */ jsxs2(Fragment, { children: [
357
+ /* @__PURE__ */ jsx2(ErrorIcon, {}),
358
+ /* @__PURE__ */ jsx2("p", { style: { marginTop: "0.5rem", color: "#dc2626" }, children: errorMessage }),
359
+ /* @__PURE__ */ jsx2(
360
+ "p",
361
+ {
362
+ style: {
363
+ marginTop: "0.25rem",
364
+ fontSize: "0.875rem",
365
+ color: "#6b7280"
366
+ },
367
+ children: "Click to try again"
368
+ }
369
+ )
370
+ ] }),
371
+ (state === "idle" || state === "dragging") && /* @__PURE__ */ jsxs2(Fragment, { children: [
372
+ /* @__PURE__ */ jsx2(UploadIcon, {}),
373
+ /* @__PURE__ */ jsx2("p", { style: { marginTop: "0.5rem", color: "#374151" }, children: state === "dragging" ? "Drop files here" : "Drag & drop files here" }),
374
+ /* @__PURE__ */ jsx2(
375
+ "p",
376
+ {
377
+ style: {
378
+ marginTop: "0.25rem",
379
+ fontSize: "0.875rem",
380
+ color: "#6b7280"
381
+ },
382
+ children: "or click to browse"
383
+ }
384
+ ),
385
+ maxSize && /* @__PURE__ */ jsxs2(
386
+ "p",
387
+ {
388
+ style: {
389
+ marginTop: "0.5rem",
390
+ fontSize: "0.75rem",
391
+ color: "#9ca3af"
392
+ },
393
+ children: [
394
+ "Max file size: ",
395
+ formatBytes(maxSize)
396
+ ]
397
+ }
398
+ )
399
+ ] })
400
+ ]
401
+ }
402
+ )
403
+ );
404
+ }
405
+ async function uploadSingleFile(file, endpoint, route, onProgress) {
406
+ const client = new StowClient({ endpoint });
407
+ const result = await client.uploadFile(file, {
408
+ route,
409
+ onProgress: onProgress ? (p) => onProgress(p.loaded) : void 0
410
+ });
411
+ return { key: result.key, url: result.url };
412
+ }
413
+ function formatBytes(bytes) {
414
+ if (bytes === 0) {
415
+ return "0 Bytes";
416
+ }
417
+ const k = 1024;
418
+ const sizes = ["Bytes", "KB", "MB", "GB"];
419
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
420
+ return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
421
+ }
422
+ export {
423
+ UploadDropzone
424
+ };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@howells/stow-react",
3
+ "version": "0.1.0",
4
+ "description": "React components for Stow file storage",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/howells/stow.git",
9
+ "directory": "packages/stow-react"
10
+ },
11
+ "homepage": "https://stow.sh",
12
+ "keywords": [
13
+ "stow",
14
+ "file-storage",
15
+ "react",
16
+ "upload",
17
+ "components"
18
+ ],
19
+ "main": "./dist/index.js",
20
+ "module": "./dist/index.mjs",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.mjs",
26
+ "require": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "dependencies": {
33
+ "@howells/stow-client": "0.1.0"
34
+ },
35
+ "peerDependencies": {
36
+ "react": "^18.0.0 || ^19.0.0",
37
+ "react-dom": "^18.0.0 || ^19.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@testing-library/jest-dom": "^6.9.1",
41
+ "@testing-library/react": "^16.3.2",
42
+ "@types/react": "19.2.14",
43
+ "@types/react-dom": "19.2.3",
44
+ "jsdom": "^28.1.0",
45
+ "react": "^19.2.4",
46
+ "react-dom": "^19.2.4",
47
+ "tsup": "^8.5.1",
48
+ "typescript": "^5.9.3",
49
+ "vitest": "^4.0.18",
50
+ "@stow/typescript-config": "0.0.0"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup src/index.tsx --format cjs,esm --dts --external react --external @howells/stow-client",
54
+ "dev": "tsup src/index.tsx --format cjs,esm --dts --external react --external @howells/stow-client --watch",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest"
57
+ }
58
+ }