diff --git a/src/components/HeaderLink.astro b/src/components/HeaderLink.astro index f60a4c6..985e16e 100644 --- a/src/components/HeaderLink.astro +++ b/src/components/HeaderLink.astro @@ -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'; } --- - diff --git a/src/utils/strings.ts b/src/utils/strings.ts index dff07d1..bb6ffa1 100644 --- a/src/utils/strings.ts +++ b/src/utils/strings.ts @@ -1,3 +1,5 @@ +import { ROUTES } from '@/constants/routes'; + export const getRandomInt = (max: number, min = 0) => Math.floor(Math.random() * (max - min + 1)) + min; @@ -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; +};