Files
web/components/TempDesignSystem/Link/index.tsx
Erik Tiekstra dd4a2d8120 Merged in feat/SW-1296-hotel-subpages (pull request #1233)
feat(SW-1296): added Subpage for hotel pages and its routing

* feat(SW-1296): added Subpage for hotel pages and its routing


Approved-by: Fredrik Thorsson
2025-02-03 10:58:53 +00:00

115 lines
2.3 KiB
TypeScript

"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 <Link /> 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 ? (
<a
{...linkProps}
{...props}
onClick={(e) => {
if (onClick) {
onClick(e)
}
}}
/>
) : (
<NextLink
scroll={scroll}
prefetch={prefetch}
onClick={(e) => {
if (onClick) {
onClick(e)
}
if (trackingId) {
trackClickById()
}
}}
id={trackingId}
{...props}
{...linkProps}
/>
)
}