import { useEffect, useRef, useState } from 'react';
import {
DndContext,
DragOverlay,
PointerSensor,
pointerWithin,
closestCenter,
useSensor,
useSensors,
type DragStartEvent,
type DragEndEvent,
type CollisionDetection,
} from '@dnd-kit/core';
import { SortableContext, horizontalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { toast } from 'sonner';
import { useRackStore } from '../../store/useRackStore';
import { apiClient } from '../../api/client';
import { RackToolbar } from './RackToolbar';
import { RackColumn } from './RackColumn';
import { DevicePalette } from './DevicePalette';
import { AddModuleModal } from '../modals/AddModuleModal';
import { RackSkeleton } from '../ui/Skeleton';
import type { ModuleType } from '../../types';
import { MODULE_TYPE_COLORS, MODULE_TYPE_LABELS } from '../../lib/constants';
import { cn } from '../../lib/utils';
interface PendingDrop {
rackId: string;
uPosition: number;
type: ModuleType;
}
function DragOverlayItem({ type }: { type: ModuleType }) {
const colors = MODULE_TYPE_COLORS[type];
return (
{MODULE_TYPE_LABELS[type]}
);
}
function ModuleDragOverlay({ label }: { label: string }) {
return (
{label}
);
}
/**
* Collision detection strategy:
*
* Problem: SortableContext registers each rack column as a droppable. Columns
* are ~1800px tall; individual slots are 44px. Default closestCenter picks the
* column centre over any slot centre. pointerWithin returns multiple matches
* sorted by registration order (columns register before their child slots), so
* the rack column still wins.
*
* Fix:
* 1. First try pointerWithin restricted to ONLY elements whose data has
* dropType === 'slot'. This is an exact hit-test against the 44px slot rects.
* 2. Fall back to closestCenter over ALL droppables so rack-header reorder
* (which needs the sortable rack targets) still works.
*/
const slotFirstCollision: CollisionDetection = (args) => {
// droppableContainers is a custom NodeMap (not a plain Array) — it only
// implements [Symbol.iterator], so .filter() doesn't exist on it.
// Convert to Array first before filtering.
const allContainers = Array.from(args.droppableContainers);
const slotContainers = allContainers.filter(
(c) => c.data.current?.dropType === 'slot'
);
if (slotContainers.length > 0) {
const slotHits = pointerWithin({ ...args, droppableContainers: slotContainers as typeof args.droppableContainers });
if (slotHits.length > 0) return slotHits;
}
// Nothing hit a slot — use full closestCenter for rack reorder
return closestCenter(args);
};
export function RackPlanner() {
const { racks, loading, fetchRacks, moveModule, updateRack } = useRackStore();
const canvasRef = useRef(null);
// Drag state
const [activePaletteType, setActivePaletteType] = useState(null);
const [activeDragModuleLabel, setActiveDragModuleLabel] = useState(null);
const [draggingModuleId, setDraggingModuleId] = useState(null);
const [pendingDrop, setPendingDrop] = useState(null);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } })
);
useEffect(() => {
fetchRacks().catch(() => toast.error('Failed to load racks'));
}, [fetchRacks]);
function handleDragStart(event: DragStartEvent) {
const data = event.active.data.current as Record;
if (data?.dragType === 'palette') {
setActivePaletteType(data.type as ModuleType);
} else if (data?.dragType === 'module') {
setDraggingModuleId(data.moduleId as string);
setActiveDragModuleLabel(data.label as string);
}
}
async function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
setActivePaletteType(null);
setActiveDragModuleLabel(null);
setDraggingModuleId(null);
if (!over) return;
const dragData = active.data.current as Record;
const dropData = over.data.current as Record | undefined;
// --- Palette → slot: open AddModuleModal pre-filled ---
if (dragData?.dragType === 'palette' && dropData?.dropType === 'slot') {
setPendingDrop({
type: dragData.type as ModuleType,
rackId: dropData.rackId as string,
uPosition: dropData.uPosition as number,
});
return;
}
// --- Module → slot: move the module ---
if (dragData?.dragType === 'module' && dropData?.dropType === 'slot') {
const moduleId = dragData.moduleId as string;
const targetRackId = dropData.rackId as string;
const targetUPosition = dropData.uPosition as number;
// No-op if dropped on own position
if (dragData.fromRackId === targetRackId && dragData.fromUPosition === targetUPosition) return;
try {
await moveModule(moduleId, targetRackId, targetUPosition);
toast.success('Module moved');
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Move failed');
}
return;
}
// --- Rack header → rack header: reorder racks ---
if (dragData?.dragType === 'rack' && over.data.current?.dragType === 'rack') {
const oldIndex = racks.findIndex((r) => r.id === active.id);
const newIndex = racks.findIndex((r) => r.id === over.id);
if (oldIndex === newIndex) return;
const reordered = arrayMove(racks, oldIndex, newIndex);
// Persist new displayOrder values
try {
await Promise.all(
reordered.map((rack, idx) =>
rack.displayOrder !== idx ? apiClient.racks.update(rack.id, { displayOrder: idx }) : Promise.resolve(rack)
)
);
// Refresh store to sync
await fetchRacks();
} catch {
toast.error('Failed to save rack order');
await fetchRacks(); // rollback
}
}
}
const rackIds = racks.map((r) => r.id);
return (
{loading ? (
) : racks.length === 0 ? (
No racks yet
Click Add Rack in the toolbar to create your first rack.
) : (
{racks.map((rack) => (
))}
)}
{activePaletteType && }
{activeDragModuleLabel && }
{pendingDrop && (
setPendingDrop(null)}
rackId={pendingDrop.rackId}
uPosition={pendingDrop.uPosition}
initialType={pendingDrop.type}
/>
)}
);
}