{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "comp-554",
  "type": "registry:component",
  "title": "Comp 554",
  "description": "Comp 554",
  "files": [
    {
      "path": "registry/ui-basic/comp-554.tsx",
      "content": "\"use client\";\r\n\r\nimport { useCallback, useEffect, useRef, useState } from \"react\";\r\n\r\nimport { Button } from \"@/components/ui/button\";\r\nimport {\r\n\tCropper,\r\n\tCropperCropArea,\r\n\tCropperDescription,\r\n\tCropperImage,\r\n} from \"@/components/ui/cropper\";\r\nimport {\r\n\tDialog,\r\n\tDialogContent,\r\n\tDialogDescription,\r\n\tDialogFooter,\r\n\tDialogHeader,\r\n\tDialogTitle,\r\n} from \"@/components/ui/dialog\";\r\nimport { Slider } from \"@/components/ui/slider\";\r\nimport {\r\n\tArrowLeftIcon,\r\n\tCircleUserRoundIcon,\r\n\tXIcon,\r\n\tZoomInIcon,\r\n\tZoomOutIcon,\r\n} from \"lucide-react\";\r\n\r\nimport { useFileUpload } from \"../utilities/usefileUpload\";\r\n\r\n// Define type for pixel crop area\r\ntype Area = { x: number; y: number; width: number; height: number };\r\n\r\n// Helper function to create a cropped image blob\r\nconst createImage = (url: string): Promise<HTMLImageElement> =>\r\n\tnew Promise((resolve, reject) => {\r\n\t\tconst image = new Image();\r\n\t\timage.addEventListener(\"load\", () => resolve(image));\r\n\t\timage.addEventListener(\"error\", (error) => reject(error));\r\n\t\timage.setAttribute(\"crossOrigin\", \"anonymous\"); // Needed for canvas Tainted check\r\n\t\timage.src = url;\r\n\t});\r\n\r\nasync function getCroppedImg(\r\n\timageSrc: string,\r\n\tpixelCrop: Area,\r\n\toutputWidth: number = pixelCrop.width, // Optional: specify output size\r\n\toutputHeight: number = pixelCrop.height\r\n): Promise<Blob | null> {\r\n\ttry {\r\n\t\tconst image = await createImage(imageSrc);\r\n\t\tconst canvas = document.createElement(\"canvas\");\r\n\t\tconst ctx = canvas.getContext(\"2d\");\r\n\r\n\t\tif (!ctx) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\t// Set canvas size to desired output size\r\n\t\tcanvas.width = outputWidth;\r\n\t\tcanvas.height = outputHeight;\r\n\r\n\t\t// Draw the cropped image onto the canvas\r\n\t\tctx.drawImage(\r\n\t\t\timage,\r\n\t\t\tpixelCrop.x,\r\n\t\t\tpixelCrop.y,\r\n\t\t\tpixelCrop.width,\r\n\t\t\tpixelCrop.height,\r\n\t\t\t0,\r\n\t\t\t0,\r\n\t\t\toutputWidth, // Draw onto the output size\r\n\t\t\toutputHeight\r\n\t\t);\r\n\r\n\t\t// Convert canvas to blob\r\n\t\treturn new Promise((resolve) => {\r\n\t\t\tcanvas.toBlob((blob) => {\r\n\t\t\t\tresolve(blob);\r\n\t\t\t}, \"image/jpeg\"); // Specify format and quality if needed\r\n\t\t});\r\n\t} catch (error) {\r\n\t\tconsole.error(\"Error in getCroppedImg:\", error);\r\n\t\treturn null;\r\n\t}\r\n}\r\n\r\nexport default function Component() {\r\n\tconst [\r\n\t\t{ files, isDragging },\r\n\t\t{\r\n\t\t\thandleDragEnter,\r\n\t\t\thandleDragLeave,\r\n\t\t\thandleDragOver,\r\n\t\t\thandleDrop,\r\n\t\t\topenFileDialog,\r\n\t\t\tremoveFile,\r\n\t\t\tgetInputProps,\r\n\t\t},\r\n\t] = useFileUpload({\r\n\t\taccept: \"image/*\",\r\n\t});\r\n\r\n\tconst previewUrl = files[0]?.preview || null;\r\n\tconst fileId = files[0]?.id;\r\n\r\n\tconst [finalImageUrl, setFinalImageUrl] = useState<string | null>(null);\r\n\tconst [isDialogOpen, setIsDialogOpen] = useState(false);\r\n\r\n\t// Ref to track the previous file ID to detect new uploads\r\n\tconst previousFileIdRef = useRef<string | undefined | null>(null);\r\n\r\n\t// State to store the desired crop area in pixels\r\n\tconst [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(\r\n\t\tnull\r\n\t);\r\n\r\n\t// State for zoom level\r\n\tconst [zoom, setZoom] = useState(1);\r\n\r\n\t// Callback for Cropper to provide crop data - Wrap with useCallback\r\n\tconst handleCropChange = useCallback((pixels: Area | null) => {\r\n\t\tsetCroppedAreaPixels(pixels);\r\n\t}, []);\r\n\r\n\tconst handleApply = async () => {\r\n\t\t// Check if we have the necessary data\r\n\t\tif (!previewUrl || !fileId || !croppedAreaPixels) {\r\n\t\t\tconsole.error(\"Missing data for apply:\", {\r\n\t\t\t\tpreviewUrl,\r\n\t\t\t\tfileId,\r\n\t\t\t\tcroppedAreaPixels,\r\n\t\t\t});\r\n\t\t\t// Remove file if apply is clicked without crop data?\r\n\t\t\tif (fileId) {\r\n\t\t\t\tremoveFile(fileId);\r\n\t\t\t\tsetCroppedAreaPixels(null);\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t// 1. Get the cropped image blob using the helper\r\n\t\t\tconst croppedBlob = await getCroppedImg(previewUrl, croppedAreaPixels);\r\n\r\n\t\t\tif (!croppedBlob) {\r\n\t\t\t\tthrow new Error(\"Failed to generate cropped image blob.\");\r\n\t\t\t}\r\n\r\n\t\t\t// 2. Create a NEW object URL from the cropped blob\r\n\t\t\tconst newFinalUrl = URL.createObjectURL(croppedBlob);\r\n\r\n\t\t\t// 3. Revoke the OLD finalImageUrl if it exists\r\n\t\t\tif (finalImageUrl) {\r\n\t\t\t\tURL.revokeObjectURL(finalImageUrl);\r\n\t\t\t}\r\n\r\n\t\t\t// 4. Set the final avatar state to the NEW URL\r\n\t\t\tsetFinalImageUrl(newFinalUrl);\r\n\r\n\t\t\t// 5. Close the dialog (don't remove the file yet)\r\n\t\t\tsetIsDialogOpen(false);\r\n\t\t} catch (error) {\r\n\t\t\tconsole.error(\"Error during apply:\", error);\r\n\t\t\t// Close the dialog even if cropping fails\r\n\t\t\tsetIsDialogOpen(false);\r\n\t\t}\r\n\t};\r\n\r\n\tconst handleRemoveFinalImage = () => {\r\n\t\tif (finalImageUrl) {\r\n\t\t\tURL.revokeObjectURL(finalImageUrl);\r\n\t\t}\r\n\t\tsetFinalImageUrl(null);\r\n\t};\r\n\r\n\tuseEffect(() => {\r\n\t\tconst currentFinalUrl = finalImageUrl;\r\n\t\t// Cleanup function\r\n\t\treturn () => {\r\n\t\t\tif (currentFinalUrl && currentFinalUrl.startsWith(\"blob:\")) {\r\n\t\t\t\tURL.revokeObjectURL(currentFinalUrl);\r\n\t\t\t}\r\n\t\t};\r\n\t}, [finalImageUrl]);\r\n\r\n\t// Effect to open dialog when a *new* file is ready\r\n\tuseEffect(() => {\r\n\t\t// Check if fileId exists and is different from the previous one\r\n\t\tif (fileId && fileId !== previousFileIdRef.current) {\r\n\t\t\tsetIsDialogOpen(true); // Open dialog for the new file\r\n\t\t\tsetCroppedAreaPixels(null); // Reset crop area for the new file\r\n\t\t\tsetZoom(1); // Reset zoom for the new file\r\n\t\t}\r\n\t\t// Update the ref to the current fileId for the next render\r\n\t\tpreviousFileIdRef.current = fileId;\r\n\t}, [fileId]); // Depend only on fileId\r\n\r\n\treturn (\r\n\t\t<div className=\"flex flex-col items-center gap-2\">\r\n\t\t\t<div className=\"relative inline-flex\">\r\n\t\t\t\t{/* Drop area - uses finalImageUrl */}\r\n\t\t\t\t<button\r\n\t\t\t\t\tclassName=\"border-input hover:bg-accent/50 data-[dragging=true]:bg-accent/50 focus-visible:border-ring focus-visible:ring-ring/50 relative flex size-16 items-center justify-center overflow-hidden rounded-full border border-dashed transition-colors outline-hidden focus-visible:ring-[3px] has-disabled:pointer-events-none has-disabled:opacity-50 has-[img]:border-none\"\r\n\t\t\t\t\tonClick={openFileDialog}\r\n\t\t\t\t\tonDragEnter={handleDragEnter}\r\n\t\t\t\t\tonDragLeave={handleDragLeave}\r\n\t\t\t\t\tonDragOver={handleDragOver}\r\n\t\t\t\t\tonDrop={handleDrop}\r\n\t\t\t\t\tdata-dragging={isDragging || undefined}\r\n\t\t\t\t\taria-label={finalImageUrl ? \"Change image\" : \"Upload image\"}\r\n\t\t\t\t>\r\n\t\t\t\t\t{finalImageUrl ? (\r\n\t\t\t\t\t\t<img\r\n\t\t\t\t\t\t\tclassName=\"size-full object-cover\"\r\n\t\t\t\t\t\t\tsrc={finalImageUrl}\r\n\t\t\t\t\t\t\talt=\"User avatar\"\r\n\t\t\t\t\t\t\twidth={64}\r\n\t\t\t\t\t\t\theight={64}\r\n\t\t\t\t\t\t\tstyle={{ objectFit: \"cover\" }}\r\n\t\t\t\t\t\t/>\r\n\t\t\t\t\t) : (\r\n\t\t\t\t\t\t<div aria-hidden=\"true\">\r\n\t\t\t\t\t\t\t<CircleUserRoundIcon className=\"size-4 opacity-60\" />\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t)}\r\n\t\t\t\t</button>\r\n\t\t\t\t{/* Remove button - depends on finalImageUrl */}\r\n\t\t\t\t{finalImageUrl && (\r\n\t\t\t\t\t<Button\r\n\t\t\t\t\t\tonClick={handleRemoveFinalImage}\r\n\t\t\t\t\t\tsize=\"icon\"\r\n\t\t\t\t\t\tclassName=\"border-background focus-visible:border-background absolute -top-1 -right-1 size-6 rounded-full border-2 shadow-none\"\r\n\t\t\t\t\t\taria-label=\"Remove image\"\r\n\t\t\t\t\t>\r\n\t\t\t\t\t\t<XIcon className=\"size-3.5\" />\r\n\t\t\t\t\t</Button>\r\n\t\t\t\t)}\r\n\t\t\t\t<input\r\n\t\t\t\t\t{...getInputProps()}\r\n\t\t\t\t\tclassName=\"sr-only\"\r\n\t\t\t\t\taria-label=\"Upload image file\"\r\n\t\t\t\t\ttabIndex={-1}\r\n\t\t\t\t/>\r\n\t\t\t</div>\r\n\r\n\t\t\t{/* Cropper Dialog - Use isDialogOpen for open prop */}\r\n\t\t\t<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>\r\n\t\t\t\t<DialogContent className=\"gap-0 p-0 sm:max-w-140 [button]:*:hidden\">\r\n\t\t\t\t\t<DialogDescription className=\"sr-only\">\r\n\t\t\t\t\t\tCrop image dialog\r\n\t\t\t\t\t</DialogDescription>\r\n\t\t\t\t\t<DialogHeader className=\"contents space-y-0 text-left\">\r\n\t\t\t\t\t\t<DialogTitle className=\"flex items-center justify-between border-b p-4 text-base\">\r\n\t\t\t\t\t\t\t<div className=\"flex items-center gap-2\">\r\n\t\t\t\t\t\t\t\t<Button\r\n\t\t\t\t\t\t\t\t\ttype=\"button\"\r\n\t\t\t\t\t\t\t\t\tvariant=\"ghost\"\r\n\t\t\t\t\t\t\t\t\tsize=\"icon\"\r\n\t\t\t\t\t\t\t\t\tclassName=\"-my-1 opacity-60\"\r\n\t\t\t\t\t\t\t\t\tonClick={() => setIsDialogOpen(false)}\r\n\t\t\t\t\t\t\t\t\taria-label=\"Cancel\"\r\n\t\t\t\t\t\t\t\t>\r\n\t\t\t\t\t\t\t\t\t<ArrowLeftIcon aria-hidden=\"true\" />\r\n\t\t\t\t\t\t\t\t</Button>\r\n\t\t\t\t\t\t\t\t<span>Crop image</span>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t<Button\r\n\t\t\t\t\t\t\t\tclassName=\"-my-1\"\r\n\t\t\t\t\t\t\t\tonClick={handleApply}\r\n\t\t\t\t\t\t\t\tdisabled={!previewUrl}\r\n\t\t\t\t\t\t\t\tautoFocus\r\n\t\t\t\t\t\t\t>\r\n\t\t\t\t\t\t\t\tApply\r\n\t\t\t\t\t\t\t</Button>\r\n\t\t\t\t\t\t</DialogTitle>\r\n\t\t\t\t\t</DialogHeader>\r\n\t\t\t\t\t{previewUrl && (\r\n\t\t\t\t\t\t<Cropper\r\n\t\t\t\t\t\t\tclassName=\"h-96 sm:h-120\"\r\n\t\t\t\t\t\t\timage={previewUrl}\r\n\t\t\t\t\t\t\tzoom={zoom}\r\n\t\t\t\t\t\t\tonCropChange={handleCropChange}\r\n\t\t\t\t\t\t\tonZoomChange={setZoom}\r\n\t\t\t\t\t\t>\r\n\t\t\t\t\t\t\t<CropperDescription />\r\n\t\t\t\t\t\t\t<CropperImage />\r\n\t\t\t\t\t\t\t<CropperCropArea />\r\n\t\t\t\t\t\t</Cropper>\r\n\t\t\t\t\t)}\r\n\t\t\t\t\t<DialogFooter className=\"border-t px-4 py-6\">\r\n\t\t\t\t\t\t<div className=\"mx-auto flex w-full max-w-80 items-center gap-4\">\r\n\t\t\t\t\t\t\t<ZoomOutIcon\r\n\t\t\t\t\t\t\t\tclassName=\"shrink-0 opacity-60\"\r\n\t\t\t\t\t\t\t\tsize={16}\r\n\t\t\t\t\t\t\t\taria-hidden=\"true\"\r\n\t\t\t\t\t\t\t/>\r\n\t\t\t\t\t\t\t<Slider\r\n\t\t\t\t\t\t\t\tdefaultValue={[1]}\r\n\t\t\t\t\t\t\t\tvalue={[zoom]}\r\n\t\t\t\t\t\t\t\tmin={1}\r\n\t\t\t\t\t\t\t\tmax={3}\r\n\t\t\t\t\t\t\t\tstep={0.1}\r\n\t\t\t\t\t\t\t\tonValueChange={(value) => setZoom(value[0])}\r\n\t\t\t\t\t\t\t\taria-label=\"Zoom slider\"\r\n\t\t\t\t\t\t\t/>\r\n\t\t\t\t\t\t\t<ZoomInIcon\r\n\t\t\t\t\t\t\t\tclassName=\"shrink-0 opacity-60\"\r\n\t\t\t\t\t\t\t\tsize={16}\r\n\t\t\t\t\t\t\t\taria-hidden=\"true\"\r\n\t\t\t\t\t\t\t/>\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</DialogFooter>\r\n\t\t\t\t</DialogContent>\r\n\t\t\t</Dialog>\r\n\r\n\t\t\t<p\r\n\t\t\t\taria-live=\"polite\"\r\n\t\t\t\trole=\"region\"\r\n\t\t\t\tclassName=\"text-muted-foreground mt-2 text-xs\"\r\n\t\t\t>\r\n\t\t\t\tAvatar{\" \"}\r\n\t\t\t\t<a\r\n\t\t\t\t\thref=\"https://github.com/origin-space/originui/tree/main/docs/use-file-upload.md\"\r\n\t\t\t\t\tclassName=\"hover:text-foreground underline\"\r\n\t\t\t\t\ttarget=\"_blank\"\r\n\t\t\t\t>\r\n\t\t\t\t\tuploader\r\n\t\t\t\t</a>{\" \"}\r\n\t\t\t\twith{\" \"}\r\n\t\t\t\t<a\r\n\t\t\t\t\thref=\"https://github.com/origin-space/image-cropper\"\r\n\t\t\t\t\tclassName=\"hover:text-foreground underline\"\r\n\t\t\t\t\ttarget=\"_blank\"\r\n\t\t\t\t>\r\n\t\t\t\t\tcropper\r\n\t\t\t\t</a>\r\n\t\t\t</p>\r\n\t\t</div>\r\n\t);\r\n}\r\n",
      "type": "registry:ui"
    },
    {
      "path": "components/ui/button.tsx",
      "content": "import * as React from \"react\";\r\n\r\nimport { cn } from \"@/registry/utilities/cn\";\r\nimport { Slot } from \"@radix-ui/react-slot\";\r\nimport { cva, type VariantProps } from \"class-variance-authority\";\r\n\r\nconst buttonVariants = cva(\r\n\t\"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm text-white hover:text-gray-400 font-medium ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\",\r\n\t{\r\n\t\tvariants: {\r\n\t\t\tvariant: {\r\n\t\t\t\tsimple:\r\n\t\t\t\t\t\"bg-secondary relative z-10 bg-transparent hover:border-secondary hover:bg-secondary/50  border border-transparent dark:text-white text-sm md:text-sm transition font-medium duration-200  rounded-md px-4 py-2  flex items-center justify-center\",\r\n\t\t\t\tdefault: \"bg-primary text-primary-foreground hover:bg-primary/90\",\r\n\t\t\t\tdestructive:\r\n\t\t\t\t\t\"bg-destructive text-destructive-foreground hover:bg-destructive/90\",\r\n\t\t\t\toutline:\r\n\t\t\t\t\t\"border border-input bg-background hover:bg-accent hover:text-accent-foreground\",\r\n\t\t\t\tsecondary:\r\n\t\t\t\t\t\"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\r\n\t\t\t\tghost: \"hover:bg-accent hover:text-black hover:stroke-black dark:text-white text-black\",\r\n\t\t\t\tlink: \"text-primary underline-offset-4 hover:underline\",\r\n\t\t\t},\r\n\t\t\tsize: {\r\n\t\t\t\tdefault: \"h-10 px-4 py-2\",\r\n\t\t\t\tsm: \"h-9 rounded-md px-3\",\r\n\t\t\t\tlg: \"h-11 rounded-md px-8\",\r\n\t\t\t\ticon: \"h-10 w-10\",\r\n\t\t\t},\r\n\t\t},\r\n\t\tdefaultVariants: {\r\n\t\t\tvariant: \"default\",\r\n\t\t\tsize: \"default\",\r\n\t\t},\r\n\t}\r\n);\r\n\r\nexport interface ButtonProps\r\n\textends React.ButtonHTMLAttributes<HTMLButtonElement>,\r\n\t\tVariantProps<typeof buttonVariants> {\r\n\tasChild?: boolean;\r\n}\r\n\r\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\r\n\t({ className, variant, size, asChild = false, ...props }, ref) => {\r\n\t\tconst Comp = asChild ? Slot : \"button\";\r\n\t\treturn (\r\n\t\t\t<Comp\r\n\t\t\t\tclassName={cn(buttonVariants({ variant, size, className }))}\r\n\t\t\t\tref={ref}\r\n\t\t\t\t{...props}\r\n\t\t\t/>\r\n\t\t);\r\n\t}\r\n);\r\nButton.displayName = \"Button\";\r\n\r\nexport { Button, buttonVariants };\r\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/utilities/cn.ts",
      "content": "import { ClassValue, clsx } from \"clsx\";\r\nimport { twMerge } from \"tailwind-merge\";\r\n\r\nexport function cn(...inputs: ClassValue[]) {\r\n\treturn twMerge(clsx(inputs));\r\n}\r\n",
      "type": "registry:ui"
    },
    {
      "path": "components/ui/slider.tsx",
      "content": "\"use client\";\r\n\r\nimport React from \"react\";\r\n\r\nimport { cn } from \"@/registry/utilities/cn\";\r\nimport * as SliderPrimitive from \"@radix-ui/react-slider\";\r\n\r\nconst Slider = React.forwardRef<\r\n\tReact.ElementRef<typeof SliderPrimitive.Root>,\r\n\tReact.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>\r\n>(({ className, ...props }, ref) => (\r\n\t<SliderPrimitive.Root\r\n\t\tref={ref}\r\n\t\tclassName={cn(\r\n\t\t\t\"relative flex w-full touch-none select-none items-center\",\r\n\t\t\tclassName\r\n\t\t)}\r\n\t\t{...props}\r\n\t>\r\n\t\t<SliderPrimitive.Track className=\"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary\">\r\n\t\t\t<SliderPrimitive.Range className=\"absolute h-full bg-primary\" />\r\n\t\t</SliderPrimitive.Track>\r\n\t\t<SliderPrimitive.Thumb className=\"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\" />\r\n\t\t<SliderPrimitive.Thumb className=\"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50\" />\r\n\t</SliderPrimitive.Root>\r\n));\r\nSlider.displayName = SliderPrimitive.Root.displayName;\r\n\r\nexport { Slider };\r\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/utilities/usefileUpload.ts",
      "content": "\"use client\"\r\n\r\nimport type React from \"react\"\r\nimport {\r\n    useCallback,\r\n    useRef,\r\n    useState,\r\n    type ChangeEvent,\r\n    type DragEvent,\r\n    type InputHTMLAttributes,\r\n} from \"react\"\r\n\r\nexport type FileMetadata = {\r\n    name: string\r\n    size: number\r\n    type: string\r\n    url: string\r\n    id: string\r\n}\r\n\r\nexport type FileWithPreview = {\r\n    file: File | FileMetadata\r\n    id: string\r\n    preview?: string\r\n}\r\n\r\nexport type FileUploadOptions = {\r\n    maxFiles?: number // Only used when multiple is true, defaults to Infinity\r\n    maxSize?: number // in bytes\r\n    accept?: string\r\n    multiple?: boolean // Defaults to false\r\n    initialFiles?: FileMetadata[]\r\n    onFilesChange?: (files: FileWithPreview[]) => void // Callback when files change\r\n    onFilesAdded?: (addedFiles: FileWithPreview[]) => void // Callback when new files are added\r\n}\r\n\r\nexport type FileUploadState = {\r\n    files: FileWithPreview[]\r\n    isDragging: boolean\r\n    errors: string[]\r\n}\r\n\r\nexport type FileUploadActions = {\r\n    addFiles: (files: FileList | File[]) => void\r\n    removeFile: (id: string) => void\r\n    clearFiles: () => void\r\n    clearErrors: () => void\r\n    handleDragEnter: (e: DragEvent<HTMLElement>) => void\r\n    handleDragLeave: (e: DragEvent<HTMLElement>) => void\r\n    handleDragOver: (e: DragEvent<HTMLElement>) => void\r\n    handleDrop: (e: DragEvent<HTMLElement>) => void\r\n    handleFileChange: (e: ChangeEvent<HTMLInputElement>) => void\r\n    openFileDialog: () => void\r\n    getInputProps: (\r\n        props?: InputHTMLAttributes<HTMLInputElement>\r\n    ) => InputHTMLAttributes<HTMLInputElement> & {\r\n        ref: React.Ref<HTMLInputElement>\r\n    }\r\n}\r\n\r\nexport const useFileUpload = (\r\n    options: FileUploadOptions = {}\r\n): [FileUploadState, FileUploadActions] => {\r\n    const {\r\n        maxFiles = Infinity,\r\n        maxSize = Infinity,\r\n        accept = \"*\",\r\n        multiple = false,\r\n        initialFiles = [],\r\n        onFilesChange,\r\n        onFilesAdded,\r\n    } = options\r\n\r\n    const [state, setState] = useState<FileUploadState>({\r\n        files: initialFiles.map((file) => ({\r\n            file,\r\n            id: file.id,\r\n            preview: file.url,\r\n        })),\r\n        isDragging: false,\r\n        errors: [],\r\n    })\r\n\r\n    const inputRef = useRef<HTMLInputElement>(null)\r\n\r\n    const validateFile = useCallback(\r\n        (file: File | FileMetadata): string | null => {\r\n            if (file instanceof File) {\r\n                if (file.size > maxSize) {\r\n                    return `File \"${file.name}\" exceeds the maximum size of ${formatBytes(maxSize)}.`\r\n                }\r\n            } else {\r\n                if (file.size > maxSize) {\r\n                    return `File \"${file.name}\" exceeds the maximum size of ${formatBytes(maxSize)}.`\r\n                }\r\n            }\r\n\r\n            if (accept !== \"*\") {\r\n                const acceptedTypes = accept.split(\",\").map((type) => type.trim())\r\n                const fileType = file instanceof File ? file.type || \"\" : file.type\r\n                const fileExtension = `.${file instanceof File ? file.name.split(\".\").pop() : file.name.split(\".\").pop()}`\r\n\r\n                const isAccepted = acceptedTypes.some((type) => {\r\n                    if (type.startsWith(\".\")) {\r\n                        return fileExtension.toLowerCase() === type.toLowerCase()\r\n                    }\r\n                    if (type.endsWith(\"/*\")) {\r\n                        const baseType = type.split(\"/\")[0]\r\n                        return fileType.startsWith(`${baseType}/`)\r\n                    }\r\n                    return fileType === type\r\n                })\r\n\r\n                if (!isAccepted) {\r\n                    return `File \"${file instanceof File ? file.name : file.name}\" is not an accepted file type.`\r\n                }\r\n            }\r\n\r\n            return null\r\n        },\r\n        [accept, maxSize]\r\n    )\r\n\r\n    const createPreview = useCallback(\r\n        (file: File | FileMetadata): string | undefined => {\r\n            if (file instanceof File) {\r\n                return URL.createObjectURL(file)\r\n            }\r\n            return file.url\r\n        },\r\n        []\r\n    )\r\n\r\n    const generateUniqueId = useCallback((file: File | FileMetadata): string => {\r\n        if (file instanceof File) {\r\n            return `${file.name}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`\r\n        }\r\n        return file.id\r\n    }, [])\r\n\r\n    const clearFiles = useCallback(() => {\r\n        setState((prev) => {\r\n            // Clean up object URLs\r\n            prev.files.forEach((file) => {\r\n                if (\r\n                    file.preview &&\r\n                    file.file instanceof File &&\r\n                    file.file.type.startsWith(\"image/\")\r\n                ) {\r\n                    URL.revokeObjectURL(file.preview)\r\n                }\r\n            })\r\n\r\n            if (inputRef.current) {\r\n                inputRef.current.value = \"\"\r\n            }\r\n\r\n            const newState = {\r\n                ...prev,\r\n                files: [],\r\n                errors: [],\r\n            }\r\n\r\n            onFilesChange?.(newState.files)\r\n            return newState\r\n        })\r\n    }, [onFilesChange])\r\n\r\n    const addFiles = useCallback(\r\n        (newFiles: FileList | File[]) => {\r\n            if (!newFiles || newFiles.length === 0) return\r\n\r\n            const newFilesArray = Array.from(newFiles)\r\n            const errors: string[] = []\r\n\r\n            // Clear existing errors when new files are uploaded\r\n            setState((prev) => ({ ...prev, errors: [] }))\r\n\r\n            // In single file mode, clear existing files first\r\n            if (!multiple) {\r\n                clearFiles()\r\n            }\r\n\r\n            // Check if adding these files would exceed maxFiles (only in multiple mode)\r\n            if (\r\n                multiple &&\r\n                maxFiles !== Infinity &&\r\n                state.files.length + newFilesArray.length > maxFiles\r\n            ) {\r\n                errors.push(`You can only upload a maximum of ${maxFiles} files.`)\r\n                setState((prev) => ({ ...prev, errors }))\r\n                return\r\n            }\r\n\r\n            const validFiles: FileWithPreview[] = []\r\n\r\n            newFilesArray.forEach((file) => {\r\n                // Only check for duplicates if multiple files are allowed\r\n                if (multiple) {\r\n                    const isDuplicate = state.files.some(\r\n                        (existingFile) =>\r\n                            existingFile.file.name === file.name &&\r\n                            existingFile.file.size === file.size\r\n                    )\r\n\r\n                    // Skip duplicate files silently\r\n                    if (isDuplicate) {\r\n                        return\r\n                    }\r\n                }\r\n\r\n                // Check file size\r\n                if (file.size > maxSize) {\r\n                    errors.push(\r\n                        multiple\r\n                            ? `Some files exceed the maximum size of ${formatBytes(maxSize)}.`\r\n                            : `File exceeds the maximum size of ${formatBytes(maxSize)}.`\r\n                    )\r\n                    return\r\n                }\r\n\r\n                const error = validateFile(file)\r\n                if (error) {\r\n                    errors.push(error)\r\n                } else {\r\n                    validFiles.push({\r\n                        file,\r\n                        id: generateUniqueId(file),\r\n                        preview: createPreview(file),\r\n                    })\r\n                }\r\n            })\r\n\r\n            // Only update state if we have valid files to add\r\n            if (validFiles.length > 0) {\r\n                // Call the onFilesAdded callback with the newly added valid files\r\n                onFilesAdded?.(validFiles)\r\n\r\n                setState((prev) => {\r\n                    const newFiles = !multiple\r\n                        ? validFiles\r\n                        : [...prev.files, ...validFiles]\r\n                    onFilesChange?.(newFiles)\r\n                    return {\r\n                        ...prev,\r\n                        files: newFiles,\r\n                        errors,\r\n                    }\r\n                })\r\n            } else if (errors.length > 0) {\r\n                setState((prev) => ({\r\n                    ...prev,\r\n                    errors,\r\n                }))\r\n            }\r\n\r\n            // Reset input value after handling files\r\n            if (inputRef.current) {\r\n                inputRef.current.value = \"\"\r\n            }\r\n        },\r\n        [\r\n            state.files,\r\n            maxFiles,\r\n            multiple,\r\n            maxSize,\r\n            validateFile,\r\n            createPreview,\r\n            generateUniqueId,\r\n            clearFiles,\r\n            onFilesChange,\r\n            onFilesAdded,\r\n        ]\r\n    )\r\n\r\n    const removeFile = useCallback(\r\n        (id: string) => {\r\n            setState((prev) => {\r\n                const fileToRemove = prev.files.find((file) => file.id === id)\r\n                if (\r\n                    fileToRemove &&\r\n                    fileToRemove.preview &&\r\n                    fileToRemove.file instanceof File &&\r\n                    fileToRemove.file.type.startsWith(\"image/\")\r\n                ) {\r\n                    URL.revokeObjectURL(fileToRemove.preview)\r\n                }\r\n\r\n                const newFiles = prev.files.filter((file) => file.id !== id)\r\n                onFilesChange?.(newFiles)\r\n\r\n                return {\r\n                    ...prev,\r\n                    files: newFiles,\r\n                    errors: [],\r\n                }\r\n            })\r\n        },\r\n        [onFilesChange]\r\n    )\r\n\r\n    const clearErrors = useCallback(() => {\r\n        setState((prev) => ({\r\n            ...prev,\r\n            errors: [],\r\n        }))\r\n    }, [])\r\n\r\n    const handleDragEnter = useCallback((e: DragEvent<HTMLElement>) => {\r\n        e.preventDefault()\r\n        e.stopPropagation()\r\n        setState((prev) => ({ ...prev, isDragging: true }))\r\n    }, [])\r\n\r\n    const handleDragLeave = useCallback((e: DragEvent<HTMLElement>) => {\r\n        e.preventDefault()\r\n        e.stopPropagation()\r\n\r\n        if (e.currentTarget.contains(e.relatedTarget as Node)) {\r\n            return\r\n        }\r\n\r\n        setState((prev) => ({ ...prev, isDragging: false }))\r\n    }, [])\r\n\r\n    const handleDragOver = useCallback((e: DragEvent<HTMLElement>) => {\r\n        e.preventDefault()\r\n        e.stopPropagation()\r\n    }, [])\r\n\r\n    const handleDrop = useCallback(\r\n        (e: DragEvent<HTMLElement>) => {\r\n            e.preventDefault()\r\n            e.stopPropagation()\r\n            setState((prev) => ({ ...prev, isDragging: false }))\r\n\r\n            // Don't process files if the input is disabled\r\n            if (inputRef.current?.disabled) {\r\n                return\r\n            }\r\n\r\n            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {\r\n                // In single file mode, only use the first file\r\n                if (!multiple) {\r\n                    const file = e.dataTransfer.files[0]\r\n                    addFiles([file])\r\n                } else {\r\n                    addFiles(e.dataTransfer.files)\r\n                }\r\n            }\r\n        },\r\n        [addFiles, multiple]\r\n    )\r\n\r\n    const handleFileChange = useCallback(\r\n        (e: ChangeEvent<HTMLInputElement>) => {\r\n            if (e.target.files && e.target.files.length > 0) {\r\n                addFiles(e.target.files)\r\n            }\r\n        },\r\n        [addFiles]\r\n    )\r\n\r\n    const openFileDialog = useCallback(() => {\r\n        if (inputRef.current) {\r\n            inputRef.current.click()\r\n        }\r\n    }, [])\r\n\r\n    const getInputProps = useCallback(\r\n        (props: InputHTMLAttributes<HTMLInputElement> = {}) => {\r\n            return {\r\n                ...props,\r\n                type: \"file\" as const,\r\n                onChange: handleFileChange,\r\n                accept: props.accept || accept,\r\n                multiple: props.multiple !== undefined ? props.multiple : multiple,\r\n                ref: inputRef,\r\n            }\r\n        },\r\n        [accept, multiple, handleFileChange]\r\n    )\r\n\r\n    return [\r\n        state,\r\n        {\r\n            addFiles,\r\n            removeFile,\r\n            clearFiles,\r\n            clearErrors,\r\n            handleDragEnter,\r\n            handleDragLeave,\r\n            handleDragOver,\r\n            handleDrop,\r\n            handleFileChange,\r\n            openFileDialog,\r\n            getInputProps,\r\n        },\r\n    ]\r\n}\r\n\r\n// Helper function to format bytes to human-readable format\r\nexport const formatBytes = (bytes: number, decimals = 2): string => {\r\n    if (bytes === 0) return \"0 Bytes\"\r\n\r\n    const k = 1024\r\n    const dm = decimals < 0 ? 0 : decimals\r\n    const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"]\r\n\r\n    const i = Math.floor(Math.log(bytes) / Math.log(k))\r\n\r\n    return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + sizes[i]\r\n}",
      "type": "registry:ui"
    }
  ]
}