Skip to content

Commit

Permalink
implement isActiveNavItem()
Browse files Browse the repository at this point in the history
  • Loading branch information
nemanjam committed May 21, 2024
1 parent 5b42b12 commit 39c6c02
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/components/HeaderLink.astro
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
---
import Button from '@/components/Button.astro';
import { isActiveNavItem } from '@/utils/strings';
import { cn } from '@/utils/styles';
import type { Props } from '@/components/Button.astro';
// eslint-disable-next-line no-unused-vars
const { slot, ...props } = Astro.props as Props;
const isActive = Astro.url.pathname.startsWith(`${props.href}`);
const isActive = isActiveNavItem({
routePathname: Astro.url.pathname,
navItemHref: props.href as string,
});
if (isActive) {
props['aria-current'] = 'page';
}
---

<Button {...props} class={isActive ? 'bg-slate-200/50 dark:bg-slate-800/50' : ''}>
<Button {...props} class={cn({ 'bg-slate-200/50 dark:bg-slate-800/50': isActive })}>
<slot name="icon" />
<slot />
</Button>
35 changes: 35 additions & 0 deletions src/utils/strings.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ROUTES } from '@/constants/routes';

export const getRandomInt = (max: number, min = 0) =>
Math.floor(Math.random() * (max - min + 1)) + min;

Expand All @@ -13,3 +15,36 @@ export const trimHttpProtocol = (url: string) => {

return withoutProtocol;
};

export const isActiveNavItem = ({
routePathname,
navItemHref,
}: {
routePathname: string;
navItemHref: string;
}): boolean => {
let isActive: boolean;

switch (true) {
// navItemHref identifies button, routePathname is route
case navItemHref === ROUTES.BLOG && routePathname === ROUTES.BLOG:
case navItemHref === ROUTES.ABOUT && routePathname === ROUTES.ABOUT:
case navItemHref === ROUTES.HOME && routePathname === ROUTES.HOME:
case navItemHref === ROUTES.RESUME && routePathname === ROUTES.RESUME:
case navItemHref === ROUTES.PROJECTS && routePathname.startsWith(ROUTES.PROJECTS):
case navItemHref === ROUTES.TAGS && routePathname.startsWith(ROUTES.TAGS):
case navItemHref === ROUTES.CATEGORIES && routePathname.startsWith(ROUTES.CATEGORIES):
case navItemHref === ROUTES.BLOG &&
!routePathname.startsWith(ROUTES.TAGS) &&
!routePathname.startsWith(ROUTES.CATEGORIES) &&
routePathname.startsWith(ROUTES.BLOG):
isActive = true;
break;

default:
isActive = false;
break;
}

return isActive;
};

0 comments on commit 39c6c02

Please sign in to comment.