Created
October 13, 2023 18:05
-
-
Save tommie/5645a135e788705f00fbc56314d77ada to your computer and use it in GitHub Desktop.
Nuxt #23595 WiP workaround
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { RouteRecordRaw } from "vue-router"; | |
import type { RouterOptions } from '@nuxt/schema'; | |
export default { | |
routes(routes) { | |
if (hasChildren(routes)) { | |
console.warn('The pages had children, which means the fix-pagehierarchy module can be removed!'); | |
return routes; | |
} | |
return buildHierarchy(routes as any); | |
}, | |
} satisfies RouterOptions; | |
function hasChildren(pages: readonly RouteRecordRaw[]) { | |
return pages.some(page => page.children?.length); | |
} | |
// Workaround for Nuxt not populating the hierarchy of pages properly. | |
// | |
// See https://github.com/nuxt/nuxt/issues/23595. | |
function buildHierarchy(routes: readonly RouteRecordRaw[]) { | |
const root: RouteRecordRaw[] = []; | |
const routes2 = [...routes]; | |
routes2.sort((a, b) => a.path.length - b.path.length); | |
for (const rec of routes2) { | |
const path = parsePath(rec.path); | |
let accPath = ""; | |
let els = root; | |
for (const p of path) { | |
accPath += "/" + p; | |
let eli = els.findIndex((el) => el.path === accPath); | |
if (eli < 0) { | |
els.push({ ...rec, children: [] }); | |
eli = els.length - 1; | |
} | |
els = els[eli].children!; | |
} | |
} | |
return root; | |
} | |
function parsePath(s: string) { | |
const parts: string[] = []; | |
if (s.startsWith("/")) s = s.slice(1); | |
while (s) { | |
const br = s.indexOf("("); | |
let slash = s.indexOf("/"); | |
if (br >= 0 && (slash < 0 || br < slash)) { | |
const bre = s.indexOf(")", br + 1); | |
if (bre >= 0) slash = s.indexOf("/", bre + 1); | |
} | |
if (slash < 0) slash = s.length; | |
parts.push(s.slice(0, slash)); | |
s = s.slice(slash + 1); | |
} | |
return parts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment