mirror of
https://github.com/vercel/commerce.git
synced 2025-05-11 12:17:51 +00:00
add dedicated filters for models and years
Signed-off-by: Chloe <pinkcloudvnn@gmail.com>
This commit is contained in:
parent
a077bbe753
commit
7e9a84aaae
@ -13,6 +13,7 @@ import { getProductsInCollection } from 'components/layout/products-list/actions
|
||||
import FiltersContainer, {
|
||||
FiltersListPlaceholder
|
||||
} from 'components/layout/search/filters/filters-container';
|
||||
import MakeModelFilters from 'components/layout/search/filters/make-model-filters';
|
||||
import MobileFilters from 'components/layout/search/filters/mobile-filters';
|
||||
import SubMenu from 'components/layout/search/filters/sub-menu';
|
||||
import Header, { HeaderPlaceholder } from 'components/layout/search/header';
|
||||
@ -96,6 +97,9 @@ export default async function CategorySearchPage(props: {
|
||||
</div>
|
||||
|
||||
<SubMenu collection={collectionHandle} />
|
||||
<Suspense>
|
||||
<MakeModelFilters collection={collectionHandle} />
|
||||
</Suspense>
|
||||
<h3 className="sr-only">Filters</h3>
|
||||
<Suspense fallback={<FiltersListPlaceholder />} key={`filters-${collectionHandle}`}>
|
||||
<FiltersContainer searchParams={props.searchParams} collection={collectionHandle} />
|
||||
|
@ -1,12 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@headlessui/react';
|
||||
import { MAKE_FILTER_ID, MODEL_FILTER_ID, PART_TYPES, YEAR_FILTER_ID } from 'lib/constants';
|
||||
import { PART_TYPES } from 'lib/constants';
|
||||
import { Menu, Metaobject } from 'lib/shopify/types';
|
||||
import { createUrl, findParentCollection } from 'lib/utils';
|
||||
import { findParentCollection } from 'lib/utils';
|
||||
import get from 'lodash.get';
|
||||
import { useParams, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState, useTransition } from 'react';
|
||||
import kebabCase from 'lodash.kebabcase';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fetMetaobjects } from './actions';
|
||||
import FilterField from './field';
|
||||
|
||||
@ -19,42 +20,35 @@ type FiltersListProps = {
|
||||
const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
const params = useParams<{ collection?: string }>();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [, initialMake, initialModel, initialYear] = params.collection?.split('_') || [];
|
||||
|
||||
const parentCollection = params.collection ? findParentCollection(menu, params.collection) : null;
|
||||
// get the active collection (if any) to identify the default part type.
|
||||
// if a collection is a sub collection, we will find the parent. Normally in this case, the parent collection would either be transmissions or engines.
|
||||
const partTypeCollection = parentCollection?.path.split('/').slice(-1)[0] || params.collection;
|
||||
|
||||
const [partType, setPartType] = useState<{ label: string; value: string } | null>(
|
||||
PART_TYPES.find((type) => type.value === partTypeCollection) || null
|
||||
PART_TYPES.find(
|
||||
(type) =>
|
||||
type.value === partTypeCollection ||
|
||||
(partTypeCollection && partTypeCollection.includes(type.value))
|
||||
) || null
|
||||
);
|
||||
|
||||
const makeIdFromSearchParams = searchParams.get(MAKE_FILTER_ID);
|
||||
const modelIdFromSearchParams = searchParams.get(MODEL_FILTER_ID);
|
||||
const yearIdFromSearchParams = searchParams.get(YEAR_FILTER_ID);
|
||||
|
||||
const [models, setModels] = useState<Metaobject[]>([]);
|
||||
const [years, setYears] = useState<Metaobject[]>([]);
|
||||
const [isLoading, startTransition] = useTransition();
|
||||
|
||||
const [make, setMake] = useState<Metaobject | null>(
|
||||
(partType &&
|
||||
makes.find((make) =>
|
||||
makeIdFromSearchParams
|
||||
? make.id === makeIdFromSearchParams
|
||||
initialMake
|
||||
? kebabCase(make.name) === initialMake
|
||||
: params.collection?.includes(make.name!.toLowerCase())
|
||||
)) ||
|
||||
null
|
||||
);
|
||||
const [model, setModel] = useState<Metaobject | null>(
|
||||
models.find((model) => model.id === searchParams.get(MODEL_FILTER_ID)) || null
|
||||
);
|
||||
const [model, setModel] = useState<Metaobject | null>(null);
|
||||
const [year, setYear] = useState<Metaobject | null>(null);
|
||||
|
||||
const [year, setYear] = useState<Metaobject | null>(
|
||||
years.find((y) => y.id === searchParams.get(YEAR_FILTER_ID)) || null
|
||||
);
|
||||
const [models, setModels] = useState<Metaobject[]>([]);
|
||||
const [years, setYears] = useState<Metaobject[]>([]);
|
||||
|
||||
const [loadingAttribute, setLoadingAttribute] = useState<'models' | 'years'>();
|
||||
const modelOptions = make ? models.filter((m) => get(m, 'make') === make.id) : models;
|
||||
const yearOptions = model ? years.filter((y) => get(y, 'make_model') === model.id) : years;
|
||||
|
||||
@ -63,8 +57,8 @@ const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
useEffect(() => {
|
||||
if (partType) {
|
||||
const _make = makes.find((make) =>
|
||||
makeIdFromSearchParams
|
||||
? make.id === makeIdFromSearchParams
|
||||
initialMake
|
||||
? kebabCase(make.name) === initialMake
|
||||
: params.collection?.includes(make.name!.toLowerCase())
|
||||
);
|
||||
|
||||
@ -78,37 +72,44 @@ const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [makeIdFromSearchParams, makes, params.collection, partType]);
|
||||
}, [initialMake, makes, params.collection, partType]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchModels = async () => {
|
||||
setLoadingAttribute('models');
|
||||
const modelsResponse = await fetMetaobjects('make_model_composite');
|
||||
if (initialModel) {
|
||||
setModel(
|
||||
(currentModel) =>
|
||||
modelsResponse?.find((model) => kebabCase(model.name) === initialModel) || currentModel
|
||||
);
|
||||
}
|
||||
setModels(modelsResponse || []);
|
||||
setLoadingAttribute(undefined);
|
||||
};
|
||||
|
||||
if (make?.id && models.length === 0) {
|
||||
startTransition(async () => {
|
||||
const modelsResponse = await fetMetaobjects('make_model_composite');
|
||||
if (modelIdFromSearchParams) {
|
||||
setModel(
|
||||
(currentModel) =>
|
||||
modelsResponse?.find((model) => model.id === modelIdFromSearchParams) || currentModel
|
||||
);
|
||||
}
|
||||
setModels(modelsResponse || []);
|
||||
});
|
||||
fetchModels();
|
||||
}
|
||||
}, [make?.id, modelIdFromSearchParams, models.length]);
|
||||
}, [make?.id, initialModel, models.length]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchYears = async () => {
|
||||
setLoadingAttribute('years');
|
||||
const yearsResponse = await fetMetaobjects('make_model_year_composite');
|
||||
if (initialYear) {
|
||||
setYear(
|
||||
(currentYear) => yearsResponse?.find((year) => year.name === initialYear) || currentYear
|
||||
);
|
||||
}
|
||||
setYears(yearsResponse || []);
|
||||
setLoadingAttribute(undefined);
|
||||
};
|
||||
|
||||
if (model?.id && years.length === 0) {
|
||||
startTransition(async () => {
|
||||
const yearsResponse = await fetMetaobjects('make_model_year_composite');
|
||||
if (yearIdFromSearchParams) {
|
||||
setYear(
|
||||
(currentYear) =>
|
||||
yearsResponse?.find((year) => year.id === yearIdFromSearchParams) || currentYear
|
||||
);
|
||||
}
|
||||
setYears(yearsResponse || []);
|
||||
});
|
||||
fetchYears();
|
||||
}
|
||||
}, [model?.id, yearIdFromSearchParams, years.length]);
|
||||
}, [model?.id, initialYear, years.length]);
|
||||
|
||||
const onChangeMake = async (value: Metaobject | null) => {
|
||||
setMake(value);
|
||||
@ -133,11 +134,10 @@ const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
};
|
||||
|
||||
const onSearch = () => {
|
||||
const newSearchParams = new URLSearchParams(searchParams.toString());
|
||||
newSearchParams.set(MAKE_FILTER_ID, make?.id || '');
|
||||
newSearchParams.set(MODEL_FILTER_ID, model?.id || '');
|
||||
newSearchParams.set(YEAR_FILTER_ID, year?.id || '');
|
||||
router.push(createUrl(`/search/${partType?.value}`, newSearchParams), { scroll: false });
|
||||
router.push(
|
||||
`/${partType?.value}/${kebabCase(make?.name)}/${kebabCase(model?.name)}/${kebabCase(year?.name)}`,
|
||||
{ scroll: false }
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
@ -169,7 +169,7 @@ const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
getId={(option) => option.id}
|
||||
disabled={!make}
|
||||
autoFocus={autoFocusField === 'model'}
|
||||
isLoading={isLoading}
|
||||
isLoading={loadingAttribute === 'models'}
|
||||
/>
|
||||
<FilterField
|
||||
label="Year"
|
||||
@ -179,7 +179,7 @@ const FiltersList = ({ makes, menu, autoFocusField }: FiltersListProps) => {
|
||||
getId={(option) => option.id}
|
||||
disabled={!model || !make}
|
||||
autoFocus={autoFocusField === 'year'}
|
||||
isLoading={isLoading}
|
||||
isLoading={loadingAttribute === 'years'}
|
||||
/>
|
||||
<Button
|
||||
onClick={onSearch}
|
||||
|
53
components/layout/search/filters/make-model-filters.tsx
Normal file
53
components/layout/search/filters/make-model-filters.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { MODEL_FILTER_ID, YEAR_FILTER_ID } from 'lib/constants';
|
||||
import { getProductFilters } from 'lib/shopify';
|
||||
import { Filter } from 'lib/shopify/types';
|
||||
import { getCollectionUrl } from 'lib/utils';
|
||||
import kebabCase from 'lodash.kebabcase';
|
||||
import Link from 'next/link';
|
||||
|
||||
type MakeModelFiltersProps = {
|
||||
collection: string;
|
||||
};
|
||||
|
||||
const MakeModelFilters = async ({ collection }: MakeModelFiltersProps) => {
|
||||
if (!collection) return null;
|
||||
|
||||
const [, make, model] = collection.split('_');
|
||||
if (!make && !model) return null;
|
||||
|
||||
let data = null as Filter | null | undefined;
|
||||
let title = '';
|
||||
|
||||
if (model) {
|
||||
data = await getProductFilters({ collection }, YEAR_FILTER_ID);
|
||||
title = 'Years';
|
||||
} else if (make) {
|
||||
data = await getProductFilters({ collection }, MODEL_FILTER_ID);
|
||||
title = 'Models';
|
||||
}
|
||||
|
||||
if (!data?.values || !data?.values.length) return null;
|
||||
|
||||
return (
|
||||
<div className="border-t pt-4">
|
||||
<div className="text-sm font-medium text-gray-900">{title}</div>
|
||||
<ul
|
||||
role="list"
|
||||
className="ml-1 mt-2 max-h-[300px] space-y-3 overflow-y-auto border-b border-gray-200 pb-6 text-sm text-gray-600"
|
||||
>
|
||||
{data.values.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link
|
||||
href={`${getCollectionUrl(`${collection}_${kebabCase(item.label)}`)}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MakeModelFilters;
|
@ -39,7 +39,7 @@ import {
|
||||
getCollectionProductsQuery,
|
||||
getCollectionQuery,
|
||||
getCollectionsQuery,
|
||||
getTransmissionCodesQuery
|
||||
getProductFiltersQuery
|
||||
} from './queries/collection';
|
||||
import { getCustomerQuery } from './queries/customer';
|
||||
import { getMenuQuery } from './queries/menu';
|
||||
@ -1188,7 +1188,7 @@ export async function getProductFilters(
|
||||
const _make = Array.isArray(make) ? make : make ? [make] : undefined;
|
||||
|
||||
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
|
||||
query: getTransmissionCodesQuery,
|
||||
query: getProductFiltersQuery,
|
||||
tags: [TAGS.collections, TAGS.products],
|
||||
variables: {
|
||||
handle: collection,
|
||||
|
@ -79,8 +79,8 @@ export const getCollectionProductsQuery = /* GraphQL */ `
|
||||
${productFragment}
|
||||
`;
|
||||
|
||||
export const getTransmissionCodesQuery = /* GraphQL */ `
|
||||
query getTransmissionCodes($handle: String!, $filters: [ProductFilter!]) {
|
||||
export const getProductFiltersQuery = /* GraphQL */ `
|
||||
query getProductFilters($handle: String!, $filters: [ProductFilter!]) {
|
||||
collection(handle: $handle) {
|
||||
products(first: 1, filters: $filters) {
|
||||
filters {
|
||||
|
18
lib/utils.ts
18
lib/utils.ts
@ -145,23 +145,7 @@ export const isBeforeToday = (date?: string | null) => {
|
||||
};
|
||||
|
||||
export const getCollectionUrl = (handle: string, includeSlashPrefix = true) => {
|
||||
let rewriteUrl = '';
|
||||
const enginesPattern = /^\/?remanufactured-engines(-.+)?$/;
|
||||
const transferCasesPattern = /^\/?transfer-cases(-.+)?$/;
|
||||
|
||||
if (enginesPattern.test(handle)) {
|
||||
rewriteUrl = handle
|
||||
.replace(/-/g, '/')
|
||||
.replace('/engines/', '-engines/')
|
||||
.replace('/engines', '-engines');
|
||||
} else if (transferCasesPattern.test(handle)) {
|
||||
rewriteUrl = handle
|
||||
.replace(/-/g, '/')
|
||||
.replace('/cases/', '-cases/')
|
||||
.replace('/cases', '-cases');
|
||||
} else {
|
||||
rewriteUrl = handle.split('-').filter(Boolean).join('/');
|
||||
}
|
||||
const rewriteUrl = handle.split('_').filter(Boolean).join('/');
|
||||
|
||||
return includeSlashPrefix ? `/${rewriteUrl}` : rewriteUrl;
|
||||
};
|
||||
|
@ -12,7 +12,7 @@ export async function middleware(request: NextRequest) {
|
||||
|
||||
if (URL_PREFIXES.some((url) => request.nextUrl.pathname.startsWith(url))) {
|
||||
// /transmissions/bmw/x5 would turn into /transmissions-bmw-x5
|
||||
const requestPathname = request.nextUrl.pathname.split('/').filter(Boolean).join('-');
|
||||
const requestPathname = request.nextUrl.pathname.split('/').filter(Boolean).join('_');
|
||||
const searchString = request.nextUrl.search;
|
||||
|
||||
return NextResponse.rewrite(
|
||||
|
Loading…
x
Reference in New Issue
Block a user