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
@@ -936,7 +936,7 @@ export default function GunbuilderPage() {
BATTL BUILDERS BATTL BUILDERS
</p> </p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight"> <h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
BattlBuilder <span className="text-amber-300">Early Access</span> Builder <span className="text-amber-300">Early Access</span>
</h1> </h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl"> <p className="mt-2 text-sm text-zinc-400 max-w-xl">
Explore components from trusted brands, choose one part per Explore components from trusted brands, choose one part per
@@ -1317,10 +1317,7 @@ export default function GunbuilderPage() {
</> </>
) : hasParts ? ( ) : hasParts ? (
<Link <Link
href={{ href={`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(category.id)}`}
pathname: `/parts/p/${platform}/${category.id}`,
query: platform ? { 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
@@ -0,0 +1,16 @@
import PartsBrowseClient from "@/components/parts/PartsBrowseClient";
export default async function PartsBrowsePage({
params,
}: {
params: Promise<{ partRole: string }>;
}) {
const { partRole } = await params;
return (
<PartsBrowseClient
partRole={decodeURIComponent(partRole)}
platform={null} // let client read ?platform=... or default
/>
);
}
@@ -204,7 +204,7 @@ export default function ProductDetailsPage() {
href={{ pathname: "/builder", query: platform ? { platform } : {} }} href={{ pathname: "/builder", query: platform ? { platform } : {} }}
className="hover:text-zinc-300" className="hover:text-zinc-300"
> >
The Armory The Builder
</Link> </Link>
<span className="text-zinc-700">/</span> <span className="text-zinc-700">/</span>
<Link <Link
@@ -370,7 +370,7 @@ export default function CategoryPage() {
href={{ pathname: "/builder", query: platform ? { platform } : {} }} href={{ pathname: "/builder", query: platform ? { platform } : {} }}
className="text-xs text-zinc-400 hover:text-zinc-300 mb-4 inline-block" className="text-xs text-zinc-400 hover:text-zinc-300 mb-4 inline-block"
> >
Back to The Armory Back to the Builder
</Link> </Link>
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4">
<div> <div>
@@ -17,6 +17,7 @@ type BuildDto = {
slot: string; slot: string;
productId: number; productId: number;
productName?: string | null; productName?: string | null;
productBrand?: string | null;
bestPrice?: number | string | null; // backend may serialize BigDecimal as string bestPrice?: number | string | null; // backend may serialize BigDecimal as string
}>; }>;
photos?: BuildPhotoDto[]; photos?: BuildPhotoDto[];
@@ -68,7 +69,7 @@ export default function VaultBuildEditPage() {
return () => { return () => {
previews.forEach((p) => URL.revokeObjectURL(p.url)); previews.forEach((p) => URL.revokeObjectURL(p.url));
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
const authed = !!token; const authed = !!token;
@@ -311,54 +312,62 @@ export default function VaultBuildEditPage() {
{!build.items?.length ? ( {!build.items?.length ? (
<div className="text-sm opacity-70">No parts saved yet.</div> <div className="text-sm opacity-70">No parts saved yet.</div>
) : ( ) : (
<div className="space-y-4"> <div className="overflow-hidden rounded-lg border border-white/10 bg-black/20">
{Object.entries( {/* header */}
build.items.reduce<Record<string, typeof build.items>>( <div className="grid grid-cols-12 gap-3 border-b border-white/10 px-3 py-2 text-[11px] font-semibold uppercase tracking-wider text-zinc-400">
(acc, it) => { <div className="col-span-5">Product</div>
(acc[it.slot] ||= []).push(it); <div className="col-span-4">Component (Role)</div>
return acc; <div className="col-span-2">Brand</div>
}, <div className="col-span-1 text-right">Price</div>
{} </div>
)
).map(([slot, items]) => (
<div key={slot}>
<div className="mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-400">
{slot}
</div>
<div className="rounded-lg border border-white/10 bg-black/20"> {/* rows */}
{items.map((it, idx) => ( {build.items
<div .slice()
key={`${it.slot}-${it.productId}-${idx}`} .sort((a, b) => a.slot.localeCompare(b.slot))
className="flex items-center justify-between gap-4 px-3 py-2 text-sm border-b border-white/5 last:border-b-0" .map((it, idx) => {
> const price =
<div className="min-w-0"> typeof it.bestPrice === "number"
<div className="truncate text-zinc-100"> ? it.bestPrice
{it.productName ?? `Product #${it.productId}`} : it.bestPrice
</div> ? Number(it.bestPrice)
<div className="text-xs text-zinc-400"> : null;
ID:{" "}
<span className="font-mono">{it.productId}</span> return (
</div> <div
key={`${it.slot}-${it.productId}-${idx}`}
className="grid grid-cols-12 gap-2 border-b border-white/5 px-3 py-2 text-sm last:border-b-0"
>
{/* Product */}
<div className="col-span-5 min-w-0">
<div className="truncate text-zinc-100">
{it.productName ?? `Product #${it.productId}`}
</div> </div>
<div className="text-xs text-zinc-500">
<div className="shrink-0 text-right"> ID:{" "}
<div className="font-semibold"> <span className="font-mono">{it.productId}</span>
{typeof it.bestPrice === "number"
? `$${it.bestPrice.toFixed(2)}`
: it.bestPrice
? `$${Number(it.bestPrice).toFixed(2)}`
: "—"}
</div>
<div className="text-[11px] text-zinc-500">
Best price
</div>
</div> </div>
</div> </div>
))}
</div> {/* Component (Role) */}
</div> <div className="col-span-4 truncate text-zinc-200">
))} {it.slot}
</div>
{/* Brand */}
<div className="col-span-2 truncate text-zinc-300">
{it.productBrand ?? "—"}
</div>
{/* Price */}
<div className="col-span-1 text-right font-semibold text-zinc-100">
{price != null && !Number.isNaN(price)
? `$${price.toFixed(2)}`
: "—"}
</div>
</div>
);
})}
</div> </div>
)} )}
</div> </div>
+1 -1
View File
@@ -91,7 +91,7 @@ export default function LoginPage() {
<main className="min-h-screen bg-black text-zinc-50"> <main className="min-h-screen bg-black text-zinc-50">
<div className="mx-auto flex max-w-md flex-col px-4 py-10"> <div className="mx-auto flex max-w-md flex-col px-4 py-10">
<h1 className="text-2xl font-semibold tracking-tight"> <h1 className="text-2xl font-semibold tracking-tight">
Log In to <span className="text-amber-300">The Armory</span> Log In to <span className="text-amber-300">The Builder</span>
</h1> </h1>
<p className="mt-2 text-sm text-zinc-400"> <p className="mt-2 text-sm text-zinc-400">
Use your beta credentials to get back to your saved builds. Use your beta credentials to get back to your saved builds.
+1 -1
View File
@@ -11,7 +11,7 @@ export function Banner() {
Early Access Beta Early Access Beta
</span> </span>
<span className="hidden text-amber-100/90 md:inline"> <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. pricing, and available parts are still evolving.
</span> </span>
</div> </div>
+10 -3
View File
@@ -57,6 +57,8 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
const renderDropdown = (label: string, items: Category[]) => { const renderDropdown = (label: string, items: Category[]) => {
if (!items.length) return null; if (!items.length) return null;
const platform = searchParams.get("platform");
return ( return (
<div className="relative group"> <div className="relative group">
{/* Dropdown trigger */} {/* Dropdown trigger */}
@@ -80,7 +82,10 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
return ( return (
<li key={cat.id}> <li key={cat.id}>
<Link <Link
href={`${baseHref}/${cat.id}`} href={{
pathname: `${baseHref}/${cat.id}`,
query: platform ? { platform } : {},
}}
className={`block w-full px-3 py-1.5 transition-colors ${ className={`block w-full px-3 py-1.5 transition-colors ${
isActive isActive
? "bg-neutral-800 text-white" ? "bg-neutral-800 text-white"
@@ -162,7 +167,9 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) {
{/* "Viewing" indicator (only shows when a category is active) */} {/* "Viewing" indicator (only shows when a category is active) */}
{currentCategory && ( {currentCategory && (
<div className="flex items-center gap-2 text-neutral-400 text-xs"> <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"> <span className="font-medium text-neutral-100">
{CATEGORIES.find((c) => c.id === currentCategory)?.name ?? {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"; "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 { interface PricingHistoryGraphProps {
data: PriceHistoryPoint[]; data: PriceHistoryPoint[];
+1 -1
View File
@@ -1,6 +1,6 @@
"use client"; "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 { interface RetailersListProps {
retailers: RetailerOffer[]; retailers: RetailerOffer[];
+151 -187
View File
@@ -1,8 +1,3 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
/** /**
* PartsBrowseClient * PartsBrowseClient
* ----------------------------------------------------------------------------- * -----------------------------------------------------------------------------
@@ -13,8 +8,11 @@ import { usePathname } from "next/navigation";
* - layout + list/card views * - layout + list/card views
*/ */
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react"; 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 Filters from "@/components/parts/Filters";
import SortBar from "@/components/parts/SortBar"; import SortBar from "@/components/parts/SortBar";
@@ -23,10 +21,7 @@ import Pagination from "@/components/parts/Pagination";
import PlatformSwitcher from "@/components/parts/PlatformSwitcher"; import PlatformSwitcher from "@/components/parts/PlatformSwitcher";
import type { CategoryId } from "@/types/gunbuilder"; import type { CategoryId } from "@/types/gunbuilder";
import { import { PART_ROLE_TO_CATEGORY, normalizePartRole } from "@/lib/catalogMappings";
PART_ROLE_TO_CATEGORY,
normalizePartRole,
} from "@/lib/catalogMappings";
type ViewMode = "card" | "list"; type ViewMode = "card" | "list";
type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc"; type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc";
@@ -49,7 +44,7 @@ type UiPart = {
brand: string; brand: string;
platform: string; platform: string;
partRole: string; partRole: string;
price: number; // normalized price: number;
imageUrl?: string; imageUrl?: string;
buyUrl?: string; buyUrl?: string;
inStock?: boolean; inStock?: boolean;
@@ -57,6 +52,7 @@ type UiPart = {
const API_BASE_URL = const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"; process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
const PAGE_SIZE = 24; const PAGE_SIZE = 24;
function normalizeId(id: string | number) { function normalizeId(id: string | number) {
@@ -92,8 +88,13 @@ export default function PartsBrowseClient(props: {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const pathname = usePathname(); 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 = const effectivePlatform =
props.platform ?? searchParams.get("platform") ?? "AR-15"; props.platform ?? searchParams.get("platform") ?? "AR-15";
const partRole = props.partRole; const partRole = props.partRole;
const [viewMode, setViewMode] = useState<ViewMode>("list"); const [viewMode, setViewMode] = useState<ViewMode>("list");
@@ -103,7 +104,7 @@ export default function PartsBrowseClient(props: {
const [brandFilter, setBrandFilter] = useState<string[]>([]); const [brandFilter, setBrandFilter] = useState<string[]>([]);
const [sortBy, setSortBy] = useState<SortOption>("relevance"); const [sortBy, setSortBy] = useState<SortOption>("relevance");
const [searchQuery, setSearchQuery] = useState<string>(""); const [searchQuery, setSearchQuery] = useState("");
const [priceRange, setPriceRange] = useState<{ const [priceRange, setPriceRange] = useState<{
min: number | null; min: number | null;
max: number | null; max: number | null;
@@ -114,6 +115,9 @@ export default function PartsBrowseClient(props: {
const [inStockOnly, setInStockOnly] = useState(false); const [inStockOnly, setInStockOnly] = useState(false);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
// ----------------------------
// Fetch parts
// ----------------------------
useEffect(() => { useEffect(() => {
if (!partRole) return; if (!partRole) return;
@@ -128,26 +132,28 @@ export default function PartsBrowseClient(props: {
search.set("platform", effectivePlatform); search.set("platform", effectivePlatform);
search.append("partRoles", partRole); search.append("partRoles", partRole);
const url = `${API_BASE_URL}/api/v1/products?${search.toString()}`; const res = await fetch(
const res = await fetch(url, { signal: controller.signal }); `${API_BASE_URL}/api/v1/products?${search.toString()}`,
{ signal: controller.signal }
);
if (!res.ok) throw new Error(`Failed to load products (${res.status})`); if (!res.ok) throw new Error(`Failed to load products (${res.status})`);
const data: GunbuilderProductFromApi[] = await res.json(); const data: GunbuilderProductFromApi[] = await res.json();
const normalized: UiPart[] = data.map((p) => ({ setParts(
id: normalizeId(p.id), data.map((p) => ({
name: p.name, id: normalizeId(p.id),
brand: p.brand, name: p.name,
platform: p.platform, brand: p.brand,
partRole: p.partRole, platform: p.platform,
price: p.price ?? 0, partRole: p.partRole,
imageUrl: p.mainImageUrl ?? undefined, price: p.price ?? 0,
buyUrl: p.buyUrl ?? undefined, imageUrl: p.mainImageUrl ?? undefined,
inStock: p.inStock ?? true, buyUrl: p.buyUrl ?? undefined,
})); inStock: p.inStock ?? true,
}))
setParts(normalized); );
} catch (err: any) { } catch (err: any) {
if (err?.name === "AbortError") return; if (err?.name === "AbortError") return;
setError(err?.message ?? "Failed to load products"); setError(err?.message ?? "Failed to load products");
@@ -160,6 +166,7 @@ export default function PartsBrowseClient(props: {
return () => controller.abort(); return () => controller.abort();
}, [partRole, effectivePlatform]); }, [partRole, effectivePlatform]);
// Reset pagination on filters
useEffect(() => { useEffect(() => {
setCurrentPage(1); setCurrentPage(1);
}, [ }, [
@@ -172,11 +179,14 @@ export default function PartsBrowseClient(props: {
inStockOnly, inStockOnly,
]); ]);
// Reset scroll on route change
useEffect(() => { useEffect(() => {
// Reset scroll position whenever we land on or change parts routes window.scrollTo({ top: 0, behavior: "auto" });
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
}, [pathname]); }, [pathname]);
// ----------------------------
// Derived values
// ----------------------------
const availableBrands = useMemo( const availableBrands = useMemo(
() => () =>
Array.from(new Set(parts.map((p) => p.brand))) Array.from(new Set(parts.map((p) => p.brand)))
@@ -186,34 +196,27 @@ export default function PartsBrowseClient(props: {
); );
const priceBounds = useMemo(() => { const priceBounds = useMemo(() => {
if (parts.length === 0) if (!parts.length) return { min: null as number | null, max: null as number | null };
return { min: null as number | null, max: null as number | null }; return {
min: Math.min(...parts.map((p) => p.price)),
let min = Number.POSITIVE_INFINITY; max: Math.max(...parts.map((p) => p.price)),
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 };
}, [parts]); }, [parts]);
// Keep priceRange clamped to bounds when bounds change
useEffect(() => { 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) => { setPriceRange((prev) => {
const min = prev.min ?? priceBounds.min!; const nextMin = prev.min == null ? minBound : Math.max(minBound, prev.min);
const max = prev.max ?? priceBounds.max!; const nextMax = prev.max == null ? maxBound : Math.min(maxBound, prev.max);
// Ensure min never exceeds max (in case user typed weird values)
return { return {
min: Math.max(priceBounds.min!, Math.min(min, priceBounds.max!)), min: Math.min(nextMin, nextMax),
max: Math.min(priceBounds.max!, Math.max(max, priceBounds.min!)), max: Math.max(nextMin, nextMax),
}; };
}); });
}, [priceBounds.min, priceBounds.max]); }, [priceBounds.min, priceBounds.max]);
@@ -221,30 +224,24 @@ export default function PartsBrowseClient(props: {
const filteredParts = useMemo(() => { const filteredParts = useMemo(() => {
let result = [...parts]; let result = [...parts];
const effectiveMin = priceRange.min ?? priceBounds.min; if (priceRange.min != null)
const effectiveMax = priceRange.max ?? priceBounds.max; result = result.filter((p) => p.price >= priceRange.min!);
if (effectiveMin != null && effectiveMax != null) { if (priceRange.max != null)
result = result.filter( result = result.filter((p) => p.price <= priceRange.max!);
(p) => p.price >= effectiveMin && p.price <= effectiveMax
);
}
if (brandFilter.length > 0) { if (brandFilter.length)
result = result.filter((p) => brandFilter.includes(p.brand)); result = result.filter((p) => brandFilter.includes(p.brand));
}
if (inStockOnly) { if (inStockOnly)
result = result.filter((p) => p.inStock ?? true); result = result.filter((p) => p.inStock ?? true);
}
const q = searchQuery.trim().toLowerCase(); const q = searchQuery.toLowerCase().trim();
if (q) { if (q)
result = result.filter((p) => { result = result.filter(
const name = (p.name ?? "").toLowerCase(); (p) =>
const brand = (p.brand ?? "").toLowerCase(); p.name.toLowerCase().includes(q) ||
return name.includes(q) || brand.includes(q); p.brand.toLowerCase().includes(q)
}); );
}
switch (sortBy) { switch (sortBy) {
case "price-asc": case "price-asc":
@@ -262,47 +259,25 @@ export default function PartsBrowseClient(props: {
} }
return result; return result;
}, [ }, [parts, brandFilter, sortBy, searchQuery, priceRange, inStockOnly]);
parts,
brandFilter,
sortBy,
searchQuery,
priceRange,
priceBounds.min,
priceBounds.max,
inStockOnly,
]);
const totalPages = useMemo( const totalPages = Math.max(1, Math.ceil(filteredParts.length / PAGE_SIZE));
() => const paginatedParts = filteredParts.slice(
filteredParts.length === 0 (currentPage - 1) * PAGE_SIZE,
? 1 currentPage * PAGE_SIZE
: Math.ceil(filteredParts.length / PAGE_SIZE),
[filteredParts.length]
); );
const paginatedParts = useMemo(() => { const visibleRange = {
if (filteredParts.length === 0) return []; start: filteredParts.length ? (currentPage - 1) * PAGE_SIZE + 1 : 0,
const startIndex = (currentPage - 1) * PAGE_SIZE; end: Math.min(currentPage * PAGE_SIZE, filteredParts.length),
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 headingTitle = props.title ?? `${partRole.replaceAll("-", " ")} parts`; const headingTitle = props.title ?? `${partRole.replaceAll("-", " ")} parts`;
const headingSubtitle = const headingSubtitle = props.subtitle ?? "Browse available parts.";
props.subtitle ??
"Browse available parts pulled from your Ballistic backend.";
// ✅ Add-to-build handler: deep-links into builders existing ?select= logic // ----------------------------
// Add → Builder handoff
// ----------------------------
const handleAddToBuild = (p: UiPart) => { const handleAddToBuild = (p: UiPart) => {
const normalizedRole = normalizePartRole(partRole); const normalizedRole = normalizePartRole(partRole);
const categoryId: CategoryId | null = const categoryId: CategoryId | null =
@@ -327,22 +302,22 @@ export default function PartsBrowseClient(props: {
return ( return (
<main className="min-h-screen bg-black text-zinc-50"> <main className="min-h-screen bg-black text-zinc-50">
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10"> <div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
<header className="mb-6"> <header className="mb-6 flex justify-between gap-4">
<div className="flex items-start justify-between gap-4"> <div>
<div> <p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500"> Battl Builders
Battl Builders </p>
</p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight"> <h1 className="mt-1 text-2xl md:text-3xl font-semibold">
{headingTitle}{" "} {headingTitle}{" "}
<span className="text-amber-300">{effectivePlatform}</span> <span className="text-amber-300">{effectivePlatform}</span>
</h1> </h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl"> <p className="mt-2 text-sm text-zinc-400 max-w-xl">
{headingSubtitle} {headingSubtitle}
</p> </p>
{!isBuilderMode && (
<div className="mt-3"> <div className="mt-3">
<PlatformSwitcher <PlatformSwitcher
currentPlatform={effectivePlatform} currentPlatform={effectivePlatform}
@@ -350,57 +325,53 @@ export default function PartsBrowseClient(props: {
preserveQuery preserveQuery
/> />
</div> </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> </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> </header>
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4"> <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4">
<div className="flex flex-col gap-4 md:flex-row"> <div className="flex flex-col md:flex-row gap-4">
{!loading && !error && parts.length > 0 && ( {parts.length > 0 && (
<aside className="w-full md:w-64 shrink-0"> <aside className="w-full md:w-64">
<Filters <Filters
partRoleLabel={partRole} partRoleLabel={partRole}
availableBrands={availableBrands} availableBrands={availableBrands}
@@ -416,7 +387,7 @@ export default function PartsBrowseClient(props: {
)} )}
<div className="flex-1"> <div className="flex-1">
{!loading && !error && parts.length > 0 && ( {!loading && !error && (
<SortBar <SortBar
visibleRange={visibleRange} visibleRange={visibleRange}
totalCount={filteredParts.length} totalCount={filteredParts.length}
@@ -428,13 +399,9 @@ export default function PartsBrowseClient(props: {
)} )}
{loading ? ( {loading ? (
<p className="py-8 text-center text-sm text-zinc-500"> <p className="py-8 text-center text-sm text-zinc-500">Loading</p>
Loading
</p>
) : error ? ( ) : error ? (
<p className="py-8 text-center text-sm text-red-400"> <p className="py-8 text-center text-sm text-red-400">{error}</p>
{error} check that the Ballistic API is running.
</p>
) : filteredParts.length === 0 ? ( ) : filteredParts.length === 0 ? (
<p className="py-8 text-center text-sm text-zinc-500"> <p className="py-8 text-center text-sm text-zinc-500">
No parts found for this role yet. No parts found for this role yet.
@@ -451,23 +418,20 @@ export default function PartsBrowseClient(props: {
/> />
)} )}
{!loading && {totalPages > 1 && (
!error && <Pagination
filteredParts.length > 0 && currentPage={currentPage}
totalPages > 1 && ( totalPages={totalPages}
<Pagination onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))}
currentPage={currentPage} onNext={() =>
totalPages={totalPages} setCurrentPage((p) => Math.min(totalPages, p + 1))
onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))} }
onNext={() => />
setCurrentPage((p) => Math.min(totalPages, p + 1)) )}
}
/>
)}
</div> </div>
</div> </div>
</section> </section>
</div> </div>
</main> </main>
); );
} }
+12 -20
View File
@@ -3,23 +3,10 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation"; 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: { export default function PlatformSwitcher(props: {
currentPlatform: string; currentPlatform: string;
partRole: string; partRole: string;
// If true, we keep query params when switching (nice for sort/paging) preserveQuery?: boolean; // keep sort/page/etc (but NOT platform)
preserveQuery?: boolean;
}) { }) {
const { currentPlatform, partRole, preserveQuery = true } = props; const { currentPlatform, partRole, preserveQuery = true } = props;
@@ -29,13 +16,19 @@ export default function PlatformSwitcher(props: {
const queryString = useMemo(() => { const queryString = useMemo(() => {
if (!preserveQuery) return ""; 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}` : ""; return q ? `?${q}` : "";
}, [searchParams, preserveQuery]); }, [searchParams, preserveQuery]);
function go(platform: string) { function go(platform: string) {
// We always navigate to canonical to keep it simple & consistent router.replace(
router.push(`/parts/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}${queryString}`); `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}${queryString}`
);
} }
return ( return (
@@ -52,9 +45,8 @@ export default function PlatformSwitcher(props: {
<option value="AK-47">AK-47</option> <option value="AK-47">AK-47</option>
</select> </select>
<span className="ml-2 text-[0.7rem] text-zinc-500"> {/* debug only */}
{pathname} <span className="ml-2 text-[0.7rem] text-zinc-500">{pathname}</span>
</span>
</div> </div>
); );
} }
+3 -2
View File
@@ -122,11 +122,12 @@ export default function ProductDetailPageClient(props: {
</h1> </h1>
</div> </div>
<PlatformSwitcher currentPlatform={platform} partRole={partRole} /> {/* temp disabling while I rework the routing. */}
{/* <PlatformSwitcher currentPlatform={platform} partRole={partRole} /> */}
</div> </div>
<div className="flex items-center gap-2 text-xs text-zinc-500"> <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 Back to list
</Link> </Link>
<span></span> <span></span>