schon/storefront/app/composables/breadcrumbs/useBreadcrumbs.ts
2026-02-27 21:59:51 +03:00

90 lines
1.9 KiB
TypeScript

import type { ICategory, IProduct } from '@types';
interface Crumb {
text: string;
link?: string;
}
function findCategoryPath(
nodes: ICategory[],
targetSlug: string,
path: ICategory[] = [],
): ICategory[] | null {
for (const node of nodes) {
const newPath = [
...path,
node,
];
if (node.slug === targetSlug) {
return newPath;
}
if (node.children?.length) {
const found = findCategoryPath(node.children, targetSlug, newPath);
if (found) {
return found;
}
}
}
return null;
}
export function useBreadcrumbs() {
const { t } = useI18n();
const route = useRoute();
const pageTitle = useState<string>('pageTitle');
const categoryStore = useCategoryStore();
const product = useState<IProduct | null>('currentProduct');
const breadcrumbs = computed<Crumb[]>(() => {
const crumbs: Crumb[] = [
{
text: t('breadcrumbs.home'),
link: '/',
},
];
if (route.path.includes('/catalog') || route.path.includes('/product')) {
crumbs.push({
text: t('breadcrumbs.catalog'),
link: '/catalog',
});
let categorySlug: string | undefined;
if (route.path.includes('/catalog')) {
categorySlug = route.params.categorySlug as string;
} else if (route.path.includes('/product')) {
categorySlug = product.value?.category?.slug;
}
if (categorySlug) {
const roots = categoryStore.categories.map((e) => e.node);
const path = findCategoryPath(roots, categorySlug);
path?.forEach((node) => {
crumbs.push({
text: node.name,
link: `/catalog/${node.slug}`,
});
});
}
if (route.path.includes('/product') && product.value) {
crumbs.push({
text: product.value.name,
});
}
} else {
const routeNameWithoutLocale = String(route.name).split('___')[0];
crumbs.push({
text: pageTitle.value || t(`breadcrumbs.${routeNameWithoutLocale}`),
});
}
return crumbs;
});
console.log(breadcrumbs.value)
return {
breadcrumbs,
};
}