"use client" import NextLink from "next/link" import { usePathname, useSearchParams } from "next/navigation" import { useCallback, useMemo } from "react" import { useCheckIfExternalLink } from "@/hooks/useCheckIfExternalLink" import { trackClick } from "@/utils/tracking" import { linkVariants } from "./variants" import type { LinkProps } from "./link" export default function Link({ active, className, color, href, partialMatch = false, textDecoration, size, scroll = true, prefetch, variant, weight, trackingId, trackingParams, onClick, /** * Decides if the link should include the current search params in the URL */ keepSearchParams, appendToCurrentPath, ...props }: LinkProps) { const currentPageSlug = usePathname() const searchParams = useSearchParams() let isActive = active || currentPageSlug === href if (partialMatch && !isActive) { isActive = currentPageSlug === href } const classNames = linkVariants({ active: isActive, className, textDecoration, color, size, weight, variant, }) const fullUrl = useMemo(() => { let newPath = href if (appendToCurrentPath) { newPath = `${currentPageSlug}${newPath}` } if (keepSearchParams && searchParams.size) { const delimiter = newPath.includes("?") ? "&" : "?" return `${newPath}${delimiter}${searchParams}` } return newPath }, [ href, searchParams, keepSearchParams, appendToCurrentPath, currentPageSlug, ]) // TODO: Remove this check (and hook) and only return when current web is deleted const isExternal = useCheckIfExternalLink(href) const trackClickById = useCallback(() => { if (trackingId) { trackClick(trackingId, trackingParams) } }, [trackingId, trackingParams]) const linkProps = { href: fullUrl, className: classNames, } return isExternal ? ( { if (onClick) { onClick(e) } }} /> ) : ( { if (onClick) { onClick(e) } if (trackingId) { trackClickById() } }} id={trackingId} {...props} {...linkProps} /> ) }