uplofile 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/dist/index.cjs ADDED
@@ -0,0 +1,423 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var reactSlot = require('@radix-ui/react-slot');
5
+ var react = require('react');
6
+
7
+ const uid = ()=>Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
8
+
9
+ const UploaderCtx = /*#__PURE__*/ react.createContext(null);
10
+ const Root = ({ multiple = true, initial = [], onChange, upload, removeMode = 'optimistic', onRemove, accept = 'image/*', name = 'images', maxCount, disabled, children })=>{
11
+ const [items, setItems] = react.useState([]);
12
+ const controllers = react.useRef(new Map());
13
+ const removeControllers = react.useRef(new Map());
14
+ const inputRef = react.useRef(null);
15
+ // Hydrate initial items from the server and keep them marked as done
16
+ react.useEffect(()=>{
17
+ const arr = initial ?? [];
18
+ if (!Array.isArray(arr)) return;
19
+ const mapped = arr.map((it)=>{
20
+ return {
21
+ uid: it.uid || it.id,
22
+ id: it.id,
23
+ name: it.name,
24
+ url: it.url,
25
+ status: 'done'
26
+ };
27
+ });
28
+ // Only hydrate if the user hasn't already added/modified items locally
29
+ setItems((prev)=>prev.length === 0 ? mapped : prev);
30
+ }, [
31
+ initial
32
+ ]);
33
+ const hiddenInputValue = react.useMemo(()=>{
34
+ const done = items.filter((i)=>i.status === 'done' && i.url);
35
+ return JSON.stringify(done.map(({ uid: _u, previewUrl: _p, file: _f, status: _s, progress: _pr, error: _e, ...rest })=>rest));
36
+ }, [
37
+ items
38
+ ]);
39
+ const emitChange = react.useCallback((next)=>{
40
+ setItems((prev)=>{
41
+ const nextState = typeof next === 'function' ? next(prev) : next;
42
+ if (onChange) Promise.resolve(onChange(nextState)).catch(()=>{});
43
+ return nextState;
44
+ });
45
+ }, [
46
+ onChange
47
+ ]);
48
+ const startUpload = react.useCallback(async (item)=>{
49
+ if (!item.file) return;
50
+ const controller = new AbortController();
51
+ controllers.current.set(item.uid, controller);
52
+ const setProgress = (pct)=>{
53
+ emitChange((items)=>items.map((it)=>it.uid === item.uid ? {
54
+ ...it,
55
+ progress: Math.max(0, Math.min(100, pct))
56
+ } : it));
57
+ };
58
+ emitChange((items)=>items.map((it)=>it.uid === item.uid ? {
59
+ ...it,
60
+ status: 'uploading',
61
+ error: undefined
62
+ } : it));
63
+ try {
64
+ const result = await upload(item.file, controller.signal, setProgress);
65
+ emitChange((items)=>items.map((it)=>{
66
+ if (it.uid !== item.uid) return it;
67
+ // Revoke the local objectURL preview to avoid memory leaks
68
+ if (it.previewUrl && it.previewUrl.startsWith('blob:')) {
69
+ try {
70
+ URL.revokeObjectURL(it.previewUrl);
71
+ } catch {
72
+ /*fail silently*/ }
73
+ }
74
+ const serverPreview = result.preview || result.url;
75
+ console.log({
76
+ result
77
+ });
78
+ return {
79
+ ...it,
80
+ status: 'done',
81
+ url: result.url,
82
+ id: result.id,
83
+ previewUrl: serverPreview,
84
+ progress: 100
85
+ };
86
+ }));
87
+ } catch (err) {
88
+ const wasAborted = controller.signal.aborted;
89
+ emitChange((items)=>items.map((it)=>it.uid === item.uid ? {
90
+ ...it,
91
+ status: wasAborted ? 'canceled' : 'error',
92
+ error: wasAborted ? undefined : err?.message || 'Upload failed'
93
+ } : it));
94
+ } finally{
95
+ controllers.current.delete(item.uid);
96
+ }
97
+ }, [
98
+ emitChange,
99
+ upload
100
+ ]);
101
+ const selectFiles = react.useCallback((files)=>{
102
+ if (!files || files.length === 0) return;
103
+ const selected = Array.from(files);
104
+ const remaining = maxCount ? Math.max(0, maxCount - items.filter((i)=>i.status !== 'canceled').length) : undefined;
105
+ const toUse = typeof remaining === 'number' ? selected.slice(0, remaining) : selected;
106
+ const newItems = toUse.map((file)=>({
107
+ uid: uid(),
108
+ name: file.name,
109
+ file,
110
+ previewUrl: URL.createObjectURL(file),
111
+ status: 'idle',
112
+ progress: 0
113
+ }));
114
+ emitChange([
115
+ ...items,
116
+ ...newItems
117
+ ]);
118
+ newItems.forEach((it)=>startUpload(it));
119
+ }, [
120
+ emitChange,
121
+ items,
122
+ maxCount,
123
+ startUpload
124
+ ]);
125
+ const onInputChange = react.useCallback((e)=>{
126
+ selectFiles(e.target.files);
127
+ e.currentTarget.value = '';
128
+ }, [
129
+ selectFiles
130
+ ]);
131
+ const onDrop = react.useCallback((e)=>{
132
+ e.preventDefault();
133
+ if (disabled) return;
134
+ selectFiles(e.dataTransfer.files);
135
+ }, [
136
+ disabled,
137
+ selectFiles
138
+ ]);
139
+ const onDragOver = react.useCallback((e)=>e.preventDefault(), []);
140
+ const actions = react.useMemo(()=>({
141
+ cancel: (uidStr)=>{
142
+ const ctrl = controllers.current.get(uidStr);
143
+ ctrl?.abort();
144
+ },
145
+ remove: async (uidStr)=>{
146
+ const item = items.find((i)=>i.uid === uidStr);
147
+ if (!item) return;
148
+ // abort any in-flight upload first
149
+ controllers.current.get(uidStr)?.abort();
150
+ // If no server-side removal needed or not uploaded yet, just remove
151
+ if (!onRemove || item.status !== 'done') {
152
+ emitChange((list)=>list.filter((i)=>i.uid !== uidStr));
153
+ return;
154
+ }
155
+ const ctrl = new AbortController();
156
+ removeControllers.current.set(uidStr, ctrl);
157
+ if (removeMode === 'optimistic') {
158
+ const prev = items;
159
+ // remove from UI immediately
160
+ emitChange((list)=>list.filter((i)=>i.uid !== uidStr));
161
+ try {
162
+ await onRemove(item, ctrl.signal);
163
+ } catch {
164
+ // rollback UI if server delete fails
165
+ emitChange(prev);
166
+ } finally{
167
+ removeControllers.current.delete(uidStr);
168
+ }
169
+ } else {
170
+ // strict: mark as removing, wait for API, then remove
171
+ emitChange((list)=>list.map((it)=>it.uid === uidStr ? {
172
+ ...it,
173
+ status: 'removing'
174
+ } : it));
175
+ try {
176
+ await onRemove(item, ctrl.signal);
177
+ emitChange((list)=>list.filter((i)=>i.uid !== uidStr));
178
+ } catch {
179
+ // revert to done if delete fails
180
+ emitChange((list)=>list.map((it)=>it.uid === uidStr ? {
181
+ ...it,
182
+ status: 'done'
183
+ } : it));
184
+ } finally{
185
+ removeControllers.current.delete(uidStr);
186
+ }
187
+ }
188
+ },
189
+ retry: (uidStr)=>{
190
+ const item = items.find((i)=>i.uid === uidStr);
191
+ if (!item) return;
192
+ if (item.file) {
193
+ void startUpload({
194
+ ...item,
195
+ status: 'idle',
196
+ error: undefined,
197
+ progress: 0
198
+ });
199
+ emitChange((items)=>items.map((it)=>it.uid === uidStr ? {
200
+ ...it,
201
+ status: 'idle',
202
+ error: undefined,
203
+ progress: 0
204
+ } : it));
205
+ }
206
+ }
207
+ }), [
208
+ emitChange,
209
+ items,
210
+ onRemove,
211
+ removeMode,
212
+ startUpload
213
+ ]);
214
+ react.useEffect(()=>()=>{
215
+ items.forEach((i)=>i.previewUrl && URL.revokeObjectURL(i.previewUrl));
216
+ controllers.current.forEach((c)=>c.abort());
217
+ }, []);
218
+ const ctx = {
219
+ items,
220
+ disabled,
221
+ multiple,
222
+ accept,
223
+ actions,
224
+ openFileDialog: ()=>inputRef.current?.click(),
225
+ fileInputProps: {
226
+ ref: inputRef,
227
+ onChange: onInputChange,
228
+ accept,
229
+ multiple,
230
+ disabled
231
+ },
232
+ getDropzoneProps: ()=>({
233
+ role: 'button',
234
+ tabIndex: 0,
235
+ onDrop,
236
+ onDragOver,
237
+ onKeyDown: (e)=>{
238
+ if (disabled) return;
239
+ if (e.key === 'Enter' || e.key === ' ') inputRef.current?.click();
240
+ },
241
+ 'data-disabled': disabled ? '' : undefined,
242
+ 'data-multiple': multiple ? '' : undefined
243
+ }),
244
+ hiddenInputValue,
245
+ name
246
+ };
247
+ return /*#__PURE__*/ jsxRuntime.jsx(UploaderCtx.Provider, {
248
+ value: ctx,
249
+ children: /*#__PURE__*/ jsxRuntime.jsxs("div", {
250
+ "data-part": "root",
251
+ children: [
252
+ /*#__PURE__*/ jsxRuntime.jsx("input", {
253
+ type: "file",
254
+ hidden: true,
255
+ ...ctx.fileInputProps
256
+ }),
257
+ children
258
+ ]
259
+ })
260
+ });
261
+ };
262
+
263
+ const useImageUploader = ()=>{
264
+ const ctx = react.useContext(UploaderCtx);
265
+ if (!ctx) throw new Error("ImageUploader components must be used within <ImageUploader.Root>");
266
+ return ctx;
267
+ };
268
+
269
+ const Dropzone = ({ asChild, ...rest })=>{
270
+ const { getDropzoneProps } = useImageUploader();
271
+ const Comp = asChild ? reactSlot.Slot : "div";
272
+ return /*#__PURE__*/ jsxRuntime.jsx(Comp, {
273
+ "data-part": "dropzone",
274
+ ...getDropzoneProps(),
275
+ ...rest
276
+ });
277
+ };
278
+
279
+ const Preview = ({ render, className })=>{
280
+ const { items, actions } = useImageUploader();
281
+ if (render && typeof render === 'function') {
282
+ return render({
283
+ items,
284
+ actions
285
+ });
286
+ }
287
+ return /*#__PURE__*/ jsxRuntime.jsx("div", {
288
+ "data-part": "preview",
289
+ className: className,
290
+ children: /*#__PURE__*/ jsxRuntime.jsx("div", {
291
+ className: "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4",
292
+ children: items.map((item)=>/*#__PURE__*/ jsxRuntime.jsxs("div", {
293
+ onClick: (e)=>e.stopPropagation(),
294
+ className: "relative overflow-hidden rounded-xl border",
295
+ "data-state": item.status,
296
+ children: [
297
+ item.url || item.previewUrl ? /*#__PURE__*/ jsxRuntime.jsx("img", {
298
+ src: item.url || item.previewUrl,
299
+ alt: item.name,
300
+ className: "h-32 w-full object-cover"
301
+ }) : /*#__PURE__*/ jsxRuntime.jsx("div", {
302
+ className: "flex h-32 w-full items-center justify-center text-xs text-gray-500",
303
+ children: "No preview"
304
+ }),
305
+ item.status === 'uploading' && /*#__PURE__*/ jsxRuntime.jsx("div", {
306
+ className: "absolute bottom-0 left-0 right-0 h-1 bg-gray-200",
307
+ children: /*#__PURE__*/ jsxRuntime.jsx("div", {
308
+ className: "h-full bg-black/80",
309
+ style: {
310
+ width: `${Math.max(0, Math.min(100, item.progress ?? 0))}%`
311
+ }
312
+ })
313
+ }),
314
+ /*#__PURE__*/ jsxRuntime.jsxs("div", {
315
+ className: "absolute inset-x-0 bottom-0 flex justify-end gap-2 bg-gradient-to-t from-black/60 to-transparent p-2",
316
+ children: [
317
+ item.status === 'uploading' && /*#__PURE__*/ jsxRuntime.jsx("button", {
318
+ type: "button",
319
+ className: "rounded-xl bg-black/50 px-2 py-1 text-xs text-white",
320
+ onClick: ()=>actions.cancel(item.uid),
321
+ children: "Cancel"
322
+ }),
323
+ (item.status === 'error' || item.status === 'canceled') && /*#__PURE__*/ jsxRuntime.jsx("button", {
324
+ type: "button",
325
+ className: "rounded-xl bg-black/50 px-2 py-1 text-xs text-white",
326
+ onClick: ()=>actions.retry(item.uid),
327
+ children: "Retry"
328
+ }),
329
+ /*#__PURE__*/ jsxRuntime.jsx("button", {
330
+ type: "button",
331
+ className: "rounded-xl bg-black/50 px-2 py-1 text-xs text-white",
332
+ onClick: ()=>actions.remove(item.uid),
333
+ children: "Remove"
334
+ })
335
+ ]
336
+ })
337
+ ]
338
+ }, item.uid))
339
+ })
340
+ });
341
+ };
342
+ const HiddenInput = ({ name })=>{
343
+ const { hiddenInputValue, name: defaultName } = useImageUploader();
344
+ return /*#__PURE__*/ jsxRuntime.jsx("input", {
345
+ type: "hidden",
346
+ name: name ?? defaultName,
347
+ value: hiddenInputValue
348
+ });
349
+ };
350
+ const Cancel = ({ uid, asChild, ...rest })=>{
351
+ const { actions } = useImageUploader();
352
+ const Comp = asChild ? reactSlot.Slot : 'button';
353
+ return /*#__PURE__*/ jsxRuntime.jsx(Comp, {
354
+ onClick: (e)=>{
355
+ e.stopPropagation();
356
+ actions.cancel(uid);
357
+ },
358
+ ...rest
359
+ });
360
+ };
361
+ const Retry = ({ uid, asChild, ...rest })=>{
362
+ const { actions } = useImageUploader();
363
+ const Comp = asChild ? reactSlot.Slot : 'button';
364
+ return /*#__PURE__*/ jsxRuntime.jsx(Comp, {
365
+ onClick: (e)=>{
366
+ e.stopPropagation();
367
+ actions.retry(uid);
368
+ },
369
+ ...rest
370
+ });
371
+ };
372
+ const Remove = ({ uid, asChild, ...rest })=>{
373
+ const { actions } = useImageUploader();
374
+ const Comp = asChild ? reactSlot.Slot : 'button';
375
+ return /*#__PURE__*/ jsxRuntime.jsx(Comp, {
376
+ onClick: (e)=>{
377
+ e.stopPropagation();
378
+ actions.remove(uid);
379
+ },
380
+ ...rest
381
+ });
382
+ };
383
+
384
+ const Trigger = ({ asChild, children, render, ...rest })=>{
385
+ const { openFileDialog, disabled, items } = useImageUploader();
386
+ const Comp = asChild ? reactSlot.Slot : 'button';
387
+ const uploading = items.filter((i)=>i.status === 'uploading');
388
+ const uploadingCount = uploading.length;
389
+ const doneCount = items.filter((i)=>i.status === 'done').length;
390
+ const errorCount = items.filter((i)=>i.status === 'error').length;
391
+ const totalProgress = uploadingCount ? Math.round(uploading.reduce((acc, it)=>acc + (typeof it.progress === 'number' ? it.progress : 0), 0) / uploadingCount) : undefined;
392
+ const api = {
393
+ items,
394
+ isUploading: uploadingCount > 0,
395
+ uploadingCount,
396
+ doneCount,
397
+ errorCount,
398
+ totalProgress,
399
+ open: openFileDialog
400
+ };
401
+ return /*#__PURE__*/ jsxRuntime.jsx(Comp, {
402
+ type: asChild ? undefined : 'button',
403
+ "aria-disabled": disabled,
404
+ "data-part": "trigger",
405
+ onClick: (e)=>{
406
+ if (disabled) return;
407
+ rest.onClick?.(e);
408
+ openFileDialog();
409
+ },
410
+ ...rest,
411
+ children: render ? render(api) : children
412
+ });
413
+ };
414
+
415
+ exports.Cancel = Cancel;
416
+ exports.Dropzone = Dropzone;
417
+ exports.HiddenInput = HiddenInput;
418
+ exports.Preview = Preview;
419
+ exports.Remove = Remove;
420
+ exports.Retry = Retry;
421
+ exports.Root = Root;
422
+ exports.Trigger = Trigger;
423
+ exports.useImageUploader = useImageUploader;
@@ -0,0 +1,114 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import React, { HTMLAttributes, PropsWithChildren, RefObject, ChangeEvent, DragEvent, ButtonHTMLAttributes } from 'react';
3
+
4
+ declare const Dropzone: ({ asChild, ...rest }: {
5
+ asChild?: boolean;
6
+ } & HTMLAttributes<HTMLElement>) => react_jsx_runtime.JSX.Element;
7
+
8
+ type UploadStatus = "idle" | "uploading" | "done" | "error" | "canceled" | "removing";
9
+ type UploadFileItem = {
10
+ uid: string;
11
+ id?: string;
12
+ name: string;
13
+ url?: string;
14
+ previewUrl?: string;
15
+ file?: File;
16
+ status: UploadStatus;
17
+ progress?: number;
18
+ error?: string;
19
+ data?: any;
20
+ };
21
+ type UploadResult = {
22
+ url: string;
23
+ id?: string;
24
+ };
25
+ type RootProps = PropsWithChildren<{
26
+ multiple?: boolean;
27
+ initial?: Array<Pick<UploadFileItem, "uid" | "id" | "name" | "url">>;
28
+ /**
29
+ * optimistic (default): remove from UI immediately, call onRemove in the background; if it fails, restore the item and show error.
30
+ * strict: call onRemove first; only remove from UI if it succeeds.
31
+ */
32
+ removeMode?: "optimistic" | "strict";
33
+ name?: string;
34
+ maxCount?: number;
35
+ disabled?: boolean;
36
+ accept?: string;
37
+ onChange?: (items: UploadFileItem[]) => Promise<void> | void;
38
+ upload: (file: File, signal: AbortSignal, setProgress?: (pct: number) => void) => Promise<UploadResult>;
39
+ onRemove?: (item: UploadFileItem, signal: AbortSignal) => Promise<void>;
40
+ }>;
41
+ type ItemActions = {
42
+ cancel: (uid: string) => void;
43
+ remove: (uid: string) => void;
44
+ retry: (uid: string) => void;
45
+ };
46
+ type ImageUploaderContextValue = {
47
+ items: UploadFileItem[];
48
+ disabled?: boolean;
49
+ multiple: boolean;
50
+ accept: string;
51
+ actions: ItemActions;
52
+ openFileDialog: () => void;
53
+ fileInputProps: {
54
+ ref: RefObject<HTMLInputElement>;
55
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
56
+ accept: string;
57
+ multiple: boolean;
58
+ disabled?: boolean;
59
+ };
60
+ getDropzoneProps: () => {
61
+ role: string;
62
+ tabIndex: number;
63
+ onDrop: (e: DragEvent) => void;
64
+ onDragOver: (e: DragEvent) => void;
65
+ onKeyDown: (e: KeyboardEvent) => void;
66
+ "data-disabled"?: string;
67
+ "data-multiple"?: string;
68
+ };
69
+ hiddenInputValue: string;
70
+ name: string;
71
+ };
72
+ type TriggerRenderProps = {
73
+ items: UploadFileItem[];
74
+ isUploading: boolean;
75
+ uploadingCount: number;
76
+ doneCount: number;
77
+ errorCount: number;
78
+ totalProgress?: number;
79
+ open: () => void;
80
+ };
81
+ type PreviewRenderProps = {
82
+ items: UploadFileItem[];
83
+ actions: ItemActions;
84
+ };
85
+
86
+ type Props = {
87
+ render?: (api: PreviewRenderProps) => React.ReactNode;
88
+ className?: string;
89
+ };
90
+ declare const Preview: ({ render, className }: Props) => string | number | boolean | react_jsx_runtime.JSX.Element | Iterable<React.ReactNode> | null | undefined;
91
+ declare const HiddenInput: ({ name }: {
92
+ name?: string;
93
+ }) => react_jsx_runtime.JSX.Element;
94
+ type ButtonProps = {
95
+ uid: string;
96
+ asChild?: boolean;
97
+ } & ButtonHTMLAttributes<HTMLButtonElement>;
98
+ declare const Cancel: ({ uid, asChild, ...rest }: ButtonProps) => react_jsx_runtime.JSX.Element;
99
+ declare const Retry: ({ uid, asChild, ...rest }: ButtonProps) => react_jsx_runtime.JSX.Element;
100
+ declare const Remove: ({ uid, asChild, ...rest }: ButtonProps) => react_jsx_runtime.JSX.Element;
101
+
102
+ declare const Trigger: ({ asChild, children, render, ...rest }: PropsWithChildren<{
103
+ asChild?: boolean;
104
+ render?: (api: TriggerRenderProps) => React.ReactNode;
105
+ children?: React.ReactNode | ((api: TriggerRenderProps) => React.ReactNode);
106
+ } & React.HTMLAttributes<HTMLElement>>) => react_jsx_runtime.JSX.Element;
107
+
108
+ declare const Root: ({ multiple, initial, onChange, upload, removeMode, onRemove, accept, name, maxCount, disabled, children, }: RootProps) => react_jsx_runtime.JSX.Element;
109
+
110
+ declare const useImageUploader: () => ImageUploaderContextValue;
111
+
112
+ export { Cancel, Dropzone, HiddenInput, Preview, Remove, Retry, Root, Trigger, useImageUploader };
113
+ export type { ImageUploaderContextValue, ItemActions, RootProps, UploadFileItem, UploadResult };
114
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sources":["../src/components/dropzone.tsx","../src/types.ts","../src/components/preview.tsx","../src/components/trigger.tsx","../src/context.tsx","../src/hook.ts"],"sourcesContent":["import { Slot } from \"@radix-ui/react-slot\";\nimport { HTMLAttributes } from \"react\";\n\nimport { useImageUploader } from \"../hook\";\n\nexport const Dropzone = ({\n asChild,\n ...rest\n}: { asChild?: boolean } & HTMLAttributes<HTMLElement>) => {\n const { getDropzoneProps } = useImageUploader();\n const Comp: any = asChild ? Slot : \"div\";\n return <Comp data-part=\"dropzone\" {...getDropzoneProps()} {...rest} />;\n};\n","import type {\n ChangeEvent,\n DragEvent,\n PropsWithChildren,\n RefObject,\n} from \"react\";\n\nexport type UploadStatus =\n | \"idle\"\n | \"uploading\"\n | \"done\"\n | \"error\"\n | \"canceled\"\n | \"removing\";\n\nexport type UploadFileItem = {\n uid: string;\n id?: string;\n name: string;\n url?: string;\n previewUrl?: string;\n file?: File;\n status: UploadStatus;\n progress?: number;\n error?: string;\n data?: any;\n};\n\nexport type UploadResult = { url: string; id?: string };\n\nexport type RootProps = PropsWithChildren<{\n multiple?: boolean;\n initial?: Array<Pick<UploadFileItem, \"uid\" | \"id\" | \"name\" | \"url\">>;\n /**\n * optimistic (default): remove from UI immediately, call onRemove in the background; if it fails, restore the item and show error.\n * strict: call onRemove first; only remove from UI if it succeeds.\n */\n removeMode?: \"optimistic\" | \"strict\";\n name?: string;\n maxCount?: number;\n disabled?: boolean;\n accept?: string;\n onChange?: (items: UploadFileItem[]) => Promise<void> | void;\n upload: (\n file: File,\n signal: AbortSignal,\n setProgress?: (pct: number) => void,\n ) => Promise<UploadResult>;\n onRemove?: (item: UploadFileItem, signal: AbortSignal) => Promise<void>;\n}>;\n\nexport type ItemActions = {\n cancel: (uid: string) => void;\n remove: (uid: string) => void;\n retry: (uid: string) => void;\n};\n\nexport type ImageUploaderContextValue = {\n items: UploadFileItem[];\n disabled?: boolean;\n multiple: boolean;\n accept: string;\n actions: ItemActions;\n openFileDialog: () => void;\n fileInputProps: {\n ref: RefObject<HTMLInputElement>;\n onChange: (e: ChangeEvent<HTMLInputElement>) => void;\n accept: string;\n multiple: boolean;\n disabled?: boolean;\n };\n getDropzoneProps: () => {\n role: string;\n tabIndex: number;\n onDrop: (e: DragEvent) => void;\n onDragOver: (e: DragEvent) => void;\n onKeyDown: (e: KeyboardEvent) => void;\n \"data-disabled\"?: string;\n \"data-multiple\"?: string;\n };\n hiddenInputValue: string;\n name: string;\n};\n\nexport type TriggerRenderProps = {\n items: UploadFileItem[];\n isUploading: boolean;\n uploadingCount: number;\n doneCount: number;\n errorCount: number;\n totalProgress?: number;\n open: () => void;\n};\n\nexport type PreviewRenderProps = {\n items: UploadFileItem[];\n actions: ItemActions;\n};\n","import { Slot } from '@radix-ui/react-slot'\nimport React, { ButtonHTMLAttributes } from 'react'\n\nimport { useImageUploader } from '../hook'\n\nimport type { PreviewRenderProps } from '../types'\n\ntype Props = {\n render?: (api: PreviewRenderProps) => React.ReactNode\n className?: string\n}\n\nexport const Preview = ({ render, className }: Props) => {\n const { items, actions } = useImageUploader()\n\n if (render && typeof render === 'function') {\n return render({ items, actions })\n }\n\n return (\n <div data-part=\"preview\" className={className}>\n <div className=\"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4\">\n {items.map((item) => (\n <div\n key={item.uid}\n onClick={(e) => e.stopPropagation()}\n className=\"relative overflow-hidden rounded-xl border\"\n data-state={item.status}\n >\n {item.url || item.previewUrl ? (\n <img\n src={item.url || item.previewUrl}\n alt={item.name}\n className=\"h-32 w-full object-cover\"\n />\n ) : (\n <div className=\"flex h-32 w-full items-center justify-center text-xs text-gray-500\">\n No preview\n </div>\n )}\n {item.status === 'uploading' && (\n <div className=\"absolute bottom-0 left-0 right-0 h-1 bg-gray-200\">\n <div\n className=\"h-full bg-black/80\"\n style={{ width: `${Math.max(0, Math.min(100, item.progress ?? 0))}%` }}\n />\n </div>\n )}\n <div className=\"absolute inset-x-0 bottom-0 flex justify-end gap-2 bg-gradient-to-t from-black/60 to-transparent p-2\">\n {item.status === 'uploading' && (\n <button\n type=\"button\"\n className=\"rounded-xl bg-black/50 px-2 py-1 text-xs text-white\"\n onClick={() => actions.cancel(item.uid)}\n >\n Cancel\n </button>\n )}\n {(item.status === 'error' || item.status === 'canceled') && (\n <button\n type=\"button\"\n className=\"rounded-xl bg-black/50 px-2 py-1 text-xs text-white\"\n onClick={() => actions.retry(item.uid)}\n >\n Retry\n </button>\n )}\n <button\n type=\"button\"\n className=\"rounded-xl bg-black/50 px-2 py-1 text-xs text-white\"\n onClick={() => actions.remove(item.uid)}\n >\n Remove\n </button>\n </div>\n </div>\n ))}\n </div>\n </div>\n )\n}\n\nexport const HiddenInput = ({ name }: { name?: string }) => {\n const { hiddenInputValue, name: defaultName } = useImageUploader()\n return <input type=\"hidden\" name={name ?? defaultName} value={hiddenInputValue} />\n}\n\ntype ButtonProps = {\n uid: string\n asChild?: boolean\n} & ButtonHTMLAttributes<HTMLButtonElement>\n\nexport const Cancel = ({ uid, asChild, ...rest }: ButtonProps) => {\n const { actions } = useImageUploader()\n const Comp: any = asChild ? Slot : 'button'\n return (\n <Comp\n onClick={(e: { stopPropagation: () => void }) => {\n e.stopPropagation()\n actions.cancel(uid)\n }}\n {...rest}\n />\n )\n}\n\nexport const Retry = ({ uid, asChild, ...rest }: ButtonProps) => {\n const { actions } = useImageUploader()\n const Comp: any = asChild ? Slot : 'button'\n return (\n <Comp\n onClick={(e: { stopPropagation: () => void }) => {\n e.stopPropagation()\n actions.retry(uid)\n }}\n {...rest}\n />\n )\n}\n\nexport const Remove = ({ uid, asChild, ...rest }: ButtonProps) => {\n const { actions } = useImageUploader()\n const Comp: any = asChild ? Slot : 'button'\n return (\n <Comp\n onClick={(e: { stopPropagation: () => void }) => {\n e.stopPropagation()\n actions.remove(uid)\n }}\n {...rest}\n />\n )\n}\n","import { Slot } from '@radix-ui/react-slot'\nimport React, { PropsWithChildren } from 'react'\n\nimport { useImageUploader } from '../hook'\nimport type { TriggerRenderProps } from '../types'\n\nexport const Trigger = ({\n asChild,\n children,\n render,\n ...rest\n}: PropsWithChildren<\n {\n asChild?: boolean\n render?: (api: TriggerRenderProps) => React.ReactNode\n children?: React.ReactNode | ((api: TriggerRenderProps) => React.ReactNode)\n } & React.HTMLAttributes<HTMLElement>\n>) => {\n const { openFileDialog, disabled, items } = useImageUploader()\n const Comp: any = asChild ? Slot : 'button'\n\n const uploading = items.filter((i) => i.status === 'uploading')\n const uploadingCount = uploading.length\n const doneCount = items.filter((i) => i.status === 'done').length\n const errorCount = items.filter((i) => i.status === 'error').length\n const totalProgress = uploadingCount\n ? Math.round(\n uploading.reduce(\n (acc, it) => acc + (typeof it.progress === 'number' ? it.progress : 0),\n 0\n ) / uploadingCount\n )\n : undefined\n\n const api: TriggerRenderProps = {\n items,\n isUploading: uploadingCount > 0,\n uploadingCount,\n doneCount,\n errorCount,\n totalProgress,\n open: openFileDialog,\n }\n\n return (\n <Comp\n type={asChild ? undefined : 'button'}\n aria-disabled={disabled}\n data-part=\"trigger\"\n onClick={(e: any) => {\n if (disabled) return\n ;(rest as any).onClick?.(e)\n openFileDialog()\n }}\n {...rest}\n >\n {render ? render(api) : children}\n </Comp>\n )\n}\n","import type { DragEvent, RefObject } from 'react'\nimport React, { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\nimport type { ImageUploaderContextValue, ItemActions, RootProps, UploadFileItem } from './types'\nimport { uid } from './utils'\n\nexport const UploaderCtx = createContext<ImageUploaderContextValue | null>(null)\n\nexport const Root = ({\n multiple = true,\n initial = [],\n onChange,\n upload,\n removeMode = 'optimistic',\n onRemove,\n accept = 'image/*',\n name = 'images',\n maxCount,\n disabled,\n children,\n}: RootProps) => {\n const [items, setItems] = useState<UploadFileItem[]>([])\n const controllers = useRef(new Map<string, AbortController>())\n const removeControllers = useRef(new Map<string, AbortController>())\n const inputRef = useRef<HTMLInputElement | null>(null)\n\n // Hydrate initial items from the server and keep them marked as done\n useEffect(() => {\n const arr = initial ?? []\n if (!Array.isArray(arr)) return\n\n const mapped: UploadFileItem[] = arr.map((it) => {\n return {\n uid: it.uid || it.id,\n id: it.id,\n name: it.name,\n url: it.url,\n status: 'done',\n } as UploadFileItem\n })\n\n // Only hydrate if the user hasn't already added/modified items locally\n setItems((prev) => (prev.length === 0 ? mapped : prev))\n }, [initial])\n\n const hiddenInputValue = useMemo(() => {\n const done = items.filter((i) => i.status === 'done' && i.url)\n return JSON.stringify(\n done.map(\n ({ uid: _u, previewUrl: _p, file: _f, status: _s, progress: _pr, error: _e, ...rest }) =>\n rest\n )\n )\n }, [items])\n\n const emitChange = useCallback(\n (next: UploadFileItem[] | ((prev: UploadFileItem[]) => UploadFileItem[])) => {\n setItems((prev) => {\n const nextState = typeof next === 'function' ? (next as any)(prev) : next\n if (onChange) Promise.resolve(onChange(nextState)).catch(() => {})\n return nextState\n })\n },\n [onChange]\n )\n\n const startUpload = useCallback(\n async (item: UploadFileItem) => {\n if (!item.file) return\n const controller = new AbortController()\n controllers.current.set(item.uid, controller)\n\n const setProgress = (pct: number) => {\n emitChange((items) =>\n items.map((it) =>\n it.uid === item.uid ? { ...it, progress: Math.max(0, Math.min(100, pct)) } : it\n )\n )\n }\n\n emitChange((items) =>\n items.map((it) =>\n it.uid === item.uid ? { ...it, status: 'uploading', error: undefined } : it\n )\n )\n\n try {\n const result = await upload(item.file, controller.signal, setProgress)\n emitChange((items) =>\n items.map((it) => {\n if (it.uid !== item.uid) return it\n // Revoke the local objectURL preview to avoid memory leaks\n if (it.previewUrl && it.previewUrl.startsWith('blob:')) {\n try {\n URL.revokeObjectURL(it.previewUrl)\n } catch {\n /*fail silently*/\n }\n }\n const serverPreview = (result as any).preview || result.url\n console.log({ result })\n return {\n ...it,\n status: 'done',\n url: result.url,\n id: result.id,\n previewUrl: serverPreview,\n progress: 100,\n }\n })\n )\n } catch (err: any) {\n const wasAborted = controller.signal.aborted\n emitChange((items) =>\n items.map((it) =>\n it.uid === item.uid\n ? {\n ...it,\n status: wasAborted ? 'canceled' : 'error',\n error: wasAborted ? undefined : err?.message || 'Upload failed',\n }\n : it\n )\n )\n } finally {\n controllers.current.delete(item.uid)\n }\n },\n [emitChange, upload]\n )\n\n const selectFiles = useCallback(\n (files: FileList | null) => {\n if (!files || files.length === 0) return\n const selected = Array.from(files)\n const remaining = maxCount\n ? Math.max(0, maxCount - items.filter((i) => i.status !== 'canceled').length)\n : undefined\n const toUse = typeof remaining === 'number' ? selected.slice(0, remaining) : selected\n\n const newItems: UploadFileItem[] = toUse.map((file) => ({\n uid: uid(),\n name: file.name,\n file,\n previewUrl: URL.createObjectURL(file),\n status: 'idle',\n progress: 0,\n }))\n\n emitChange([...items, ...newItems])\n newItems.forEach((it) => startUpload(it))\n },\n [emitChange, items, maxCount, startUpload]\n )\n\n const onInputChange = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => {\n selectFiles(e.target.files)\n e.currentTarget.value = ''\n },\n [selectFiles]\n )\n\n const onDrop = useCallback(\n (e: DragEvent) => {\n e.preventDefault()\n if (disabled) return\n selectFiles(e.dataTransfer.files)\n },\n [disabled, selectFiles]\n )\n\n const onDragOver = useCallback((e: DragEvent) => e.preventDefault(), [])\n\n const actions: ItemActions = useMemo(\n () => ({\n cancel: (uidStr: string) => {\n const ctrl = controllers.current.get(uidStr)\n ctrl?.abort()\n },\n remove: async (uidStr: string) => {\n const item = items.find((i) => i.uid === uidStr)\n if (!item) return\n\n // abort any in-flight upload first\n controllers.current.get(uidStr)?.abort()\n\n // If no server-side removal needed or not uploaded yet, just remove\n if (!onRemove || item.status !== 'done') {\n emitChange((list) => list.filter((i) => i.uid !== uidStr))\n return\n }\n\n const ctrl = new AbortController()\n removeControllers.current.set(uidStr, ctrl)\n\n if (removeMode === 'optimistic') {\n const prev = items\n // remove from UI immediately\n emitChange((list) => list.filter((i) => i.uid !== uidStr))\n try {\n await onRemove(item, ctrl.signal)\n } catch {\n // rollback UI if server delete fails\n emitChange(prev)\n } finally {\n removeControllers.current.delete(uidStr)\n }\n } else {\n // strict: mark as removing, wait for API, then remove\n emitChange((list) =>\n list.map((it) => (it.uid === uidStr ? { ...it, status: 'removing' as const } : it))\n )\n try {\n await onRemove(item, ctrl.signal)\n emitChange((list) => list.filter((i) => i.uid !== uidStr))\n } catch {\n // revert to done if delete fails\n emitChange((list) =>\n list.map((it) => (it.uid === uidStr ? { ...it, status: 'done' as const } : it))\n )\n } finally {\n removeControllers.current.delete(uidStr)\n }\n }\n },\n retry: (uidStr: string) => {\n const item = items.find((i) => i.uid === uidStr)\n if (!item) return\n if (item.file) {\n void startUpload({ ...item, status: 'idle', error: undefined, progress: 0 })\n emitChange((items) =>\n items.map((it) =>\n it.uid === uidStr ? { ...it, status: 'idle', error: undefined, progress: 0 } : it\n )\n )\n }\n },\n }),\n [emitChange, items, onRemove, removeMode, startUpload]\n )\n\n useEffect(\n () => () => {\n items.forEach((i) => i.previewUrl && URL.revokeObjectURL(i.previewUrl))\n controllers.current.forEach((c) => c.abort())\n },\n []\n )\n\n const ctx: ImageUploaderContextValue = {\n items,\n disabled,\n multiple,\n accept,\n actions,\n openFileDialog: () => inputRef.current?.click(),\n fileInputProps: {\n ref: inputRef as RefObject<HTMLInputElement>,\n onChange: onInputChange,\n accept,\n multiple,\n disabled,\n },\n getDropzoneProps: () => ({\n role: 'button',\n tabIndex: 0,\n onDrop,\n onDragOver,\n onKeyDown: (e) => {\n if (disabled) return\n if (e.key === 'Enter' || e.key === ' ') inputRef.current?.click()\n },\n 'data-disabled': disabled ? '' : undefined,\n 'data-multiple': multiple ? '' : undefined,\n }),\n hiddenInputValue,\n name,\n }\n\n return (\n <UploaderCtx.Provider value={ctx}>\n <div data-part=\"root\">\n <input type=\"file\" hidden {...ctx.fileInputProps} />\n {children}\n </div>\n </UploaderCtx.Provider>\n )\n}\n","import { useContext } from 'react'\n\nimport { UploaderCtx } from './context'\n\nexport const useImageUploader = () => {\n const ctx = useContext(UploaderCtx);\n if (!ctx) throw new Error(\"ImageUploader components must be used within <ImageUploader.Root>\");\n return ctx;\n};"],"names":[],"mappings":";;;AACO;AACP;AACA;;ACFO;AACA;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;;AC3EA;AACA;AACA;AACA;AACO;AACA;AACP;AACA;AACA;AACA;AACA;AACA;AACO;AACA;AACA;;ACdA;AACP;AACA;AACA;AACA;;ACHO;;ACHA;;;"}