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('pageTitle'); const categoryStore = useCategoryStore(); const product = useState('currentProduct'); const breadcrumbs = computed(() => { 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; }); return { breadcrumbs, }; }