import React from 'react' import ConsoleMenu from '@alicloud/console-components-console-menu' import { Link } from 'gatsby' import { usePageCtx } from './context' import DocMenuLabel from './DocMenuLabel' import { IDocPageMeta, IPageContext } from '.' const SideBar: React.FC = () => { let pageCtx: IPageContext try { pageCtx = usePageCtx() } catch (error) { return } if (!('sideNav' in pageCtx.pageMeta)) return const { navCategories, header } = pageCtx.pageMeta.sideNav return ( {navCategories.map((navCategory, navCategoryIdx) => { if (navCategory.tagSelector) { const docs = Object.keys(navCategory.tagSelector).reduce< IDocPageMeta[] | null >((acc, tagName) => { const tagVal = String(navCategory.tagSelector[tagName]) if (!acc) { if (tagVal === 'true') { const map = new Map() Object.keys(pageCtx.tagIndex[tagName]).forEach(_tagVal => { pageCtx.tagIndex[tagName][_tagVal].forEach(docMeta => { map.set(docMeta.path, docMeta) }) }) return Array.from(map).map(([_, docInfo]) => docInfo) } return pageCtx.tagIndex[tagName]?.[tagVal] ?? [] } return acc.filter(({ tags }) => { if (tagVal === 'true') return tags?.[tagName] !== undefined return tags?.[tagName] === tagVal }) }, null) if (!docs || docs.length == 0) return null docs.sort(getSortFn(navCategory.sortByTag)) const consoleMenuItems = docs.map(docInfo => { return ( ) }) // 不创建可展开/收起的Submenu节点 if (navCategory.flat || !navCategory.label) return consoleMenuItems return ( {consoleMenuItems} ) } else if (navCategory.categoryName) { const currentCategory = pageCtx.siteMeta.categories.find( ({ name }) => name === navCategory.categoryName ) if (!currentCategory) { console.warn(`category not exist: ${navCategory.categoryName}`) return null } const consoleMenuItems = currentCategory.docs .sort(getSortFn(navCategory.sortByTag)) .map(docInfo => { return ( ) }) // 不创建可展开/收起的Submenu节点 if (navCategory.flat) return consoleMenuItems const label = navCategory.label ?? currentCategory.zhName return ( {consoleMenuItems} ) } else { return null } })} ) } export default SideBar function getSortFn(sortByTag?: string) { return (a: IDocPageMeta, b: IDocPageMeta) => { const { sortA, sortB } = (() => { if (sortByTag) { const sortA = Number(a.tags?.[sortByTag] ?? 1) || 1 const sortB = Number(b.tags?.[sortByTag] ?? 1) || 1 return { sortA, sortB } } else { const sortA = Number(a.sort ?? 1) || 1 const sortB = Number(b.sort ?? 1) || 1 return { sortA, sortB } } })() const cmp = sortA - sortB return cmp != 0 ? cmp : a.name.localeCompare(b.name) } }