zentrixui
Version:
ZentrixUI - A modern, highly customizable and accessible React file upload component library with multiple variants, JSON-based configuration, and excellent developer experience.
6,752 lines • 233 kB
JavaScript
"use strict";
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const utils = require("../utils.cjs");
const schema = require("./schema-BOtZesVP.cjs");
const theme = require("./theme-Bz28eVNI.cjs");
function _interopNamespaceDefault(e) {
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
if (e) {
for (const k in e) {
if (k !== "default") {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
const initialState = {
files: [],
isUploading: false,
progress: 0,
overallProgress: 0,
error: null,
isDragOver: false,
isDropValid: false,
selectedFiles: [],
rejectedFiles: [],
uploadQueue: [],
completedUploads: [],
failedUploads: []
};
function fileUploadReducer(state, action) {
switch (action.type) {
case "SET_FILES":
return { ...state, files: action.payload };
case "ADD_FILES":
return { ...state, files: [...state.files, ...action.payload] };
case "REMOVE_FILE":
return {
...state,
files: state.files.filter((file) => file.id !== action.payload),
completedUploads: state.completedUploads.filter((id) => id !== action.payload),
failedUploads: state.failedUploads.filter((id) => id !== action.payload),
uploadQueue: state.uploadQueue.filter((id) => id !== action.payload)
};
case "UPDATE_FILE":
return {
...state,
files: state.files.map(
(file) => file.id === action.payload.id ? { ...file, ...action.payload.updates } : file
)
};
case "SET_UPLOADING":
return { ...state, isUploading: action.payload };
case "SET_PROGRESS":
return { ...state, progress: action.payload };
case "SET_OVERALL_PROGRESS":
return { ...state, overallProgress: action.payload };
case "SET_ERROR":
return { ...state, error: action.payload };
case "SET_DRAG_OVER":
return { ...state, isDragOver: action.payload };
case "SET_DROP_VALID":
return { ...state, isDropValid: action.payload };
case "SET_SELECTED_FILES":
return { ...state, selectedFiles: action.payload };
case "CLEAR_ALL":
return {
...state,
files: [],
selectedFiles: [],
rejectedFiles: [],
uploadQueue: [],
completedUploads: [],
failedUploads: [],
error: null,
progress: 0,
overallProgress: 0,
isUploading: false
};
case "RESET":
return initialState;
default:
return state;
}
}
const FileUploadContext = React.createContext(null);
const FileUploadProvider = ({
children,
config,
handlers = {}
}) => {
const [state, dispatch] = React.useReducer(fileUploadReducer, initialState);
const [processedErrors, setProcessedErrors] = React.useState([]);
const selectFiles = React.useCallback((files) => {
dispatch({ type: "SET_SELECTED_FILES", payload: files });
const uploadFiles2 = files.map((file) => ({
id: `file_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
file,
status: "pending",
progress: 0,
size: file.size,
type: file.type,
name: file.name,
lastModified: file.lastModified,
retryCount: 0,
maxRetries: 3,
startedAt: /* @__PURE__ */ new Date()
}));
dispatch({ type: "ADD_FILES", payload: uploadFiles2 });
if (handlers.onFileSelect) {
handlers.onFileSelect({
type: "select",
files: uploadFiles2,
timestamp: /* @__PURE__ */ new Date()
});
}
}, [handlers]);
const removeFile = React.useCallback((fileId) => {
const fileToRemove = state.files.find((f) => f.id === fileId);
if (fileToRemove) {
dispatch({ type: "REMOVE_FILE", payload: fileId });
if (handlers.onFileRemove) {
handlers.onFileRemove({
type: "remove",
files: [fileToRemove],
timestamp: /* @__PURE__ */ new Date()
});
}
}
}, [state.files, handlers]);
const retryUpload = React.useCallback((fileId) => {
const file = state.files.find((f) => f.id === fileId);
if (file) {
const updatedFile = {
...file,
status: "pending",
progress: 0,
error: void 0,
retryCount: file.retryCount + 1
};
dispatch({
type: "UPDATE_FILE",
payload: { id: fileId, updates: updatedFile }
});
if (handlers.onUploadRetry) {
handlers.onUploadRetry({
type: "retry",
files: [updatedFile],
timestamp: /* @__PURE__ */ new Date()
});
}
}
}, [state.files, handlers]);
const clearAll = React.useCallback(() => {
dispatch({ type: "CLEAR_ALL" });
}, []);
const uploadFiles = React.useCallback(async () => {
const pendingFiles = state.files.filter((f) => f.status === "pending");
if (pendingFiles.length === 0) return;
dispatch({ type: "SET_UPLOADING", payload: true });
dispatch({ type: "SET_ERROR", payload: null });
if (handlers.onUploadStart) {
handlers.onUploadStart({
type: "upload",
files: pendingFiles,
timestamp: /* @__PURE__ */ new Date()
});
}
for (const file of pendingFiles) {
dispatch({
type: "UPDATE_FILE",
payload: {
id: file.id,
updates: { status: "uploading", startedAt: /* @__PURE__ */ new Date() }
}
});
for (let progress = 0; progress <= 100; progress += 10) {
await new Promise((resolve) => setTimeout(resolve, 100));
dispatch({
type: "UPDATE_FILE",
payload: { id: file.id, updates: { progress } }
});
if (handlers.onUploadProgress) {
handlers.onUploadProgress({
type: "progress",
files: [{ ...file, progress }],
timestamp: /* @__PURE__ */ new Date()
});
}
}
dispatch({
type: "UPDATE_FILE",
payload: {
id: file.id,
updates: {
status: "success",
progress: 100,
completedAt: /* @__PURE__ */ new Date()
}
}
});
if (handlers.onUploadSuccess) {
handlers.onUploadSuccess({
type: "success",
files: [{ ...file, status: "success", progress: 100 }],
timestamp: /* @__PURE__ */ new Date()
});
}
}
dispatch({ type: "SET_UPLOADING", payload: false });
}, [state.files, handlers]);
const updateProgress = React.useCallback((fileId, progress) => {
dispatch({
type: "UPDATE_FILE",
payload: { id: fileId, updates: { progress } }
});
}, []);
const setError = React.useCallback((fileId, error) => {
dispatch({
type: "UPDATE_FILE",
payload: {
id: fileId,
updates: {
status: "error",
error,
completedAt: /* @__PURE__ */ new Date()
}
}
});
const file = state.files.find((f) => f.id === fileId);
if (file && handlers.onUploadError) {
handlers.onUploadError({
type: "error",
files: [{ ...file, status: "error", error }],
timestamp: /* @__PURE__ */ new Date()
});
}
}, [state.files, handlers]);
const setSuccess = React.useCallback((fileId) => {
dispatch({
type: "UPDATE_FILE",
payload: {
id: fileId,
updates: {
status: "success",
progress: 100,
completedAt: /* @__PURE__ */ new Date()
}
}
});
}, []);
const handleError = React.useCallback((error, context = {}) => {
try {
const processedError = utils.processError(error, {
fileName: context.fileName,
operation: context.operation,
timestamp: /* @__PURE__ */ new Date()
}, config);
utils.logError(processedError, { fileId: context.fileId });
setProcessedErrors((prev) => [...prev, processedError]);
if (context.fileId) {
setError(context.fileId, processedError.userMessage);
} else {
dispatch({ type: "SET_ERROR", payload: processedError.userMessage });
}
if (handlers.onUploadError) {
const file = context.fileId ? state.files.find((f) => f.id === context.fileId) : void 0;
handlers.onUploadError({
type: "error",
files: file ? [{ ...file, status: "error", error: processedError.userMessage }] : [],
timestamp: /* @__PURE__ */ new Date()
});
}
return processedError;
} catch (processingError) {
console.error("Error processing error:", processingError);
const fallbackMessage = typeof error === "string" ? error : error.message;
dispatch({ type: "SET_ERROR", payload: fallbackMessage });
return null;
}
}, [config, handlers, state.files, setError]);
const handleValidationErrors = React.useCallback((errors, context = {}) => {
try {
const { errors: processedErrors2 } = utils.processErrors(errors, {
operation: context.operation,
timestamp: /* @__PURE__ */ new Date()
}, config);
processedErrors2.forEach((error) => utils.logError(error));
setProcessedErrors((prev) => [...prev, ...processedErrors2]);
const errorSummary = processedErrors2.length === 1 ? processedErrors2[0].userMessage : `${processedErrors2.length} validation errors occurred`;
dispatch({ type: "SET_ERROR", payload: errorSummary });
return processedErrors2;
} catch (processingError) {
console.error("Error processing validation errors:", processingError);
dispatch({ type: "SET_ERROR", payload: "Multiple validation errors occurred" });
return [];
}
}, [config]);
const dismissError = React.useCallback((errorId) => {
setProcessedErrors((prev) => prev.filter((error) => error.id !== errorId));
}, []);
const dismissAllErrors = React.useCallback(() => {
setProcessedErrors([]);
dispatch({ type: "SET_ERROR", payload: null });
}, []);
const retryFailedUploads = React.useCallback(() => {
const failedFiles = state.files.filter((f) => f.status === "error");
failedFiles.forEach((file) => {
if (file.retryCount < file.maxRetries) {
retryUpload(file.id);
}
});
}, [state.files, retryUpload]);
const clearFailedUploads = React.useCallback(() => {
const failedFileIds = state.files.filter((f) => f.status === "error").map((f) => f.id);
failedFileIds.forEach((fileId) => {
dispatch({ type: "REMOVE_FILE", payload: fileId });
});
setProcessedErrors(
(prev) => prev.filter(
(error) => !failedFileIds.some(
(fileId) => error.context.fileName === state.files.find((f) => f.id === fileId)?.name
)
)
);
}, [state.files]);
const contextValue = {
state,
config,
processedErrors,
actions: {
selectFiles,
removeFile,
retryUpload,
clearAll,
uploadFiles,
updateProgress,
setError,
setSuccess,
handleError,
handleValidationErrors,
dismissError,
dismissAllErrors,
retryFailedUploads,
clearFailedUploads
},
handlers
};
return /* @__PURE__ */ jsxRuntime.jsx(FileUploadContext.Provider, { value: contextValue, children });
};
const useFileUpload = () => {
const context = React.useContext(FileUploadContext);
if (!context) {
throw new Error("useFileUpload must be used within a FileUploadProvider");
}
return context;
};
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
const toCamelCase = (string) => string.replace(
/^([A-Z])|[\s-_]+(\w)/g,
(match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()
);
const toPascalCase = (string) => {
const camelCase = toCamelCase(string);
return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
};
const mergeClasses = (...classes) => classes.filter((className, index, array) => {
return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
}).join(" ").trim();
const hasA11yProp = (props) => {
for (const prop in props) {
if (prop.startsWith("aria-") || prop === "role" || prop === "title") {
return true;
}
}
};
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
var defaultAttributes = {
xmlns: "http://www.w3.org/2000/svg",
width: 24,
height: 24,
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: 2,
strokeLinecap: "round",
strokeLinejoin: "round"
};
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const Icon = React.forwardRef(
({
color = "currentColor",
size = 24,
strokeWidth = 2,
absoluteStrokeWidth,
className = "",
children,
iconNode,
...rest
}, ref) => React.createElement(
"svg",
{
ref,
...defaultAttributes,
width: size,
height: size,
stroke: color,
strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,
className: mergeClasses("lucide", className),
...!children && !hasA11yProp(rest) && { "aria-hidden": "true" },
...rest
},
[
...iconNode.map(([tag, attrs]) => React.createElement(tag, attrs)),
...Array.isArray(children) ? children : [children]
]
)
);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const createLucideIcon = (iconName, iconNode) => {
const Component = React.forwardRef(
({ className, ...props }, ref) => React.createElement(Icon, {
ref,
iconNode,
className: mergeClasses(
`lucide-${toKebabCase(toPascalCase(iconName))}`,
`lucide-${iconName}`,
className
),
...props
})
);
Component.displayName = toPascalCase(iconName);
return Component;
};
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$9 = [
["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
["line", { x1: "12", x2: "12", y1: "8", y2: "12", key: "1pkeuh" }],
["line", { x1: "12", x2: "12.01", y1: "16", y2: "16", key: "4dfq90" }]
];
const CircleAlert = createLucideIcon("circle-alert", __iconNode$9);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$8 = [
["path", { d: "M21.801 10A10 10 0 1 1 17 3.335", key: "yps3ct" }],
["path", { d: "m9 11 3 3L22 4", key: "1pflzl" }]
];
const CircleCheckBig = createLucideIcon("circle-check-big", __iconNode$8);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$7 = [
["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
["path", { d: "M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3", key: "1u773s" }],
["path", { d: "M12 17h.01", key: "p32p05" }]
];
const CircleQuestionMark = createLucideIcon("circle-question-mark", __iconNode$7);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$6 = [
["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
["path", { d: "m15 9-6 6", key: "1uzhvr" }],
["path", { d: "m9 9 6 6", key: "z0biqf" }]
];
const CircleX = createLucideIcon("circle-x", __iconNode$6);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$5 = [
["path", { d: "M12 6v6l4 2", key: "mmk7yg" }],
["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }]
];
const Clock = createLucideIcon("clock", __iconNode$5);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$4 = [
["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
["path", { d: "M12 16v-4", key: "1dtifu" }],
["path", { d: "M12 8h.01", key: "e9boi3" }]
];
const Info = createLucideIcon("info", __iconNode$4);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$3 = [
["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8", key: "v9h5vc" }],
["path", { d: "M21 3v5h-5", key: "1q7to0" }],
["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16", key: "3uifl3" }],
["path", { d: "M8 16H3v5", key: "1cv678" }]
];
const RefreshCw = createLucideIcon("refresh-cw", __iconNode$3);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$2 = [
["path", { d: "M10 11v6", key: "nco0om" }],
["path", { d: "M14 11v6", key: "outv1u" }],
["path", { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6", key: "miytrc" }],
["path", { d: "M3 6h18", key: "d0wm0j" }],
["path", { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2", key: "e791ji" }]
];
const Trash2 = createLucideIcon("trash-2", __iconNode$2);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode$1 = [
[
"path",
{
d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",
key: "wmoenq"
}
],
["path", { d: "M12 9v4", key: "juzpu7" }],
["path", { d: "M12 17h.01", key: "p32p05" }]
];
const TriangleAlert = createLucideIcon("triangle-alert", __iconNode$1);
/**
* @license lucide-react v0.536.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
const __iconNode = [
["path", { d: "M18 6 6 18", key: "1bl5f8" }],
["path", { d: "m6 6 12 12", key: "d8bk6v" }]
];
const X = createLucideIcon("x", __iconNode);
class FileUploadErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
errorId: ""
};
}
static getDerivedStateFromError(error) {
const errorId = `error_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
return {
hasError: true,
error,
errorId
};
}
componentDidCatch(error, errorInfo) {
this.setState({
error,
errorInfo
});
this.props.onError?.(error, errorInfo);
console.error("FileUpload Error Boundary caught an error:", error, errorInfo);
}
handleRetry = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
errorId: ""
});
};
handleDismiss = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
errorId: ""
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: theme.cn(
"file-upload-error-boundary",
"border border-red-200 rounded-lg p-6 bg-red-50",
"text-red-900 space-y-4",
this.props.className
),
role: "alert",
"aria-live": "assertive",
"aria-labelledby": `error-title-${this.state.errorId}`,
"aria-describedby": `error-description-${this.state.errorId}`,
children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
/* @__PURE__ */ jsxRuntime.jsx(
TriangleAlert,
{
className: "w-5 h-5 text-red-500 flex-shrink-0 mt-0.5",
"aria-hidden": "true"
}
),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"h3",
{
id: `error-title-${this.state.errorId}`,
className: "text-sm font-medium text-red-800",
children: "Something went wrong with the file upload component"
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"p",
{
id: `error-description-${this.state.errorId}`,
className: "mt-1 text-sm text-red-700",
children: "An unexpected error occurred. You can try refreshing the component or contact support if the problem persists."
}
),
this.props.showErrorDetails && this.state.error && /* @__PURE__ */ jsxRuntime.jsxs("details", { className: "mt-3", children: [
/* @__PURE__ */ jsxRuntime.jsx("summary", { className: "text-sm font-medium text-red-800 cursor-pointer hover:text-red-900", children: "Technical Details" }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-2 p-3 bg-red-100 rounded border text-xs font-mono text-red-800 overflow-auto", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-2", children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Error:" }),
" ",
this.state.error.message
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-2", children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Stack:" }),
/* @__PURE__ */ jsxRuntime.jsx("pre", { className: "whitespace-pre-wrap mt-1", children: this.state.error.stack })
] }),
this.state.errorInfo && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Component Stack:" }),
/* @__PURE__ */ jsxRuntime.jsx("pre", { className: "whitespace-pre-wrap mt-1", children: this.state.errorInfo.componentStack })
] })
] })
] })
] }),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: this.handleDismiss,
className: "text-red-400 hover:text-red-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 rounded",
"aria-label": "Dismiss error",
children: /* @__PURE__ */ jsxRuntime.jsx(X, { className: "w-4 h-4" })
}
)
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-3 pt-2", children: [
/* @__PURE__ */ jsxRuntime.jsxs(
"button",
{
type: "button",
onClick: this.handleRetry,
className: theme.cn(
"inline-flex items-center gap-2 px-3 py-2 text-sm font-medium",
"text-red-700 bg-red-100 border border-red-300 rounded-md",
"hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2",
"transition-colors duration-200"
),
children: [
/* @__PURE__ */ jsxRuntime.jsx(RefreshCw, { className: "w-4 h-4" }),
"Try Again"
]
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => window.location.reload(),
className: theme.cn(
"inline-flex items-center px-3 py-2 text-sm font-medium",
"text-red-700 bg-transparent border border-red-300 rounded-md",
"hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2",
"transition-colors duration-200"
),
children: "Refresh Page"
}
)
] })
]
}
);
}
return this.props.children;
}
}
const withErrorBoundary = (Component2, errorBoundaryProps) => {
const WrappedComponent = (props) => /* @__PURE__ */ jsxRuntime.jsx(FileUploadErrorBoundary, { ...errorBoundaryProps, children: /* @__PURE__ */ jsxRuntime.jsx(Component2, { ...props }) });
WrappedComponent.displayName = `withErrorBoundary(${Component2.displayName || Component2.name})`;
return WrappedComponent;
};
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);
}
}
};
}
};
}
// @__NO_SIDE_EFFECTS__
function createSlot(ownerName) {
const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
const Slot2 = React__namespace.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
const childrenArray = React__namespace.Children.toArray(children);
const slottable = childrenArray.find(isSlottable);
if (slottable) {
const newElement = slottable.props.children;
const newChildren = childrenArray.map((child) => {
if (child === slottable) {
if (React__namespace.Children.count(newElement) > 1) return React__namespace.Children.only(null);
return React__namespace.isValidElement(newElement) ? newElement.props.children : null;
} else {
return child;
}
});
return /* @__PURE__ */ jsxRuntime.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children: React__namespace.isValidElement(newElement) ? React__namespace.cloneElement(newElement, void 0, newChildren) : null });
}
return /* @__PURE__ */ jsxRuntime.jsx(SlotClone, { ...slotProps, ref: forwardedRef, children });
});
Slot2.displayName = `${ownerName}.Slot`;
return Slot2;
}
var Slot = /* @__PURE__ */ createSlot("Slot");
// @__NO_SIDE_EFFECTS__
function createSlotClone(ownerName) {
const SlotClone = React__namespace.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
if (React__namespace.isValidElement(children)) {
const childrenRef = getElementRef(children);
const props2 = mergeProps(slotProps, children.props);
if (children.type !== React__namespace.Fragment) {
props2.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;
}
return React__namespace.cloneElement(children, props2);
}
return React__namespace.Children.count(children) > 1 ? React__namespace.Children.only(null) : null;
});
SlotClone.displayName = `${ownerName}.SlotClone`;
return SlotClone;
}
var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
function isSlottable(child) {
return React__namespace.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;
}
function r(e) {
var t, f, n = "";
if ("string" == typeof e || "number" == typeof e) n += e;
else if ("object" == typeof e) if (Array.isArray(e)) {
var o = e.length;
for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
} else for (f in e) e[f] && (n && (n += " "), n += f);
return n;
}
function clsx() {
for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
return n;
}
const CLASS_PART_SEPARATOR = "-";
const createClassGroupUtils = (config) => {
const classMap = createClassMap(config);
const {
conflictingClassGroups,
conflictingClassGroupModifiers
} = config;
const getClassGroupId = (className) => {
const classParts = className.split(CLASS_PART_SEPARATOR);
if (classParts[0] === "" && classParts.length !== 1) {
classParts.shift();
}
return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className);
};
const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {
const conflicts = conflictingClassGroups[classGroupId] || [];
if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {
return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]];
}
return conflicts;
};
return {
getClassGroupId,
getConflictingClassGroupIds
};
};
const getGroupRecursive = (classParts, classPartObject) => {
if (classParts.length === 0) {
return classPartObject.classGroupId;
}
const currentClassPart = classParts[0];
const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);
const classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : void 0;
if (classGroupFromNextClassPart) {
return classGroupFromNextClassPart;
}
if (classPartObject.validators.length === 0) {
return void 0;
}
const classRest = classParts.join(CLASS_PART_SEPARATOR);
return classPartObject.validators.find(({
validator
}) => validator(classRest))?.classGroupId;
};
const arbitraryPropertyRegex = /^\[(.+)\]$/;
const getGroupIdForArbitraryProperty = (className) => {
if (arbitraryPropertyRegex.test(className)) {
const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1];
const property = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(":"));
if (property) {
return "arbitrary.." + property;
}
}
};
const createClassMap = (config) => {
const {
theme: theme2,
classGroups
} = config;
const classMap = {
nextPart: /* @__PURE__ */ new Map(),
validators: []
};
for (const classGroupId in classGroups) {
processClassesRecursively(classGroups[classGroupId], classMap, classGroupId, theme2);
}
return classMap;
};
const processClassesRecursively = (classGroup, classPartObject, classGroupId, theme2) => {
classGroup.forEach((classDefinition) => {
if (typeof classDefinition === "string") {
const classPartObjectToEdit = classDefinition === "" ? classPartObject : getPart(classPartObject, classDefinition);
classPartObjectToEdit.classGroupId = classGroupId;
return;
}
if (typeof classDefinition === "function") {
if (isThemeGetter(classDefinition)) {
processClassesRecursively(classDefinition(theme2), classPartObject, classGroupId, theme2);
return;
}
classPartObject.validators.push({
validator: classDefinition,
classGroupId
});
return;
}
Object.entries(classDefinition).forEach(([key, classGroup2]) => {
processClassesRecursively(classGroup2, getPart(classPartObject, key), classGroupId, theme2);
});
});
};
const getPart = (classPartObject, path) => {
let currentClassPartObject = classPartObject;
path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => {
if (!currentClassPartObject.nextPart.has(pathPart)) {
currentClassPartObject.nextPart.set(pathPart, {
nextPart: /* @__PURE__ */ new Map(),
validators: []
});
}
currentClassPartObject = currentClassPartObject.nextPart.get(pathPart);
});
return currentClassPartObject;
};
const isThemeGetter = (func) => func.isThemeGetter;
const createLruCache = (maxCacheSize) => {
if (maxCacheSize < 1) {
return {
get: () => void 0,
set: () => {
}
};
}
let cacheSize = 0;
let cache = /* @__PURE__ */ new Map();
let previousCache = /* @__PURE__ */ new Map();
const update = (key, value) => {
cache.set(key, value);
cacheSize++;
if (cacheSize > maxCacheSize) {
cacheSize = 0;
previousCache = cache;
cache = /* @__PURE__ */ new Map();
}
};
return {
get(key) {
let value = cache.get(key);
if (value !== void 0) {
return value;
}
if ((value = previousCache.get(key)) !== void 0) {
update(key, value);
return value;
}
},
set(key, value) {
if (cache.has(key)) {
cache.set(key, value);
} else {
update(key, value);
}
}
};
};
const IMPORTANT_MODIFIER = "!";
const MODIFIER_SEPARATOR = ":";
const MODIFIER_SEPARATOR_LENGTH = MODIFIER_SEPARATOR.length;
const createParseClassName = (config) => {
const {
prefix,
experimentalParseClassName
} = config;
let parseClassName = (className) => {
const modifiers = [];
let bracketDepth = 0;
let parenDepth = 0;
let modifierStart = 0;
let postfixModifierPosition;
for (let index = 0; index < className.length; index++) {
let currentCharacter = className[index];
if (bracketDepth === 0 && parenDepth === 0) {
if (currentCharacter === MODIFIER_SEPARATOR) {
modifiers.push(className.slice(modifierStart, index));
modifierStart = index + MODIFIER_SEPARATOR_LENGTH;
continue;
}
if (currentCharacter === "/") {
postfixModifierPosition = index;
continue;
}
}
if (currentCharacter === "[") {
bracketDepth++;
} else if (currentCharacter === "]") {
bracketDepth--;
} else if (currentCharacter === "(") {
parenDepth++;
} else if (currentCharacter === ")") {
parenDepth--;
}
}
const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.substring(modifierStart);
const baseClassName = stripImportantModifier(baseClassNameWithImportantModifier);
const hasImportantModifier = baseClassName !== baseClassNameWithImportantModifier;
const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : void 0;
return {
modifiers,
hasImportantModifier,
baseClassName,
maybePostfixModifierPosition
};
};
if (prefix) {
const fullPrefix = prefix + MODIFIER_SEPARATOR;
const parseClassNameOriginal = parseClassName;
parseClassName = (className) => className.startsWith(fullPrefix) ? parseClassNameOriginal(className.substring(fullPrefix.length)) : {
isExternal: true,
modifiers: [],
hasImportantModifier: false,
baseClassName: className,
maybePostfixModifierPosition: void 0
};
}
if (experimentalParseClassName) {
const parseClassNameOriginal = parseClassName;
parseClassName = (className) => experimentalParseClassName({
className,
parseClassName: parseClassNameOriginal
});
}
return parseClassName;
};
const stripImportantModifier = (baseClassName) => {
if (baseClassName.endsWith(IMPORTANT_MODIFIER)) {
return baseClassName.substring(0, baseClassName.length - 1);
}
if (baseClassName.startsWith(IMPORTANT_MODIFIER)) {
return baseClassName.substring(1);
}
return baseClassName;
};
const createSortModifiers = (config) => {
const orderSensitiveModifiers = Object.fromEntries(config.orderSensitiveModifiers.map((modifier) => [modifier, true]));
const sortModifiers = (modifiers) => {
if (modifiers.length <= 1) {
return modifiers;
}
const sortedModifiers = [];
let unsortedModifiers = [];
modifiers.forEach((modifier) => {
const isPositionSensitive = modifier[0] === "[" || orderSensitiveModifiers[modifier];
if (isPositionSensitive) {
sortedModifiers.push(...unsortedModifiers.sort(), modifier);
unsortedModifiers = [];
} else {
unsortedModifiers.push(modifier);
}
});
sortedModifiers.push(...unsortedModifiers.sort());
return sortedModifiers;
};
return sortModifiers;
};
const createConfigUtils = (config) => ({
cache: createLruCache(config.cacheSize),
parseClassName: createParseClassName(config),
sortModifiers: createSortModifiers(config),
...createClassGroupUtils(config)
});
const SPLIT_CLASSES_REGEX = /\s+/;
const mergeClassList = (classList, configUtils) => {
const {
parseClassName,
getClassGroupId,
getConflictingClassGroupIds,
sortModifiers
} = configUtils;
const classGroupsInConflict = [];
const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);
let result = "";
for (let index = classNames.length - 1; index >= 0; index -= 1) {
const originalClassName = classNames[index];
const {
isExternal,
modifiers,
hasImportantModifier,
baseClassName,
maybePostfixModifierPosition
} = parseClassName(originalClassName);
if (isExternal) {
result = originalClassName + (result.length > 0 ? " " + result : result);
continue;
}
let hasPostfixModifier = !!maybePostfixModifierPosition;
let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);
if (!classGroupId) {
if (!hasPostfixModifier) {
result = originalClassName + (result.length > 0 ? " " + result : result);
continue;
}
classGroupId = getClassGroupId(baseClassName);
if (!classGroupId) {
result = originalClassName + (result.length > 0 ? " " + result : result);
continue;
}
hasPostfixModifier = false;
}
const variantModifier = sortModifiers(modifiers).join(":");
const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;
const classId = modifierId + classGroupId;
if (classGroupsInConflict.includes(classId)) {
continue;
}
classGroupsInConflict.push(classId);
const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);
for (let i = 0; i < conflictGroups.length; ++i) {
const group = conflictGroups[i];
classGroupsInConflict.push(modifierId + group);
}
result = originalClassName + (result.length > 0 ? " " + result : result);
}
return result;
};
function twJoin() {
let index = 0;
let argument;
let resolvedValue;
let string = "";
while (index < arguments.length) {
if (argument = arguments[index++]) {
if (resolvedValue = toValue(argument)) {
string && (string += " ");
string += resolvedValue;
}
}
}
return string;
}
const toValue = (mix) => {
if (typeof mix === "string") {
return mix;
}
let resolvedValue;
let string = "";
for (let k = 0; k < mix.length; k++) {
if (mix[k]) {
if (resolvedValue = toValue(mix[k])) {
string && (string += " ");
string += resolvedValue;
}
}
}
return string;
};
function createTailwindMerge(createConfigFirst, ...createConfigRest) {
let configUtils;
let cacheGet;
let cacheSet;
let functionToCall = initTailwindMerge;
function initTailwindMerge(classList) {
const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());
configUtils = createConfigUtils(config);
cacheGet = configUtils.cache.get;
cacheSet = configUtils.cache.set;
functionToCall = tailwindMerge;
return tailwindMerge(classList);
}
function tailwindMerge(classList) {
const cachedResult = cacheGet(classList);
if (cachedResult) {
return cachedResult;
}
const result = mergeClassList(classList, configUtils);
cacheSet(classList, result);
return result;
}
return function callTailwindMerge() {
return functionToCall(twJoin.apply(null, arguments));
};
}
const fromTheme = (key) => {
const themeGetter = (theme2) => theme2[key] || [];
themeGetter.isThemeGetter = true;
return themeGetter;
};
const arbitraryValueRegex = /^\[(?:(\w[\w-]*):)?(.+)\]$/i;
const arbitraryVariableRegex = /^\((?:(\w[\w-]*):)?(.+)\)$/i;
const fractionRegex = /^\d+\/\d+$/;
const tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/;
const lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/;
const colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/;
const shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/;
const imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;
const isFraction = (value) => fractionRegex.test(value);
const isNumber = (value) => !!value && !Number.isNaN(Number(value));
const isInteger = (value) => !!value && Number.isInteger(Number(value));
const isPercent = (value) => value.endsWith("%") && isNumber(value.slice(0, -1));
const isTshirtSize = (value) => tshirtUnitRegex.test(value);
const isAny = () => true;
const isLengthOnly = (value) => (
// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
// For example, `hsl(0 0% 0%)` would be classified as a length without this check.
// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)
);
const isNever = () => false;
const isShadow = (value) => shadowRegex.test(value);
const isImage = (value) => imageRegex.test(value);
const isAnyNonArbitrary = (value) => !isArbitraryValue(value) && !isArbitraryVariable(value);
const isArbitrarySize = (value) => getIsArbitraryValue(value, isLabelSize, isNever);
const isArbitraryValue = (value) => arbitraryValueRegex.test(value);
const isArbitraryLength = (value) => getIsArbitraryValue(value, isLabelLength, isLengthOnly);
const isArbitraryNumber = (value) => getIsArbitraryValue(value, isLabelNumber, isNumber);
const isArbitraryPosition = (value) => getIsArbitraryValue(value, isLabelPosition, isNever);
const isArbitraryImage = (value) => getIsArbitraryValue(value, isLabelImage, isImage);
const isArbitraryShadow = (value) => getIsArbitraryValue(value, isLabelShadow, isShadow);
const isArbitraryVariable = (value) => arbitraryVariableRegex.test(value);
const isArbitraryVariableLength = (value) => getIsArbitraryVariable(value, isLabelLength);
const isArbitraryVariableFamilyName = (value) => getIsArbitraryVariable(value, isLabelFamilyName);
const isArbitraryVariablePosition = (value) => getIsArbitraryVariable(value, isLabelPosition);
const isArbitraryVariableSize = (value) => getIsArbitraryVariable(value, isLabelSize);
const isArbitraryVariableImage = (value) => getIsArbitraryVariable(value, isLabelImage);
const isArbitraryVariableShadow = (value) => getIsArbitraryVariable(value, isLabelShadow, true);
const getIsArbitraryValue = (value, testLabel, testValue) => {
const result = arbitraryValueRegex.exec(value);
if (result) {
if (result[1]) {
return testLabel(result[1]);
}
return testValue(result[2]);
}
return false;
};
const getIsArbitraryVariable = (value, testLabel, shouldMatchNoLabel = false) => {
const result = arbitraryVariableRegex.exec(value);
if (result) {
if (result[1]) {
return testLabel(result[1]);
}
return shouldMatchNoLabel;
}
return false;
};
const isLabelPosition = (label) => label === "position" || label === "percentage";
const isLabelImage = (label) => label === "image" || label === "url";
const isLabelSize = (label) => label === "length" || label === "size" || label === "bg-size";
const isLabelLength = (label) => label === "length";
const isLabelNumber = (label) => label === "number";
const isLabelFamilyName = (label) => label === "family-name";
const isLabelShadow = (label) => label === "shadow";
const getDefaultConfig = () => {
const themeColor = fromTheme("color");
const themeFont = fromTheme("font");
const themeText = fromTheme("text");
const themeFontWeight = fromTheme("font-weight");
const themeTracking = fromTheme("tracking");
const themeLeading = fromTheme("leading");
const themeBreakpoint = fromTheme("breakpoint");
const themeContainer = fromTheme("container");
const themeSpacing = fromTheme("spacing");
const themeRadius = fromTheme("radius");
const themeShadow = fromTheme("shadow");
const themeInsetShadow = fromTheme("inset-shadow");
const themeTextShadow = fromTheme("text-shadow");
const themeDropShadow = fromTheme("drop-shadow");
const themeBlur = fromTheme("blur");
const themePerspective = fromTheme("perspective");
const themeAspect = fromTheme("aspect");
const themeEase = fromTheme("ease");
const themeAnimate = fromTheme("animate");
const scaleBreak = () => ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"];
const scalePosition = () => [
"center",
"top",
"bottom",
"left",
"right",
"top-left",
// Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378
"left-top",
"top-right",
// Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378
"right-top",
"bottom-right",
// Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378
"right-bottom",
"bottom-left",
// Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378
"left-bottom"
];
const scalePositionWithArbitrary = () => [...scalePosition(), isArbitraryVariable, isArbitraryValue];
const scaleOverflow = () => ["auto", "hidden", "clip", "visible", "scroll"];
const scaleOverscroll = () => ["auto", "contain", "none"];
const scaleUnambiguousSpacing = () => [isArbitraryVariable, isArbitraryValue, themeSpacing];
const scaleInset = () => [isFraction, "full", "auto", ...scaleUnambiguousSpacing()];
const scaleGridTemplateColsRows = () => [isInteger, "none", "subgrid", isArbitraryVariable, isArbitraryValue];
const scaleGridColRowStartAndEnd = () => ["auto", {
span: ["full", isInteger, isArbitraryVariable, isArbitraryValue]
}, isInteger, isArbitraryVariable, isArbitraryValue];
const scaleGridColRowStartOrEnd = () => [isInteger, "auto", isArbitraryVariable, isArbitraryValue];
const scaleGridAutoColsRows = () => ["auto", "min", "max", "fr", isArbitraryVariable, isArbitraryValue];
const scaleAlignPrimaryAxis = () => ["start", "end", "center", "between", "around", "evenly", "stretch", "baseline", "center-safe", "end-safe"];
const scaleAlignSecondaryAxis = () => ["start", "end", "center", "stretch", "center-safe", "end-safe"];
const scaleMargin = () => ["auto", ...scaleUnambiguousSpacing()];
const scaleSizing = () => [isFraction, "auto", "full", "dvw", "dvh", "lvw", "lvh", "svw", "svh", "min", "max", "fit", ...scaleUnambiguousSpacing()];
const scaleColor = () => [themeColor, isArbitraryVariable, isArbitraryValue];
const scaleBgPosition = () => [...scalePosition(), isArbitraryVariablePosition, isArbitraryPosition, {
position: [isArbitraryVariable, isArbitraryValue]
}];
const scaleBgRepeat = () => ["no-repeat", {
repeat: ["", "x", "y", "space", "round"]
}];
const scaleBgSize = () => ["auto", "cover", "contain", isArbitraryVariableSize, isArbitrarySize, {
size: [isArbitraryVariable, isArbitraryValue]
}];
const scaleGradientStopPosition = () => [isPercent, isArbitraryVariableLength, isArbitraryLength];
const scaleRadius = () => [
// Deprecated since Tailwind CSS v4.0.0
"",
"none",
"full",
themeRadius,
isArbitraryVariable,
isArbitraryValue
];
const scaleBorderWidth = () => ["", isNumber, isArbitraryVariableLength, isArbitraryLength];
const scaleLineStyle = () => ["solid", "dashed", "dotted", "double"];
const scaleBlendMode = () => ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"];
const scaleMaskImagePosition = () => [isNumber, isPercent, isArbitraryVariablePosition, isArbitraryPosition];
const scaleBlur = () => [
// Deprecated since Tailwind CSS v4.0.0
"",
"none",
themeBlur,
isArbitraryVariable,
isArbitraryValue
];
const scaleRotate = () => ["none", isNumber, isArbitraryVariable, isArbitraryValue];
const scaleScale = () => ["none", isNumber, isArbitraryVariable, isArbitraryValue];
const scaleSkew = () => [isNumber, isArbitraryVariable, isArbitraryValue];
const scaleTranslate = () => [isFraction, "full", ...scaleUnambiguousSpacing()];
return {
cacheSize: 500,
theme: {
animate: ["spin", "ping", "pulse", "bounce"],
aspect: ["video"],
blur: [isTshirtSize],
breakpoint: [isTshirtSize],
color: [isAny],
container: [isTshirtSize],
"drop-shadow": [isTshirtSize],
ease: ["in", "out", "in-out"],
font: [isAnyNonArbitrary],
"font-weight": ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black"],
"inset-shadow": [isTshirtSize],
leading: ["none", "tight", "snug", "normal", "relaxed", "loose"],
perspective: ["dramatic", "near", "normal", "midrange", "distant", "none"],
radius: [isTshirtSize],
shadow: [isTshirtSize],
spacing: ["px", isNumber],
text: [isTshirtSize],
"text-shadow": [isTshirtSize],
tracking: ["tighter", "tight", "normal", "wide", "wider", "widest"]
},
classGroups: {
// --------------
// --- Layout ---
// --------------
/**
* Aspect Ratio
* @see https://tailwindcss.com/docs/aspect-ratio
*/
aspect: [{
aspect: ["auto", "square", isFraction, isArbitraryValue, isArbitraryVariable, themeAspect]
}],
/**
* Container
* @see https://tailwindcss.com/docs/container
* @deprecated since Tailwind CSS v4.0.0
*/
container: ["container"],
/**
* Columns
* @see https://tailwindcss.com/docs/columns
*/
columns: [{
columns: [isNumber, isArbitraryValue, isArbitraryVariable, themeContainer]
}],
/**
* Break After
* @see https://tailwindcss.com/docs/break-after
*/
"break-after": [{
"break-after": scaleBreak()
}],
/**
* Break Before
* @see https://tailwindcss.com/docs/break-before
*/
"break-before": [{
"break-before": scaleBreak()
}],
/**
* Break Inside
* @see https://tailwindcss.com/docs/break-inside
*/
"break-inside": [{
"break-inside": ["auto", "avoid", "avoid-page", "avoid-column"]
}],
/**
* Box Decoration Break
* @see https://tailwindcss.com/docs/box-decoration-break
*/
"box-decoration": [{
"box-decoration": ["slice", "clone"]
}],
/**
* Box Sizing
* @see https://tailwindcss.com/docs/box-sizing
*/
box: [{
box: ["border", "content"]
}],
/**
* Display
* @see https://tailwindcss.com/docs/display
*/
display: ["block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden"],
/**
* Screen Reader Only
* @see https://tailwindcss.com/docs/display#screen-reader-only
*/
sr: ["sr-only", "not-sr-only"],
/**
* Floats
* @see https://tailwindcss.com/docs/float
*/
float: [{
float: ["right", "left", "none", "start", "end"]
}],
/**
* Clear
* @see https://tailwindcss.com/docs/clear
*/
clear: [{
clear: ["left", "right", "both", "none", "start", "end"]
}],
/**
* Isolation
* @see https://tailwindcss.com/docs/isolation
*/
isolation: ["isolate", "isolation-auto"],
/**
* Object Fit
* @see https://tailwindcss.com/docs/object-fit
*/
"object-fit": [{
object: ["contain", "cover", "fill", "none", "scale-down"]
}],
/**
* Object Position
* @see https://tailwindcss.com/docs/object-position
*/
"object-position": [{
object: scalePositionWithArbitrary()
}],
/**
* Overflow
* @see https://tailwindcss.com/docs/overflow
*/
overflow: [{
overflow: scaleOverflow()
}],
/**
* Overflow X
* @see https://tailwindcss.com/docs/overflow
*/
"overflow-x": [{
"overflow-x": scaleOverflow()
}],
/**
* Overflow Y
* @see https://tailwindcss.com/docs/overflow
*/
"overflow-y": [{
"overflow-y": scaleOverflow()
}],
/**
* Overscroll Behavior
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
overscroll: [{
overscroll: scaleOverscroll()
}],
/**
* Overscroll Behavior X
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
"overscroll-x": [{
"overscroll-x": scaleOverscroll()
}],
/**
* Overscroll Behavior Y
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
"overscroll-y": [{
"overscroll-y": scaleOverscroll()
}],
/**
* Position
* @see https://tailwindcss.com/docs/position
*/
position: ["static", "fixed", "absolute", "relative", "sticky"],
/**
* Top / Right / Bottom / Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
inset: [{
inset: scaleInset()
}],
/**
* Right / Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
"inset-x": [{
"inset-x": scaleInset()
}],
/**
* Top / Bottom
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
"inset-y": [{
"inset-y": scaleInset()
}],
/**
* Start
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
start: [{
start: scaleInset()
}],
/**
* End
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
end: [{
end: scaleInset()
}],
/**
* Top
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
top: [{
top: scaleInset()
}],
/**
* Right
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
right: [{
right: scaleInset()
}],
/**
* Bottom
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
bottom: [{
bottom: scaleInset()
}],
/**
* Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
left: [{
left: scaleInset()
}],
/**
* Visibility
* @see https://tailwindcss.com/docs/visibility
*/
visibility: ["visible", "invisible", "collapse"],
/**
* Z-Index
* @see https://tailwindcss.com/docs/z-index
*/
z: [{
z: [isInteger, "auto", isArbitraryVariable, isArbitraryValue]
}],
// ------------------------
// --- Flexbox and Grid ---
// ------------------------
/**
* Flex Basis
* @see https://tailwindcss.com/docs/flex-basis
*/
basis: [{
basis: [isFraction, "full", "auto", themeContainer, ...scaleUnambiguousSpacing()]
}],
/**
* Flex Direction
* @see https://tailwindcss.com/docs/flex-direction
*/
"flex-direction": [{
flex: ["row", "row-reverse", "col", "col-reverse"]
}],
/**
* Flex Wrap
* @see https://tailwindcss.com/docs/flex-wrap
*/
"flex-wrap": [{
flex: ["nowrap", "wrap", "wrap-reverse"]
}],
/**
* Flex
* @see https://tailwindcss.com/docs/flex
*/
flex: [{
flex: [isNumber, isFraction, "auto", "initial", "none", isArbitraryValue]
}],
/**
* Flex Grow
* @see https://tailwindcss.com/docs/flex-grow
*/
grow: [{
grow: ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Flex Shrink
* @see https://tailwindcss.com/docs/flex-shrink
*/
shrink: [{
shrink: ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Order
* @see https://tailwindcss.com/docs/order
*/
order: [{
order: [isInteger, "first", "last", "none", isArbitraryVariable, isArbitraryValue]
}],
/**
* Grid Template Columns
* @see https://tailwindcss.com/docs/grid-template-columns
*/
"grid-cols": [{
"grid-cols": scaleGridTemplateColsRows()
}],
/**
* Grid Column Start / End
* @see https://tailwindcss.com/docs/grid-column
*/
"col-start-end": [{
col: scaleGridColRowStartAndEnd()
}],
/**
* Grid Column Start
* @see https://tailwindcss.com/docs/grid-column
*/
"col-start": [{
"col-start": scaleGridColRowStartOrEnd()
}],
/**
* Grid Column End
* @see https://tailwindcss.com/docs/grid-column
*/
"col-end": [{
"col-end": scaleGridColRowStartOrEnd()
}],
/**
* Grid Template Rows
* @see https://tailwindcss.com/docs/grid-template-rows
*/
"grid-rows": [{
"grid-rows": scaleGridTemplateColsRows()
}],
/**
* Grid Row Start / End
* @see https://tailwindcss.com/docs/grid-row
*/
"row-start-end": [{
row: scaleGridColRowStartAndEnd()
}],
/**
* Grid Row Start
* @see https://tailwindcss.com/docs/grid-row
*/
"row-start": [{
"row-start": scaleGridColRowStartOrEnd()
}],
/**
* Grid Row End
* @see https://tailwindcss.com/docs/grid-row
*/
"row-end": [{
"row-end": scaleGridColRowStartOrEnd()
}],
/**
* Grid Auto Flow
* @see https://tailwindcss.com/docs/grid-auto-flow
*/
"grid-flow": [{
"grid-flow": ["row", "col", "dense", "row-dense", "col-dense"]
}],
/**
* Grid Auto Columns
* @see https://tailwindcss.com/docs/grid-auto-columns
*/
"auto-cols": [{
"auto-cols": scaleGridAutoColsRows()
}],
/**
* Grid Auto Rows
* @see https://tailwindcss.com/docs/grid-auto-rows
*/
"auto-rows": [{
"auto-rows": scaleGridAutoColsRows()
}],
/**
* Gap
* @see https://tailwindcss.com/docs/gap
*/
gap: [{
gap: scaleUnambiguousSpacing()
}],
/**
* Gap X
* @see https://tailwindcss.com/docs/gap
*/
"gap-x": [{
"gap-x": scaleUnambiguousSpacing()
}],
/**
* Gap Y
* @see https://tailwindcss.com/docs/gap
*/
"gap-y": [{
"gap-y": scaleUnambiguousSpacing()
}],
/**
* Justify Content
* @see https://tailwindcss.com/docs/justify-content
*/
"justify-content": [{
justify: [...scaleAlignPrimaryAxis(), "normal"]
}],
/**
* Justify Items
* @see https://tailwindcss.com/docs/justify-items
*/
"justify-items": [{
"justify-items": [...scaleAlignSecondaryAxis(), "normal"]
}],
/**
* Justify Self
* @see https://tailwindcss.com/docs/justify-self
*/
"justify-self": [{
"justify-self": ["auto", ...scaleAlignSecondaryAxis()]
}],
/**
* Align Content
* @see https://tailwindcss.com/docs/align-content
*/
"align-content": [{
content: ["normal", ...scaleAlignPrimaryAxis()]
}],
/**
* Align Items
* @see https://tailwindcss.com/docs/align-items
*/
"align-items": [{
items: [...scaleAlignSecondaryAxis(), {
baseline: ["", "last"]
}]
}],
/**
* Align Self
* @see https://tailwindcss.com/docs/align-self
*/
"align-self": [{
self: ["auto", ...scaleAlignSecondaryAxis(), {
baseline: ["", "last"]
}]
}],
/**
* Place Content
* @see https://tailwindcss.com/docs/place-content
*/
"place-content": [{
"place-content": scaleAlignPrimaryAxis()
}],
/**
* Place Items
* @see https://tailwindcss.com/docs/place-items
*/
"place-items": [{
"place-items": [...scaleAlignSecondaryAxis(), "baseline"]
}],
/**
* Place Self
* @see https://tailwindcss.com/docs/place-self
*/
"place-self": [{
"place-self": ["auto", ...scaleAlignSecondaryAxis()]
}],
// Spacing
/**
* Padding
* @see https://tailwindcss.com/docs/padding
*/
p: [{
p: scaleUnambiguousSpacing()
}],
/**
* Padding X
* @see https://tailwindcss.com/docs/padding
*/
px: [{
px: scaleUnambiguousSpacing()
}],
/**
* Padding Y
* @see https://tailwindcss.com/docs/padding
*/
py: [{
py: scaleUnambiguousSpacing()
}],
/**
* Padding Start
* @see https://tailwindcss.com/docs/padding
*/
ps: [{
ps: scaleUnambiguousSpacing()
}],
/**
* Padding End
* @see https://tailwindcss.com/docs/padding
*/
pe: [{
pe: scaleUnambiguousSpacing()
}],
/**
* Padding Top
* @see https://tailwindcss.com/docs/padding
*/
pt: [{
pt: scaleUnambiguousSpacing()
}],
/**
* Padding Right
* @see https://tailwindcss.com/docs/padding
*/
pr: [{
pr: scaleUnambiguousSpacing()
}],
/**
* Padding Bottom
* @see https://tailwindcss.com/docs/padding
*/
pb: [{
pb: scaleUnambiguousSpacing()
}],
/**
* Padding Left
* @see https://tailwindcss.com/docs/padding
*/
pl: [{
pl: scaleUnambiguousSpacing()
}],
/**
* Margin
* @see https://tailwindcss.com/docs/margin
*/
m: [{
m: scaleMargin()
}],
/**
* Margin X
* @see https://tailwindcss.com/docs/margin
*/
mx: [{
mx: scaleMargin()
}],
/**
* Margin Y
* @see https://tailwindcss.com/docs/margin
*/
my: [{
my: scaleMargin()
}],
/**
* Margin Start
* @see https://tailwindcss.com/docs/margin
*/
ms: [{
ms: scaleMargin()
}],
/**
* Margin End
* @see https://tailwindcss.com/docs/margin
*/
me: [{
me: scaleMargin()
}],
/**
* Margin Top
* @see https://tailwindcss.com/docs/margin
*/
mt: [{
mt: scaleMargin()
}],
/**
* Margin Right
* @see https://tailwindcss.com/docs/margin
*/
mr: [{
mr: scaleMargin()
}],
/**
* Margin Bottom
* @see https://tailwindcss.com/docs/margin
*/
mb: [{
mb: scaleMargin()
}],
/**
* Margin Left
* @see https://tailwindcss.com/docs/margin
*/
ml: [{
ml: scaleMargin()
}],
/**
* Space Between X
* @see https://tailwindcss.com/docs/margin#adding-space-between-children
*/
"space-x": [{
"space-x": scaleUnambiguousSpacing()
}],
/**
* Space Between X Reverse
* @see https://tailwindcss.com/docs/margin#adding-space-between-children
*/
"space-x-reverse": ["space-x-reverse"],
/**
* Space Between Y
* @see https://tailwindcss.com/docs/margin#adding-space-between-children
*/
"space-y": [{
"space-y": scaleUnambiguousSpacing()
}],
/**
* Space Between Y Reverse
* @see https://tailwindcss.com/docs/margin#adding-space-between-children
*/
"space-y-reverse": ["space-y-reverse"],
// --------------
// --- Sizing ---
// --------------
/**
* Size
* @see https://tailwindcss.com/docs/width#setting-both-width-and-height
*/
size: [{
size: scaleSizing()
}],
/**
* Width
* @see https://tailwindcss.com/docs/width
*/
w: [{
w: [themeContainer, "screen", ...scaleSizing()]
}],
/**
* Min-Width
* @see https://tailwindcss.com/docs/min-width
*/
"min-w": [{
"min-w": [
themeContainer,
"screen",
/** Deprecated. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */
"none",
...scaleSizing()
]
}],
/**
* Max-Width
* @see https://tailwindcss.com/docs/max-width
*/
"max-w": [{
"max-w": [
themeContainer,
"screen",
"none",
/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */
"prose",
/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */
{
screen: [themeBreakpoint]
},
...scaleSizing()
]
}],
/**
* Height
* @see https://tailwindcss.com/docs/height
*/
h: [{
h: ["screen", "lh", ...scaleSizing()]
}],
/**
* Min-Height
* @see https://tailwindcss.com/docs/min-height
*/
"min-h": [{
"min-h": ["screen", "lh", "none", ...scaleSizing()]
}],
/**
* Max-Height
* @see https://tailwindcss.com/docs/max-height
*/
"max-h": [{
"max-h": ["screen", "lh", ...scaleSizing()]
}],
// ------------------
// --- Typography ---
// ------------------
/**
* Font Size
* @see https://tailwindcss.com/docs/font-size
*/
"font-size": [{
text: ["base", themeText, isArbitraryVariableLength, isArbitraryLength]
}],
/**
* Font Smoothing
* @see https://tailwindcss.com/docs/font-smoothing
*/
"font-smoothing": ["antialiased", "subpixel-antialiased"],
/**
* Font Style
* @see https://tailwindcss.com/docs/font-style
*/
"font-style": ["italic", "not-italic"],
/**
* Font Weight
* @see https://tailwindcss.com/docs/font-weight
*/
"font-weight": [{
font: [themeFontWeight, isArbitraryVariable, isArbitraryNumber]
}],
/**
* Font Stretch
* @see https://tailwindcss.com/docs/font-stretch
*/
"font-stretch": [{
"font-stretch": ["ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded", isPercent, isArbitraryValue]
}],
/**
* Font Family
* @see https://tailwindcss.com/docs/font-family
*/
"font-family": [{
font: [isArbitraryVariableFamilyName, isArbitraryValue, themeFont]
}],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-normal": ["normal-nums"],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-ordinal": ["ordinal"],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-slashed-zero": ["slashed-zero"],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-figure": ["lining-nums", "oldstyle-nums"],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-spacing": ["proportional-nums", "tabular-nums"],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
"fvn-fraction": ["diagonal-fractions", "stacked-fractions"],
/**
* Letter Spacing
* @see https://tailwindcss.com/docs/letter-spacing
*/
tracking: [{
tracking: [themeTracking, isArbitraryVariable, isArbitraryValue]
}],
/**
* Line Clamp
* @see https://tailwindcss.com/docs/line-clamp
*/
"line-clamp": [{
"line-clamp": [isNumber, "none", isArbitraryVariable, isArbitraryNumber]
}],
/**
* Line Height
* @see https://tailwindcss.com/docs/line-height
*/
leading: [{
leading: [
/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */
themeLeading,
...scaleUnambiguousSpacing()
]
}],
/**
* List Style Image
* @see https://tailwindcss.com/docs/list-style-image
*/
"list-image": [{
"list-image": ["none", isArbitraryVariable, isArbitraryValue]
}],
/**
* List Style Position
* @see https://tailwindcss.com/docs/list-style-position
*/
"list-style-position": [{
list: ["inside", "outside"]
}],
/**
* List Style Type
* @see https://tailwindcss.com/docs/list-style-type
*/
"list-style-type": [{
list: ["disc", "decimal", "none", isArbitraryVariable, isArbitraryValue]
}],
/**
* Text Alignment
* @see https://tailwindcss.com/docs/text-align
*/
"text-alignment": [{
text: ["left", "center", "right", "justify", "start", "end"]
}],
/**
* Placeholder Color
* @deprecated since Tailwind CSS v3.0.0
* @see https://v3.tailwindcss.com/docs/placeholder-color
*/
"placeholder-color": [{
placeholder: scaleColor()
}],
/**
* Text Color
* @see https://tailwindcss.com/docs/text-color
*/
"text-color": [{
text: scaleColor()
}],
/**
* Text Decoration
* @see https://tailwindcss.com/docs/text-decoration
*/
"text-decoration": ["underline", "overline", "line-through", "no-underline"],
/**
* Text Decoration Style
* @see https://tailwindcss.com/docs/text-decoration-style
*/
"text-decoration-style": [{
decoration: [...scaleLineStyle(), "wavy"]
}],
/**
* Text Decoration Thickness
* @see https://tailwindcss.com/docs/text-decoration-thickness
*/
"text-decoration-thickness": [{
decoration: [isNumber, "from-font", "auto", isArbitraryVariable, isArbitraryLength]
}],
/**
* Text Decoration Color
* @see https://tailwindcss.com/docs/text-decoration-color
*/
"text-decoration-color": [{
decoration: scaleColor()
}],
/**
* Text Underline Offset
* @see https://tailwindcss.com/docs/text-underline-offset
*/
"underline-offset": [{
"underline-offset": [isNumber, "auto", isArbitraryVariable, isArbitraryValue]
}],
/**
* Text Transform
* @see https://tailwindcss.com/docs/text-transform
*/
"text-transform": ["uppercase", "lowercase", "capitalize", "normal-case"],
/**
* Text Overflow
* @see https://tailwindcss.com/docs/text-overflow
*/
"text-overflow": ["truncate", "text-ellipsis", "text-clip"],
/**
* Text Wrap
* @see https://tailwindcss.com/docs/text-wrap
*/
"text-wrap": [{
text: ["wrap", "nowrap", "balance", "pretty"]
}],
/**
* Text Indent
* @see https://tailwindcss.com/docs/text-indent
*/
indent: [{
indent: scaleUnambiguousSpacing()
}],
/**
* Vertical Alignment
* @see https://tailwindcss.com/docs/vertical-align
*/
"vertical-align": [{
align: ["baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", isArbitraryVariable, isArbitraryValue]
}],
/**
* Whitespace
* @see https://tailwindcss.com/docs/whitespace
*/
whitespace: [{
whitespace: ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"]
}],
/**
* Word Break
* @see https://tailwindcss.com/docs/word-break
*/
break: [{
break: ["normal", "words", "all", "keep"]
}],
/**
* Overflow Wrap
* @see https://tailwindcss.com/docs/overflow-wrap
*/
wrap: [{
wrap: ["break-word", "anywhere", "normal"]
}],
/**
* Hyphens
* @see https://tailwindcss.com/docs/hyphens
*/
hyphens: [{
hyphens: ["none", "manual", "auto"]
}],
/**
* Content
* @see https://tailwindcss.com/docs/content
*/
content: [{
content: ["none", isArbitraryVariable, isArbitraryValue]
}],
// -------------------
// --- Backgrounds ---
// -------------------
/**
* Background Attachment
* @see https://tailwindcss.com/docs/background-attachment
*/
"bg-attachment": [{
bg: ["fixed", "local", "scroll"]
}],
/**
* Background Clip
* @see https://tailwindcss.com/docs/background-clip
*/
"bg-clip": [{
"bg-clip": ["border", "padding", "content", "text"]
}],
/**
* Background Origin
* @see https://tailwindcss.com/docs/background-origin
*/
"bg-origin": [{
"bg-origin": ["border", "padding", "content"]
}],
/**
* Background Position
* @see https://tailwindcss.com/docs/background-position
*/
"bg-position": [{
bg: scaleBgPosition()
}],
/**
* Background Repeat
* @see https://tailwindcss.com/docs/background-repeat
*/
"bg-repeat": [{
bg: scaleBgRepeat()
}],
/**
* Background Size
* @see https://tailwindcss.com/docs/background-size
*/
"bg-size": [{
bg: scaleBgSize()
}],
/**
* Background Image
* @see https://tailwindcss.com/docs/background-image
*/
"bg-image": [{
bg: ["none", {
linear: [{
to: ["t", "tr", "r", "br", "b", "bl", "l", "tl"]
}, isInteger, isArbitraryVariable, isArbitraryValue],
radial: ["", isArbitraryVariable, isArbitraryValue],
conic: [isInteger, isArbitraryVariable, isArbitraryValue]
}, isArbitraryVariableImage, isArbitraryImage]
}],
/**
* Background Color
* @see https://tailwindcss.com/docs/background-color
*/
"bg-color": [{
bg: scaleColor()
}],
/**
* Gradient Color Stops From Position
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-from-pos": [{
from: scaleGradientStopPosition()
}],
/**
* Gradient Color Stops Via Position
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-via-pos": [{
via: scaleGradientStopPosition()
}],
/**
* Gradient Color Stops To Position
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-to-pos": [{
to: scaleGradientStopPosition()
}],
/**
* Gradient Color Stops From
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-from": [{
from: scaleColor()
}],
/**
* Gradient Color Stops Via
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-via": [{
via: scaleColor()
}],
/**
* Gradient Color Stops To
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
"gradient-to": [{
to: scaleColor()
}],
// ---------------
// --- Borders ---
// ---------------
/**
* Border Radius
* @see https://tailwindcss.com/docs/border-radius
*/
rounded: [{
rounded: scaleRadius()
}],
/**
* Border Radius Start
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-s": [{
"rounded-s": scaleRadius()
}],
/**
* Border Radius End
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-e": [{
"rounded-e": scaleRadius()
}],
/**
* Border Radius Top
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-t": [{
"rounded-t": scaleRadius()
}],
/**
* Border Radius Right
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-r": [{
"rounded-r": scaleRadius()
}],
/**
* Border Radius Bottom
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-b": [{
"rounded-b": scaleRadius()
}],
/**
* Border Radius Left
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-l": [{
"rounded-l": scaleRadius()
}],
/**
* Border Radius Start Start
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-ss": [{
"rounded-ss": scaleRadius()
}],
/**
* Border Radius Start End
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-se": [{
"rounded-se": scaleRadius()
}],
/**
* Border Radius End End
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-ee": [{
"rounded-ee": scaleRadius()
}],
/**
* Border Radius End Start
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-es": [{
"rounded-es": scaleRadius()
}],
/**
* Border Radius Top Left
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-tl": [{
"rounded-tl": scaleRadius()
}],
/**
* Border Radius Top Right
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-tr": [{
"rounded-tr": scaleRadius()
}],
/**
* Border Radius Bottom Right
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-br": [{
"rounded-br": scaleRadius()
}],
/**
* Border Radius Bottom Left
* @see https://tailwindcss.com/docs/border-radius
*/
"rounded-bl": [{
"rounded-bl": scaleRadius()
}],
/**
* Border Width
* @see https://tailwindcss.com/docs/border-width
*/
"border-w": [{
border: scaleBorderWidth()
}],
/**
* Border Width X
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-x": [{
"border-x": scaleBorderWidth()
}],
/**
* Border Width Y
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-y": [{
"border-y": scaleBorderWidth()
}],
/**
* Border Width Start
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-s": [{
"border-s": scaleBorderWidth()
}],
/**
* Border Width End
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-e": [{
"border-e": scaleBorderWidth()
}],
/**
* Border Width Top
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-t": [{
"border-t": scaleBorderWidth()
}],
/**
* Border Width Right
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-r": [{
"border-r": scaleBorderWidth()
}],
/**
* Border Width Bottom
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-b": [{
"border-b": scaleBorderWidth()
}],
/**
* Border Width Left
* @see https://tailwindcss.com/docs/border-width
*/
"border-w-l": [{
"border-l": scaleBorderWidth()
}],
/**
* Divide Width X
* @see https://tailwindcss.com/docs/border-width#between-children
*/
"divide-x": [{
"divide-x": scaleBorderWidth()
}],
/**
* Divide Width X Reverse
* @see https://tailwindcss.com/docs/border-width#between-children
*/
"divide-x-reverse": ["divide-x-reverse"],
/**
* Divide Width Y
* @see https://tailwindcss.com/docs/border-width#between-children
*/
"divide-y": [{
"divide-y": scaleBorderWidth()
}],
/**
* Divide Width Y Reverse
* @see https://tailwindcss.com/docs/border-width#between-children
*/
"divide-y-reverse": ["divide-y-reverse"],
/**
* Border Style
* @see https://tailwindcss.com/docs/border-style
*/
"border-style": [{
border: [...scaleLineStyle(), "hidden", "none"]
}],
/**
* Divide Style
* @see https://tailwindcss.com/docs/border-style#setting-the-divider-style
*/
"divide-style": [{
divide: [...scaleLineStyle(), "hidden", "none"]
}],
/**
* Border Color
* @see https://tailwindcss.com/docs/border-color
*/
"border-color": [{
border: scaleColor()
}],
/**
* Border Color X
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-x": [{
"border-x": scaleColor()
}],
/**
* Border Color Y
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-y": [{
"border-y": scaleColor()
}],
/**
* Border Color S
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-s": [{
"border-s": scaleColor()
}],
/**
* Border Color E
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-e": [{
"border-e": scaleColor()
}],
/**
* Border Color Top
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-t": [{
"border-t": scaleColor()
}],
/**
* Border Color Right
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-r": [{
"border-r": scaleColor()
}],
/**
* Border Color Bottom
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-b": [{
"border-b": scaleColor()
}],
/**
* Border Color Left
* @see https://tailwindcss.com/docs/border-color
*/
"border-color-l": [{
"border-l": scaleColor()
}],
/**
* Divide Color
* @see https://tailwindcss.com/docs/divide-color
*/
"divide-color": [{
divide: scaleColor()
}],
/**
* Outline Style
* @see https://tailwindcss.com/docs/outline-style
*/
"outline-style": [{
outline: [...scaleLineStyle(), "none", "hidden"]
}],
/**
* Outline Offset
* @see https://tailwindcss.com/docs/outline-offset
*/
"outline-offset": [{
"outline-offset": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Outline Width
* @see https://tailwindcss.com/docs/outline-width
*/
"outline-w": [{
outline: ["", isNumber, isArbitraryVariableLength, isArbitraryLength]
}],
/**
* Outline Color
* @see https://tailwindcss.com/docs/outline-color
*/
"outline-color": [{
outline: scaleColor()
}],
// ---------------
// --- Effects ---
// ---------------
/**
* Box Shadow
* @see https://tailwindcss.com/docs/box-shadow
*/
shadow: [{
shadow: [
// Deprecated since Tailwind CSS v4.0.0
"",
"none",
themeShadow,
isArbitraryVariableShadow,
isArbitraryShadow
]
}],
/**
* Box Shadow Color
* @see https://tailwindcss.com/docs/box-shadow#setting-the-shadow-color
*/
"shadow-color": [{
shadow: scaleColor()
}],
/**
* Inset Box Shadow
* @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-shadow
*/
"inset-shadow": [{
"inset-shadow": ["none", themeInsetShadow, isArbitraryVariableShadow, isArbitraryShadow]
}],
/**
* Inset Box Shadow Color
* @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-shadow-color
*/
"inset-shadow-color": [{
"inset-shadow": scaleColor()
}],
/**
* Ring Width
* @see https://tailwindcss.com/docs/box-shadow#adding-a-ring
*/
"ring-w": [{
ring: scaleBorderWidth()
}],
/**
* Ring Width Inset
* @see https://v3.tailwindcss.com/docs/ring-width#inset-rings
* @deprecated since Tailwind CSS v4.0.0
* @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158
*/
"ring-w-inset": ["ring-inset"],
/**
* Ring Color
* @see https://tailwindcss.com/docs/box-shadow#setting-the-ring-color
*/
"ring-color": [{
ring: scaleColor()
}],
/**
* Ring Offset Width
* @see https://v3.tailwindcss.com/docs/ring-offset-width
* @deprecated since Tailwind CSS v4.0.0
* @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158
*/
"ring-offset-w": [{
"ring-offset": [isNumber, isArbitraryLength]
}],
/**
* Ring Offset Color
* @see https://v3.tailwindcss.com/docs/ring-offset-color
* @deprecated since Tailwind CSS v4.0.0
* @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158
*/
"ring-offset-color": [{
"ring-offset": scaleColor()
}],
/**
* Inset Ring Width
* @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-ring
*/
"inset-ring-w": [{
"inset-ring": scaleBorderWidth()
}],
/**
* Inset Ring Color
* @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-ring-color
*/
"inset-ring-color": [{
"inset-ring": scaleColor()
}],
/**
* Text Shadow
* @see https://tailwindcss.com/docs/text-shadow
*/
"text-shadow": [{
"text-shadow": ["none", themeTextShadow, isArbitraryVariableShadow, isArbitraryShadow]
}],
/**
* Text Shadow Color
* @see https://tailwindcss.com/docs/text-shadow#setting-the-shadow-color
*/
"text-shadow-color": [{
"text-shadow": scaleColor()
}],
/**
* Opacity
* @see https://tailwindcss.com/docs/opacity
*/
opacity: [{
opacity: [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Mix Blend Mode
* @see https://tailwindcss.com/docs/mix-blend-mode
*/
"mix-blend": [{
"mix-blend": [...scaleBlendMode(), "plus-darker", "plus-lighter"]
}],
/**
* Background Blend Mode
* @see https://tailwindcss.com/docs/background-blend-mode
*/
"bg-blend": [{
"bg-blend": scaleBlendMode()
}],
/**
* Mask Clip
* @see https://tailwindcss.com/docs/mask-clip
*/
"mask-clip": [{
"mask-clip": ["border", "padding", "content", "fill", "stroke", "view"]
}, "mask-no-clip"],
/**
* Mask Composite
* @see https://tailwindcss.com/docs/mask-composite
*/
"mask-composite": [{
mask: ["add", "subtract", "intersect", "exclude"]
}],
/**
* Mask Image
* @see https://tailwindcss.com/docs/mask-image
*/
"mask-image-linear-pos": [{
"mask-linear": [isNumber]
}],
"mask-image-linear-from-pos": [{
"mask-linear-from": scaleMaskImagePosition()
}],
"mask-image-linear-to-pos": [{
"mask-linear-to": scaleMaskImagePosition()
}],
"mask-image-linear-from-color": [{
"mask-linear-from": scaleColor()
}],
"mask-image-linear-to-color": [{
"mask-linear-to": scaleColor()
}],
"mask-image-t-from-pos": [{
"mask-t-from": scaleMaskImagePosition()
}],
"mask-image-t-to-pos": [{
"mask-t-to": scaleMaskImagePosition()
}],
"mask-image-t-from-color": [{
"mask-t-from": scaleColor()
}],
"mask-image-t-to-color": [{
"mask-t-to": scaleColor()
}],
"mask-image-r-from-pos": [{
"mask-r-from": scaleMaskImagePosition()
}],
"mask-image-r-to-pos": [{
"mask-r-to": scaleMaskImagePosition()
}],
"mask-image-r-from-color": [{
"mask-r-from": scaleColor()
}],
"mask-image-r-to-color": [{
"mask-r-to": scaleColor()
}],
"mask-image-b-from-pos": [{
"mask-b-from": scaleMaskImagePosition()
}],
"mask-image-b-to-pos": [{
"mask-b-to": scaleMaskImagePosition()
}],
"mask-image-b-from-color": [{
"mask-b-from": scaleColor()
}],
"mask-image-b-to-color": [{
"mask-b-to": scaleColor()
}],
"mask-image-l-from-pos": [{
"mask-l-from": scaleMaskImagePosition()
}],
"mask-image-l-to-pos": [{
"mask-l-to": scaleMaskImagePosition()
}],
"mask-image-l-from-color": [{
"mask-l-from": scaleColor()
}],
"mask-image-l-to-color": [{
"mask-l-to": scaleColor()
}],
"mask-image-x-from-pos": [{
"mask-x-from": scaleMaskImagePosition()
}],
"mask-image-x-to-pos": [{
"mask-x-to": scaleMaskImagePosition()
}],
"mask-image-x-from-color": [{
"mask-x-from": scaleColor()
}],
"mask-image-x-to-color": [{
"mask-x-to": scaleColor()
}],
"mask-image-y-from-pos": [{
"mask-y-from": scaleMaskImagePosition()
}],
"mask-image-y-to-pos": [{
"mask-y-to": scaleMaskImagePosition()
}],
"mask-image-y-from-color": [{
"mask-y-from": scaleColor()
}],
"mask-image-y-to-color": [{
"mask-y-to": scaleColor()
}],
"mask-image-radial": [{
"mask-radial": [isArbitraryVariable, isArbitraryValue]
}],
"mask-image-radial-from-pos": [{
"mask-radial-from": scaleMaskImagePosition()
}],
"mask-image-radial-to-pos": [{
"mask-radial-to": scaleMaskImagePosition()
}],
"mask-image-radial-from-color": [{
"mask-radial-from": scaleColor()
}],
"mask-image-radial-to-color": [{
"mask-radial-to": scaleColor()
}],
"mask-image-radial-shape": [{
"mask-radial": ["circle", "ellipse"]
}],
"mask-image-radial-size": [{
"mask-radial": [{
closest: ["side", "corner"],
farthest: ["side", "corner"]
}]
}],
"mask-image-radial-pos": [{
"mask-radial-at": scalePosition()
}],
"mask-image-conic-pos": [{
"mask-conic": [isNumber]
}],
"mask-image-conic-from-pos": [{
"mask-conic-from": scaleMaskImagePosition()
}],
"mask-image-conic-to-pos": [{
"mask-conic-to": scaleMaskImagePosition()
}],
"mask-image-conic-from-color": [{
"mask-conic-from": scaleColor()
}],
"mask-image-conic-to-color": [{
"mask-conic-to": scaleColor()
}],
/**
* Mask Mode
* @see https://tailwindcss.com/docs/mask-mode
*/
"mask-mode": [{
mask: ["alpha", "luminance", "match"]
}],
/**
* Mask Origin
* @see https://tailwindcss.com/docs/mask-origin
*/
"mask-origin": [{
"mask-origin": ["border", "padding", "content", "fill", "stroke", "view"]
}],
/**
* Mask Position
* @see https://tailwindcss.com/docs/mask-position
*/
"mask-position": [{
mask: scaleBgPosition()
}],
/**
* Mask Repeat
* @see https://tailwindcss.com/docs/mask-repeat
*/
"mask-repeat": [{
mask: scaleBgRepeat()
}],
/**
* Mask Size
* @see https://tailwindcss.com/docs/mask-size
*/
"mask-size": [{
mask: scaleBgSize()
}],
/**
* Mask Type
* @see https://tailwindcss.com/docs/mask-type
*/
"mask-type": [{
"mask-type": ["alpha", "luminance"]
}],
/**
* Mask Image
* @see https://tailwindcss.com/docs/mask-image
*/
"mask-image": [{
mask: ["none", isArbitraryVariable, isArbitraryValue]
}],
// ---------------
// --- Filters ---
// ---------------
/**
* Filter
* @see https://tailwindcss.com/docs/filter
*/
filter: [{
filter: [
// Deprecated since Tailwind CSS v3.0.0
"",
"none",
isArbitraryVariable,
isArbitraryValue
]
}],
/**
* Blur
* @see https://tailwindcss.com/docs/blur
*/
blur: [{
blur: scaleBlur()
}],
/**
* Brightness
* @see https://tailwindcss.com/docs/brightness
*/
brightness: [{
brightness: [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Contrast
* @see https://tailwindcss.com/docs/contrast
*/
contrast: [{
contrast: [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Drop Shadow
* @see https://tailwindcss.com/docs/drop-shadow
*/
"drop-shadow": [{
"drop-shadow": [
// Deprecated since Tailwind CSS v4.0.0
"",
"none",
themeDropShadow,
isArbitraryVariableShadow,
isArbitraryShadow
]
}],
/**
* Drop Shadow Color
* @see https://tailwindcss.com/docs/filter-drop-shadow#setting-the-shadow-color
*/
"drop-shadow-color": [{
"drop-shadow": scaleColor()
}],
/**
* Grayscale
* @see https://tailwindcss.com/docs/grayscale
*/
grayscale: [{
grayscale: ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Hue Rotate
* @see https://tailwindcss.com/docs/hue-rotate
*/
"hue-rotate": [{
"hue-rotate": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Invert
* @see https://tailwindcss.com/docs/invert
*/
invert: [{
invert: ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Saturate
* @see https://tailwindcss.com/docs/saturate
*/
saturate: [{
saturate: [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Sepia
* @see https://tailwindcss.com/docs/sepia
*/
sepia: [{
sepia: ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Filter
* @see https://tailwindcss.com/docs/backdrop-filter
*/
"backdrop-filter": [{
"backdrop-filter": [
// Deprecated since Tailwind CSS v3.0.0
"",
"none",
isArbitraryVariable,
isArbitraryValue
]
}],
/**
* Backdrop Blur
* @see https://tailwindcss.com/docs/backdrop-blur
*/
"backdrop-blur": [{
"backdrop-blur": scaleBlur()
}],
/**
* Backdrop Brightness
* @see https://tailwindcss.com/docs/backdrop-brightness
*/
"backdrop-brightness": [{
"backdrop-brightness": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Contrast
* @see https://tailwindcss.com/docs/backdrop-contrast
*/
"backdrop-contrast": [{
"backdrop-contrast": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Grayscale
* @see https://tailwindcss.com/docs/backdrop-grayscale
*/
"backdrop-grayscale": [{
"backdrop-grayscale": ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Hue Rotate
* @see https://tailwindcss.com/docs/backdrop-hue-rotate
*/
"backdrop-hue-rotate": [{
"backdrop-hue-rotate": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Invert
* @see https://tailwindcss.com/docs/backdrop-invert
*/
"backdrop-invert": [{
"backdrop-invert": ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Opacity
* @see https://tailwindcss.com/docs/backdrop-opacity
*/
"backdrop-opacity": [{
"backdrop-opacity": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Saturate
* @see https://tailwindcss.com/docs/backdrop-saturate
*/
"backdrop-saturate": [{
"backdrop-saturate": [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Backdrop Sepia
* @see https://tailwindcss.com/docs/backdrop-sepia
*/
"backdrop-sepia": [{
"backdrop-sepia": ["", isNumber, isArbitraryVariable, isArbitraryValue]
}],
// --------------
// --- Tables ---
// --------------
/**
* Border Collapse
* @see https://tailwindcss.com/docs/border-collapse
*/
"border-collapse": [{
border: ["collapse", "separate"]
}],
/**
* Border Spacing
* @see https://tailwindcss.com/docs/border-spacing
*/
"border-spacing": [{
"border-spacing": scaleUnambiguousSpacing()
}],
/**
* Border Spacing X
* @see https://tailwindcss.com/docs/border-spacing
*/
"border-spacing-x": [{
"border-spacing-x": scaleUnambiguousSpacing()
}],
/**
* Border Spacing Y
* @see https://tailwindcss.com/docs/border-spacing
*/
"border-spacing-y": [{
"border-spacing-y": scaleUnambiguousSpacing()
}],
/**
* Table Layout
* @see https://tailwindcss.com/docs/table-layout
*/
"table-layout": [{
table: ["auto", "fixed"]
}],
/**
* Caption Side
* @see https://tailwindcss.com/docs/caption-side
*/
caption: [{
caption: ["top", "bottom"]
}],
// ---------------------------------
// --- Transitions and Animation ---
// ---------------------------------
/**
* Transition Property
* @see https://tailwindcss.com/docs/transition-property
*/
transition: [{
transition: ["", "all", "colors", "opacity", "shadow", "transform", "none", isArbitraryVariable, isArbitraryValue]
}],
/**
* Transition Behavior
* @see https://tailwindcss.com/docs/transition-behavior
*/
"transition-behavior": [{
transition: ["normal", "discrete"]
}],
/**
* Transition Duration
* @see https://tailwindcss.com/docs/transition-duration
*/
duration: [{
duration: [isNumber, "initial", isArbitraryVariable, isArbitraryValue]
}],
/**
* Transition Timing Function
* @see https://tailwindcss.com/docs/transition-timing-function
*/
ease: [{
ease: ["linear", "initial", themeEase, isArbitraryVariable, isArbitraryValue]
}],
/**
* Transition Delay
* @see https://tailwindcss.com/docs/transition-delay
*/
delay: [{
delay: [isNumber, isArbitraryVariable, isArbitraryValue]
}],
/**
* Animation
* @see https://tailwindcss.com/docs/animation
*/
animate: [{
animate: ["none", themeAnimate, isArbitraryVariable, isArbitraryValue]
}],
// ------------------
// --- Transforms ---
// ------------------
/**
* Backface Visibility
* @see https://tailwindcss.com/docs/backface-visibility
*/
backface: [{
backface: ["hidden", "visible"]
}],
/**
* Perspective
* @see https://tailwindcss.com/docs/perspective
*/
perspective: [{
perspective: [themePerspective, isArbitraryVariable, isArbitraryValue]
}],
/**
* Perspective Origin
* @see https://tailwindcss.com/docs/perspective-origin
*/
"perspective-origin": [{
"perspective-origin": scalePositionWithArbitrary()
}],
/**
* Rotate
* @see https://tailwindcss.com/docs/rotate
*/
rotate: [{
rotate: scaleRotate()
}],
/**
* Rotate X
* @see https://tailwindcss.com/docs/rotate
*/
"rotate-x": [{
"rotate-x": scaleRotate()
}],
/**
* Rotate Y
* @see https://tailwindcss.com/docs/rotate
*/
"rotate-y": [{
"rotate-y": scaleRotate()
}],
/**
* Rotate Z
* @see https://tailwindcss.com/docs/rotate
*/
"rotate-z": [{
"rotate-z": scaleRotate()
}],
/**
* Scale
* @see https://tailwindcss.com/docs/scale
*/
scale: [{
scale: scaleScale()
}],
/**
* Scale X
* @see https://tailwindcss.com/docs/scale
*/
"scale-x": [{
"scale-x": scaleScale()
}],
/**
* Scale Y
* @see https://tailwindcss.com/docs/scale
*/
"scale-y": [{
"scale-y": scaleScale()
}],
/**
* Scale Z
* @see https://tailwindcss.com/docs/scale
*/
"scale-z": [{
"scale-z": scaleScale()
}],
/**
* Scale 3D
* @see https://tailwindcss.com/docs/scale
*/
"scale-3d": ["scale-3d"],
/**
* Skew
* @see https://tailwindcss.com/docs/skew
*/
skew: [{
skew: scaleSkew()
}],
/**
* Skew X
* @see https://tailwindcss.com/docs/skew
*/
"skew-x": [{
"skew-x": scaleSkew()
}],
/**
* Skew Y
* @see https://tailwindcss.com/docs/skew
*/
"skew-y": [{
"skew-y": scaleSkew()
}],
/**
* Transform
* @see https://tailwindcss.com/docs/transform
*/
transform: [{
transform: [isArbitraryVariable, isArbitraryValue, "", "none", "gpu", "cpu"]
}],
/**
* Transform Origin
* @see https://tailwindcss.com/docs/transform-origin
*/
"transform-origin": [{
origin: scalePositionWithArbitrary()
}],
/**
* Transform Style
* @see https://tailwindcss.com/docs/transform-style
*/
"transform-style": [{
transform: ["3d", "flat"]
}],
/**
* Translate
* @see https://tailwindcss.com/docs/translate
*/
translate: [{
translate: scaleTranslate()
}],
/**
* Translate X
* @see https://tailwindcss.com/docs/translate
*/
"translate-x": [{
"translate-x": scaleTranslate()
}],
/**
* Translate Y
* @see https://tailwindcss.com/docs/translate
*/
"translate-y": [{
"translate-y": scaleTranslate()
}],
/**
* Translate Z
* @see https://tailwindcss.com/docs/translate
*/
"translate-z": [{
"translate-z": scaleTranslate()
}],
/**
* Translate None
* @see https://tailwindcss.com/docs/translate
*/
"translate-none": ["translate-none"],
// ---------------------
// --- Interactivity ---
// ---------------------
/**
* Accent Color
* @see https://tailwindcss.com/docs/accent-color
*/
accent: [{
accent: scaleColor()
}],
/**
* Appearance
* @see https://tailwindcss.com/docs/appearance
*/
appearance: [{
appearance: ["none", "auto"]
}],
/**
* Caret Color
* @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities
*/
"caret-color": [{
caret: scaleColor()
}],
/**
* Color Scheme
* @see https://tailwindcss.com/docs/color-scheme
*/
"color-scheme": [{
scheme: ["normal", "dark", "light", "light-dark", "only-dark", "only-light"]
}],
/**
* Cursor
* @see https://tailwindcss.com/docs/cursor
*/
cursor: [{
cursor: ["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none", "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing", "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out", isArbitraryVariable, isArbitraryValue]
}],
/**
* Field Sizing
* @see https://tailwindcss.com/docs/field-sizing
*/
"field-sizing": [{
"field-sizing": ["fixed", "content"]
}],
/**
* Pointer Events
* @see https://tailwindcss.com/docs/pointer-events
*/
"pointer-events": [{
"pointer-events": ["auto", "none"]
}],
/**
* Resize
* @see https://tailwindcss.com/docs/resize
*/
resize: [{
resize: ["none", "", "y", "x"]
}],
/**
* Scroll Behavior
* @see https://tailwindcss.com/docs/scroll-behavior
*/
"scroll-behavior": [{
scroll: ["auto", "smooth"]
}],
/**
* Scroll Margin
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-m": [{
"scroll-m": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin X
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-mx": [{
"scroll-mx": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Y
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-my": [{
"scroll-my": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Start
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-ms": [{
"scroll-ms": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin End
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-me": [{
"scroll-me": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Top
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-mt": [{
"scroll-mt": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Right
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-mr": [{
"scroll-mr": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Bottom
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-mb": [{
"scroll-mb": scaleUnambiguousSpacing()
}],
/**
* Scroll Margin Left
* @see https://tailwindcss.com/docs/scroll-margin
*/
"scroll-ml": [{
"scroll-ml": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-p": [{
"scroll-p": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding X
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-px": [{
"scroll-px": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Y
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-py": [{
"scroll-py": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Start
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-ps": [{
"scroll-ps": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding End
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-pe": [{
"scroll-pe": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Top
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-pt": [{
"scroll-pt": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Right
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-pr": [{
"scroll-pr": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Bottom
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-pb": [{
"scroll-pb": scaleUnambiguousSpacing()
}],
/**
* Scroll Padding Left
* @see https://tailwindcss.com/docs/scroll-padding
*/
"scroll-pl": [{
"scroll-pl": scaleUnambiguousSpacing()
}],
/**
* Scroll Snap Align
* @see https://tailwindcss.com/docs/scroll-snap-align
*/
"snap-align": [{
snap: ["start", "end", "center", "align-none"]
}],
/**
* Scroll Snap Stop
* @see https://tailwindcss.com/docs/scroll-snap-stop
*/
"snap-stop": [{
snap: ["normal", "always"]
}],
/**
* Scroll Snap Type
* @see https://tailwindcss.com/docs/scroll-snap-type
*/
"snap-type": [{
snap: ["none", "x", "y", "both"]
}],
/**
* Scroll Snap Type Strictness
* @see https://tailwindcss.com/docs/scroll-snap-type
*/
"snap-strictness": [{
snap: ["mandatory", "proximity"]
}],
/**
* Touch Action
* @see https://tailwindcss.com/docs/touch-action
*/
touch: [{
touch: ["auto", "none", "manipulation"]
}],
/**
* Touch Action X
* @see https://tailwindcss.com/docs/touch-action
*/
"touch-x": [{
"touch-pan": ["x", "left", "right"]
}],
/**
* Touch Action Y
* @see https://tailwindcss.com/docs/touch-action
*/
"touch-y": [{
"touch-pan": ["y", "up", "down"]
}],
/**
* Touch Action Pinch Zoom
* @see https://tailwindcss.com/docs/touch-action
*/
"touch-pz": ["touch-pinch-zoom"],
/**
* User Select
* @see https://tailwindcss.com/docs/user-select
*/
select: [{
select: ["none", "text", "all", "auto"]
}],
/**
* Will Change
* @see https://tailwindcss.com/docs/will-change
*/
"will-change": [{
"will-change": ["auto", "scroll", "contents", "transform", isArbitraryVariable, isArbitraryValue]
}],
// -----------
// --- SVG ---
// -----------
/**
* Fill
* @see https://tailwindcss.com/docs/fill
*/
fill: [{
fill: ["none", ...scaleColor()]
}],
/**
* Stroke Width
* @see https://tailwindcss.com/docs/stroke-width
*/
"stroke-w": [{
stroke: [isNumber, isArbitraryVariableLength, isArbitraryLength, isArbitraryNumber]
}],
/**
* Stroke
* @see https://tailwindcss.com/docs/stroke
*/
stroke: [{
stroke: ["none", ...scaleColor()]
}],
// ---------------------
// --- Accessibility ---
// ---------------------
/**
* Forced Color Adjust
* @see https://tailwindcss.com/docs/forced-color-adjust
*/
"forced-color-adjust": [{
"forced-color-adjust": ["auto", "none"]
}]
},
conflictingClassGroups: {
overflow: ["overflow-x", "overflow-y"],
overscroll: ["overscroll-x", "overscroll-y"],
inset: ["inset-x", "inset-y", "start", "end", "top", "right", "bottom", "left"],
"inset-x": ["right", "left"],
"inset-y": ["top", "bottom"],
flex: ["basis", "grow", "shrink"],
gap: ["gap-x", "gap-y"],
p: ["px", "py", "ps", "pe", "pt", "pr", "pb", "pl"],
px: ["pr", "pl"],
py: ["pt", "pb"],
m: ["mx", "my", "ms", "me", "mt", "mr", "mb", "ml"],
mx: ["mr", "ml"],
my: ["mt", "mb"],
size: ["w", "h"],
"font-size": ["leading"],
"fvn-normal": ["fvn-ordinal", "fvn-slashed-zero", "fvn-figure", "fvn-spacing", "fvn-fraction"],
"fvn-ordinal": ["fvn-normal"],
"fvn-slashed-zero": ["fvn-normal"],
"fvn-figure": ["fvn-normal"],
"fvn-spacing": ["fvn-normal"],
"fvn-fraction": ["fvn-normal"],
"line-clamp": ["display", "overflow"],
rounded: ["rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"],
"rounded-s": ["rounded-ss", "rounded-es"],
"rounded-e": ["rounded-se", "rounded-ee"],
"rounded-t": ["rounded-tl", "rounded-tr"],
"rounded-r": ["rounded-tr", "rounded-br"],
"rounded-b": ["rounded-br", "rounded-bl"],
"rounded-l": ["rounded-tl", "rounded-bl"],
"border-spacing": ["border-spacing-x", "border-spacing-y"],
"border-w": ["border-w-x", "border-w-y", "border-w-s", "border-w-e", "border-w-t", "border-w-r", "border-w-b", "border-w-l"],
"border-w-x": ["border-w-r", "border-w-l"],
"border-w-y": ["border-w-t", "border-w-b"],
"border-color": ["border-color-x", "border-color-y", "border-color-s", "border-color-e", "border-color-t", "border-color-r", "border-color-b", "border-color-l"],
"border-color-x": ["border-color-r", "border-color-l"],
"border-color-y": ["border-color-t", "border-color-b"],
translate: ["translate-x", "translate-y", "translate-none"],
"translate-none": ["translate", "translate-x", "translate-y", "translate-z"],
"scroll-m": ["scroll-mx", "scroll-my", "scroll-ms", "scroll-me", "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml"],
"scroll-mx": ["scroll-mr", "scroll-ml"],
"scroll-my": ["scroll-mt", "scroll-mb"],
"scroll-p": ["scroll-px", "scroll-py", "scroll-ps", "scroll-pe", "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl"],
"scroll-px": ["scroll-pr", "scroll-pl"],
"scroll-py": ["scroll-pt", "scroll-pb"],
touch: ["touch-x", "touch-y", "touch-pz"],
"touch-x": ["touch"],
"touch-y": ["touch"],
"touch-pz": ["touch"]
},
conflictingClassGroupModifiers: {
"font-size": ["leading"]
},
orderSensitiveModifiers: ["*", "**", "after", "backdrop", "before", "details-content", "file", "first-letter", "first-line", "marker", "placeholder", "selection"]
};
};
const twMerge = /* @__PURE__ */ createTailwindMerge(getDefaultConfig);
function cn(...inputs) {
return twMerge(clsx(inputs));
}
const ProgressBar = ({
progress,
size = "md",
variant = "default",
showPercentage = false,
animated = true,
className,
"aria-label": ariaLabel,
"aria-describedby": ariaDescribedBy
}) => {
const clampedProgress = Math.max(0, Math.min(100, progress));
const sizeClasses = {
sm: "h-1",
md: "h-2",
lg: "h-3"
};
const variantClasses = {
default: "bg-blue-500",
success: "bg-green-500",
error: "bg-red-500",
warning: "bg-yellow-500"
};
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cn("w-full", className), children: [
/* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: cn(
"w-full bg-gray-200 rounded-full overflow-hidden",
sizeClasses[size]
),
role: "progressbar",
"aria-valuenow": clampedProgress,
"aria-valuemin": 0,
"aria-valuemax": 100,
"aria-label": ariaLabel || `Upload progress: ${clampedProgress}%`,
"aria-describedby": ariaDescribedBy,
children: /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: cn(
"h-full rounded-full transition-all duration-300 ease-out",
variantClasses[variant],
animated && "transition-transform"
),
style: { width: `${clampedProgress}%` }
}
)
}
),
showPercentage && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-1 text-xs text-gray-600 text-right", children: [
Math.round(clampedProgress),
"%"
] })
] });
};
const statusConfig = {
pending: {
icon: Clock,
color: "text-gray-500",
bgColor: "bg-gray-100",
text: "Pending"
},
uploading: {
icon: Clock,
color: "text-blue-500",
bgColor: "bg-blue-100",
text: "Uploading"
},
success: {
icon: CircleCheckBig,
color: "text-green-500",
bgColor: "bg-green-100",
text: "Success"
},
error: {
icon: CircleX,
color: "text-red-500",
bgColor: "bg-red-100",
text: "Error"
}
};
const StatusIndicator = ({
status,
size = "md",
showText = false,
className,
"aria-label": ariaLabel
}) => {
const config = statusConfig[status];
const Icon2 = config.icon;
const sizeClasses = {
sm: "w-4 h-4",
md: "w-5 h-5",
lg: "w-6 h-6"
};
const textSizeClasses = {
sm: "text-xs",
md: "text-sm",
lg: "text-base"
};
return /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: cn("flex items-center gap-2", className),
role: "status",
"aria-label": ariaLabel || `File status: ${config.text}`,
children: [
/* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: cn(
"rounded-full p-1 flex items-center justify-center",
config.bgColor
),
children: /* @__PURE__ */ jsxRuntime.jsx(
Icon2,
{
className: cn(
sizeClasses[size],
config.color
),
"aria-hidden": "true"
}
)
}
),
showText && /* @__PURE__ */ jsxRuntime.jsx("span", { className: cn(textSizeClasses[size], config.color), children: config.text })
]
}
);
};
const LoadingSpinner = ({
size = "md",
variant = "default",
className,
"aria-label": ariaLabel
}) => {
const sizeClasses = {
sm: "w-4 h-4",
md: "w-6 h-6",
lg: "w-8 h-8"
};
const variantClasses = {
default: "text-gray-500",
primary: "text-blue-500",
secondary: "text-gray-400"
};
return /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: cn(
"inline-block animate-spin rounded-full border-2 border-solid border-current border-r-transparent",
sizeClasses[size],
variantClasses[variant],
className
),
role: "status",
"aria-label": ariaLabel || "Loading",
children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Loading..." })
}
);
};
const AccessibilityAnnouncer$1 = ({
files,
isUploading,
announceProgress = true,
announceStatus = true,
announceErrors = true,
className
}) => {
const liveRegionRef = React.useRef(null);
const previousFilesRef = React.useRef([]);
const announcementTimeoutRef = React.useRef();
const announce = (message, priority = "polite") => {
if (liveRegionRef.current) {
if (announcementTimeoutRef.current) {
clearTimeout(announcementTimeoutRef.current);
}
liveRegionRef.current.setAttribute("aria-live", priority);
liveRegionRef.current.textContent = "";
announcementTimeoutRef.current = setTimeout(() => {
if (liveRegionRef.current) {
liveRegionRef.current.textContent = message;
}
}, 100);
}
};
React.useEffect(() => {
const previousFiles = previousFilesRef.current;
const currentFiles = files;
if (currentFiles.length > previousFiles.length && announceStatus) {
const newFilesCount = currentFiles.length - previousFiles.length;
announce(
`${newFilesCount} file${newFilesCount === 1 ? "" : "s"} selected for upload`,
"polite"
);
}
if (!previousFiles.some((f) => f.status === "uploading") && currentFiles.some((f) => f.status === "uploading") && announceStatus) {
announce("Upload started", "polite");
}
currentFiles.forEach((currentFile) => {
const previousFile = previousFiles.find((f) => f.id === currentFile.id);
if (previousFile && previousFile.status !== currentFile.status) {
if (currentFile.status === "success" && announceStatus) {
announce(`${currentFile.name} uploaded successfully`, "polite");
} else if (currentFile.status === "error" && announceErrors) {
const errorMessage = currentFile.error || "Upload failed";
announce(`${currentFile.name} upload failed: ${errorMessage}`, "assertive");
}
}
if (previousFile && announceProgress && currentFile.status === "uploading" && currentFile.progress > 0) {
const currentMilestone = Math.floor(currentFile.progress / 25) * 25;
const previousMilestone = Math.floor(previousFile.progress / 25) * 25;
if (currentMilestone > previousMilestone && currentMilestone > 0) {
announce(`${currentFile.name} ${currentMilestone}% uploaded`, "polite");
}
}
});
const allCompleted = currentFiles.length > 0 && currentFiles.every((f) => f.status === "success" || f.status === "error");
const wasUploading = previousFiles.some((f) => f.status === "uploading");
if (allCompleted && wasUploading && announceStatus) {
const successCount = currentFiles.filter((f) => f.status === "success").length;
const errorCount = currentFiles.filter((f) => f.status === "error").length;
if (errorCount === 0) {
announce(`All ${successCount} files uploaded successfully`, "polite");
} else {
announce(
`Upload complete: ${successCount} successful, ${errorCount} failed`,
"assertive"
);
}
}
previousFilesRef.current = [...currentFiles];
}, [files, announceProgress, announceStatus, announceErrors]);
React.useEffect(() => {
return () => {
if (announcementTimeoutRef.current) {
clearTimeout(announcementTimeoutRef.current);
}
};
}, []);
return /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
ref: liveRegionRef,
className,
role: "status",
"aria-live": "polite",
"aria-atomic": "true",
style: {
position: "absolute",
left: "-10000px",
width: "1px",
height: "1px",
overflow: "hidden"
}
}
);
};
const ErrorIcon = ({
severity,
className
}) => {
const iconProps = { className: theme.cn("w-5 h-5 flex-shrink-0", className), "aria-hidden": true };
switch (severity) {
case "critical":
return /* @__PURE__ */ jsxRuntime.jsx(TriangleAlert, { ...iconProps, className: theme.cn(iconProps.className, "text-red-600") });
case "high":
return /* @__PURE__ */ jsxRuntime.jsx(CircleAlert, { ...iconProps, className: theme.cn(iconProps.className, "text-red-500") });
case "medium":
return /* @__PURE__ */ jsxRuntime.jsx(CircleAlert, { ...iconProps, className: theme.cn(iconProps.className, "text-orange-500") });
case "low":
return /* @__PURE__ */ jsxRuntime.jsx(Info, { ...iconProps, className: theme.cn(iconProps.className, "text-blue-500") });
default:
return /* @__PURE__ */ jsxRuntime.jsx(CircleAlert, { ...iconProps, className: theme.cn(iconProps.className, "text-gray-500") });
}
};
const ErrorActionButton = ({ action, error, onAction, compact }) => {
const handleClick = React.useCallback(() => {
if (action.handler) {
action.handler();
} else {
onAction(action, error);
}
}, [action, error, onAction]);
const getActionIcon = () => {
switch (action.type) {
case "retry":
return /* @__PURE__ */ jsxRuntime.jsx(RefreshCw, { className: "w-4 h-4" });
case "remove":
case "clear":
return /* @__PURE__ */ jsxRuntime.jsx(Trash2, { className: "w-4 h-4" });
case "contact":
return /* @__PURE__ */ jsxRuntime.jsx(CircleQuestionMark, { className: "w-4 h-4" });
default:
return null;
}
};
const getButtonClasses = () => {
const baseClasses = [
"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md",
"focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors duration-200",
action.disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
];
if (compact) {
baseClasses.push("px-2 py-1 text-xs");
}
if (action.primary) {
baseClasses.push(
"text-white bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",
action.disabled ? "" : "hover:bg-blue-700"
);
} else {
baseClasses.push(
"text-gray-700 bg-gray-100 border border-gray-300 hover:bg-gray-200 focus:ring-gray-500",
action.disabled ? "" : "hover:bg-gray-200"
);
}
return theme.cn(...baseClasses);
};
return /* @__PURE__ */ jsxRuntime.jsxs(
"button",
{
type: "button",
onClick: handleClick,
disabled: action.disabled,
className: getButtonClasses(),
"aria-label": `${action.label} for ${error.context.fileName || "file"}`,
children: [
getActionIcon(),
action.label
]
}
);
};
const SingleErrorDisplay = ({ error, onAction, onDismiss, compact, showTechnicalDetails }) => {
const getSeverityClasses = () => {
switch (error.severity) {
case "critical":
return "border-red-300 bg-red-50 text-red-900";
case "high":
return "border-red-200 bg-red-50 text-red-800";
case "medium":
return "border-orange-200 bg-orange-50 text-orange-800";
case "low":
return "border-blue-200 bg-blue-50 text-blue-800";
default:
return "border-gray-200 bg-gray-50 text-gray-800";
}
};
const containerClasses = theme.cn(
"border rounded-lg p-4 space-y-3",
getSeverityClasses(),
compact && "p-3 space-y-2"
);
return /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: containerClasses,
role: "alert",
"aria-live": "polite",
"aria-labelledby": `error-title-${error.id}`,
"aria-describedby": `error-description-${error.id}`,
children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
/* @__PURE__ */ jsxRuntime.jsx(ErrorIcon, { severity: error.severity }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"h4",
{
id: `error-title-${error.id}`,
className: theme.cn(
"font-medium",
compact ? "text-sm" : "text-base"
),
children: error.title
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"p",
{
id: `error-description-${error.id}`,
className: theme.cn(
"mt-1 text-sm",
compact ? "text-xs" : "text-sm"
),
children: utils.formatErrorForUser(error, true)
}
),
error.suggestions.length > 0 && !compact && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-2", children: [
/* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium mb-1", children: "Suggestions:" }),
/* @__PURE__ */ jsxRuntime.jsx("ul", { className: "text-sm space-y-1 list-disc list-inside", children: error.suggestions.map((suggestion, index) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: suggestion }, index)) })
] }),
showTechnicalDetails && /* @__PURE__ */ jsxRuntime.jsxs("details", { className: "mt-3", children: [
/* @__PURE__ */ jsxRuntime.jsx("summary", { className: "text-sm font-medium cursor-pointer hover:underline", children: "Technical Details" }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-2 p-2 bg-gray-100 rounded text-xs font-mono overflow-auto", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Error ID:" }),
" ",
error.id
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Code:" }),
" ",
error.code
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Type:" }),
" ",
error.type
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Message:" }),
" ",
error.technicalMessage
] }),
error.context.timestamp && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Time:" }),
" ",
error.context.timestamp.toISOString()
] }),
error.context.fileName && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "File:" }),
" ",
error.context.fileName
] }),
error.context.fileSize && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
/* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Size:" }),
" ",
error.context.fileSize,
" bytes"
] })
] })
] })
] }),
onDismiss && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => onDismiss(error.id),
className: "text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 rounded",
"aria-label": "Dismiss error",
children: /* @__PURE__ */ jsxRuntime.jsx(X, { className: "w-4 h-4" })
}
)
] }),
error.actions.length > 0 && onAction && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-2 pt-2", children: error.actions.map((action) => /* @__PURE__ */ jsxRuntime.jsx(
ErrorActionButton,
{
action,
error,
onAction,
compact
},
action.id
)) })
]
}
);
};
const ErrorDisplay = ({
errors,
onAction,
onDismiss,
onDismissAll,
className,
compact = false,
showTechnicalDetails = false,
maxErrors = 5,
groupByType = false
}) => {
const displayErrors = React.useMemo(() => {
if (errors.length <= maxErrors) {
return errors;
}
return errors.slice(0, maxErrors);
}, [errors, maxErrors]);
const groupedErrors = React.useMemo(() => {
if (!groupByType) {
return { ungrouped: displayErrors };
}
return displayErrors.reduce((groups, error) => {
const key = error.type;
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(error);
return groups;
}, {});
}, [displayErrors, groupByType]);
const hasMoreErrors = errors.length > maxErrors;
if (errors.length === 0) {
return null;
}
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: theme.cn("space-y-4", className), role: "region", "aria-label": "Error messages", children: [
errors.length > 1 && onDismissAll && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
/* @__PURE__ */ jsxRuntime.jsxs("h3", { className: "text-lg font-medium text-gray-900", children: [
errors.length,
" Error",
errors.length !== 1 ? "s" : "",
" Occurred"
] }),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: onDismissAll,
className: "text-sm text-gray-500 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 rounded",
children: "Dismiss All"
}
)
] }),
Object.entries(groupedErrors).map(([groupKey, groupErrors]) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
groupByType && groupKey !== "ungrouped" && /* @__PURE__ */ jsxRuntime.jsxs("h4", { className: "text-md font-medium text-gray-800 capitalize", children: [
groupKey.replace("-", " "),
" Errors (",
groupErrors.length,
")"
] }),
groupErrors.map((error) => /* @__PURE__ */ jsxRuntime.jsx(
SingleErrorDisplay,
{
error,
onAction,
onDismiss,
compact,
showTechnicalDetails
},
error.id
))
] }, groupKey)),
hasMoreErrors && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-center py-2", children: /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-sm text-gray-500", children: [
"Showing ",
maxErrors,
" of ",
errors.length,
" errors"
] }) })
] });
};
ErrorDisplay.displayName = "ErrorDisplay";
const AccessibilityAnnouncer = ({
errors = [],
announceErrors = true,
announceProgress = true,
announceFileSelection = true,
politeAnnouncements = false,
className = ""
}) => {
const [announcements, setAnnouncements] = React.useState([]);
const [currentAnnouncement, setCurrentAnnouncement] = React.useState("");
const announcementTimeoutRef = React.useRef();
const processedErrorsRef = React.useRef(/* @__PURE__ */ new Set());
React.useEffect(() => {
if (!announceErrors || errors.length === 0) return;
const newErrors = errors.filter(
(error) => !processedErrorsRef.current.has(error.id) && utils.shouldAnnounceError(error)
);
if (newErrors.length === 0) return;
const newAnnouncements = newErrors.map((error) => ({
id: `error-${error.id}`,
message: utils.createErrorAnnouncement(error),
priority: error.severity === "critical" || error.severity === "high" ? "assertive" : "polite",
timestamp: /* @__PURE__ */ new Date()
}));
newErrors.forEach((error) => {
processedErrorsRef.current.add(error.id);
});
setAnnouncements((prev) => [...prev, ...newAnnouncements]);
}, [errors, announceErrors]);
React.useEffect(() => {
if (announcements.length === 0) return;
const processNextAnnouncement = () => {
const nextAnnouncement = announcements[0];
if (!nextAnnouncement) return;
setCurrentAnnouncement(nextAnnouncement.message);
setAnnouncements((prev) => prev.slice(1));
announcementTimeoutRef.current = setTimeout(() => {
setCurrentAnnouncement("");
}, 1e3);
};
if (!currentAnnouncement) {
processNextAnnouncement();
} else {
const timeout = setTimeout(processNextAnnouncement, 1500);
return () => clearTimeout(timeout);
}
}, [announcements, currentAnnouncement]);
React.useEffect(() => {
return () => {
if (announcementTimeoutRef.current) {
clearTimeout(announcementTimeoutRef.current);
}
};
}, []);
const announce = React.useCallback((message, priority = "polite") => {
const announcement = {
id: `custom-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
message,
priority,
timestamp: /* @__PURE__ */ new Date()
};
setAnnouncements((prev) => [...prev, announcement]);
}, []);
React.useImperativeHandle(React.forwardRef(() => null), () => ({
announce
}));
const liveRegionProps = {
"aria-live": politeAnnouncements ? "polite" : "assertive",
"aria-atomic": true,
role: "status",
className: `sr-only ${className}`.trim()
};
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { ...liveRegionProps, children: currentAnnouncement }),
/* @__PURE__ */ jsxRuntime.jsx(
"div",
{
"aria-live": "polite",
"aria-atomic": "true",
role: "status",
className: "sr-only"
}
)
] });
};
AccessibilityAnnouncer.displayName = "AccessibilityAnnouncer";
const ErrorFeedback = ({
className,
compact = false,
showTechnicalDetails = false,
maxErrors = 5,
groupByType = false,
showAccessibilityAnnouncer = true
}) => {
const { processedErrors, actions, config } = useFileUpload();
const handleErrorAction = React.useCallback((action, error) => {
switch (action.type) {
case "retry":
if (error.context.fileName) {
const fileToRetry = actions.state?.files.find((f) => f.name === error.context.fileName);
if (fileToRetry) {
actions.retryUpload(fileToRetry.id);
}
} else {
actions.retryFailedUploads();
}
actions.dismissError(error.id);
break;
case "remove":
if (error.context.fileName) {
const fileToRemove = actions.state?.files.find((f) => f.name === error.context.fileName);
if (fileToRemove) {
actions.removeFile(fileToRemove.id);
}
}
actions.dismissError(error.id);
break;
case "clear":
actions.clearFailedUploads();
actions.dismissAllErrors();
break;
case "refresh":
window.location.reload();
break;
case "contact":
console.log("Contact support for error:", error.id);
break;
default:
if (action.handler) {
action.handler();
}
break;
}
}, [actions]);
const handleDismissError = React.useCallback((errorId) => {
actions.dismissError(errorId);
}, [actions]);
const handleDismissAllErrors = React.useCallback(() => {
actions.dismissAllErrors();
}, [actions]);
if (processedErrors.length === 0) {
return showAccessibilityAnnouncer ? /* @__PURE__ */ jsxRuntime.jsx(
AccessibilityAnnouncer,
{
errors: processedErrors,
announceErrors: config.accessibility.announceErrors,
announceProgress: config.accessibility.announceProgress,
announceFileSelection: config.accessibility.announceFileSelection
}
) : null;
}
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: theme.cn("error-feedback-container", className), children: [
showAccessibilityAnnouncer && /* @__PURE__ */ jsxRuntime.jsx(
AccessibilityAnnouncer,
{
errors: processedErrors,
announceErrors: config.accessibility.announceErrors,
announceProgress: config.accessibility.announceProgress,
announceFileSelection: config.accessibility.announceFileSelection
}
),
/* @__PURE__ */ jsxRuntime.jsx(
ErrorDisplay,
{
errors: processedErrors,
onAction: handleErrorAction,
onDismiss: handleDismissError,
onDismissAll: handleDismissAllErrors,
compact,
showTechnicalDetails,
maxErrors,
groupByType
}
)
] });
};
ErrorFeedback.displayName = "ErrorFeedback";
const UploadFeedback = ({
files = [],
isUploading,
showIndividualProgress = true,
showOverallProgress = true,
showStatusIndicators = true,
showFileNames = true,
enableAccessibilityAnnouncements = true,
showErrorFeedback = true,
showAccessibilityAnnouncer = true,
layout = "default",
progressSize = "md",
statusSize = "md",
maxVisibleFiles = 10,
className,
onRetry,
onRemove
}) => {
if (!files || files.length === 0) {
return null;
}
const totalProgress = files.reduce((sum, file) => sum + file.progress, 0);
const overallProgress = files.length > 0 ? totalProgress / files.length : 0;
const completedFiles = files.filter((f) => f.status === "success").length;
const failedFiles = files.filter((f) => f.status === "error").length;
const uploadingFiles = files.filter((f) => f.status === "uploading").length;
const overallStatus = failedFiles > 0 && !isUploading ? "error" : completedFiles === files.length && files.length > 0 ? "success" : "default";
const visibleFiles = files.slice(0, maxVisibleFiles);
const hiddenFilesCount = Math.max(0, files.length - maxVisibleFiles);
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: theme.cn("space-y-4", className), children: [
showErrorFeedback && /* @__PURE__ */ jsxRuntime.jsx(
ErrorFeedback,
{
compact: layout === "compact",
showAccessibilityAnnouncer
}
),
enableAccessibilityAnnouncements && /* @__PURE__ */ jsxRuntime.jsx(
AccessibilityAnnouncer$1,
{
files,
isUploading,
announceProgress: true,
announceStatus: true,
announceErrors: true
}
),
showOverallProgress && files.length > 1 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
isUploading && /* @__PURE__ */ jsxRuntime.jsx(LoadingSpinner, { size: "sm" }),
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: isUploading ? "Uploading files..." : "Upload complete" })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-gray-600", children: [
completedFiles,
"/",
files.length,
" files"
] })
] }),
/* @__PURE__ */ jsxRuntime.jsx(
ProgressBar,
{
progress: overallProgress,
variant: overallStatus,
showPercentage: true,
"aria-label": `Overall upload progress: ${Math.round(overallProgress)}%`
}
),
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-between text-xs text-gray-600", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-4", children: [
completedFiles > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-green-600", children: [
"✓ ",
completedFiles,
" completed"
] }),
uploadingFiles > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-blue-600", children: [
"↑ ",
uploadingFiles,
" uploading"
] }),
failedFiles > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-red-600", children: [
"✗ ",
failedFiles,
" failed"
] })
] }) })
] }),
showIndividualProgress && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
visibleFiles.map((file) => /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: "flex items-center gap-3 p-3 bg-gray-50 rounded-lg",
children: [
showStatusIndicators && /* @__PURE__ */ jsxRuntime.jsx(
StatusIndicator,
{
status: file.status,
size: "sm",
"aria-label": `${file.name} status: ${file.status}`
}
),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
showFileNames && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between mb-1", children: [
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium truncate", children: file.name }),
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-gray-500 ml-2", children: [
(file.size / 1024 / 1024).toFixed(1),
" MB"
] })
] }),
(file.status === "uploading" || file.progress > 0) && /* @__PURE__ */ jsxRuntime.jsx(
ProgressBar,
{
progress: file.progress,
size: "sm",
variant: file.status === "error" ? "error" : file.status === "success" ? "success" : "default",
showPercentage: file.status === "uploading",
"aria-label": `${file.name} upload progress: ${file.progress}%`
}
),
file.status === "error" && file.error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-1 text-xs text-red-600", children: file.error })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
file.status === "error" && onRetry && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
onClick: () => onRetry(file.id),
className: "text-xs text-blue-600 hover:text-blue-800 px-2 py-1 rounded border border-blue-200 hover:border-blue-300",
"aria-label": `Retry upload for ${file.name}`,
children: "Retry"
}
),
onRemove && file.status !== "uploading" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
onClick: () => onRemove(file.id),
className: "text-xs text-gray-600 hover:text-red-600 px-2 py-1 rounded border border-gray-200 hover:border-red-300",
"aria-label": `Remove ${file.name}`,
children: "Remove"
}
)
] })
]
},
file.id
)),
hiddenFilesCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "text-center text-sm text-gray-600 py-2", children: [
"... and ",
hiddenFilesCount,
" more file",
hiddenFilesCount === 1 ? "" : "s"
] })
] })
] });
};
const ButtonUpload = ({
className = "",
style,
ariaLabel,
ariaDescribedBy,
children,
buttonText,
icon,
iconPosition = "left",
asChild = false,
disabled: propDisabled,
multiple: propMultiple,
accept: propAccept,
maxSize: propMaxSize,
maxFiles: propMaxFiles,
onFileSelect,
onError,
...props
}) => {
const { config, actions, state } = useFileUpload();
const inputRef = React.useRef(null);
const disabled = propDisabled ?? config.defaults.disabled ?? false;
const multiple = propMultiple ?? config.defaults.multiple ?? false;
const accept = propAccept ?? config.defaults.accept ?? "*";
const maxSize = propMaxSize ?? config.validation.maxSize;
const maxFiles = propMaxFiles ?? config.validation.maxFiles;
const handleFileSelect = React.useCallback(async (event) => {
const files = Array.from(event.target.files || []);
if (files.length === 0) return;
try {
const validationResult = await utils.validateFiles(files, {
...config,
validation: {
...config.validation,
maxSize,
maxFiles,
allowedTypes: accept === "*" ? ["*"] : accept.split(",").map((t) => t.trim())
}
}, state.files.length);
if (validationResult.validFiles.length > 0) {
actions.selectFiles(validationResult.validFiles);
onFileSelect?.(validationResult.validFiles);
}
if (validationResult.rejectedFiles.length > 0) {
const errorMessage = validationResult.rejectedFiles.map((rf) => `${rf.file.name}: ${rf.errors.map((e) => e.message).join(", ")}`).join("\n");
onError?.(errorMessage);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "File validation failed";
onError?.(errorMessage);
}
event.target.value = "";
}, [config, maxSize, maxFiles, accept, state.files.length, actions, onFileSelect, onError]);
const handleButtonClick = React.useCallback(() => {
if (disabled || state.isUploading) return;
inputRef.current?.click();
}, [disabled, state.isUploading]);
const handleKeyDown = React.useCallback((event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleButtonClick();
}
}, [handleButtonClick]);
const getButtonClasses = () => {
const themeClasses = theme.generateThemeClasses(
"button",
config.defaults.size,
config.defaults.radius,
config,
["file-upload--primary"]
);
const additionalClasses = [
"inline-flex items-center justify-center gap-2",
disabled || state.isUploading ? "file-upload--disabled" : "",
state.isUploading ? "file-upload--loading" : ""
];
return theme.cn(themeClasses, ...additionalClasses, className);
};
const renderButtonContent = () => {
const text = buttonText || children || config.labels.selectFilesText;
const showIcon = icon && !state.isUploading;
const showCount = state.files.length > 0;
if (state.isUploading) {
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
/* @__PURE__ */ jsxRuntime.jsx(LoadingSpinner, { size: "sm", color: "primary" }),
config.labels.progressText
] });
}
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
showIcon && iconPosition === "left" && icon,
/* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
text,
showCount && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 text-xs opacity-75", children: [
"(",
state.files.length,
" ",
state.files.length === 1 ? "file" : "files",
")"
] })
] }),
showIcon && iconPosition === "right" && icon
] });
};
const buttonProps = {
type: "button",
className: getButtonClasses(),
onClick: handleButtonClick,
onKeyDown: handleKeyDown,
disabled: disabled || state.isUploading,
"aria-label": ariaLabel || config.labels.selectFilesText,
"aria-describedby": ariaDescribedBy,
"aria-pressed": state.files.length > 0,
style,
...props
};
const Comp = asChild ? Slot : "button";
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-button-container", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"input",
{
ref: inputRef,
type: "file",
multiple,
accept,
disabled: disabled || state.isUploading,
onChange: handleFileSelect,
className: "sr-only",
"aria-hidden": "true",
tabIndex: -1
}
),
/* @__PURE__ */ jsxRuntime.jsx(Comp, { ...buttonProps, children: renderButtonContent() }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntime.jsx(
UploadFeedback,
{
showOverallProgress: true,
showIndividualProgress: false,
showStatusIndicator: true,
showAccessibilityAnnouncer: true,
layout: "compact",
progressSize: "sm",
statusSize: "sm"
}
) }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-4 space-y-2", role: "list", "aria-label": "Selected files", children: [
state.files.map((file) => /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: theme.cn(
"flex items-center justify-between",
"file-upload--sm",
"file-upload--radius-md",
"border border-[var(--file-upload-border)]",
"bg-[var(--file-upload-background)]",
"text-[var(--file-upload-foreground)]"
),
role: "listitem",
children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
/* @__PURE__ */ jsxRuntime.jsx("p", { className: "font-medium truncate", style: { fontSize: "var(--file-upload-font-size-sm)" }, children: file.name }),
/* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-[var(--file-upload-muted)]", style: { fontSize: "var(--file-upload-font-size-sm)" }, children: [
(file.size / 1024 / 1024).toFixed(2),
" MB"
] })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 ml-4", children: [
/* @__PURE__ */ jsxRuntime.jsx(
StatusIndicator,
{
status: file.status,
size: "sm",
showText: false
}
),
file.status === "uploading" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-16", children: /* @__PURE__ */ jsxRuntime.jsx(
ProgressBar,
{
file,
size: "sm",
showLabel: false,
showPercentage: false
}
) }),
file.status === "pending" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.removeFile(file.id),
className: theme.cn(
theme.generateThemeClasses("button", "sm", "sm", config, ["file-upload--error", "file-upload--outline"])
),
"aria-label": `Remove ${file.name}`,
children: config.labels.removeText
}
),
file.status === "error" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.retryUpload(file.id),
className: theme.cn(
theme.generateThemeClasses("button", "sm", "sm", config, ["file-upload--error", "file-upload--outline"])
),
"aria-label": `Retry upload for ${file.name}`,
children: config.labels.retryText
}
)
] })
]
},
file.id
)),
state.files.some((f) => f.status === "pending") && !config.features.autoUpload && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: actions.uploadFiles,
disabled: state.isUploading,
className: theme.cn(
theme.generateThemeClasses("button", "md", config.defaults.radius, config, ["file-upload--success"]),
"w-full mt-3",
state.isUploading ? "file-upload--disabled" : ""
),
children: state.isUploading ? config.labels.progressText : "Upload Files"
}
)
] })
] });
};
ButtonUpload.displayName = "ButtonUpload";
const DropzoneUpload = ({
className,
style,
ariaLabel,
ariaDescribedBy,
onDragEnter,
onDragLeave,
onDragOver,
onDrop,
children,
height = "200px",
showBorder = true,
dropzoneText,
activeDropzoneText
}) => {
const { config, actions, state } = useFileUpload();
const inputRef = React.useRef(null);
const dropzoneRef = React.useRef(null);
const [isDragOver, setIsDragOver] = React.useState(false);
const [dragCounter, setDragCounter] = React.useState(0);
const [isFocused, setIsFocused] = React.useState(false);
const handleFileSelect = React.useCallback((event) => {
const files = Array.from(event.target.files || []);
if (files.length > 0) {
actions.selectFiles(files);
}
event.target.value = "";
}, [actions]);
const handleClick = React.useCallback(() => {
if (!config.defaults.disabled && !state.isUploading) {
inputRef.current?.click();
}
}, [config.defaults.disabled, state.isUploading]);
const handleKeyDown = React.useCallback((event) => {
if (config.defaults.disabled || state.isUploading) return;
switch (event.key) {
case "Enter":
case " ":
event.preventDefault();
handleClick();
break;
case "Escape":
if (isDragOver) {
event.preventDefault();
setIsDragOver(false);
setDragCounter(0);
}
break;
}
}, [config.defaults.disabled, state.isUploading, handleClick, isDragOver]);
const handleFocus = React.useCallback(() => {
setIsFocused(true);
}, []);
const handleBlur = React.useCallback(() => {
setIsFocused(false);
}, []);
const handleDragEnter = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
if (config.defaults.disabled || state.isUploading || !config.features.dragAndDrop) {
return;
}
setDragCounter((prev) => prev + 1);
if (dragCounter === 0) {
setIsDragOver(true);
}
onDragEnter?.(event);
}, [config.defaults.disabled, state.isUploading, config.features.dragAndDrop, dragCounter, onDragEnter]);
const handleDragLeave = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
if (config.defaults.disabled || state.isUploading || !config.features.dragAndDrop) {
return;
}
setDragCounter((prev) => {
const newCounter = prev - 1;
if (newCounter === 0) {
setIsDragOver(false);
}
return newCounter;
});
onDragLeave?.(event);
}, [config.defaults.disabled, state.isUploading, config.features.dragAndDrop, onDragLeave]);
const handleDragOver = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
if (config.defaults.disabled || state.isUploading || !config.features.dragAndDrop) {
return;
}
event.dataTransfer.dropEffect = "copy";
onDragOver?.(event);
}, [config.defaults.disabled, state.isUploading, config.features.dragAndDrop, onDragOver]);
const handleDrop = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
if (config.defaults.disabled || state.isUploading || !config.features.dragAndDrop) {
return;
}
setIsDragOver(false);
setDragCounter(0);
const files = Array.from(event.dataTransfer.files);
if (files.length > 0) {
actions.selectFiles(files);
}
onDrop?.(event);
}, [config.defaults.disabled, state.isUploading, config.features.dragAndDrop, actions, onDrop]);
React.useEffect(() => {
if (config.defaults.disabled || state.isUploading) {
setIsDragOver(false);
setDragCounter(0);
}
}, [config.defaults.disabled, state.isUploading]);
const isDisabled = config.defaults.disabled || state.isUploading;
const isActive = isDragOver && !isDisabled;
const hasFocus = isFocused && !isDisabled;
const dropzoneClasses = [
"file-upload-dropzone",
`file-upload-dropzone--${config.defaults.size}`,
`file-upload-dropzone--${config.defaults.radius}`,
isDisabled ? "file-upload-dropzone--disabled" : "",
state.isUploading ? "file-upload-dropzone--uploading" : "",
isActive ? "file-upload-dropzone--drag-over" : "",
hasFocus ? "file-upload-dropzone--focused" : "",
className || ""
].filter(Boolean).join(" ");
const dropzoneStyle = {
border: showBorder ? `2px ${config.styling.borders.style} ${isActive ? config.styling.colors.primary : hasFocus ? config.styling.colors.primary : config.styling.colors.border}` : "none",
borderRadius: config.styling.spacing.borderRadius,
padding: "2rem",
textAlign: "center",
cursor: isDisabled ? "not-allowed" : "pointer",
backgroundColor: isActive ? `${config.styling.colors.primary}15` : hasFocus ? `${config.styling.colors.primary}08` : config.styling.colors.background,
color: config.styling.colors.foreground,
fontSize: config.styling.typography.fontSize,
transition: config.animations.enabled ? `all ${config.animations.duration}ms ${config.animations.easing}` : "none",
opacity: isDisabled ? 0.6 : 1,
minHeight: typeof height === "number" ? `${height}px` : height,
height: typeof height === "number" ? `${height}px` : height,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: config.styling.spacing.gap,
outline: hasFocus ? `2px solid ${config.styling.colors.primary}` : "none",
outlineOffset: "2px",
boxShadow: isActive ? config.styling.shadows.md : hasFocus ? config.styling.shadows.sm : "none",
...style
};
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload file-upload--dropzone", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"input",
{
ref: inputRef,
type: "file",
multiple: config.defaults.multiple,
accept: config.defaults.accept,
disabled: isDisabled,
onChange: handleFileSelect,
className: "sr-only",
"aria-hidden": "true",
tabIndex: -1
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"div",
{
ref: dropzoneRef,
className: dropzoneClasses,
onClick: handleClick,
onKeyDown: handleKeyDown,
onFocus: handleFocus,
onBlur: handleBlur,
onDragEnter: config.features.dragAndDrop ? handleDragEnter : void 0,
onDragLeave: config.features.dragAndDrop ? handleDragLeave : void 0,
onDragOver: config.features.dragAndDrop ? handleDragOver : void 0,
onDrop: config.features.dragAndDrop ? handleDrop : void 0,
role: "button",
tabIndex: isDisabled ? -1 : 0,
"aria-label": ariaLabel || (isActive ? activeDropzoneText || config.labels.dropText : dropzoneText || config.labels.dragText),
"aria-describedby": ariaDescribedBy,
"aria-disabled": isDisabled,
"aria-pressed": state.files.length > 0,
style: dropzoneStyle,
children: children || /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-dropzone-icon", style: {
fontSize: "2rem",
color: isDragOver ? config.styling.colors.primary : config.styling.colors.muted
}, children: "📁" }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-dropzone-text", children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-dropzone-primary-text", style: {
fontWeight: "600",
marginBottom: "0.5rem",
color: isDragOver ? config.styling.colors.primary : config.styling.colors.foreground
}, children: isDragOver ? config.labels.dropText : config.labels.dragText }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-dropzone-secondary-text", style: {
fontSize: "0.875rem",
color: config.styling.colors.muted
}, children: [
"or ",
/* @__PURE__ */ jsxRuntime.jsx("span", { style: { color: config.styling.colors.primary, textDecoration: "underline" }, children: config.labels.browseText }),
" to choose files"
] })
] }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-dropzone-count", style: {
fontSize: "0.875rem",
color: config.styling.colors.primary,
fontWeight: "500"
}, children: [
state.files.length,
" ",
state.files.length === 1 ? "file" : "files",
" selected"
] })
] })
}
),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { style: { marginTop: config.styling.spacing.margin }, children: /* @__PURE__ */ jsxRuntime.jsx(
UploadFeedback,
{
showOverallProgress: true,
showIndividualProgress: false,
showStatusIndicator: true,
showAccessibilityAnnouncer: true,
layout: "vertical",
progressSize: "md",
statusSize: "sm"
}
) }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-files", style: { marginTop: config.styling.spacing.margin }, children: [
state.files.map((file) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-file-item", style: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "0.75rem",
border: `1px solid ${config.styling.colors.border}`,
borderRadius: config.styling.spacing.borderRadius,
marginBottom: "0.5rem",
backgroundColor: config.styling.colors.background
}, children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-file-info", children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-file-name", style: {
fontWeight: "500",
color: config.styling.colors.foreground
}, children: file.name }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-file-size", style: {
fontSize: "0.75rem",
color: config.styling.colors.muted
}, children: [
(file.size / 1024).toFixed(1),
" KB"
] })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-file-actions", style: {
display: "flex",
alignItems: "center",
gap: "0.5rem"
}, children: [
/* @__PURE__ */ jsxRuntime.jsx(
StatusIndicator,
{
status: file.status,
size: "sm",
showText: false
}
),
file.status === "uploading" && /* @__PURE__ */ jsxRuntime.jsx("div", { style: { width: "60px" }, children: /* @__PURE__ */ jsxRuntime.jsx(
ProgressBar,
{
file,
size: "sm",
showLabel: false,
showPercentage: true
}
) }),
file.status === "error" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.retryUpload(file.id),
className: "file-upload-retry-button",
style: {
background: "none",
border: `1px solid ${config.styling.colors.error}`,
color: config.styling.colors.error,
cursor: "pointer",
fontSize: "0.75rem",
padding: "0.25rem 0.5rem",
borderRadius: "0.25rem"
},
"aria-label": `${config.labels.retryText} ${file.name}`,
children: config.labels.retryText
}
),
file.status === "pending" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.removeFile(file.id),
className: "file-upload-remove-button",
style: {
background: "none",
border: "none",
color: config.styling.colors.error,
cursor: "pointer",
fontSize: "1.25rem",
padding: "0.25rem"
},
"aria-label": `${config.labels.removeText} ${file.name}`,
children: "×"
}
)
] })
] }, file.id)),
state.files.some((f) => f.status === "pending") && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: actions.uploadFiles,
disabled: state.isUploading,
className: "file-upload-upload-button",
style: {
backgroundColor: config.styling.colors.primary,
color: config.styling.colors.background,
padding: "0.75rem 1.5rem",
border: "none",
borderRadius: config.styling.spacing.borderRadius,
cursor: state.isUploading ? "not-allowed" : "pointer",
opacity: state.isUploading ? 0.6 : 1,
fontSize: config.styling.typography.fontSize,
fontWeight: "500",
width: "100%",
marginTop: "1rem"
},
children: state.isUploading ? config.labels.progressText : "Upload Files"
}
)
] })
] });
};
DropzoneUpload.displayName = "DropzoneUpload";
const PreviewUpload = ({
className = "",
style,
ariaLabel,
ariaDescribedBy,
children,
previewSize = "md",
showFileInfo = true,
allowReorder = false,
disabled: propDisabled,
multiple: propMultiple,
accept: propAccept,
maxSize: propMaxSize,
maxFiles: propMaxFiles,
onFileSelect,
onError,
onFileRemove
}) => {
const { config, actions, state } = useFileUpload();
const inputRef = React.useRef(null);
const [previews, setPreviews] = React.useState(/* @__PURE__ */ new Map());
const [focusedFileIndex, setFocusedFileIndex] = React.useState(-1);
const disabled = propDisabled ?? config.defaults.disabled ?? false;
const multiple = propMultiple ?? config.defaults.multiple ?? false;
const accept = propAccept ?? config.defaults.accept ?? "*";
const maxSize = propMaxSize ?? config.validation.maxSize;
const maxFiles = propMaxFiles ?? config.validation.maxFiles;
const generateImageThumbnail = React.useCallback(async (file) => {
return new Promise((resolve, reject) => {
if (!utils.isImageFile(file)) {
reject(new Error("Not an image file"));
return;
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
const maxDimension = previewSize === "sm" ? 80 : previewSize === "lg" ? 200 : 120;
let { width, height } = img;
if (width > height) {
if (width > maxDimension) {
height = height * maxDimension / width;
width = maxDimension;
}
} else {
if (height > maxDimension) {
width = width * maxDimension / height;
height = maxDimension;
}
}
canvas.width = width;
canvas.height = height;
if (ctx) {
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL("image/jpeg", 0.8));
} else {
reject(new Error("Could not get canvas context"));
}
URL.revokeObjectURL(img.src);
};
img.onerror = () => {
URL.revokeObjectURL(img.src);
reject(new Error("Failed to load image"));
};
img.src = URL.createObjectURL(file);
});
}, [previewSize]);
const generateFilePreview = React.useCallback(async (file) => {
if (utils.isImageFile(file)) {
try {
const thumbnailUrl = await generateImageThumbnail(file);
return {
id: `preview_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
url: thumbnailUrl,
type: "image"
};
} catch (error) {
console.warn("Failed to generate thumbnail:", error);
return {
id: `preview_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
url: getFileIcon(file),
type: "icon"
};
}
} else {
return {
id: `preview_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
url: getFileIcon(file),
type: "icon"
};
}
}, [generateImageThumbnail]);
const getFileIcon = React.useCallback((file) => {
if (file.type.startsWith("image/")) return "🖼️";
if (file.type.startsWith("video/")) return "🎥";
if (file.type.startsWith("audio/")) return "🎵";
if (file.type.includes("pdf")) return "📄";
if (file.type.includes("text")) return "📝";
if (file.type.includes("zip") || file.type.includes("archive")) return "📦";
if (file.type.includes("word")) return "📝";
if (file.type.includes("excel") || file.type.includes("spreadsheet")) return "📊";
if (file.type.includes("powerpoint") || file.type.includes("presentation")) return "📽️";
return "📁";
}, []);
React.useEffect(() => {
const updatePreviews = async () => {
const newPreviews = /* @__PURE__ */ new Map();
for (const uploadFile of state.files) {
if (!previews.has(uploadFile.id)) {
const preview = await generateFilePreview(uploadFile.file);
newPreviews.set(uploadFile.id, preview);
} else {
newPreviews.set(uploadFile.id, previews.get(uploadFile.id));
}
}
setPreviews(newPreviews);
};
updatePreviews();
}, [state.files, generateFilePreview]);
const handleFileSelect = React.useCallback(async (event) => {
const files = Array.from(event.target.files || []);
if (files.length === 0) return;
try {
const validationResult = await utils.validateFiles(files, {
...config,
validation: {
...config.validation,
maxSize,
maxFiles,
allowedTypes: accept === "*" ? ["*"] : accept.split(",").map((t) => t.trim())
}
}, state.files.length);
if (validationResult.validFiles.length > 0) {
actions.selectFiles(validationResult.validFiles);
onFileSelect?.(validationResult.validFiles);
}
if (validationResult.rejectedFiles.length > 0) {
const errorMessage = validationResult.rejectedFiles.map((rf) => `${rf.file.name}: ${rf.errors.map((e) => e.message).join(", ")}`).join("\n");
onError?.(errorMessage);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "File validation failed";
onError?.(errorMessage);
}
event.target.value = "";
}, [config, maxSize, maxFiles, accept, state.files.length, actions, onFileSelect, onError]);
const handleButtonClick = React.useCallback(() => {
if (disabled || state.isUploading) return;
inputRef.current?.click();
}, [disabled, state.isUploading]);
const handleButtonKeyDown = React.useCallback((event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleButtonClick();
}
}, [handleButtonClick]);
const handleRemoveFile = React.useCallback((fileId, fileName) => {
actions.removeFile(fileId);
onFileRemove?.(fileId);
const preview = previews.get(fileId);
if (preview && preview.type === "image" && preview.url.startsWith("data:")) {
setPreviews((prev) => {
const newPreviews = new Map(prev);
newPreviews.delete(fileId);
return newPreviews;
});
}
if (config.accessibility.announceFileSelection) {
const announcement = `File ${fileName} removed`;
const announcer = document.createElement("div");
announcer.setAttribute("aria-live", "polite");
announcer.setAttribute("aria-atomic", "true");
announcer.className = "sr-only";
announcer.textContent = announcement;
document.body.appendChild(announcer);
setTimeout(() => document.body.removeChild(announcer), 1e3);
}
}, [actions, onFileRemove, previews, config.accessibility.announceFileSelection]);
const handleFileListKeyDown = React.useCallback((event, fileIndex, fileId, fileName) => {
switch (event.key) {
case "Delete":
case "Backspace":
event.preventDefault();
handleRemoveFile(fileId, fileName);
break;
case "ArrowDown":
event.preventDefault();
setFocusedFileIndex(Math.min(fileIndex + 1, state.files.length - 1));
break;
case "ArrowUp":
event.preventDefault();
setFocusedFileIndex(Math.max(fileIndex - 1, 0));
break;
case "Home":
event.preventDefault();
setFocusedFileIndex(0);
break;
case "End":
event.preventDefault();
setFocusedFileIndex(state.files.length - 1);
break;
}
}, [handleRemoveFile, state.files.length]);
const getPreviewSizeClasses = () => {
const sizeMap = {
sm: { container: "min-w-[150px]", media: "h-20", text: "text-xs" },
md: { container: "min-w-[200px]", media: "h-28", text: "text-sm" },
lg: { container: "min-w-[250px]", media: "h-36", text: "text-base" }
};
return sizeMap[previewSize] || sizeMap.md;
};
const sizeClasses = getPreviewSizeClasses();
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `file-upload file-upload--preview ${className}`, style, children: [
/* @__PURE__ */ jsxRuntime.jsx(
"input",
{
ref: inputRef,
type: "file",
multiple,
accept,
disabled: disabled || state.isUploading,
onChange: handleFileSelect,
className: "sr-only",
"aria-hidden": "true",
tabIndex: -1
}
),
/* @__PURE__ */ jsxRuntime.jsxs(
"button",
{
type: "button",
onClick: handleButtonClick,
onKeyDown: handleButtonKeyDown,
disabled: disabled || state.isUploading,
"aria-label": ariaLabel || config.labels.selectFilesText,
"aria-describedby": ariaDescribedBy,
className: "inline-flex items-center justify-center gap-2 font-medium transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 text-sm rounded-md bg-blue-600 text-white hover:bg-blue-700 focus-visible:ring-blue-500",
children: [
state.isUploading && /* @__PURE__ */ jsxRuntime.jsxs("svg", { className: "animate-spin h-4 w-4", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"circle",
{
className: "opacity-25",
cx: "12",
cy: "12",
r: "10",
stroke: "currentColor",
strokeWidth: "4",
fill: "none"
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"path",
{
className: "opacity-75",
fill: "currentColor",
d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
}
)
] }),
/* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
children || (state.isUploading ? config.labels.progressText : config.labels.selectFilesText),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 text-xs opacity-75", children: [
"(",
state.files.length,
" ",
state.files.length === 1 ? "file" : "files",
")"
] })
] })
]
}
),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: "mt-4 grid gap-4",
style: {
gridTemplateColumns: `repeat(auto-fill, minmax(${sizeClasses.container.replace("min-w-[", "").replace("]", "")}, 1fr))`
},
role: "list",
"aria-label": "Selected files with previews",
children: state.files.map((file, index) => {
const preview = previews.get(file.id);
const isFocused = focusedFileIndex === index;
return /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: `relative border rounded-lg p-4 bg-white transition-all duration-200 ${isFocused ? "ring-2 ring-blue-500 ring-offset-2" : "hover:shadow-md"}`,
role: "listitem",
tabIndex: config.accessibility.keyboardNavigation ? 0 : -1,
onKeyDown: (e) => handleFileListKeyDown(e, index, file.id, file.name),
onFocus: () => setFocusedFileIndex(index),
onBlur: () => setFocusedFileIndex(-1),
"aria-label": `File: ${file.name}, ${utils.formatFileSize(file.size)}, ${file.status}`,
children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: `w-full ${sizeClasses.media} flex items-center justify-center bg-gray-50 rounded-md mb-3 overflow-hidden`, children: preview?.type === "image" ? /* @__PURE__ */ jsxRuntime.jsx(
"img",
{
src: preview.url,
alt: `Preview of ${file.name}`,
className: "max-w-full max-h-full object-cover rounded-md",
loading: "lazy"
}
) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-4xl opacity-70", role: "img", "aria-label": `${file.type} file`, children: preview?.url || getFileIcon(file.file) }) }),
showFileInfo && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1", children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: `font-medium text-gray-900 truncate ${sizeClasses.text}`, title: file.name, children: file.name }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between text-xs text-gray-500", children: [
/* @__PURE__ */ jsxRuntime.jsx("span", { children: utils.formatFileSize(file.size) }),
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "uppercase", children: file.type.split("/")[1] || "file" })
] })
] }),
file.status === "uploading" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-3 space-y-1", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between text-xs", children: [
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-blue-600", children: "Uploading..." }),
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-blue-600 font-medium", children: [
file.progress,
"%"
] })
] }),
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full bg-gray-200 rounded-full h-2 overflow-hidden", children: /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
className: "bg-blue-600 h-2 rounded-full transition-all duration-300 ease-out",
style: { width: `${file.progress}%` },
role: "progressbar",
"aria-valuenow": file.progress,
"aria-valuemin": 0,
"aria-valuemax": 100,
"aria-label": `Upload progress: ${file.progress}%`
}
) })
] }),
file.status === "success" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-3 flex items-center text-green-600 text-sm", children: [
/* @__PURE__ */ jsxRuntime.jsx("svg", { className: "w-4 h-4 mr-1", fill: "currentColor", viewBox: "0 0 20 20", children: /* @__PURE__ */ jsxRuntime.jsx(
"path",
{
fillRule: "evenodd",
d: "M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",
clipRule: "evenodd"
}
) }),
/* @__PURE__ */ jsxRuntime.jsx("span", { children: config.labels.successText })
] }),
file.status === "error" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-3 space-y-2", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center text-red-600 text-sm", children: [
/* @__PURE__ */ jsxRuntime.jsx("svg", { className: "w-4 h-4 mr-1", fill: "currentColor", viewBox: "0 0 20 20", children: /* @__PURE__ */ jsxRuntime.jsx(
"path",
{
fillRule: "evenodd",
d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z",
clipRule: "evenodd"
}
) }),
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs", children: file.error || config.labels.errorText })
] }),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.retryUpload(file.id),
className: "text-xs text-red-600 hover:text-red-800 border border-red-300 hover:border-red-400 px-2 py-1 rounded transition-colors focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-1",
"aria-label": `Retry upload for ${file.name}`,
children: config.labels.retryText
}
)
] }),
file.status === "pending" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-3 text-gray-500 text-sm", children: "Ready to upload" }),
(file.status === "pending" || file.status === "error") && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => handleRemoveFile(file.id, file.name),
className: "absolute top-2 right-2 w-6 h-6 bg-red-500 hover:bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-bold transition-colors focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2",
"aria-label": `Remove ${file.name}`,
title: `Remove ${file.name}`,
children: "×"
}
)
]
},
file.id
);
})
}
),
state.files.some((f) => f.status === "pending") && !config.features.autoUpload && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: actions.uploadFiles,
disabled: state.isUploading,
className: "w-full mt-4 bg-green-600 text-white py-3 px-4 rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 font-medium transition-colors",
children: state.isUploading ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "flex items-center justify-center gap-2", children: [
/* @__PURE__ */ jsxRuntime.jsxs("svg", { className: "animate-spin h-4 w-4", viewBox: "0 0 24 24", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"circle",
{
className: "opacity-25",
cx: "12",
cy: "12",
r: "10",
stroke: "currentColor",
strokeWidth: "4",
fill: "none"
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"path",
{
className: "opacity-75",
fill: "currentColor",
d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
}
)
] }),
config.labels.progressText
] }) : `Upload All Files (${state.files.filter((f) => f.status === "pending").length})`
}
),
/* @__PURE__ */ jsxRuntime.jsx("div", { "aria-live": "polite", "aria-atomic": "true", className: "sr-only", children: state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
state.files.length,
" ",
state.files.length === 1 ? "file" : "files",
" selected.",
state.files.filter((f) => f.status === "pending").length > 0 && ` ${state.files.filter((f) => f.status === "pending").length} ready to upload.`,
state.files.filter((f) => f.status === "success").length > 0 && ` ${state.files.filter((f) => f.status === "success").length} uploaded successfully.`,
state.files.filter((f) => f.status === "error").length > 0 && ` ${state.files.filter((f) => f.status === "error").length} failed to upload.`
] }) })
] });
};
PreviewUpload.displayName = "PreviewUpload";
const ImageUpload = ({
className,
style,
ariaLabel,
ariaDescribedBy,
children,
aspectRatio,
cropEnabled = false,
resizeEnabled = false,
quality = 0.8
}) => {
const { config, actions, state } = useFileUpload();
const inputRef = React.useRef(null);
const [imageValidationErrors, setImageValidationErrors] = React.useState({});
const validateImageFile = React.useCallback(async (file) => {
if (!file.type.startsWith("image/")) return [];
const errors = [];
try {
const validation = await utils.validateImageDimensions(
file,
config.validation.maxWidth,
config.validation.maxHeight,
config.validation.minWidth,
config.validation.minHeight
);
if (!validation.isValid) {
errors.push(...validation.errors.map((e) => e.message));
}
} catch (error) {
errors.push("Failed to validate image dimensions");
}
return errors;
}, [config.validation]);
const handleFileSelect = async (event) => {
const files = Array.from(event.target.files || []);
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
if (imageFiles.length > 0) {
const validationResults = {};
for (const file of imageFiles) {
const errors = await validateImageFile(file);
if (errors.length > 0) {
validationResults[file.name] = errors;
}
}
setImageValidationErrors(validationResults);
const validFiles = imageFiles.filter((file) => !validationResults[file.name]);
if (validFiles.length > 0) {
const processedFiles = await Promise.all(
validFiles.map((file) => processImage(file))
);
actions.selectFiles(processedFiles);
}
}
};
const handleButtonClick = () => {
inputRef.current?.click();
};
const handleKeyDown = (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleButtonClick();
}
};
const getImagePreview = (file) => {
return URL.createObjectURL(file);
};
const resizeImage = React.useCallback((file, maxWidth, maxHeight) => {
return new Promise((resolve) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
let { width, height } = img;
if (width > height) {
if (width > maxWidth) {
height = height * maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width = width * maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
ctx?.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
if (blob) {
const resizedFile = new File([blob], file.name, {
type: file.type,
lastModified: Date.now()
});
resolve(resizedFile);
} else {
resolve(file);
}
}, file.type, quality);
};
img.src = URL.createObjectURL(file);
});
}, [quality]);
const cropImage = React.useCallback((file, aspectRatio2) => {
return new Promise((resolve) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
const { width, height } = img;
let cropWidth = width;
let cropHeight = height;
let offsetX = 0;
let offsetY = 0;
const imageAspectRatio = width / height;
if (imageAspectRatio > aspectRatio2) {
cropWidth = height * aspectRatio2;
offsetX = (width - cropWidth) / 2;
} else {
cropHeight = width / aspectRatio2;
offsetY = (height - cropHeight) / 2;
}
canvas.width = cropWidth;
canvas.height = cropHeight;
ctx?.drawImage(
img,
offsetX,
offsetY,
cropWidth,
cropHeight,
0,
0,
cropWidth,
cropHeight
);
canvas.toBlob((blob) => {
if (blob) {
const croppedFile = new File([blob], file.name, {
type: file.type,
lastModified: Date.now()
});
resolve(croppedFile);
} else {
resolve(file);
}
}, file.type, quality);
};
img.src = URL.createObjectURL(file);
});
}, [quality]);
const processImage = React.useCallback(async (file) => {
let processedFile = file;
if (cropEnabled && aspectRatio) {
processedFile = await cropImage(processedFile, aspectRatio);
}
if (resizeEnabled && (config.validation.maxWidth || config.validation.maxHeight)) {
const maxWidth = config.validation.maxWidth || 1920;
const maxHeight = config.validation.maxHeight || 1080;
processedFile = await resizeImage(processedFile, maxWidth, maxHeight);
}
return processedFile;
}, [cropEnabled, resizeEnabled, aspectRatio, config.validation, cropImage, resizeImage]);
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `file-upload file-upload--image ${className || ""}`, style, children: [
/* @__PURE__ */ jsxRuntime.jsx(
"input",
{
ref: inputRef,
type: "file",
multiple: config.defaults.multiple,
accept: "image/*",
disabled: config.defaults.disabled || state.isUploading,
onChange: handleFileSelect,
className: "file-upload-input",
style: { display: "none" },
"aria-hidden": "true"
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"div",
{
onClick: handleButtonClick,
onKeyDown: handleKeyDown,
role: "button",
tabIndex: config.defaults.disabled || state.isUploading ? -1 : 0,
"aria-label": ariaLabel || "Upload images",
"aria-describedby": ariaDescribedBy,
style: {
border: `2px dashed ${config.styling.colors.border}`,
borderRadius: config.styling.spacing.borderRadius,
padding: "2rem",
textAlign: "center",
cursor: config.defaults.disabled || state.isUploading ? "not-allowed" : "pointer",
backgroundColor: config.styling.colors.background,
color: config.styling.colors.foreground,
fontSize: config.styling.typography.fontSize,
opacity: config.defaults.disabled || state.isUploading ? 0.6 : 1,
minHeight: "200px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: config.styling.spacing.gap
},
children: children || /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-image-icon", style: {
fontSize: "3rem",
color: config.styling.colors.muted
}, children: "🖼️" }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-image-text", children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-image-primary-text", style: {
fontWeight: "600",
marginBottom: "0.5rem",
color: config.styling.colors.foreground
}, children: state.isUploading ? config.labels.progressText : "Upload Images" }),
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-image-secondary-text", style: {
fontSize: "0.875rem",
color: config.styling.colors.muted
}, children: "Click to select image files" })
] }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-image-count", style: {
fontSize: "0.875rem",
color: config.styling.colors.primary,
fontWeight: "500"
}, children: [
state.files.length,
" ",
state.files.length === 1 ? "image" : "images",
" selected"
] })
] })
}
),
Object.keys(imageValidationErrors).length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-validation-errors", style: {
marginTop: "1rem",
padding: "1rem",
backgroundColor: config.styling.colors.error + "10",
border: `1px solid ${config.styling.colors.error}`,
borderRadius: config.styling.spacing.borderRadius
}, children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { style: {
fontSize: "0.875rem",
fontWeight: "600",
color: config.styling.colors.error,
marginBottom: "0.5rem"
}, children: "Image Validation Errors:" }),
Object.entries(imageValidationErrors).map(([fileName, errors]) => /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: "0.5rem" }, children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
fontSize: "0.8rem",
fontWeight: "500",
color: config.styling.colors.foreground,
marginBottom: "0.25rem"
}, children: [
fileName,
":"
] }),
/* @__PURE__ */ jsxRuntime.jsx("ul", { style: {
margin: 0,
paddingLeft: "1rem",
fontSize: "0.75rem",
color: config.styling.colors.error
}, children: errors.map((error, index) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: error }, index)) })
] }, fileName))
] }),
state.files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "file-upload-image-previews", style: {
display: "grid",
gridTemplateColumns: config.defaults.multiple ? "repeat(auto-fill, minmax(150px, 1fr))" : "1fr",
gap: config.styling.spacing.gap,
marginTop: config.styling.spacing.margin
}, children: state.files.map((file) => {
const preview = getImagePreview(file.file);
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "file-upload-image-preview", style: {
position: "relative",
border: `1px solid ${config.styling.colors.border}`,
borderRadius: config.styling.spacing.borderRadius,
overflow: "hidden",
backgroundColor: config.styling.colors.background
}, children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
width: "100%",
height: aspectRatio ? `${(config.defaults.multiple ? 150 : 200) / aspectRatio}px` : config.defaults.multiple ? "150px" : "200px",
position: "relative",
overflow: "hidden",
aspectRatio: aspectRatio ? aspectRatio.toString() : void 0
}, children: [
/* @__PURE__ */ jsxRuntime.jsx(
"img",
{
src: preview,
alt: file.name,
style: {
width: "100%",
height: "100%",
objectFit: cropEnabled ? "cover" : "contain",
backgroundColor: config.styling.colors.muted + "20"
},
onLoad: () => {
setTimeout(() => URL.revokeObjectURL(preview), 1e3);
}
}
),
file.status === "uploading" && /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0, 0, 0, 0.7)",
display: "flex",
alignItems: "center",
justifyContent: "center",
color: "white"
}, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
textAlign: "center"
}, children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { style: {
width: "60px",
height: "4px",
backgroundColor: "rgba(255, 255, 255, 0.3)",
borderRadius: "2px",
overflow: "hidden",
marginBottom: "0.5rem"
}, children: /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
width: `${file.progress}%`,
height: "100%",
backgroundColor: config.styling.colors.primary,
transition: "width 0.3s ease"
} }) }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: { fontSize: "0.875rem" }, children: [
file.progress,
"%"
] })
] }) }),
file.status === "success" && /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
position: "absolute",
top: "0.5rem",
left: "0.5rem",
backgroundColor: config.styling.colors.success,
color: config.styling.colors.background,
borderRadius: "50%",
width: "24px",
height: "24px",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "0.875rem"
}, children: "✓" }),
file.status === "error" && /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
position: "absolute",
top: "0.5rem",
left: "0.5rem",
backgroundColor: config.styling.colors.error,
color: config.styling.colors.background,
borderRadius: "50%",
width: "24px",
height: "24px",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "0.875rem"
}, children: "!" }),
(file.status === "pending" || file.status === "error") && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: (e) => {
e.stopPropagation();
actions.removeFile(file.id);
},
style: {
position: "absolute",
top: "0.5rem",
right: "0.5rem",
background: config.styling.colors.error,
color: config.styling.colors.background,
border: "none",
borderRadius: "50%",
width: "24px",
height: "24px",
cursor: "pointer",
fontSize: "0.875rem",
display: "flex",
alignItems: "center",
justifyContent: "center"
},
"aria-label": `${config.labels.removeText} ${file.name}`,
children: "×"
}
)
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
padding: "0.75rem",
borderTop: `1px solid ${config.styling.colors.border}`
}, children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { style: {
fontSize: "0.875rem",
fontWeight: "500",
color: config.styling.colors.foreground,
marginBottom: "0.25rem",
wordBreak: "break-word"
}, children: file.name }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { style: {
fontSize: "0.75rem",
color: config.styling.colors.muted,
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}, children: [
/* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
(file.size / 1024).toFixed(1),
" KB"
] }),
file.status === "error" && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => actions.retryUpload(file.id),
style: {
background: "none",
border: `1px solid ${config.styling.colors.error}`,
color: config.styling.colors.error,
cursor: "pointer",
fontSize: "0.75rem",
padding: "0.25rem 0.5rem",
borderRadius: "0.25rem"
},
"aria-label": `${config.labels.retryText} ${file.name}`,
children: config.labels.retryText
}
)
] })
] })
] }, file.id);
}) }),
state.files.some((f) => f.status === "pending") && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: actions.uploadFiles,
disabled: state.isUploading,
style: {
backgroundColor: config.styling.colors.primary,
color: config.styling.colors.background,
padding: "0.75rem 1.5rem",
border: "none",
borderRadius: config.styling.spacing.borderRadius,
cursor: state.isUploading ? "not-allowed" : "pointer",
opacity: state.isUploading ? 0.6 : 1,
fontSize: config.styling.typography.fontSize,
fontWeight: "500",
width: "100%",
marginTop: "1rem"
},
children: state.isUploading ? config.labels.progressText : "Upload Images"
}
)
] });
};
ImageUpload.displayName = "ImageUpload";
const MultiFileUpload = ({
className = "",
style,
ariaLabel,
ariaDescribedBy,
children,
disabled: propDisabled,
multiple: propMultiple = true,
// Multi-file upload should default to multiple
accept: propAccept,
maxSize: propMaxSize,
maxFiles: propMaxFiles,
listLayout = "list",
sortable = false,
bulkActions = true,
onFileSelect,
onError,
onDragEnter,
onDragLeave,
onDragOver,
onDrop,
...props
}) => {
const { config, actions, state } = useFileUpload();
const inputRef = React.useRef(null);
const [selectedFileIds, setSelectedFileIds] = React.useState(/* @__PURE__ */ new Set());
const [isDragOver, setIsDragOver] = React.useState(false);
const [focusedIndex, setFocusedIndex] = React.useState(-1);
const disabled = propDisabled ?? config.defaults.disabled ?? false;
const multiple = propMultiple ?? config.defaults.multiple ?? true;
const accept = propAccept ?? config.defaults.accept ?? "*";
const maxSize = propMaxSize ?? config.validation.maxSize;
const maxFiles = propMaxFiles ?? config.validation.maxFiles;
const handleFileSelect = React.useCallback(async (files) => {
if (files.length === 0) return;
try {
const validationResult = await utils.validateFiles(files, {
...config,
validation: {
...config.validation,
maxSize,
maxFiles,
allowedTypes: accept === "*" ? ["*"] : accept.split(",").map((t) => t.trim())
}
}, state.files.length);
if (validationResult.validFiles.length > 0) {
actions.selectFiles(validationResult.validFiles);
onFileSelect?.(validationResult.validFiles);
}
if (validationResult.rejectedFiles.length > 0) {
const errorMessage = validationResult.rejectedFiles.map((rf) => `${rf.file.name}: ${rf.errors.map((e) => e.message).join(", ")}`).join("\n");
onError?.(errorMessage);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "File validation failed";
onError?.(errorMessage);
}
}, [config, maxSize, maxFiles, accept, state.files.length, actions, onFileSelect, onError]);
const handleInputChange = React.useCallback(async (event) => {
const files = Array.from(event.target.files || []);
await handleFileSelect(files);
event.target.value = "";
}, [handleFileSelect]);
const handleDragEnter = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
setIsDragOver(true);
onDragEnter?.(event);
}, [onDragEnter]);
const handleDragLeave = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
if (!event.currentTarget.contains(event.relatedTarget)) {
setIsDragOver(false);
}
onDragLeave?.(event);
}, [onDragLeave]);
const handleDragOver = React.useCallback((event) => {
event.preventDefault();
event.stopPropagation();
onDragOver?.(event);
}, [onDragOver]);
const handleDrop = React.useCallback(async (event) => {
event.preventDefault();
event.stopPropagation();
setIsDragOver(false);
const files = Array.from(event.dataTransfer.files);
await handleFileSelect(files);
onDrop?.(event);
}, [handleFileSelect, onDrop]);
const handleSelectAll = React.useCallback(() => {
const allFileIds = new Set(state.files.map((f) => f.id));
setSelectedFileIds(allFileIds);
}, [state.files]);
const handleDeselectAll = React.useCallback(() => {
setSelectedFileIds(/* @__PURE__ */ new Set());
}, []);
const handleRemoveSelected = React.useCallback(() => {
selectedFileIds.forEach((fileId) => {
actions.removeFile(fileId);
});
setSelectedFileIds(/* @__PURE__ */ new Set());
}, [selectedFileIds, actions]);
const handleUploadSelected = React.useCallback(async () => {
const selectedFiles = state.files.filter((f) => selectedFileIds.has(f.id) && f.status === "pending");
if (selectedFiles.length === 0) return;
await actions.uploadFiles();
}, [selectedFileIds, state.files, actions]);
const handleRemoveAll = React.useCallback(() => {
actions.clearAll();
setSelectedFileIds(/* @__PURE__ */ new Set());
}, [actions]);
const handleUploadAll = React.useCallback(async () => {
await actions.uploadFiles();
}, [actions]);
const handleFileToggle = React.useCallback((fileId) => {
setSelectedFileIds((prev) => {
const newSet = new Set(prev);
if (newSet.has(fileId)) {
newSet.delete(fileId);
} else {
newSet.add(fileId);
}
return newSet;
});
}, []);
const handleKeyDown = React.useCallback((event) => {
if (state.files.length === 0) return;
switch (event.key) {
case "ArrowDown":
event.preventDefault();
setFocusedIndex((prev) => Math.min(prev + 1, state.files.length - 1));
break;
case "ArrowUp":
event.preventDefault();
setFocusedIndex((prev) => Math.max(prev - 1, 0));
break;
case " ":
event.preventDefault();
if (focusedIndex >= 0 && focusedIndex < state.files.length) {
const fileId = state.files[focusedIndex].id;
handleFileToggle(fileId);
}
break;
case "Enter":
event.preventDefault();
inputRef.current?.click();
break;
case "Delete":
case "Backspace":
event.preventDefault();
if (selectedFileIds.size > 0) {
handleRemoveSelected();
} else if (focusedIndex >= 0 && focusedIndex < state.files.length) {
const fileId = state.files[focusedIndex].id;
actions.removeFile(fileId);
}
break;
case "a":
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
handleSelectAll();
}
break;
}
}, [state.files, focusedIndex, selectedFileIds, handleFileToggle, handleRemoveSelected, handleSelectAll, actions]);
React.useEffect(() => {
if (focusedIndex >= state.files.length) {
setFocusedIndex(Math.max(0, state.files.length - 1));
}
}, [state.files.length, focusedIndex]);
const getContainerClasses = () => {
const baseClasses = [
"multi-file-upload",
"border-2 border-dashed rounded-lg p-6",
"transition-colors duration-200",
"focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-blue-500"
];
const stateClasses = [];
if (isDragOver) {
stateClasses.push("border-blue-500 bg-blue-50");
} else {
stateClasses.push("border-gray-300 hover:border-gray-400");
}
if (disabled) {
stateClasses.push("opacity-50 cursor-not-allowed");
}
return [...baseClasses, ...stateClasses, className].filter(Boolean).join(" ");
};
const hasFiles = state.files.length > 0;
const hasSelectedFiles = selectedFileIds.size > 0;
const hasPendingFiles = state.files.some((f) => f.status === "pending");
const selectedPendingFiles = state.files.filter((f) => selectedFileIds.has(f.id) && f.status === "pending");
return /* @__PURE__ */ jsxRuntime.jsxs(
"div",
{
className: getContainerClasses(),
onDragEnter: handleDragEnter,
onDragLeave: handleDragLeave,
onDragOver: handleDragOver,
onDrop: handleDrop,
onKeyDown: handleKeyDown,
tabIndex: 0,
role: "application",
"aria-label": ariaLabel || "Multi-file upload area",
"aria-describedby": ariaDescribedBy,
style,
children: [
/* @__PURE__ */ jsxRuntime.jsx(
"input",
{
ref: inputRef,
type: "file",
multiple,
accept,
disabled: disabled || state.isUploading,
onChange: handleInputChange,
className: "sr-only",
"aria-hidden": "true"
}
),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "text-center", children: [
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "mx-auto h-12 w-12 text-gray-400 mb-4", children: /* @__PURE__ */ jsxRuntime.jsx("svg", { fill: "none", stroke: "currentColor", viewBox: "0 0 48 48", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx(
"path",
{
strokeLinecap: "round",
strokeLinejoin: "round",
strokeWidth: 2,
d: "M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
}
) }) }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: () => inputRef.current?.click(),
disabled: disabled || state.isUploading,
className: "text-blue-600 hover:text-blue-700 font-medium focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded px-2 py-1",
children: config.labels.selectFilesText || "Select files"
}
),
/* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-600", children: "or drag and drop files here" }),
maxFiles > 1 && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-xs text-gray-500", children: [
"Maximum ",
maxFiles,
" files, up to ",
(maxSize / 1024 / 1024).toFixed(0),
"MB each"
] })
] })
] }),
hasFiles && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-6", children: [
bulkActions && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between mb-4 p-3 bg-gray-50 rounded-md", children: [
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4", children: [
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm text-gray-700", children: [
state.files.length,
" file",
state.files.length !== 1 ? "s" : "",
hasSelectedFiles && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-2 text-blue-600", children: [
"(",
selectedFileIds.size,
" selected)"
] })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: handleSelectAll,
className: "text-xs text-blue-600 hover:text-blue-700 focus:outline-none focus:ring-1 focus:ring-blue-500 rounded px-2 py-1",
children: "Select All"
}
),
hasSelectedFiles && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: handleDeselectAll,
className: "text-xs text-gray-600 hover:text-gray-700 focus:outline-none focus:ring-1 focus:ring-gray-500 rounded px-2 py-1",
children: "Deselect All"
}
)
] })
] }),
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
hasSelectedFiles && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
selectedPendingFiles.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
"button",
{
type: "button",
onClick: handleUploadSelected,
disabled: state.isUploading,
className: "text-xs bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700 disabled:opacity-50 focus:outline-none focus:ring-2 focus:ring-blue-500",
children: [
"Upload Selected (",
selectedPendingFiles.length,
")"
]
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: handleRemoveSelected,
className: "text-xs bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500",
children: "Remove Selected"
}
)
] }),
hasPendingFiles && /* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: handleUploadAll,
disabled: state.isUploading,
className: "text-xs bg-green-600 text-white px-3 py-1 rounded hover:bg-green-700 disabled:opacity-50 focus:outline-none focus:ring-2 focus:ring-green-500",
children: "Upload All"
}
),
/* @__PURE__ */ jsxRuntime.jsx(
"button",
{
type: "button",
onClick: handleRemoveAll,
className: "text-xs text-red-600 hover:text-red-700 px-2 py-1 rounded focus:outline-none focus:ring-1 focus:ring-red-500",
children: "Remove All"
}
)
] })
] }),
/* @__PURE__ */ jsxRuntime.jsx(
UploadFeedback,
{
files: state.files,
isUploading: state.isUploading,
showIndividualProgress: true,
showOverallProgress: state.files.length > 1,
showStatusIndicators: true,
showFileNames: true,
enableAccessibilityAnnouncements: config.accessibility?.announceProgress ?? true,
onRetry: actions.retryUpload,
onRemove: actions.removeFile
}
),
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-4 text-xs text-gray-500 space-y-1", children: /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
/* @__PURE__ */ jsxRuntime.jsx("kbd", { className: "px-1 py-0.5 bg-gray-100 rounded", children: "↑↓" }),
" Navigate • ",
/* @__PURE__ */ jsxRuntime.jsx("kbd", { className: "px-1 py-0.5 bg-gray-100 rounded", children: "Space" }),
" Select • ",
/* @__PURE__ */ jsxRuntime.jsx("kbd", { className: "px-1 py-0.5 bg-gray-100 rounded", children: "Ctrl+A" }),
" Select All • ",
/* @__PURE__ */ jsxRuntime.jsx("kbd", { className: "px-1 py-0.5 bg-gray-100 rounded", children: "Del" }),
" Remove"
] }) })
] }),
children
]
}
);
};
MultiFileUpload.displayName = "MultiFileUpload";
const FileUpload = ({
variant,
size,
radius,
theme: theme$1,
disabled,
multiple,
accept,
maxSize,
maxFiles,
onUpload,
onError,
onProgress,
onFileSelect,
onFileRemove,
onDragEnter,
onDragLeave,
onDragOver,
onDrop,
config: configProp,
className,
style,
ariaLabel,
ariaDescribedBy,
children,
...props
}) => {
const mergedConfig = React.useMemo(() => {
let baseConfig = schema.defaultConfig;
if (configProp) {
if (typeof configProp === "string") {
try {
const { config: loadedConfig } = schema.loadConfigFromJSON(configProp);
if (loadedConfig) {
baseConfig = loadedConfig;
}
} catch (error) {
console.warn("Failed to load config from string:", error);
}
} else {
baseConfig = schema.mergeConfig(configProp);
}
}
const propOverrides = {};
if (variant !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, variant };
}
if (size !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, size };
}
if (radius !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, radius };
}
if (theme$1 !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, theme: theme$1 };
propOverrides.styling = { ...propOverrides.styling, theme: theme$1 };
}
if (disabled !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, disabled };
}
if (multiple !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, multiple };
propOverrides.features = { ...propOverrides.features, multipleFiles: multiple };
}
if (accept !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, accept };
}
if (maxSize !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, maxSize };
propOverrides.validation = { ...propOverrides.validation, maxSize };
}
if (maxFiles !== void 0) {
propOverrides.defaults = { ...propOverrides.defaults, maxFiles };
propOverrides.validation = { ...propOverrides.validation, maxFiles };
}
return Object.keys(propOverrides).length > 0 ? schema.mergeConfig({ ...baseConfig, ...propOverrides }) : baseConfig;
}, [configProp, variant, size, radius, theme$1, disabled, multiple, accept, maxSize, maxFiles]);
const eventHandlers = React.useMemo(() => ({
onFileSelect: onFileSelect ? (event) => onFileSelect(event.files.map((f) => f.file)) : void 0,
onUploadStart: onUpload ? (event) => onUpload(event.files.map((f) => f.file)) : void 0,
onUploadProgress: onProgress ? (event) => {
const file = event.files[0];
if (file) {
onProgress(file.progress, file);
}
} : void 0,
onUploadSuccess: void 0,
// Will be handled internally
onUploadError: onError ? (event) => {
const file = event.files[0];
if (file?.error) {
onError(file.error);
}
} : void 0,
onFileRemove: onFileRemove ? (event) => {
const file = event.files[0];
if (file) {
onFileRemove(file.id);
}
} : void 0,
onUploadRetry: void 0
// Will be handled internally
}), [onUpload, onError, onProgress, onFileSelect, onFileRemove]);
React.useEffect(() => {
if (mergedConfig.styling?.theme) {
theme.applyTheme(mergedConfig.styling.theme, mergedConfig);
}
}, [mergedConfig]);
const effectiveVariant = mergedConfig.defaults.variant;
const effectiveSize = mergedConfig.defaults.size;
const effectiveRadius = mergedConfig.defaults.radius;
const effectiveTheme = mergedConfig.styling.theme;
const themeClasses = theme.generateThemeClasses(
effectiveVariant,
effectiveSize,
effectiveRadius
);
const combinedClassName = theme.cn(
themeClasses,
disabled && "file-upload--disabled",
className
);
const cssVariables = React.useMemo(() => {
const variables = {};
if (mergedConfig.styling) {
const { colors, spacing, typography, borders, shadows } = mergedConfig.styling;
if (colors) {
Object.entries(colors).forEach(([key, value]) => {
variables[`--file-upload-${key}`] = value;
});
}
if (spacing) {
Object.entries(spacing).forEach(([key, value]) => {
variables[`--file-upload-spacing-${key}`] = value;
});
}
if (typography) {
Object.entries(typography).forEach(([key, value]) => {
variables[`--file-upload-${key}`] = value;
});
}
if (borders) {
Object.entries(borders).forEach(([key, value]) => {
variables[`--file-upload-border-${key}`] = value;
});
}
if (shadows) {
Object.entries(shadows).forEach(([key, value]) => {
variables[`--file-upload-shadow-${key}`] = value;
});
}
}
return variables;
}, [mergedConfig]);
const combinedStyle = {
...cssVariables,
...style
};
const renderVariant = () => {
const commonProps = {
className: combinedClassName,
style: combinedStyle,
ariaLabel,
ariaDescribedBy,
onDragEnter,
onDragLeave,
onDragOver,
onDrop,
children,
...props
};
switch (effectiveVariant) {
case "dropzone":
return /* @__PURE__ */ jsxRuntime.jsx(DropzoneUpload, { ...commonProps });
case "preview":
return /* @__PURE__ */ jsxRuntime.jsx(PreviewUpload, { ...commonProps });
case "image-only":
return /* @__PURE__ */ jsxRuntime.jsx(ImageUpload, { ...commonProps });
case "multi-file":
return /* @__PURE__ */ jsxRuntime.jsx(MultiFileUpload, { ...commonProps });
case "button":
default:
return /* @__PURE__ */ jsxRuntime.jsx(ButtonUpload, { ...commonProps });
}
};
return /* @__PURE__ */ jsxRuntime.jsx(
FileUploadErrorBoundary,
{
onError: (error, errorInfo) => {
console.error("FileUpload component crashed:", error, errorInfo);
onError?.(error.message);
},
showErrorDetails: process.env.NODE_ENV === "development",
children: /* @__PURE__ */ jsxRuntime.jsx(FileUploadProvider, { config: mergedConfig, handlers: eventHandlers, children: /* @__PURE__ */ jsxRuntime.jsx(
"div",
{
"data-theme": effectiveTheme,
className: "file-upload-wrapper",
style: cssVariables,
children: renderVariant()
}
) })
}
);
};
FileUpload.displayName = "FileUpload";
exports.AccessibilityAnnouncer = AccessibilityAnnouncer;
exports.ButtonUpload = ButtonUpload;
exports.DropzoneUpload = DropzoneUpload;
exports.ErrorDisplay = ErrorDisplay;
exports.ErrorFeedback = ErrorFeedback;
exports.FileUpload = FileUpload;
exports.FileUploadErrorBoundary = FileUploadErrorBoundary;
exports.FileUploadProvider = FileUploadProvider;
exports.ImageUpload = ImageUpload;
exports.LoadingSpinner = LoadingSpinner;
exports.MultiFileUpload = MultiFileUpload;
exports.PreviewUpload = PreviewUpload;
exports.ProgressBar = ProgressBar;
exports.StatusIndicator = StatusIndicator;
exports.UploadFeedback = UploadFeedback;
exports.cn = cn;
exports.useFileUpload = useFileUpload;
exports.withErrorBoundary = withErrorBoundary;
//# sourceMappingURL=file-upload-tgTAdTQa.cjs.map