|
| 1 | +function normalizeSourceSlug(slug) { |
| 2 | + if (typeof slug !== 'string') { |
| 3 | + return '' |
| 4 | + } |
| 5 | + |
| 6 | + const normalized = slug.trim() |
| 7 | + if ( |
| 8 | + !normalized || |
| 9 | + normalized === '#' || |
| 10 | + /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(normalized) |
| 11 | + ) { |
| 12 | + return '' |
| 13 | + } |
| 14 | + |
| 15 | + return normalized.replace(/^\/+|\/+$/g, '') |
| 16 | +} |
| 17 | + |
| 18 | +export function getSourcePageSlugs(collectionData) { |
| 19 | + return new Map( |
| 20 | + collectionData |
| 21 | + .filter(page => page?.type === 'Page' && page?.slug) |
| 22 | + .map(page => [page.id, page.slug]) |
| 23 | + ) |
| 24 | +} |
| 25 | + |
| 26 | +function getPageHrefBySourceSlug(collectionData, sourcePageSlugs) { |
| 27 | + const pageHrefBySourceSlug = new Map() |
| 28 | + const ambiguousSlugs = new Set() |
| 29 | + |
| 30 | + collectionData.forEach(page => { |
| 31 | + if (page?.type !== 'Page' || page?.status !== 'Published' || !page?.href) { |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + const sourceSlug = normalizeSourceSlug(sourcePageSlugs?.get(page.id)) |
| 36 | + if (!sourceSlug || ambiguousSlugs.has(sourceSlug)) { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + const existingHref = pageHrefBySourceSlug.get(sourceSlug) |
| 41 | + if (existingHref && existingHref !== page.href) { |
| 42 | + pageHrefBySourceSlug.delete(sourceSlug) |
| 43 | + ambiguousSlugs.add(sourceSlug) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + pageHrefBySourceSlug.set(sourceSlug, page.href) |
| 48 | + }) |
| 49 | + |
| 50 | + return pageHrefBySourceSlug |
| 51 | +} |
| 52 | + |
| 53 | +export function getCustomMenu({ collectionData, sourcePageSlugs }) { |
| 54 | + const pageHrefBySourceSlug = getPageHrefBySourceSlug( |
| 55 | + collectionData, |
| 56 | + sourcePageSlugs |
| 57 | + ) |
| 58 | + const menuPages = collectionData.filter( |
| 59 | + post => |
| 60 | + post.status === 'Published' && |
| 61 | + (post?.type === 'Menu' || post?.type === 'SubMenu') |
| 62 | + ) |
| 63 | + const menus = [] |
| 64 | + if (menuPages && menuPages.length > 0) { |
| 65 | + menuPages.forEach(e => { |
| 66 | + e.show = true |
| 67 | + const sourceSlug = normalizeSourceSlug(e.slug) |
| 68 | + if (sourceSlug && pageHrefBySourceSlug.has(sourceSlug)) { |
| 69 | + e.href = pageHrefBySourceSlug.get(sourceSlug) |
| 70 | + } |
| 71 | + if (e.type === 'Menu') { |
| 72 | + menus.push(e) |
| 73 | + } else if (e.type === 'SubMenu') { |
| 74 | + const parentMenu = menus[menus.length - 1] |
| 75 | + if (parentMenu) { |
| 76 | + if (parentMenu.subMenus) { |
| 77 | + parentMenu.subMenus.push(e) |
| 78 | + } else { |
| 79 | + parentMenu.subMenus = [e] |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + }) |
| 84 | + } |
| 85 | + return menus |
| 86 | +} |
0 commit comments