1
0
Fork 0
polaris-task-force/src/components/frontend/storage/InventoryGrid.tsx
Z8MB1E 7c135cd282 fix(grids): resize drag preview when rotating mid-drag
dnd-kit pins the DragOverlay container to the activator rect measured
at drag start, so pressing R while dragging left the preview at the
pre-rotation footprint (a square-ish box for elongated items). Pass the
live rotated dimensions through the DragOverlay style prop, which is
spread after the pinned rect, in all three R-to-rotate grids: garage
vehicle bay, locker, and structure storage.
2026-10-13 16:42:50 -04:00

376 lines
12 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
DragOverlay,
type DragStartEvent,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { GameStructure, Resource, Structure } from "@/payload-types";
import {
getGridOccupancy,
getItemFootprint,
type GridItem,
isValidPlacement,
} from "@/lib/logistics";
import { GridItemComponent } from "./GridItem";
import { GridCell } from "./GridCell";
function DragOverlayContent({
item,
cellSize,
rotated,
}: {
item: GridItem;
cellSize: number;
rotated?: boolean;
}) {
const resource = item.resource as Resource;
const effective = rotated ?? item.rotated;
const { width, height } = getItemFootprint(resource, effective);
const bgColor = resource.color ?? "oklch(0.269 0 0)";
return (
<div
style={{
width: width * cellSize - 2,
height: height * cellSize - 2,
}}
className="relative rounded-md border border-primary/50 shadow-xl ring-2 ring-primary/50 select-none overflow-hidden flex flex-col items-center justify-center gap-0.5"
>
<div className="absolute inset-0 opacity-20" style={{ backgroundColor: bgColor }} />
<div className="relative flex flex-col items-center justify-center gap-0.5 p-1 w-full h-full">
{resource.icon && typeof resource.icon === "object" && "url" in resource.icon && (
<img
src={resource.icon.url ?? ""}
alt={resource.name}
className="size-6 object-contain opacity-80"
/>
)}
<span className="text-[10px] leading-tight font-medium text-center text-foreground/90 line-clamp-2 px-0.5">
{resource.name}
</span>
{item.amount > 1 && (
<span
className="text-[9px] font-bold leading-none px-1 py-0.5 rounded-sm"
style={{ backgroundColor: bgColor, color: "white" }}
>
{item.amount.toLocaleString()}
</span>
)}
</div>
</div>
);
}
function findMergeTarget(
items: GridItem[],
dragged: GridItem,
targetX: number,
targetY: number,
rotated?: boolean,
): GridItem | null {
const effective = rotated ?? dragged.rotated;
const fp = getItemFootprint(dragged.resource as Resource, effective);
const targetCells = new Set<string>();
for (let dx = 0; dx < fp.width; dx++) {
for (let dy = 0; dy < fp.height; dy++) {
targetCells.add(`${targetX + dx},${targetY + dy}`);
}
}
for (const other of items) {
if (other.id === dragged.id) continue;
if (other.resourceId !== dragged.resourceId) continue;
const otherFp = getItemFootprint(other.resource as Resource, other.rotated);
for (let dx = 0; dx < otherFp.width; dx++) {
for (let dy = 0; dy < otherFp.height; dy++) {
if (targetCells.has(`${other.gridX + dx},${other.gridY + dy}`)) {
return other;
}
}
}
}
return null;
}
interface InventoryGridProps {
structure: GameStructure & { type: Structure };
storedResources: GridItem[];
onMoveItem: (entryId: string, gridX: number, gridY: number, rotated?: boolean) => Promise<void>;
onMergeStacks: (sourceId: string, targetId: string) => Promise<void>;
onRotateItem: (entryId: string) => Promise<void>;
onRemoveItem: (entryId: string) => Promise<void>;
onSelectItem: (item: GridItem | null) => void;
selectedItem: GridItem | null;
}
export function InventoryGrid({
structure,
storedResources,
onMoveItem,
onMergeStacks,
onRotateItem,
onRemoveItem,
onSelectItem,
selectedItem,
}: InventoryGridProps) {
const [activeItem, setActiveItem] = useState<GridItem | null>(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [cellSize, setCellSize] = useState(48);
const gridRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const gridWidth = structure.type.xSize ?? 1;
const gridHeight = structure.type.ySize ?? 1;
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const w = entry.contentRect.width;
const computed = Math.floor(w / gridWidth);
setCellSize(Math.max(32, Math.min(computed, 80)));
}
});
observer.observe(el);
return () => observer.disconnect();
}, [gridWidth]);
useEffect(() => {
if (!activeItem) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "r" || e.key === "R") {
e.preventDefault();
setPendingRotated((v) => !v);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [activeItem]);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: { distance: 5 },
}),
);
const occupiedCells = useMemo(() => {
const cells = new Set<string>();
for (const item of storedResources) {
const fp = getItemFootprint(item.resource as Resource, item.rotated);
for (let dx = 0; dx < fp.width; dx++) {
for (let dy = 0; dy < fp.height; dy++) {
cells.add(`${item.gridX + dx},${item.gridY + dy}`);
}
}
}
return cells;
}, [storedResources]);
const occupancy = getGridOccupancy(storedResources, gridWidth, gridHeight);
const hoverInfo = useMemo(() => {
if (!hoverPosition || !activeItem) return null;
const res = activeItem.resource as Resource;
const fp = getItemFootprint(res, pendingRotated);
const cells = new Set<string>();
for (let dx = 0; dx < fp.width; dx++) {
for (let dy = 0; dy < fp.height; dy++) {
cells.add(`${hoverPosition.x + dx},${hoverPosition.y + dy}`);
}
}
const mergeTarget = findMergeTarget(
storedResources,
activeItem,
hoverPosition.x,
hoverPosition.y,
pendingRotated,
);
const valid =
mergeTarget !== null ||
isValidPlacement(
storedResources,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
return { cells, valid };
}, [hoverPosition, activeItem, storedResources, gridWidth, gridHeight, pendingRotated]);
const handleDragStart = useCallback((event: DragStartEvent) => {
const data = event.active.data.current;
if (data?.item) {
const item = data.item as GridItem;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
}
setHoverPosition(null);
}, []);
const handleDragMove = useCallback(
(event: DragMoveEvent) => {
const { activatorEvent, delta } = event;
const gridEl = gridRef.current;
if (!gridEl) return;
const rect = gridEl.getBoundingClientRect();
if (!("clientX" in activatorEvent)) return;
const px = (activatorEvent as PointerEvent).clientX + delta.x;
const py = (activatorEvent as PointerEvent).clientY + delta.y;
const x = Math.floor((px - rect.left) / cellSize);
const y = Math.floor((py - rect.top) / cellSize);
if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) {
setHoverPosition(null);
return;
}
setHoverPosition({ x, y });
},
[gridWidth, gridHeight, cellSize],
);
const handleDragEnd = useCallback(
async (event: DragEndEvent) => {
setActiveItem(null);
setHoverPosition(null);
const { active, activatorEvent, delta } = event;
const item = active.data.current?.item as GridItem | undefined;
if (!item) return;
const gridEl = gridRef.current;
if (!gridEl) return;
const rect = gridEl.getBoundingClientRect();
if (!("clientX" in activatorEvent)) return;
const px = (activatorEvent as PointerEvent).clientX + delta.x;
const py = (activatorEvent as PointerEvent).clientY + delta.y;
const targetX = Math.floor((px - rect.left) / cellSize);
const targetY = Math.floor((py - rect.top) / cellSize);
if (targetX < 0 || targetY < 0 || targetX >= gridWidth || targetY >= gridHeight) return;
if (targetX === item.gridX && targetY === item.gridY) {
if (pendingRotated === item.rotated) return;
await onMoveItem(item.id, targetX, targetY, pendingRotated);
return;
}
const mergeTarget = findMergeTarget(storedResources, item, targetX, targetY, pendingRotated);
if (mergeTarget) {
await onMergeStacks(item.id, mergeTarget.id);
return;
}
const res = item.resource as Resource;
const fp = getItemFootprint(res, pendingRotated);
const valid = isValidPlacement(
storedResources,
item.id,
targetX,
targetY,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
if (valid) {
await onMoveItem(item.id, targetX, targetY, pendingRotated);
}
},
[storedResources, gridWidth, gridHeight, onMoveItem, onMergeStacks, cellSize, pendingRotated],
);
const handleBackgroundClick = useCallback(() => {
onSelectItem(null);
}, [onSelectItem]);
return (
<DndContext
sensors={sensors}
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
>
<div className="flex flex-col gap-3">
<div ref={containerRef} className="rounded-lg border bg-muted/20 p-2">
<div
ref={gridRef}
className="relative grid"
style={{
gridTemplateColumns: `repeat(${gridWidth}, ${cellSize}px)`,
gridTemplateRows: `repeat(${gridHeight}, ${cellSize}px)`,
}}
onClick={handleBackgroundClick}
>
{Array.from({ length: gridHeight }, (_, y) =>
Array.from({ length: gridWidth }, (_, x) => {
const key = `${x},${y}`;
return (
<GridCell
key={key}
x={x}
y={y}
cellSize={cellSize}
isOccupied={occupiedCells.has(key)}
isDropTarget={!!activeItem}
isHovered={hoverInfo !== null && hoverInfo.cells.has(key)}
isInvalidDrop={hoverInfo !== null && !hoverInfo.valid}
/>
);
}),
)}
{storedResources.map((item) => (
<GridItemComponent
key={item.id}
item={item}
cellSize={cellSize}
onSelect={onSelectItem}
selected={selectedItem?.id === item.id}
/>
))}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>
{occupancy.used} / {occupancy.total} cells used
</span>
<span>
{gridWidth} x {gridHeight}
</span>
</div>
</div>
<DragOverlay
dropAnimation={null}
style={
activeItem
? (() => {
// dnd-kit pins the overlay container to the activator rect
// from drag start; override width/height so mid-drag rotation
// resizes the preview (style is spread after the pinned rect).
const fp = getItemFootprint(activeItem.resource as Resource, pendingRotated);
return { width: fp.width * cellSize - 2, height: fp.height * cellSize - 2 };
})()
: undefined
}
>
{activeItem && (
<DragOverlayContent item={activeItem} cellSize={cellSize} rotated={pendingRotated} />
)}
</DragOverlay>
</DndContext>
);
}