From 15ee55773c3e0e6ec2240f76479d0cc68274dda5 Mon Sep 17 00:00:00 2001 From: Mehmet Date: Fri, 10 May 2024 12:07:19 +0200 Subject: [PATCH] fix: nodes not having real ids --- .changeset/strange-mice-know.md | 5 ++ apps/web/src/services/cms/get-navbar-tree.ts | 48 ++++++++++++-------- 2 files changed, 33 insertions(+), 20 deletions(-) create mode 100644 .changeset/strange-mice-know.md diff --git a/.changeset/strange-mice-know.md b/.changeset/strange-mice-know.md new file mode 100644 index 00000000..397c0ebc --- /dev/null +++ b/.changeset/strange-mice-know.md @@ -0,0 +1,5 @@ +--- +"web": patch +--- + +Fixed breadcrumbs not rendering properly when parent of node isn't present diff --git a/apps/web/src/services/cms/get-navbar-tree.ts b/apps/web/src/services/cms/get-navbar-tree.ts index 0e8d2b03..e8bc6878 100644 --- a/apps/web/src/services/cms/get-navbar-tree.ts +++ b/apps/web/src/services/cms/get-navbar-tree.ts @@ -10,26 +10,34 @@ export type NavbarNode = { export async function getNavbarTree() { const pages = await getNavbarPages(); - - const root: NavbarNode = { name: 'root', children: new Map(), url: '/', id: '_' }; - - for (const page of pages) { - if (!page.slug || !page.name) continue; - - const parts = page.name.split('/').filter(Boolean); - - let parent = root; - - for (const part of parts) { - if (!parent.children.has(part)) - parent.children.set(part, { name: part, parent, children: new Map(), url: '', id: String(page.id) }); - - parent = parent.children.get(part)!; - } - - parent.url = page.slug; - parent.name = parts.at(-1) || ''; - } + const root: NavbarNode = { name: 'root', id: 'root', url: '', children: new Map() }; + + pages.forEach((item) => { + const parts = item.name!.split('/'); + let current = root; + + parts.forEach((part, index) => { + if (!current.children.has(part)) { + const nodeId = `synthetic:${Math.random().toString(36).substring(2, 9)}`; + const newNode: NavbarNode = { + url: '', + id: nodeId, + name: part, + parent: current, + children: new Map(), + }; + + current.children.set(part, newNode); + } + + current = current.children.get(part)!; + + if (index === parts.length - 1) { + current.url = item.slug!; + current.id = String(item.id); + } + }); + }); return root; }