little bit of ui clean up and fixing the platform labels/keys

This commit is contained in:
2026-01-05 13:47:59 -05:00
parent b7e3db8d34
commit 055ebb4cd9
7 changed files with 601 additions and 326 deletions
+104 -92
View File
@@ -31,8 +31,9 @@ import { CATEGORIES } from "@/data/gunbuilderParts";
import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots"; import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots";
import type { BuilderSlotKey, Part } from "@/types/builderSlots"; import type { BuilderSlotKey, Part } from "@/types/builderSlots";
import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings"; import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings";
import { normalizePlatformKey } from "@/lib/platforms";
// Centralized overlap rules + helpers // Centralized overlap rules + helpers
import OverlapChip from "@/components/builder/OverlapChip"; import OverlapChip from "@/components/builder/OverlapChip";
import { import {
getOverlapChipsForCategory, getOverlapChipsForCategory,
@@ -51,7 +52,22 @@ type GunbuilderProductFromApi = {
buyUrl: string | null; buyUrl: string | null;
}; };
const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const; const PLATFORMS = ["AR15"] as const;
// Disabling all other platforms for now
// const PLATFORMS = ["AR15", "AR10", "AR9"] as const;
const PLATFORM_LABEL: Record<(typeof PLATFORMS)[number], string> = {
AR15: "AR-15",
// AR10: "AR-10",
// AR9: "AR-9",
};
const isValidPlatform = (
value: string | null
): value is (typeof PLATFORMS)[number] =>
!!value && (PLATFORMS as readonly string[]).includes(value);
const isUuid = (v: string) => const isUuid = (v: string) =>
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
@@ -146,6 +162,16 @@ export default function GunbuilderPage() {
// ✅ Auth: we need the token ready before calling /builds/me/* // ✅ Auth: we need the token ready before calling /builds/me/*
const { token, loading: authLoading, getAuthHeaders } = useAuth(); const { token, loading: authLoading, getAuthHeaders } = useAuth();
const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>(() => {
if (typeof window === "undefined") return "AR15";
const initial = new URLSearchParams(window.location.search).get("platform");
const normalized = normalizePlatformKey(initial ?? "");
return isValidPlatform(normalized) ? normalized : "AR15";
});
// Canonical, URL-safe platform (AR15 / AR10 / AR9)
const canonicalPlatform = normalizePlatformKey(platform);
// ----------------------------- // -----------------------------
// Save As… modal state (Vault variants) // Save As… modal state (Vault variants)
// ----------------------------- // -----------------------------
@@ -161,20 +187,6 @@ export default function GunbuilderPage() {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// -----------------------------
// Platform state (AR-15/AR-10/AR-9)
// -----------------------------
const isValidPlatform = (
value: string | null
): value is (typeof PLATFORMS)[number] =>
!!value && (PLATFORMS as readonly string[]).includes(value);
const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>(() => {
if (typeof window === "undefined") return "AR-15";
const initial = new URLSearchParams(window.location.search).get("platform");
return isValidPlatform(initial) ? initial : "AR-15";
});
// ----------------------------- // -----------------------------
// Build state (categoryId -> productId), persisted locally // Build state (categoryId -> productId), persisted locally
// ----------------------------- // -----------------------------
@@ -228,7 +240,7 @@ export default function GunbuilderPage() {
const didHydrateRef = useRef(false); const didHydrateRef = useRef(false);
const lastPlatformRef = useRef(platform); const lastPlatformRef = useRef(platform);
// Guard to prevent infinite loops when processing ?select / ?remove // Guard to prevent infinite loops when processing ?select / ?remove
const processedActionKeyRef = useRef<string>(""); const processedActionKeyRef = useRef<string>("");
// ----------------------------- // -----------------------------
@@ -326,7 +338,7 @@ export default function GunbuilderPage() {
if (normalizedRole.includes("suppress")) return "suppressor"; if (normalizedRole.includes("suppress")) return "suppressor";
// ✅ FIX: Lower Parts Kit canonical key // Lower Parts Kit canonical key
if ( if (
normalizedRole.includes("lower-parts") || normalizedRole.includes("lower-parts") ||
normalizedRole.includes("lpk") normalizedRole.includes("lpk")
@@ -336,7 +348,7 @@ export default function GunbuilderPage() {
if (normalizedRole.includes("trigger")) return "trigger"; if (normalizedRole.includes("trigger")) return "trigger";
if (normalizedRole.includes("grip")) return "grip"; if (normalizedRole.includes("grip")) return "grip";
// ✅ FIX: Safety canonical key // Safety canonical key
if ( if (
normalizedRole.includes("safety") || normalizedRole.includes("safety") ||
normalizedRole.includes("selector") normalizedRole.includes("selector")
@@ -385,26 +397,26 @@ export default function GunbuilderPage() {
useEffect(() => { useEffect(() => {
const controller = new AbortController(); const controller = new AbortController();
async function hydrateSelected() { async function hydrateSelected() {
const ids = (Object.values(build).filter(Boolean) as string[]) const ids = (Object.values(build).filter(Boolean) as string[])
.map(String) .map(String)
.sort(); .sort();
const key = ids.join(","); const key = ids.join(",");
if (key === lastHydrateKeyRef.current) return; if (key === lastHydrateKeyRef.current) return;
lastHydrateKeyRef.current = key; lastHydrateKeyRef.current = key;
if (ids.length === 0) { if (ids.length === 0) {
setParts([]); setParts([]);
setError(null); setError(null);
setLoading(false); setLoading(false);
return; return;
} }
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
const res = await fetch( const res = await fetch(
`${API_BASE_URL}/api/v1/catalog/products/by-ids`, `${API_BASE_URL}/api/v1/catalog/products/by-ids`,
@@ -415,27 +427,27 @@ export default function GunbuilderPage() {
body: JSON.stringify({ ids }), body: JSON.stringify({ ids }),
} }
); );
if (!res.ok) throw new Error(`Failed to hydrate parts (${res.status})`); if (!res.ok) throw new Error(`Failed to hydrate parts (${res.status})`);
const data: GunbuilderProductFromApi[] = await res.json(); const data: GunbuilderProductFromApi[] = await res.json();
// Map products by id for quick lookup // Map products by id for quick lookup
const byId = new Map<string, GunbuilderProductFromApi>(); const byId = new Map<string, GunbuilderProductFromApi>();
for (const p of data) byId.set(String(p.id), p); for (const p of data) byId.set(String(p.id), p);
// Build the hydrated parts by iterating the BUILD STATE (slot -> id) // Build the hydrated parts by iterating the BUILD STATE (slot -> id)
const hydrated: Part[] = Object.entries(build) const hydrated: Part[] = Object.entries(build)
.filter(([, id]) => Boolean(id)) .filter(([, id]) => Boolean(id))
.map(([slot, id]) => { .map(([slot, id]) => {
const p = byId.get(String(id)); const p = byId.get(String(id));
if (!p) return null; if (!p) return null;
const buyUrl = p.buyUrl ?? undefined; const buyUrl = p.buyUrl ?? undefined;
return { return {
id: String(p.id), id: String(p.id),
categoryId: slot as any, // slot is the source of truth categoryId: slot as any, // slot is the source of truth
name: p.name, name: p.name,
brand: p.brand, brand: p.brand,
price: p.price ?? 0, price: p.price ?? 0,
@@ -446,9 +458,8 @@ export default function GunbuilderPage() {
} as Part; } as Part;
}) })
.filter((x): x is Part => x !== null); .filter((x): x is Part => x !== null);
setParts(hydrated); setParts(hydrated);
} catch (err: any) { } catch (err: any) {
if (err?.name === "AbortError") return; if (err?.name === "AbortError") return;
setError(err?.message ?? "Failed to hydrate selected parts"); setError(err?.message ?? "Failed to hydrate selected parts");
@@ -456,7 +467,7 @@ export default function GunbuilderPage() {
setLoading(false); setLoading(false);
} }
} }
hydrateSelected(); hydrateSelected();
return () => controller.abort(); return () => controller.abort();
}, [build]); }, [build]);
@@ -512,10 +523,10 @@ export default function GunbuilderPage() {
if (!uuidToLoad) return; if (!uuidToLoad) return;
// Wait for AuthProvider hydration before calling /me endpoints. // Wait for AuthProvider hydration before calling /me endpoints.
if (authLoading) return; if (authLoading) return;
// If not logged in, don't spam the backend; show a helpful message instead. // If not logged in, don't spam the backend; show a helpful message instead.
if (!token) { if (!token) {
setShareStatus("Please log in to load builds from your Vault."); setShareStatus("Please log in to load builds from your Vault.");
window.setTimeout(() => setShareStatus(null), 4500); window.setTimeout(() => setShareStatus(null), 4500);
@@ -633,7 +644,7 @@ export default function GunbuilderPage() {
showToast({ showToast({
type: "success", type: "success",
message: "Saved to Vault ✅ (UUID copied)", message: "Saved to your Vault ✅ ",
}); });
// Close modal + reset inputs for next variant // Close modal + reset inputs for next variant
@@ -674,66 +685,70 @@ export default function GunbuilderPage() {
}, },
[build] [build]
); );
// ----------------------------- // Handle URL query parameters (?select, ?remove) and keep platform synced + canonical
// Handle URL query parameters: useEffect(() => {
// - ?select=categoryId:partId const sp = new URLSearchParams(searchParams.toString());
// - ?remove=categoryId
// -----------------------------
useEffect(() => {
const selectParam = searchParams.get("select");
const removeParam = searchParams.get("remove");
const qpPlatform = searchParams.get("platform");
const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${ const selectParam = sp.get("select");
qpPlatform ?? "" const removeParam = sp.get("remove");
}`;
if (!selectParam && !removeParam) { // Normalize platform from URL (AR-15 -> AR15)
processedActionKeyRef.current = ""; const qpPlatformRaw = sp.get("platform");
return; const qpPlatform = normalizePlatformKey(qpPlatformRaw ?? "");
}
if (processedActionKeyRef.current === actionKey) return; // Decide canonical platform to use (URL if valid, else current state)
processedActionKeyRef.current = actionKey; const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform;
if (selectParam) { // Keep React state in sync (only when needed)
const [categoryIdRaw, partId] = selectParam.split(":"); if (isValidPlatform(qpPlatform) && qpPlatform !== platform) {
const requestedCategoryId = categoryIdRaw as BuilderSlotKey; setPlatform(qpPlatform);
}
if (requestedCategoryId && partId) { // Prevent repeating select/remove actions
handleSelectPart(requestedCategoryId, partId, { confirm: false }); const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${nextPlatform}`;
const hasAction = !!selectParam || !!removeParam;
if (hasAction) {
if (processedActionKeyRef.current !== actionKey) {
processedActionKeyRef.current = actionKey;
if (selectParam) {
const [categoryIdRaw, partId] = selectParam.split(":");
const requestedCategoryId = categoryIdRaw as BuilderSlotKey;
if (requestedCategoryId && partId) {
handleSelectPart(requestedCategoryId, partId, { confirm: false });
}
}
if (removeParam) {
if (CATEGORIES.some((c) => c.id === removeParam)) {
setBuild((prev) => {
const next: BuildState = { ...prev };
delete next[removeParam as BuilderSlotKey];
return next;
});
}
} }
} }
} else {
// no action params → allow future actions to run
processedActionKeyRef.current = "";
}
if (removeParam) { // Canonicalize URL: set platform to canonical key and remove action params
if (CATEGORIES.some((c) => c.id === removeParam)) { const before = searchParams.toString();
setBuild((prev) => {
const next: BuildState = { ...prev };
delete next[removeParam as BuilderSlotKey];
return next;
});
}
}
const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; sp.set("platform", nextPlatform);
sp.delete("select");
sp.delete("remove");
// Keep URL clean/stable const after = sp.toString();
const nextUrl = `/builder?platform=${encodeURIComponent(nextPlatform)}`;
if (typeof window !== "undefined") {
const current = `${window.location.pathname}${window.location.search}`;
if (current !== nextUrl) router.replace(nextUrl, { scroll: false });
} else {
router.replace(nextUrl, { scroll: false });
}
}, [searchParams, router, platform, handleSelectPart]);
// Keep platform in sync w/ URL if (after !== before) {
useEffect(() => { router.replace(`/builder?${after}`, { scroll: false });
const qp = searchParams.get("platform"); }
if (isValidPlatform(qp) && qp !== platform) { }, [searchParams, router, platform, handleSelectPart]);
setPlatform(qp);
}
}, [searchParams, platform]);
// Build share URL whenever build changes (client-side only) // Build share URL whenever build changes (client-side only)
useEffect(() => { useEffect(() => {
@@ -971,7 +986,7 @@ export default function GunbuilderPage() {
// Keep URL in sync, and clear transient action params // Keep URL in sync, and clear transient action params
const qp = new URLSearchParams(searchParams.toString()); const qp = new URLSearchParams(searchParams.toString());
qp.set("platform", next); qp.set("platform", normalizePlatformKey(next));
qp.delete("select"); qp.delete("select");
qp.delete("remove"); qp.delete("remove");
@@ -983,7 +998,7 @@ export default function GunbuilderPage() {
> >
{PLATFORMS.map((p) => ( {PLATFORMS.map((p) => (
<option key={p} value={p}> <option key={p} value={p}>
{p} {PLATFORM_LABEL[p]}
</option> </option>
))} ))}
</select> </select>
@@ -1352,11 +1367,8 @@ export default function GunbuilderPage() {
</> </>
) : ( ) : (
<Link <Link
href={`/parts/${encodeURIComponent( href={`/parts/${encodeURIComponent(category.id)}?platform=${encodeURIComponent(canonicalPlatform)}`}
category.id
)}?platform=${encodeURIComponent(
platform
)}`}
className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors" className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
> >
<svg <svg
+27 -7
View File
@@ -71,7 +71,8 @@ export default function AdminPlatformsPage() {
} }
async function onDelete(p: Platform) { async function onDelete(p: Platform) {
if (!window.confirm(`Delete platform "${p.key}"? This cannot be undone.`)) return; if (!window.confirm(`Delete platform "${p.key}"? This cannot be undone.`))
return;
try { try {
setSaving(true); setSaving(true);
@@ -107,7 +108,8 @@ export default function AdminPlatformsPage() {
const update: UpdatePlatformDto = {}; const update: UpdatePlatformDto = {};
if (key !== selected.key) update.key = key; if (key !== selected.key) update.key = key;
if (label !== selected.label) update.label = label; if (label !== selected.label) update.label = label;
if ((form.isActive ?? true) !== selected.isActive) update.isActive = form.isActive; if ((form.isActive ?? true) !== selected.isActive)
update.isActive = form.isActive;
await updatePlatform(getAuthHeaders(), selected.id, update); await updatePlatform(getAuthHeaders(), selected.id, update);
} }
@@ -164,7 +166,9 @@ export default function AdminPlatformsPage() {
<th className="border-b border-zinc-900 px-3 py-2">Key</th> <th className="border-b border-zinc-900 px-3 py-2">Key</th>
<th className="border-b border-zinc-900 px-3 py-2">Label</th> <th className="border-b border-zinc-900 px-3 py-2">Label</th>
<th className="border-b border-zinc-900 px-3 py-2">Active</th> <th className="border-b border-zinc-900 px-3 py-2">Active</th>
<th className="border-b border-zinc-900 px-3 py-2 text-right">Actions</th> <th className="border-b border-zinc-900 px-3 py-2 text-right">
Actions
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -245,7 +249,15 @@ export default function AdminPlatformsPage() {
</label> </label>
<input <input
value={form.key} value={form.key}
onChange={(e) => setForm((s) => ({ ...s, key: e.target.value }))} onChange={(e) =>
setForm((s) => ({
...s,
key: e.target.value
.toUpperCase()
.replace(/\s+/g, "") // remove spaces
.replace(/-/g, ""),
}))
}
className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400" className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400"
placeholder="AR15" placeholder="AR15"
required required
@@ -258,7 +270,9 @@ export default function AdminPlatformsPage() {
</label> </label>
<input <input
value={form.label} value={form.label}
onChange={(e) => setForm((s) => ({ ...s, label: e.target.value }))} onChange={(e) =>
setForm((s) => ({ ...s, label: e.target.value }))
}
className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400" className="w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-500 focus:border-amber-400/80 focus:outline-none focus:ring-1 focus:ring-amber-400"
placeholder="AR-15" placeholder="AR-15"
required required
@@ -269,7 +283,9 @@ export default function AdminPlatformsPage() {
<input <input
type="checkbox" type="checkbox"
checked={!!form.isActive} checked={!!form.isActive}
onChange={(e) => setForm((s) => ({ ...s, isActive: e.target.checked }))} onChange={(e) =>
setForm((s) => ({ ...s, isActive: e.target.checked }))
}
className="h-4 w-4 rounded border-zinc-700 bg-zinc-900 text-amber-400" className="h-4 w-4 rounded border-zinc-700 bg-zinc-900 text-amber-400"
/> />
Active Active
@@ -289,7 +305,11 @@ export default function AdminPlatformsPage() {
className="flex-1 rounded-md bg-emerald-600 px-4 py-2 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50" className="flex-1 rounded-md bg-emerald-600 px-4 py-2 text-xs font-medium text-white hover:bg-emerald-500 disabled:opacity-50"
disabled={saving} disabled={saving}
> >
{saving ? "Saving…" : modalMode === "create" ? "Create" : "Update"} {saving
? "Saving…"
: modalMode === "create"
? "Create"
: "Update"}
</button> </button>
</div> </div>
</form> </form>
+433 -214
View File
@@ -38,6 +38,9 @@ type PageResponse<T> = {
const API_BASE = const API_BASE =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"; process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
// -----------------------------
// Auth helpers (kept as-is)
// -----------------------------
function getCookie(name: string): string | null { function getCookie(name: string): string | null {
if (typeof document === "undefined") return null; if (typeof document === "undefined") return null;
const match = document.cookie.match( const match = document.cookie.match(
@@ -51,35 +54,15 @@ function getCookie(name: string): string | null {
function getToken(): string | null { function getToken(): string | null {
if (typeof window === "undefined") return null; if (typeof window === "undefined") return null;
// 1) Prefer localStorage (your canonical token store)
const ls = localStorage.getItem("ballistic_auth_token"); const ls = localStorage.getItem("ballistic_auth_token");
if (ls && ls.trim().length > 0) return ls; if (ls && ls.trim().length > 0) return ls;
// 2) Fallback to cookie (only works if NOT HttpOnly)
const ck = getCookie("bb_access_token"); const ck = getCookie("bb_access_token");
if (ck && ck.trim().length > 0) return ck; if (ck && ck.trim().length > 0) return ck;
return null; return null;
} }
function getRole(): string | null {
if (typeof window === "undefined") return null;
const lsUser = localStorage.getItem("ballistic_auth_user");
if (lsUser) {
try {
const parsed = JSON.parse(lsUser);
// adjust if your user object uses a different key
return parsed?.role ?? parsed?.roles?.[0] ?? null;
} catch {
// ignore
}
}
const ckRole = getCookie("bb_role");
return ckRole ?? null;
}
function qs(params: Record<string, any>) { function qs(params: Record<string, any>) {
const sp = new URLSearchParams(); const sp = new URLSearchParams();
Object.entries(params).forEach(([k, v]) => { Object.entries(params).forEach(([k, v]) => {
@@ -118,6 +101,8 @@ async function bulkUpdate(
builderEligible: boolean; builderEligible: boolean;
adminLocked: boolean; adminLocked: boolean;
adminNote: string; adminNote: string;
platform: string;
platformLocked: boolean;
}> }>
) { ) {
const token = getToken(); const token = getToken();
@@ -137,25 +122,101 @@ async function bulkUpdate(
throw new Error(`Bulk update failed (${res.status}): ${txt}`); throw new Error(`Bulk update failed (${res.status}): ${txt}`);
} }
return (await res.json()) as { updatedCount: number }; return (await res.json()) as {
updatedCount: number;
skippedLockedCount: number;
};
}
// -----------------------------
// UI types
// -----------------------------
type AdminFilters = {
q: string;
platform: string; // platform KEY
partRole: string;
visibility: ProductVisibility | "";
status: ProductStatus | "";
builderEligible: "" | "true" | "false";
adminLocked: "" | "true" | "false";
};
type PlatformDto = {
id: number;
key: string;
label: string;
is_active: boolean;
};
async function fetchPlatforms() {
const res = await fetch(`${API_BASE}/api/platforms`, {
method: "GET",
headers: { Accept: "application/json" },
cache: "no-store",
});
if (!res.ok) {
const txt = await res.text();
throw new Error(`Failed to load platforms (${res.status}): ${txt}`);
}
const all = (await res.json()) as PlatformDto[];
return all.filter((p) => p.is_active);
}
// Replace with an API later if you want.
// For now: derive from the current page results + known “common” roles.
function buildRoleOptions(rows: AdminProductRow[]) {
const set = new Set<string>();
rows.forEach((r) => {
if (r.partRole) set.add(r.partRole);
});
return ["", ...Array.from(set).sort((a, b) => a.localeCompare(b))];
}
// -----------------------------
// Small UI helpers
// -----------------------------
function Field({
label,
children,
widthClass,
}: {
label: string;
children: React.ReactNode;
widthClass?: string;
}) {
return (
<div className={widthClass ?? "w-[180px]"}>
<div className="mb-1 text-[11px] uppercase tracking-[0.16em] text-zinc-500">
{label}
</div>
{children}
</div>
);
}
function Chip({ text, onClear }: { text: string; onClear: () => void }) {
return (
<button
type="button"
onClick={onClear}
className="rounded-full border border-zinc-800 bg-zinc-950 px-2 py-1 text-[11px] text-zinc-200 hover:bg-zinc-900"
title="Clear filter"
>
{text} <span className="ml-1 text-zinc-500">×</span>
</button>
);
} }
export default function AdminProductsPage() { export default function AdminProductsPage() {
// filters
const [q, setQ] = useState("");
const [platform, setPlatform] = useState("");
const [partRole, setPartRole] = useState("");
const [visibility, setVisibility] = useState<ProductVisibility | "">("");
const [status, setStatus] = useState<ProductStatus | "">("");
const [builderEligible, setBuilderEligible] = useState<"" | "true" | "false">(
""
);
const [adminLocked, setAdminLocked] = useState<"" | "true" | "false">("");
// paging // paging
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [size, setSize] = useState(50); const [size, setSize] = useState(50);
// dropdown data
const [platformOptions, setPlatformOptions] = useState<PlatformDto[]>([]);
// data // data
const [data, setData] = useState<PageResponse<AdminProductRow> | null>(null); const [data, setData] = useState<PageResponse<AdminProductRow> | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -164,30 +225,35 @@ export default function AdminProductsPage() {
// selection // selection
const [selected, setSelected] = useState<Set<number>>(new Set()); const [selected, setSelected] = useState<Set<number>>(new Set());
// filters: draft vs applied (THIS is the big clarity win)
const initialFilters: AdminFilters = {
q: "",
platform: "",
partRole: "",
visibility: "",
status: "",
builderEligible: "",
adminLocked: "",
};
const [draft, setDraft] = useState<AdminFilters>(initialFilters);
const [applied, setApplied] = useState<AdminFilters>(initialFilters);
// bulk action UI state
const [bulkPlatformKey, setBulkPlatformKey] = useState<string>("");
const [bulkPlatformLock, setBulkPlatformLock] = useState(false);
const queryParams = useMemo(() => { const queryParams = useMemo(() => {
return { return {
q, ...applied,
platform, builderEligible:
partRole, applied.builderEligible === "" ? null : applied.builderEligible,
visibility, adminLocked: applied.adminLocked === "" ? null : applied.adminLocked,
status,
builderEligible: builderEligible === "" ? null : builderEligible,
adminLocked: adminLocked === "" ? null : adminLocked,
page, page,
size, size,
sort: "updatedAt,desc", sort: "updatedAt,desc",
}; };
}, [ }, [applied, page, size]);
q,
platform,
partRole,
visibility,
status,
builderEligible,
adminLocked,
page,
size,
]);
const refresh = async () => { const refresh = async () => {
setLoading(true); setLoading(true);
@@ -195,8 +261,7 @@ export default function AdminProductsPage() {
try { try {
const res = await fetchAdminProducts(queryParams); const res = await fetchAdminProducts(queryParams);
setData(res); setData(res);
// clear selection on refresh so you dont accidentally nuke new stuff setSelected(new Set()); // prevent accidental “bulk” on new results
setSelected(new Set());
} catch (e: any) { } catch (e: any) {
setErr(e?.message ?? "Failed to load."); setErr(e?.message ?? "Failed to load.");
} finally { } finally {
@@ -204,23 +269,39 @@ export default function AdminProductsPage() {
} }
}; };
// auto-refresh only on paging (kept behavior)
useEffect(() => { useEffect(() => {
refresh(); refresh();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [queryParams.page, queryParams.size]); // only auto-refresh on page/size }, [page, size]);
// load platforms
useEffect(() => {
(async () => {
try {
const plats = await fetchPlatforms();
plats.sort((a, b) => a.label.localeCompare(b.label));
setPlatformOptions(plats);
} catch (e: any) {
console.warn(e?.message ?? "Failed to load platforms");
}
})();
}, []);
const content = data?.content ?? []; const content = data?.content ?? [];
// derive role options from current page (good enough v1)
const roleOptions = useMemo(() => buildRoleOptions(content), [content]);
const selectedIds = Array.from(selected);
const allOnPageSelected = const allOnPageSelected =
content.length > 0 && content.every((r) => selected.has(r.id)); content.length > 0 && content.every((r) => selected.has(r.id));
const toggleAllOnPage = () => { const toggleAllOnPage = () => {
const next = new Set(selected); const next = new Set(selected);
if (allOnPageSelected) { if (allOnPageSelected) content.forEach((r) => next.delete(r.id));
content.forEach((r) => next.delete(r.id)); else content.forEach((r) => next.add(r.id));
} else {
content.forEach((r) => next.add(r.id));
}
setSelected(next); setSelected(next);
}; };
@@ -231,29 +312,83 @@ export default function AdminProductsPage() {
setSelected(next); setSelected(next);
}; };
const selectedIds = Array.from(selected); const applyFilters = async () => {
setPage(0);
setApplied({ ...draft });
// keep your “manual” refresh model:
await refresh();
};
const clearFilters = async () => {
setDraft(initialFilters);
setApplied(initialFilters);
setPage(0);
await refresh();
};
const runBulk = async (set: Parameters<typeof bulkUpdate>[1]) => { const runBulk = async (set: Parameters<typeof bulkUpdate>[1]) => {
if (selectedIds.length === 0) return; if (selectedIds.length === 0) return;
// no confirmations per your “keep moving” vibe, but you can add one later
setLoading(true); setLoading(true);
setErr(null); setErr(null);
try { try {
const res = await bulkUpdate(selectedIds, set); const res = await bulkUpdate(selectedIds, set);
// eslint-disable-next-line no-console console.log(
console.log("Bulk updated:", res.updatedCount); `Updated ${res.updatedCount}` +
(res.skippedLockedCount > 0
? ` • Skipped ${res.skippedLockedCount} (platform locked)`
: "")
);
await refresh(); await refresh();
if ("platform" in set) {
setBulkPlatformKey("");
setBulkPlatformLock(false);
}
} catch (e: any) { } catch (e: any) {
setErr(e?.message ?? "Bulk update failed."); setErr(e?.message ?? "Bulk update failed.");
setLoading(false); setLoading(false);
} }
}; };
// active filter chips (optional but huge clarity)
const chips = useMemo(() => {
const out: { key: keyof AdminFilters; label: string }[] = [];
if (applied.q) out.push({ key: "q", label: `Search: ${applied.q}` });
if (applied.platform)
out.push({ key: "platform", label: `Platform: ${applied.platform}` });
if (applied.partRole)
out.push({ key: "partRole", label: `Role: ${applied.partRole}` });
if (applied.visibility)
out.push({
key: "visibility",
label: `Visibility: ${applied.visibility}`,
});
if (applied.status)
out.push({ key: "status", label: `Status: ${applied.status}` });
if (applied.builderEligible)
out.push({
key: "builderEligible",
label: `Builder: ${applied.builderEligible}`,
});
if (applied.adminLocked)
out.push({ key: "adminLocked", label: `Locked: ${applied.adminLocked}` });
return out;
}, [applied]);
const clearOne = async (key: keyof AdminFilters) => {
const nextDraft = { ...draft, [key]: "" } as AdminFilters;
const nextApplied = { ...applied, [key]: "" } as AdminFilters;
setDraft(nextDraft);
setApplied(nextApplied);
setPage(0);
await refresh();
};
return ( return (
<div className="mx-auto max-w-7xl px-4 py-10"> <div className="mx-auto max-w-screen-2xl px-2 py-6">
<div className="mb-6 flex items-start justify-between gap-4"> <div className="mb-4 flex items-start justify-between gap-4">
<div> <div>
<h1 className="text-2xl font-semibold">Admin · Products</h1> <h1 className="text-2xl font-semibold">Admin · Products</h1>
<p className="text-sm opacity-70"> <p className="text-sm opacity-70">
@@ -271,167 +406,251 @@ export default function AdminProductsPage() {
</button> </button>
</div> </div>
{/* Filters */} {/* ROW 1: FILTER BAR */}
<div className="mb-4 grid grid-cols-1 gap-3 md:grid-cols-6"> <div className="mb-3 rounded-md border border-zinc-800 bg-zinc-950/40 p-3">
<input <div className="flex flex-wrap items-end gap-2">
value={q} <Field label="Search" widthClass="min-w-[260px] flex-1">
onChange={(e) => setQ(e.target.value)} <input
placeholder="Search (name, slug, mpn, upc)…" value={draft.q}
className="md:col-span-2 rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" onChange={(e) => setDraft((s) => ({ ...s, q: e.target.value }))}
/> placeholder="name, slug, mpn, upc…"
className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
/>
</Field>
<input <Field label="Platform">
value={platform} <select
onChange={(e) => setPlatform(e.target.value)} value={draft.platform}
placeholder="Platform (AR-15)…" onChange={(e) =>
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" setDraft((s) => ({ ...s, platform: e.target.value }))
/> }
className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
>
<option value="">Any</option>
{platformOptions.map((p) => (
<option key={p.key} value={p.key}>
{p.key}
</option>
))}
</select>
</Field>
<input <Field label="Role">
value={partRole} <select
onChange={(e) => setPartRole(e.target.value)} value={draft.partRole}
placeholder="Part role (barrel)…" onChange={(e) =>
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" setDraft((s) => ({ ...s, partRole: e.target.value }))
/> }
className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
>
<option value="">Any</option>
{roleOptions.map((r) => (
<option key={r || "any"} value={r}>
{r || "Any"}
</option>
))}
</select>
</Field>
<select <Field label="Visibility">
value={visibility} <select
onChange={(e) => setVisibility(e.target.value as any)} value={draft.visibility}
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" onChange={(e) =>
> setDraft((s) => ({ ...s, visibility: e.target.value as any }))
<option value="">Visibility (any)</option> }
<option value="PUBLIC">PUBLIC</option> className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
<option value="HIDDEN">HIDDEN</option> >
</select> <option value="">Any</option>
<option value="PUBLIC">PUBLIC</option>
<option value="HIDDEN">HIDDEN</option>
</select>
</Field>
<select <Field label="Status">
value={status} <select
onChange={(e) => setStatus(e.target.value as any)} value={draft.status}
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" onChange={(e) =>
> setDraft((s) => ({ ...s, status: e.target.value as any }))
<option value="">Status (any)</option> }
<option value="ACTIVE">ACTIVE</option> className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
<option value="DISABLED">DISABLED</option> >
<option value="ARCHIVED">ARCHIVED</option> <option value="">Any</option>
</select> <option value="ACTIVE">ACTIVE</option>
<option value="DISABLED">DISABLED</option>
<option value="ARCHIVED">ARCHIVED</option>
</select>
</Field>
<div className="md:col-span-6 flex flex-wrap items-center gap-3"> <Field label="Builder">
<select <select
value={builderEligible} value={draft.builderEligible}
onChange={(e) => setBuilderEligible(e.target.value as any)} onChange={(e) =>
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" setDraft((s) => ({
> ...s,
<option value="">Builder eligible (any)</option> builderEligible: e.target.value as any,
<option value="true">true</option> }))
<option value="false">false</option> }
</select> className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
>
<option value="">Any</option>
<option value="true">Eligible</option>
<option value="false">Not eligible</option>
</select>
</Field>
<select <Field label="Locked">
value={adminLocked} <select
onChange={(e) => setAdminLocked(e.target.value as any)} value={draft.adminLocked}
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" onChange={(e) =>
> setDraft((s) => ({ ...s, adminLocked: e.target.value as any }))
<option value="">Admin locked (any)</option> }
<option value="true">true</option> className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
<option value="false">false</option> >
</select> <option value="">Any</option>
<option value="true">Locked</option>
<option value="false">Unlocked</option>
</select>
</Field>
<button <div className="ml-auto flex items-center gap-2">
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50" <button
onClick={() => { className="rounded-md bg-emerald-600 px-3 py-2 text-sm hover:bg-emerald-500 disabled:opacity-50"
setPage(0); onClick={applyFilters}
refresh(); disabled={loading}
}} >
disabled={loading} Apply
> </button>
Apply filters
</button>
<button <button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900" className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900"
onClick={() => { onClick={clearFilters}
setQ(""); disabled={loading}
setPlatform(""); >
setPartRole(""); Clear
setVisibility(""); </button>
setStatus(""); </div>
setBuilderEligible("");
setAdminLocked("");
setPage(0);
refresh();
}}
>
Clear
</button>
</div> </div>
{chips.length > 0 && (
<div className="mt-3 flex flex-wrap gap-2">
{chips.map((c) => (
<Chip
key={c.key}
text={c.label}
onClear={() => void clearOne(c.key)}
/>
))}
</div>
)}
</div> </div>
{/* Bulk actions */} {/* ROW 2: BULK BAR (only when selection > 0) */}
<div className="mb-3 flex flex-wrap items-center justify-between gap-3"> {selectedIds.length > 0 && (
<div className="text-sm opacity-70"> <div className="mb-3 rounded-md border border-zinc-800 bg-zinc-950/40 p-3">
Selected:{" "} <div className="flex flex-wrap items-center gap-3">
<span className="font-semibold opacity-100"> <div className="text-sm opacity-80">
{selectedIds.length} Selected:{" "}
</span> <span className="font-semibold">{selectedIds.length}</span>
</div>
<div className="h-4 w-px bg-zinc-800" />
<div className="flex flex-wrap items-center gap-2">
<select
value={bulkPlatformKey}
onChange={(e) => setBulkPlatformKey(e.target.value)}
className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
>
<option value="">Set platform</option>
{platformOptions.map((p) => (
<option key={p.key} value={p.key}>
{p.label}
</option>
))}
</select>
<label className="flex items-center gap-2 text-xs opacity-80">
<input
type="checkbox"
checked={bulkPlatformLock}
onChange={(e) => setBulkPlatformLock(e.target.checked)}
/>
Lock platform
</label>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || bulkPlatformKey.length === 0}
onClick={() =>
runBulk({
platform: bulkPlatformKey,
...(bulkPlatformLock ? { platformLocked: true } : {}),
})
}
>
Apply Platform
</button>
</div>
<div className="ml-auto flex flex-wrap gap-2">
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() =>
runBulk({
visibility: "HIDDEN",
builderEligible: false,
adminLocked: true,
adminNote: "Hidden + removed from builder (bulk)",
})
}
>
Hide + Remove + Lock
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() => runBulk({ builderEligible: false })}
>
Remove from Builder
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() => runBulk({ visibility: "HIDDEN" })}
>
Hide
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() => runBulk({ status: "DISABLED" })}
>
Disable
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() => runBulk({ adminLocked: true })}
>
Lock
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading}
onClick={() => runBulk({ adminLocked: false })}
>
Unlock
</button>
</div>
</div>
</div> </div>
)}
<div className="flex flex-wrap gap-2">
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() =>
runBulk({
visibility: "HIDDEN",
builderEligible: false,
adminLocked: true,
adminNote: "Hidden + removed from builder (bulk)",
})
}
>
Hide + Remove from Builder + Lock
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() => runBulk({ builderEligible: false })}
>
Remove from Builder
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() => runBulk({ visibility: "HIDDEN" })}
>
Hide
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() => runBulk({ status: "DISABLED" })}
>
Disable
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() => runBulk({ adminLocked: true })}
>
Lock
</button>
<button
className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
disabled={loading || selectedIds.length === 0}
onClick={() => runBulk({ adminLocked: false })}
>
Unlock
</button>
</div>
</div>
{/* Errors */} {/* Errors */}
{err && ( {err && (
@@ -562,7 +781,7 @@ export default function AdminProductsPage() {
{/* Pagination */} {/* Pagination */}
<div className="mt-4 flex items-center justify-between gap-3"> <div className="mt-4 flex items-center justify-between gap-3">
<div className="text-sm opacity-70"> <div className="text-sm opacity-70">
Page {(data?.number ?? 0) + 1} of {data?.totalPages ?? 1} Page {(data?.number ?? 0) + 1} of {data?.totalPages ?? 1} {" "}
{data?.totalElements ?? 0} total {data?.totalElements ?? 0} total
</div> </div>
+2 -2
View File
@@ -75,7 +75,7 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
</button> </button>
{/* Dropdown menu */} {/* Dropdown menu */}
<div className="invisible opacity-0 group-hover:visible group-hover:opacity-100 transition-all absolute left-0 mt-2 rounded-md border border-neutral-800 bg-black/95 shadow-xl z-40 min-w-[220px]"> <div className="invisible opacity-0 group-hover:visible group-hover:opacity-100 transition-all absolute left-0 mt-2 rounded-md border border-neutral-800 bg-black/95 shadow-xl z-100 min-w-[220px]">
<ul className="py-2 text-sm"> <ul className="py-2 text-sm">
{items.map((cat) => { {items.map((cat) => {
const isActive = currentCategory === cat.id; const isActive = currentCategory === cat.id;
@@ -114,7 +114,7 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
* - Everything before the RIGHT cluster is "left side" * - Everything before the RIGHT cluster is "left side"
* - Then a single `ml-auto` cluster pushes everything else to the right * - Then a single `ml-auto` cluster pushes everything else to the right
*/} */}
<nav className="flex items-center gap-6 border-b border-neutral-900 px-6 py-3 text-sm backdrop-blur-sm"> <nav className="relative z-50 flex items-center gap-6 border-b border-neutral-900 px-6 py-3 text-sm backdrop-blur-sm">
{/* ------------------------------------------------------------------ */} {/* ------------------------------------------------------------------ */}
{/* LEFT SIDE: primary nav */} {/* LEFT SIDE: primary nav */}
{/* ------------------------------------------------------------------ */} {/* ------------------------------------------------------------------ */}
+11 -9
View File
@@ -19,6 +19,7 @@ import SortBar from "@/components/parts/SortBar";
import PartsGrid from "@/components/parts/PartsGrid"; import PartsGrid from "@/components/parts/PartsGrid";
import Pagination from "@/components/parts/Pagination"; import Pagination from "@/components/parts/Pagination";
import PlatformSwitcher from "@/components/parts/PlatformSwitcher"; import PlatformSwitcher from "@/components/parts/PlatformSwitcher";
import { normalizePlatformKey } from "@/lib/platforms";
import type { Category } from "@/types/builderSlots"; import type { Category } from "@/types/builderSlots";
import { import {
@@ -111,9 +112,10 @@ export default function PartsBrowseClient(props: {
const isBuilderMode = pathname.startsWith("/parts/p/"); const isBuilderMode = pathname.startsWith("/parts/p/");
// ✅ Respect prop override first, else read query, else fallback // ✅ Respect prop override first, else read query, else fallback
const effectivePlatform = const effectivePlatform = normalizePlatformKey(
props.platform ?? searchParams.get("platform") ?? "AR-15"; props.platform ?? searchParams.get("platform") ?? "AR15"
);
const partRole = props.partRole; const partRole = props.partRole;
const [viewMode, setViewMode] = useState<ViewMode>("list"); const [viewMode, setViewMode] = useState<ViewMode>("list");
@@ -149,7 +151,7 @@ export default function PartsBrowseClient(props: {
setError(null); setError(null);
const search = new URLSearchParams(); const search = new URLSearchParams();
search.set("platform", effectivePlatform); search.set("platform", normalizePlatformKey(effectivePlatform));
search.append("partRole", partRole); search.append("partRole", partRole);
// server paging (0-based) // server paging (0-based)
@@ -320,7 +322,7 @@ export default function PartsBrowseClient(props: {
} }
const qp = new URLSearchParams(); const qp = new URLSearchParams();
qp.set("platform", effectivePlatform); qp.set("platform", normalizePlatformKey(effectivePlatform));
qp.set("select", `${categoryId}:${p.id}`); qp.set("select", `${categoryId}:${p.id}`);
router.push(`/builder?${qp.toString()}`); router.push(`/builder?${qp.toString()}`);
@@ -344,14 +346,14 @@ export default function PartsBrowseClient(props: {
{headingSubtitle} {headingSubtitle}
</p> </p>
{!isBuilderMode && ( {/* {!isBuilderMode && (
<div className="mt-4 flex flex-wrap items-center gap-3"> <div className="mt-4 flex flex-wrap items-center gap-3">
<PlatformSwitcher <PlatformSwitcher
currentPlatform={effectivePlatform} currentPlatform={effectivePlatform}
partRole={partRole} partRole={partRole}
preserveQuery preserveQuery
mode="browse" mode="browse"
/> /> */}
<Link <Link
href={`/builder?platform=${encodeURIComponent( href={`/builder?platform=${encodeURIComponent(
@@ -361,8 +363,8 @@ export default function PartsBrowseClient(props: {
> >
Start New Build Start New Build
</Link> </Link>
</div> {/* </div>
)} )} */}
</div> </div>
{isBuilderMode && ( {isBuilderMode && (
+17 -2
View File
@@ -92,7 +92,8 @@ export default function PartsGrid(props: {
return ( return (
<> <>
{/* Header (DESKTOP ONLY) */} {/* Header (DESKTOP ONLY) */}
<div className="hidden md:grid md:grid-cols-[minmax(0,1fr)_120px_110px_120px] md:items-center md:gap-4 px-3 pb-2 text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500"> <div className="hidden md:grid md:grid-cols-[44px_minmax(0,1fr)_120px_110px_120px] md:items-center md:gap-4 px-3 pb-2 text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500">
<span className="sr-only">Image</span>
<span className="min-w-0">Part</span> <span className="min-w-0">Part</span>
<span className="text-right">Caliber</span> <span className="text-right">Caliber</span>
<span className="text-right">Price</span> <span className="text-right">Price</span>
@@ -106,7 +107,21 @@ export default function PartsGrid(props: {
key={part.id} key={part.id}
className="group relative rounded-md border border-zinc-700 bg-zinc-900/50 p-3 transition-all hover:border-amber-400/60 hover:bg-amber-400/10" className="group relative rounded-md border border-zinc-700 bg-zinc-900/50 p-3 transition-all hover:border-amber-400/60 hover:bg-amber-400/10"
> >
<div className="flex flex-col gap-2 md:grid md:grid-cols-[minmax(0,1fr)_120px_110px_120px] md:items-center md:gap-4"> <div className="flex flex-col gap-2 md:grid md:grid-cols-[44px_minmax(0,1fr)_120px_110px_120px] md:items-center md:gap-4">
{/* Image */}
<div className="hidden md:block">
{part.imageUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={part.imageUrl}
alt=""
className="h-10 w-10 rounded object-cover border border-zinc-800 bg-zinc-950"
loading="lazy"
/>
) : (
<div className="h-10 w-10 rounded border border-zinc-800 bg-zinc-950" />
)}
</div>
{/* Part */} {/* Part */}
<div className="min-w-0"> <div className="min-w-0">
<Link <Link
+7
View File
@@ -0,0 +1,7 @@
// lib/platforms.ts
export function normalizePlatformKey(p?: string | null): string {
return (p ?? "")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9]/g, "");
}