1
0
Fork 0
polaris-task-force/src/components/frontend/locker/LockerGrid.tsx

667 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
DragOverlay,
type DragStartEvent,
PointerSensor,
useDraggable,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import {
Backpack,
Crosshair,
FlaskConical,
Gem,
Glasses,
Hammer,
Headset,
Luggage,
Monitor,
MoonStar,
Package,
Palette,
Shield,
Shirt,
Tag,
Target,
Wrench,
} from "lucide-react";
import type { Asset } from "@/payload-types";
import {
ATTACHMENT_CATEGORIES,
findLockerMergeTarget,
getLockerGridOccupancy,
getLockerItemFootprint,
isAttachmentCompatible,
isLockerPlacementValid,
type LockerGridItem,
type LockerItemEquipment,
resolveAssetId,
} from "@/lib/locker";
import { GridCell } from "@/components/frontend/storage/GridCell";
import type { ActionResult } from "@/app/(frontend)/locker/actions";
import { cn } from "@/lib/utils";
export function getAssetIcon(assetType: Asset["assetType"], className?: string) {
const cls = className ?? "size-4";
switch (assetType) {
case "weapon":
return <Crosshair className={cls} />;
case "magazine":
return <Package className={cls} />;
case "optic":
return <Target className={cls} />;
case "muzzle":
return <FlaskConical className={cls} />;
case "bipod":
return <Hammer className={cls} />;
case "uniform":
return <Shirt className={cls} />;
case "vest":
return <Shield className={cls} />;
case "backpack":
return <Backpack className={cls} />;
case "helmet":
return <Shield className={cls} />;
case "facewear":
return <Glasses className={cls} />;
case "nvg":
return <MoonStar className={cls} />;
case "radio":
return <Headset className={cls} />;
case "medical":
return <Monitor className={cls} />;
case "tool":
return <Wrench className={cls} />;
case "explosive":
return <Gem className={cls} />;
case "skin":
return <Palette className={cls} />;
case "miscellaneous":
return <Luggage className={cls} />;
default:
return <Package className={cls} />;
}
}
function assetThumbnailUrl(asset: Asset): string | null {
const thumb = asset["Asset Metadata"]?.thumbnail;
if (thumb && typeof thumb === "object" && "url" in thumb) return thumb.url ?? null;
return null;
}
function itemContainsCell(item: LockerGridItem, x: number, y: number): boolean {
const fp = getLockerItemFootprint(item.asset, item.rotated);
return (
x >= item.gridX && x < item.gridX + fp.width && y >= item.gridY && y < item.gridY + fp.height
);
}
export function LockerItemFace({
asset,
quantity,
rotated,
cellSize,
equipment,
}: {
asset: Asset;
quantity: number;
rotated?: boolean;
cellSize: number;
equipment?: LockerItemEquipment;
}) {
const fp = getLockerItemFootprint(asset, rotated ?? false);
const thumb = assetThumbnailUrl(asset);
const displayName = equipment?.customName?.trim() || asset.name;
const hasCustomName = !!equipment?.customName?.trim();
const hasSkin = equipment?.skin != null;
const attachmentCount = equipment?.attachments?.length ?? 0;
return (
<div
style={{
width: fp.width * cellSize - 2,
height: fp.height * cellSize - 2,
}}
className="relative flex select-none flex-col items-center justify-center overflow-hidden rounded-sm bg-card/60"
>
{/* Subtle selection glow */}
{(hasSkin || attachmentCount > 0 || hasCustomName) && (
<div className="absolute inset-0 bg-primary/5" />
)}
{(hasSkin || attachmentCount > 0 || hasCustomName) && (
<div className="absolute right-0.5 top-0.5 z-10 flex flex-col items-end gap-0.5">
{hasCustomName && (
<span
className="rounded-sm border border-primary/30 bg-primary/15 p-0.5 text-primary"
title="Custom name"
>
<Tag className="size-2.5" />
</span>
)}
{hasSkin && (
<span
className="rounded-sm border border-amber-400/30 bg-amber-400/15 p-0.5 text-amber-200"
title="Skin applied"
>
<Palette className="size-2.5" />
</span>
)}
{attachmentCount > 0 && (
<span
className="flex items-center gap-0.5 rounded-sm border border-primary/30 bg-primary/15 px-0.5 py-0.5 text-primary"
title={`${attachmentCount} attachment${attachmentCount === 1 ? "" : "s"}`}
>
<Crosshair className="size-2.5" />
<span className="font-mono text-[10px] font-semibold leading-none tabular-nums">
{attachmentCount}
</span>
</span>
)}
</div>
)}
<div className="relative flex h-full w-full flex-col items-center justify-center gap-1 p-0.5">
{thumb ? (
<img src={thumb} alt={displayName} className="size-5.5 object-contain opacity-85" />
) : (
<span className="text-primary/60">{getAssetIcon(asset.assetType, "size-4")}</span>
)}
<span className="line-clamp-1 px-1 text-center text-[10px] font-medium leading-tight text-foreground/80">
{displayName}
</span>
{quantity > 1 && (
<span className="rounded-sm bg-primary/15 px-0.5 py-0.5 font-mono text-[10px] font-semibold leading-none tabular-nums text-primary">
{quantity.toLocaleString()}
</span>
)}
</div>
</div>
);
}
function DraggableLockerItem({
item,
cellSize,
onSelect,
selected,
highlight,
}: {
item: LockerGridItem;
cellSize: number;
onSelect: (item: LockerGridItem) => void;
selected: boolean;
highlight?: boolean;
}) {
const didDrag = useRef(false);
const fp = getLockerItemFootprint(item.asset, item.rotated);
const displayName = item.equipment?.customName?.trim() || item.asset.name;
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: `grid-item-${item.id}`,
data: { item },
});
useEffect(() => {
if (isDragging) didDrag.current = true;
}, [isDragging]);
const handleClick = useCallback(
(e: React.MouseEvent) => {
if (!didDrag.current) {
e.stopPropagation();
onSelect(item);
}
didDrag.current = false;
},
[item, onSelect],
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
onSelect(item);
},
[item, onSelect],
);
const style: React.CSSProperties = {
position: "absolute",
left: item.gridX * cellSize,
top: item.gridY * cellSize,
width: fp.width * cellSize - 2,
height: fp.height * cellSize - 2,
zIndex: 10,
transition: isDragging ? "none" : "left 0.15s ease, top 0.15s ease",
transform: CSS.Translate.toString(transform),
opacity: isDragging ? 0 : 1,
};
return (
<div
ref={setNodeRef}
style={style}
className={cn(
"group cursor-grab select-none overflow-hidden rounded-sm border border-border/60 bg-card/80 active:cursor-grabbing",
"transition-all duration-200 hover:border-border/90 hover:bg-card focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-reduce:transition-none",
selected && "ring-2 ring-primary ring-offset-2 ring-offset-background",
!selected && "hover:ring-1 hover:ring-primary/40",
highlight && "locker-search-highlight motion-reduce:animate-none",
)}
{...listeners}
{...attributes}
onClick={handleClick}
onKeyDown={handleKeyDown}
aria-label={`${displayName}, quantity ${item.quantity.toLocaleString()}`}
suppressHydrationWarning
>
<LockerItemFace
asset={item.asset}
quantity={item.quantity}
rotated={item.rotated}
cellSize={cellSize}
equipment={item.equipment}
/>
</div>
);
}
interface LockerGridProps {
gridWidth: number;
gridHeight: number;
items: LockerGridItem[];
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: LockerGridItem | null) => void;
selectedItem: LockerGridItem | null;
highlightId?: string | null;
onAttachItem?: (weaponEntryId: string, attachmentEntryId: string) => Promise<ActionResult>;
}
export function LockerGrid({
gridWidth,
gridHeight,
items,
onMoveItem,
onMergeStacks,
onRotateItem,
onRemoveItem,
onSelectItem,
selectedItem,
highlightId,
onAttachItem,
}: LockerGridProps) {
const [activeItem, setActiveItem] = useState<LockerGridItem | null>(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [dragError, setDragError] = useState<string | null>(null);
const dragErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [cellSize, setCellSize] = useState(48);
const gridRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
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 items) {
const fp = getLockerItemFootprint(item.asset, 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;
}, [items]);
const occupancy = getLockerGridOccupancy(items, gridWidth, gridHeight);
const hoverInfo = useMemo(() => {
if (!hoverPosition || !activeItem) return null;
const fp = getLockerItemFootprint(activeItem.asset, pendingRotated);
const isAttachment = ATTACHMENT_CATEGORIES.some(
(c) => c.assetType === activeItem.asset.assetType,
);
const targetItem =
items.find(
(it) => it.id !== activeItem.id && itemContainsCell(it, hoverPosition.x, hoverPosition.y),
) ?? null;
const mergeTarget = findLockerMergeTarget(
items,
activeItem,
hoverPosition.x,
hoverPosition.y,
pendingRotated,
);
let mode: "move" | "merge" | "attach" = "move";
if (mergeTarget) {
mode = "merge";
} else if (
isAttachment &&
targetItem?.asset.assetType === "weapon" &&
isAttachmentCompatible(targetItem.asset, activeItem.asset)
) {
const alreadyInstalled = (targetItem.equipment?.attachments ?? []).some(
(a) => resolveAssetId(a.asset) === activeItem.assetId,
);
if (!alreadyInstalled) {
mode = "attach";
}
}
const cells = new Set<string>();
if (mode === "attach" && targetItem) {
const tFp = getLockerItemFootprint(targetItem.asset, targetItem.rotated);
for (let dx = 0; dx < tFp.width; dx++) {
for (let dy = 0; dy < tFp.height; dy++) {
cells.add(`${targetItem.gridX + dx},${targetItem.gridY + dy}`);
}
}
} else {
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 valid =
mode !== "move" ||
isLockerPlacementValid(
items,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
return { cells, valid, isAttachDrop: mode === "attach" };
}, [hoverPosition, activeItem, items, gridWidth, gridHeight, pendingRotated]);
const handleDragStart = useCallback((event: DragStartEvent) => {
const data = event.active.data.current;
if (data?.item) {
const item = data.item as LockerGridItem;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
}
setHoverPosition(null);
setDragError(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 LockerGridItem | 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 = findLockerMergeTarget(items, item, targetX, targetY, pendingRotated);
if (mergeTarget) {
await onMergeStacks(item.id, mergeTarget.id);
return;
}
if (onAttachItem) {
const isAttachment = ATTACHMENT_CATEGORIES.some(
(c) => c.assetType === item.asset.assetType,
);
const targetItem =
items.find((it) => it.id !== item.id && itemContainsCell(it, targetX, targetY)) ?? null;
if (
isAttachment &&
targetItem?.asset.assetType === "weapon" &&
isAttachmentCompatible(targetItem.asset, item.asset)
) {
const alreadyInstalled = (targetItem.equipment?.attachments ?? []).some(
(a) => resolveAssetId(a.asset) === item.assetId,
);
if (!alreadyInstalled) {
const result = await onAttachItem(targetItem.id, item.id);
if (!result.success && result.error) {
setDragError(result.error);
if (dragErrorTimer.current) clearTimeout(dragErrorTimer.current);
dragErrorTimer.current = setTimeout(() => setDragError(null), 5000);
}
return;
}
}
}
const fp = getLockerItemFootprint(item.asset, pendingRotated);
const valid = isLockerPlacementValid(
items,
item.id,
targetX,
targetY,
fp.width,
fp.height,
gridWidth,
gridHeight,
);
if (valid) {
await onMoveItem(item.id, targetX, targetY, pendingRotated);
}
},
[
items,
gridWidth,
gridHeight,
onMoveItem,
onMergeStacks,
onAttachItem,
cellSize,
pendingRotated,
],
);
const handleBackgroundClick = useCallback(() => {
onSelectItem(null);
}, [onSelectItem]);
// Drag preview must track mid-drag rotation: dnd-kit pins the overlay
// container to the activator rect captured at drag start, so we override
// its width/height via the style prop (spread after the pinned rect).
const overlayFp = activeItem
? getLockerItemFootprint(activeItem.asset, pendingRotated)
: null;
return (
<DndContext
sensors={sensors}
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
>
<div className="flex flex-col gap-2">
{/* Tactical grid frame */}
<div
ref={containerRef}
className="inventory-frame relative min-w-0 max-w-full overflow-auto overscroll-contain rounded border border-border bg-card/80 shadow-sm"
role="region"
aria-label="Locker inventory grid"
tabIndex={0}
>
<div
ref={gridRef}
className="relative grid bg-background/10"
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}
isAttachDrop={hoverInfo?.isAttachDrop ?? false}
/>
);
}),
)}
{items.filter((item) => item.quantity >= 1).map((item) => (
<DraggableLockerItem
key={item.id}
item={item}
cellSize={cellSize}
onSelect={onSelectItem}
selected={selectedItem?.id === item.id}
highlight={highlightId === item.id}
/>
))}
</div>
</div>
{/* Tactical metadata strip */}
<div className="metadata-strip flex flex-wrap items-center justify-between gap-2 border-t border-border/60 px-2 py-2 text-[10px] text-muted-foreground/70">
<div className="flex items-center gap-4">
<span>
<span className="font-mono tabular-nums text-foreground/80">
USAGE
</span>
<span className="mx-1 text-muted-foreground/40">:</span>
<span className="font-mono tabular-nums text-foreground/80">
{occupancy.used} / {occupancy.total}
</span>
</span>
<span>
<span className="font-mono tabular-nums text-foreground/80">
GRID
</span>
<span className="mx-1 text-muted-foreground/40">:</span>
<span className="font-mono tabular-nums text-foreground/80">
{gridWidth}×{gridHeight}
</span>
</span>
</div>
<span className="hidden sm:inline">
SELECT to inspect · DRAG to move · R to rotate
</span>
</div>
{dragError && (
<p role="alert" className="text-[10px] text-destructive">
{dragError}
</p>
)}
</div>
{/* Tactical drag overlay */}
<DragOverlay
dropAnimation={null}
style={
overlayFp
? { width: overlayFp.width * cellSize, height: overlayFp.height * cellSize }
: undefined
}
>
{activeItem && (
<div className="h-full w-full rounded-sm border border-primary/50 bg-card shadow-lg ring-2 ring-primary/40">
<LockerItemFace
asset={activeItem.asset}
quantity={activeItem.quantity}
rotated={pendingRotated}
cellSize={cellSize}
equipment={activeItem.equipment}
/>
</div>
)}
</DragOverlay>
</DndContext>
);
}