Skip to content

Commit

Permalink
chore: optimize isActive logic
Browse files Browse the repository at this point in the history
  • Loading branch information
sanyuan0704 committed Oct 10, 2022
1 parent fe07e51 commit 1523963
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/theme-default/components/Nav/NavMenuSingleItem.tsx
Expand Up @@ -5,7 +5,9 @@ import { Link } from '../Link/index';

export function NavMenuSingleItem(item: DefaultTheme.NavItemWithLink) {
const location = useLocation();
const isActive = new RegExp(item.activeMatch || '').test(location.pathname);
const isActive = new RegExp(item.activeMatch || item.link).test(
location.pathname
);
return (
<div
key={item.text}
Expand Down
5 changes: 3 additions & 2 deletions src/theme-default/components/Siderbar/index.tsx
Expand Up @@ -4,6 +4,7 @@ import { Link } from '../Link/index';
import { DefaultTheme } from '../../../shared/types';
import { normalizeHref, useSidebarData } from '../../logic/index';
import { useLocation } from 'react-router-dom';
import { isActive } from '../../logic/index';

export function SideBar() {
const { pathname } = useLocation();
Expand All @@ -15,15 +16,15 @@ export function SideBar() {
if ('items' in item) {
children = item.items.map((child) => renderGroupItem(child, depth + 1));
}
const isActive = pathname.startsWith(item.link!);
const active = isActive(pathname, item.link);
return (
<div style={{ marginLeft }}>
<div
p="1"
block="~"
text="sm"
font-medium="~"
className={`${isActive ? 'text-brand' : 'text-text-2'}`}
className={`${active ? 'text-brand' : 'text-text-2'}`}
>
<Link href={normalizeHref(item.link!)}>{item.text}</Link>
</div>
Expand Down
5 changes: 5 additions & 0 deletions src/theme-default/layout/DocLayout/index.tsx
Expand Up @@ -34,7 +34,12 @@ export function DocLayout() {
<div
relative="~"
m="x-auto"
p="l-2"
className={'md:max-w-712px lg:min-w-640px'}
style={{
maxWidth: hasAside ? '' : '1024px',
paddingLeft: hasAside ? '0' : '72px'
}}
>
<div className="island-doc">
<Content fallback={<div>Loading...</div>} />
Expand Down
Empty file.
10 changes: 10 additions & 0 deletions src/theme-default/logic/utils.ts
Expand Up @@ -49,3 +49,13 @@ export function backTrackHeaders(
}
return res;
}

export function isActive(currentPath: string, targetLink?: string) {
if (!targetLink) {
return false;
}
if (targetLink === '' || targetLink === '/') {
return currentPath === targetLink;
}
return currentPath.startsWith(targetLink);
}

1 comment on commit 1523963

@vercel
Copy link

@vercel vercel bot commented on 1523963 Oct 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.