diff --git a/next.config.js b/next.config.js new file mode 100644 index 000000000..980e7284d --- /dev/null +++ b/next.config.js @@ -0,0 +1,19 @@ +module.exports = { + rewrites() { + return [ + { + source: '/search/designers/:name', + destination: '/search', + }, + { + source: '/search/designers/:name/:category', + destination: '/search', + }, + { + // This rewrite will also handle `/search/designers` + source: '/search/:category', + destination: '/search', + }, + ] + }, +} diff --git a/pages/search.tsx b/pages/search.tsx index bc45b1b8d..d71049a4b 100644 --- a/pages/search.tsx +++ b/pages/search.tsx @@ -1,10 +1,12 @@ +import { useEffect, useState } from 'react' import { GetStaticPropsContext, InferGetStaticPropsType } from 'next' +import { useRouter } from 'next/router' +import Link from 'next/link' import getSiteInfo from '@lib/bigcommerce/api/operations/get-site-info' import useSearch from '@lib/bigcommerce/products/use-search' import { Layout } from '@components/core' import { Container, Grid } from '@components/ui' import { ProductCard } from '@components/product' -import { useRouter } from 'next/router' export async function getStaticProps({ preview }: GetStaticPropsContext) { const { categories, brands } = await getSiteInfo() @@ -23,6 +25,9 @@ export default function Home({ const { data } = useSearch({ search: typeof q === 'string' ? q : '', }) + const { category, brand } = useSearchMeta(router.asPath) + + console.log('Q', category, brand) return ( @@ -34,7 +39,9 @@ export default function Home({ {categories.map((cat) => (
  • - {cat.name} + + {cat.name} +
  • ))} @@ -44,7 +51,9 @@ export default function Home({ {brands.flatMap(({ node }) => (
  • - {node.name} + + {node.name} +
  • ))} @@ -89,3 +98,38 @@ export default function Home({ } Home.Layout = Layout + +function useSearchMeta(asPath: string) { + const [category, setCategory] = useState() + const [brand, setBrand] = useState() + + useEffect(() => { + const parts = asPath.split('/') + + // console.log('parts', parts) + + let c = parts[2] + let b = parts[3] + + if (c === 'designers') { + c = parts[4] + } + + if (c !== category) setCategory(c) + if (b !== brand) setBrand(b) + }, [asPath]) + + return { category, brand } +} + +function getCategoryPath(path: string, designer?: string) { + return designer ? `/search/designers/${designer}${path}` : `/search${path}` +} + +function getDesignerPath(path: string, category?: string) { + // Remove the trailing slash and replace /brands with /designers + const designer = path.replace(/^\/brands/, '/designers').replace(/\/$/, '') + const href = `/search${designer}` + + return category ? `${href}/${category}` : href +}