From 47288849319b7cec46aaf83f81845fb1ba5986d4 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Fri, 4 Jul 2025 01:30:24 +0200 Subject: refactor: new reusable draggable-item component and use it --- apps/web/src/components/ui/draggable-item.tsx | 150 ++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 apps/web/src/components/ui/draggable-item.tsx (limited to 'apps/web/src/components/ui') diff --git a/apps/web/src/components/ui/draggable-item.tsx b/apps/web/src/components/ui/draggable-item.tsx new file mode 100644 index 00000000..c24e31d3 --- /dev/null +++ b/apps/web/src/components/ui/draggable-item.tsx @@ -0,0 +1,150 @@ +"use client"; + +import { AspectRatio } from "@/components/ui/aspect-ratio"; +import { Button } from "@/components/ui/button"; +import { ReactNode, useState, useRef, useEffect } from "react"; +import { createPortal } from "react-dom"; +import { Plus } from "lucide-react"; +import { cn } from "@/lib/utils"; + +export interface DraggableMediaItemProps { + name: string; + preview: ReactNode; + dragData: Record; + onDragStart?: (e: React.DragEvent) => void; + aspectRatio?: number; + className?: string; + showPlusOnDrag?: boolean; + showLabel?: boolean; + rounded?: boolean; +} + +export function DraggableMediaItem({ + name, + preview, + dragData, + onDragStart, + aspectRatio = 16 / 9, + className = "", + showPlusOnDrag = true, + showLabel = true, + rounded = true, +}: DraggableMediaItemProps) { + const [isDragging, setIsDragging] = useState(false); + const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 }); + const dragRef = useRef(null); + + useEffect(() => { + if (!isDragging) return; + + const handleDragOver = (e: DragEvent) => { + setDragPosition({ x: e.clientX, y: e.clientY }); + }; + + document.addEventListener("dragover", handleDragOver); + + return () => { + document.removeEventListener("dragover", handleDragOver); + }; + }, [isDragging]); + + const handleDragStart = (e: React.DragEvent) => { + // Hide the default ghost image + const emptyImg = new Image(); + emptyImg.src = + "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="; + e.dataTransfer.setDragImage(emptyImg, 0, 0); + + // Set drag data + e.dataTransfer.setData( + "application/x-media-item", + JSON.stringify(dragData) + ); + e.dataTransfer.effectAllowed = "copy"; + + // Set initial position and show custom drag preview + setDragPosition({ x: e.clientX, y: e.clientY }); + setIsDragging(true); + + onDragStart?.(e); + }; + + const handleDragEnd = () => { + setIsDragging(false); + }; + + return ( + <> +
+ +
+ + {/* Custom drag preview */} + {isDragging && + typeof document !== "undefined" && + createPortal( +
+
+ +
+ {preview} +
+ {showPlusOnDrag && } +
+
+
, + document.body + )} + + ); +} + +function PlusButton({ className }: { className?: string }) { + return ( + + ); +} -- cgit v1.3.1