1
0
Fork 0
polaris-task-force/src/components/frontend/garage/GarageGrid.tsx
Z8MB1E fe57d63311 fix(garage): always fit the vehicle bay grid to its container
Cell size was computed from the wrapper width without subtracting the
inventory frame's p-2 padding and borders, so the grid was ~16px wider
than its container and grew a horizontal scrollbar. Subtract the 18px
frame chrome, lower the cell floor 40->24 (legibility guard only), and
switch the wrapper to overflow-hidden so no scrollbar can appear.
2026-10-13 16:43:16 -04:00

467 lines
15 KiB
TypeScript

"use client";
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
import {
DndContext,
type DragEndEvent,
type DragMoveEvent,
type DragStartEvent,
DragOverlay,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import { useDraggable } from "@dnd-kit/core";
import { ShieldAlert, Truck as TruckIcon } from "lucide-react";
import { GridCell } from "@/components/frontend/storage/GridCell";
import { cn } from "@/lib/utils";
/**
* Garage vehicle bay grid. Modeled on storage/InventoryGrid and
* locker/LockerGrid (dnd-kit, hover cell preview, R-to-rotate), but items are
* vehicle instances with per-template footprints. Dragging ONLY rearranges
* cells (server action moveGarageItem); real game movement is the explicit
* Dispatch/Store actions in GarageView. Dense data UI: plain shadcn + site
* dark theme, no dossier styling (D12).
*/
export interface GarageVehicleItem {
/** game-vehicles instance id. */
id: number;
name: string;
status: "idle" | "assigned" | "in_transit" | "damaged" | "destroyed";
gridX: number;
gridY: number;
rotated: boolean;
/** Template footprint at rotation 0. */
width: number;
height: number;
thumbnailUrl: string | null;
fuelPct: number | null;
healthPct: number | null;
/** Operation label when actively reserved ("Reserved for op X" badge). */
reservedFor?: string | null;
}
function footprint(item: { width: number; height: number; rotated: boolean }) {
return item.rotated
? { width: item.height, height: item.width }
: { width: item.width, height: item.height };
}
function cellsOf(x: number, y: number, w: number, h: number): string[] {
const cells: string[] = [];
for (let dx = 0; dx < w; dx++) {
for (let dy = 0; dy < h; dy++) {
cells.push(`${x + dx},${y + dy}`);
}
}
return cells;
}
function isPlacementValid(
items: GarageVehicleItem[],
excludeId: number,
x: number,
y: number,
w: number,
h: number,
gridWidth: number,
gridHeight: number,
): boolean {
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) return false;
const target = new Set(cellsOf(x, y, w, h));
for (const item of items) {
if (item.id === excludeId) continue;
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
if (target.has(cell)) return false;
}
}
return true;
}
/** Status tinting for the vehicle face (A4: destroyed stays visible, tinted). */
function statusTint(status: GarageVehicleItem["status"]): string | null {
switch (status) {
case "destroyed":
return "bg-red-500/40";
case "damaged":
return "bg-amber-500/30";
case "in_transit":
return "bg-sky-500/20";
default:
return null;
}
}
export function VehicleFace({
item,
cellSize,
dragging,
}: {
item: GarageVehicleItem;
cellSize: number;
dragging?: boolean;
}) {
const fp = footprint(item);
const cardW = fp.width * cellSize - 2;
const cardH = fp.height * cellSize - 2;
// Thumbnail caps are applied PRE-rotation, so for rotated cards the long
// edge must be capped by the card's HEIGHT (it becomes vertical after the
// 90deg turn) and vice versa. Pixel math, since % would resolve against
// the wrong axis of the already-rotated card. The rotated image is taken
// out of flow and anchored to the card centre so the 90deg turn happens
// around the card's middle (an in-flow image would rotate around its own
// top-biased box and clip against the card edge).
const thumbStyle: CSSProperties = item.rotated
? {
position: "absolute",
left: "50%",
top: "50%",
width: Math.floor(cardH * 0.85),
height: Math.floor(cardW * 0.85),
objectFit: "contain",
transform: "translate(-50%, -50%) rotate(90deg)",
}
: {
maxWidth: Math.floor(cardW * 0.85),
maxHeight: Math.floor(cardH * 0.55),
};
return (
<div
className={cn(
"relative flex h-full w-full flex-col items-center justify-center gap-0.5 overflow-hidden rounded-md border p-1 text-center transition-shadow",
"border-border/70 bg-muted/40",
item.status === "destroyed" && "border-red-500/50 grayscale",
item.status === "damaged" && "border-amber-500/50",
item.reservedFor && "ring-1 ring-sky-400/60",
dragging && "shadow-lg",
)}
style={{ width: cardW, height: cardH }}
title={
item.reservedFor ? `${item.name} (reserved for ${item.reservedFor})` : item.name
}
>
{item.thumbnailUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={item.thumbnailUrl}
alt=""
className="pointer-events-none object-contain opacity-85"
style={thumbStyle}
/>
) : (
<TruckIcon className="size-5 opacity-70" />
)}
<span className="line-clamp-2 text-[9px] leading-tight text-foreground/90">
{item.name}
</span>
{statusTint(item.status) && (
<span
aria-hidden="true"
className={cn("pointer-events-none absolute inset-0", statusTint(item.status))}
/>
)}
{item.status === "destroyed" && (
<ShieldAlert className="absolute right-0.5 top-0.5 size-3 text-red-400" aria-label="Destroyed" />
)}
{item.reservedFor ? (
<span className="absolute left-0.5 top-0.5 rounded-sm bg-sky-500/90 px-1 font-mono text-[8px] font-semibold uppercase tracking-wide text-white">
OP
</span>
) : null}
</div>
);
}
function DraggableVehicle({
item,
cellSize,
selected,
onSelect,
}: {
item: GarageVehicleItem;
cellSize: number;
selected: boolean;
onSelect: (item: GarageVehicleItem) => void;
}) {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: `garage-item-${item.id}`,
data: { item },
});
const didDrag = useRef(false);
useEffect(() => {
if (isDragging) didDrag.current = true;
}, [isDragging]);
const fp = footprint(item);
return (
<button
ref={setNodeRef}
type="button"
{...listeners}
{...attributes}
onClick={() => {
if (!didDrag.current) onSelect(item);
didDrag.current = false;
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect(item);
}
}}
className={cn(
"absolute cursor-grab rounded-md transition-[left,top] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",
selected && "ring-2 ring-primary",
)}
style={{
left: item.gridX * cellSize,
top: item.gridY * cellSize,
width: fp.width * cellSize - 2,
height: fp.height * cellSize - 2,
zIndex: 10,
transform: CSS.Translate.toString(transform),
opacity: isDragging ? 0 : 1,
}}
aria-label={`${item.name}, ${item.status}`}
>
<VehicleFace item={item} cellSize={cellSize} />
</button>
);
}
interface GarageGridProps {
gridWidth: number;
gridHeight: number;
items: GarageVehicleItem[];
canEdit: boolean;
onMoveItem: (
vehicleId: number,
gridX: number,
gridY: number,
rotated?: boolean,
) => Promise<void>;
onSelectItem: (item: GarageVehicleItem | null) => void;
selectedItem: GarageVehicleItem | null;
}
export function GarageGrid({
gridWidth,
gridHeight,
items,
canEdit,
onMoveItem,
onSelectItem,
selectedItem,
}: GarageGridProps) {
const [activeItem, setActiveItem] = useState<GarageVehicleItem | null>(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null);
const [pendingRotated, setPendingRotated] = useState(false);
const [cellSize, setCellSize] = useState(64);
const gridRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
// Chrome between the measured wrapper and the grid: the inventory frame's
// p-2 padding (8+8) plus its 1px borders (1+1).
const FRAME_CHROME_PX = 18;
// Responsive cell size: always fit the bay width into the container (the
// grid must never overflow, so no scrollbar can appear). The small floor is
// a legibility guard only; realistic containers never reach it.
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
const width = entries[0]?.contentRect.width ?? 0;
if (width > FRAME_CHROME_PX) {
setCellSize(
Math.max(24, Math.min(96, Math.floor((width - FRAME_CHROME_PX) / gridWidth))),
);
}
});
observer.observe(el);
return () => observer.disconnect();
}, [gridWidth]);
// R rotates the dragged vehicle while dragging (same gesture as locker).
useEffect(() => {
if (!activeItem) return;
const handler = (e: KeyboardEvent) => {
if (e.key === "r" || e.key === "R") {
e.preventDefault();
setPendingRotated((prev) => !prev);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeItem]);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
const occupiedCells = useMemo(() => {
const set = new Set<string>();
for (const item of items) {
const fp = footprint(item);
for (const cell of cellsOf(item.gridX, item.gridY, fp.width, fp.height)) {
set.add(cell);
}
}
return set;
}, [items]);
const hoverInfo = useMemo(() => {
if (!activeItem || !hoverPosition) return null;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
const valid = isPlacementValid(
items,
activeItem.id,
hoverPosition.x,
hoverPosition.y,
w,
h,
gridWidth,
gridHeight,
);
return { cells: new Set(cellsOf(hoverPosition.x, hoverPosition.y, w, h)), valid };
}, [activeItem, hoverPosition, pendingRotated, items, gridWidth, gridHeight]);
const handleDragStart = (event: DragStartEvent) => {
const item = event.active.data.current?.item as GarageVehicleItem | undefined;
if (!item) return;
setActiveItem(item);
setPendingRotated(item.rotated ?? false);
setHoverPosition(null);
};
const handleDragMove = (event: DragMoveEvent) => {
if (!activeItem) return;
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const x = activeItem.gridX + dx;
const y = activeItem.gridY + dy;
const w = pendingRotated ? activeItem.height : activeItem.width;
const h = pendingRotated ? activeItem.width : activeItem.height;
if (x < 0 || y < 0 || x + w > gridWidth || y + h > gridHeight) {
setHoverPosition(null);
return;
}
setHoverPosition({ x, y });
};
const handleDragEnd = (event: DragEndEvent) => {
const item = activeItem;
setActiveItem(null);
setHoverPosition(null);
if (!item || !canEdit) return;
// Derive the target cell from the drag translation (pointer-anchored math
// like InventoryGrid: original cell + rounded delta).
const dx = Math.round(event.delta.x / cellSize);
const dy = Math.round(event.delta.y / cellSize);
const targetX = item.gridX + dx;
const targetY = item.gridY + dy;
if (dx === 0 && dy === 0) {
if (pendingRotated === item.rotated) return;
void onMoveItem(item.id, item.gridX, item.gridY, pendingRotated);
return;
}
const w = pendingRotated ? item.height : item.width;
const h = pendingRotated ? item.width : item.height;
if (
isPlacementValid(items, item.id, targetX, targetY, w, h, gridWidth, gridHeight)
) {
void onMoveItem(item.id, targetX, targetY, pendingRotated);
}
};
// 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
? {
width: pendingRotated ? activeItem.height : activeItem.width,
height: pendingRotated ? activeItem.width : activeItem.height,
}
: null;
return (
<DndContext
sensors={sensors}
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
>
<div className="flex flex-col gap-2">
<div ref={containerRef} className="min-w-0 max-w-full overflow-hidden">
<div
className="inventory-frame relative rounded border border-border bg-card/80 p-2 shadow-sm"
role="region"
aria-label="Garage vehicle bay"
tabIndex={0}
>
<div
ref={gridRef}
className="relative grid bg-background/10"
style={{
gridTemplateColumns: `repeat(${gridWidth}, ${cellSize}px)`,
gridTemplateRows: `repeat(${gridHeight}, ${cellSize}px)`,
}}
>
{Array.from({ length: gridHeight }).map((_, y) =>
Array.from({ length: gridWidth }).map((__, 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}
/>
);
}),
)}
{items.map((item) => (
<DraggableVehicle
key={item.id}
item={item}
cellSize={cellSize}
selected={selectedItem?.id === item.id}
onSelect={onSelectItem}
/>
))}
</div>
</div>
</div>
<div className="metadata-strip flex items-center gap-4 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
<span>{items.length} parked</span>
<span>
bay {gridWidth} &times; {gridHeight}
</span>
{canEdit && <span className="ml-auto normal-case">drag to move &middot; R to rotate</span>}
</div>
</div>
<DragOverlay
dropAnimation={null}
style={
overlayFp
? { width: overlayFp.width * cellSize, height: overlayFp.height * cellSize }
: undefined
}
>
{activeItem ? (
<div className="h-full w-full rounded-md border border-primary/50 bg-card/95 shadow-xl">
<VehicleFace item={{ ...activeItem, rotated: pendingRotated }} cellSize={cellSize} dragging />
</div>
) : null}
</DragOverlay>
</DndContext>
);
}