sirv-uploader-lib
Version:
Reusable React component to upload files to Sirv.com
656 lines (639 loc) • 22.5 kB
JavaScript
"use client";
// src/components/file-upload-area.tsx
import { useCallback } from "react";
import { useDropzone } from "react-dropzone";
// src/components/ui/card.tsx
import * as React from "react";
// src/lib/utils.ts
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
function cn(...inputs) {
return twMerge(clsx(inputs));
}
function formatFileSize(bytes) {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
// src/components/ui/card.tsx
import { jsx } from "react/jsx-runtime";
var Card = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
"div",
{
ref,
className: cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
),
...props
}
));
Card.displayName = "Card";
var CardHeader = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
"div",
{
ref,
className: cn("flex flex-col space-y-1.5 p-6", className),
...props
}
));
CardHeader.displayName = "CardHeader";
var CardTitle = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
"h3",
{
ref,
className: cn(
"text-2xl font-semibold leading-none tracking-tight",
className
),
...props
}
));
CardTitle.displayName = "CardTitle";
var CardDescription = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
"p",
{
ref,
className: cn("text-sm text-muted-foreground", className),
...props
}
));
CardDescription.displayName = "CardDescription";
var CardContent = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, className: cn("p-6 pt-0", className), ...props }));
CardContent.displayName = "CardContent";
var CardFooter = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
"div",
{
ref,
className: cn("flex items-center p-6 pt-0", className),
...props
}
));
CardFooter.displayName = "CardFooter";
// src/components/file-upload-area.tsx
import { Upload } from "lucide-react";
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
function FileUploadArea({ onFilesAdded }) {
const onDrop = useCallback(
(acceptedFiles) => {
onFilesAdded(acceptedFiles);
},
[onFilesAdded]
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: {
"image/*": [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"],
"application/pdf": [".pdf"],
"text/*": [".txt", ".md", ".csv"],
"application/msword": [".doc"],
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": [".docx"],
"application/vnd.ms-excel": [".xls"],
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [
".xlsx"
]
}
});
return /* @__PURE__ */ jsx2(Card, { className: "mb-6", children: /* @__PURE__ */ jsx2(CardContent, { className: "p-6", children: /* @__PURE__ */ jsxs(
"div",
{
...getRootProps(),
className: `border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${isDragActive ? "border-blue-500 bg-blue-50" : "border-gray-300 hover:border-gray-400"}`,
children: [
/* @__PURE__ */ jsx2("input", { ...getInputProps() }),
/* @__PURE__ */ jsx2(Upload, { className: "mx-auto h-12 w-12 text-gray-400 mb-4" }),
isDragActive ? /* @__PURE__ */ jsx2("p", { className: "text-blue-600 font-medium", children: "Drop the files here..." }) : /* @__PURE__ */ jsxs("div", { children: [
/* @__PURE__ */ jsx2("p", { className: "text-gray-600 font-medium mb-2", children: "Drag and drop files here, or click to browse" }),
/* @__PURE__ */ jsx2("p", { className: "text-sm text-gray-500", children: "Supports images, PDFs, documents, spreadsheets, and text files" })
] })
]
}
) }) });
}
// src/components/ui/button.tsx
import * as React4 from "react";
// node_modules/@radix-ui/react-slot/dist/index.mjs
import * as React3 from "react";
// node_modules/@radix-ui/react-compose-refs/dist/index.mjs
import * as React2 from "react";
function setRef(ref, value) {
if (typeof ref === "function") {
return ref(value);
} else if (ref !== null && ref !== void 0) {
ref.current = value;
}
}
function composeRefs(...refs) {
return (node) => {
let hasCleanup = false;
const cleanups = refs.map((ref) => {
const cleanup = setRef(ref, node);
if (!hasCleanup && typeof cleanup == "function") {
hasCleanup = true;
}
return cleanup;
});
if (hasCleanup) {
return () => {
for (let i = 0; i < cleanups.length; i++) {
const cleanup = cleanups[i];
if (typeof cleanup == "function") {
cleanup();
} else {
setRef(refs[i], null);
}
}
};
}
};
}
// node_modules/@radix-ui/react-slot/dist/index.mjs
import { Fragment as Fragment2, jsx as jsx3 } from "react/jsx-runtime";
// @__NO_SIDE_EFFECTS__
function createSlot(ownerName) {
const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
const Slot2 = React3.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
const childrenArray = React3.Children.toArray(children);
const slottable = childrenArray.find(isSlottable);
if (slottable) {
const newElement = slottable.props.children;
const newChildren = childrenArray.map((child) => {
if (child === slottable) {
if (React3.Children.count(newElement) > 1) return React3.Children.only(null);
return React3.isValidElement(newElement) ? newElement.props.children : null;
} else {
return child;
}
});
return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children: React3.isValidElement(newElement) ? React3.cloneElement(newElement, void 0, newChildren) : null });
}
return /* @__PURE__ */ jsx3(SlotClone, { ...slotProps, ref: forwardedRef, children });
});
Slot2.displayName = `${ownerName}.Slot`;
return Slot2;
}
var Slot = /* @__PURE__ */ createSlot("Slot");
// @__NO_SIDE_EFFECTS__
function createSlotClone(ownerName) {
const SlotClone = React3.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
if (React3.isValidElement(children)) {
const childrenRef = getElementRef(children);
const props2 = mergeProps(slotProps, children.props);
if (children.type !== React3.Fragment) {
props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
}
return React3.cloneElement(children, props2);
}
return React3.Children.count(children) > 1 ? React3.Children.only(null) : null;
});
SlotClone.displayName = `${ownerName}.SlotClone`;
return SlotClone;
}
var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
function isSlottable(child) {
return React3.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;
}
function mergeProps(slotProps, childProps) {
const overrideProps = { ...childProps };
for (const propName in childProps) {
const slotPropValue = slotProps[propName];
const childPropValue = childProps[propName];
const isHandler = /^on[A-Z]/.test(propName);
if (isHandler) {
if (slotPropValue && childPropValue) {
overrideProps[propName] = (...args) => {
const result = childPropValue(...args);
slotPropValue(...args);
return result;
};
} else if (slotPropValue) {
overrideProps[propName] = slotPropValue;
}
} else if (propName === "style") {
overrideProps[propName] = { ...slotPropValue, ...childPropValue };
} else if (propName === "className") {
overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
}
}
return { ...slotProps, ...overrideProps };
}
function getElementRef(element) {
let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
if (mayWarn) {
return element.ref;
}
getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
if (mayWarn) {
return element.props.ref;
}
return element.props.ref || element.ref;
}
// src/components/ui/button.tsx
import { cva } from "class-variance-authority";
import { jsx as jsx4 } from "react/jsx-runtime";
var buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline"
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10"
}
},
defaultVariants: {
variant: "default",
size: "default"
}
}
);
var Button = React4.forwardRef(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return /* @__PURE__ */ jsx4(
Comp,
{
className: cn(buttonVariants({ variant, size, className })),
ref,
...props
}
);
}
);
Button.displayName = "Button";
// src/components/ui/progress.tsx
import * as React5 from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { jsx as jsx5 } from "react/jsx-runtime";
var Progress = React5.forwardRef(({ className, value, ...props }, ref) => /* @__PURE__ */ jsx5(
ProgressPrimitive.Root,
{
ref,
className: cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className
),
...props,
children: /* @__PURE__ */ jsx5(
ProgressPrimitive.Indicator,
{
className: "h-full w-full flex-1 bg-primary transition-all",
style: { transform: `translateX(-${100 - (value || 0)}%)` }
}
)
}
));
Progress.displayName = ProgressPrimitive.Root.displayName;
// src/components/ui/alert.tsx
import * as React6 from "react";
import { cva as cva2 } from "class-variance-authority";
import { jsx as jsx6 } from "react/jsx-runtime";
var alertVariants = cva2(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"
}
},
defaultVariants: {
variant: "default"
}
}
);
var Alert = React6.forwardRef(({ className, variant, ...props }, ref) => /* @__PURE__ */ jsx6(
"div",
{
ref,
role: "alert",
className: cn(alertVariants({ variant }), className),
...props
}
));
Alert.displayName = "Alert";
var AlertTitle = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx6(
"h5",
{
ref,
className: cn("mb-1 font-medium leading-none tracking-tight", className),
...props
}
));
AlertTitle.displayName = "AlertTitle";
var AlertDescription = React6.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx6(
"div",
{
ref,
className: cn("text-sm [&_p]:leading-relaxed", className),
...props
}
));
AlertDescription.displayName = "AlertDescription";
// src/components/file-list.tsx
import { Upload as Upload2, File, CheckCircle, XCircle, Loader2 } from "lucide-react";
import { jsx as jsx7, jsxs as jsxs2 } from "react/jsx-runtime";
function FileList({
files,
onUploadFile,
onUploadAll,
onRemoveFile,
onClearAll
}) {
const getStatusIcon = (status) => {
switch (status) {
case "uploading":
return /* @__PURE__ */ jsx7(Loader2, { className: "h-4 w-4 animate-spin text-blue-500" });
case "deleting":
return /* @__PURE__ */ jsx7(Loader2, { className: "h-4 w-4 animate-spin text-red-500" });
case "success":
return /* @__PURE__ */ jsx7(CheckCircle, { className: "h-4 w-4 text-green-500" });
case "error":
return /* @__PURE__ */ jsx7(XCircle, { className: "h-4 w-4 text-red-500" });
default:
return /* @__PURE__ */ jsx7(File, { className: "h-4 w-4 text-gray-500" });
}
};
const pendingFiles = files.filter((f) => f.status === "pending");
return /* @__PURE__ */ jsxs2(Card, { className: "mb-6", children: [
/* @__PURE__ */ jsxs2(CardHeader, { className: "flex flex-row items-center justify-between", children: [
/* @__PURE__ */ jsxs2("div", { children: [
/* @__PURE__ */ jsxs2(CardTitle, { children: [
"Files to Upload (",
files.length,
")"
] }),
/* @__PURE__ */ jsx7(CardDescription, { children: "Review and upload your selected files" })
] }),
/* @__PURE__ */ jsxs2("div", { className: "flex gap-2", children: [
/* @__PURE__ */ jsxs2(
Button,
{
onClick: onUploadAll,
disabled: pendingFiles.length === 0,
className: "flex items-center gap-2",
children: [
/* @__PURE__ */ jsx7(Upload2, { className: "h-4 w-4" }),
"Upload All (",
pendingFiles.length,
")"
]
}
),
/* @__PURE__ */ jsx7(Button, { variant: "outline", onClick: onClearAll, children: "Clear All" })
] })
] }),
/* @__PURE__ */ jsx7(CardContent, { children: /* @__PURE__ */ jsx7("div", { className: "space-y-3", children: files.map((uploadFile) => /* @__PURE__ */ jsxs2(
"div",
{
className: "flex items-center gap-3 p-3 border rounded-lg",
children: [
getStatusIcon(uploadFile.status),
/* @__PURE__ */ jsxs2("div", { className: "flex-1 min-w-0", children: [
/* @__PURE__ */ jsx7("p", { className: "text-sm font-medium text-gray-900 truncate", children: uploadFile.file.name }),
/* @__PURE__ */ jsxs2("p", { className: "text-xs text-gray-500", children: [
formatFileSize(uploadFile.file.size),
" \u2022",
" ",
uploadFile.file.type || "Unknown type"
] }),
uploadFile.status === "uploading" && /* @__PURE__ */ jsx7(Progress, { value: uploadFile.progress, className: "mt-2 h-2" }),
uploadFile.status === "error" && uploadFile.error && /* @__PURE__ */ jsxs2(Alert, { className: "mt-2", children: [
/* @__PURE__ */ jsx7(XCircle, { className: "h-4 w-4" }),
/* @__PURE__ */ jsx7(AlertDescription, { className: "text-xs", children: uploadFile.error })
] })
] }),
/* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
uploadFile.status === "pending" && /* @__PURE__ */ jsx7(Button, { size: "sm", onClick: () => onUploadFile(uploadFile), children: "Upload" }),
/* @__PURE__ */ jsx7(
Button,
{
size: "sm",
variant: "outline",
disabled: uploadFile.status === "deleting" || uploadFile.status === "uploading",
onClick: () => onRemoveFile(uploadFile.id),
children: uploadFile.status === "deleting" ? "Removing..." : "Remove"
}
)
] })
]
},
uploadFile.id
)) }) })
] });
}
// src/hooks/use-upload-file.ts
import { useState, useCallback as useCallback3 } from "react";
// src/lib/sirv-upload.ts
async function uploadToSirvWithProgress(file, uploadPath, onProgress, clientId, clientSecret) {
const authRes = await fetch("https://api.sirv.com/v2/token", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ clientId, clientSecret })
});
if (!authRes.ok) {
throw new Error(
`Token request failed (${authRes.status}): ${await authRes.text()}`
);
}
const { token } = await authRes.json();
if (!token) throw new Error("Sirv did not return a token.");
const safePath = uploadPath.endsWith("/") ? uploadPath : `${uploadPath}/`;
const url = `https://api.sirv.com/v2/files/upload?filename=${encodeURIComponent(
`${safePath}${file.name}`
)}`;
const xhr = new XMLHttpRequest();
const promise = new Promise((resolve, reject) => {
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && e.total > 0)
onProgress(Math.round(e.loaded / e.total * 100));
};
xhr.onload = () => xhr.status >= 200 && xhr.status < 300 ? (onProgress(100), resolve()) : reject(
new Error(`Upload failed (${xhr.status}): ${xhr.responseText}`)
);
xhr.onerror = () => reject(new Error("Network error during upload"));
});
xhr.open("POST", url);
xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(file);
return promise;
}
async function deleteFromSirv(uploadPath, fileName, clientId, clientSecret) {
const authRes = await fetch("https://api.sirv.com/v2/token", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ clientId, clientSecret })
});
if (!authRes.ok) {
throw new Error(
`Token request failed (${authRes.status}): ${await authRes.text()}`
);
}
const { token } = await authRes.json();
if (!token) throw new Error("Sirv did not return a token.");
const safePath = uploadPath.endsWith("/") ? uploadPath : `${uploadPath}/`;
const encoded = encodeURIComponent(`${safePath}${fileName}`);
const delRes = await fetch(
`https://api.sirv.com/v2/files/delete?filename=${encoded}`,
{
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${token}`
}
}
);
if (!delRes.ok) {
const text = await delRes.text();
throw new Error(
`Delete failed (${delRes.status}): ${text || "Unknown error"}`
);
}
}
// src/hooks/use-upload-file.ts
function useFileUpload({
uploadPath,
clientId,
clientSecret
}) {
const [files, setFiles] = useState([]);
const addFiles = useCallback3((newFiles) => {
const uploadFiles = newFiles.map((file) => ({
file,
id: Math.random().toString(36).substr(2, 9),
status: "pending",
progress: 0
}));
setFiles((prev) => [...prev, ...uploadFiles]);
}, []);
const uploadFile = useCallback3(
async (uploadFile2) => {
setFiles(
(prev) => prev.map(
(f) => f.id === uploadFile2.id ? { ...f, status: "uploading", progress: 0 } : f
)
);
try {
await uploadToSirvWithProgress(
uploadFile2.file,
uploadPath,
(progress) => {
setFiles(
(prev) => prev.map((f) => f.id === uploadFile2.id ? { ...f, progress } : f)
);
},
clientId,
clientSecret
);
setFiles(
(prev) => prev.map(
(f) => f.id === uploadFile2.id ? { ...f, status: "success", progress: 100 } : f
)
);
} catch (error) {
setFiles(
(prev) => prev.map(
(f) => f.id === uploadFile2.id ? {
...f,
status: "error",
error: error instanceof Error ? error.message : "Upload failed"
} : f
)
);
}
},
[uploadPath, clientId, clientSecret]
);
const uploadAllFiles = useCallback3(() => {
files.filter((f) => f.status === "pending").forEach(uploadFile);
}, [files, uploadFile]);
const removeFile = useCallback3(
async (id) => {
const target = files.find((f) => f.id === id);
if (!target) return;
if (target.status !== "success") {
setFiles((prev) => prev.filter((f) => f.id !== id));
return;
}
setFiles(
(prev) => prev.map((f) => f.id === id ? { ...f, status: "deleting" } : f)
);
try {
await deleteFromSirv(
uploadPath,
target.file.name,
clientId,
clientSecret
);
setFiles((prev) => prev.filter((f) => f.id !== id));
} catch (e) {
const msg = e instanceof Error ? e.message : "Delete failed";
setFiles(
(prev) => prev.map(
(f) => f.id === id ? { ...f, status: "error", error: msg } : f
)
);
}
},
[files, uploadPath, clientId, clientSecret]
);
const clearAllFiles = useCallback3(() => {
setFiles([]);
}, []);
return {
files,
addFiles,
uploadFile,
uploadAllFiles,
removeFile,
clearAllFiles
};
}
// src/components/sirv-uploader.tsx
import { jsx as jsx8, jsxs as jsxs3 } from "react/jsx-runtime";
function SirvUploader({
uploadPath,
clientId,
clientSecret
}) {
const {
files,
addFiles,
uploadFile,
uploadAllFiles,
removeFile,
clearAllFiles
} = useFileUpload({ uploadPath, clientId, clientSecret });
return /* @__PURE__ */ jsx8("div", { className: "min-h-screen bg-gray-50 py-8", children: /* @__PURE__ */ jsxs3("div", { className: "container mx-auto px-4 max-w-4xl", children: [
/* @__PURE__ */ jsx8(FileUploadArea, { onFilesAdded: addFiles }),
files.length > 0 && /* @__PURE__ */ jsx8(
FileList,
{
files,
onUploadFile: uploadFile,
onUploadAll: uploadAllFiles,
onRemoveFile: removeFile,
onClearAll: clearAllFiles
}
)
] }) });
}
export {
SirvUploader
};
//# sourceMappingURL=index.mjs.map