-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathwithSidebar.tsx
More file actions
78 lines (66 loc) · 2.2 KB
/
withSidebar.tsx
File metadata and controls
78 lines (66 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use client';
import Sidebar from '@node-core/ui-components/Containers/Sidebar';
import { useTranslations } from 'next-intl';
import { useRef } from 'react';
import Link from '#site/components/Link';
import { useClientContext, useScrollToElement } from '#site/hooks/client';
import { useSiteNavigation } from '#site/hooks/generic';
import { useRouter, usePathname } from '#site/navigation.mjs';
import type { FormattedMessage, NavigationKeys } from '#site/types';
import type { RichTranslationValues } from 'next-intl';
import type { FC } from 'react';
type WithSidebarProps = {
navKeys: Array<NavigationKeys>;
context?: Record<string, RichTranslationValues>;
};
type MappedItem = {
label: FormattedMessage;
link: string;
target?: string;
items?: Array<[string, MappedItem]>;
};
type SidebarMappedEntry = {
label: FormattedMessage;
link: string;
target?: string;
items?: Array<SidebarMappedEntry>;
};
const mapItem = ([, item]: [string, MappedItem]): SidebarMappedEntry => ({
label: item.label,
link: item.link,
target: item.target,
items: item.items ? item.items.map(mapItem) : [],
});
const WithSidebar: FC<WithSidebarProps> = ({ navKeys, context, ...props }) => {
const { getSideNavigation } = useSiteNavigation();
const pathname = usePathname()!;
const t = useTranslations();
const { push } = useRouter();
const { frontmatter } = useClientContext();
const sidebarRef = useRef<HTMLElement>(null);
const sideNavigation = getSideNavigation(navKeys, context);
// Preserve sidebar scroll position across navigations
useScrollToElement('sidebar', sidebarRef);
const mappedSidebarItems =
// If there's only a single navigation key, use its sub-items
// as our navigation.
(navKeys.length === 1 ? sideNavigation[0][1].items : sideNavigation).map(
([, { label, items }]: [string, MappedItem]) => ({
groupName: label,
items: items ? items.map(mapItem) : [],
})
);
return (
<Sidebar
ref={sidebarRef}
groups={mappedSidebarItems}
pathname={pathname}
title={t('components.common.sidebar.title')}
placeholder={frontmatter?.title}
onSelect={push}
as={Link}
{...props}
/>
);
};
export default WithSidebar;