fixed layouts, routing and the platform switcher.

This commit is contained in:
2025-12-22 08:36:19 -05:00
parent b1a8dae8ed
commit 34e915f904
21 changed files with 254 additions and 268 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ export function Banner() {
Early Access Beta
</span>
<span className="hidden text-amber-100/90 md:inline">
You&apos;re using an early-access prototype of The Armory. Data,
You&apos;re using an early-access prototype of the Builder. Data,
pricing, and available parts are still evolving.
</span>
</div>
+10 -3
View File
@@ -57,6 +57,8 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
const renderDropdown = (label: string, items: Category[]) => {
if (!items.length) return null;
const platform = searchParams.get("platform");
return (
<div className="relative group">
{/* Dropdown trigger */}
@@ -80,7 +82,10 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
return (
<li key={cat.id}>
<Link
href={`${baseHref}/${cat.id}`}
href={{
pathname: `${baseHref}/${cat.id}`,
query: platform ? { platform } : {},
}}
className={`block w-full px-3 py-1.5 transition-colors ${
isActive
? "bg-neutral-800 text-white"
@@ -162,7 +167,9 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
{/* "Viewing" indicator (only shows when a category is active) */}
{currentCategory && (
<div className="flex items-center gap-2 text-neutral-400 text-xs">
<span className="uppercase tracking-wide text-[10px]">Viewing</span>
<span className="uppercase tracking-wide text-[10px]">
Viewing
</span>
<span className="font-medium text-neutral-100">
{CATEGORIES.find((c) => c.id === currentCategory)?.name ??
@@ -188,4 +195,4 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
);
}
export default BuilderNav;
export default BuilderNav;
+1 -1
View File
@@ -1,6 +1,6 @@
"use client";
import type { PriceHistoryPoint } from "@/app/(builder)/parts/[partRole]/_old_prod_details/data";
import type { PriceHistoryPoint } from "@/app/(app)/(builder)/parts/__DELETE[partRole]/_old_prod_details/data";
interface PricingHistoryGraphProps {
data: PriceHistoryPoint[];
+1 -1
View File
@@ -1,6 +1,6 @@
"use client";
import type { RetailerOffer } from "@/app/(builder)/parts/[partRole]/_old_prod_details/data";
import type { RetailerOffer } from "@/app/(app)/(builder)/parts/__DELETE[partRole]/_old_prod_details/data";
interface RetailersListProps {
retailers: RetailerOffer[];
+151 -187
View File
@@ -1,8 +1,3 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
/**
* PartsBrowseClient
* -----------------------------------------------------------------------------
@@ -13,8 +8,11 @@ import { usePathname } from "next/navigation";
* - layout + list/card views
*/
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import Filters from "@/components/parts/Filters";
import SortBar from "@/components/parts/SortBar";
@@ -23,10 +21,7 @@ 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 +44,7 @@ type UiPart = {
brand: string;
platform: string;
partRole: string;
price: number; // normalized
price: number;
imageUrl?: string;
buyUrl?: string;
inStock?: boolean;
@@ -57,6 +52,7 @@ type UiPart = {
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
const PAGE_SIZE = 24;
function normalizeId(id: string | number) {
@@ -92,8 +88,13 @@ export default function PartsBrowseClient(props: {
const searchParams = useSearchParams();
const pathname = usePathname();
// ✅ Builder-mode = /parts/p/... (detail routes)
const isBuilderMode = pathname.startsWith("/parts/p/");
// ✅ Respect prop override first, else read query, else fallback
const effectivePlatform =
props.platform ?? searchParams.get("platform") ?? "AR-15";
const partRole = props.partRole;
const [viewMode, setViewMode] = useState<ViewMode>("list");
@@ -103,7 +104,7 @@ export default function PartsBrowseClient(props: {
const [brandFilter, setBrandFilter] = useState<string[]>([]);
const [sortBy, setSortBy] = useState<SortOption>("relevance");
const [searchQuery, setSearchQuery] = useState<string>("");
const [searchQuery, setSearchQuery] = useState("");
const [priceRange, setPriceRange] = useState<{
min: number | null;
max: number | null;
@@ -114,6 +115,9 @@ export default function PartsBrowseClient(props: {
const [inStockOnly, setInStockOnly] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
// ----------------------------
// Fetch parts
// ----------------------------
useEffect(() => {
if (!partRole) return;
@@ -128,26 +132,28 @@ export default function PartsBrowseClient(props: {
search.set("platform", effectivePlatform);
search.append("partRoles", partRole);
const url = `${API_BASE_URL}/api/v1/products?${search.toString()}`;
const res = await fetch(url, { signal: controller.signal });
const res = await fetch(
`${API_BASE_URL}/api/v1/products?${search.toString()}`,
{ signal: controller.signal }
);
if (!res.ok) throw new Error(`Failed to load products (${res.status})`);
const data: GunbuilderProductFromApi[] = await res.json();
const normalized: UiPart[] = data.map((p) => ({
id: normalizeId(p.id),
name: p.name,
brand: p.brand,
platform: p.platform,
partRole: p.partRole,
price: p.price ?? 0,
imageUrl: p.mainImageUrl ?? undefined,
buyUrl: p.buyUrl ?? undefined,
inStock: p.inStock ?? true,
}));
setParts(normalized);
setParts(
data.map((p) => ({
id: normalizeId(p.id),
name: p.name,
brand: p.brand,
platform: p.platform,
partRole: p.partRole,
price: p.price ?? 0,
imageUrl: p.mainImageUrl ?? undefined,
buyUrl: p.buyUrl ?? undefined,
inStock: p.inStock ?? true,
}))
);
} catch (err: any) {
if (err?.name === "AbortError") return;
setError(err?.message ?? "Failed to load products");
@@ -160,6 +166,7 @@ export default function PartsBrowseClient(props: {
return () => controller.abort();
}, [partRole, effectivePlatform]);
// Reset pagination on filters
useEffect(() => {
setCurrentPage(1);
}, [
@@ -172,11 +179,14 @@ export default function PartsBrowseClient(props: {
inStockOnly,
]);
// Reset scroll on route change
useEffect(() => {
// Reset scroll position whenever we land on or change parts routes
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
window.scrollTo({ top: 0, behavior: "auto" });
}, [pathname]);
// ----------------------------
// Derived values
// ----------------------------
const availableBrands = useMemo(
() =>
Array.from(new Set(parts.map((p) => p.brand)))
@@ -186,34 +196,27 @@ export default function PartsBrowseClient(props: {
);
const priceBounds = useMemo(() => {
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;
for (const p of parts) {
const price = p.price ?? 0;
if (price < min) min = price;
if (price > max) max = price;
}
if (!Number.isFinite(min) || !Number.isFinite(max)) {
return { min: null as number | null, max: null as number | null };
}
return { min, max };
if (!parts.length) return { min: null as number | null, max: null as number | null };
return {
min: Math.min(...parts.map((p) => p.price)),
max: Math.max(...parts.map((p) => p.price)),
};
}, [parts]);
// Keep priceRange clamped to bounds when bounds change
useEffect(() => {
if (priceBounds.min == null || priceBounds.max == null) return;
const minBound = priceBounds.min;
const maxBound = priceBounds.max;
if (minBound == null || maxBound == null) return;
setPriceRange((prev) => {
const min = prev.min ?? priceBounds.min!;
const max = prev.max ?? priceBounds.max!;
const nextMin = prev.min == null ? minBound : Math.max(minBound, prev.min);
const nextMax = prev.max == null ? maxBound : Math.min(maxBound, prev.max);
// Ensure min never exceeds max (in case user typed weird values)
return {
min: Math.max(priceBounds.min!, Math.min(min, priceBounds.max!)),
max: Math.min(priceBounds.max!, Math.max(max, priceBounds.min!)),
min: Math.min(nextMin, nextMax),
max: Math.max(nextMin, nextMax),
};
});
}, [priceBounds.min, priceBounds.max]);
@@ -221,30 +224,24 @@ export default function PartsBrowseClient(props: {
const filteredParts = useMemo(() => {
let result = [...parts];
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
);
}
if (priceRange.min != null)
result = result.filter((p) => p.price >= priceRange.min!);
if (priceRange.max != null)
result = result.filter((p) => p.price <= priceRange.max!);
if (brandFilter.length > 0) {
if (brandFilter.length)
result = result.filter((p) => brandFilter.includes(p.brand));
}
if (inStockOnly) {
if (inStockOnly)
result = result.filter((p) => p.inStock ?? true);
}
const q = searchQuery.trim().toLowerCase();
if (q) {
result = result.filter((p) => {
const name = (p.name ?? "").toLowerCase();
const brand = (p.brand ?? "").toLowerCase();
return name.includes(q) || brand.includes(q);
});
}
const q = searchQuery.toLowerCase().trim();
if (q)
result = result.filter(
(p) =>
p.name.toLowerCase().includes(q) ||
p.brand.toLowerCase().includes(q)
);
switch (sortBy) {
case "price-asc":
@@ -262,47 +259,25 @@ export default function PartsBrowseClient(props: {
}
return result;
}, [
parts,
brandFilter,
sortBy,
searchQuery,
priceRange,
priceBounds.min,
priceBounds.max,
inStockOnly,
]);
}, [parts, brandFilter, sortBy, searchQuery, priceRange, inStockOnly]);
const totalPages = useMemo(
() =>
filteredParts.length === 0
? 1
: Math.ceil(filteredParts.length / PAGE_SIZE),
[filteredParts.length]
const totalPages = Math.max(1, Math.ceil(filteredParts.length / PAGE_SIZE));
const paginatedParts = filteredParts.slice(
(currentPage - 1) * PAGE_SIZE,
currentPage * PAGE_SIZE
);
const paginatedParts = useMemo(() => {
if (filteredParts.length === 0) return [];
const startIndex = (currentPage - 1) * PAGE_SIZE;
return filteredParts.slice(startIndex, startIndex + PAGE_SIZE);
}, [filteredParts, currentPage]);
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
);
return { start, end };
}, [filteredParts.length, currentPage, paginatedParts.length]);
const visibleRange = {
start: filteredParts.length ? (currentPage - 1) * PAGE_SIZE + 1 : 0,
end: Math.min(currentPage * PAGE_SIZE, filteredParts.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.";
// ✅ Add-to-build handler: deep-links into builders existing ?select= logic
// ----------------------------
// Add → Builder handoff
// ----------------------------
const handleAddToBuild = (p: UiPart) => {
const normalizedRole = normalizePartRole(partRole);
const categoryId: CategoryId | null =
@@ -327,22 +302,22 @@ export default function PartsBrowseClient(props: {
return (
<main className="min-h-screen bg-black text-zinc-50">
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
<header className="mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
Battl Builders
</p>
<header className="mb-6 flex justify-between gap-4">
<div>
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
Battl Builders
</p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
{headingTitle}{" "}
<span className="text-amber-300">{effectivePlatform}</span>
</h1>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold">
{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>
{!isBuilderMode && (
<div className="mt-3">
<PlatformSwitcher
currentPlatform={effectivePlatform}
@@ -350,57 +325,53 @@ export default function PartsBrowseClient(props: {
preserveQuery
/>
</div>
</div>
{!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"
>
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>
{isBuilderMode && (
<div className="flex items-center gap-2">
<Link
href={`/builder?platform=${encodeURIComponent(effectivePlatform)}`}
className="rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-xs font-semibold hover:bg-zinc-800"
>
Back to Build
</Link>
{/* Optional: view toggle in builder-mode too */}
{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>
)}
</header>
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
<div className="flex flex-col gap-4 md:flex-row">
{!loading && !error && parts.length > 0 && (
<aside className="w-full md:w-64 shrink-0">
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4">
<div className="flex flex-col md:flex-row gap-4">
{parts.length > 0 && (
<aside className="w-full md:w-64">
<Filters
partRoleLabel={partRole}
availableBrands={availableBrands}
@@ -416,7 +387,7 @@ export default function PartsBrowseClient(props: {
)}
<div className="flex-1">
{!loading && !error && parts.length > 0 && (
{!loading && !error && (
<SortBar
visibleRange={visibleRange}
totalCount={filteredParts.length}
@@ -428,13 +399,9 @@ 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>
<p className="py-8 text-center text-sm text-red-400">{error}</p>
) : filteredParts.length === 0 ? (
<p className="py-8 text-center text-sm text-zinc-500">
No parts found for this role yet.
@@ -451,23 +418,20 @@ export default function PartsBrowseClient(props: {
/>
)}
{!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))
}
/>
)}
{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>
);
}
}
+12 -20
View File
@@ -3,23 +3,10 @@
import { useMemo } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
/**
* PlatformSwitcher
*
* Works on BOTH:
* - /parts/[partRole] (default browse route)
* - /parts/[platform]/[partRole] (canonical route)
*
* Behavior:
* - If you're on /parts/[partRole], switching platform navigates to /parts/[platform]/[partRole]
* (so your URL becomes explicit/shareable).
* - If you're already on /parts/[platform]/[partRole], it swaps the platform segment.
*/
export default function PlatformSwitcher(props: {
currentPlatform: string;
partRole: string;
// If true, we keep query params when switching (nice for sort/paging)
preserveQuery?: boolean;
preserveQuery?: boolean; // keep sort/page/etc (but NOT platform)
}) {
const { currentPlatform, partRole, preserveQuery = true } = props;
@@ -29,13 +16,19 @@ export default function PlatformSwitcher(props: {
const queryString = useMemo(() => {
if (!preserveQuery) return "";
const q = searchParams?.toString();
// Copy params and DROP legacy platform param so it cant conflict with the path
const sp = new URLSearchParams(searchParams?.toString());
sp.delete("platform");
const q = sp.toString();
return q ? `?${q}` : "";
}, [searchParams, preserveQuery]);
function go(platform: string) {
// We always navigate to canonical to keep it simple & consistent
router.push(`/parts/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}${queryString}`);
router.replace(
`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}${queryString}`
);
}
return (
@@ -52,9 +45,8 @@ export default function PlatformSwitcher(props: {
<option value="AK-47">AK-47</option>
</select>
<span className="ml-2 text-[0.7rem] text-zinc-500">
{pathname}
</span>
{/* debug only */}
<span className="ml-2 text-[0.7rem] text-zinc-500">{pathname}</span>
</div>
);
}
+3 -2
View File
@@ -122,11 +122,12 @@ export default function ProductDetailPageClient(props: {
</h1>
</div>
<PlatformSwitcher currentPlatform={platform} partRole={partRole} />
{/* temp disabling while I rework the routing. */}
{/* <PlatformSwitcher currentPlatform={platform} partRole={partRole} /> */}
</div>
<div className="flex items-center gap-2 text-xs text-zinc-500">
<Link className="hover:text-amber-200" href={`/parts/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}`}>
<Link className="hover:text-amber-200" href={`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}`}>
Back to list
</Link>
<span></span>