-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathNavBar.tsx
More file actions
315 lines (277 loc) · 11.6 KB
/
Copy pathNavBar.tsx
File metadata and controls
315 lines (277 loc) · 11.6 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import debounce from 'lodash/debounce';
import Link from 'next/link';
import type { NextRouter } from 'next/router';
import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next';
import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { defaultLanguage, i18nPaths, languages } from '@/utils/i18n';
import { SearchButton } from '../AlgoliaSearch';
import GithubButton from '../buttons/GithubButton';
import DarkModeToggle from '../DarkModeToggle';
import { isMobileDevice } from '../helpers/is-mobile';
import { useOutsideClick } from '../helpers/use-outside-click';
import IconLoupe from '../icons/Loupe';
import LanguageSelect from '../languageSelector/LanguageSelect';
import AsyncAPILogo from '../logos/AsyncAPILogo';
import CommunityPanel from './CommunityPanel';
import LearningPanel from './LearningPanel';
import MobileNavMenu from './MobileNavMenu';
import NavItem from './NavItem';
import otherItems from './otherItems';
import ToolsPanel from './ToolsPanel';
interface NavBarProps {
className?: string;
hideLogo?: boolean;
}
const isMobile = isMobileDevice();
/**
* @description Renders the navigation bar component.
* @param {Object} props - Props object for NavBar component.
* @param {string} [props.className=''] - Additional CSS classes for styling.
* @param {boolean} [props.hideLogo=false] - Indicates whether to hide the logo.
*/
export default function NavBar({ className = '', hideLogo = false }: NavBarProps) {
const router: NextRouter = useRouter();
const { pathname, query, asPath } = router;
const [open, setOpen] = useState<'learning' | 'tooling' | 'community' | null>(null);
const [mobileMenuOpen, setMobileMenuOpen] = useState<boolean>(false);
const [isMounted, setIsMounted] = useState<boolean>(false);
const [isScrolled, setIsScrolled] = useState<boolean>(false);
const { i18n } = useTranslation();
useEffect(() => {
setIsMounted(true);
}, []);
// Adding Scroll listener
useEffect(() => {
const handleScroll = debounce(() => {
const scrollTop = window.scrollY;
setIsScrolled(scrollTop > 50);
}, 10);
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
handleScroll.cancel();
};
}, []);
/**
* Retrieves unique language options based on the current path and i18nPaths configuration.
*
* @returns {string[]} - An array of unique language options with first letter in uppercase.
*/
const getUniqueLangs = (): string[] => {
let pathnameWithoutLocale = pathname ?? '';
// Strip dynamic [lang] segment from localized routes (e.g. /[lang]/tools/cli -> /tools/cli)
if (pathnameWithoutLocale.includes('/[lang]')) {
pathnameWithoutLocale = pathnameWithoutLocale.replace('/[lang]', '');
} else {
// Strip locale prefix from asPath when route file has no [lang] segment (e.g. /de/tools/cli)
const slug = asPath.split('/')[1];
if (languages.includes(slug)) {
pathnameWithoutLocale = asPath.slice(`/${slug}`.length) || '';
}
}
// Homepage routes use '' in i18nPaths, not '/'
if (pathnameWithoutLocale === '/') {
pathnameWithoutLocale = '';
}
const uniqueLangs = languages.filter((lang) => i18nPaths[lang]?.includes(pathnameWithoutLocale));
return uniqueLangs.length === 0 ? [defaultLanguage] : uniqueLangs;
};
const uniqueLangs = getUniqueLangs().map((lang) => ({
key: lang,
text: lang,
value: lang
}));
/**
* @description Changes the language and updates the URL accordingly.
* @param {string} locale - The new locale/language to set.
* @param {boolean} langPicker - Indicates whether the change is from the language picker.
* If true, stores the language in local storage.
*/
const changeLanguage = async (locale: string, langPicker: boolean): Promise<void> => {
// Verifies if the language change is from langPicker or the browser-api
if (langPicker) {
localStorage.setItem('i18nLang', locale);
}
// Detect current language
const slug = asPath.split('/')[1];
const langSlug = languages.includes(slug) && slug;
const language = query.lang || langSlug || defaultLanguage;
let href = pathname;
if (locale) {
if (pathname.startsWith('/404')) {
href = `/${locale}`;
} else {
href = pathname.replace('[lang]', locale);
}
} else if (language) {
href = `/${language}${href}`;
} else {
href = `/${href}`;
}
// Fix double slashes
href = href.replace(/([^:]\/)\/+/g, '$1').replace('//', '/');
router.push(href);
};
/**
* @description Handles the outside click event for closing menus.
* @param {('learning' | 'tooling' | 'community' | null)} menu - The menu to close if clicked outside.
*/
function outsideClick(menu: 'learning' | 'tooling' | 'community' | null) {
if (open !== menu) return;
setOpen(null);
}
const learningRef = useOutsideClick(() => outsideClick('learning'));
const toolingRef = useOutsideClick(() => outsideClick('tooling'));
const communityRef = useOutsideClick(() => outsideClick('community'));
/**
* @description Shows or hides the specified menu.
* @param {('learning' | 'tooling' | 'community' | null)} menu - The menu to show or hide.
*/
function showMenu(menu: 'learning' | 'tooling' | 'community' | null) {
if (open === menu) return;
setOpen(menu);
}
/**
* @description Shows or hides the specified menu on click (for mobile).
* @param {('learning' | 'tooling' | 'community' | null)} menu - The menu to show or hide.
*/
function showOnClickMenu(menu: 'learning' | 'tooling' | 'community' | null) {
if (!isMobile) return;
if (open === menu) {
setOpen(null);
} else {
setOpen(menu);
}
}
useEffect(() => {
setMobileMenuOpen(false);
setOpen(null);
}, [asPath]);
return (
<>
<div
// eslint-disable-next-line max-len
className={`bg-white/60 transition-all duration-500 ease-in-out lg:rounded-xl backdrop-blur-lg z-50
${isScrolled ? 'py-4 shadow-md ring-1 dark:backdrop-blur-xl dark:bg-dark-card/60 ring-black/5 lg:rounded-xl' : 'mt-0 py-4 dark:bg-dark-background rounded-none'} ${className}`}
>
{/* <div
className={`bg-white/60 mx-auto fixed flex left-0 right-0 top-0 w-full z-[12] items-center justify-between max-w-[76rem] select-none transition-all duration-300 ease-spring ring-1 ring-black/5 bg-white/76 backdrop-blur-lg shadow-lg lg:rounded-full lg:mt-3 translate-y-0 ${className} z-50`}
></div> */}
<div className='flex w-full items-center justify-between py-1 lg:justify-start lg:space-x-2'>
{!hideLogo && (
<div className='lg:w-auto lg:flex-1'>
<div className='flex'>
<Link href='/' className='cursor-pointer' aria-label='AsyncAPI' data-testid='Navbar-logo'>
<AsyncAPILogo className={'w-auto transition-all duration-500 ease-in-out h-8'} />
</Link>
</div>
</div>
)}
<div
className='-my-2 -mr-2 flex flex-row items-center justify-center gap-1 min-[1100px]:hidden'
data-testid='Navbar-search'
>
<SearchButton
className='flex items-center rounded-lg p-2.5 text-gray-600 dark:text-gray-300 transition-all duration-200 ease-in-out hover:bg-gray-100 dark:hover:bg-gray-800 hover:scale-105 active:scale-95'
aria-label='Open Search'
>
<IconLoupe />
</SearchButton>
<DarkModeToggle />
<button
onClick={() => setMobileMenuOpen(true)}
type='button'
className='inline-flex items-center justify-center rounded-lg p-2.5 text-gray-600 dark:text-gray-300 transition-all duration-200 ease-in-out hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none hover:scale-105 active:scale-95'
aria-label='Open Menu'
>
<svg className='size-6' stroke='currentColor' fill='none' viewBox='0 0 24 24'>
<title>Menu</title>
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth='2' d='M4 6h16M4 12h16M4 18h16' />
</svg>
</button>
</div>
<nav
className='hidden w-full space-x-4 min-[1100px]:flex min-[1100px]:items-center min-[1100px]:justify-end xl:space-x-8'
data-testid='Navbar-main'
>
<div className='relative' onMouseLeave={() => showMenu(null)} ref={learningRef}>
<NavItem
text='Docs'
href='/docs'
onClick={() => showOnClickMenu('learning')}
onMouseEnter={() => showMenu('learning')}
hasDropdown
isOpen={open === 'learning'}
/>
{open === 'learning' && <LearningPanel />}
</div>
<div className='relative' onMouseLeave={() => showMenu(null)} ref={toolingRef}>
<NavItem
text='Tools'
href='/tools'
onClick={() => showOnClickMenu('tooling')}
onMouseEnter={() => showMenu('tooling')}
hasDropdown
isOpen={open === 'tooling'}
/>
{open === 'tooling' && <ToolsPanel />}
</div>
<div className='relative' onMouseLeave={() => showMenu(null)} ref={communityRef}>
<NavItem
text='Community'
href='/community'
onClick={() => showOnClickMenu('community')}
onMouseEnter={() => showMenu('community')}
hasDropdown
isOpen={open === 'community'}
/>
{open === 'community' && <CommunityPanel />}
</div>
{otherItems.map((item, index) => (
<NavItem href={item.href} key={index} text={item.text} target={item.target} className={item.className} />
))}
<div className='justify-content flex flex-row items-center'>
<SearchButton
className='mr-2 flex items-center space-x-2 rounded-md p-2 text-left text-zinc-700 dark:text-dark-text dark:hover:text-dark-heading text-opacity-75 transition duration-150 ease-in-out hover:bg-gray-100 dark:hover:bg-primary-500 hover:text-gray-800 focus:bg-gray-100 focus:text-gray-500 focus:outline-none'
aria-label='Open Search'
>
<IconLoupe />
</SearchButton>
{/* // Language Picker Component */}
<LanguageSelect
options={uniqueLangs}
onChange={(value) => {
changeLanguage(value.toLowerCase(), true);
}}
className=''
selected={i18n.language ? i18n.language : 'en'}
/>
<GithubButton
text='Star on GitHub'
href='https://github.com/asyncapi/spec'
className='ml-2 py-2'
inNav={true}
/>
<DarkModeToggle />
</div>
</nav>
</div>
</div>
{/* </div> */}
{/* Mobile menu, show/hide based on mobile menu state. */}
{isMounted &&
mobileMenuOpen &&
createPortal(
<MobileNavMenu
onClickClose={() => setMobileMenuOpen(false)}
uniqueLangs={uniqueLangs}
currentLanguage={i18n.language ? i18n.language : 'en'}
changeLanguage={changeLanguage}
/>,
document.body
)}
</>
);
}