ui using new v1 api for products

This commit is contained in:
2025-12-18 19:18:15 -05:00
parent 463fd06a12
commit 7f3818f795
12 changed files with 153 additions and 74 deletions
+130 -51
View File
@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
/**
* PartsBrowseClient
* -----------------------------------------------------------------------------
@@ -20,7 +21,10 @@ import Pagination from "@/components/parts/Pagination";
import PlatformSwitcher from "@/components/parts/PlatformSwitcher";
import type { CategoryId } from "@/types/gunbuilder";
import { PART_ROLE_TO_CATEGORY, normalizePartRole } from "@/lib/catalogMappings";
import {
PART_ROLE_TO_CATEGORY,
normalizePartRole,
} from "@/lib/catalogMappings";
type ViewMode = "card" | "list";
type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc";
@@ -49,7 +53,8 @@ type UiPart = {
inStock?: boolean;
};
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
const PAGE_SIZE = 24;
function normalizeId(id: string | number) {
@@ -70,9 +75,9 @@ function toSlug(s: string) {
*/
function buildDetailHref(platform: string, partRole: string, p: UiPart) {
const slug = toSlug(`${p.brand ?? ""} ${p.name ?? ""}`);
return `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}/${encodeURIComponent(
`${p.id}-${slug}`
)}`;
return `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(
partRole
)}/${encodeURIComponent(`${p.id}-${slug}`)}`;
}
export default function PartsBrowseClient(props: {
@@ -84,7 +89,8 @@ export default function PartsBrowseClient(props: {
const router = useRouter();
const searchParams = useSearchParams();
const effectivePlatform = props.platform ?? searchParams.get("platform") ?? "AR-15";
const effectivePlatform =
props.platform ?? searchParams.get("platform") ?? "AR-15";
const partRole = props.partRole;
const [viewMode, setViewMode] = useState<ViewMode>("list");
@@ -95,7 +101,10 @@ export default function PartsBrowseClient(props: {
const [brandFilter, setBrandFilter] = useState<string[]>([]);
const [sortBy, setSortBy] = useState<SortOption>("relevance");
const [searchQuery, setSearchQuery] = useState<string>("");
const [priceRange, setPriceRange] = useState<{ min: number | null; max: number | null }>({
const [priceRange, setPriceRange] = useState<{
min: number | null;
max: number | null;
}>({
min: null,
max: null,
});
@@ -116,7 +125,7 @@ export default function PartsBrowseClient(props: {
search.set("platform", effectivePlatform);
search.append("partRoles", partRole);
const url = `${API_BASE_URL}/api/products?${search.toString()}`;
const url = `${API_BASE_URL}/api/v1/products?${search.toString()}`;
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`Failed to load products (${res.status})`);
@@ -150,7 +159,15 @@ export default function PartsBrowseClient(props: {
useEffect(() => {
setCurrentPage(1);
}, [partRole, effectivePlatform, brandFilter, sortBy, searchQuery, priceRange, inStockOnly]);
}, [
partRole,
effectivePlatform,
brandFilter,
sortBy,
searchQuery,
priceRange,
inStockOnly,
]);
const availableBrands = useMemo(
() =>
@@ -161,7 +178,8 @@ export default function PartsBrowseClient(props: {
);
const priceBounds = useMemo(() => {
if (parts.length === 0) return { min: null as number | null, max: null as number | null };
if (parts.length === 0)
return { min: null as number | null, max: null as number | null };
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
@@ -198,7 +216,9 @@ export default function PartsBrowseClient(props: {
const effectiveMin = priceRange.min ?? priceBounds.min;
const effectiveMax = priceRange.max ?? priceBounds.max;
if (effectiveMin != null && effectiveMax != null) {
result = result.filter((p) => p.price >= effectiveMin && p.price <= effectiveMax);
result = result.filter(
(p) => p.price >= effectiveMin && p.price <= effectiveMax
);
}
if (brandFilter.length > 0) {
@@ -234,10 +254,22 @@ export default function PartsBrowseClient(props: {
}
return result;
}, [parts, brandFilter, sortBy, searchQuery, priceRange, priceBounds.min, priceBounds.max, inStockOnly]);
}, [
parts,
brandFilter,
sortBy,
searchQuery,
priceRange,
priceBounds.min,
priceBounds.max,
inStockOnly,
]);
const totalPages = useMemo(
() => (filteredParts.length === 0 ? 1 : Math.ceil(filteredParts.length / PAGE_SIZE)),
() =>
filteredParts.length === 0
? 1
: Math.ceil(filteredParts.length / PAGE_SIZE),
[filteredParts.length]
);
@@ -250,21 +282,30 @@ export default function PartsBrowseClient(props: {
const visibleRange = useMemo(() => {
if (filteredParts.length === 0) return { start: 0, end: 0 };
const start = (currentPage - 1) * PAGE_SIZE + 1;
const end = Math.min(start + paginatedParts.length - 1, filteredParts.length);
const end = Math.min(
start + paginatedParts.length - 1,
filteredParts.length
);
return { start, end };
}, [filteredParts.length, currentPage, paginatedParts.length]);
const headingTitle = props.title ?? `${partRole.replaceAll("-", " ")} parts`;
const headingSubtitle = props.subtitle ?? "Browse available parts pulled from your Ballistic backend.";
const headingSubtitle =
props.subtitle ??
"Browse available parts pulled from your Ballistic backend.";
// ✅ Add-to-build handler: deep-links into builders existing ?select= logic
const handleAddToBuild = (p: UiPart) => {
const normalizedRole = normalizePartRole(partRole);
const categoryId: CategoryId | null =
PART_ROLE_TO_CATEGORY[partRole] ?? PART_ROLE_TO_CATEGORY[normalizedRole] ?? null;
PART_ROLE_TO_CATEGORY[partRole] ??
PART_ROLE_TO_CATEGORY[normalizedRole] ??
null;
if (!categoryId) {
alert(`No CategoryId mapping found for role "${partRole}". Add it to catalogMappings.`);
alert(
`No CategoryId mapping found for role "${partRole}". Add it to catalogMappings.`
);
return;
}
@@ -286,36 +327,63 @@ export default function PartsBrowseClient(props: {
</p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
{headingTitle} <span className="text-amber-300">{effectivePlatform}</span>
{headingTitle}{" "}
<span className="text-amber-300">{effectivePlatform}</span>
</h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">{headingSubtitle}</p>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">
{headingSubtitle}
</p>
<div className="mt-3">
<PlatformSwitcher currentPlatform={effectivePlatform} partRole={partRole} preserveQuery />
<PlatformSwitcher
currentPlatform={effectivePlatform}
partRole={partRole}
preserveQuery
/>
</div>
</div>
{!loading && !error && parts.length > 0 && (
<div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60">
<button
type="button"
onClick={() => setViewMode("card")}
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
viewMode === "card" ? "bg-zinc-800 text-zinc-50" : "text-zinc-400 hover:text-zinc-300"
}`}
{!loading && !error && (
<div className="flex items-center gap-2">
<Link
href={{
pathname: "/builder",
query: effectivePlatform
? { platform: effectivePlatform }
: {},
}}
className="rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-xs font-semibold text-zinc-200 hover:bg-zinc-800"
>
Card
</button>
<button
type="button"
onClick={() => setViewMode("list")}
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
viewMode === "list" ? "bg-zinc-800 text-zinc-50" : "text-zinc-400 hover:text-zinc-300"
}`}
>
List
</button>
Back to Build
</Link>
{parts.length > 0 && (
<div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60">
<button
type="button"
onClick={() => setViewMode("card")}
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
viewMode === "card"
? "bg-zinc-800 text-zinc-50"
: "text-zinc-400 hover:text-zinc-300"
}`}
>
Card
</button>
<button
type="button"
onClick={() => setViewMode("list")}
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
viewMode === "list"
? "bg-zinc-800 text-zinc-50"
: "text-zinc-400 hover:text-zinc-300"
}`}
>
List
</button>
</div>
)}
</div>
)}
</div>
@@ -352,35 +420,46 @@ export default function PartsBrowseClient(props: {
)}
{loading ? (
<p className="py-8 text-center text-sm text-zinc-500">Loading</p>
<p className="py-8 text-center text-sm text-zinc-500">
Loading
</p>
) : error ? (
<p className="py-8 text-center text-sm text-red-400">
{error} check that the Ballistic API is running.
</p>
) : filteredParts.length === 0 ? (
<p className="py-8 text-center text-sm text-zinc-500">No parts found for this role yet.</p>
<p className="py-8 text-center text-sm text-zinc-500">
No parts found for this role yet.
</p>
) : (
<PartsGrid
viewMode={viewMode}
parts={paginatedParts}
buildDetailHref={(p) => buildDetailHref(effectivePlatform, partRole, p)}
buildDetailHref={(p) =>
buildDetailHref(effectivePlatform, partRole, p)
}
onAddToBuild={handleAddToBuild}
addLabel="Add to Build"
/>
)}
{!loading && !error && filteredParts.length > 0 && totalPages > 1 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))}
onNext={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
/>
)}
{!loading &&
!error &&
filteredParts.length > 0 &&
totalPages > 1 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))}
onNext={() =>
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
/>
)}
</div>
</div>
</section>
</div>
</main>
);
}
}