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